budctl90075f3
budctl: read-only CLI for the realme Buds T310
A Linux CLI for controlling wireless earbuds without the vendor app. This first version reads only and has been checked on the owner's T310 (checkpoint HW1). - budctl-core: Bluetooth transport (RFCOMM, its own SDP client), BlueZ device listing, and the T310 plugin: framing, handshake, command bitmap, battery, noise control, EQ, switches, codec, firmware and touch controls. - budctl CLI: `list`, `status` and `touch`, plus `--device`, `--json` (schema 1) and `--debug` hex dumps. Exit codes are 0/1/2/3/4. - docs/protocol: the clean-room protocol spec. Every fact carries an evidence level, and the verification log records HW1. - Guards: cargo-deny bans network crates, and tests/guards.rs checks that sources have no network code, Cargo.lock has no banned crate and every `Spec:` anchor exists. Dependencies: - libc: raw AF_BLUETOOTH sockets (RFCOMM control link, L2CAP for SDP). - zbus (blocking, async-io): list paired devices from BlueZ over the local system D-Bus socket, which budctl opens at its fixed path. - serde: Serialize for the status types that `--json` prints. - clap (derive): command-line parsing. - serde_json: `--json` output.
+6239 −0
33 files changed
- A .gitignore +1 −0
- A CLAUDE.md +127 −0
- A Cargo.lock +1016 −0
- A Cargo.toml +23 −0
- A LICENSE +674 −0
- A clippy.toml +17 −0
- A crates/budctl-cli/Cargo.toml +20 −0
- A crates/budctl-cli/src/main.rs +106 −0
- A crates/budctl-cli/src/output.rs +187 −0
- A crates/budctl-cli/tests/cli.rs +27 −0
- A crates/budctl-core/Cargo.toml +16 −0
- A crates/budctl-core/src/bluez.rs +159 −0
- A crates/budctl-core/src/bt.rs +166 −0
- A crates/budctl-core/src/debug.rs +42 −0
- A crates/budctl-core/src/devices/mod.rs +48 −0
- A crates/budctl-core/src/devices/realme_t310/codec.rs +542 −0
- A crates/budctl-core/src/devices/realme_t310/frame.rs +363 −0
- A crates/budctl-core/src/devices/realme_t310/link.rs +221 −0
- A crates/budctl-core/src/devices/realme_t310/mod.rs +412 −0
- A crates/budctl-core/src/error.rs +100 −0
- A crates/budctl-core/src/lib.rs +185 −0
- A crates/budctl-core/src/reader.rs +89 −0
- A crates/budctl-core/src/status.rs +80 −0
- A crates/budctl-core/src/transport/mock.rs +80 −0
- A crates/budctl-core/src/transport/mod.rs +103 −0
- A crates/budctl-core/src/transport/rfcomm.rs +47 −0
- A crates/budctl-core/src/transport/sdp.rs +287 −0
- A crates/budctl-core/src/transport/socket.rs +197 −0
- A crates/budctl-core/tests/guards.rs +155 −0
- A deny.toml +75 −0
- A docs/protocol/realme_t310.md +532 −0
- A docs/protocol/transport.md +140 −0
- A rustfmt.toml +2 −0
| @@ -0,0 +1 @@ | |||
| 1 | + | /target | |
| @@ -0,0 +1,127 @@ | |||
| 1 | + | # budctl | |
| 2 | + | ||
| 3 | + | budctl is a Linux CLI (and later a GUI) for controlling wireless earbuds without the vendor app. It has no telemetry, needs no account and never makes a network call. | |
| 4 | + | ||
| 5 | + | The first supported device is the **realme Buds T310**. More devices are added as plugins when the owner gets new earbuds. | |
| 6 | + | ||
| 7 | + | ## Goals | |
| 8 | + | ||
| 9 | + | - Control earbud features from Linux: ANC / transparency / off, EQ presets, game mode, touch controls, battery readout, and anything else the buds offer. | |
| 10 | + | - Two front ends, one core: a `budctl` CLI and later a `budctl-gui`, both thin layers over the same library (`budctl-core`). The GUI is undecided. It will be either a Quickshell/Aurora integration (which can use `budctl --json`) or a standalone Rust GUI. | |
| 11 | + | - One small, readable codebase that the owner fully understands. | |
| 12 | + | - Device support is pluggable. Adding a new pair of buds means adding one module under `crates/budctl-core/src/devices/` and registering it in `devices/mod.rs`, without touching transport, CLI or GUI code. | |
| 13 | + | - Coexist with the phone app. Settings live on the buds, so budctl never stores device state locally beyond user config. | |
| 14 | + | ||
| 15 | + | ## Non-goals | |
| 16 | + | ||
| 17 | + | - No firmware dumping, flashing or modification. We only speak the buds' existing control protocol. | |
| 18 | + | - No network access of any kind: no update checks, crash reports or analytics. | |
| 19 | + | - No support for models the owner doesn't have. Don't speculatively add devices. | |
| 20 | + | - No Windows or macOS support. | |
| 21 | + | ||
| 22 | + | ## Hard rules | |
| 23 | + | ||
| 24 | + | 1. **No network code.** Nothing in this workspace may open a socket except a Bluetooth socket (RFCOMM for the control link, L2CAP for SDP). | |
| 25 | + | - The one exception, approved by the owner: the local system D-Bus Unix socket, used through `zbus` only to talk to BlueZ (`org.bluez`). budctl opens that socket itself at the fixed path, so an environment variable can never redirect it to TCP. | |
| 26 | + | - No HTTP clients (reqwest, hyper, ureq, surf, etc.) may appear in the dependency tree, direct or transitive. This is enforced with `cargo deny` (`deny.toml`), clippy `disallowed-types`, and `crates/budctl-core/tests/guards.rs`. | |
| 27 | + | 2. **Clean-room protocol work.** Protocol facts (UUIDs, channel numbers, packet framing, command IDs, init sequences) may come from public references, but no other project's source code is ever translated or copied. Write findings into `docs/protocol/<device>.md` in our own words, then implement from that spec. | |
| 28 | + | - Committed files do not name or cite those references. Each fact carries an evidence level instead (rule 3). | |
| 29 | + | - Only the owner can change this rule, by editing it here. | |
| 30 | + | 3. **Never guess command bytes.** Every command in a device module must trace back to an anchor in its protocol spec, and the spec must give the fact's evidence level (`realme_t310.md#sources`): seen on a T310, vendor behavior, another model of the family, derived, or verified by us on hardware (`ours-YYYY-MM-DD`). | |
| 31 | + | - Put the spec reference in a doc comment on the constant, as `/// Spec: realme_t310.md#anchor`. `tests/guards.rs` checks that each anchor exists. | |
| 32 | + | 4. **Write commands are the risky part.** Read-only commands (battery, current ANC mode, firmware version) get implemented and tested first. Write commands are added one at a time and tested on real hardware before the next one. | |
| 33 | + | 5. **No `unwrap()`/`expect()`/`panic!`/indexing outside tests.** Bluetooth fails in many ways, and every failure becomes a typed `budctl_core::Error`. Workspace clippy lints enforce this. `unsafe` is allowed only in `crates/budctl-core/src/transport/socket.rs`. | |
| 34 | + | ||
| 35 | + | ## Stack | |
| 36 | + | ||
| 37 | + | - Rust (edition 2024) in a cargo workspace: | |
| 38 | + | - `crates/budctl-core`: library with transport, BlueZ and device plugins. | |
| 39 | + | - `crates/budctl-cli`: package and binary `budctl`. | |
| 40 | + | - `crates/budctl-gui` will come later. | |
| 41 | + | - Bluetooth goes through BlueZ: | |
| 42 | + | - Raw `AF_BLUETOOTH` sockets via `libc`: RFCOMM for the control link, L2CAP to read the buds' SDP record. | |
| 43 | + | - `zbus` (blocking API) only to list paired devices. | |
| 44 | + | - Supporting BLE GATT would need a new transport kind in core. | |
| 45 | + | - CLI: `clap` (derive). It is parsed with `try_parse`, so usage errors exit 1, not clap's default 2. `serde_json` provides `--json`. | |
| 46 | + | - Tests: `cargo test --workspace`. Lints: `cargo clippy --workspace --all-targets -- -D warnings`. Dependency policy: `cargo deny check bans licenses sources`. | |
| 47 | + | - Keep dependencies minimal. Every new dependency needs a reason in the commit message. The current direct dependencies: | |
| 48 | + | - core: `libc`, `zbus`, `serde` | |
| 49 | + | - cli: `clap`, `serde_json` | |
| 50 | + | ||
| 51 | + | ## Device plugin contract | |
| 52 | + | ||
| 53 | + | Each module in `crates/budctl-core/src/devices/` defines one `Device` implementation and is listed in `devices::REGISTRY`. A device declares: | |
| 54 | + | ||
| 55 | + | - `name()`, plus `matches()`: how to recognize it from BlueZ data (Bluetooth name and/or service UUID). | |
| 56 | + | - `rfcomm_uuids()`: the transport. SDP turns the UUID into an RFCOMM channel. | |
| 57 | + | - `open()`: runs any init sequence the buds need before they accept commands, and returns a `Session`. | |
| 58 | + | - The features the model supports. The CLI and GUI only show features the connected device declares. | |
| 59 | + | - Pure encode/decode functions (value → bytes, bytes → value) with no I/O, so they can be unit-tested without hardware. | |
| 60 | + | ||
| 61 | + | Many realme / OPPO / OnePlus buds share one protocol family. `devices/realme_t310/frame.rs` and `link.rs` hold the shared framing and request/reply logic, and contain no T310 tables. If a second device from that family is added, move them to `devices/oppo_family/` then, not before. | |
| 62 | + | ||
| 63 | + | ## Connection behavior | |
| 64 | + | ||
| 65 | + | - The control channel is often single-client. If an app on the phone holds it, connecting from Linux may fail. Report that plainly ("control channel busy — is another app connected?") instead of retrying in a loop. | |
| 66 | + | - CLI commands connect, act and disconnect. The GUI must also release the channel when idle rather than hold it open. | |
| 67 | + | - Timeouts on every read. Buds that don't answer should produce a clear error, never a hang. | |
| 68 | + | - While a session waits for anything, it keeps answering the buds' own requests (e.g. the time request). Never `thread::sleep` in core; clippy bans it. | |
| 69 | + | ||
| 70 | + | ## CLI shape | |
| 71 | + | ||
| 72 | + | ``` | |
| 73 | + | budctl list # paired devices budctl recognizes | |
| 74 | + | budctl status # battery, ANC mode, EQ, game mode | |
| 75 | + | budctl touch # touch controls (gesture table) per bud | |
| 76 | + | budctl anc off|on|transparency | |
| 77 | + | budctl eq <preset> | |
| 78 | + | budctl game on|off | |
| 79 | + | budctl --device <MAC> ... # when more than one supported device is paired | |
| 80 | + | budctl --json status # machine-readable output for scripts/status bars ("schema": 1) | |
| 81 | + | budctl --debug ... # hex-dump every frame sent/received (stderr) | |
| 82 | + | ``` | |
| 83 | + | ||
| 84 | + | Write commands (`anc`, `eq`, `game`, `set`, `bass`, `touch <side> …`, `find`, `fit-test`, custom EQ) are added one at a time, following rule 4. The plan is in `docs/protocol/realme_t310.md#roadmap`. | |
| 85 | + | ||
| 86 | + | Exit codes: | |
| 87 | + | ||
| 88 | + | | Code | Meaning | | |
| 89 | + | |---|---| | |
| 90 | + | | 0 | success | | |
| 91 | + | | 1 | usage error | | |
| 92 | + | | 2 | device not found / not connected | | |
| 93 | + | | 3 | channel busy | | |
| 94 | + | | 4 | device rejected command or timed out | | |
| 95 | + | ||
| 96 | + | ## Roadmap | |
| 97 | + | ||
| 98 | + | 1. **Spec**: `docs/protocol/realme_t310.md` and `docs/protocol/transport.md`. Done when they cover transport, framing, handshake and the command table with sources. | |
| 99 | + | 2. **Read-only CLI**: connect, handshake, `list`, `status`, `touch`. Verify on real buds (checkpoint HW1). | |
| 100 | + | 3. **Write commands**, one at a time, each verified on hardware before the next: | |
| 101 | + | 1. ANC | |
| 102 | + | 2. ANC levels | |
| 103 | + | 3. game mode | |
| 104 | + | 4. EQ preset | |
| 105 | + | 5. switches (bass boost, 3D sound, wind; dual connection last) | |
| 106 | + | 6. bass level | |
| 107 | + | 7. find | |
| 108 | + | 8. touch controls | |
| 109 | + | 9. hold cycle | |
| 110 | + | 10. fit test | |
| 111 | + | 11. custom EQ | |
| 112 | + | 4. **GUI**: Quickshell/Aurora via `--json`, or a Rust GUI on top of the same core. | |
| 113 | + | 5. **More devices**: as acquired. | |
| 114 | + | ||
| 115 | + | ## Working with Claude | |
| 116 | + | ||
| 117 | + | - Claude has no access to the buds. Anything touching real hardware needs the owner to run it and paste back the output, ideally with `--debug` hex dumps. | |
| 118 | + | - Each hardware checkpoint goes into `docs/protocol/realme_t310.md#verification-log`, with the date and the evidence level ("ours-YYYY-MM-DD"). | |
| 119 | + | - When the spec is unclear, ask for a capture rather than guessing: | |
| 120 | + | - `sudo btmon -w file.btsnoop` on Linux shows budctl's own traffic. | |
| 121 | + | - An Android "Bluetooth HCI snoop log" shows what realme Link sends. | |
| 122 | + | - Keep the encode/decode logic pure and covered by tests, so most changes can be verified without hardware. | |
| 123 | + | - Before adding a feature, check the spec says the T310 supports it. The protocol family covers many models, and not every command applies to this one. The T310's command bitmap (spec §5) is the authority: never send a command whose bit is off. | |
| 124 | + | ||
| 125 | + | ## License | |
| 126 | + | ||
| 127 | + | GPL-3.0-or-later (`LICENSE`). Rule 2 forbids copying other projects' code. | |
| @@ -0,0 +1,1016 @@ | |||
| 1 | + | # This file is automatically @generated by Cargo. | |
| 2 | + | # It is not intended for manual editing. | |
| 3 | + | version = 4 | |
| 4 | + | ||
| 5 | + | [[package]] | |
| 6 | + | name = "anstream" | |
| 7 | + | version = "1.0.0" | |
| 8 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 9 | + | checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" | |
| 10 | + | dependencies = [ | |
| 11 | + | "anstyle", | |
| 12 | + | "anstyle-parse", | |
| 13 | + | "anstyle-query", | |
| 14 | + | "anstyle-wincon", | |
| 15 | + | "colorchoice", | |
| 16 | + | "is_terminal_polyfill", | |
| 17 | + | "utf8parse", | |
| 18 | + | ] | |
| 19 | + | ||
| 20 | + | [[package]] | |
| 21 | + | name = "anstyle" | |
| 22 | + | version = "1.0.14" | |
| 23 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 24 | + | checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" | |
| 25 | + | ||
| 26 | + | [[package]] | |
| 27 | + | name = "anstyle-parse" | |
| 28 | + | version = "1.0.0" | |
| 29 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 30 | + | checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" | |
| 31 | + | dependencies = [ | |
| 32 | + | "utf8parse", | |
| 33 | + | ] | |
| 34 | + | ||
| 35 | + | [[package]] | |
| 36 | + | name = "anstyle-query" | |
| 37 | + | version = "1.1.5" | |
| 38 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 39 | + | checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" | |
| 40 | + | dependencies = [ | |
| 41 | + | "windows-sys", | |
| 42 | + | ] | |
| 43 | + | ||
| 44 | + | [[package]] | |
| 45 | + | name = "anstyle-wincon" | |
| 46 | + | version = "3.0.11" | |
| 47 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 48 | + | checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" | |
| 49 | + | dependencies = [ | |
| 50 | + | "anstyle", | |
| 51 | + | "once_cell_polyfill", | |
| 52 | + | "windows-sys", | |
| 53 | + | ] | |
| 54 | + | ||
| 55 | + | [[package]] | |
| 56 | + | name = "async-broadcast" | |
| 57 | + | version = "0.7.2" | |
| 58 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 59 | + | checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" | |
| 60 | + | dependencies = [ | |
| 61 | + | "event-listener", | |
| 62 | + | "event-listener-strategy", | |
| 63 | + | "futures-core", | |
| 64 | + | "pin-project-lite", | |
| 65 | + | ] | |
| 66 | + | ||
| 67 | + | [[package]] | |
| 68 | + | name = "async-channel" | |
| 69 | + | version = "2.5.0" | |
| 70 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 71 | + | checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" | |
| 72 | + | dependencies = [ | |
| 73 | + | "concurrent-queue", | |
| 74 | + | "event-listener-strategy", | |
| 75 | + | "futures-core", | |
| 76 | + | "pin-project-lite", | |
| 77 | + | ] | |
| 78 | + | ||
| 79 | + | [[package]] | |
| 80 | + | name = "async-executor" | |
| 81 | + | version = "1.14.0" | |
| 82 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 83 | + | checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" | |
| 84 | + | dependencies = [ | |
| 85 | + | "async-task", | |
| 86 | + | "concurrent-queue", | |
| 87 | + | "fastrand", | |
| 88 | + | "futures-lite", | |
| 89 | + | "pin-project-lite", | |
| 90 | + | "slab", | |
| 91 | + | ] | |
| 92 | + | ||
| 93 | + | [[package]] | |
| 94 | + | name = "async-io" | |
| 95 | + | version = "2.6.0" | |
| 96 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 97 | + | checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" | |
| 98 | + | dependencies = [ | |
| 99 | + | "autocfg", | |
| 100 | + | "cfg-if", | |
| 101 | + | "concurrent-queue", | |
| 102 | + | "futures-io", | |
| 103 | + | "futures-lite", | |
| 104 | + | "parking", | |
| 105 | + | "polling", | |
| 106 | + | "rustix", | |
| 107 | + | "slab", | |
| 108 | + | "windows-sys", | |
| 109 | + | ] | |
| 110 | + | ||
| 111 | + | [[package]] | |
| 112 | + | name = "async-lock" | |
| 113 | + | version = "3.4.2" | |
| 114 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 115 | + | checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" | |
| 116 | + | dependencies = [ | |
| 117 | + | "event-listener", | |
| 118 | + | "event-listener-strategy", | |
| 119 | + | "pin-project-lite", | |
| 120 | + | ] | |
| 121 | + | ||
| 122 | + | [[package]] | |
| 123 | + | name = "async-process" | |
| 124 | + | version = "2.5.0" | |
| 125 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 126 | + | checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" | |
| 127 | + | dependencies = [ | |
| 128 | + | "async-channel", | |
| 129 | + | "async-io", | |
| 130 | + | "async-lock", | |
| 131 | + | "async-signal", | |
| 132 | + | "async-task", | |
| 133 | + | "blocking", | |
| 134 | + | "cfg-if", | |
| 135 | + | "event-listener", | |
| 136 | + | "futures-lite", | |
| 137 | + | "rustix", | |
| 138 | + | ] | |
| 139 | + | ||
| 140 | + | [[package]] | |
| 141 | + | name = "async-recursion" | |
| 142 | + | version = "1.2.0" | |
| 143 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 144 | + | checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" | |
| 145 | + | dependencies = [ | |
| 146 | + | "proc-macro2", | |
| 147 | + | "quote", | |
| 148 | + | "syn 3.0.9", | |
| 149 | + | ] | |
| 150 | + | ||
| 151 | + | [[package]] | |
| 152 | + | name = "async-signal" | |
| 153 | + | version = "0.2.14" | |
| 154 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 155 | + | checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" | |
| 156 | + | dependencies = [ | |
| 157 | + | "async-io", | |
| 158 | + | "async-lock", | |
| 159 | + | "atomic-waker", | |
| 160 | + | "cfg-if", | |
| 161 | + | "futures-core", | |
| 162 | + | "futures-io", | |
| 163 | + | "rustix", | |
| 164 | + | "signal-hook-registry", | |
| 165 | + | "slab", | |
| 166 | + | "windows-sys", | |
| 167 | + | ] | |
| 168 | + | ||
| 169 | + | [[package]] | |
| 170 | + | name = "async-task" | |
| 171 | + | version = "4.7.1" | |
| 172 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 173 | + | checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" | |
| 174 | + | ||
| 175 | + | [[package]] | |
| 176 | + | name = "async-trait" | |
| 177 | + | version = "0.1.92" | |
| 178 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 179 | + | checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" | |
| 180 | + | dependencies = [ | |
| 181 | + | "proc-macro2", | |
| 182 | + | "quote", | |
| 183 | + | "syn 3.0.9", | |
| 184 | + | ] | |
| 185 | + | ||
| 186 | + | [[package]] | |
| 187 | + | name = "atomic-waker" | |
| 188 | + | version = "1.1.2" | |
| 189 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 190 | + | checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" | |
| 191 | + | ||
| 192 | + | [[package]] | |
| 193 | + | name = "autocfg" | |
| 194 | + | version = "1.5.1" | |
| 195 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 196 | + | checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" | |
| 197 | + | ||
| 198 | + | [[package]] | |
| 199 | + | name = "bitflags" | |
| 200 | + | version = "2.13.2" | |
| 201 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 202 | + | checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" | |
| 203 | + | ||
| 204 | + | [[package]] | |
| 205 | + | name = "blocking" | |
| 206 | + | version = "1.7.0" | |
| 207 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 208 | + | checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" | |
| 209 | + | dependencies = [ | |
| 210 | + | "async-channel", | |
| 211 | + | "async-task", | |
| 212 | + | "futures-io", | |
| 213 | + | "futures-lite", | |
| 214 | + | "piper", | |
| 215 | + | ] | |
| 216 | + | ||
| 217 | + | [[package]] | |
| 218 | + | name = "budctl" | |
| 219 | + | version = "0.1.0" | |
| 220 | + | dependencies = [ | |
| 221 | + | "budctl-core", | |
| 222 | + | "clap", | |
| 223 | + | "serde_json", | |
| 224 | + | ] | |
| 225 | + | ||
| 226 | + | [[package]] | |
| 227 | + | name = "budctl-core" | |
| 228 | + | version = "0.1.0" | |
| 229 | + | dependencies = [ | |
| 230 | + | "libc", | |
| 231 | + | "serde", | |
| 232 | + | "zbus", | |
| 233 | + | ] | |
| 234 | + | ||
| 235 | + | [[package]] | |
| 236 | + | name = "bumpalo" | |
| 237 | + | version = "3.20.3" | |
| 238 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 239 | + | checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" | |
| 240 | + | ||
| 241 | + | [[package]] | |
| 242 | + | name = "cfg-if" | |
| 243 | + | version = "1.0.5" | |
| 244 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 245 | + | checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" | |
| 246 | + | ||
| 247 | + | [[package]] | |
| 248 | + | name = "clap" | |
| 249 | + | version = "4.6.7" | |
| 250 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 251 | + | checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" | |
| 252 | + | dependencies = [ | |
| 253 | + | "clap_builder", | |
| 254 | + | "clap_derive", | |
| 255 | + | ] | |
| 256 | + | ||
| 257 | + | [[package]] | |
| 258 | + | name = "clap_builder" | |
| 259 | + | version = "4.6.7" | |
| 260 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 261 | + | checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" | |
| 262 | + | dependencies = [ | |
| 263 | + | "anstream", | |
| 264 | + | "anstyle", | |
| 265 | + | "clap_lex", | |
| 266 | + | "strsim", | |
| 267 | + | ] | |
| 268 | + | ||
| 269 | + | [[package]] | |
| 270 | + | name = "clap_derive" | |
| 271 | + | version = "4.6.7" | |
| 272 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 273 | + | checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" | |
| 274 | + | dependencies = [ | |
| 275 | + | "heck", | |
| 276 | + | "proc-macro2", | |
| 277 | + | "quote", | |
| 278 | + | "syn 3.0.9", | |
| 279 | + | ] | |
| 280 | + | ||
| 281 | + | [[package]] | |
| 282 | + | name = "clap_lex" | |
| 283 | + | version = "1.1.1" | |
| 284 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 285 | + | checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" | |
| 286 | + | ||
| 287 | + | [[package]] | |
| 288 | + | name = "colorchoice" | |
| 289 | + | version = "1.0.5" | |
| 290 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 291 | + | checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" | |
| 292 | + | ||
| 293 | + | [[package]] | |
| 294 | + | name = "concurrent-queue" | |
| 295 | + | version = "2.5.0" | |
| 296 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 297 | + | checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" | |
| 298 | + | dependencies = [ | |
| 299 | + | "crossbeam-utils", | |
| 300 | + | ] | |
| 301 | + | ||
| 302 | + | [[package]] | |
| 303 | + | name = "crossbeam-utils" | |
| 304 | + | version = "0.8.23" | |
| 305 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 306 | + | checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" | |
| 307 | + | ||
| 308 | + | [[package]] | |
| 309 | + | name = "endi" | |
| 310 | + | version = "1.1.1" | |
| 311 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 312 | + | checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" | |
| 313 | + | ||
| 314 | + | [[package]] | |
| 315 | + | name = "enumflags2" | |
| 316 | + | version = "0.7.12" | |
| 317 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 318 | + | checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" | |
| 319 | + | dependencies = [ | |
| 320 | + | "enumflags2_derive", | |
| 321 | + | "serde", | |
| 322 | + | ] | |
| 323 | + | ||
| 324 | + | [[package]] | |
| 325 | + | name = "enumflags2_derive" | |
| 326 | + | version = "0.7.12" | |
| 327 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 328 | + | checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" | |
| 329 | + | dependencies = [ | |
| 330 | + | "proc-macro2", | |
| 331 | + | "quote", | |
| 332 | + | "syn 2.0.119", | |
| 333 | + | ] | |
| 334 | + | ||
| 335 | + | [[package]] | |
| 336 | + | name = "equivalent" | |
| 337 | + | version = "1.0.3" | |
| 338 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 339 | + | checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" | |
| 340 | + | ||
| 341 | + | [[package]] | |
| 342 | + | name = "errno" | |
| 343 | + | version = "0.3.14" | |
| 344 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 345 | + | checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" | |
| 346 | + | dependencies = [ | |
| 347 | + | "libc", | |
| 348 | + | "windows-sys", | |
| 349 | + | ] | |
| 350 | + | ||
| 351 | + | [[package]] | |
| 352 | + | name = "event-listener" | |
| 353 | + | version = "5.4.2" | |
| 354 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 355 | + | checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" | |
| 356 | + | dependencies = [ | |
| 357 | + | "parking", | |
| 358 | + | "pin-project-lite", | |
| 359 | + | ] | |
| 360 | + | ||
| 361 | + | [[package]] | |
| 362 | + | name = "event-listener-strategy" | |
| 363 | + | version = "0.5.4" | |
| 364 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 365 | + | checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" | |
| 366 | + | dependencies = [ | |
| 367 | + | "event-listener", | |
| 368 | + | "pin-project-lite", | |
| 369 | + | ] | |
| 370 | + | ||
| 371 | + | [[package]] | |
| 372 | + | name = "fastrand" | |
| 373 | + | version = "2.5.0" | |
| 374 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 375 | + | checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" | |
| 376 | + | ||
| 377 | + | [[package]] | |
| 378 | + | name = "futures-core" | |
| 379 | + | version = "0.3.34" | |
| 380 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 381 | + | checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" | |
| 382 | + | ||
| 383 | + | [[package]] | |
| 384 | + | name = "futures-io" | |
| 385 | + | version = "0.3.34" | |
| 386 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 387 | + | checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" | |
| 388 | + | ||
| 389 | + | [[package]] | |
| 390 | + | name = "futures-lite" | |
| 391 | + | version = "2.6.1" | |
| 392 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 393 | + | checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" | |
| 394 | + | dependencies = [ | |
| 395 | + | "fastrand", | |
| 396 | + | "futures-core", | |
| 397 | + | "futures-io", | |
| 398 | + | "parking", | |
| 399 | + | "pin-project-lite", | |
| 400 | + | ] | |
| 401 | + | ||
| 402 | + | [[package]] | |
| 403 | + | name = "futures-task" | |
| 404 | + | version = "0.3.34" | |
| 405 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 406 | + | checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" | |
| 407 | + | ||
| 408 | + | [[package]] | |
| 409 | + | name = "futures-util" | |
| 410 | + | version = "0.3.34" | |
| 411 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 412 | + | checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" | |
| 413 | + | dependencies = [ | |
| 414 | + | "futures-core", | |
| 415 | + | "futures-task", | |
| 416 | + | "pin-project-lite", | |
| 417 | + | "slab", | |
| 418 | + | ] | |
| 419 | + | ||
| 420 | + | [[package]] | |
| 421 | + | name = "getrandom" | |
| 422 | + | version = "0.4.3" | |
| 423 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 424 | + | checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" | |
| 425 | + | dependencies = [ | |
| 426 | + | "cfg-if", | |
| 427 | + | "libc", | |
| 428 | + | "r-efi", | |
| 429 | + | ] | |
| 430 | + | ||
| 431 | + | [[package]] | |
| 432 | + | name = "hashbrown" | |
| 433 | + | version = "0.17.1" | |
| 434 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 435 | + | checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" | |
| 436 | + | ||
| 437 | + | [[package]] | |
| 438 | + | name = "heck" | |
| 439 | + | version = "0.5.0" | |
| 440 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 441 | + | checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" | |
| 442 | + | ||
| 443 | + | [[package]] | |
| 444 | + | name = "hermit-abi" | |
| 445 | + | version = "0.5.3" | |
| 446 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 447 | + | checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" | |
| 448 | + | ||
| 449 | + | [[package]] | |
| 450 | + | name = "hex" | |
| 451 | + | version = "0.4.3" | |
| 452 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 453 | + | checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" | |
| 454 | + | ||
| 455 | + | [[package]] | |
| 456 | + | name = "indexmap" | |
| 457 | + | version = "2.14.2" | |
| 458 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 459 | + | checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" | |
| 460 | + | dependencies = [ | |
| 461 | + | "equivalent", | |
| 462 | + | "hashbrown", | |
| 463 | + | ] | |
| 464 | + | ||
| 465 | + | [[package]] | |
| 466 | + | name = "is_terminal_polyfill" | |
| 467 | + | version = "1.70.2" | |
| 468 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 469 | + | checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" | |
| 470 | + | ||
| 471 | + | [[package]] | |
| 472 | + | name = "itoa" | |
| 473 | + | version = "1.0.18" | |
| 474 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 475 | + | checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" | |
| 476 | + | ||
| 477 | + | [[package]] | |
| 478 | + | name = "js-sys" | |
| 479 | + | version = "0.3.106" | |
| 480 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 481 | + | checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" | |
| 482 | + | dependencies = [ | |
| 483 | + | "cfg-if", | |
| 484 | + | "futures-util", | |
| 485 | + | "wasm-bindgen", | |
| 486 | + | ] | |
| 487 | + | ||
| 488 | + | [[package]] | |
| 489 | + | name = "libc" | |
| 490 | + | version = "0.2.191" | |
| 491 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 492 | + | checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" | |
| 493 | + | ||
| 494 | + | [[package]] | |
| 495 | + | name = "linux-raw-sys" | |
| 496 | + | version = "0.12.1" | |
| 497 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 498 | + | checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" | |
| 499 | + | ||
| 500 | + | [[package]] | |
| 501 | + | name = "memchr" | |
| 502 | + | version = "2.8.3" | |
| 503 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 504 | + | checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" | |
| 505 | + | ||
| 506 | + | [[package]] | |
| 507 | + | name = "memoffset" | |
| 508 | + | version = "0.9.1" | |
| 509 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 510 | + | checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" | |
| 511 | + | dependencies = [ | |
| 512 | + | "autocfg", | |
| 513 | + | ] | |
| 514 | + | ||
| 515 | + | [[package]] | |
| 516 | + | name = "once_cell" | |
| 517 | + | version = "1.21.4" | |
| 518 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 519 | + | checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" | |
| 520 | + | ||
| 521 | + | [[package]] | |
| 522 | + | name = "once_cell_polyfill" | |
| 523 | + | version = "1.70.2" | |
| 524 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 525 | + | checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" | |
| 526 | + | ||
| 527 | + | [[package]] | |
| 528 | + | name = "ordered-stream" | |
| 529 | + | version = "0.2.0" | |
| 530 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 531 | + | checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" | |
| 532 | + | dependencies = [ | |
| 533 | + | "futures-core", | |
| 534 | + | "pin-project-lite", | |
| 535 | + | ] | |
| 536 | + | ||
| 537 | + | [[package]] | |
| 538 | + | name = "parking" | |
| 539 | + | version = "2.2.1" | |
| 540 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 541 | + | checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" | |
| 542 | + | ||
| 543 | + | [[package]] | |
| 544 | + | name = "pin-project-lite" | |
| 545 | + | version = "0.2.17" | |
| 546 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 547 | + | checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" | |
| 548 | + | ||
| 549 | + | [[package]] | |
| 550 | + | name = "piper" | |
| 551 | + | version = "0.2.5" | |
| 552 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 553 | + | checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" | |
| 554 | + | dependencies = [ | |
| 555 | + | "atomic-waker", | |
| 556 | + | "fastrand", | |
| 557 | + | "futures-io", | |
| 558 | + | ] | |
| 559 | + | ||
| 560 | + | [[package]] | |
| 561 | + | name = "polling" | |
| 562 | + | version = "3.11.0" | |
| 563 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 564 | + | checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" | |
| 565 | + | dependencies = [ | |
| 566 | + | "cfg-if", | |
| 567 | + | "concurrent-queue", | |
| 568 | + | "hermit-abi", | |
| 569 | + | "pin-project-lite", | |
| 570 | + | "rustix", | |
| 571 | + | "windows-sys", | |
| 572 | + | ] | |
| 573 | + | ||
| 574 | + | [[package]] | |
| 575 | + | name = "proc-macro-crate" | |
| 576 | + | version = "3.5.0" | |
| 577 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 578 | + | checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" | |
| 579 | + | dependencies = [ | |
| 580 | + | "toml_edit", | |
| 581 | + | ] | |
| 582 | + | ||
| 583 | + | [[package]] | |
| 584 | + | name = "proc-macro2" | |
| 585 | + | version = "1.0.107" | |
| 586 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 587 | + | checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" | |
| 588 | + | dependencies = [ | |
| 589 | + | "unicode-ident", | |
| 590 | + | ] | |
| 591 | + | ||
| 592 | + | [[package]] | |
| 593 | + | name = "quote" | |
| 594 | + | version = "1.0.47" | |
| 595 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 596 | + | checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" | |
| 597 | + | dependencies = [ | |
| 598 | + | "proc-macro2", | |
| 599 | + | ] | |
| 600 | + | ||
| 601 | + | [[package]] | |
| 602 | + | name = "r-efi" | |
| 603 | + | version = "6.0.0" | |
| 604 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 605 | + | checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" | |
| 606 | + | ||
| 607 | + | [[package]] | |
| 608 | + | name = "rustix" | |
| 609 | + | version = "1.1.6" | |
| 610 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 611 | + | checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" | |
| 612 | + | dependencies = [ | |
| 613 | + | "bitflags", | |
| 614 | + | "errno", | |
| 615 | + | "libc", | |
| 616 | + | "linux-raw-sys", | |
| 617 | + | "windows-sys", | |
| 618 | + | ] | |
| 619 | + | ||
| 620 | + | [[package]] | |
| 621 | + | name = "rustversion" | |
| 622 | + | version = "1.0.23" | |
| 623 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 624 | + | checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" | |
| 625 | + | ||
| 626 | + | [[package]] | |
| 627 | + | name = "serde" | |
| 628 | + | version = "1.0.229" | |
| 629 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 630 | + | checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" | |
| 631 | + | dependencies = [ | |
| 632 | + | "serde_core", | |
| 633 | + | "serde_derive", | |
| 634 | + | ] | |
| 635 | + | ||
| 636 | + | [[package]] | |
| 637 | + | name = "serde_core" | |
| 638 | + | version = "1.0.229" | |
| 639 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 640 | + | checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" | |
| 641 | + | dependencies = [ | |
| 642 | + | "serde_derive", | |
| 643 | + | ] | |
| 644 | + | ||
| 645 | + | [[package]] | |
| 646 | + | name = "serde_derive" | |
| 647 | + | version = "1.0.229" | |
| 648 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 649 | + | checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" | |
| 650 | + | dependencies = [ | |
| 651 | + | "proc-macro2", | |
| 652 | + | "quote", | |
| 653 | + | "syn 3.0.9", | |
| 654 | + | ] | |
| 655 | + | ||
| 656 | + | [[package]] | |
| 657 | + | name = "serde_json" | |
| 658 | + | version = "1.0.154" | |
| 659 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 660 | + | checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" | |
| 661 | + | dependencies = [ | |
| 662 | + | "itoa", | |
| 663 | + | "memchr", | |
| 664 | + | "serde", | |
| 665 | + | "serde_core", | |
| 666 | + | "zmij", | |
| 667 | + | ] | |
| 668 | + | ||
| 669 | + | [[package]] | |
| 670 | + | name = "serde_repr" | |
| 671 | + | version = "0.1.21" | |
| 672 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 673 | + | checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" | |
| 674 | + | dependencies = [ | |
| 675 | + | "proc-macro2", | |
| 676 | + | "quote", | |
| 677 | + | "syn 3.0.9", | |
| 678 | + | ] | |
| 679 | + | ||
| 680 | + | [[package]] | |
| 681 | + | name = "signal-hook-registry" | |
| 682 | + | version = "1.4.8" | |
| 683 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 684 | + | checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" | |
| 685 | + | dependencies = [ | |
| 686 | + | "errno", | |
| 687 | + | "libc", | |
| 688 | + | ] | |
| 689 | + | ||
| 690 | + | [[package]] | |
| 691 | + | name = "slab" | |
| 692 | + | version = "0.4.12" | |
| 693 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 694 | + | checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" | |
| 695 | + | ||
| 696 | + | [[package]] | |
| 697 | + | name = "strsim" | |
| 698 | + | version = "0.11.1" | |
| 699 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 700 | + | checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" | |
| 701 | + | ||
| 702 | + | [[package]] | |
| 703 | + | name = "syn" | |
| 704 | + | version = "2.0.119" | |
| 705 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 706 | + | checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" | |
| 707 | + | dependencies = [ | |
| 708 | + | "proc-macro2", | |
| 709 | + | "quote", | |
| 710 | + | "unicode-ident", | |
| 711 | + | ] | |
| 712 | + | ||
| 713 | + | [[package]] | |
| 714 | + | name = "syn" | |
| 715 | + | version = "3.0.9" | |
| 716 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 717 | + | checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" | |
| 718 | + | dependencies = [ | |
| 719 | + | "proc-macro2", | |
| 720 | + | "quote", | |
| 721 | + | "unicode-ident", | |
| 722 | + | ] | |
| 723 | + | ||
| 724 | + | [[package]] | |
| 725 | + | name = "tempfile" | |
| 726 | + | version = "3.27.0" | |
| 727 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 728 | + | checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" | |
| 729 | + | dependencies = [ | |
| 730 | + | "fastrand", | |
| 731 | + | "getrandom", | |
| 732 | + | "once_cell", | |
| 733 | + | "rustix", | |
| 734 | + | "windows-sys", | |
| 735 | + | ] | |
| 736 | + | ||
| 737 | + | [[package]] | |
| 738 | + | name = "toml_datetime" | |
| 739 | + | version = "1.1.2+spec-1.1.0" | |
| 740 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 741 | + | checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" | |
| 742 | + | dependencies = [ | |
| 743 | + | "serde_core", | |
| 744 | + | ] | |
| 745 | + | ||
| 746 | + | [[package]] | |
| 747 | + | name = "toml_edit" | |
| 748 | + | version = "0.25.17+spec-1.1.0" | |
| 749 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 750 | + | checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" | |
| 751 | + | dependencies = [ | |
| 752 | + | "indexmap", | |
| 753 | + | "toml_datetime", | |
| 754 | + | "toml_parser", | |
| 755 | + | "winnow", | |
| 756 | + | ] | |
| 757 | + | ||
| 758 | + | [[package]] | |
| 759 | + | name = "toml_parser" | |
| 760 | + | version = "1.1.5+spec-1.1.0" | |
| 761 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 762 | + | checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" | |
| 763 | + | dependencies = [ | |
| 764 | + | "winnow", | |
| 765 | + | ] | |
| 766 | + | ||
| 767 | + | [[package]] | |
| 768 | + | name = "tracing" | |
| 769 | + | version = "0.1.44" | |
| 770 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 771 | + | checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" | |
| 772 | + | dependencies = [ | |
| 773 | + | "pin-project-lite", | |
| 774 | + | "tracing-attributes", | |
| 775 | + | "tracing-core", | |
| 776 | + | ] | |
| 777 | + | ||
| 778 | + | [[package]] | |
| 779 | + | name = "tracing-attributes" | |
| 780 | + | version = "0.1.31" | |
| 781 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 782 | + | checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" | |
| 783 | + | dependencies = [ | |
| 784 | + | "proc-macro2", | |
| 785 | + | "quote", | |
| 786 | + | "syn 2.0.119", | |
| 787 | + | ] | |
| 788 | + | ||
| 789 | + | [[package]] | |
| 790 | + | name = "tracing-core" | |
| 791 | + | version = "0.1.36" | |
| 792 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 793 | + | checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" | |
| 794 | + | dependencies = [ | |
| 795 | + | "once_cell", | |
| 796 | + | ] | |
| 797 | + | ||
| 798 | + | [[package]] | |
| 799 | + | name = "uds_windows" | |
| 800 | + | version = "1.2.1" | |
| 801 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 802 | + | checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" | |
| 803 | + | dependencies = [ | |
| 804 | + | "memoffset", | |
| 805 | + | "tempfile", | |
| 806 | + | "windows-sys", | |
| 807 | + | ] | |
| 808 | + | ||
| 809 | + | [[package]] | |
| 810 | + | name = "unicode-ident" | |
| 811 | + | version = "1.0.27" | |
| 812 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 813 | + | checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" | |
| 814 | + | ||
| 815 | + | [[package]] | |
| 816 | + | name = "utf8parse" | |
| 817 | + | version = "0.2.2" | |
| 818 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 819 | + | checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" | |
| 820 | + | ||
| 821 | + | [[package]] | |
| 822 | + | name = "uuid" | |
| 823 | + | version = "1.26.1" | |
| 824 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 825 | + | checksum = "2ef6dac1e96601b4fb3acccccff2139741fcb757cb9a36089bf5be91cfb285ce" | |
| 826 | + | dependencies = [ | |
| 827 | + | "js-sys", | |
| 828 | + | "serde_core", | |
| 829 | + | "wasm-bindgen", | |
| 830 | + | ] | |
| 831 | + | ||
| 832 | + | [[package]] | |
| 833 | + | name = "wasm-bindgen" | |
| 834 | + | version = "0.2.129" | |
| 835 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 836 | + | checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" | |
| 837 | + | dependencies = [ | |
| 838 | + | "cfg-if", | |
| 839 | + | "once_cell", | |
| 840 | + | "rustversion", | |
| 841 | + | "wasm-bindgen-macro", | |
| 842 | + | "wasm-bindgen-shared", | |
| 843 | + | ] | |
| 844 | + | ||
| 845 | + | [[package]] | |
| 846 | + | name = "wasm-bindgen-macro" | |
| 847 | + | version = "0.2.129" | |
| 848 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 849 | + | checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" | |
| 850 | + | dependencies = [ | |
| 851 | + | "quote", | |
| 852 | + | "wasm-bindgen-macro-support", | |
| 853 | + | ] | |
| 854 | + | ||
| 855 | + | [[package]] | |
| 856 | + | name = "wasm-bindgen-macro-support" | |
| 857 | + | version = "0.2.129" | |
| 858 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 859 | + | checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" | |
| 860 | + | dependencies = [ | |
| 861 | + | "bumpalo", | |
| 862 | + | "proc-macro2", | |
| 863 | + | "quote", | |
| 864 | + | "syn 3.0.9", | |
| 865 | + | "wasm-bindgen-shared", | |
| 866 | + | ] | |
| 867 | + | ||
| 868 | + | [[package]] | |
| 869 | + | name = "wasm-bindgen-shared" | |
| 870 | + | version = "0.2.129" | |
| 871 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 872 | + | checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" | |
| 873 | + | dependencies = [ | |
| 874 | + | "unicode-ident", | |
| 875 | + | ] | |
| 876 | + | ||
| 877 | + | [[package]] | |
| 878 | + | name = "windows-link" | |
| 879 | + | version = "0.2.1" | |
| 880 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 881 | + | checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" | |
| 882 | + | ||
| 883 | + | [[package]] | |
| 884 | + | name = "windows-sys" | |
| 885 | + | version = "0.61.2" | |
| 886 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 887 | + | checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" | |
| 888 | + | dependencies = [ | |
| 889 | + | "windows-link", | |
| 890 | + | ] | |
| 891 | + | ||
| 892 | + | [[package]] | |
| 893 | + | name = "winnow" | |
| 894 | + | version = "1.0.4" | |
| 895 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 896 | + | checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" | |
| 897 | + | dependencies = [ | |
| 898 | + | "memchr", | |
| 899 | + | ] | |
| 900 | + | ||
| 901 | + | [[package]] | |
| 902 | + | name = "zbus" | |
| 903 | + | version = "5.19.0" | |
| 904 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 905 | + | checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" | |
| 906 | + | dependencies = [ | |
| 907 | + | "async-broadcast", | |
| 908 | + | "async-executor", | |
| 909 | + | "async-io", | |
| 910 | + | "async-lock", | |
| 911 | + | "async-process", | |
| 912 | + | "async-recursion", | |
| 913 | + | "async-task", | |
| 914 | + | "async-trait", | |
| 915 | + | "blocking", | |
| 916 | + | "enumflags2", | |
| 917 | + | "event-listener", | |
| 918 | + | "futures-core", | |
| 919 | + | "futures-lite", | |
| 920 | + | "hex", | |
| 921 | + | "libc", | |
| 922 | + | "ordered-stream", | |
| 923 | + | "rustix", | |
| 924 | + | "serde", | |
| 925 | + | "serde_repr", | |
| 926 | + | "tracing", | |
| 927 | + | "uds_windows", | |
| 928 | + | "uuid", | |
| 929 | + | "windows-sys", | |
| 930 | + | "winnow", | |
| 931 | + | "zbus_macros", | |
| 932 | + | "zbus_names", | |
| 933 | + | "zvariant", | |
| 934 | + | ] | |
| 935 | + | ||
| 936 | + | [[package]] | |
| 937 | + | name = "zbus_macros" | |
| 938 | + | version = "5.19.0" | |
| 939 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 940 | + | checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" | |
| 941 | + | dependencies = [ | |
| 942 | + | "proc-macro-crate", | |
| 943 | + | "proc-macro2", | |
| 944 | + | "quote", | |
| 945 | + | "syn 3.0.9", | |
| 946 | + | "zbus_names", | |
| 947 | + | "zvariant", | |
| 948 | + | "zvariant_utils", | |
| 949 | + | ] | |
| 950 | + | ||
| 951 | + | [[package]] | |
| 952 | + | name = "zbus_names" | |
| 953 | + | version = "4.3.5" | |
| 954 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 955 | + | checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" | |
| 956 | + | dependencies = [ | |
| 957 | + | "serde", | |
| 958 | + | "winnow", | |
| 959 | + | "zvariant", | |
| 960 | + | ] | |
| 961 | + | ||
| 962 | + | [[package]] | |
| 963 | + | name = "zcheapstr" | |
| 964 | + | version = "1.1.0" | |
| 965 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 966 | + | checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" | |
| 967 | + | dependencies = [ | |
| 968 | + | "serde", | |
| 969 | + | ] | |
| 970 | + | ||
| 971 | + | [[package]] | |
| 972 | + | name = "zmij" | |
| 973 | + | version = "1.0.23" | |
| 974 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 975 | + | checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" | |
| 976 | + | ||
| 977 | + | [[package]] | |
| 978 | + | name = "zvariant" | |
| 979 | + | version = "5.15.1" | |
| 980 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 981 | + | checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" | |
| 982 | + | dependencies = [ | |
| 983 | + | "endi", | |
| 984 | + | "enumflags2", | |
| 985 | + | "serde", | |
| 986 | + | "winnow", | |
| 987 | + | "zcheapstr", | |
| 988 | + | "zvariant_derive", | |
| 989 | + | "zvariant_utils", | |
| 990 | + | ] | |
| 991 | + | ||
| 992 | + | [[package]] | |
| 993 | + | name = "zvariant_derive" | |
| 994 | + | version = "5.15.1" | |
| 995 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 996 | + | checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" | |
| 997 | + | dependencies = [ | |
| 998 | + | "proc-macro-crate", | |
| 999 | + | "proc-macro2", | |
| 1000 | + | "quote", | |
| 1001 | + | "syn 3.0.9", | |
| 1002 | + | "zvariant_utils", | |
| 1003 | + | ] | |
| 1004 | + | ||
| 1005 | + | [[package]] | |
| 1006 | + | name = "zvariant_utils" | |
| 1007 | + | version = "4.2.0" | |
| 1008 | + | source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 1009 | + | checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" | |
| 1010 | + | dependencies = [ | |
| 1011 | + | "proc-macro2", | |
| 1012 | + | "quote", | |
| 1013 | + | "serde", | |
| 1014 | + | "syn 3.0.9", | |
| 1015 | + | "winnow", | |
| 1016 | + | ] | |
| @@ -0,0 +1,23 @@ | |||
| 1 | + | [workspace] | |
| 2 | + | resolver = "3" | |
| 3 | + | members = ["crates/budctl-core", "crates/budctl-cli"] | |
| 4 | + | ||
| 5 | + | [workspace.package] | |
| 6 | + | version = "0.1.0" | |
| 7 | + | edition = "2024" | |
| 8 | + | rust-version = "1.88" | |
| 9 | + | license = "GPL-3.0-or-later" | |
| 10 | + | publish = false | |
| 11 | + | ||
| 12 | + | [workspace.lints.rust] | |
| 13 | + | # The only exception is crates/budctl-core/src/transport/socket.rs (Bluetooth socket syscalls). | |
| 14 | + | unsafe_code = "deny" | |
| 15 | + | ||
| 16 | + | [workspace.lints.clippy] | |
| 17 | + | # Bluetooth fails in many ways; every failure must become a typed error, never a panic. | |
| 18 | + | unwrap_used = "deny" | |
| 19 | + | expect_used = "deny" | |
| 20 | + | panic = "deny" | |
| 21 | + | indexing_slicing = "deny" | |
| 22 | + | cast_possible_truncation = "deny" | |
| 23 | + | undocumented_unsafe_blocks = "deny" | |
| @@ -0,0 +1,674 @@ | |||
| 1 | + | GNU GENERAL PUBLIC LICENSE | |
| 2 | + | Version 3, 29 June 2007 | |
| 3 | + | ||
| 4 | + | Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> | |
| 5 | + | Everyone is permitted to copy and distribute verbatim copies | |
| 6 | + | of this license document, but changing it is not allowed. | |
| 7 | + | ||
| 8 | + | Preamble | |
| 9 | + | ||
| 10 | + | The GNU General Public License is a free, copyleft license for | |
| 11 | + | software and other kinds of works. | |
| 12 | + | ||
| 13 | + | The licenses for most software and other practical works are designed | |
| 14 | + | to take away your freedom to share and change the works. By contrast, | |
| 15 | + | the GNU General Public License is intended to guarantee your freedom to | |
| 16 | + | share and change all versions of a program--to make sure it remains free | |
| 17 | + | software for all its users. We, the Free Software Foundation, use the | |
| 18 | + | GNU General Public License for most of our software; it applies also to | |
| 19 | + | any other work released this way by its authors. You can apply it to | |
| 20 | + | your programs, too. | |
| 21 | + | ||
| 22 | + | When we speak of free software, we are referring to freedom, not | |
| 23 | + | price. Our General Public Licenses are designed to make sure that you | |
| 24 | + | have the freedom to distribute copies of free software (and charge for | |
| 25 | + | them if you wish), that you receive source code or can get it if you | |
| 26 | + | want it, that you can change the software or use pieces of it in new | |
| 27 | + | free programs, and that you know you can do these things. | |
| 28 | + | ||
| 29 | + | To protect your rights, we need to prevent others from denying you | |
| 30 | + | these rights or asking you to surrender the rights. Therefore, you have | |
| 31 | + | certain responsibilities if you distribute copies of the software, or if | |
| 32 | + | you modify it: responsibilities to respect the freedom of others. | |
| 33 | + | ||
| 34 | + | For example, if you distribute copies of such a program, whether | |
| 35 | + | gratis or for a fee, you must pass on to the recipients the same | |
| 36 | + | freedoms that you received. You must make sure that they, too, receive | |
| 37 | + | or can get the source code. And you must show them these terms so they | |
| 38 | + | know their rights. | |
| 39 | + | ||
| 40 | + | Developers that use the GNU GPL protect your rights with two steps: | |
| 41 | + | (1) assert copyright on the software, and (2) offer you this License | |
| 42 | + | giving you legal permission to copy, distribute and/or modify it. | |
| 43 | + | ||
| 44 | + | For the developers' and authors' protection, the GPL clearly explains | |
| 45 | + | that there is no warranty for this free software. For both users' and | |
| 46 | + | authors' sake, the GPL requires that modified versions be marked as | |
| 47 | + | changed, so that their problems will not be attributed erroneously to | |
| 48 | + | authors of previous versions. | |
| 49 | + | ||
| 50 | + | Some devices are designed to deny users access to install or run | |
| 51 | + | modified versions of the software inside them, although the manufacturer | |
| 52 | + | can do so. This is fundamentally incompatible with the aim of | |
| 53 | + | protecting users' freedom to change the software. The systematic | |
| 54 | + | pattern of such abuse occurs in the area of products for individuals to | |
| 55 | + | use, which is precisely where it is most unacceptable. Therefore, we | |
| 56 | + | have designed this version of the GPL to prohibit the practice for those | |
| 57 | + | products. If such problems arise substantially in other domains, we | |
| 58 | + | stand ready to extend this provision to those domains in future versions | |
| 59 | + | of the GPL, as needed to protect the freedom of users. | |
| 60 | + | ||
| 61 | + | Finally, every program is threatened constantly by software patents. | |
| 62 | + | States should not allow patents to restrict development and use of | |
| 63 | + | software on general-purpose computers, but in those that do, we wish to | |
| 64 | + | avoid the special danger that patents applied to a free program could | |
| 65 | + | make it effectively proprietary. To prevent this, the GPL assures that | |
| 66 | + | patents cannot be used to render the program non-free. | |
| 67 | + | ||
| 68 | + | The precise terms and conditions for copying, distribution and | |
| 69 | + | modification follow. | |
| 70 | + | ||
| 71 | + | TERMS AND CONDITIONS | |
| 72 | + | ||
| 73 | + | 0. Definitions. | |
| 74 | + | ||
| 75 | + | "This License" refers to version 3 of the GNU General Public License. | |
| 76 | + | ||
| 77 | + | "Copyright" also means copyright-like laws that apply to other kinds of | |
| 78 | + | works, such as semiconductor masks. | |
| 79 | + | ||
| 80 | + | "The Program" refers to any copyrightable work licensed under this | |
| 81 | + | License. Each licensee is addressed as "you". "Licensees" and | |
| 82 | + | "recipients" may be individuals or organizations. | |
| 83 | + | ||
| 84 | + | To "modify" a work means to copy from or adapt all or part of the work | |
| 85 | + | in a fashion requiring copyright permission, other than the making of an | |
| 86 | + | exact copy. The resulting work is called a "modified version" of the | |
| 87 | + | earlier work or a work "based on" the earlier work. | |
| 88 | + | ||
| 89 | + | A "covered work" means either the unmodified Program or a work based | |
| 90 | + | on the Program. | |
| 91 | + | ||
| 92 | + | To "propagate" a work means to do anything with it that, without | |
| 93 | + | permission, would make you directly or secondarily liable for | |
| 94 | + | infringement under applicable copyright law, except executing it on a | |
| 95 | + | computer or modifying a private copy. Propagation includes copying, | |
| 96 | + | distribution (with or without modification), making available to the | |
| 97 | + | public, and in some countries other activities as well. | |
| 98 | + | ||
| 99 | + | To "convey" a work means any kind of propagation that enables other | |
| 100 | + | parties to make or receive copies. Mere interaction with a user through | |
| 101 | + | a computer network, with no transfer of a copy, is not conveying. | |
| 102 | + | ||
| 103 | + | An interactive user interface displays "Appropriate Legal Notices" | |
| 104 | + | to the extent that it includes a convenient and prominently visible | |
| 105 | + | feature that (1) displays an appropriate copyright notice, and (2) | |
| 106 | + | tells the user that there is no warranty for the work (except to the | |
| 107 | + | extent that warranties are provided), that licensees may convey the | |
| 108 | + | work under this License, and how to view a copy of this License. If | |
| 109 | + | the interface presents a list of user commands or options, such as a | |
| 110 | + | menu, a prominent item in the list meets this criterion. | |
| 111 | + | ||
| 112 | + | 1. Source Code. | |
| 113 | + | ||
| 114 | + | The "source code" for a work means the preferred form of the work | |
| 115 | + | for making modifications to it. "Object code" means any non-source | |
| 116 | + | form of a work. | |
| 117 | + | ||
| 118 | + | A "Standard Interface" means an interface that either is an official | |
| 119 | + | standard defined by a recognized standards body, or, in the case of | |
| 120 | + | interfaces specified for a particular programming language, one that | |
| 121 | + | is widely used among developers working in that language. | |
| 122 | + | ||
| 123 | + | The "System Libraries" of an executable work include anything, other | |
| 124 | + | than the work as a whole, that (a) is included in the normal form of | |
| 125 | + | packaging a Major Component, but which is not part of that Major | |
| 126 | + | Component, and (b) serves only to enable use of the work with that | |
| 127 | + | Major Component, or to implement a Standard Interface for which an | |
| 128 | + | implementation is available to the public in source code form. A | |
| 129 | + | "Major Component", in this context, means a major essential component | |
| 130 | + | (kernel, window system, and so on) of the specific operating system | |
| 131 | + | (if any) on which the executable work runs, or a compiler used to | |
| 132 | + | produce the work, or an object code interpreter used to run it. | |
| 133 | + | ||
| 134 | + | The "Corresponding Source" for a work in object code form means all | |
| 135 | + | the source code needed to generate, install, and (for an executable | |
| 136 | + | work) run the object code and to modify the work, including scripts to | |
| 137 | + | control those activities. However, it does not include the work's | |
| 138 | + | System Libraries, or general-purpose tools or generally available free | |
| 139 | + | programs which are used unmodified in performing those activities but | |
| 140 | + | which are not part of the work. For example, Corresponding Source | |
| 141 | + | includes interface definition files associated with source files for | |
| 142 | + | the work, and the source code for shared libraries and dynamically | |
| 143 | + | linked subprograms that the work is specifically designed to require, | |
| 144 | + | such as by intimate data communication or control flow between those | |
| 145 | + | subprograms and other parts of the work. | |
| 146 | + | ||
| 147 | + | The Corresponding Source need not include anything that users | |
| 148 | + | can regenerate automatically from other parts of the Corresponding | |
| 149 | + | Source. | |
| 150 | + | ||
| 151 | + | The Corresponding Source for a work in source code form is that | |
| 152 | + | same work. | |
| 153 | + | ||
| 154 | + | 2. Basic Permissions. | |
| 155 | + | ||
| 156 | + | All rights granted under this License are granted for the term of | |
| 157 | + | copyright on the Program, and are irrevocable provided the stated | |
| 158 | + | conditions are met. This License explicitly affirms your unlimited | |
| 159 | + | permission to run the unmodified Program. The output from running a | |
| 160 | + | covered work is covered by this License only if the output, given its | |
| 161 | + | content, constitutes a covered work. This License acknowledges your | |
| 162 | + | rights of fair use or other equivalent, as provided by copyright law. | |
| 163 | + | ||
| 164 | + | You may make, run and propagate covered works that you do not | |
| 165 | + | convey, without conditions so long as your license otherwise remains | |
| 166 | + | in force. You may convey covered works to others for the sole purpose | |
| 167 | + | of having them make modifications exclusively for you, or provide you | |
| 168 | + | with facilities for running those works, provided that you comply with | |
| 169 | + | the terms of this License in conveying all material for which you do | |
| 170 | + | not control copyright. Those thus making or running the covered works | |
| 171 | + | for you must do so exclusively on your behalf, under your direction | |
| 172 | + | and control, on terms that prohibit them from making any copies of | |
| 173 | + | your copyrighted material outside their relationship with you. | |
| 174 | + | ||
| 175 | + | Conveying under any other circumstances is permitted solely under | |
| 176 | + | the conditions stated below. Sublicensing is not allowed; section 10 | |
| 177 | + | makes it unnecessary. | |
| 178 | + | ||
| 179 | + | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. | |
| 180 | + | ||
| 181 | + | No covered work shall be deemed part of an effective technological | |
| 182 | + | measure under any applicable law fulfilling obligations under article | |
| 183 | + | 11 of the WIPO copyright treaty adopted on 20 December 1996, or | |
| 184 | + | similar laws prohibiting or restricting circumvention of such | |
| 185 | + | measures. | |
| 186 | + | ||
| 187 | + | When you convey a covered work, you waive any legal power to forbid | |
| 188 | + | circumvention of technological measures to the extent such circumvention | |
| 189 | + | is effected by exercising rights under this License with respect to | |
| 190 | + | the covered work, and you disclaim any intention to limit operation or | |
| 191 | + | modification of the work as a means of enforcing, against the work's | |
| 192 | + | users, your or third parties' legal rights to forbid circumvention of | |
| 193 | + | technological measures. | |
| 194 | + | ||
| 195 | + | 4. Conveying Verbatim Copies. | |
| 196 | + | ||
| 197 | + | You may convey verbatim copies of the Program's source code as you | |
| 198 | + | receive it, in any medium, provided that you conspicuously and | |
| 199 | + | appropriately publish on each copy an appropriate copyright notice; | |
| 200 | + | keep intact all notices stating that this License and any | |
| 201 | + | non-permissive terms added in accord with section 7 apply to the code; | |
| 202 | + | keep intact all notices of the absence of any warranty; and give all | |
| 203 | + | recipients a copy of this License along with the Program. | |
| 204 | + | ||
| 205 | + | You may charge any price or no price for each copy that you convey, | |
| 206 | + | and you may offer support or warranty protection for a fee. | |
| 207 | + | ||
| 208 | + | 5. Conveying Modified Source Versions. | |
| 209 | + | ||
| 210 | + | You may convey a work based on the Program, or the modifications to | |
| 211 | + | produce it from the Program, in the form of source code under the | |
| 212 | + | terms of section 4, provided that you also meet all of these conditions: | |
| 213 | + | ||
| 214 | + | a) The work must carry prominent notices stating that you modified | |
| 215 | + | it, and giving a relevant date. | |
| 216 | + | ||
| 217 | + | b) The work must carry prominent notices stating that it is | |
| 218 | + | released under this License and any conditions added under section | |
| 219 | + | 7. This requirement modifies the requirement in section 4 to | |
| 220 | + | "keep intact all notices". | |
| 221 | + | ||
| 222 | + | c) You must license the entire work, as a whole, under this | |
| 223 | + | License to anyone who comes into possession of a copy. This | |
| 224 | + | License will therefore apply, along with any applicable section 7 | |
| 225 | + | additional terms, to the whole of the work, and all its parts, | |
| 226 | + | regardless of how they are packaged. This License gives no | |
| 227 | + | permission to license the work in any other way, but it does not | |
| 228 | + | invalidate such permission if you have separately received it. | |
| 229 | + | ||
| 230 | + | d) If the work has interactive user interfaces, each must display | |
| 231 | + | Appropriate Legal Notices; however, if the Program has interactive | |
| 232 | + | interfaces that do not display Appropriate Legal Notices, your | |
| 233 | + | work need not make them do so. | |
| 234 | + | ||
| 235 | + | A compilation of a covered work with other separate and independent | |
| 236 | + | works, which are not by their nature extensions of the covered work, | |
| 237 | + | and which are not combined with it such as to form a larger program, | |
| 238 | + | in or on a volume of a storage or distribution medium, is called an | |
| 239 | + | "aggregate" if the compilation and its resulting copyright are not | |
| 240 | + | used to limit the access or legal rights of the compilation's users | |
| 241 | + | beyond what the individual works permit. Inclusion of a covered work | |
| 242 | + | in an aggregate does not cause this License to apply to the other | |
| 243 | + | parts of the aggregate. | |
| 244 | + | ||
| 245 | + | 6. Conveying Non-Source Forms. | |
| 246 | + | ||
| 247 | + | You may convey a covered work in object code form under the terms | |
| 248 | + | of sections 4 and 5, provided that you also convey the | |
| 249 | + | machine-readable Corresponding Source under the terms of this License, | |
| 250 | + | in one of these ways: | |
| 251 | + | ||
| 252 | + | a) Convey the object code in, or embodied in, a physical product | |
| 253 | + | (including a physical distribution medium), accompanied by the | |
| 254 | + | Corresponding Source fixed on a durable physical medium | |
| 255 | + | customarily used for software interchange. | |
| 256 | + | ||
| 257 | + | b) Convey the object code in, or embodied in, a physical product | |
| 258 | + | (including a physical distribution medium), accompanied by a | |
| 259 | + | written offer, valid for at least three years and valid for as | |
| 260 | + | long as you offer spare parts or customer support for that product | |
| 261 | + | model, to give anyone who possesses the object code either (1) a | |
| 262 | + | copy of the Corresponding Source for all the software in the | |
| 263 | + | product that is covered by this License, on a durable physical | |
| 264 | + | medium customarily used for software interchange, for a price no | |
| 265 | + | more than your reasonable cost of physically performing this | |
| 266 | + | conveying of source, or (2) access to copy the | |
| 267 | + | Corresponding Source from a network server at no charge. | |
| 268 | + | ||
| 269 | + | c) Convey individual copies of the object code with a copy of the | |
| 270 | + | written offer to provide the Corresponding Source. This | |
| 271 | + | alternative is allowed only occasionally and noncommercially, and | |
| 272 | + | only if you received the object code with such an offer, in accord | |
| 273 | + | with subsection 6b. | |
| 274 | + | ||
| 275 | + | d) Convey the object code by offering access from a designated | |
| 276 | + | place (gratis or for a charge), and offer equivalent access to the | |
| 277 | + | Corresponding Source in the same way through the same place at no | |
| 278 | + | further charge. You need not require recipients to copy the | |
| 279 | + | Corresponding Source along with the object code. If the place to | |
| 280 | + | copy the object code is a network server, the Corresponding Source | |
| 281 | + | may be on a different server (operated by you or a third party) | |
| 282 | + | that supports equivalent copying facilities, provided you maintain | |
| 283 | + | clear directions next to the object code saying where to find the | |
| 284 | + | Corresponding Source. Regardless of what server hosts the | |
| 285 | + | Corresponding Source, you remain obligated to ensure that it is | |
| 286 | + | available for as long as needed to satisfy these requirements. | |
| 287 | + | ||
| 288 | + | e) Convey the object code using peer-to-peer transmission, provided | |
| 289 | + | you inform other peers where the object code and Corresponding | |
| 290 | + | Source of the work are being offered to the general public at no | |
| 291 | + | charge under subsection 6d. | |
| 292 | + | ||
| 293 | + | A separable portion of the object code, whose source code is excluded | |
| 294 | + | from the Corresponding Source as a System Library, need not be | |
| 295 | + | included in conveying the object code work. | |
| 296 | + | ||
| 297 | + | A "User Product" is either (1) a "consumer product", which means any | |
| 298 | + | tangible personal property which is normally used for personal, family, | |
| 299 | + | or household purposes, or (2) anything designed or sold for incorporation | |
| 300 | + | into a dwelling. In determining whether a product is a consumer product, | |
| 301 | + | doubtful cases shall be resolved in favor of coverage. For a particular | |
| 302 | + | product received by a particular user, "normally used" refers to a | |
| 303 | + | typical or common use of that class of product, regardless of the status | |
| 304 | + | of the particular user or of the way in which the particular user | |
| 305 | + | actually uses, or expects or is expected to use, the product. A product | |
| 306 | + | is a consumer product regardless of whether the product has substantial | |
| 307 | + | commercial, industrial or non-consumer uses, unless such uses represent | |
| 308 | + | the only significant mode of use of the product. | |
| 309 | + | ||
| 310 | + | "Installation Information" for a User Product means any methods, | |
| 311 | + | procedures, authorization keys, or other information required to install | |
| 312 | + | and execute modified versions of a covered work in that User Product from | |
| 313 | + | a modified version of its Corresponding Source. The information must | |
| 314 | + | suffice to ensure that the continued functioning of the modified object | |
| 315 | + | code is in no case prevented or interfered with solely because | |
| 316 | + | modification has been made. | |
| 317 | + | ||
| 318 | + | If you convey an object code work under this section in, or with, or | |
| 319 | + | specifically for use in, a User Product, and the conveying occurs as | |
| 320 | + | part of a transaction in which the right of possession and use of the | |
| 321 | + | User Product is transferred to the recipient in perpetuity or for a | |
| 322 | + | fixed term (regardless of how the transaction is characterized), the | |
| 323 | + | Corresponding Source conveyed under this section must be accompanied | |
| 324 | + | by the Installation Information. But this requirement does not apply | |
| 325 | + | if neither you nor any third party retains the ability to install | |
| 326 | + | modified object code on the User Product (for example, the work has | |
| 327 | + | been installed in ROM). | |
| 328 | + | ||
| 329 | + | The requirement to provide Installation Information does not include a | |
| 330 | + | requirement to continue to provide support service, warranty, or updates | |
| 331 | + | for a work that has been modified or installed by the recipient, or for | |
| 332 | + | the User Product in which it has been modified or installed. Access to a | |
| 333 | + | network may be denied when the modification itself materially and | |
| 334 | + | adversely affects the operation of the network or violates the rules and | |
| 335 | + | protocols for communication across the network. | |
| 336 | + | ||
| 337 | + | Corresponding Source conveyed, and Installation Information provided, | |
| 338 | + | in accord with this section must be in a format that is publicly | |
| 339 | + | documented (and with an implementation available to the public in | |
| 340 | + | source code form), and must require no special password or key for | |
| 341 | + | unpacking, reading or copying. | |
| 342 | + | ||
| 343 | + | 7. Additional Terms. | |
| 344 | + | ||
| 345 | + | "Additional permissions" are terms that supplement the terms of this | |
| 346 | + | License by making exceptions from one or more of its conditions. | |
| 347 | + | Additional permissions that are applicable to the entire Program shall | |
| 348 | + | be treated as though they were included in this License, to the extent | |
| 349 | + | that they are valid under applicable law. If additional permissions | |
| 350 | + | apply only to part of the Program, that part may be used separately | |
| 351 | + | under those permissions, but the entire Program remains governed by | |
| 352 | + | this License without regard to the additional permissions. | |
| 353 | + | ||
| 354 | + | When you convey a copy of a covered work, you may at your option | |
| 355 | + | remove any additional permissions from that copy, or from any part of | |
| 356 | + | it. (Additional permissions may be written to require their own | |
| 357 | + | removal in certain cases when you modify the work.) You may place | |
| 358 | + | additional permissions on material, added by you to a covered work, | |
| 359 | + | for which you have or can give appropriate copyright permission. | |
| 360 | + | ||
| 361 | + | Notwithstanding any other provision of this License, for material you | |
| 362 | + | add to a covered work, you may (if authorized by the copyright holders of | |
| 363 | + | that material) supplement the terms of this License with terms: | |
| 364 | + | ||
| 365 | + | a) Disclaiming warranty or limiting liability differently from the | |
| 366 | + | terms of sections 15 and 16 of this License; or | |
| 367 | + | ||
| 368 | + | b) Requiring preservation of specified reasonable legal notices or | |
| 369 | + | author attributions in that material or in the Appropriate Legal | |
| 370 | + | Notices displayed by works containing it; or | |
| 371 | + | ||
| 372 | + | c) Prohibiting misrepresentation of the origin of that material, or | |
| 373 | + | requiring that modified versions of such material be marked in | |
| 374 | + | reasonable ways as different from the original version; or | |
| 375 | + | ||
| 376 | + | d) Limiting the use for publicity purposes of names of licensors or | |
| 377 | + | authors of the material; or | |
| 378 | + | ||
| 379 | + | e) Declining to grant rights under trademark law for use of some | |
| 380 | + | trade names, trademarks, or service marks; or | |
| 381 | + | ||
| 382 | + | f) Requiring indemnification of licensors and authors of that | |
| 383 | + | material by anyone who conveys the material (or modified versions of | |
| 384 | + | it) with contractual assumptions of liability to the recipient, for | |
| 385 | + | any liability that these contractual assumptions directly impose on | |
| 386 | + | those licensors and authors. | |
| 387 | + | ||
| 388 | + | All other non-permissive additional terms are considered "further | |
| 389 | + | restrictions" within the meaning of section 10. If the Program as you | |
| 390 | + | received it, or any part of it, contains a notice stating that it is | |
| 391 | + | governed by this License along with a term that is a further | |
| 392 | + | restriction, you may remove that term. If a license document contains | |
| 393 | + | a further restriction but permits relicensing or conveying under this | |
| 394 | + | License, you may add to a covered work material governed by the terms | |
| 395 | + | of that license document, provided that the further restriction does | |
| 396 | + | not survive such relicensing or conveying. | |
| 397 | + | ||
| 398 | + | If you add terms to a covered work in accord with this section, you | |
| 399 | + | must place, in the relevant source files, a statement of the | |
| 400 | + | additional terms that apply to those files, or a notice indicating | |
| 401 | + | where to find the applicable terms. | |
| 402 | + | ||
| 403 | + | Additional terms, permissive or non-permissive, may be stated in the | |
| 404 | + | form of a separately written license, or stated as exceptions; | |
| 405 | + | the above requirements apply either way. | |
| 406 | + | ||
| 407 | + | 8. Termination. | |
| 408 | + | ||
| 409 | + | You may not propagate or modify a covered work except as expressly | |
| 410 | + | provided under this License. Any attempt otherwise to propagate or | |
| 411 | + | modify it is void, and will automatically terminate your rights under | |
| 412 | + | this License (including any patent licenses granted under the third | |
| 413 | + | paragraph of section 11). | |
| 414 | + | ||
| 415 | + | However, if you cease all violation of this License, then your | |
| 416 | + | license from a particular copyright holder is reinstated (a) | |
| 417 | + | provisionally, unless and until the copyright holder explicitly and | |
| 418 | + | finally terminates your license, and (b) permanently, if the copyright | |
| 419 | + | holder fails to notify you of the violation by some reasonable means | |
| 420 | + | prior to 60 days after the cessation. | |
| 421 | + | ||
| 422 | + | Moreover, your license from a particular copyright holder is | |
| 423 | + | reinstated permanently if the copyright holder notifies you of the | |
| 424 | + | violation by some reasonable means, this is the first time you have | |
| 425 | + | received notice of violation of this License (for any work) from that | |
| 426 | + | copyright holder, and you cure the violation prior to 30 days after | |
| 427 | + | your receipt of the notice. | |
| 428 | + | ||
| 429 | + | Termination of your rights under this section does not terminate the | |
| 430 | + | licenses of parties who have received copies or rights from you under | |
| 431 | + | this License. If your rights have been terminated and not permanently | |
| 432 | + | reinstated, you do not qualify to receive new licenses for the same | |
| 433 | + | material under section 10. | |
| 434 | + | ||
| 435 | + | 9. Acceptance Not Required for Having Copies. | |
| 436 | + | ||
| 437 | + | You are not required to accept this License in order to receive or | |
| 438 | + | run a copy of the Program. Ancillary propagation of a covered work | |
| 439 | + | occurring solely as a consequence of using peer-to-peer transmission | |
| 440 | + | to receive a copy likewise does not require acceptance. However, | |
| 441 | + | nothing other than this License grants you permission to propagate or | |
| 442 | + | modify any covered work. These actions infringe copyright if you do | |
| 443 | + | not accept this License. Therefore, by modifying or propagating a | |
| 444 | + | covered work, you indicate your acceptance of this License to do so. | |
| 445 | + | ||
| 446 | + | 10. Automatic Licensing of Downstream Recipients. | |
| 447 | + | ||
| 448 | + | Each time you convey a covered work, the recipient automatically | |
| 449 | + | receives a license from the original licensors, to run, modify and | |
| 450 | + | propagate that work, subject to this License. You are not responsible | |
| 451 | + | for enforcing compliance by third parties with this License. | |
| 452 | + | ||
| 453 | + | An "entity transaction" is a transaction transferring control of an | |
| 454 | + | organization, or substantially all assets of one, or subdividing an | |
| 455 | + | organization, or merging organizations. If propagation of a covered | |
| 456 | + | work results from an entity transaction, each party to that | |
| 457 | + | transaction who receives a copy of the work also receives whatever | |
| 458 | + | licenses to the work the party's predecessor in interest had or could | |
| 459 | + | give under the previous paragraph, plus a right to possession of the | |
| 460 | + | Corresponding Source of the work from the predecessor in interest, if | |
| 461 | + | the predecessor has it or can get it with reasonable efforts. | |
| 462 | + | ||
| 463 | + | You may not impose any further restrictions on the exercise of the | |
| 464 | + | rights granted or affirmed under this License. For example, you may | |
| 465 | + | not impose a license fee, royalty, or other charge for exercise of | |
| 466 | + | rights granted under this License, and you may not initiate litigation | |
| 467 | + | (including a cross-claim or counterclaim in a lawsuit) alleging that | |
| 468 | + | any patent claim is infringed by making, using, selling, offering for | |
| 469 | + | sale, or importing the Program or any portion of it. | |
| 470 | + | ||
| 471 | + | 11. Patents. | |
| 472 | + | ||
| 473 | + | A "contributor" is a copyright holder who authorizes use under this | |
| 474 | + | License of the Program or a work on which the Program is based. The | |
| 475 | + | work thus licensed is called the contributor's "contributor version". | |
| 476 | + | ||
| 477 | + | A contributor's "essential patent claims" are all patent claims | |
| 478 | + | owned or controlled by the contributor, whether already acquired or | |
| 479 | + | hereafter acquired, that would be infringed by some manner, permitted | |
| 480 | + | by this License, of making, using, or selling its contributor version, | |
| 481 | + | but do not include claims that would be infringed only as a | |
| 482 | + | consequence of further modification of the contributor version. For | |
| 483 | + | purposes of this definition, "control" includes the right to grant | |
| 484 | + | patent sublicenses in a manner consistent with the requirements of | |
| 485 | + | this License. | |
| 486 | + | ||
| 487 | + | Each contributor grants you a non-exclusive, worldwide, royalty-free | |
| 488 | + | patent license under the contributor's essential patent claims, to | |
| 489 | + | make, use, sell, offer for sale, import and otherwise run, modify and | |
| 490 | + | propagate the contents of its contributor version. | |
| 491 | + | ||
| 492 | + | In the following three paragraphs, a "patent license" is any express | |
| 493 | + | agreement or commitment, however denominated, not to enforce a patent | |
| 494 | + | (such as an express permission to practice a patent or covenant not to | |
| 495 | + | sue for patent infringement). To "grant" such a patent license to a | |
| 496 | + | party means to make such an agreement or commitment not to enforce a | |
| 497 | + | patent against the party. | |
| 498 | + | ||
| 499 | + | If you convey a covered work, knowingly relying on a patent license, | |
| 500 | + | and the Corresponding Source of the work is not available for anyone | |
| 501 | + | to copy, free of charge and under the terms of this License, through a | |
| 502 | + | publicly available network server or other readily accessible means, | |
| 503 | + | then you must either (1) cause the Corresponding Source to be so | |
| 504 | + | available, or (2) arrange to deprive yourself of the benefit of the | |
| 505 | + | patent license for this particular work, or (3) arrange, in a manner | |
| 506 | + | consistent with the requirements of this License, to extend the patent | |
| 507 | + | license to downstream recipients. "Knowingly relying" means you have | |
| 508 | + | actual knowledge that, but for the patent license, your conveying the | |
| 509 | + | covered work in a country, or your recipient's use of the covered work | |
| 510 | + | in a country, would infringe one or more identifiable patents in that | |
| 511 | + | country that you have reason to believe are valid. | |
| 512 | + | ||
| 513 | + | If, pursuant to or in connection with a single transaction or | |
| 514 | + | arrangement, you convey, or propagate by procuring conveyance of, a | |
| 515 | + | covered work, and grant a patent license to some of the parties | |
| 516 | + | receiving the covered work authorizing them to use, propagate, modify | |
| 517 | + | or convey a specific copy of the covered work, then the patent license | |
| 518 | + | you grant is automatically extended to all recipients of the covered | |
| 519 | + | work and works based on it. | |
| 520 | + | ||
| 521 | + | A patent license is "discriminatory" if it does not include within | |
| 522 | + | the scope of its coverage, prohibits the exercise of, or is | |
| 523 | + | conditioned on the non-exercise of one or more of the rights that are | |
| 524 | + | specifically granted under this License. You may not convey a covered | |
| 525 | + | work if you are a party to an arrangement with a third party that is | |
| 526 | + | in the business of distributing software, under which you make payment | |
| 527 | + | to the third party based on the extent of your activity of conveying | |
| 528 | + | the work, and under which the third party grants, to any of the | |
| 529 | + | parties who would receive the covered work from you, a discriminatory | |
| 530 | + | patent license (a) in connection with copies of the covered work | |
| 531 | + | conveyed by you (or copies made from those copies), or (b) primarily | |
| 532 | + | for and in connection with specific products or compilations that | |
| 533 | + | contain the covered work, unless you entered into that arrangement, | |
| 534 | + | or that patent license was granted, prior to 28 March 2007. | |
| 535 | + | ||
| 536 | + | Nothing in this License shall be construed as excluding or limiting | |
| 537 | + | any implied license or other defenses to infringement that may | |
| 538 | + | otherwise be available to you under applicable patent law. | |
| 539 | + | ||
| 540 | + | 12. No Surrender of Others' Freedom. | |
| 541 | + | ||
| 542 | + | If conditions are imposed on you (whether by court order, agreement or | |
| 543 | + | otherwise) that contradict the conditions of this License, they do not | |
| 544 | + | excuse you from the conditions of this License. If you cannot convey a | |
| 545 | + | covered work so as to satisfy simultaneously your obligations under this | |
| 546 | + | License and any other pertinent obligations, then as a consequence you may | |
| 547 | + | not convey it at all. For example, if you agree to terms that obligate you | |
| 548 | + | to collect a royalty for further conveying from those to whom you convey | |
| 549 | + | the Program, the only way you could satisfy both those terms and this | |
| 550 | + | License would be to refrain entirely from conveying the Program. | |
| 551 | + | ||
| 552 | + | 13. Use with the GNU Affero General Public License. | |
| 553 | + | ||
| 554 | + | Notwithstanding any other provision of this License, you have | |
| 555 | + | permission to link or combine any covered work with a work licensed | |
| 556 | + | under version 3 of the GNU Affero General Public License into a single | |
| 557 | + | combined work, and to convey the resulting work. The terms of this | |
| 558 | + | License will continue to apply to the part which is the covered work, | |
| 559 | + | but the special requirements of the GNU Affero General Public License, | |
| 560 | + | section 13, concerning interaction through a network will apply to the | |
| 561 | + | combination as such. | |
| 562 | + | ||
| 563 | + | 14. Revised Versions of this License. | |
| 564 | + | ||
| 565 | + | The Free Software Foundation may publish revised and/or new versions of | |
| 566 | + | the GNU General Public License from time to time. Such new versions will | |
| 567 | + | be similar in spirit to the present version, but may differ in detail to | |
| 568 | + | address new problems or concerns. | |
| 569 | + | ||
| 570 | + | Each version is given a distinguishing version number. If the | |
| 571 | + | Program specifies that a certain numbered version of the GNU General | |
| 572 | + | Public License "or any later version" applies to it, you have the | |
| 573 | + | option of following the terms and conditions either of that numbered | |
| 574 | + | version or of any later version published by the Free Software | |
| 575 | + | Foundation. If the Program does not specify a version number of the | |
| 576 | + | GNU General Public License, you may choose any version ever published | |
| 577 | + | by the Free Software Foundation. | |
| 578 | + | ||
| 579 | + | If the Program specifies that a proxy can decide which future | |
| 580 | + | versions of the GNU General Public License can be used, that proxy's | |
| 581 | + | public statement of acceptance of a version permanently authorizes you | |
| 582 | + | to choose that version for the Program. | |
| 583 | + | ||
| 584 | + | Later license versions may give you additional or different | |
| 585 | + | permissions. However, no additional obligations are imposed on any | |
| 586 | + | author or copyright holder as a result of your choosing to follow a | |
| 587 | + | later version. | |
| 588 | + | ||
| 589 | + | 15. Disclaimer of Warranty. | |
| 590 | + | ||
| 591 | + | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY | |
| 592 | + | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT | |
| 593 | + | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY | |
| 594 | + | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, | |
| 595 | + | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | |
| 596 | + | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM | |
| 597 | + | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF | |
| 598 | + | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. | |
| 599 | + | ||
| 600 | + | 16. Limitation of Liability. | |
| 601 | + | ||
| 602 | + | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING | |
| 603 | + | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS | |
| 604 | + | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY | |
| 605 | + | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE | |
| 606 | + | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF | |
| 607 | + | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD | |
| 608 | + | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), | |
| 609 | + | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF | |
| 610 | + | SUCH DAMAGES. | |
| 611 | + | ||
| 612 | + | 17. Interpretation of Sections 15 and 16. | |
| 613 | + | ||
| 614 | + | If the disclaimer of warranty and limitation of liability provided | |
| 615 | + | above cannot be given local legal effect according to their terms, | |
| 616 | + | reviewing courts shall apply local law that most closely approximates | |
| 617 | + | an absolute waiver of all civil liability in connection with the | |
| 618 | + | Program, unless a warranty or assumption of liability accompanies a | |
| 619 | + | copy of the Program in return for a fee. | |
| 620 | + | ||
| 621 | + | END OF TERMS AND CONDITIONS | |
| 622 | + | ||
| 623 | + | How to Apply These Terms to Your New Programs | |
| 624 | + | ||
| 625 | + | If you develop a new program, and you want it to be of the greatest | |
| 626 | + | possible use to the public, the best way to achieve this is to make it | |
| 627 | + | free software which everyone can redistribute and change under these terms. | |
| 628 | + | ||
| 629 | + | To do so, attach the following notices to the program. It is safest | |
| 630 | + | to attach them to the start of each source file to most effectively | |
| 631 | + | state the exclusion of warranty; and each file should have at least | |
| 632 | + | the "copyright" line and a pointer to where the full notice is found. | |
| 633 | + | ||
| 634 | + | <one line to give the program's name and a brief idea of what it does.> | |
| 635 | + | Copyright (C) <year> <name of author> | |
| 636 | + | ||
| 637 | + | This program is free software: you can redistribute it and/or modify | |
| 638 | + | it under the terms of the GNU General Public License as published by | |
| 639 | + | the Free Software Foundation, either version 3 of the License, or | |
| 640 | + | (at your option) any later version. | |
| 641 | + | ||
| 642 | + | This program is distributed in the hope that it will be useful, | |
| 643 | + | but WITHOUT ANY WARRANTY; without even the implied warranty of | |
| 644 | + | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
| 645 | + | GNU General Public License for more details. | |
| 646 | + | ||
| 647 | + | You should have received a copy of the GNU General Public License | |
| 648 | + | along with this program. If not, see <https://www.gnu.org/licenses/>. | |
| 649 | + | ||
| 650 | + | Also add information on how to contact you by electronic and paper mail. | |
| 651 | + | ||
| 652 | + | If the program does terminal interaction, make it output a short | |
| 653 | + | notice like this when it starts in an interactive mode: | |
| 654 | + | ||
| 655 | + | <program> Copyright (C) <year> <name of author> | |
| 656 | + | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. | |
| 657 | + | This is free software, and you are welcome to redistribute it | |
| 658 | + | under certain conditions; type `show c' for details. | |
| 659 | + | ||
| 660 | + | The hypothetical commands `show w' and `show c' should show the appropriate | |
| 661 | + | parts of the General Public License. Of course, your program's commands | |
| 662 | + | might be different; for a GUI interface, you would use an "about box". | |
| 663 | + | ||
| 664 | + | You should also get your employer (if you work as a programmer) or school, | |
| 665 | + | if any, to sign a "copyright disclaimer" for the program, if necessary. | |
| 666 | + | For more information on this, and how to apply and follow the GNU GPL, see | |
| 667 | + | <https://www.gnu.org/licenses/>. | |
| 668 | + | ||
| 669 | + | The GNU General Public License does not permit incorporating your program | |
| 670 | + | into proprietary programs. If your program is a subroutine library, you | |
| 671 | + | may consider it more useful to permit linking proprietary applications with | |
| 672 | + | the library. If this is what you want to do, use the GNU Lesser General | |
| 673 | + | Public License instead of this License. But first, please read | |
| 674 | + | <https://www.gnu.org/licenses/why-not-lgpl.html>. | |
| @@ -0,0 +1,17 @@ | |||
| 1 | + | # Tests may unwrap and index; production code may not (see [workspace.lints] in Cargo.toml). | |
| 2 | + | allow-unwrap-in-tests = true | |
| 3 | + | allow-expect-in-tests = true | |
| 4 | + | allow-panic-in-tests = true | |
| 5 | + | allow-indexing-slicing-in-tests = true | |
| 6 | + | ||
| 7 | + | # CLAUDE.md hard rule 1: no network sockets, ever. | |
| 8 | + | disallowed-types = [ | |
| 9 | + | { path = "std::net::TcpStream", reason = "budctl never opens network sockets (CLAUDE.md rule 1)" }, | |
| 10 | + | { path = "std::net::TcpListener", reason = "budctl never opens network sockets (CLAUDE.md rule 1)" }, | |
| 11 | + | { path = "std::net::UdpSocket", reason = "budctl never opens network sockets (CLAUDE.md rule 1)" }, | |
| 12 | + | ] | |
| 13 | + | ||
| 14 | + | disallowed-methods = [ | |
| 15 | + | { path = "std::thread::sleep", reason = "wait with Link::pump_until, so the buds' requests are still answered" }, | |
| 16 | + | { path = "std::process::exit", reason = "return an error and let main turn it into an exit code" }, | |
| 17 | + | ] | |
| @@ -0,0 +1,20 @@ | |||
| 1 | + | [package] | |
| 2 | + | name = "budctl" | |
| 3 | + | description = "Control wireless earbuds from Linux, without the vendor app" | |
| 4 | + | version.workspace = true | |
| 5 | + | edition.workspace = true | |
| 6 | + | rust-version.workspace = true | |
| 7 | + | license.workspace = true | |
| 8 | + | publish.workspace = true | |
| 9 | + | ||
| 10 | + | [[bin]] | |
| 11 | + | name = "budctl" | |
| 12 | + | path = "src/main.rs" | |
| 13 | + | ||
| 14 | + | [dependencies] | |
| 15 | + | budctl-core = { path = "../budctl-core" } | |
| 16 | + | clap = { version = "4.6.7", features = ["derive"] } | |
| 17 | + | serde_json = "1.0.154" | |
| 18 | + | ||
| 19 | + | [lints] | |
| 20 | + | workspace = true | |
| @@ -0,0 +1,106 @@ | |||
| 1 | + | //! `budctl`: control wireless earbuds from Linux. | |
| 2 | + | //! | |
| 3 | + | //! A thin layer over budctl-core: parse the command line, run one command, print the result, | |
| 4 | + | //! turn errors into the exit codes listed in CLAUDE.md. | |
| 5 | + | ||
| 6 | + | mod output; | |
| 7 | + | ||
| 8 | + | use std::io::{self, Write}; | |
| 9 | + | use std::process::ExitCode; | |
| 10 | + | ||
| 11 | + | use budctl_core::bt::BdAddr; | |
| 12 | + | use budctl_core::{Error, Kind}; | |
| 13 | + | use clap::{Parser, Subcommand}; | |
| 14 | + | ||
| 15 | + | /// Control wireless earbuds from Linux, without the vendor app. | |
| 16 | + | #[derive(Parser)] | |
| 17 | + | #[command(name = "budctl", version)] | |
| 18 | + | struct Cli { | |
| 19 | + | /// The buds to use, when more than one supported pair is paired. | |
| 20 | + | #[arg(long, global = true, value_name = "MAC")] | |
| 21 | + | device: Option<BdAddr>, | |
| 22 | + | ||
| 23 | + | /// Machine-readable output (JSON with "schema": 1). | |
| 24 | + | #[arg(long, global = true)] | |
| 25 | + | json: bool, | |
| 26 | + | ||
| 27 | + | /// Hex-dump every frame sent and received on stderr. | |
| 28 | + | #[arg(long, global = true)] | |
| 29 | + | debug: bool, | |
| 30 | + | ||
| 31 | + | #[command(subcommand)] | |
| 32 | + | command: Command, | |
| 33 | + | } | |
| 34 | + | ||
| 35 | + | #[derive(Subcommand)] | |
| 36 | + | enum Command { | |
| 37 | + | /// Paired devices and whether budctl recognizes them. | |
| 38 | + | List, | |
| 39 | + | /// Battery, noise control, EQ and switches. | |
| 40 | + | Status, | |
| 41 | + | /// Touch controls (gesture table) of each bud. | |
| 42 | + | Touch, | |
| 43 | + | } | |
| 44 | + | ||
| 45 | + | fn main() -> ExitCode { | |
| 46 | + | let cli = match Cli::try_parse() { | |
| 47 | + | Ok(cli) => cli, | |
| 48 | + | Err(error) => { | |
| 49 | + | // Help and version are not errors; everything else is a usage error (exit 1). | |
| 50 | + | let code = if error.use_stderr() { 1 } else { 0 }; | |
| 51 | + | // Nothing useful can be done if printing the usage message fails. | |
| 52 | + | let _ = error.print(); | |
| 53 | + | return ExitCode::from(code); | |
| 54 | + | } | |
| 55 | + | }; | |
| 56 | + | if cli.debug { | |
| 57 | + | budctl_core::debug::enable(); | |
| 58 | + | } | |
| 59 | + | ||
| 60 | + | let mut stdout = io::stdout().lock(); | |
| 61 | + | let result = run(&cli, &mut stdout).and_then(|()| stdout.flush().map_err(output::Failure::Io)); | |
| 62 | + | match result { | |
| 63 | + | Ok(()) => ExitCode::SUCCESS, | |
| 64 | + | // `budctl status | head -1` is fine. | |
| 65 | + | Err(output::Failure::Io(e)) if e.kind() == io::ErrorKind::BrokenPipe => ExitCode::SUCCESS, | |
| 66 | + | Err(output::Failure::Io(e)) => { | |
| 67 | + | eprintln!("budctl: cannot write output: {e}"); | |
| 68 | + | ExitCode::from(1) | |
| 69 | + | } | |
| 70 | + | Err(output::Failure::Budctl(e)) => { | |
| 71 | + | eprintln!("budctl: {e}"); | |
| 72 | + | ExitCode::from(exit_code(&e)) | |
| 73 | + | } | |
| 74 | + | } | |
| 75 | + | } | |
| 76 | + | ||
| 77 | + | fn run(cli: &Cli, out: &mut impl Write) -> Result<(), output::Failure> { | |
| 78 | + | let found = budctl_core::scan()?; | |
| 79 | + | if let Command::List = cli.command { | |
| 80 | + | return output::list(out, &found, cli.json); | |
| 81 | + | } | |
| 82 | + | ||
| 83 | + | let (device, model) = budctl_core::select(found, cli.device)?; | |
| 84 | + | let mut session = budctl_core::connect(&device, model)?; | |
| 85 | + | match cli.command { | |
| 86 | + | Command::List => Ok(()), | |
| 87 | + | Command::Status => { | |
| 88 | + | let status = session.status()?; | |
| 89 | + | output::status(out, &device, model, &status, cli.json) | |
| 90 | + | } | |
| 91 | + | Command::Touch => { | |
| 92 | + | let touch = session.touch_controls()?; | |
| 93 | + | output::touch(out, &device, model, &touch, cli.json) | |
| 94 | + | } | |
| 95 | + | } | |
| 96 | + | } | |
| 97 | + | ||
| 98 | + | /// Exit codes from CLAUDE.md: 1 usage, 2 not found, 3 busy, 4 rejected or timed out. | |
| 99 | + | fn exit_code(error: &Error) -> u8 { | |
| 100 | + | match error.kind() { | |
| 101 | + | Kind::Usage => 1, | |
| 102 | + | Kind::NotFound => 2, | |
| 103 | + | Kind::Busy => 3, | |
| 104 | + | Kind::Failed => 4, | |
| 105 | + | } | |
| 106 | + | } | |
| @@ -0,0 +1,187 @@ | |||
| 1 | + | //! Printing results, as text for people or as JSON (`--json`) for scripts and status bars. | |
| 2 | + | ||
| 3 | + | use std::io::{self, Write}; | |
| 4 | + | ||
| 5 | + | use budctl_core::bluez::PairedDevice; | |
| 6 | + | use budctl_core::devices::Device; | |
| 7 | + | use budctl_core::status::{Charge, JSON_SCHEMA, Status, TouchControls}; | |
| 8 | + | use budctl_core::{Error, Found}; | |
| 9 | + | use serde_json::Value; | |
| 10 | + | ||
| 11 | + | /// Why a command did not finish: budctl failed, or stdout did. | |
| 12 | + | pub enum Failure { | |
| 13 | + | Budctl(Error), | |
| 14 | + | Io(io::Error), | |
| 15 | + | } | |
| 16 | + | ||
| 17 | + | impl From<Error> for Failure { | |
| 18 | + | fn from(error: Error) -> Self { | |
| 19 | + | Failure::Budctl(error) | |
| 20 | + | } | |
| 21 | + | } | |
| 22 | + | ||
| 23 | + | impl From<io::Error> for Failure { | |
| 24 | + | fn from(error: io::Error) -> Self { | |
| 25 | + | Failure::Io(error) | |
| 26 | + | } | |
| 27 | + | } | |
| 28 | + | ||
| 29 | + | impl From<serde_json::Error> for Failure { | |
| 30 | + | fn from(error: serde_json::Error) -> Self { | |
| 31 | + | Failure::Io(io::Error::from(error)) | |
| 32 | + | } | |
| 33 | + | } | |
| 34 | + | ||
| 35 | + | /// Print `body` inside the JSON envelope every result shares: `schema`, plus `device` and | |
| 36 | + | /// `address` when the result is about one pair of buds. | |
| 37 | + | fn json(out: &mut impl Write, target: Option<(&PairedDevice, &dyn Device)>, body: Value) -> Result<(), Failure> { | |
| 38 | + | let mut envelope = serde_json::Map::new(); | |
| 39 | + | envelope.insert("schema".to_owned(), JSON_SCHEMA.into()); | |
| 40 | + | if let Some((device, model)) = target { | |
| 41 | + | envelope.insert("device".to_owned(), model.name().into()); | |
| 42 | + | envelope.insert("address".to_owned(), device.address.to_string().into()); | |
| 43 | + | } | |
| 44 | + | if let Value::Object(fields) = body { | |
| 45 | + | envelope.extend(fields); | |
| 46 | + | } | |
| 47 | + | serde_json::to_writer(&mut *out, &envelope)?; | |
| 48 | + | writeln!(out)?; | |
| 49 | + | Ok(()) | |
| 50 | + | } | |
| 51 | + | ||
| 52 | + | pub fn list(out: &mut impl Write, found: &[Found], as_json: bool) -> Result<(), Failure> { | |
| 53 | + | if as_json { | |
| 54 | + | let devices: Vec<Value> = found | |
| 55 | + | .iter() | |
| 56 | + | .map(|f| { | |
| 57 | + | serde_json::json!({ | |
| 58 | + | "address": f.device.address, | |
| 59 | + | "name": f.device.name, | |
| 60 | + | "alias": f.device.alias, | |
| 61 | + | "connected": f.device.connected, | |
| 62 | + | // The model budctl recognized, or null. | |
| 63 | + | "model": f.model.map(|m| m.name()), | |
| 64 | + | }) | |
| 65 | + | }) | |
| 66 | + | .collect(); | |
| 67 | + | return json(out, None, serde_json::json!({ "devices": devices })); | |
| 68 | + | } | |
| 69 | + | ||
| 70 | + | if found.is_empty() { | |
| 71 | + | writeln!(out, "No paired Bluetooth devices.")?; | |
| 72 | + | return Ok(()); | |
| 73 | + | } | |
| 74 | + | for f in found { | |
| 75 | + | let state = if f.device.connected { | |
| 76 | + | "connected" | |
| 77 | + | } else { | |
| 78 | + | "not connected" | |
| 79 | + | }; | |
| 80 | + | let model = match f.model { | |
| 81 | + | Some(model) => format!("supported: {}", model.name()), | |
| 82 | + | None => "not supported".to_owned(), | |
| 83 | + | }; | |
| 84 | + | writeln!(out, "{} {} ({state}, {model})", f.device.address, f.device.alias)?; | |
| 85 | + | } | |
| 86 | + | Ok(()) | |
| 87 | + | } | |
| 88 | + | ||
| 89 | + | fn charge(charge: Option<Charge>) -> String { | |
| 90 | + | match charge { | |
| 91 | + | Some(Charge { level, charging: true }) => format!("{level}% (charging)"), | |
| 92 | + | Some(Charge { level, charging: false }) => format!("{level}%"), | |
| 93 | + | None => "—".to_owned(), | |
| 94 | + | } | |
| 95 | + | } | |
| 96 | + | ||
| 97 | + | fn header(out: &mut impl Write, device: &PairedDevice, model: &dyn Device) -> io::Result<()> { | |
| 98 | + | writeln!(out, "{} ({})", model.name(), device.address) | |
| 99 | + | } | |
| 100 | + | ||
| 101 | + | fn warnings(out: &mut impl Write, warnings: &[String]) -> io::Result<()> { | |
| 102 | + | for warning in warnings { | |
| 103 | + | writeln!(out, " warning: {warning}")?; | |
| 104 | + | } | |
| 105 | + | Ok(()) | |
| 106 | + | } | |
| 107 | + | ||
| 108 | + | pub fn status( | |
| 109 | + | out: &mut impl Write, | |
| 110 | + | device: &PairedDevice, | |
| 111 | + | model: &dyn Device, | |
| 112 | + | status: &Status, | |
| 113 | + | as_json: bool, | |
| 114 | + | ) -> Result<(), Failure> { | |
| 115 | + | if as_json { | |
| 116 | + | return json(out, Some((device, model)), serde_json::to_value(status)?); | |
| 117 | + | } | |
| 118 | + | ||
| 119 | + | header(out, device, model)?; | |
| 120 | + | let battery = &status.battery; | |
| 121 | + | let mut rows: Vec<(&str, String)> = vec![( | |
| 122 | + | "Battery", | |
| 123 | + | format!( | |
| 124 | + | "L {} R {} case {}", | |
| 125 | + | charge(battery.left), | |
| 126 | + | charge(battery.right), | |
| 127 | + | charge(battery.case) | |
| 128 | + | ), | |
| 129 | + | )]; | |
| 130 | + | if let Some(noise) = &status.noise_control { | |
| 131 | + | let value = match &noise.level { | |
| 132 | + | Some(level) => format!("{} ({level})", noise.mode), | |
| 133 | + | None => noise.mode.clone(), | |
| 134 | + | }; | |
| 135 | + | rows.push(("Noise control", value)); | |
| 136 | + | } | |
| 137 | + | if let Some(eq) = &status.eq { | |
| 138 | + | rows.push(("EQ", eq.clone())); | |
| 139 | + | } | |
| 140 | + | if let Some(bass) = status.bass_level { | |
| 141 | + | rows.push(("Bass level", bass.to_string())); | |
| 142 | + | } | |
| 143 | + | for switch in &status.switches { | |
| 144 | + | rows.push((switch.label, if switch.on { "on" } else { "off" }.to_owned())); | |
| 145 | + | } | |
| 146 | + | if let Some(codec) = &status.codec { | |
| 147 | + | rows.push(("Codec", codec.clone())); | |
| 148 | + | } | |
| 149 | + | if let Some(firmware) = &status.firmware { | |
| 150 | + | rows.push(("Firmware", firmware.clone())); | |
| 151 | + | } | |
| 152 | + | // Labels are as wide as the longest one, so values line up whatever the device names. | |
| 153 | + | let width = rows.iter().map(|(label, _)| label.chars().count()).max().unwrap_or(0); | |
| 154 | + | for (label, value) in &rows { | |
| 155 | + | writeln!(out, " {label:<width$} {value}")?; | |
| 156 | + | } | |
| 157 | + | warnings(out, &status.warnings)?; | |
| 158 | + | Ok(()) | |
| 159 | + | } | |
| 160 | + | ||
| 161 | + | pub fn touch( | |
| 162 | + | out: &mut impl Write, | |
| 163 | + | device: &PairedDevice, | |
| 164 | + | model: &dyn Device, | |
| 165 | + | touch: &TouchControls, | |
| 166 | + | as_json: bool, | |
| 167 | + | ) -> Result<(), Failure> { | |
| 168 | + | if as_json { | |
| 169 | + | return json(out, Some((device, model)), serde_json::to_value(touch)?); | |
| 170 | + | } | |
| 171 | + | ||
| 172 | + | header(out, device, model)?; | |
| 173 | + | if touch.gestures.is_empty() { | |
| 174 | + | writeln!(out, " (no gestures reported)")?; | |
| 175 | + | } | |
| 176 | + | for g in &touch.gestures { | |
| 177 | + | match g.group { | |
| 178 | + | Some(group) => writeln!(out, " {:<6} {:<12} {} [group {group}]", g.side, g.gesture, g.action)?, | |
| 179 | + | None => writeln!(out, " {:<6} {:<12} {}", g.side, g.gesture, g.action)?, | |
| 180 | + | } | |
| 181 | + | } | |
| 182 | + | if let Some(cycle) = &touch.hold_cycle { | |
| 183 | + | writeln!(out, " Hold cycles through: {}", cycle.join(" → "))?; | |
| 184 | + | } | |
| 185 | + | warnings(out, &touch.warnings)?; | |
| 186 | + | Ok(()) | |
| 187 | + | } | |
| @@ -0,0 +1,27 @@ | |||
| 1 | + | //! Exit codes that need no Bluetooth (CLAUDE.md, "Exit codes"). | |
| 2 | + | ||
| 3 | + | // Test-only file: helpers may panic (clippy.toml exempts only #[test] functions themselves). | |
| 4 | + | #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)] | |
| 5 | + | ||
| 6 | + | use std::process::Command; | |
| 7 | + | ||
| 8 | + | fn budctl(args: &[&str]) -> std::process::Output { | |
| 9 | + | Command::new(env!("CARGO_BIN_EXE_budctl")).args(args).output().unwrap() | |
| 10 | + | } | |
| 11 | + | ||
| 12 | + | #[test] | |
| 13 | + | fn help_and_version_exit_0() { | |
| 14 | + | for flag in ["--help", "--version"] { | |
| 15 | + | let out = budctl(&[flag]); | |
| 16 | + | assert_eq!(out.status.code(), Some(0), "{flag}"); | |
| 17 | + | assert!(!out.stdout.is_empty(), "{flag}"); | |
| 18 | + | } | |
| 19 | + | } | |
| 20 | + | ||
| 21 | + | #[test] | |
| 22 | + | fn usage_errors_exit_1() { | |
| 23 | + | for args in [&["frobnicate"][..], &[], &["--device", "not-a-mac", "status"]] { | |
| 24 | + | let out = budctl(args); | |
| 25 | + | assert_eq!(out.status.code(), Some(1), "{args:?}"); | |
| 26 | + | } | |
| 27 | + | } | |
| @@ -0,0 +1,16 @@ | |||
| 1 | + | [package] | |
| 2 | + | name = "budctl-core" | |
| 3 | + | description = "Device plugins, Bluetooth transport and protocol for budctl" | |
| 4 | + | version.workspace = true | |
| 5 | + | edition.workspace = true | |
| 6 | + | rust-version.workspace = true | |
| 7 | + | license.workspace = true | |
| 8 | + | publish.workspace = true | |
| 9 | + | ||
| 10 | + | [dependencies] | |
| 11 | + | libc = "0.2.191" | |
| 12 | + | serde = { version = "1.0.229", features = ["derive"] } | |
| 13 | + | zbus = { version = "5.19.0", default-features = false, features = ["blocking-api", "async-io"] } | |
| 14 | + | ||
| 15 | + | [lints] | |
| 16 | + | workspace = true | |
| @@ -0,0 +1,159 @@ | |||
| 1 | + | //! Paired devices, from BlueZ over the system D-Bus. | |
| 2 | + | //! | |
| 3 | + | //! The only use of D-Bus in budctl is listing paired devices (CLAUDE.md, hard rule 1). budctl | |
| 4 | + | //! connects to the system bus socket at its fixed path itself, so no environment variable can | |
| 5 | + | //! point the connection anywhere else (such as a TCP address). | |
| 6 | + | ||
| 7 | + | use std::collections::HashMap; | |
| 8 | + | use std::os::unix::net::UnixStream; | |
| 9 | + | ||
| 10 | + | use zbus::blocking::connection::Builder; | |
| 11 | + | use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value}; | |
| 12 | + | ||
| 13 | + | use crate::bt::BdAddr; | |
| 14 | + | use crate::error::{Error, Result}; | |
| 15 | + | ||
| 16 | + | /// The system bus. `DBUS_SYSTEM_BUS_ADDRESS` is deliberately ignored. | |
| 17 | + | const SYSTEM_BUS_SOCKET: &str = "/var/run/dbus/system_bus_socket"; | |
| 18 | + | ||
| 19 | + | /// A device BlueZ has paired, as BlueZ describes it. | |
| 20 | + | #[derive(Debug, Clone)] | |
| 21 | + | pub struct PairedDevice { | |
| 22 | + | pub address: BdAddr, | |
| 23 | + | /// The name the device advertises. Device modules recognize models by this. | |
| 24 | + | pub name: String, | |
| 25 | + | /// The name the user gave it (BlueZ falls back to `name`). Shown to people. | |
| 26 | + | pub alias: String, | |
| 27 | + | pub connected: bool, | |
| 28 | + | /// Service UUIDs BlueZ found, lowercase and hyphenated. | |
| 29 | + | pub uuids: Vec<String>, | |
| 30 | + | } | |
| 31 | + | ||
| 32 | + | type Properties = HashMap<String, OwnedValue>; | |
| 33 | + | type ManagedObjects = HashMap<OwnedObjectPath, HashMap<String, Properties>>; | |
| 34 | + | ||
| 35 | + | fn bluez_error(error: impl std::fmt::Display) -> Error { | |
| 36 | + | Error::Bluez(error.to_string()) | |
| 37 | + | } | |
| 38 | + | ||
| 39 | + | /// Every paired device BlueZ knows, sorted by address. | |
| 40 | + | pub fn paired_devices() -> Result<Vec<PairedDevice>> { | |
| 41 | + | let stream = | |
| 42 | + | UnixStream::connect(SYSTEM_BUS_SOCKET).map_err(|e| Error::Bluez(format!("{SYSTEM_BUS_SOCKET}: {e}")))?; | |
| 43 | + | let connection = Builder::async_io_unix_stream(stream).build().map_err(bluez_error)?; | |
| 44 | + | let reply = connection | |
| 45 | + | .call_method( | |
| 46 | + | Some("org.bluez"), | |
| 47 | + | "/", | |
| 48 | + | Some("org.freedesktop.DBus.ObjectManager"), | |
| 49 | + | "GetManagedObjects", | |
| 50 | + | &(), | |
| 51 | + | ) | |
| 52 | + | .map_err(bluez_error)?; | |
| 53 | + | let objects: ManagedObjects = reply.body().deserialize().map_err(bluez_error)?; | |
| 54 | + | ||
| 55 | + | let mut devices: Vec<PairedDevice> = objects | |
| 56 | + | .values() | |
| 57 | + | .filter_map(|interfaces| interfaces.get("org.bluez.Device1")) | |
| 58 | + | .filter_map(device) | |
| 59 | + | .collect(); | |
| 60 | + | devices.sort_by_key(|d| d.address); | |
| 61 | + | Ok(devices) | |
| 62 | + | } | |
| 63 | + | ||
| 64 | + | /// A paired device from its `org.bluez.Device1` properties; `None` if it is not paired or has | |
| 65 | + | /// no usable address. | |
| 66 | + | fn device(properties: &Properties) -> Option<PairedDevice> { | |
| 67 | + | if !flag(properties, "Paired") { | |
| 68 | + | return None; | |
| 69 | + | } | |
| 70 | + | let address = text(properties, "Address")?.parse().ok()?; | |
| 71 | + | let name = text(properties, "Name").unwrap_or_default(); | |
| 72 | + | let alias = text(properties, "Alias").unwrap_or_else(|| name.clone()); | |
| 73 | + | let uuids = properties | |
| 74 | + | .get("UUIDs") | |
| 75 | + | .and_then(|v| match &**v { | |
| 76 | + | Value::Array(array) => Some( | |
| 77 | + | array | |
| 78 | + | .iter() | |
| 79 | + | .filter_map(|item| match item { | |
| 80 | + | Value::Str(s) => Some(s.as_str().to_ascii_lowercase()), | |
| 81 | + | _ => None, | |
| 82 | + | }) | |
| 83 | + | .collect(), | |
| 84 | + | ), | |
| 85 | + | _ => None, | |
| 86 | + | }) | |
| 87 | + | .unwrap_or_default(); | |
| 88 | + | Some(PairedDevice { | |
| 89 | + | address, | |
| 90 | + | name, | |
| 91 | + | alias, | |
| 92 | + | connected: flag(properties, "Connected"), | |
| 93 | + | uuids, | |
| 94 | + | }) | |
| 95 | + | } | |
| 96 | + | ||
| 97 | + | fn text(properties: &Properties, key: &str) -> Option<String> { | |
| 98 | + | match &**properties.get(key)? { | |
| 99 | + | Value::Str(s) => Some(s.as_str().to_owned()), | |
| 100 | + | _ => None, | |
| 101 | + | } | |
| 102 | + | } | |
| 103 | + | ||
| 104 | + | fn flag(properties: &Properties, key: &str) -> bool { | |
| 105 | + | matches!(properties.get(key).map(|v| &**v), Some(Value::Bool(true))) | |
| 106 | + | } | |
| 107 | + | ||
| 108 | + | #[cfg(test)] | |
| 109 | + | mod tests { | |
| 110 | + | use super::*; | |
| 111 | + | ||
| 112 | + | fn properties(entries: Vec<(&str, Value<'static>)>) -> Properties { | |
| 113 | + | entries | |
| 114 | + | .into_iter() | |
| 115 | + | .map(|(k, v)| (k.to_owned(), OwnedValue::try_from(v).unwrap())) | |
| 116 | + | .collect() | |
| 117 | + | } | |
| 118 | + | ||
| 119 | + | #[test] | |
| 120 | + | fn paired_device_from_properties() { | |
| 121 | + | let props = properties(vec![ | |
| 122 | + | ("Address", Value::from("AA:BB:CC:DD:EE:FF")), | |
| 123 | + | ("Name", Value::from("realme Buds T310")), | |
| 124 | + | ("Alias", Value::from("my buds")), | |
| 125 | + | ("Paired", Value::from(true)), | |
| 126 | + | ("Connected", Value::from(true)), | |
| 127 | + | ("UUIDs", Value::from(vec!["0000110B-0000-1000-8000-00805F9B34FB"])), | |
| 128 | + | ]); | |
| 129 | + | let device = device(&props).unwrap(); | |
| 130 | + | assert_eq!(device.address.to_string(), "AA:BB:CC:DD:EE:FF"); | |
| 131 | + | assert_eq!(device.name, "realme Buds T310"); | |
| 132 | + | assert_eq!(device.alias, "my buds"); | |
| 133 | + | assert!(device.connected); | |
| 134 | + | assert_eq!(device.uuids, ["0000110b-0000-1000-8000-00805f9b34fb"]); | |
| 135 | + | } | |
| 136 | + | ||
| 137 | + | #[test] | |
| 138 | + | fn unpaired_or_unaddressed_devices_are_skipped() { | |
| 139 | + | let unpaired = properties(vec![ | |
| 140 | + | ("Address", Value::from("AA:BB:CC:DD:EE:FF")), | |
| 141 | + | ("Paired", Value::from(false)), | |
| 142 | + | ]); | |
| 143 | + | assert!(device(&unpaired).is_none()); | |
| 144 | + | let no_address = properties(vec![("Paired", Value::from(true))]); | |
| 145 | + | assert!(device(&no_address).is_none()); | |
| 146 | + | } | |
| 147 | + | ||
| 148 | + | #[test] | |
| 149 | + | fn alias_falls_back_to_name() { | |
| 150 | + | let props = properties(vec![ | |
| 151 | + | ("Address", Value::from("AA:BB:CC:DD:EE:FF")), | |
| 152 | + | ("Name", Value::from("realme Buds T310")), | |
| 153 | + | ("Paired", Value::from(true)), | |
| 154 | + | ]); | |
| 155 | + | let device = device(&props).unwrap(); | |
| 156 | + | assert_eq!(device.alias, "realme Buds T310"); | |
| 157 | + | assert!(!device.connected); | |
| 158 | + | } | |
| 159 | + | } | |
| @@ -0,0 +1,166 @@ | |||
| 1 | + | //! Bluetooth addresses and UUIDs. | |
| 2 | + | ||
| 3 | + | use std::fmt; | |
| 4 | + | use std::str::FromStr; | |
| 5 | + | ||
| 6 | + | use serde::{Serialize, Serializer}; | |
| 7 | + | ||
| 8 | + | use crate::error::{Error, Result}; | |
| 9 | + | ||
| 10 | + | /// A Bluetooth device address, kept in the order people write it (`AA:BB:CC:DD:EE:FF`). | |
| 11 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] | |
| 12 | + | pub struct BdAddr([u8; 6]); | |
| 13 | + | ||
| 14 | + | impl BdAddr { | |
| 15 | + | /// The address as the kernel's `bdaddr_t` stores it: reversed. | |
| 16 | + | /// Spec: transport.md#sockets | |
| 17 | + | pub(crate) fn kernel_order(self) -> [u8; 6] { | |
| 18 | + | let mut bytes = self.0; | |
| 19 | + | bytes.reverse(); | |
| 20 | + | bytes | |
| 21 | + | } | |
| 22 | + | } | |
| 23 | + | ||
| 24 | + | #[derive(Debug, Clone, PartialEq, Eq)] | |
| 25 | + | pub struct AddrParseError(String); | |
| 26 | + | ||
| 27 | + | impl fmt::Display for AddrParseError { | |
| 28 | + | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| 29 | + | write!(f, "{:?} is not a Bluetooth address like AA:BB:CC:DD:EE:FF", self.0) | |
| 30 | + | } | |
| 31 | + | } | |
| 32 | + | ||
| 33 | + | impl std::error::Error for AddrParseError {} | |
| 34 | + | ||
| 35 | + | impl FromStr for BdAddr { | |
| 36 | + | type Err = AddrParseError; | |
| 37 | + | ||
| 38 | + | fn from_str(text: &str) -> std::result::Result<Self, Self::Err> { | |
| 39 | + | let error = || AddrParseError(text.to_owned()); | |
| 40 | + | let mut bytes = [0u8; 6]; | |
| 41 | + | let mut parts = text.split(':'); | |
| 42 | + | for byte in &mut bytes { | |
| 43 | + | let part = parts.next().ok_or_else(error)?; | |
| 44 | + | if part.len() != 2 { | |
| 45 | + | return Err(error()); | |
| 46 | + | } | |
| 47 | + | *byte = u8::from_str_radix(part, 16).map_err(|_| error())?; | |
| 48 | + | } | |
| 49 | + | if parts.next().is_some() { | |
| 50 | + | return Err(error()); | |
| 51 | + | } | |
| 52 | + | Ok(BdAddr(bytes)) | |
| 53 | + | } | |
| 54 | + | } | |
| 55 | + | ||
| 56 | + | impl fmt::Display for BdAddr { | |
| 57 | + | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| 58 | + | let [a, b, c, d, e, g] = self.0; | |
| 59 | + | write!(f, "{a:02X}:{b:02X}:{c:02X}:{d:02X}:{e:02X}:{g:02X}") | |
| 60 | + | } | |
| 61 | + | } | |
| 62 | + | ||
| 63 | + | impl Serialize for BdAddr { | |
| 64 | + | fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> { | |
| 65 | + | serializer.collect_str(self) | |
| 66 | + | } | |
| 67 | + | } | |
| 68 | + | ||
| 69 | + | /// A 128-bit Bluetooth UUID. | |
| 70 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 71 | + | pub struct Uuid(u128); | |
| 72 | + | ||
| 73 | + | /// `00000000-0000-1000-8000-00805F9B34FB`; short UUIDs are offsets into it. | |
| 74 | + | /// Spec: transport.md#sdp-data-elements | |
| 75 | + | const BASE_UUID: u128 = 0x0000_0000_0000_1000_8000_0080_5F9B_34FB; | |
| 76 | + | ||
| 77 | + | impl Uuid { | |
| 78 | + | pub const fn from_u128(value: u128) -> Self { | |
| 79 | + | Uuid(value) | |
| 80 | + | } | |
| 81 | + | ||
| 82 | + | /// A 16- or 32-bit UUID, expanded with the Bluetooth base UUID. | |
| 83 | + | pub const fn from_u32(short: u32) -> Self { | |
| 84 | + | Uuid(BASE_UUID | ((short as u128) << 96)) | |
| 85 | + | } | |
| 86 | + | ||
| 87 | + | /// RFCOMM's protocol UUID (`0x0003`). | |
| 88 | + | /// Spec: transport.md#sdp-rfcomm-channel | |
| 89 | + | pub const RFCOMM: Uuid = Uuid::from_u32(0x0003); | |
| 90 | + | ||
| 91 | + | pub fn to_be_bytes(self) -> [u8; 16] { | |
| 92 | + | self.0.to_be_bytes() | |
| 93 | + | } | |
| 94 | + | ||
| 95 | + | /// A UUID as SDP encodes it: 2, 4 or 16 big-endian bytes. | |
| 96 | + | /// Spec: transport.md#sdp-data-elements | |
| 97 | + | pub(crate) fn from_sdp(bytes: &[u8]) -> Result<Self> { | |
| 98 | + | match *bytes { | |
| 99 | + | [a, b] => Ok(Uuid::from_u32(u32::from(u16::from_be_bytes([a, b])))), | |
| 100 | + | [a, b, c, d] => Ok(Uuid::from_u32(u32::from_be_bytes([a, b, c, d]))), | |
| 101 | + | _ => { | |
| 102 | + | let long: [u8; 16] = bytes | |
| 103 | + | .try_into() | |
| 104 | + | .map_err(|_| Error::Protocol(format!("SDP UUID of {} bytes", bytes.len())))?; | |
| 105 | + | Ok(Uuid(u128::from_be_bytes(long))) | |
| 106 | + | } | |
| 107 | + | } | |
| 108 | + | } | |
| 109 | + | } | |
| 110 | + | ||
| 111 | + | impl fmt::Display for Uuid { | |
| 112 | + | /// Lowercase and hyphenated, as BlueZ writes it. | |
| 113 | + | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| 114 | + | let hex = format!("{:032x}", self.0); | |
| 115 | + | let part = |range: std::ops::Range<usize>| hex.get(range).unwrap_or_default(); | |
| 116 | + | write!( | |
| 117 | + | f, | |
| 118 | + | "{}-{}-{}-{}-{}", | |
| 119 | + | part(0..8), | |
| 120 | + | part(8..12), | |
| 121 | + | part(12..16), | |
| 122 | + | part(16..20), | |
| 123 | + | part(20..32) | |
| 124 | + | ) | |
| 125 | + | } | |
| 126 | + | } | |
| 127 | + | ||
| 128 | + | #[cfg(test)] | |
| 129 | + | mod tests { | |
| 130 | + | use super::*; | |
| 131 | + | ||
| 132 | + | #[test] | |
| 133 | + | fn address_round_trip_and_kernel_order() { | |
| 134 | + | let addr: BdAddr = "AA:bb:CC:01:02:03".parse().unwrap(); | |
| 135 | + | assert_eq!(addr.to_string(), "AA:BB:CC:01:02:03"); | |
| 136 | + | assert_eq!(addr.kernel_order(), [0x03, 0x02, 0x01, 0xCC, 0xBB, 0xAA]); | |
| 137 | + | } | |
| 138 | + | ||
| 139 | + | #[test] | |
| 140 | + | fn bad_addresses_are_rejected() { | |
| 141 | + | for text in [ | |
| 142 | + | "", | |
| 143 | + | "AA:BB:CC:DD:EE", | |
| 144 | + | "AA:BB:CC:DD:EE:FF:00", | |
| 145 | + | "AA:BB:CC:DD:EE:F", | |
| 146 | + | "GG:BB:CC:DD:EE:FF", | |
| 147 | + | ] { | |
| 148 | + | assert!(text.parse::<BdAddr>().is_err(), "{text}"); | |
| 149 | + | } | |
| 150 | + | } | |
| 151 | + | ||
| 152 | + | #[test] | |
| 153 | + | fn uuid_display_matches_bluez() { | |
| 154 | + | let uuid = Uuid::from_u128(0x0000_079A_D102_11E1_9B23_0002_5B00_A5A5); | |
| 155 | + | assert_eq!(uuid.to_string(), "0000079a-d102-11e1-9b23-00025b00a5a5"); | |
| 156 | + | assert_eq!(Uuid::RFCOMM.to_string(), "00000003-0000-1000-8000-00805f9b34fb"); | |
| 157 | + | } | |
| 158 | + | ||
| 159 | + | #[test] | |
| 160 | + | fn short_sdp_uuids_expand_with_the_base() { | |
| 161 | + | assert_eq!(Uuid::from_sdp(&[0x00, 0x03]).unwrap(), Uuid::RFCOMM); | |
| 162 | + | assert_eq!(Uuid::from_sdp(&[0x00, 0x00, 0x00, 0x03]).unwrap(), Uuid::RFCOMM); | |
| 163 | + | assert_eq!(Uuid::from_sdp(&Uuid::RFCOMM.to_be_bytes()).unwrap(), Uuid::RFCOMM); | |
| 164 | + | assert!(Uuid::from_sdp(&[1, 2, 3]).is_err()); | |
| 165 | + | } | |
| 166 | + | } | |
| @@ -0,0 +1,42 @@ | |||
| 1 | + | //! `--debug` output on stderr: a hex dump of every byte sent and received, plus notes on what | |
| 2 | + | //! budctl decoded and decided. Off by default. | |
| 3 | + | ||
| 4 | + | use std::sync::atomic::{AtomicBool, Ordering}; | |
| 5 | + | ||
| 6 | + | static ENABLED: AtomicBool = AtomicBool::new(false); | |
| 7 | + | ||
| 8 | + | pub fn enable() { | |
| 9 | + | ENABLED.store(true, Ordering::Relaxed); | |
| 10 | + | } | |
| 11 | + | ||
| 12 | + | pub fn enabled() -> bool { | |
| 13 | + | ENABLED.load(Ordering::Relaxed) | |
| 14 | + | } | |
| 15 | + | ||
| 16 | + | /// Print a note when debugging is on. The message is only built if it will be printed. | |
| 17 | + | pub(crate) fn note(message: impl FnOnce() -> String) { | |
| 18 | + | if enabled() { | |
| 19 | + | eprintln!("# {}", message()); | |
| 20 | + | } | |
| 21 | + | } | |
| 22 | + | ||
| 23 | + | /// `AA 07 00 …` | |
| 24 | + | pub fn hex(bytes: &[u8]) -> String { | |
| 25 | + | let mut out = String::with_capacity(bytes.len() * 3); | |
| 26 | + | for (i, byte) in bytes.iter().enumerate() { | |
| 27 | + | if i > 0 { | |
| 28 | + | out.push(' '); | |
| 29 | + | } | |
| 30 | + | out.push_str(&format!("{byte:02X}")); | |
| 31 | + | } | |
| 32 | + | out | |
| 33 | + | } | |
| 34 | + | ||
| 35 | + | #[cfg(test)] | |
| 36 | + | mod tests { | |
| 37 | + | #[test] | |
| 38 | + | fn hex_is_spaced_uppercase() { | |
| 39 | + | assert_eq!(super::hex(&[0xAA, 0x07, 0x00]), "AA 07 00"); | |
| 40 | + | assert_eq!(super::hex(&[]), ""); | |
| 41 | + | } | |
| 42 | + | } | |
| @@ -0,0 +1,48 @@ | |||
| 1 | + | //! Device plugins. | |
| 2 | + | //! | |
| 3 | + | //! To support a new pair of buds, add one module here and list it in [`REGISTRY`]. Transport, | |
| 4 | + | //! CLI and GUI code do not change. | |
| 5 | + | ||
| 6 | + | use crate::bluez::PairedDevice; | |
| 7 | + | use crate::bt::Uuid; | |
| 8 | + | use crate::error::{Error, Result}; | |
| 9 | + | use crate::status::{Status, TouchControls}; | |
| 10 | + | use crate::transport::Transport; | |
| 11 | + | ||
| 12 | + | pub mod realme_t310; | |
| 13 | + | ||
| 14 | + | /// Every model budctl supports. | |
| 15 | + | pub static REGISTRY: &[&dyn Device] = &[&realme_t310::RealmeT310]; | |
| 16 | + | ||
| 17 | + | /// One supported model. | |
| 18 | + | pub trait Device: Sync { | |
| 19 | + | /// Model name, e.g. `realme Buds T310`. | |
| 20 | + | fn name(&self) -> &'static str; | |
| 21 | + | ||
| 22 | + | /// Whether a paired device is this model, judged from BlueZ data alone. | |
| 23 | + | fn matches(&self, device: &PairedDevice) -> bool; | |
| 24 | + | ||
| 25 | + | /// The control service(s), in the order to try. SDP turns each into an RFCOMM channel. | |
| 26 | + | fn rfcomm_uuids(&self) -> &'static [Uuid]; | |
| 27 | + | ||
| 28 | + | /// Run the model's init sequence on a fresh link and return a ready session. | |
| 29 | + | fn open(&self, link: Box<dyn Transport>) -> Result<Box<dyn Session>>; | |
| 30 | + | } | |
| 31 | + | ||
| 32 | + | /// An open control link to one pair of buds. Dropping it closes the link. | |
| 33 | + | pub trait Session: Send { | |
| 34 | + | /// Battery, noise control, EQ, switches and whatever else the model can read. | |
| 35 | + | fn status(&mut self) -> Result<Status>; | |
| 36 | + | ||
| 37 | + | /// The touch-control (gesture) settings of each bud. | |
| 38 | + | fn touch_controls(&mut self) -> Result<TouchControls> { | |
| 39 | + | Err(Error::Unsupported( | |
| 40 | + | "these buds have no touch-control settings budctl can read".to_owned(), | |
| 41 | + | )) | |
| 42 | + | } | |
| 43 | + | } | |
| 44 | + | ||
| 45 | + | /// The supported model a paired device is, if any. | |
| 46 | + | pub fn identify(device: &PairedDevice) -> Option<&'static dyn Device> { | |
| 47 | + | REGISTRY.iter().copied().find(|model| model.matches(device)) | |
| 48 | + | } | |
| @@ -0,0 +1,542 @@ | |||
| 1 | + | //! realme Buds T310 commands, tables and pure decoders. No I/O here, so every function can be | |
| 2 | + | //! tested with bytes from the spec. Each constant cites docs/protocol/realme_t310.md. | |
| 3 | + | ||
| 4 | + | use crate::error::{Error, Result}; | |
| 5 | + | use crate::reader::Reader; | |
| 6 | + | use crate::status::{Battery, Charge, Gesture, NoiseControl, Switch}; | |
| 7 | + | ||
| 8 | + | /// Spec: realme_t310.md#bitmap | |
| 9 | + | pub(super) const HANDSHAKE: u16 = 0x0100; | |
| 10 | + | /// Spec: realme_t310.md#identity | |
| 11 | + | pub(super) const PRODUCT_ID: u16 = 0x0103; | |
| 12 | + | /// Spec: realme_t310.md#firmware | |
| 13 | + | pub(super) const FIRMWARE: u16 = 0x0105; | |
| 14 | + | /// Spec: realme_t310.md#battery | |
| 15 | + | pub(super) const BATTERY: u16 = 0x0106; | |
| 16 | + | /// Spec: realme_t310.md#gestures | |
| 17 | + | pub(super) const GESTURES: u16 = 0x0108; | |
| 18 | + | /// Spec: realme_t310.md#anc-read | |
| 19 | + | pub(super) const NOISE_CONTROL: u16 = 0x010C; | |
| 20 | + | /// Spec: realme_t310.md#switches | |
| 21 | + | pub(super) const SWITCHES: u16 = 0x010D; | |
| 22 | + | /// Spec: realme_t310.md#eq-read | |
| 23 | + | pub(super) const EQ_PRESET: u16 = 0x010F; | |
| 24 | + | /// Spec: realme_t310.md#codec | |
| 25 | + | pub(super) const CODEC: u16 = 0x0114; | |
| 26 | + | /// Not sent: the T310 does not answer it (HW1). Kept for W6. Spec: realme_t310.md#bass-read | |
| 27 | + | #[allow(dead_code)] | |
| 28 | + | pub(super) const BASS_LEVEL: u16 = 0x0124; | |
| 29 | + | /// Spec: realme_t310.md#events-offered | |
| 30 | + | pub(super) const EVENTS_OFFERED: u16 = 0x0200; | |
| 31 | + | /// Spec: realme_t310.md#subscribe | |
| 32 | + | pub(super) const SUBSCRIBE: u16 = 0x0205; | |
| 33 | + | /// Spec: realme_t310.md#fit-test | |
| 34 | + | pub(super) const FIT_TEST: u16 = 0x0405; | |
| 35 | + | ||
| 36 | + | /// Spec: realme_t310.md#identity | |
| 37 | + | pub(super) const T310_PRODUCT_ID: u32 = 0x06_3C_12; | |
| 38 | + | ||
| 39 | + | /// Payload asking for the current noise-control mode. Spec: realme_t310.md#anc-read | |
| 40 | + | pub(super) const NOISE_MODE_QUERY: [u8; 2] = [0x01, 0x01]; | |
| 41 | + | /// Payload asking for the hold's noise-control cycle (one setting for both buds). | |
| 42 | + | /// Spec: realme_t310.md#hold-cycle | |
| 43 | + | pub(super) const HOLD_CYCLE_QUERY: [u8; 2] = [0x02, 0x01]; | |
| 44 | + | /// Count, then the T310's switch ids: `05 06 11 1A 1B 1D`. Spec: realme_t310.md#switches | |
| 45 | + | pub(super) const SWITCH_QUERY: [u8; 7] = [6, 0x05, 0x06, 0x11, 0x1A, 0x1B, 0x1D]; | |
| 46 | + | ||
| 47 | + | /// Event codes to subscribe to; the optional ones only when their command is allowed. | |
| 48 | + | /// Spec: realme_t310.md#subscribe | |
| 49 | + | const EVENTS: [(u8, Option<u16>); 4] = [(0x01, None), (0x02, None), (0x03, None), (0x04, Some(FIT_TEST))]; | |
| 50 | + | ||
| 51 | + | /// Spec: realme_t310.md#switches | |
| 52 | + | const SWITCH_NAMES: [(u8, &str, &str); 5] = [ | |
| 53 | + | (0x06, "game", "Game mode"), | |
| 54 | + | (0x11, "dual", "Dual connection"), | |
| 55 | + | (0x1A, "wind", "Wind-noise reduction"), | |
| 56 | + | (0x1B, "spatial", "3D sound"), | |
| 57 | + | (0x1D, "bass-boost", "Bass boost"), | |
| 58 | + | ]; | |
| 59 | + | ||
| 60 | + | /// Noise-control masks: mode and level. Spec: realme_t310.md#anc-read | |
| 61 | + | const NOISE_MODES: [(u32, &str, Option<&str>); 5] = [ | |
| 62 | + | (0x01, "off", None), | |
| 63 | + | (0x02, "transparency", None), | |
| 64 | + | (0x04, "anc", Some("light")), | |
| 65 | + | (0x08, "anc", Some("deep")), | |
| 66 | + | (0x10, "anc", Some("medium")), | |
| 67 | + | ]; | |
| 68 | + | ||
| 69 | + | /// Bits of the hold cycle. Spec: realme_t310.md#hold-cycle | |
| 70 | + | const CYCLE_MODES: [(u32, &str); 3] = [(0x01, "off"), (0x02, "transparency"), (0x08, "anc")]; | |
| 71 | + | ||
| 72 | + | /// Built-in EQ presets by id. Spec: realme_t310.md#eq-read | |
| 73 | + | const EQ_PRESETS: [(u8, &str); 4] = [ | |
| 74 | + | (0x00, "pure-raw"), | |
| 75 | + | (0x01, "deep-bass"), | |
| 76 | + | (0x02, "pure-vocals"), | |
| 77 | + | (0x03, "pure-bass"), | |
| 78 | + | ]; | |
| 79 | + | ||
| 80 | + | /// Spec: realme_t310.md#codec | |
| 81 | + | const CODECS: [(u8, &str); 8] = [ | |
| 82 | + | (0x01, "SBC"), | |
| 83 | + | (0x02, "AAC"), | |
| 84 | + | (0x03, "LDAC"), | |
| 85 | + | (0x04, "aptX"), | |
| 86 | + | (0x05, "aptX HD"), | |
| 87 | + | (0x06, "aptX Adaptive"), | |
| 88 | + | (0x07, "LHDC"), | |
| 89 | + | (0x08, "LHDC V5"), | |
| 90 | + | ]; | |
| 91 | + | ||
| 92 | + | /// Gesture-table names. Spec: realme_t310.md#gestures | |
| 93 | + | const SIDES: [(u8, &str); 3] = [(0x01, "left"), (0x02, "right"), (0x04, "both")]; | |
| 94 | + | /// Spec: realme_t310.md#gestures | |
| 95 | + | const MAIN_GROUP: u8 = 0x01; | |
| 96 | + | /// Spec: realme_t310.md#gestures | |
| 97 | + | const ACTS: [(u8, &str); 6] = [ | |
| 98 | + | (0x01, "single-tap"), | |
| 99 | + | (0x02, "double-tap"), | |
| 100 | + | (0x03, "triple-tap"), | |
| 101 | + | (0x04, "hold"), | |
| 102 | + | (0x05, "slide"), | |
| 103 | + | (0x06, "long-hold"), | |
| 104 | + | ]; | |
| 105 | + | /// Spec: realme_t310.md#gestures | |
| 106 | + | const FUNCTIONS: [(u8, &str); 15] = [ | |
| 107 | + | (0x00, "none"), | |
| 108 | + | (0x01, "play-pause"), | |
| 109 | + | (0x03, "voice-assistant"), | |
| 110 | + | (0x05, "previous"), | |
| 111 | + | (0x06, "next"), | |
| 112 | + | (0x07, "volume"), | |
| 113 | + | (0x08, "noise-cycle"), | |
| 114 | + | (0x09, "favourite-music"), | |
| 115 | + | (0x0A, "switch-track"), | |
| 116 | + | (0x0B, "volume-up"), | |
| 117 | + | (0x0C, "volume-down"), | |
| 118 | + | (0x0D, "switch-devices"), | |
| 119 | + | (0x11, "game-mode"), | |
| 120 | + | (0x1C, "decline-call"), | |
| 121 | + | (0x1D, "answer-call"), | |
| 122 | + | ]; | |
| 123 | + | ||
| 124 | + | fn name_of<K: PartialEq + Copy>(table: &[(K, &'static str)], key: K) -> Option<&'static str> { | |
| 125 | + | table.iter().find(|(k, _)| *k == key).map(|(_, name)| *name) | |
| 126 | + | } | |
| 127 | + | ||
| 128 | + | /// When a command may be sent. Spec: realme_t310.md#bitmap | |
| 129 | + | enum Gate { | |
| 130 | + | Always, | |
| 131 | + | Bit(u8), | |
| 132 | + | } | |
| 133 | + | ||
| 134 | + | /// The gate of every command budctl uses. An unlisted command is never sent. | |
| 135 | + | /// Spec: realme_t310.md#bitmap | |
| 136 | + | fn gate(cmd: u16) -> Option<Gate> { | |
| 137 | + | Some(match cmd { | |
| 138 | + | 0x0100..=0x0104 | 0x0106 | 0x010B | 0x010D | 0x0200 => Gate::Always, | |
| 139 | + | 0x0105 => Gate::Bit(0), | |
| 140 | + | 0x0108 | 0x0401 => Gate::Bit(3), | |
| 141 | + | 0x0109 => Gate::Bit(4), | |
| 142 | + | 0x0400 => Gate::Bit(5), | |
| 143 | + | 0x0403 => Gate::Bit(7), | |
| 144 | + | 0x010C | 0x0404 => Gate::Bit(8), | |
| 145 | + | 0x0405 => Gate::Bit(9), | |
| 146 | + | 0x010F | 0x0406 => Gate::Bit(10), | |
| 147 | + | 0x0114 => Gate::Bit(17), | |
| 148 | + | 0x0205 => Gate::Bit(22), | |
| 149 | + | 0x0122 | 0x0418 => Gate::Bit(34), | |
| 150 | + | 0x0124 | 0x041B => Gate::Bit(38), | |
| 151 | + | _ => return None, | |
| 152 | + | }) | |
| 153 | + | } | |
| 154 | + | ||
| 155 | + | /// The commands these buds accept, from the handshake reply. Spec: realme_t310.md#bitmap | |
| 156 | + | #[derive(Debug)] | |
| 157 | + | pub(super) struct Commands { | |
| 158 | + | bitmap: Vec<u8>, | |
| 159 | + | } | |
| 160 | + | ||
| 161 | + | impl Commands { | |
| 162 | + | pub(super) fn parse(reply: &[u8]) -> Result<Self> { | |
| 163 | + | let mut r = ok_reply(reply, "the handshake")?; | |
| 164 | + | Ok(Self { | |
| 165 | + | bitmap: r.rest().to_vec(), | |
| 166 | + | }) | |
| 167 | + | } | |
| 168 | + | ||
| 169 | + | pub(super) fn allows(&self, cmd: u16) -> bool { | |
| 170 | + | match gate(cmd) { | |
| 171 | + | Some(Gate::Always) => true, | |
| 172 | + | Some(Gate::Bit(n)) => self | |
| 173 | + | .bitmap | |
| 174 | + | .get(usize::from(n / 8)) | |
| 175 | + | .is_some_and(|byte| byte & (1 << (n % 8)) != 0), | |
| 176 | + | None => false, | |
| 177 | + | } | |
| 178 | + | } | |
| 179 | + | } | |
| 180 | + | ||
| 181 | + | /// A reply whose status byte is `00`, positioned after it. Spec: realme_t310.md#seq | |
| 182 | + | fn ok_reply<'a>(reply: &'a [u8], what: &'static str) -> Result<Reader<'a>> { | |
| 183 | + | let mut r = Reader::new(reply, what); | |
| 184 | + | match r.u8()? { | |
| 185 | + | 0x00 => Ok(r), | |
| 186 | + | status => Err(Error::Rejected { | |
| 187 | + | what: what.to_owned(), | |
| 188 | + | status, | |
| 189 | + | }), | |
| 190 | + | } | |
| 191 | + | } | |
| 192 | + | ||
| 193 | + | /// Spec: realme_t310.md#identity | |
| 194 | + | pub(super) fn decode_product_id(reply: &[u8]) -> Result<u32> { | |
| 195 | + | let mut r = ok_reply(reply, "the product id query")?; | |
| 196 | + | let [low, middle, high] = [r.u8()?, r.u8()?, r.u8()?]; | |
| 197 | + | Ok(u32::from_le_bytes([low, middle, high, 0])) | |
| 198 | + | } | |
| 199 | + | ||
| 200 | + | /// Spec: realme_t310.md#events-offered | |
| 201 | + | pub(super) fn decode_events_offered(reply: &[u8]) -> Result<Vec<u8>> { | |
| 202 | + | let mut r = ok_reply(reply, "the event list")?; | |
| 203 | + | let count = r.u8()?; | |
| 204 | + | Ok(r.take(usize::from(count))?.to_vec()) | |
| 205 | + | } | |
| 206 | + | ||
| 207 | + | /// The subscribe payload: count, then the wanted codes the buds offer. | |
| 208 | + | /// Spec: realme_t310.md#subscribe | |
| 209 | + | pub(super) fn subscribe_payload(offered: &[u8], commands: &Commands) -> Vec<u8> { | |
| 210 | + | let codes: Vec<u8> = EVENTS | |
| 211 | + | .iter() | |
| 212 | + | .filter(|(code, needs)| offered.contains(code) && needs.is_none_or(|cmd| commands.allows(cmd))) | |
| 213 | + | .map(|(code, _)| *code) | |
| 214 | + | .collect(); | |
| 215 | + | let mut payload = vec![u8::try_from(codes.len()).unwrap_or_default()]; | |
| 216 | + | payload.extend(codes); | |
| 217 | + | payload | |
| 218 | + | } | |
| 219 | + | ||
| 220 | + | /// Spec: realme_t310.md#battery | |
| 221 | + | pub(super) fn decode_battery(reply: &[u8]) -> Result<Battery> { | |
| 222 | + | let mut r = ok_reply(reply, "the battery reply")?; | |
| 223 | + | let mut battery = Battery::default(); | |
| 224 | + | for _ in 0..r.u8()? { | |
| 225 | + | let part = r.u8()?; | |
| 226 | + | let raw = r.u8()?; | |
| 227 | + | let level = raw & 0x7F; | |
| 228 | + | if level == 0 { | |
| 229 | + | continue; // not known | |
| 230 | + | } | |
| 231 | + | let charge = Some(Charge { | |
| 232 | + | level, | |
| 233 | + | charging: raw & 0x80 != 0, | |
| 234 | + | }); | |
| 235 | + | match part { | |
| 236 | + | 0x01 => battery.left = charge, | |
| 237 | + | 0x02 => battery.right = charge, | |
| 238 | + | 0x03 => battery.case = charge, | |
| 239 | + | _ => {} | |
| 240 | + | } | |
| 241 | + | } | |
| 242 | + | Ok(battery) | |
| 243 | + | } | |
| 244 | + | ||
| 245 | + | /// The versions of kind 2: plain numbers are joined with dots; full dotted versions (the T310's) | |
| 246 | + | /// are shown once each, joined with ` / `. The raw text when there are none. | |
| 247 | + | /// Spec: realme_t310.md#firmware | |
| 248 | + | pub(super) fn decode_firmware(reply: &[u8]) -> Result<String> { | |
| 249 | + | let mut r = ok_reply(reply, "the firmware reply")?; | |
| 250 | + | let _count = r.u8()?; | |
| 251 | + | let text = String::from_utf8_lossy(r.rest()).into_owned(); | |
| 252 | + | let fields: Vec<&str> = text.split(',').map(str::trim).collect(); | |
| 253 | + | let mut versions: Vec<&str> = fields | |
| 254 | + | .chunks(3) | |
| 255 | + | .filter_map(|triple| match triple { | |
| 256 | + | [_device, "2", version] => Some(*version), | |
| 257 | + | _ => None, | |
| 258 | + | }) | |
| 259 | + | .collect(); | |
| 260 | + | if versions.is_empty() { | |
| 261 | + | return Ok(text); | |
| 262 | + | } | |
| 263 | + | if !versions.iter().any(|v| v.contains('.')) { | |
| 264 | + | return Ok(versions.join(".")); | |
| 265 | + | } | |
| 266 | + | let mut seen = Vec::new(); | |
| 267 | + | versions.retain(|v| { | |
| 268 | + | let new = !seen.contains(v); | |
| 269 | + | seen.push(*v); | |
| 270 | + | new | |
| 271 | + | }); | |
| 272 | + | Ok(versions.join(" / ")) | |
| 273 | + | } | |
| 274 | + | ||
| 275 | + | /// Spec: realme_t310.md#codec | |
| 276 | + | pub(super) fn decode_codec(reply: &[u8]) -> Result<String> { | |
| 277 | + | let codec = ok_reply(reply, "the codec reply")?.u8()?; | |
| 278 | + | Ok(name_of(&CODECS, codec).map_or_else(|| format!("unknown (0x{codec:02X})"), str::to_owned)) | |
| 279 | + | } | |
| 280 | + | ||
| 281 | + | /// Spec: realme_t310.md#anc-read | |
| 282 | + | pub(super) fn decode_noise_mode(reply: &[u8]) -> Result<NoiseControl> { | |
| 283 | + | let mask = noise_mask(reply, NOISE_MODE_QUERY, "the noise-control reply")?; | |
| 284 | + | Ok(match NOISE_MODES.iter().find(|(m, _, _)| *m == mask) { | |
| 285 | + | Some((_, mode, level)) => NoiseControl { | |
| 286 | + | mode: (*mode).to_owned(), | |
| 287 | + | level: level.map(str::to_owned), | |
| 288 | + | }, | |
| 289 | + | None => NoiseControl { | |
| 290 | + | mode: format!("unknown (0x{mask:02X})"), | |
| 291 | + | level: None, | |
| 292 | + | }, | |
| 293 | + | }) | |
| 294 | + | } | |
| 295 | + | ||
| 296 | + | /// Spec: realme_t310.md#hold-cycle | |
| 297 | + | pub(super) fn decode_hold_cycle(reply: &[u8]) -> Result<Vec<String>> { | |
| 298 | + | let mask = noise_mask(reply, HOLD_CYCLE_QUERY, "the hold-cycle reply")?; | |
| 299 | + | let mut modes: Vec<String> = CYCLE_MODES | |
| 300 | + | .iter() | |
| 301 | + | .filter(|(bit, _)| mask & bit != 0) | |
| 302 | + | .map(|(_, name)| (*name).to_owned()) | |
| 303 | + | .collect(); | |
| 304 | + | let known = CYCLE_MODES.iter().fold(0, |all, (bit, _)| all | bit); | |
| 305 | + | if mask & !known != 0 { | |
| 306 | + | modes.push(format!("unknown (0x{:02X})", mask & !known)); | |
| 307 | + | } | |
| 308 | + | Ok(modes) | |
| 309 | + | } | |
| 310 | + | ||
| 311 | + | /// `00 <echo of the query> <mask, 1-4 bytes LE>`. Spec: realme_t310.md#anc-read | |
| 312 | + | fn noise_mask(reply: &[u8], query: [u8; 2], what: &'static str) -> Result<u32> { | |
| 313 | + | let mut r = ok_reply(reply, what)?; | |
| 314 | + | if [r.u8()?, r.u8()?] != query { | |
| 315 | + | return Err(Error::Protocol(format!("{what} answers a different question"))); | |
| 316 | + | } | |
| 317 | + | let bytes = r.rest(); | |
| 318 | + | if bytes.is_empty() || bytes.len() > 4 { | |
| 319 | + | return Err(Error::Protocol(format!("{what} has a {} byte value", bytes.len()))); | |
| 320 | + | } | |
| 321 | + | Ok(bytes.iter().rev().fold(0, |mask, &b| (mask << 8) | u32::from(b))) | |
| 322 | + | } | |
| 323 | + | ||
| 324 | + | /// Spec: realme_t310.md#switches | |
| 325 | + | pub(super) fn decode_switches(reply: &[u8]) -> Result<Vec<Switch>> { | |
| 326 | + | let mut r = ok_reply(reply, "the switch reply")?; | |
| 327 | + | let mut switches = Vec::new(); | |
| 328 | + | for _ in 0..r.u8()? { | |
| 329 | + | let id = r.u8()?; | |
| 330 | + | let value = r.u8()?; | |
| 331 | + | if let Some((_, key, label)) = SWITCH_NAMES.iter().find(|(known, _, _)| *known == id) { | |
| 332 | + | switches.push(Switch { | |
| 333 | + | key, | |
| 334 | + | label, | |
| 335 | + | on: value == 0x01, | |
| 336 | + | }); | |
| 337 | + | } | |
| 338 | + | } | |
| 339 | + | Ok(switches) | |
| 340 | + | } | |
| 341 | + | ||
| 342 | + | /// Spec: realme_t310.md#eq-read | |
| 343 | + | pub(super) fn decode_eq(reply: &[u8]) -> Result<String> { | |
| 344 | + | let id = ok_reply(reply, "the EQ reply")?.u8()?; | |
| 345 | + | Ok(name_of(&EQ_PRESETS, id).map_or_else(|| format!("custom-{id}"), str::to_owned)) | |
| 346 | + | } | |
| 347 | + | ||
| 348 | + | /// `00 <min> <max> <level>`, all signed. Not used until W6. Spec: realme_t310.md#bass-read | |
| 349 | + | #[allow(dead_code)] | |
| 350 | + | pub(super) fn decode_bass_level(reply: &[u8]) -> Result<i8> { | |
| 351 | + | let mut r = ok_reply(reply, "the bass-level reply")?; | |
| 352 | + | let (min, max, level) = (r.i8()?, r.i8()?, r.i8()?); | |
| 353 | + | if !(min..=max).contains(&level) { | |
| 354 | + | return Err(Error::Protocol(format!("bass level {level} outside {min}..={max}"))); | |
| 355 | + | } | |
| 356 | + | Ok(level) | |
| 357 | + | } | |
| 358 | + | ||
| 359 | + | /// Spec: realme_t310.md#gestures | |
| 360 | + | pub(super) fn decode_gestures(reply: &[u8]) -> Result<Vec<Gesture>> { | |
| 361 | + | let mut r = ok_reply(reply, "the gesture table")?; | |
| 362 | + | let mut gestures = Vec::new(); | |
| 363 | + | for _ in 0..r.u8()? { | |
| 364 | + | let [side, group, act, function] = [r.u8()?, r.u8()?, r.u8()?, r.u8()?]; | |
| 365 | + | gestures.push(Gesture { | |
| 366 | + | side: name_of(&SIDES, side).map_or_else(|| format!("device-0x{side:02X}"), str::to_owned), | |
| 367 | + | gesture: name_of(&ACTS, act).map_or_else(|| format!("act-0x{act:02X}"), str::to_owned), | |
| 368 | + | action: name_of(&FUNCTIONS, function).map_or_else(|| format!("fn-0x{function:02X}"), str::to_owned), | |
| 369 | + | group: (group != MAIN_GROUP).then_some(group), | |
| 370 | + | }); | |
| 371 | + | } | |
| 372 | + | Ok(gestures) | |
| 373 | + | } | |
| 374 | + | ||
| 375 | + | /// The handshake reply of the owner's T310 (HW1). Spec: realme_t310.md#bitmap-t310 | |
| 376 | + | #[cfg(test)] | |
| 377 | + | pub(super) const T310_BITMAP_REPLY: &str = "00 BF 1F 5A 20 45 04 40 00"; | |
| 378 | + | ||
| 379 | + | #[cfg(test)] | |
| 380 | + | mod tests { | |
| 381 | + | use super::*; | |
| 382 | + | use crate::transport::mock::hex; | |
| 383 | + | ||
| 384 | + | #[test] | |
| 385 | + | fn t310_bitmap_allows_its_commands_and_nothing_else() { | |
| 386 | + | let commands = Commands::parse(&hex(T310_BITMAP_REPLY)).unwrap(); | |
| 387 | + | // Every gated command in the T310's logged command set (realme_t310.md#bitmap-t310). | |
| 388 | + | for cmd in [ | |
| 389 | + | 0x0100, 0x0103, 0x0105, 0x0106, 0x0108, 0x0109, 0x010C, 0x010D, 0x010F, 0x0114, 0x0122, 0x0124, 0x0205, | |
| 390 | + | 0x0400, 0x0401, 0x0403, 0x0404, 0x0405, 0x0406, 0x0418, 0x041B, 0x0200, | |
| 391 | + | ] { | |
| 392 | + | assert!(commands.allows(cmd), "0x{cmd:04X} should be allowed"); | |
| 393 | + | } | |
| 394 | + | // Commands the T310 lacks, and commands budctl has no gate for. | |
| 395 | + | for cmd in [0x012F, 0x041E, 0x0413, 0x0130, 0x0427, 0x0423, 0x012A, 0x0422, 0x9999] { | |
| 396 | + | assert!(!commands.allows(cmd), "0x{cmd:04X} should be refused"); | |
| 397 | + | } | |
| 398 | + | } | |
| 399 | + | ||
| 400 | + | #[test] | |
| 401 | + | fn a_short_bitmap_allows_only_the_always_commands() { | |
| 402 | + | let commands = Commands::parse(&hex("00")).unwrap(); | |
| 403 | + | assert!(commands.allows(BATTERY) && commands.allows(SWITCHES) && commands.allows(HANDSHAKE)); | |
| 404 | + | assert!(!commands.allows(FIRMWARE) && !commands.allows(NOISE_CONTROL)); | |
| 405 | + | assert!(matches!( | |
| 406 | + | Commands::parse(&hex("01 FF")), | |
| 407 | + | Err(Error::Rejected { status: 1, .. }) | |
| 408 | + | )); | |
| 409 | + | } | |
| 410 | + | ||
| 411 | + | #[test] | |
| 412 | + | fn product_id_is_three_bytes_little_endian() { | |
| 413 | + | assert_eq!(decode_product_id(&hex("00 12 3C 06")).unwrap(), T310_PRODUCT_ID); | |
| 414 | + | assert_eq!(decode_product_id(&hex("00 14 54 06")).unwrap(), 0x06_54_14); | |
| 415 | + | assert!(decode_product_id(&hex("00 12 3C")).is_err()); | |
| 416 | + | } | |
| 417 | + | ||
| 418 | + | #[test] | |
| 419 | + | fn subscribes_to_offered_events_only() { | |
| 420 | + | let commands = Commands::parse(&hex(T310_BITMAP_REPLY)).unwrap(); | |
| 421 | + | let buds4_offer = hex("00 09 01 02 03 04 08 0B F1 F2 F3"); | |
| 422 | + | let offered = decode_events_offered(&buds4_offer).unwrap(); | |
| 423 | + | assert_eq!(subscribe_payload(&offered, &commands), hex("04 01 02 03 04")); | |
| 424 | + | assert_eq!(subscribe_payload(&[0x02, 0x01], &commands), hex("02 01 02")); | |
| 425 | + | let no_fit_test = Commands::parse(&hex("00 BD 0D")).unwrap(); | |
| 426 | + | assert_eq!(subscribe_payload(&offered, &no_fit_test), hex("03 01 02 03")); | |
| 427 | + | } | |
| 428 | + | ||
| 429 | + | #[test] | |
| 430 | + | fn battery_levels_charging_and_unknown_parts() { | |
| 431 | + | let battery = decode_battery(&hex("00 03 01 64 02 E4 03 00")).unwrap(); | |
| 432 | + | assert_eq!( | |
| 433 | + | battery.left, | |
| 434 | + | Some(Charge { | |
| 435 | + | level: 100, | |
| 436 | + | charging: false | |
| 437 | + | }) | |
| 438 | + | ); | |
| 439 | + | assert_eq!( | |
| 440 | + | battery.right, | |
| 441 | + | Some(Charge { | |
| 442 | + | level: 100, | |
| 443 | + | charging: true | |
| 444 | + | }) | |
| 445 | + | ); | |
| 446 | + | assert_eq!(battery.case, None); | |
| 447 | + | assert_eq!(decode_battery(&hex("00 00")).unwrap(), Battery::default()); | |
| 448 | + | assert!(decode_battery(&hex("00 03 01 64")).is_err()); | |
| 449 | + | } | |
| 450 | + | ||
| 451 | + | #[test] | |
| 452 | + | fn firmware_shows_kind_two_versions() { | |
| 453 | + | let mut reply = hex("00 04"); | |
| 454 | + | reply.extend(b"1,2,138,2,2,138,3,1,01,3,2,105"); | |
| 455 | + | assert_eq!(decode_firmware(&reply).unwrap(), "138.138.105"); | |
| 456 | + | // The owner's T310 (HW1): both buds report the same full version. | |
| 457 | + | let mut t310 = hex("00 02"); | |
| 458 | + | t310.extend(b"1,2,1.1.0.43,2,2,1.1.0.43"); | |
| 459 | + | assert_eq!(decode_firmware(&t310).unwrap(), "1.1.0.43"); | |
| 460 | + | let mut differ = hex("00 02"); | |
| 461 | + | differ.extend(b"1,2,1.1.0.43,2,2,1.1.0.44"); | |
| 462 | + | assert_eq!(decode_firmware(&differ).unwrap(), "1.1.0.43 / 1.1.0.44"); | |
| 463 | + | let mut odd = hex("00 01"); | |
| 464 | + | odd.extend(b"V1.0.2"); | |
| 465 | + | assert_eq!(decode_firmware(&odd).unwrap(), "V1.0.2"); | |
| 466 | + | } | |
| 467 | + | ||
| 468 | + | #[test] | |
| 469 | + | fn noise_control_modes() { | |
| 470 | + | let mode = |reply: &str| decode_noise_mode(&hex(reply)).unwrap(); | |
| 471 | + | assert_eq!(mode("00 01 01 01").mode, "off"); | |
| 472 | + | assert_eq!(mode("00 01 01 02 00").mode, "transparency"); | |
| 473 | + | let deep = mode("00 01 01 08"); | |
| 474 | + | assert_eq!((deep.mode.as_str(), deep.level.as_deref()), ("anc", Some("deep"))); | |
| 475 | + | assert_eq!(mode("00 01 01 10").level.as_deref(), Some("medium")); | |
| 476 | + | assert_eq!(mode("00 01 01 00 08").mode, "unknown (0x800)"); | |
| 477 | + | assert!(decode_noise_mode(&hex("00 02 01 08")).is_err()); | |
| 478 | + | assert!(decode_noise_mode(&hex("00 01 01")).is_err()); | |
| 479 | + | assert!(matches!( | |
| 480 | + | decode_noise_mode(&hex("0E 01 01 08")), | |
| 481 | + | Err(Error::Rejected { status: 0x0E, .. }) | |
| 482 | + | )); | |
| 483 | + | } | |
| 484 | + | ||
| 485 | + | #[test] | |
| 486 | + | fn hold_cycle_lists_modes() { | |
| 487 | + | assert_eq!(decode_hold_cycle(&hex("00 02 01 0A")).unwrap(), ["transparency", "anc"]); | |
| 488 | + | assert_eq!( | |
| 489 | + | decode_hold_cycle(&hex("00 02 01 0B 00")).unwrap(), | |
| 490 | + | ["off", "transparency", "anc"] | |
| 491 | + | ); | |
| 492 | + | assert_eq!(decode_hold_cycle(&hex("00 02 01 14")).unwrap(), ["unknown (0x14)"]); | |
| 493 | + | } | |
| 494 | + | ||
| 495 | + | #[test] | |
| 496 | + | fn switches_from_report_22_values() { | |
| 497 | + | let switches = decode_switches(&hex("00 06 05 00 06 00 11 01 1A 00 1B 01 1D 01")).unwrap(); | |
| 498 | + | let on: Vec<(&str, bool)> = switches.iter().map(|s| (s.key, s.on)).collect(); | |
| 499 | + | assert_eq!( | |
| 500 | + | on, | |
| 501 | + | [ | |
| 502 | + | ("game", false), | |
| 503 | + | ("dual", true), | |
| 504 | + | ("wind", false), | |
| 505 | + | ("spatial", true), | |
| 506 | + | ("bass-boost", true) | |
| 507 | + | ] | |
| 508 | + | ); | |
| 509 | + | assert!(decode_switches(&hex("00 02 06 01")).is_err()); | |
| 510 | + | } | |
| 511 | + | ||
| 512 | + | #[test] | |
| 513 | + | fn eq_codec_and_bass_level() { | |
| 514 | + | assert_eq!(decode_eq(&hex("00 00")).unwrap(), "pure-raw"); | |
| 515 | + | assert_eq!(decode_eq(&hex("00 03")).unwrap(), "pure-bass"); | |
| 516 | + | assert_eq!(decode_eq(&hex("00 05")).unwrap(), "custom-5"); | |
| 517 | + | assert_eq!(decode_codec(&hex("00 02")).unwrap(), "AAC"); | |
| 518 | + | assert_eq!(decode_codec(&hex("00 09")).unwrap(), "unknown (0x09)"); | |
| 519 | + | assert_eq!(decode_bass_level(&hex("00 FB 05 FE")).unwrap(), -2); | |
| 520 | + | assert!(decode_bass_level(&hex("00 FB 05 07")).is_err()); | |
| 521 | + | } | |
| 522 | + | ||
| 523 | + | #[test] | |
| 524 | + | fn gesture_table_names_known_values() { | |
| 525 | + | let gestures = decode_gestures(&hex("00 03 01 01 02 01 02 01 04 08 04 06 02 1D")).unwrap(); | |
| 526 | + | let rows: Vec<(&str, &str, &str, Option<u8>)> = gestures | |
| 527 | + | .iter() | |
| 528 | + | .map(|g| (g.side.as_str(), g.gesture.as_str(), g.action.as_str(), g.group)) | |
| 529 | + | .collect(); | |
| 530 | + | assert_eq!( | |
| 531 | + | rows, | |
| 532 | + | [ | |
| 533 | + | ("left", "double-tap", "play-pause", None), | |
| 534 | + | ("right", "hold", "noise-cycle", None), | |
| 535 | + | ("both", "double-tap", "answer-call", Some(6)), | |
| 536 | + | ] | |
| 537 | + | ); | |
| 538 | + | let odd = decode_gestures(&hex("00 01 09 01 07 42")).unwrap(); | |
| 539 | + | assert_eq!(odd.first().map(|g| g.action.as_str()), Some("fn-0x42")); | |
| 540 | + | assert!(decode_gestures(&hex("00 02 01 01 02 01")).is_err()); | |
| 541 | + | } | |
| 542 | + | } | |
| @@ -0,0 +1,363 @@ | |||
| 1 | + | //! Framing of the OPPO/OnePlus/realme protocol family. Spec: realme_t310.md#frame | |
| 2 | + | //! | |
| 3 | + | //! Holds no T310 tables. If a second model of this family is added, this file moves to | |
| 4 | + | //! `devices/oppo_family/` (CLAUDE.md, "Device plugin contract"). | |
| 5 | + | ||
| 6 | + | use crate::error::{Error, Result}; | |
| 7 | + | use crate::reader::Reader; | |
| 8 | + | ||
| 9 | + | /// Spec: realme_t310.md#frame | |
| 10 | + | const START: u8 = 0xAA; | |
| 11 | + | /// Spec: realme_t310.md#frame | |
| 12 | + | const WHOLE: u8 = 0x00; | |
| 13 | + | /// What the T310 puts in the slice byte of frames it starts itself (requests and pushes). The | |
| 14 | + | /// rest is laid out as a whole message. Spec: realme_t310.md#frame-from-buds | |
| 15 | + | const WHOLE_FROM_BUDS: u8 = 0x08; | |
| 16 | + | /// Spec: realme_t310.md#frame-slices | |
| 17 | + | const FIRST_SLICE: u8 = 0x01; | |
| 18 | + | /// Spec: realme_t310.md#frame-slices | |
| 19 | + | const MIDDLE_SLICE: u8 = 0x02; | |
| 20 | + | /// Spec: realme_t310.md#frame-slices | |
| 21 | + | const LAST_SLICE: u8 = 0x03; | |
| 22 | + | /// Bytes after the length in a whole frame, before the payload: slice, 00, cmd (2), seq, | |
| 23 | + | /// paylen (2). Spec: realme_t310.md#frame-whole | |
| 24 | + | const WHOLE_HEADER: usize = 7; | |
| 25 | + | /// Shortest slice frame: slice, 00, fsn, at least one byte. Spec: realme_t310.md#frame-receive | |
| 26 | + | const MIN_SLICE_LEN: usize = 4; | |
| 27 | + | /// Spec: realme_t310.md#frame-receive | |
| 28 | + | const MAX_LEN: usize = 4096; | |
| 29 | + | /// The length field is at most 3 bytes. Spec: realme_t310.md#frame-receive | |
| 30 | + | const MAX_LEN_BYTES: usize = 3; | |
| 31 | + | /// Senders slice messages that do not fit in this many bytes. budctl never slices, so it | |
| 32 | + | /// refuses to build a bigger frame. Spec: realme_t310.md#frame-slices | |
| 33 | + | const FRAME_BUDGET: usize = 660; | |
| 34 | + | ||
| 35 | + | /// One message: a command id, its sequence byte and its payload. | |
| 36 | + | #[derive(Debug, Clone, PartialEq, Eq)] | |
| 37 | + | pub(super) struct Frame { | |
| 38 | + | pub cmd: u16, | |
| 39 | + | pub seq: u8, | |
| 40 | + | pub payload: Vec<u8>, | |
| 41 | + | } | |
| 42 | + | ||
| 43 | + | /// One whole (unsliced) frame. Spec: realme_t310.md#frame-whole | |
| 44 | + | pub(super) fn encode(cmd: u16, seq: u8, payload: &[u8]) -> Result<Vec<u8>> { | |
| 45 | + | let too_big = || Error::Protocol(format!("a {} byte payload does not fit in one frame", payload.len())); | |
| 46 | + | let paylen = u16::try_from(payload.len()).map_err(|_| too_big())?; | |
| 47 | + | let mut frame = vec![START]; | |
| 48 | + | push_leb128(WHOLE_HEADER + payload.len(), &mut frame); | |
| 49 | + | frame.extend([WHOLE, 0x00]); | |
| 50 | + | frame.extend(cmd.to_le_bytes()); | |
| 51 | + | frame.push(seq); | |
| 52 | + | frame.extend(paylen.to_le_bytes()); | |
| 53 | + | frame.extend(payload); | |
| 54 | + | if frame.len() > FRAME_BUDGET { | |
| 55 | + | return Err(too_big()); | |
| 56 | + | } | |
| 57 | + | Ok(frame) | |
| 58 | + | } | |
| 59 | + | ||
| 60 | + | /// 7 bits per byte, low bits first; the top bit says another byte follows. | |
| 61 | + | fn push_leb128(mut value: usize, out: &mut Vec<u8>) { | |
| 62 | + | loop { | |
| 63 | + | let low = u8::try_from(value & 0x7F).unwrap_or_default(); | |
| 64 | + | value >>= 7; | |
| 65 | + | if value == 0 { | |
| 66 | + | out.push(low); | |
| 67 | + | return; | |
| 68 | + | } | |
| 69 | + | out.push(low | 0x80); | |
| 70 | + | } | |
| 71 | + | } | |
| 72 | + | ||
| 73 | + | enum Length { | |
| 74 | + | /// The length and how many bytes it took. | |
| 75 | + | Value(usize, usize), | |
| 76 | + | /// More bytes are needed to finish the length. | |
| 77 | + | Incomplete, | |
| 78 | + | /// Not a valid length: more than three bytes. | |
| 79 | + | Invalid, | |
| 80 | + | } | |
| 81 | + | ||
| 82 | + | fn read_leb128(bytes: &[u8]) -> Length { | |
| 83 | + | let mut value = 0; | |
| 84 | + | for (i, &byte) in bytes.iter().take(MAX_LEN_BYTES).enumerate() { | |
| 85 | + | value |= usize::from(byte & 0x7F) << (7 * i); | |
| 86 | + | if byte & 0x80 == 0 { | |
| 87 | + | return Length::Value(value, i + 1); | |
| 88 | + | } | |
| 89 | + | } | |
| 90 | + | if bytes.len() < MAX_LEN_BYTES { | |
| 91 | + | Length::Incomplete | |
| 92 | + | } else { | |
| 93 | + | Length::Invalid | |
| 94 | + | } | |
| 95 | + | } | |
| 96 | + | ||
| 97 | + | /// Turns the byte stream from the buds back into messages. Spec: realme_t310.md#frame-receive | |
| 98 | + | #[derive(Default)] | |
| 99 | + | pub(super) struct Reassembler { | |
| 100 | + | buffer: Vec<u8>, | |
| 101 | + | /// Parts of a sliced message received so far. | |
| 102 | + | sliced: Option<Vec<u8>>, | |
| 103 | + | /// Bytes thrown away while looking for a frame start (shown with `--debug`). | |
| 104 | + | discarded: usize, | |
| 105 | + | } | |
| 106 | + | ||
| 107 | + | impl Reassembler { | |
| 108 | + | pub(super) fn push(&mut self, bytes: &[u8]) { | |
| 109 | + | self.buffer.extend_from_slice(bytes); | |
| 110 | + | } | |
| 111 | + | ||
| 112 | + | /// How many bytes were discarded since the last call. | |
| 113 | + | pub(super) fn take_discarded(&mut self) -> usize { | |
| 114 | + | std::mem::take(&mut self.discarded) | |
| 115 | + | } | |
| 116 | + | ||
| 117 | + | /// The next complete message, if one is buffered. | |
| 118 | + | pub(super) fn next_frame(&mut self) -> Option<Frame> { | |
| 119 | + | loop { | |
| 120 | + | // Throw away everything before the next frame start. | |
| 121 | + | let start = self.buffer.iter().position(|&b| b == START); | |
| 122 | + | let skip = start.unwrap_or(self.buffer.len()); | |
| 123 | + | self.discarded += skip; | |
| 124 | + | self.buffer.drain(..skip); | |
| 125 | + | if self.buffer.is_empty() { | |
| 126 | + | return None; | |
| 127 | + | } | |
| 128 | + | ||
| 129 | + | let (len, len_bytes) = match read_leb128(self.buffer.get(1..).unwrap_or_default()) { | |
| 130 | + | Length::Value(len, len_bytes) => (len, len_bytes), | |
| 131 | + | Length::Incomplete => return None, | |
| 132 | + | Length::Invalid => { | |
| 133 | + | self.drop_start(); | |
| 134 | + | continue; | |
| 135 | + | } | |
| 136 | + | }; | |
| 137 | + | let &slice = self.buffer.get(1 + len_bytes)?; | |
| 138 | + | let min_len = if is_whole(slice) { WHOLE_HEADER } else { MIN_SLICE_LEN }; | |
| 139 | + | if len < min_len || len > MAX_LEN { | |
| 140 | + | self.drop_start(); | |
| 141 | + | continue; | |
| 142 | + | } | |
| 143 | + | ||
| 144 | + | let total = 1 + len_bytes + len; | |
| 145 | + | if self.buffer.len() < total { | |
| 146 | + | return None; | |
| 147 | + | } | |
| 148 | + | let body: Vec<u8> = self.buffer.drain(..total).skip(1 + len_bytes).collect(); | |
| 149 | + | if let Some(frame) = self.body(&body) { | |
| 150 | + | return Some(frame); | |
| 151 | + | } | |
| 152 | + | } | |
| 153 | + | } | |
| 154 | + | ||
| 155 | + | /// Drop a false frame start and search on. | |
| 156 | + | fn drop_start(&mut self) { | |
| 157 | + | self.buffer.drain(..1); | |
| 158 | + | self.discarded += 1; | |
| 159 | + | } | |
| 160 | + | ||
| 161 | + | /// Spec: realme_t310.md#frame, #frame-slices | |
| 162 | + | fn body(&mut self, body: &[u8]) -> Option<Frame> { | |
| 163 | + | let mut r = Reader::new(body, "frame"); | |
| 164 | + | let slice = r.u8().ok()?; | |
| 165 | + | let _zero = r.u8().ok()?; | |
| 166 | + | if is_whole(slice) { | |
| 167 | + | return parse_message(r.rest()); | |
| 168 | + | } | |
| 169 | + | let _slice_number = r.u8().ok()?; | |
| 170 | + | let part = r.rest(); | |
| 171 | + | match slice { | |
| 172 | + | FIRST_SLICE => self.sliced = Some(part.to_vec()), | |
| 173 | + | MIDDLE_SLICE => { | |
| 174 | + | if let Some(joined) = &mut self.sliced { | |
| 175 | + | joined.extend_from_slice(part); | |
| 176 | + | } | |
| 177 | + | } | |
| 178 | + | LAST_SLICE => { | |
| 179 | + | let mut joined = self.sliced.take()?; | |
| 180 | + | joined.extend_from_slice(part); | |
| 181 | + | return parse_message(&joined); | |
| 182 | + | } | |
| 183 | + | _ => {} | |
| 184 | + | } | |
| 185 | + | None | |
| 186 | + | } | |
| 187 | + | } | |
| 188 | + | ||
| 189 | + | /// Spec: realme_t310.md#frame-whole, #frame-from-buds | |
| 190 | + | fn is_whole(slice: u8) -> bool { | |
| 191 | + | slice == WHOLE || slice == WHOLE_FROM_BUDS | |
| 192 | + | } | |
| 193 | + | ||
| 194 | + | /// `cmd(2, LE) seq paylen(2, LE) payload`. A payload shorter than `paylen` is kept as it is. | |
| 195 | + | /// Spec: realme_t310.md#frame-receive | |
| 196 | + | fn parse_message(bytes: &[u8]) -> Option<Frame> { | |
| 197 | + | let mut r = Reader::new(bytes, "message"); | |
| 198 | + | let cmd = r.u16_le().ok()?; | |
| 199 | + | let seq = r.u8().ok()?; | |
| 200 | + | let paylen = usize::from(r.u16_le().ok()?); | |
| 201 | + | let rest = r.rest(); | |
| 202 | + | let payload = rest.get(..paylen).unwrap_or(rest).to_vec(); | |
| 203 | + | Some(Frame { cmd, seq, payload }) | |
| 204 | + | } | |
| 205 | + | ||
| 206 | + | #[cfg(test)] | |
| 207 | + | mod tests { | |
| 208 | + | use super::*; | |
| 209 | + | use crate::transport::mock::hex; | |
| 210 | + | ||
| 211 | + | fn frames(input: &[u8]) -> Vec<Frame> { | |
| 212 | + | let mut r = Reassembler::default(); | |
| 213 | + | r.push(input); | |
| 214 | + | std::iter::from_fn(|| r.next_frame()).collect() | |
| 215 | + | } | |
| 216 | + | ||
| 217 | + | fn frame(cmd: u16, seq: u8, payload: &str) -> Frame { | |
| 218 | + | Frame { | |
| 219 | + | cmd, | |
| 220 | + | seq, | |
| 221 | + | payload: hex(payload), | |
| 222 | + | } | |
| 223 | + | } | |
| 224 | + | ||
| 225 | + | // Vectors: realme_t310.md#frame-whole and #frame-long. | |
| 226 | + | ||
| 227 | + | #[test] | |
| 228 | + | fn encodes_the_documented_examples() { | |
| 229 | + | assert_eq!(encode(0x0100, 0x01, &[]).unwrap(), hex("AA 07 00 00 00 01 01 00 00")); | |
| 230 | + | assert_eq!( | |
| 231 | + | encode(0x0404, 0x06, &hex("01 01 01")).unwrap(), | |
| 232 | + | hex("AA 0A 00 00 04 04 06 03 00 01 01 01") | |
| 233 | + | ); | |
| 234 | + | } | |
| 235 | + | ||
| 236 | + | #[test] | |
| 237 | + | fn long_lengths_use_leb128() { | |
| 238 | + | let payload = vec![0u8; 124]; | |
| 239 | + | let encoded = encode(0x0418, 0x03, &payload).unwrap(); | |
| 240 | + | assert_eq!(encoded.get(..3), Some(&hex("AA 83 01")[..])); | |
| 241 | + | assert_eq!( | |
| 242 | + | frames(&encoded), | |
| 243 | + | vec![Frame { | |
| 244 | + | cmd: 0x0418, | |
| 245 | + | seq: 0x03, | |
| 246 | + | payload | |
| 247 | + | }] | |
| 248 | + | ); | |
| 249 | + | ||
| 250 | + | let mut reply = hex("AA 81 02 00 00 22 81 05 FA 00"); | |
| 251 | + | reply.extend(vec![0x11; 250]); | |
| 252 | + | let decoded = frames(&reply); | |
| 253 | + | assert_eq!(decoded.len(), 1); | |
| 254 | + | assert_eq!(decoded.first().map(|f| f.payload.len()), Some(250)); | |
| 255 | + | } | |
| 256 | + | ||
| 257 | + | #[test] | |
| 258 | + | fn refuses_frames_that_would_need_slicing() { | |
| 259 | + | assert!(encode(0x0418, 1, &[0; 700]).is_err()); | |
| 260 | + | } | |
| 261 | + | ||
| 262 | + | #[test] | |
| 263 | + | fn round_trips_every_payload_size() { | |
| 264 | + | for len in 0..=640 { | |
| 265 | + | let payload: Vec<u8> = (0..len).map(|i| u8::try_from(i % 251).unwrap()).collect(); | |
| 266 | + | let encoded = encode(0x0106, 0x42, &payload).unwrap(); | |
| 267 | + | assert_eq!( | |
| 268 | + | frames(&encoded), | |
| 269 | + | vec![Frame { | |
| 270 | + | cmd: 0x0106, | |
| 271 | + | seq: 0x42, | |
| 272 | + | payload | |
| 273 | + | }] | |
| 274 | + | ); | |
| 275 | + | } | |
| 276 | + | } | |
| 277 | + | ||
| 278 | + | #[test] | |
| 279 | + | fn decodes_a_push() { | |
| 280 | + | assert_eq!( | |
| 281 | + | frames(&hex("AA 0C 00 00 04 02 FF 05 00 03 01 01 08 00")), | |
| 282 | + | vec![frame(0x0204, 0xFF, "03 01 01 08 00")] | |
| 283 | + | ); | |
| 284 | + | } | |
| 285 | + | ||
| 286 | + | /// Captured on the owner's T310 (realme_t310.md#frame-from-buds): a reply and a request | |
| 287 | + | /// from the buds in one read, then an ack and a battery push in another. | |
| 288 | + | #[test] | |
| 289 | + | fn decodes_frames_the_buds_start() { | |
| 290 | + | assert_eq!( | |
| 291 | + | frames(&hex( | |
| 292 | + | "AA 10 00 00 00 81 01 09 00 00 BF 1F 5A 20 45 04 40 00 AA 07 08 00 01 05 0F 00 00" | |
| 293 | + | )), | |
| 294 | + | vec![ | |
| 295 | + | frame(0x8100, 0x01, "00 BF 1F 5A 20 45 04 40 00"), | |
| 296 | + | frame(0x0501, 0x0F, "") | |
| 297 | + | ] | |
| 298 | + | ); | |
| 299 | + | assert_eq!( | |
| 300 | + | frames(&hex( | |
| 301 | + | "AA 11 00 00 05 82 04 0A 00 00 04 01 00 02 00 03 00 04 00 AA 0F 08 00 04 02 10 08 00 01 03 02 64 01 64 03 00" | |
| 302 | + | )), | |
| 303 | + | vec![ | |
| 304 | + | frame(0x8205, 0x04, "00 04 01 00 02 00 03 00 04 00"), | |
| 305 | + | frame(0x0204, 0x10, "01 03 02 64 01 64 03 00") | |
| 306 | + | ] | |
| 307 | + | ); | |
| 308 | + | } | |
| 309 | + | ||
| 310 | + | #[test] | |
| 311 | + | fn splits_and_joins_reads() { | |
| 312 | + | let two = | |
| 313 | + | hex("AA 0D 00 00 04 02 FF 06 00 01 02 01 64 02 64 AA 0F 00 00 04 02 0C 08 00 02 03 01 07 02 07 03 04"); | |
| 314 | + | assert_eq!( | |
| 315 | + | frames(&two), | |
| 316 | + | vec![ | |
| 317 | + | frame(0x0204, 0xFF, "01 02 01 64 02 64"), | |
| 318 | + | frame(0x0204, 0x0C, "02 03 01 07 02 07 03 04") | |
| 319 | + | ] | |
| 320 | + | ); | |
| 321 | + | ||
| 322 | + | // The same bytes, one at a time. | |
| 323 | + | let mut r = Reassembler::default(); | |
| 324 | + | let mut out = Vec::new(); | |
| 325 | + | for byte in &two { | |
| 326 | + | r.push(&[*byte]); | |
| 327 | + | out.extend(std::iter::from_fn(|| r.next_frame())); | |
| 328 | + | } | |
| 329 | + | assert_eq!(out.len(), 2); | |
| 330 | + | } | |
| 331 | + | ||
| 332 | + | #[test] | |
| 333 | + | fn skips_noise_and_bad_lengths() { | |
| 334 | + | let real = "AA 0D 00 00 04 02 FF 06 00 01 02 01 64 02 64"; | |
| 335 | + | let mut r = Reassembler::default(); | |
| 336 | + | r.push(&hex(&format!("13 37 {real}"))); | |
| 337 | + | assert_eq!(r.next_frame(), Some(frame(0x0204, 0xFF, "01 02 01 64 02 64"))); | |
| 338 | + | assert_eq!(r.take_discarded(), 2); | |
| 339 | + | ||
| 340 | + | assert_eq!(frames(&hex(&format!("AA 80 80 80 {real}"))).len(), 1); | |
| 341 | + | assert!(frames(&hex("AA 00")).is_empty()); | |
| 342 | + | assert!(frames(&hex("AA 05 00 00 23 81 00")).is_empty()); | |
| 343 | + | } | |
| 344 | + | ||
| 345 | + | #[test] | |
| 346 | + | fn short_payload_is_cut_to_what_is_present() { | |
| 347 | + | assert_eq!( | |
| 348 | + | frames(&hex("AA 09 00 00 06 81 01 09 00 07 07")), | |
| 349 | + | vec![frame(0x8106, 0x01, "07 07")] | |
| 350 | + | ); | |
| 351 | + | } | |
| 352 | + | ||
| 353 | + | #[test] | |
| 354 | + | fn joins_slices_and_drops_orphans() { | |
| 355 | + | // cmd 0x8108, seq 05, paylen 4, payload 00 01 02 03, split in three slices. | |
| 356 | + | let sliced = hex("AA 07 01 00 00 08 81 05 04 AA 05 02 00 01 00 00 AA 06 03 00 02 01 02 03"); | |
| 357 | + | assert_eq!(frames(&sliced), vec![frame(0x8108, 0x05, "00 01 02 03")]); | |
| 358 | + | ||
| 359 | + | // A last slice with no first slice is dropped; the next whole frame still decodes. | |
| 360 | + | let orphan = hex("AA 06 03 00 02 00 02 03 AA 07 00 00 00 01 01 00 00"); | |
| 361 | + | assert_eq!(frames(&orphan), vec![frame(0x0100, 0x01, "")]); | |
| 362 | + | } | |
| 363 | + | } | |
| @@ -0,0 +1,221 @@ | |||
| 1 | + | //! Requests and replies over one link, for the OPPO/OnePlus/realme protocol family. | |
| 2 | + | //! Spec: realme_t310.md#seq, #buds-requests | |
| 3 | + | //! | |
| 4 | + | //! Holds no T310 tables. If a second model of this family is added, this file moves to | |
| 5 | + | //! `devices/oppo_family/` together with `frame.rs`. | |
| 6 | + | ||
| 7 | + | use std::time::{Duration, Instant}; | |
| 8 | + | ||
| 9 | + | use super::frame::{self, Frame, Reassembler}; | |
| 10 | + | use crate::debug; | |
| 11 | + | use crate::error::{Error, Result}; | |
| 12 | + | use crate::transport::Transport; | |
| 13 | + | ||
| 14 | + | /// A reply's command id is the request's with this bit set. Spec: realme_t310.md#seq | |
| 15 | + | const REPLY: u16 = 0x8000; | |
| 16 | + | /// budctl's sequence numbers. Spec: realme_t310.md#seq | |
| 17 | + | const FIRST_SEQ: u8 = 0x01; | |
| 18 | + | /// Spec: realme_t310.md#seq | |
| 19 | + | const LAST_SEQ: u8 = 0xBF; | |
| 20 | + | /// At least this long between two frames budctl sends. Spec: realme_t310.md#init | |
| 21 | + | const SEND_GAP: Duration = Duration::from_millis(200); | |
| 22 | + | /// How long to wait for a reply. | |
| 23 | + | const REPLY_TIMEOUT: Duration = Duration::from_secs(3); | |
| 24 | + | ||
| 25 | + | /// Spec: realme_t310.md#time-request | |
| 26 | + | const TIME_REQUEST: u16 = 0x0500; | |
| 27 | + | /// Spec: realme_t310.md#buds-requests | |
| 28 | + | const APP_LIST_REQUEST: u16 = 0x050C; | |
| 29 | + | /// Spec: realme_t310.md#buds-requests | |
| 30 | + | const APP_LIST_ANSWER: &[u8] = &[0x00, 0x01, 0x00]; | |
| 31 | + | /// Spec: realme_t310.md#buds-requests | |
| 32 | + | const CAPABILITIES_REQUEST: u16 = 0x051C; | |
| 33 | + | /// Spec: realme_t310.md#buds-requests | |
| 34 | + | const CAPABILITIES_ANSWER: &[u8] = &[0x00, 0x00, 0x00]; | |
| 35 | + | /// Spec: realme_t310.md#buds-requests | |
| 36 | + | const SPATIAL_MODE_REQUEST: u16 = 0x051D; | |
| 37 | + | /// Spec: realme_t310.md#buds-requests | |
| 38 | + | const SPATIAL_MODE_ANSWER: &[u8] = &[0x01]; | |
| 39 | + | /// Command groups the buds use; a request outside them gets `UNKNOWN_ANSWER`. | |
| 40 | + | /// Spec: realme_t310.md#seq, #buds-requests | |
| 41 | + | const KNOWN_GROUPS: [u16; 6] = [0x01, 0x02, 0x03, 0x04, 0x05, 0x0F]; | |
| 42 | + | /// Spec: realme_t310.md#buds-requests | |
| 43 | + | const UNKNOWN_ANSWER: &[u8] = &[0x01]; | |
| 44 | + | ||
| 45 | + | pub(super) struct Link { | |
| 46 | + | transport: Box<dyn Transport>, | |
| 47 | + | frames: Reassembler, | |
| 48 | + | next_seq: u8, | |
| 49 | + | last_send: Option<Instant>, | |
| 50 | + | /// Unix time in seconds, for the buds' time request. Replaced in tests. | |
| 51 | + | clock: fn() -> u32, | |
| 52 | + | } | |
| 53 | + | ||
| 54 | + | impl Link { | |
| 55 | + | pub(super) fn new(transport: Box<dyn Transport>, clock: fn() -> u32) -> Self { | |
| 56 | + | Self { | |
| 57 | + | transport, | |
| 58 | + | frames: Reassembler::default(), | |
| 59 | + | next_seq: FIRST_SEQ, | |
| 60 | + | last_send: None, | |
| 61 | + | clock, | |
| 62 | + | } | |
| 63 | + | } | |
| 64 | + | ||
| 65 | + | /// Handle whatever the buds send until `deadline`, answering their requests. | |
| 66 | + | /// This is how budctl waits: never with a plain sleep. | |
| 67 | + | pub(super) fn pump_until(&mut self, deadline: Instant) -> Result<()> { | |
| 68 | + | while let Some(frame) = self.next_frame(deadline)? { | |
| 69 | + | self.handle_unsolicited(frame)?; | |
| 70 | + | } | |
| 71 | + | Ok(()) | |
| 72 | + | } | |
| 73 | + | ||
| 74 | + | /// Send a request and return the payload of its reply. | |
| 75 | + | pub(super) fn request(&mut self, cmd: u16, payload: &[u8]) -> Result<Vec<u8>> { | |
| 76 | + | let seq = self.send(cmd, payload)?; | |
| 77 | + | let deadline = Instant::now() + REPLY_TIMEOUT; | |
| 78 | + | loop { | |
| 79 | + | match self.next_frame(deadline)? { | |
| 80 | + | None => return Err(Error::Timeout(format!("no reply to command 0x{cmd:04X}"))), | |
| 81 | + | Some(frame) if frame.cmd == cmd | REPLY && frame.seq == seq => return Ok(frame.payload), | |
| 82 | + | Some(frame) => self.handle_unsolicited(frame)?, | |
| 83 | + | } | |
| 84 | + | } | |
| 85 | + | } | |
| 86 | + | ||
| 87 | + | /// Send a request without waiting for its reply. A reply that comes later is skipped. | |
| 88 | + | pub(super) fn send(&mut self, cmd: u16, payload: &[u8]) -> Result<u8> { | |
| 89 | + | if let Some(last) = self.last_send { | |
| 90 | + | self.pump_until(last + SEND_GAP)?; | |
| 91 | + | } | |
| 92 | + | let seq = self.next_seq; | |
| 93 | + | self.next_seq = if seq >= LAST_SEQ { FIRST_SEQ } else { seq + 1 }; | |
| 94 | + | debug::note(|| format!("send 0x{cmd:04X} seq {seq:02X} [{}]", debug::hex(payload))); | |
| 95 | + | self.transport.send(&frame::encode(cmd, seq, payload)?)?; | |
| 96 | + | self.last_send = Some(Instant::now()); | |
| 97 | + | Ok(seq) | |
| 98 | + | } | |
| 99 | + | ||
| 100 | + | fn next_frame(&mut self, deadline: Instant) -> Result<Option<Frame>> { | |
| 101 | + | loop { | |
| 102 | + | if let Some(frame) = self.frames.next_frame() { | |
| 103 | + | debug::note(|| { | |
| 104 | + | format!( | |
| 105 | + | "recv 0x{:04X} seq {:02X} [{}]", | |
| 106 | + | frame.cmd, | |
| 107 | + | frame.seq, | |
| 108 | + | debug::hex(&frame.payload) | |
| 109 | + | ) | |
| 110 | + | }); | |
| 111 | + | return Ok(Some(frame)); | |
| 112 | + | } | |
| 113 | + | let discarded = self.frames.take_discarded(); | |
| 114 | + | if discarded > 0 { | |
| 115 | + | debug::note(|| format!("discarded {discarded} bytes that were not a frame")); | |
| 116 | + | } | |
| 117 | + | match self.transport.recv(deadline)? { | |
| 118 | + | Some(bytes) => self.frames.push(&bytes), | |
| 119 | + | None => return Ok(None), | |
| 120 | + | } | |
| 121 | + | } | |
| 122 | + | } | |
| 123 | + | ||
| 124 | + | /// A frame nobody is waiting for: answer it if the buds expect an answer, else skip it. | |
| 125 | + | /// Spec: realme_t310.md#buds-requests, #pushes | |
| 126 | + | fn handle_unsolicited(&mut self, frame: Frame) -> Result<()> { | |
| 127 | + | if frame.cmd & REPLY != 0 { | |
| 128 | + | debug::note(|| format!("skipping late reply 0x{:04X}", frame.cmd)); | |
| 129 | + | return Ok(()); | |
| 130 | + | } | |
| 131 | + | let answer = match frame.cmd { | |
| 132 | + | TIME_REQUEST => { | |
| 133 | + | let mut answer = vec![0x00]; | |
| 134 | + | answer.extend((self.clock)().to_le_bytes()); | |
| 135 | + | answer | |
| 136 | + | } | |
| 137 | + | APP_LIST_REQUEST => APP_LIST_ANSWER.to_vec(), | |
| 138 | + | CAPABILITIES_REQUEST => CAPABILITIES_ANSWER.to_vec(), | |
| 139 | + | SPATIAL_MODE_REQUEST => SPATIAL_MODE_ANSWER.to_vec(), | |
| 140 | + | cmd if !KNOWN_GROUPS.contains(&(cmd >> 8)) => UNKNOWN_ANSWER.to_vec(), | |
| 141 | + | _ => return Ok(()), // pushes and messages that need no answer | |
| 142 | + | }; | |
| 143 | + | debug::note(|| format!("answer 0x{:04X} with [{}]", frame.cmd, debug::hex(&answer))); | |
| 144 | + | // Answered at once: some firmware drops the link when this takes too long. | |
| 145 | + | self.transport | |
| 146 | + | .send(&frame::encode(frame.cmd | REPLY, frame.seq, &answer)?) | |
| 147 | + | } | |
| 148 | + | } | |
| 149 | + | ||
| 150 | + | #[cfg(test)] | |
| 151 | + | mod tests { | |
| 152 | + | use super::*; | |
| 153 | + | use crate::transport::mock::{Script, Step, hex}; | |
| 154 | + | ||
| 155 | + | fn fixed_clock() -> u32 { | |
| 156 | + | 1_750_000_000 | |
| 157 | + | } | |
| 158 | + | ||
| 159 | + | #[test] | |
| 160 | + | fn answers_the_time_request_while_waiting() { | |
| 161 | + | // Vector: realme_t310.md#buds-requests | |
| 162 | + | let script = Script::new(vec![ | |
| 163 | + | Step::Tx(hex("AA 07 00 00 06 01 01 00 00")), | |
| 164 | + | Step::Rx(hex("AA 07 00 00 00 05 02 00 00")), | |
| 165 | + | Step::Tx(hex("AA 0C 00 00 00 85 02 05 00 00 80 E1 4E 68")), | |
| 166 | + | Step::Rx(hex("AA 0A 00 00 06 81 01 03 00 00 01 01")), | |
| 167 | + | ]); | |
| 168 | + | let mut link = Link::new(script.transport(), fixed_clock); | |
| 169 | + | assert_eq!(link.request(0x0106, &[]).unwrap(), hex("00 01 01")); | |
| 170 | + | script.assert_done(); | |
| 171 | + | } | |
| 172 | + | ||
| 173 | + | #[test] | |
| 174 | + | fn skips_pushes_and_stale_replies() { | |
| 175 | + | let script = Script::new(vec![ | |
| 176 | + | Step::Tx(hex("AA 07 00 00 06 01 01 00 00")), | |
| 177 | + | Step::Rx(hex("AA 0C 00 00 04 02 FF 05 00 03 01 01 08 00")), | |
| 178 | + | Step::Rx(hex("AA 08 00 00 06 81 77 01 00 00")), | |
| 179 | + | Step::Rx(hex("AA 08 00 00 06 81 01 01 00 00")), | |
| 180 | + | ]); | |
| 181 | + | let mut link = Link::new(script.transport(), fixed_clock); | |
| 182 | + | assert_eq!(link.request(0x0106, &[]).unwrap(), hex("00")); | |
| 183 | + | script.assert_done(); | |
| 184 | + | } | |
| 185 | + | ||
| 186 | + | #[test] | |
| 187 | + | fn unknown_requests_get_the_unknown_answer() { | |
| 188 | + | let script = Script::new(vec![ | |
| 189 | + | Step::Rx(hex("AA 07 00 00 34 12 09 00 00")), | |
| 190 | + | Step::Tx(hex("AA 08 00 00 34 92 09 01 00 01")), | |
| 191 | + | ]); | |
| 192 | + | let mut link = Link::new(script.transport(), fixed_clock); | |
| 193 | + | link.pump_until(Instant::now()).unwrap(); | |
| 194 | + | script.assert_done(); | |
| 195 | + | } | |
| 196 | + | ||
| 197 | + | #[test] | |
| 198 | + | fn silence_is_a_timeout_and_a_drop_is_not_connected() { | |
| 199 | + | let script = Script::new(vec![Step::Tx(hex("AA 07 00 00 06 01 01 00 00"))]); | |
| 200 | + | let mut link = Link::new(script.transport(), fixed_clock); | |
| 201 | + | assert!(matches!(link.request(0x0106, &[]), Err(Error::Timeout(_)))); | |
| 202 | + | ||
| 203 | + | let script = Script::new(vec![Step::Tx(hex("AA 07 00 00 06 01 01 00 00")), Step::Close]); | |
| 204 | + | let mut link = Link::new(script.transport(), fixed_clock); | |
| 205 | + | assert!(matches!(link.request(0x0106, &[]), Err(Error::NotConnected(_)))); | |
| 206 | + | } | |
| 207 | + | ||
| 208 | + | #[test] | |
| 209 | + | fn sequence_numbers_wrap_inside_budctls_range() { | |
| 210 | + | let mut steps = Vec::new(); | |
| 211 | + | for seq in (FIRST_SEQ..=LAST_SEQ).chain([FIRST_SEQ]) { | |
| 212 | + | steps.push(Step::Tx(frame::encode(0x0100, seq, &[]).unwrap())); | |
| 213 | + | } | |
| 214 | + | let script = Script::new(steps); | |
| 215 | + | let mut link = Link::new(script.transport(), fixed_clock); | |
| 216 | + | for _ in FIRST_SEQ..=LAST_SEQ + 1 { | |
| 217 | + | link.send(0x0100, &[]).unwrap(); | |
| 218 | + | } | |
| 219 | + | script.assert_done(); | |
| 220 | + | } | |
| 221 | + | } | |
| @@ -0,0 +1,412 @@ | |||
| 1 | + | //! realme Buds T310. Spec: docs/protocol/realme_t310.md | |
| 2 | + | //! | |
| 3 | + | //! `frame.rs` and `link.rs` hold the protocol family's framing and request/reply logic; | |
| 4 | + | //! `codec.rs` holds everything specific to the T310. | |
| 5 | + | ||
| 6 | + | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; | |
| 7 | + | ||
| 8 | + | use crate::bluez::PairedDevice; | |
| 9 | + | use crate::bt::Uuid; | |
| 10 | + | use crate::devices::{Device, Session}; | |
| 11 | + | use crate::error::{Error, Kind, Result}; | |
| 12 | + | use crate::status::{Status, TouchControls}; | |
| 13 | + | use crate::transport::Transport; | |
| 14 | + | ||
| 15 | + | mod codec; | |
| 16 | + | mod frame; | |
| 17 | + | mod link; | |
| 18 | + | ||
| 19 | + | use codec::Commands; | |
| 20 | + | use link::Link; | |
| 21 | + | ||
| 22 | + | /// Spec: realme_t310.md#identity | |
| 23 | + | const BLUETOOTH_NAME: &str = "realme Buds T310"; | |
| 24 | + | ||
| 25 | + | /// Control services, in the order to try. Spec: realme_t310.md#transport | |
| 26 | + | const SERVICES: [Uuid; 2] = [ | |
| 27 | + | Uuid::from_u128(0x0000_079A_D102_11E1_9B23_0002_5B00_A5A5), | |
| 28 | + | Uuid::from_u128(0x0000_1107_D102_11E1_9B23_0002_5B00_A5A5), | |
| 29 | + | ]; | |
| 30 | + | ||
| 31 | + | /// Quiet time after connecting, before the first request. Spec: realme_t310.md#init | |
| 32 | + | const SETTLE: Duration = Duration::from_millis(300); | |
| 33 | + | ||
| 34 | + | pub struct RealmeT310; | |
| 35 | + | ||
| 36 | + | impl Device for RealmeT310 { | |
| 37 | + | fn name(&self) -> &'static str { | |
| 38 | + | BLUETOOTH_NAME | |
| 39 | + | } | |
| 40 | + | ||
| 41 | + | fn matches(&self, device: &PairedDevice) -> bool { | |
| 42 | + | device.name == BLUETOOTH_NAME | |
| 43 | + | } | |
| 44 | + | ||
| 45 | + | fn rfcomm_uuids(&self) -> &'static [Uuid] { | |
| 46 | + | &SERVICES | |
| 47 | + | } | |
| 48 | + | ||
| 49 | + | fn open(&self, transport: Box<dyn Transport>) -> Result<Box<dyn Session>> { | |
| 50 | + | Ok(Box::new(T310Session::open(Link::new(transport, unix_time))?)) | |
| 51 | + | } | |
| 52 | + | } | |
| 53 | + | ||
| 54 | + | fn unix_time() -> u32 { | |
| 55 | + | let seconds = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()); | |
| 56 | + | u32::try_from(seconds).unwrap_or(u32::MAX) | |
| 57 | + | } | |
| 58 | + | ||
| 59 | + | struct T310Session { | |
| 60 | + | link: Link, | |
| 61 | + | commands: Commands, | |
| 62 | + | } | |
| 63 | + | ||
| 64 | + | /// Collects what a series of best-effort reads produced. | |
| 65 | + | #[derive(Default)] | |
| 66 | + | struct Reads { | |
| 67 | + | warnings: Vec<String>, | |
| 68 | + | answered: usize, | |
| 69 | + | } | |
| 70 | + | ||
| 71 | + | impl T310Session { | |
| 72 | + | /// The session start. Spec: realme_t310.md#init | |
| 73 | + | fn open(mut link: Link) -> Result<Self> { | |
| 74 | + | link.pump_until(Instant::now() + SETTLE)?; | |
| 75 | + | ||
| 76 | + | let bitmap = link.request(codec::HANDSHAKE, &[]).map_err(|error| match error { | |
| 77 | + | // Provisional until checkpoint HW1: a link that connects but stays silent is most | |
| 78 | + | // likely held by another app. Spec: realme_t310.md#open | |
| 79 | + | Error::Timeout(_) => Error::ChannelBusy("connected, but the buds did not answer the handshake".to_owned()), | |
| 80 | + | other => other, | |
| 81 | + | })?; | |
| 82 | + | let commands = Commands::parse(&bitmap)?; | |
| 83 | + | ||
| 84 | + | let product = codec::decode_product_id(&link.request(codec::PRODUCT_ID, &[])?)?; | |
| 85 | + | if product != codec::T310_PRODUCT_ID { | |
| 86 | + | return Err(Error::WrongModel { | |
| 87 | + | expected: BLUETOOTH_NAME, | |
| 88 | + | found: format!("{product:06X}"), | |
| 89 | + | }); | |
| 90 | + | } | |
| 91 | + | ||
| 92 | + | let offered = codec::decode_events_offered(&link.request(codec::EVENTS_OFFERED, &[])?)?; | |
| 93 | + | let subscription = codec::subscribe_payload(&offered, &commands); | |
| 94 | + | if commands.allows(codec::SUBSCRIBE) && subscription.len() > 1 { | |
| 95 | + | // Some buds never acknowledge this, so budctl does not wait. Spec: realme_t310.md#subscribe | |
| 96 | + | link.send(codec::SUBSCRIBE, &subscription)?; | |
| 97 | + | } | |
| 98 | + | Ok(Self { link, commands }) | |
| 99 | + | } | |
| 100 | + | ||
| 101 | + | /// Read and decode one value, if the buds offer the command. A read the buds answer badly | |
| 102 | + | /// (timeout, refusal, garbage) becomes a warning so the rest still shows; a lost link stops | |
| 103 | + | /// everything. | |
| 104 | + | fn read<T>( | |
| 105 | + | &mut self, | |
| 106 | + | reads: &mut Reads, | |
| 107 | + | what: &str, | |
| 108 | + | cmd: u16, | |
| 109 | + | payload: &[u8], | |
| 110 | + | decode: fn(&[u8]) -> Result<T>, | |
| 111 | + | ) -> Result<Option<T>> { | |
| 112 | + | if !self.commands.allows(cmd) { | |
| 113 | + | return Ok(None); | |
| 114 | + | } | |
| 115 | + | match self.link.request(cmd, payload).and_then(|reply| decode(&reply)) { | |
| 116 | + | Ok(value) => { | |
| 117 | + | reads.answered += 1; | |
| 118 | + | Ok(Some(value)) | |
| 119 | + | } | |
| 120 | + | Err(error) if error.kind() == Kind::Failed => { | |
| 121 | + | reads.warnings.push(format!("{what}: {error}")); | |
| 122 | + | Ok(None) | |
| 123 | + | } | |
| 124 | + | Err(error) => Err(error), | |
| 125 | + | } | |
| 126 | + | } | |
| 127 | + | } | |
| 128 | + | ||
| 129 | + | impl Session for T310Session { | |
| 130 | + | fn status(&mut self) -> Result<Status> { | |
| 131 | + | let mut reads = Reads::default(); | |
| 132 | + | let switches = self.read( | |
| 133 | + | &mut reads, | |
| 134 | + | "switches", | |
| 135 | + | codec::SWITCHES, | |
| 136 | + | &codec::SWITCH_QUERY, | |
| 137 | + | codec::decode_switches, | |
| 138 | + | )?; | |
| 139 | + | let noise_control = self.read( | |
| 140 | + | &mut reads, | |
| 141 | + | "noise control", | |
| 142 | + | codec::NOISE_CONTROL, | |
| 143 | + | &codec::NOISE_MODE_QUERY, | |
| 144 | + | codec::decode_noise_mode, | |
| 145 | + | )?; | |
| 146 | + | let battery = self.read(&mut reads, "battery", codec::BATTERY, &[], codec::decode_battery)?; | |
| 147 | + | let eq = self.read(&mut reads, "EQ", codec::EQ_PRESET, &[], codec::decode_eq)?; | |
| 148 | + | // No bass-level read: the T310 does not answer an empty 0x0124 (HW1). It returns with W6. | |
| 149 | + | // Spec: realme_t310.md#bass-read | |
| 150 | + | let codec = self.read(&mut reads, "codec", codec::CODEC, &[], codec::decode_codec)?; | |
| 151 | + | let firmware = self.read(&mut reads, "firmware", codec::FIRMWARE, &[], codec::decode_firmware)?; | |
| 152 | + | ||
| 153 | + | if reads.answered == 0 && !reads.warnings.is_empty() { | |
| 154 | + | return Err(Error::Timeout(reads.warnings.join("; "))); | |
| 155 | + | } | |
| 156 | + | Ok(Status { | |
| 157 | + | battery: battery.unwrap_or_default(), | |
| 158 | + | noise_control, | |
| 159 | + | eq, | |
| 160 | + | bass_level: None, | |
| 161 | + | switches: switches.unwrap_or_default(), | |
| 162 | + | codec, | |
| 163 | + | firmware, | |
| 164 | + | warnings: reads.warnings, | |
| 165 | + | }) | |
| 166 | + | } | |
| 167 | + | ||
| 168 | + | fn touch_controls(&mut self) -> Result<TouchControls> { | |
| 169 | + | if !self.commands.allows(codec::GESTURES) { | |
| 170 | + | return Err(Error::Unsupported( | |
| 171 | + | "these buds do not offer touch-control settings".to_owned(), | |
| 172 | + | )); | |
| 173 | + | } | |
| 174 | + | let gestures = codec::decode_gestures(&self.link.request(codec::GESTURES, &[])?)?; | |
| 175 | + | let mut reads = Reads::default(); | |
| 176 | + | let hold_cycle = self.read( | |
| 177 | + | &mut reads, | |
| 178 | + | "hold cycle", | |
| 179 | + | codec::NOISE_CONTROL, | |
| 180 | + | &codec::HOLD_CYCLE_QUERY, | |
| 181 | + | codec::decode_hold_cycle, | |
| 182 | + | )?; | |
| 183 | + | Ok(TouchControls { | |
| 184 | + | gestures, | |
| 185 | + | hold_cycle, | |
| 186 | + | warnings: reads.warnings, | |
| 187 | + | }) | |
| 188 | + | } | |
| 189 | + | } | |
| 190 | + | ||
| 191 | + | #[cfg(test)] | |
| 192 | + | mod tests { | |
| 193 | + | use super::*; | |
| 194 | + | use crate::status::Charge; | |
| 195 | + | use crate::transport::mock::{Script, Step, hex}; | |
| 196 | + | ||
| 197 | + | fn tx(cmd: u16, seq: u8, payload: &str) -> Step { | |
| 198 | + | Step::Tx(frame::encode(cmd, seq, &hex(payload)).unwrap()) | |
| 199 | + | } | |
| 200 | + | ||
| 201 | + | fn rx(cmd: u16, seq: u8, payload: &str) -> Step { | |
| 202 | + | Step::Rx(frame::encode(cmd, seq, &hex(payload)).unwrap()) | |
| 203 | + | } | |
| 204 | + | ||
| 205 | + | fn fixed_clock() -> u32 { | |
| 206 | + | 1_750_000_000 | |
| 207 | + | } | |
| 208 | + | ||
| 209 | + | fn open(script: &Script) -> Result<T310Session> { | |
| 210 | + | T310Session::open(Link::new(script.transport(), fixed_clock)) | |
| 211 | + | } | |
| 212 | + | ||
| 213 | + | /// The handshake of the owner's T310 (HW1); seq 01-04 are used up. | |
| 214 | + | fn handshake() -> Vec<Step> { | |
| 215 | + | vec![ | |
| 216 | + | tx(0x0100, 0x01, ""), | |
| 217 | + | rx(0x8100, 0x01, codec::T310_BITMAP_REPLY), | |
| 218 | + | tx(0x0103, 0x02, ""), | |
| 219 | + | rx(0x8103, 0x02, "00 12 3C 06"), | |
| 220 | + | tx(0x0200, 0x03, ""), | |
| 221 | + | rx(0x8200, 0x03, "00 09 01 02 03 04 05 06 0D F1 F4"), | |
| 222 | + | tx(0x0205, 0x04, "04 01 02 03 04"), | |
| 223 | + | rx(0x8205, 0x04, "00 04 01 00 02 00 03 00 04 00"), | |
| 224 | + | ] | |
| 225 | + | } | |
| 226 | + | ||
| 227 | + | #[test] | |
| 228 | + | fn full_status() { | |
| 229 | + | let mut steps = handshake(); | |
| 230 | + | let mut firmware = String::from("00 03"); | |
| 231 | + | for byte in b"1,2,120,2,2,120,3,2,105" { | |
| 232 | + | firmware.push_str(&format!(" {byte:02X}")); | |
| 233 | + | } | |
| 234 | + | steps.extend([ | |
| 235 | + | tx(0x010D, 0x05, "06 05 06 11 1A 1B 1D"), | |
| 236 | + | rx(0x810D, 0x05, "00 06 05 00 06 00 11 01 1A 00 1B 01 1D 01"), | |
| 237 | + | tx(0x010C, 0x06, "01 01"), | |
| 238 | + | rx(0x810C, 0x06, "00 01 01 08"), | |
| 239 | + | tx(0x0106, 0x07, ""), | |
| 240 | + | rx(0x8106, 0x07, "00 03 01 50 02 E4 03 3C"), | |
| 241 | + | tx(0x010F, 0x08, ""), | |
| 242 | + | rx(0x810F, 0x08, "00 01"), | |
| 243 | + | tx(0x0114, 0x09, ""), | |
| 244 | + | rx(0x8114, 0x09, "00 02"), | |
| 245 | + | tx(0x0105, 0x0A, ""), | |
| 246 | + | rx(0x8105, 0x0A, &firmware), | |
| 247 | + | ]); | |
| 248 | + | let script = Script::new(steps); | |
| 249 | + | let status = open(&script).unwrap().status().unwrap(); | |
| 250 | + | script.assert_done(); | |
| 251 | + | ||
| 252 | + | assert_eq!( | |
| 253 | + | status.battery.left, | |
| 254 | + | Some(Charge { | |
| 255 | + | level: 80, | |
| 256 | + | charging: false | |
| 257 | + | }) | |
| 258 | + | ); | |
| 259 | + | assert_eq!( | |
| 260 | + | status.battery.right, | |
| 261 | + | Some(Charge { | |
| 262 | + | level: 100, | |
| 263 | + | charging: true | |
| 264 | + | }) | |
| 265 | + | ); | |
| 266 | + | assert_eq!( | |
| 267 | + | status.battery.case, | |
| 268 | + | Some(Charge { | |
| 269 | + | level: 60, | |
| 270 | + | charging: false | |
| 271 | + | }) | |
| 272 | + | ); | |
| 273 | + | let noise = status.noise_control.unwrap(); | |
| 274 | + | assert_eq!((noise.mode.as_str(), noise.level.as_deref()), ("anc", Some("deep"))); | |
| 275 | + | assert_eq!(status.eq.as_deref(), Some("deep-bass")); | |
| 276 | + | assert_eq!(status.bass_level, None); | |
| 277 | + | assert_eq!(status.codec.as_deref(), Some("AAC")); | |
| 278 | + | assert_eq!(status.firmware.as_deref(), Some("120.120.105")); | |
| 279 | + | let game = status.switches.iter().find(|s| s.key == "game").unwrap(); | |
| 280 | + | assert!(!game.on); | |
| 281 | + | assert_eq!(status.switches.len(), 5); | |
| 282 | + | assert!(status.warnings.is_empty()); | |
| 283 | + | } | |
| 284 | + | ||
| 285 | + | #[test] | |
| 286 | + | fn answers_the_time_request_during_the_settle() { | |
| 287 | + | let mut steps = vec![ | |
| 288 | + | rx(0x0500, 0x01, ""), | |
| 289 | + | Step::Tx(hex("AA 0C 00 00 00 85 01 05 00 00 80 E1 4E 68")), | |
| 290 | + | ]; | |
| 291 | + | steps.extend(handshake()); | |
| 292 | + | // No 0x8205 ack this time: it may never arrive, and `open` does not wait for it. | |
| 293 | + | // Spec: realme_t310.md#subscribe | |
| 294 | + | steps.pop(); | |
| 295 | + | let script = Script::new(steps); | |
| 296 | + | open(&script).unwrap(); | |
| 297 | + | script.assert_done(); | |
| 298 | + | } | |
| 299 | + | ||
| 300 | + | #[test] | |
| 301 | + | fn a_silent_handshake_reports_a_busy_channel() { | |
| 302 | + | let script = Script::new(vec![tx(0x0100, 0x01, "")]); | |
| 303 | + | assert!(matches!(open(&script), Err(Error::ChannelBusy(_)))); | |
| 304 | + | } | |
| 305 | + | ||
| 306 | + | #[test] | |
| 307 | + | fn other_models_are_refused() { | |
| 308 | + | let script = Script::new(vec![ | |
| 309 | + | tx(0x0100, 0x01, ""), | |
| 310 | + | rx(0x8100, 0x01, codec::T310_BITMAP_REPLY), | |
| 311 | + | tx(0x0103, 0x02, ""), | |
| 312 | + | rx(0x8103, 0x02, "00 14 54 06"), | |
| 313 | + | ]); | |
| 314 | + | match open(&script) { | |
| 315 | + | Err(Error::WrongModel { found, .. }) => assert_eq!(found, "065414"), | |
| 316 | + | other => panic!("expected WrongModel, got {:?}", other.err()), | |
| 317 | + | } | |
| 318 | + | } | |
| 319 | + | ||
| 320 | + | #[test] | |
| 321 | + | fn commands_missing_from_the_bitmap_are_never_sent() { | |
| 322 | + | // A bitmap with no bits: only always-allowed commands go out, and no subscription. | |
| 323 | + | let script = Script::new(vec![ | |
| 324 | + | tx(0x0100, 0x01, ""), | |
| 325 | + | rx(0x8100, 0x01, "00"), | |
| 326 | + | tx(0x0103, 0x02, ""), | |
| 327 | + | rx(0x8103, 0x02, "00 12 3C 06"), | |
| 328 | + | tx(0x0200, 0x03, ""), | |
| 329 | + | rx(0x8200, 0x03, "00 02 01 02"), | |
| 330 | + | tx(0x010D, 0x04, "06 05 06 11 1A 1B 1D"), | |
| 331 | + | rx(0x810D, 0x04, "00 01 06 01"), | |
| 332 | + | tx(0x0106, 0x05, ""), | |
| 333 | + | // no battery reply: becomes a warning | |
| 334 | + | ]); | |
| 335 | + | let status = open(&script).unwrap().status().unwrap(); | |
| 336 | + | script.assert_done(); | |
| 337 | + | assert_eq!(status.switches.len(), 1); | |
| 338 | + | assert!(status.noise_control.is_none() && status.firmware.is_none()); | |
| 339 | + | assert_eq!(status.warnings.len(), 1); | |
| 340 | + | assert!(status.warnings.first().unwrap().starts_with("battery")); | |
| 341 | + | } | |
| 342 | + | ||
| 343 | + | #[test] | |
| 344 | + | fn a_lost_link_stops_the_status() { | |
| 345 | + | let mut steps = handshake(); | |
| 346 | + | steps.extend([tx(0x010D, 0x05, "06 05 06 11 1A 1B 1D"), Step::Close]); | |
| 347 | + | let script = Script::new(steps); | |
| 348 | + | assert!(matches!(open(&script).unwrap().status(), Err(Error::NotConnected(_)))); | |
| 349 | + | } | |
| 350 | + | ||
| 351 | + | #[test] | |
| 352 | + | fn touch_controls_and_hold_cycle() { | |
| 353 | + | let mut steps = handshake(); | |
| 354 | + | steps.extend([ | |
| 355 | + | tx(0x0108, 0x05, ""), | |
| 356 | + | rx(0x8108, 0x05, "00 02 01 01 02 01 02 01 04 08"), | |
| 357 | + | tx(0x010C, 0x06, "02 01"), | |
| 358 | + | rx(0x810C, 0x06, "00 02 01 0A"), | |
| 359 | + | ]); | |
| 360 | + | let script = Script::new(steps); | |
| 361 | + | let touch = open(&script).unwrap().touch_controls().unwrap(); | |
| 362 | + | script.assert_done(); | |
| 363 | + | assert_eq!(touch.gestures.len(), 2); | |
| 364 | + | assert_eq!(touch.hold_cycle.unwrap(), ["transparency", "anc"]); | |
| 365 | + | } | |
| 366 | + | ||
| 367 | + | /// The owner's `budctl --debug touch` (HW1), byte for byte. The buds' own frames (slice | |
| 368 | + | /// byte 08) arrive glued to replies and need no answer. | |
| 369 | + | #[test] | |
| 370 | + | fn replays_the_hw1_touch_session() { | |
| 371 | + | let script = Script::new(vec![ | |
| 372 | + | Step::Tx(hex("AA 07 00 00 00 01 01 00 00")), | |
| 373 | + | Step::Rx(hex( | |
| 374 | + | "AA 10 00 00 00 81 01 09 00 00 BF 1F 5A 20 45 04 40 00 AA 07 08 00 01 05 0F 00 00", | |
| 375 | + | )), | |
| 376 | + | Step::Tx(hex("AA 07 00 00 03 01 02 00 00")), | |
| 377 | + | Step::Rx(hex("AA 0B 00 00 03 81 02 04 00 00 12 3C 06")), | |
| 378 | + | Step::Tx(hex("AA 07 00 00 00 02 03 00 00")), | |
| 379 | + | Step::Rx(hex("AA 12 00 00 00 82 03 0B 00 00 09 01 02 03 04 05 06 0D F1 F4")), | |
| 380 | + | Step::Tx(hex("AA 0C 00 00 05 02 04 05 00 04 01 02 03 04")), | |
| 381 | + | Step::Rx(hex( | |
| 382 | + | "AA 11 00 00 05 82 04 0A 00 00 04 01 00 02 00 03 00 04 00 AA 0F 08 00 04 02 10 08 00 01 03 02 64 01 64 03 00", | |
| 383 | + | )), | |
| 384 | + | Step::Tx(hex("AA 07 00 00 08 01 05 00 00")), | |
| 385 | + | Step::Rx(hex( | |
| 386 | + | "AA 21 00 00 08 81 05 1A 00 00 06 01 01 02 01 01 01 03 06 01 01 04 08 02 01 02 01 02 01 03 06 02 01 04 08", | |
| 387 | + | )), | |
| 388 | + | Step::Tx(hex("AA 09 00 00 0C 01 06 02 00 02 01")), | |
| 389 | + | Step::Rx(hex("AA 0B 00 00 0C 81 06 04 00 00 02 01 0A")), | |
| 390 | + | ]); | |
| 391 | + | let touch = open(&script).unwrap().touch_controls().unwrap(); | |
| 392 | + | script.assert_done(); | |
| 393 | + | let table: Vec<(&str, &str, &str)> = touch | |
| 394 | + | .gestures | |
| 395 | + | .iter() | |
| 396 | + | .map(|g| (g.side.as_str(), g.gesture.as_str(), g.action.as_str())) | |
| 397 | + | .collect(); | |
| 398 | + | assert_eq!( | |
| 399 | + | table, | |
| 400 | + | [ | |
| 401 | + | ("left", "double-tap", "play-pause"), | |
| 402 | + | ("left", "triple-tap", "next"), | |
| 403 | + | ("left", "hold", "noise-cycle"), | |
| 404 | + | ("right", "double-tap", "play-pause"), | |
| 405 | + | ("right", "triple-tap", "next"), | |
| 406 | + | ("right", "hold", "noise-cycle"), | |
| 407 | + | ] | |
| 408 | + | ); | |
| 409 | + | assert_eq!(touch.hold_cycle.unwrap(), ["transparency", "anc"]); | |
| 410 | + | assert!(touch.warnings.is_empty()); | |
| 411 | + | } | |
| 412 | + | } | |
| @@ -0,0 +1,100 @@ | |||
| 1 | + | //! Every way budctl can fail, as one typed error. | |
| 2 | + | //! | |
| 3 | + | //! Front ends decide what to do with each [`Kind`]; the CLI maps them to its exit codes. | |
| 4 | + | ||
| 5 | + | use std::fmt; | |
| 6 | + | use std::io; | |
| 7 | + | ||
| 8 | + | pub type Result<T> = std::result::Result<T, Error>; | |
| 9 | + | ||
| 10 | + | #[derive(Debug)] | |
| 11 | + | pub enum Error { | |
| 12 | + | /// The request makes no sense for this device (bad value, several devices and no choice made…). | |
| 13 | + | Usage(String), | |
| 14 | + | /// The buds do not offer this feature. | |
| 15 | + | Unsupported(String), | |
| 16 | + | /// No paired device matches, or it is not a model budctl supports. | |
| 17 | + | NoDevice(String), | |
| 18 | + | /// The buds are paired but not connected, or the link dropped. | |
| 19 | + | NotConnected(String), | |
| 20 | + | /// The buds' SDP record has none of the model's control services. | |
| 21 | + | NoService(String), | |
| 22 | + | /// The buds identified themselves as a different model. | |
| 23 | + | WrongModel { expected: &'static str, found: String }, | |
| 24 | + | /// BlueZ could not be reached over D-Bus. | |
| 25 | + | Bluez(String), | |
| 26 | + | /// Another client holds the control channel. | |
| 27 | + | ChannelBusy(String), | |
| 28 | + | /// The buds did not answer in time. | |
| 29 | + | Timeout(String), | |
| 30 | + | /// The buds answered with a non-zero status byte. | |
| 31 | + | Rejected { what: String, status: u8 }, | |
| 32 | + | /// The buds sent something budctl cannot parse. | |
| 33 | + | Protocol(String), | |
| 34 | + | /// Any other operating-system error. | |
| 35 | + | Os { context: &'static str, source: io::Error }, | |
| 36 | + | } | |
| 37 | + | ||
| 38 | + | /// How a front end should treat an error. | |
| 39 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | |
| 40 | + | pub enum Kind { | |
| 41 | + | /// The user asked for something invalid. (CLI exit code 1) | |
| 42 | + | Usage, | |
| 43 | + | /// The device was not found or is not reachable. (CLI exit code 2) | |
| 44 | + | NotFound, | |
| 45 | + | /// Another app holds the control channel. (CLI exit code 3) | |
| 46 | + | Busy, | |
| 47 | + | /// The buds rejected the command, timed out or sent garbage. (CLI exit code 4) | |
| 48 | + | Failed, | |
| 49 | + | } | |
| 50 | + | ||
| 51 | + | impl Error { | |
| 52 | + | pub fn kind(&self) -> Kind { | |
| 53 | + | match self { | |
| 54 | + | Error::Usage(_) | Error::Unsupported(_) => Kind::Usage, | |
| 55 | + | Error::NoDevice(_) | |
| 56 | + | | Error::NotConnected(_) | |
| 57 | + | | Error::NoService(_) | |
| 58 | + | | Error::WrongModel { .. } | |
| 59 | + | | Error::Bluez(_) | |
| 60 | + | | Error::Os { .. } => Kind::NotFound, | |
| 61 | + | Error::ChannelBusy(_) => Kind::Busy, | |
| 62 | + | Error::Timeout(_) | Error::Rejected { .. } | Error::Protocol(_) => Kind::Failed, | |
| 63 | + | } | |
| 64 | + | } | |
| 65 | + | } | |
| 66 | + | ||
| 67 | + | impl fmt::Display for Error { | |
| 68 | + | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | |
| 69 | + | match self { | |
| 70 | + | Error::Usage(msg) | Error::Unsupported(msg) | Error::NoDevice(msg) => f.write_str(msg), | |
| 71 | + | Error::NotConnected(msg) => f.write_str(msg), | |
| 72 | + | Error::NoService(address) => write!( | |
| 73 | + | f, | |
| 74 | + | "{address} offers no control service budctl knows (checked its SDP record)" | |
| 75 | + | ), | |
| 76 | + | Error::WrongModel { expected, found } => { | |
| 77 | + | write!(f, "these buds report product id {found}, which is not a {expected}") | |
| 78 | + | } | |
| 79 | + | Error::Bluez(msg) => write!(f, "cannot reach BlueZ over D-Bus: {msg} (is bluetoothd running?)"), | |
| 80 | + | Error::ChannelBusy(detail) => { | |
| 81 | + | write!(f, "control channel busy — is another app connected? ({detail})") | |
| 82 | + | } | |
| 83 | + | Error::Timeout(what) => write!(f, "no answer from the buds: {what}"), | |
| 84 | + | Error::Rejected { what, status } => { | |
| 85 | + | write!(f, "the buds rejected {what} (status 0x{status:02X})") | |
| 86 | + | } | |
| 87 | + | Error::Protocol(msg) => write!(f, "unexpected data from the buds: {msg}"), | |
| 88 | + | Error::Os { context, source } => write!(f, "{context}: {source}"), | |
| 89 | + | } | |
| 90 | + | } | |
| 91 | + | } | |
| 92 | + | ||
| 93 | + | impl std::error::Error for Error { | |
| 94 | + | fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { | |
| 95 | + | match self { | |
| 96 | + | Error::Os { source, .. } => Some(source), | |
| 97 | + | _ => None, | |
| 98 | + | } | |
| 99 | + | } | |
| 100 | + | } | |
| @@ -0,0 +1,185 @@ | |||
| 1 | + | //! budctl-core: control wireless earbuds over Bluetooth, with device support as plugins. | |
| 2 | + | //! | |
| 3 | + | //! A front end (CLI, GUI) calls [`scan`], picks a device with [`select`], opens a session with | |
| 4 | + | //! [`connect`] and then reads or changes settings through [`devices::Session`]. | |
| 5 | + | //! | |
| 6 | + | //! No network: the only sockets are Bluetooth sockets and the local system D-Bus (BlueZ). | |
| 7 | + | //! See CLAUDE.md, hard rule 1. | |
| 8 | + | ||
| 9 | + | pub mod bluez; | |
| 10 | + | pub mod bt; | |
| 11 | + | pub mod debug; | |
| 12 | + | pub mod devices; | |
| 13 | + | mod error; | |
| 14 | + | mod reader; | |
| 15 | + | pub mod status; | |
| 16 | + | pub mod transport; | |
| 17 | + | ||
| 18 | + | pub use error::{Error, Kind, Result}; | |
| 19 | + | ||
| 20 | + | use bluez::PairedDevice; | |
| 21 | + | use bt::BdAddr; | |
| 22 | + | use devices::{Device, Session}; | |
| 23 | + | use transport::rfcomm::Rfcomm; | |
| 24 | + | use transport::{Hexdump, Transport, sdp}; | |
| 25 | + | ||
| 26 | + | /// A paired device and the model budctl recognized it as, if any. | |
| 27 | + | pub struct Found { | |
| 28 | + | pub device: PairedDevice, | |
| 29 | + | pub model: Option<&'static dyn Device>, | |
| 30 | + | } | |
| 31 | + | ||
| 32 | + | /// Every paired device BlueZ knows, each with its model when budctl supports it. | |
| 33 | + | pub fn scan() -> Result<Vec<Found>> { | |
| 34 | + | Ok(bluez::paired_devices()? | |
| 35 | + | .into_iter() | |
| 36 | + | .map(|device| Found { | |
| 37 | + | model: devices::identify(&device), | |
| 38 | + | device, | |
| 39 | + | }) | |
| 40 | + | .collect()) | |
| 41 | + | } | |
| 42 | + | ||
| 43 | + | /// Pick the device to talk to: the one at `address`, or else the only connected supported one. | |
| 44 | + | pub fn select(found: Vec<Found>, address: Option<BdAddr>) -> Result<(PairedDevice, &'static dyn Device)> { | |
| 45 | + | if let Some(address) = address { | |
| 46 | + | let found = found | |
| 47 | + | .into_iter() | |
| 48 | + | .find(|f| f.device.address == address) | |
| 49 | + | .ok_or_else(|| Error::NoDevice(format!("no paired device has the address {address}")))?; | |
| 50 | + | let model = found.model.ok_or_else(|| { | |
| 51 | + | Error::NoDevice(format!( | |
| 52 | + | "{} ({address}) is not a model budctl supports", | |
| 53 | + | found.device.alias | |
| 54 | + | )) | |
| 55 | + | })?; | |
| 56 | + | return Ok((found.device, model)); | |
| 57 | + | } | |
| 58 | + | ||
| 59 | + | let supported: Vec<(PairedDevice, &'static dyn Device)> = found | |
| 60 | + | .into_iter() | |
| 61 | + | .filter_map(|f| f.model.map(|model| (f.device, model))) | |
| 62 | + | .collect(); | |
| 63 | + | let (connected, idle): (Vec<_>, Vec<_>) = supported.into_iter().partition(|(d, _)| d.connected); | |
| 64 | + | let mut connected = connected.into_iter(); | |
| 65 | + | match (connected.next(), connected.next()) { | |
| 66 | + | (Some(only), None) => Ok(only), | |
| 67 | + | (Some(first), Some(second)) => { | |
| 68 | + | let addresses: Vec<String> = [first, second] | |
| 69 | + | .into_iter() | |
| 70 | + | .chain(connected) | |
| 71 | + | .map(|(d, _)| format!("{} ({})", d.address, d.alias)) | |
| 72 | + | .collect(); | |
| 73 | + | Err(Error::Usage(format!( | |
| 74 | + | "more than one supported device is connected; pick one with --device: {}", | |
| 75 | + | addresses.join(", ") | |
| 76 | + | ))) | |
| 77 | + | } | |
| 78 | + | (None, _) => { | |
| 79 | + | let mut idle = idle.into_iter(); | |
| 80 | + | match (idle.next(), idle.next()) { | |
| 81 | + | // One paired pair of buds: let `connect` say plainly that it is not connected. | |
| 82 | + | (Some(only), None) => Ok(only), | |
| 83 | + | (Some(_), Some(_)) => Err(Error::NotConnected( | |
| 84 | + | "none of your supported buds is connected; connect them in your Bluetooth settings first" | |
| 85 | + | .to_owned(), | |
| 86 | + | )), | |
| 87 | + | (None, _) => Err(Error::NoDevice( | |
| 88 | + | "no paired device budctl supports (pair the buds in your Bluetooth settings first)".to_owned(), | |
| 89 | + | )), | |
| 90 | + | } | |
| 91 | + | } | |
| 92 | + | } | |
| 93 | + | } | |
| 94 | + | ||
| 95 | + | /// Open a control session: find the control service with SDP, connect RFCOMM, run the model's | |
| 96 | + | /// init sequence. | |
| 97 | + | pub fn connect(device: &PairedDevice, model: &'static dyn Device) -> Result<Box<dyn Session>> { | |
| 98 | + | if !device.connected { | |
| 99 | + | return Err(Error::NotConnected(format!( | |
| 100 | + | "{} ({}) is paired but not connected; connect it in your Bluetooth settings first", | |
| 101 | + | device.alias, device.address | |
| 102 | + | ))); | |
| 103 | + | } | |
| 104 | + | for &service in model.rfcomm_uuids() { | |
| 105 | + | let Some(channel) = sdp::rfcomm_channel(device.address, service)? else { | |
| 106 | + | debug::note(|| format!("SDP: {} has no service {service}", device.address)); | |
| 107 | + | continue; | |
| 108 | + | }; | |
| 109 | + | debug::note(|| format!("SDP: service {service} is on RFCOMM channel {channel}")); | |
| 110 | + | let rfcomm = Box::new(Rfcomm::connect(device.address, channel)?); | |
| 111 | + | let link: Box<dyn Transport> = if debug::enabled() { | |
| 112 | + | Box::new(Hexdump::new(rfcomm)) | |
| 113 | + | } else { | |
| 114 | + | rfcomm | |
| 115 | + | }; | |
| 116 | + | return model.open(link); | |
| 117 | + | } | |
| 118 | + | Err(Error::NoService(device.address.to_string())) | |
| 119 | + | } | |
| 120 | + | ||
| 121 | + | #[cfg(test)] | |
| 122 | + | mod tests { | |
| 123 | + | use super::*; | |
| 124 | + | ||
| 125 | + | fn found(address: &str, name: &str, connected: bool) -> Found { | |
| 126 | + | let device = PairedDevice { | |
| 127 | + | address: address.parse().unwrap(), | |
| 128 | + | name: name.to_owned(), | |
| 129 | + | alias: name.to_owned(), | |
| 130 | + | connected, | |
| 131 | + | uuids: Vec::new(), | |
| 132 | + | }; | |
| 133 | + | Found { | |
| 134 | + | model: devices::identify(&device), | |
| 135 | + | device, | |
| 136 | + | } | |
| 137 | + | } | |
| 138 | + | ||
| 139 | + | const T310: &str = "realme Buds T310"; | |
| 140 | + | ||
| 141 | + | #[test] | |
| 142 | + | fn picks_the_only_connected_supported_device() { | |
| 143 | + | let list = vec![ | |
| 144 | + | found("00:00:00:00:00:01", "Some Speaker", true), | |
| 145 | + | found("00:00:00:00:00:02", T310, true), | |
| 146 | + | found("00:00:00:00:00:03", T310, false), | |
| 147 | + | ]; | |
| 148 | + | let (device, model) = select(list, None).unwrap(); | |
| 149 | + | assert_eq!(device.address.to_string(), "00:00:00:00:00:02"); | |
| 150 | + | assert_eq!(model.name(), T310); | |
| 151 | + | } | |
| 152 | + | ||
| 153 | + | #[test] | |
| 154 | + | fn several_connected_buds_need_a_choice() { | |
| 155 | + | let list = || { | |
| 156 | + | vec![ | |
| 157 | + | found("00:00:00:00:00:02", T310, true), | |
| 158 | + | found("00:00:00:00:00:03", T310, true), | |
| 159 | + | ] | |
| 160 | + | }; | |
| 161 | + | assert_eq!(select(list(), None).err().map(|e| e.kind()), Some(Kind::Usage)); | |
| 162 | + | let (device, _) = select(list(), Some("00:00:00:00:00:03".parse().unwrap())).unwrap(); | |
| 163 | + | assert_eq!(device.address.to_string(), "00:00:00:00:00:03"); | |
| 164 | + | } | |
| 165 | + | ||
| 166 | + | #[test] | |
| 167 | + | fn nothing_supported_or_unknown_address_is_not_found() { | |
| 168 | + | let list = || vec![found("00:00:00:00:00:01", "Some Speaker", true)]; | |
| 169 | + | assert!(matches!(select(list(), None), Err(Error::NoDevice(_)))); | |
| 170 | + | assert!(matches!( | |
| 171 | + | select(list(), Some("00:00:00:00:00:01".parse().unwrap())), | |
| 172 | + | Err(Error::NoDevice(_)) | |
| 173 | + | )); | |
| 174 | + | assert!(matches!( | |
| 175 | + | select(list(), Some("00:00:00:00:00:09".parse().unwrap())), | |
| 176 | + | Err(Error::NoDevice(_)) | |
| 177 | + | )); | |
| 178 | + | } | |
| 179 | + | ||
| 180 | + | #[test] | |
| 181 | + | fn one_idle_pair_is_selected_so_connect_can_explain() { | |
| 182 | + | let (device, model) = select(vec![found("00:00:00:00:00:02", T310, false)], None).unwrap(); | |
| 183 | + | assert!(matches!(connect(&device, model), Err(Error::NotConnected(_)))); | |
| 184 | + | } | |
| 185 | + | } | |
| @@ -0,0 +1,89 @@ | |||
| 1 | + | //! A cursor over bytes from the buds. Every read returns a `Result`, so a short or malformed | |
| 2 | + | //! message becomes an [`Error::Protocol`] instead of a panic. | |
| 3 | + | ||
| 4 | + | use crate::error::{Error, Result}; | |
| 5 | + | ||
| 6 | + | pub(crate) struct Reader<'a> { | |
| 7 | + | bytes: &'a [u8], | |
| 8 | + | /// What is being parsed, for error messages ("battery reply", "SDP response"…). | |
| 9 | + | what: &'static str, | |
| 10 | + | } | |
| 11 | + | ||
| 12 | + | impl<'a> Reader<'a> { | |
| 13 | + | pub(crate) fn new(bytes: &'a [u8], what: &'static str) -> Self { | |
| 14 | + | Self { bytes, what } | |
| 15 | + | } | |
| 16 | + | ||
| 17 | + | pub(crate) fn u8(&mut self) -> Result<u8> { | |
| 18 | + | let [byte] = self.array::<1>()?; | |
| 19 | + | Ok(byte) | |
| 20 | + | } | |
| 21 | + | ||
| 22 | + | pub(crate) fn i8(&mut self) -> Result<i8> { | |
| 23 | + | let [byte] = self.array::<1>()?; | |
| 24 | + | Ok(i8::from_le_bytes([byte])) | |
| 25 | + | } | |
| 26 | + | ||
| 27 | + | pub(crate) fn u16_le(&mut self) -> Result<u16> { | |
| 28 | + | Ok(u16::from_le_bytes(self.array()?)) | |
| 29 | + | } | |
| 30 | + | ||
| 31 | + | pub(crate) fn u16_be(&mut self) -> Result<u16> { | |
| 32 | + | Ok(u16::from_be_bytes(self.array()?)) | |
| 33 | + | } | |
| 34 | + | ||
| 35 | + | pub(crate) fn u32_be(&mut self) -> Result<u32> { | |
| 36 | + | Ok(u32::from_be_bytes(self.array()?)) | |
| 37 | + | } | |
| 38 | + | ||
| 39 | + | /// The next `n` bytes. | |
| 40 | + | pub(crate) fn take(&mut self, n: usize) -> Result<&'a [u8]> { | |
| 41 | + | let (head, tail) = self.bytes.split_at_checked(n).ok_or_else(|| self.too_short())?; | |
| 42 | + | self.bytes = tail; | |
| 43 | + | Ok(head) | |
| 44 | + | } | |
| 45 | + | ||
| 46 | + | /// Everything not read yet. | |
| 47 | + | pub(crate) fn rest(&mut self) -> &'a [u8] { | |
| 48 | + | std::mem::take(&mut self.bytes) | |
| 49 | + | } | |
| 50 | + | ||
| 51 | + | pub(crate) fn is_empty(&self) -> bool { | |
| 52 | + | self.bytes.is_empty() | |
| 53 | + | } | |
| 54 | + | ||
| 55 | + | fn array<const N: usize>(&mut self) -> Result<[u8; N]> { | |
| 56 | + | let (head, tail) = self.bytes.split_first_chunk::<N>().ok_or_else(|| self.too_short())?; | |
| 57 | + | self.bytes = tail; | |
| 58 | + | Ok(*head) | |
| 59 | + | } | |
| 60 | + | ||
| 61 | + | fn too_short(&self) -> Error { | |
| 62 | + | Error::Protocol(format!("{} is too short", self.what)) | |
| 63 | + | } | |
| 64 | + | } | |
| 65 | + | ||
| 66 | + | #[cfg(test)] | |
| 67 | + | mod tests { | |
| 68 | + | use super::*; | |
| 69 | + | ||
| 70 | + | #[test] | |
| 71 | + | fn reads_in_order_and_reports_short_input() { | |
| 72 | + | let mut r = Reader::new(&[0x01, 0x34, 0x12, 0x12, 0x34, 0xFF], "test"); | |
| 73 | + | assert_eq!(r.u8().unwrap(), 0x01); | |
| 74 | + | assert_eq!(r.u16_le().unwrap(), 0x1234); | |
| 75 | + | assert_eq!(r.u16_be().unwrap(), 0x1234); | |
| 76 | + | assert_eq!(r.i8().unwrap(), -1); | |
| 77 | + | assert!(r.is_empty()); | |
| 78 | + | assert!(matches!(r.u8(), Err(Error::Protocol(_)))); | |
| 79 | + | } | |
| 80 | + | ||
| 81 | + | #[test] | |
| 82 | + | fn take_and_rest() { | |
| 83 | + | let mut r = Reader::new(&[1, 2, 3, 4], "test"); | |
| 84 | + | assert_eq!(r.take(2).unwrap(), &[1, 2]); | |
| 85 | + | assert!(r.take(3).is_err()); | |
| 86 | + | assert_eq!(r.rest(), &[3, 4]); | |
| 87 | + | assert_eq!(r.rest(), &[] as &[u8]); | |
| 88 | + | } | |
| 89 | + | } | |
| @@ -0,0 +1,80 @@ | |||
| 1 | + | //! What a session reports, in device-neutral terms. Front ends print these, and `--json` | |
| 2 | + | //! serializes them as they are. | |
| 3 | + | ||
| 4 | + | use serde::{Serialize, Serializer}; | |
| 5 | + | ||
| 6 | + | /// Bumped whenever the JSON shape changes incompatibly. | |
| 7 | + | pub const JSON_SCHEMA: u32 = 1; | |
| 8 | + | ||
| 9 | + | #[derive(Debug, Default, Serialize)] | |
| 10 | + | pub struct Status { | |
| 11 | + | pub battery: Battery, | |
| 12 | + | pub noise_control: Option<NoiseControl>, | |
| 13 | + | /// Name of the current EQ preset. | |
| 14 | + | pub eq: Option<String>, | |
| 15 | + | pub bass_level: Option<i8>, | |
| 16 | + | /// On/off settings, serialized as `{"game": false, …}`. | |
| 17 | + | #[serde(serialize_with = "switches_as_map")] | |
| 18 | + | pub switches: Vec<Switch>, | |
| 19 | + | /// Audio codec of the link the buds report. | |
| 20 | + | pub codec: Option<String>, | |
| 21 | + | pub firmware: Option<String>, | |
| 22 | + | /// Reads that failed. The rest of the status is still valid. | |
| 23 | + | pub warnings: Vec<String>, | |
| 24 | + | } | |
| 25 | + | ||
| 26 | + | #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize)] | |
| 27 | + | pub struct Battery { | |
| 28 | + | pub left: Option<Charge>, | |
| 29 | + | pub right: Option<Charge>, | |
| 30 | + | pub case: Option<Charge>, | |
| 31 | + | } | |
| 32 | + | ||
| 33 | + | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] | |
| 34 | + | pub struct Charge { | |
| 35 | + | /// Percent. | |
| 36 | + | pub level: u8, | |
| 37 | + | pub charging: bool, | |
| 38 | + | } | |
| 39 | + | ||
| 40 | + | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] | |
| 41 | + | pub struct NoiseControl { | |
| 42 | + | /// `off`, `transparency` or `anc`, or `unknown (…)` for a value the device module cannot name. | |
| 43 | + | pub mode: String, | |
| 44 | + | /// The noise-cancelling level, when the device reports one. | |
| 45 | + | pub level: Option<String>, | |
| 46 | + | } | |
| 47 | + | ||
| 48 | + | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] | |
| 49 | + | pub struct Switch { | |
| 50 | + | /// Stable name used on the command line and in JSON (`game`, `dual`…). | |
| 51 | + | pub key: &'static str, | |
| 52 | + | /// Human name (`Game mode`). | |
| 53 | + | pub label: &'static str, | |
| 54 | + | pub on: bool, | |
| 55 | + | } | |
| 56 | + | ||
| 57 | + | #[derive(Debug, Default, Serialize)] | |
| 58 | + | pub struct TouchControls { | |
| 59 | + | pub gestures: Vec<Gesture>, | |
| 60 | + | /// Noise-control modes a hold steps through, when the device has that setting. | |
| 61 | + | pub hold_cycle: Option<Vec<String>>, | |
| 62 | + | pub warnings: Vec<String>, | |
| 63 | + | } | |
| 64 | + | ||
| 65 | + | #[derive(Debug, Clone, PartialEq, Eq, Serialize)] | |
| 66 | + | pub struct Gesture { | |
| 67 | + | /// `left`, `right` or `both`. | |
| 68 | + | pub side: String, | |
| 69 | + | /// `double-tap`, `triple-tap`, `hold`… | |
| 70 | + | pub gesture: String, | |
| 71 | + | /// `play-pause`, `next`, `none`… | |
| 72 | + | pub action: String, | |
| 73 | + | /// Raw button group, for entries outside the main gestures (calls). `None` for the main group. | |
| 74 | + | #[serde(skip_serializing_if = "Option::is_none")] | |
| 75 | + | pub group: Option<u8>, | |
| 76 | + | } | |
| 77 | + | ||
| 78 | + | fn switches_as_map<S: Serializer>(switches: &[Switch], serializer: S) -> Result<S::Ok, S::Error> { | |
| 79 | + | serializer.collect_map(switches.iter().map(|s| (s.key, s.on))) | |
| 80 | + | } | |
| @@ -0,0 +1,80 @@ | |||
| 1 | + | //! A scripted transport for tests: it checks every byte budctl sends and replays what the buds | |
| 2 | + | //! would answer, without hardware and without waiting for real time to pass. | |
| 3 | + | ||
| 4 | + | use std::collections::VecDeque; | |
| 5 | + | use std::sync::{Arc, Mutex}; | |
| 6 | + | use std::time::Instant; | |
| 7 | + | ||
| 8 | + | use super::Transport; | |
| 9 | + | use crate::debug; | |
| 10 | + | use crate::error::{Error, Result}; | |
| 11 | + | ||
| 12 | + | #[derive(Debug)] | |
| 13 | + | pub(crate) enum Step { | |
| 14 | + | /// budctl must send exactly these bytes next. | |
| 15 | + | Tx(Vec<u8>), | |
| 16 | + | /// The buds send these bytes. | |
| 17 | + | Rx(Vec<u8>), | |
| 18 | + | /// The buds drop the link. | |
| 19 | + | Close, | |
| 20 | + | } | |
| 21 | + | ||
| 22 | + | /// Cheap to clone: the test keeps one handle to check that the script was used up. | |
| 23 | + | #[derive(Clone, Default)] | |
| 24 | + | pub(crate) struct Script(Arc<Mutex<VecDeque<Step>>>); | |
| 25 | + | ||
| 26 | + | impl Script { | |
| 27 | + | pub(crate) fn new(steps: Vec<Step>) -> Self { | |
| 28 | + | Script(Arc::new(Mutex::new(steps.into()))) | |
| 29 | + | } | |
| 30 | + | ||
| 31 | + | pub(crate) fn transport(&self) -> Box<dyn Transport> { | |
| 32 | + | Box::new(self.clone()) | |
| 33 | + | } | |
| 34 | + | ||
| 35 | + | pub(crate) fn assert_done(&self) { | |
| 36 | + | let left = self.0.lock().unwrap(); | |
| 37 | + | assert!(left.is_empty(), "script not finished, next step: {:?}", left.front()); | |
| 38 | + | } | |
| 39 | + | } | |
| 40 | + | ||
| 41 | + | impl Transport for Script { | |
| 42 | + | fn send(&mut self, bytes: &[u8]) -> Result<()> { | |
| 43 | + | let mut steps = self.0.lock().unwrap(); | |
| 44 | + | match steps.pop_front() { | |
| 45 | + | Some(Step::Tx(expected)) => assert_eq!( | |
| 46 | + | debug::hex(bytes), | |
| 47 | + | debug::hex(&expected), | |
| 48 | + | "budctl sent something else than the script expects" | |
| 49 | + | ), | |
| 50 | + | other => panic!("unexpected send {} (next step: {other:?})", debug::hex(bytes)), | |
| 51 | + | } | |
| 52 | + | Ok(()) | |
| 53 | + | } | |
| 54 | + | ||
| 55 | + | /// Returns the next scripted bytes from the buds. When the script expects budctl to send | |
| 56 | + | /// next, the buds stay silent: the deadline "passes" at once. | |
| 57 | + | fn recv(&mut self, _deadline: Instant) -> Result<Option<Vec<u8>>> { | |
| 58 | + | let mut steps = self.0.lock().unwrap(); | |
| 59 | + | match steps.front() { | |
| 60 | + | Some(Step::Rx(_)) => match steps.pop_front() { | |
| 61 | + | Some(Step::Rx(bytes)) => Ok(Some(bytes)), | |
| 62 | + | _ => unreachable!(), | |
| 63 | + | }, | |
| 64 | + | Some(Step::Close) => { | |
| 65 | + | steps.pop_front(); | |
| 66 | + | Err(Error::NotConnected( | |
| 67 | + | "the buds closed the control link (script)".to_owned(), | |
| 68 | + | )) | |
| 69 | + | } | |
| 70 | + | _ => Ok(None), | |
| 71 | + | } | |
| 72 | + | } | |
| 73 | + | } | |
| 74 | + | ||
| 75 | + | /// `"AA 07 00"` → `[0xAA, 0x07, 0x00]` | |
| 76 | + | pub(crate) fn hex(text: &str) -> Vec<u8> { | |
| 77 | + | text.split_whitespace() | |
| 78 | + | .map(|byte| u8::from_str_radix(byte, 16).unwrap()) | |
| 79 | + | .collect() | |
| 80 | + | } | |
| @@ -0,0 +1,103 @@ | |||
| 1 | + | //! Byte transports. Device protocols only see the [`Transport`] trait, so they can be tested | |
| 2 | + | //! against a scripted mock instead of real buds. | |
| 3 | + | ||
| 4 | + | use std::io; | |
| 5 | + | use std::time::Instant; | |
| 6 | + | ||
| 7 | + | use crate::debug; | |
| 8 | + | use crate::error::{Error, Result}; | |
| 9 | + | ||
| 10 | + | pub mod rfcomm; | |
| 11 | + | pub mod sdp; | |
| 12 | + | mod socket; | |
| 13 | + | ||
| 14 | + | #[cfg(test)] | |
| 15 | + | pub(crate) mod mock; | |
| 16 | + | ||
| 17 | + | /// A bidirectional byte stream to the buds. | |
| 18 | + | pub trait Transport: Send { | |
| 19 | + | /// Send all of `bytes`. | |
| 20 | + | fn send(&mut self, bytes: &[u8]) -> Result<()>; | |
| 21 | + | ||
| 22 | + | /// The next bytes from the buds, or `None` once `deadline` passes with nothing to read. | |
| 23 | + | fn recv(&mut self, deadline: Instant) -> Result<Option<Vec<u8>>>; | |
| 24 | + | } | |
| 25 | + | ||
| 26 | + | /// Wraps a transport and prints every chunk sent and received (`--debug`). | |
| 27 | + | pub struct Hexdump { | |
| 28 | + | inner: Box<dyn Transport>, | |
| 29 | + | start: Instant, | |
| 30 | + | } | |
| 31 | + | ||
| 32 | + | impl Hexdump { | |
| 33 | + | pub fn new(inner: Box<dyn Transport>) -> Self { | |
| 34 | + | Self { | |
| 35 | + | inner, | |
| 36 | + | start: Instant::now(), | |
| 37 | + | } | |
| 38 | + | } | |
| 39 | + | ||
| 40 | + | fn print(&self, direction: &str, bytes: &[u8]) { | |
| 41 | + | let elapsed = self.start.elapsed().as_secs_f64(); | |
| 42 | + | eprintln!("{elapsed:>7.3} {direction} {}", debug::hex(bytes)); | |
| 43 | + | } | |
| 44 | + | } | |
| 45 | + | ||
| 46 | + | impl Transport for Hexdump { | |
| 47 | + | fn send(&mut self, bytes: &[u8]) -> Result<()> { | |
| 48 | + | self.print("TX", bytes); | |
| 49 | + | self.inner.send(bytes) | |
| 50 | + | } | |
| 51 | + | ||
| 52 | + | fn recv(&mut self, deadline: Instant) -> Result<Option<Vec<u8>>> { | |
| 53 | + | let received = self.inner.recv(deadline)?; | |
| 54 | + | if let Some(bytes) = &received { | |
| 55 | + | self.print("RX", bytes); | |
| 56 | + | } | |
| 57 | + | Ok(received) | |
| 58 | + | } | |
| 59 | + | } | |
| 60 | + | ||
| 61 | + | /// What an OS error on a Bluetooth socket means for budctl. | |
| 62 | + | /// `may_be_busy` is set only for the RFCOMM connect, where a refusal means another client | |
| 63 | + | /// holds the channel. Spec: transport.md#errno | |
| 64 | + | pub(crate) fn classify(error: io::Error, context: &'static str, may_be_busy: bool) -> Error { | |
| 65 | + | let detail = || format!("{context}: {error}"); | |
| 66 | + | match error.raw_os_error() { | |
| 67 | + | Some(libc::EBUSY | libc::EADDRINUSE | libc::ECONNREFUSED) if may_be_busy => Error::ChannelBusy(detail()), | |
| 68 | + | Some( | |
| 69 | + | libc::EHOSTDOWN | |
| 70 | + | | libc::EHOSTUNREACH | |
| 71 | + | | libc::ENOTCONN | |
| 72 | + | | libc::ECONNRESET | |
| 73 | + | | libc::ECONNABORTED | |
| 74 | + | | libc::EPIPE | |
| 75 | + | | libc::ENODEV | |
| 76 | + | | libc::ENETDOWN, | |
| 77 | + | ) => Error::NotConnected(detail()), | |
| 78 | + | Some(libc::ETIMEDOUT | libc::EINPROGRESS | libc::EAGAIN) => Error::Timeout(detail()), | |
| 79 | + | _ => Error::Os { context, source: error }, | |
| 80 | + | } | |
| 81 | + | } | |
| 82 | + | ||
| 83 | + | #[cfg(test)] | |
| 84 | + | mod tests { | |
| 85 | + | use super::*; | |
| 86 | + | use crate::error::Kind; | |
| 87 | + | ||
| 88 | + | fn kind_of(errno: i32, may_be_busy: bool) -> Kind { | |
| 89 | + | classify(io::Error::from_raw_os_error(errno), "test", may_be_busy).kind() | |
| 90 | + | } | |
| 91 | + | ||
| 92 | + | #[test] | |
| 93 | + | fn errno_maps_to_the_documented_kinds() { | |
| 94 | + | assert_eq!(kind_of(libc::ECONNREFUSED, true), Kind::Busy); | |
| 95 | + | assert_eq!(kind_of(libc::EBUSY, true), Kind::Busy); | |
| 96 | + | assert_eq!(kind_of(libc::ECONNREFUSED, false), Kind::NotFound); | |
| 97 | + | assert_eq!(kind_of(libc::EHOSTDOWN, true), Kind::NotFound); | |
| 98 | + | assert_eq!(kind_of(libc::ECONNRESET, false), Kind::NotFound); | |
| 99 | + | assert_eq!(kind_of(libc::EINPROGRESS, true), Kind::Failed); | |
| 100 | + | assert_eq!(kind_of(libc::ETIMEDOUT, false), Kind::Failed); | |
| 101 | + | assert_eq!(kind_of(libc::EACCES, false), Kind::NotFound); | |
| 102 | + | } | |
| 103 | + | } | |
| @@ -0,0 +1,47 @@ | |||
| 1 | + | //! The RFCOMM control link: a byte stream to one channel on the buds. | |
| 2 | + | ||
| 3 | + | use std::os::fd::OwnedFd; | |
| 4 | + | use std::time::{Duration, Instant}; | |
| 5 | + | ||
| 6 | + | use super::{Transport, classify, socket}; | |
| 7 | + | use crate::bt::BdAddr; | |
| 8 | + | use crate::error::{Error, Result}; | |
| 9 | + | ||
| 10 | + | /// Upper bound for the connect and for each send. The audio link is already up, so a healthy | |
| 11 | + | /// connect takes well under a second. | |
| 12 | + | const TIMEOUT: Duration = Duration::from_secs(8); | |
| 13 | + | ||
| 14 | + | pub struct Rfcomm { | |
| 15 | + | fd: OwnedFd, | |
| 16 | + | } | |
| 17 | + | ||
| 18 | + | impl Rfcomm { | |
| 19 | + | pub fn connect(address: BdAddr, channel: u8) -> Result<Self> { | |
| 20 | + | let fd = socket::connect(address, socket::Target::Rfcomm { channel }, TIMEOUT) | |
| 21 | + | .map_err(|e| classify(e, "connecting to the control channel", true))?; | |
| 22 | + | Ok(Self { fd }) | |
| 23 | + | } | |
| 24 | + | } | |
| 25 | + | ||
| 26 | + | impl Transport for Rfcomm { | |
| 27 | + | fn send(&mut self, bytes: &[u8]) -> Result<()> { | |
| 28 | + | socket::write_all(&self.fd, bytes).map_err(|e| classify(e, "sending to the buds", false)) | |
| 29 | + | } | |
| 30 | + | ||
| 31 | + | fn recv(&mut self, deadline: Instant) -> Result<Option<Vec<u8>>> { | |
| 32 | + | let readable = | |
| 33 | + | socket::wait_readable(&self.fd, deadline).map_err(|e| classify(e, "waiting for the buds", false))?; | |
| 34 | + | if !readable { | |
| 35 | + | return Ok(None); | |
| 36 | + | } | |
| 37 | + | let mut buffer = vec![0u8; 1024]; | |
| 38 | + | let n = socket::read(&self.fd, &mut buffer).map_err(|e| classify(e, "reading from the buds", false))?; | |
| 39 | + | if n == 0 { | |
| 40 | + | return Err(Error::NotConnected( | |
| 41 | + | "the buds closed the control link (case lid closed?)".to_owned(), | |
| 42 | + | )); | |
| 43 | + | } | |
| 44 | + | buffer.truncate(n); | |
| 45 | + | Ok(Some(buffer)) | |
| 46 | + | } | |
| 47 | + | } | |
| @@ -0,0 +1,287 @@ | |||
| 1 | + | //! Find a service's RFCOMM channel by asking the device's SDP server. | |
| 2 | + | //! Protocol: docs/protocol/transport.md#sdp. | |
| 3 | + | ||
| 4 | + | use std::time::{Duration, Instant}; | |
| 5 | + | ||
| 6 | + | use super::{classify, socket}; | |
| 7 | + | use crate::bt::{BdAddr, Uuid}; | |
| 8 | + | use crate::error::{Error, Result}; | |
| 9 | + | use crate::reader::Reader; | |
| 10 | + | ||
| 11 | + | /// Spec: transport.md#sockets | |
| 12 | + | const SDP_PSM: u16 = 1; | |
| 13 | + | /// Spec: transport.md#sdp-pdu | |
| 14 | + | const ERROR_RESPONSE: u8 = 0x01; | |
| 15 | + | /// Spec: transport.md#sdp-pdu | |
| 16 | + | const SEARCH_ATTRIBUTE_REQUEST: u8 = 0x06; | |
| 17 | + | /// Spec: transport.md#sdp-pdu | |
| 18 | + | const SEARCH_ATTRIBUTE_RESPONSE: u8 = 0x07; | |
| 19 | + | /// ProtocolDescriptorList. Spec: transport.md#sdp-request | |
| 20 | + | const PROTOCOL_DESCRIPTOR_LIST: u16 = 0x0004; | |
| 21 | + | /// Spec: transport.md#sdp-response | |
| 22 | + | const MAX_ROUNDS: u16 = 16; | |
| 23 | + | /// Continuation state is at most 16 bytes. Spec: transport.md#sdp-request | |
| 24 | + | const MAX_CONTINUATION: usize = 16; | |
| 25 | + | /// Nesting deeper than this is not a real service record. | |
| 26 | + | const MAX_DEPTH: usize = 8; | |
| 27 | + | ||
| 28 | + | const TIMEOUT: Duration = Duration::from_secs(5); | |
| 29 | + | ||
| 30 | + | /// The RFCOMM channel of `service` on the device, or `None` if it has no such service. | |
| 31 | + | pub fn rfcomm_channel(address: BdAddr, service: Uuid) -> Result<Option<u8>> { | |
| 32 | + | let fd = socket::connect(address, socket::Target::L2cap { psm: SDP_PSM }, TIMEOUT) | |
| 33 | + | .map_err(|e| classify(e, "connecting to the SDP server", false))?; | |
| 34 | + | ||
| 35 | + | let mut attribute_lists = Vec::new(); | |
| 36 | + | let mut continuation = Vec::new(); | |
| 37 | + | for transaction in 1..=MAX_ROUNDS { | |
| 38 | + | let request = search_attribute_request(transaction, service, &continuation)?; | |
| 39 | + | socket::write_all(&fd, &request).map_err(|e| classify(e, "sending an SDP request", false))?; | |
| 40 | + | ||
| 41 | + | let readable = | |
| 42 | + | socket::wait_readable(&fd, Instant::now() + TIMEOUT).map_err(|e| classify(e, "waiting for SDP", false))?; | |
| 43 | + | if !readable { | |
| 44 | + | return Err(Error::Timeout("SDP service search".to_owned())); | |
| 45 | + | } | |
| 46 | + | let mut pdu = vec![0u8; 4096]; | |
| 47 | + | let n = socket::read(&fd, &mut pdu).map_err(|e| classify(e, "reading SDP", false))?; | |
| 48 | + | pdu.truncate(n); | |
| 49 | + | ||
| 50 | + | let response = parse_response(&pdu, transaction)?; | |
| 51 | + | attribute_lists.extend_from_slice(response.attributes); | |
| 52 | + | if response.continuation.is_empty() { | |
| 53 | + | return channel_from_attribute_lists(&attribute_lists); | |
| 54 | + | } | |
| 55 | + | continuation = response.continuation.to_vec(); | |
| 56 | + | } | |
| 57 | + | Err(Error::Protocol("SDP answer did not end after 16 rounds".to_owned())) | |
| 58 | + | } | |
| 59 | + | ||
| 60 | + | /// A ServiceSearchAttributeRequest for one 128-bit UUID, asking only for the | |
| 61 | + | /// ProtocolDescriptorList. Spec: transport.md#sdp-request | |
| 62 | + | fn search_attribute_request(transaction: u16, service: Uuid, continuation: &[u8]) -> Result<Vec<u8>> { | |
| 63 | + | let continuation_len = u8::try_from(continuation.len()) | |
| 64 | + | .ok() | |
| 65 | + | .filter(|&len| usize::from(len) <= MAX_CONTINUATION) | |
| 66 | + | .ok_or_else(|| Error::Protocol("SDP continuation state too long".to_owned()))?; | |
| 67 | + | ||
| 68 | + | let mut parameters = vec![0x35, 0x11, 0x1C]; // sequence of 17 bytes: one 128-bit UUID | |
| 69 | + | parameters.extend(service.to_be_bytes()); | |
| 70 | + | parameters.extend([0xFF, 0xFF]); // maximum attribute byte count | |
| 71 | + | parameters.extend([0x35, 0x03, 0x09]); // sequence of 3 bytes: one 16-bit attribute id | |
| 72 | + | parameters.extend(PROTOCOL_DESCRIPTOR_LIST.to_be_bytes()); | |
| 73 | + | parameters.push(continuation_len); | |
| 74 | + | parameters.extend(continuation); | |
| 75 | + | ||
| 76 | + | let parameter_len = | |
| 77 | + | u16::try_from(parameters.len()).map_err(|_| Error::Protocol("SDP request too long".to_owned()))?; | |
| 78 | + | let mut pdu = vec![SEARCH_ATTRIBUTE_REQUEST]; | |
| 79 | + | pdu.extend(transaction.to_be_bytes()); | |
| 80 | + | pdu.extend(parameter_len.to_be_bytes()); | |
| 81 | + | pdu.extend(parameters); | |
| 82 | + | Ok(pdu) | |
| 83 | + | } | |
| 84 | + | ||
| 85 | + | struct Response<'a> { | |
| 86 | + | attributes: &'a [u8], | |
| 87 | + | continuation: &'a [u8], | |
| 88 | + | } | |
| 89 | + | ||
| 90 | + | /// Spec: transport.md#sdp-response | |
| 91 | + | fn parse_response(pdu: &[u8], transaction: u16) -> Result<Response<'_>> { | |
| 92 | + | let mut header = Reader::new(pdu, "SDP response"); | |
| 93 | + | let id = header.u8()?; | |
| 94 | + | let answered = header.u16_be()?; | |
| 95 | + | let len = header.u16_be()?; | |
| 96 | + | let mut parameters = Reader::new(header.take(usize::from(len))?, "SDP response"); | |
| 97 | + | match id { | |
| 98 | + | SEARCH_ATTRIBUTE_RESPONSE if answered == transaction => { | |
| 99 | + | let count = parameters.u16_be()?; | |
| 100 | + | let attributes = parameters.take(usize::from(count))?; | |
| 101 | + | let continuation_len = parameters.u8()?; | |
| 102 | + | if usize::from(continuation_len) > MAX_CONTINUATION { | |
| 103 | + | return Err(Error::Protocol("SDP continuation state too long".to_owned())); | |
| 104 | + | } | |
| 105 | + | let continuation = parameters.take(usize::from(continuation_len))?; | |
| 106 | + | Ok(Response { | |
| 107 | + | attributes, | |
| 108 | + | continuation, | |
| 109 | + | }) | |
| 110 | + | } | |
| 111 | + | SEARCH_ATTRIBUTE_RESPONSE => Err(Error::Protocol(format!( | |
| 112 | + | "SDP answered transaction {answered}, expected {transaction}" | |
| 113 | + | ))), | |
| 114 | + | ERROR_RESPONSE => Err(Error::Protocol(format!( | |
| 115 | + | "SDP error response 0x{:04X}", | |
| 116 | + | parameters.u16_be()? | |
| 117 | + | ))), | |
| 118 | + | other => Err(Error::Protocol(format!("unexpected SDP PDU 0x{other:02X}"))), | |
| 119 | + | } | |
| 120 | + | } | |
| 121 | + | ||
| 122 | + | /// The parts of an SDP data element budctl looks at. Spec: transport.md#sdp-data-elements | |
| 123 | + | #[derive(Debug, PartialEq)] | |
| 124 | + | enum Element { | |
| 125 | + | Uint(u64), | |
| 126 | + | Uuid(Uuid), | |
| 127 | + | /// A sequence or an alternative. | |
| 128 | + | List(Vec<Element>), | |
| 129 | + | Other, | |
| 130 | + | } | |
| 131 | + | ||
| 132 | + | fn element(r: &mut Reader, depth: usize) -> Result<Element> { | |
| 133 | + | if depth > MAX_DEPTH { | |
| 134 | + | return Err(Error::Protocol("SDP data nested too deeply".to_owned())); | |
| 135 | + | } | |
| 136 | + | let header = r.u8()?; | |
| 137 | + | let (kind, size) = (header >> 3, header & 0x07); | |
| 138 | + | let len = match size { | |
| 139 | + | 0 if kind == 0 => 0, // nil | |
| 140 | + | 0 => 1, | |
| 141 | + | 1 => 2, | |
| 142 | + | 2 => 4, | |
| 143 | + | 3 => 8, | |
| 144 | + | 4 => 16, | |
| 145 | + | 5 => usize::from(r.u8()?), | |
| 146 | + | 6 => usize::from(r.u16_be()?), | |
| 147 | + | _ => usize::try_from(r.u32_be()?).map_err(|_| Error::Protocol("SDP element too long".to_owned()))?, | |
| 148 | + | }; | |
| 149 | + | let data = r.take(len)?; | |
| 150 | + | Ok(match kind { | |
| 151 | + | 1 => match data.len() { | |
| 152 | + | 1 | 2 | 4 | 8 => Element::Uint(data.iter().fold(0, |n, &b| (n << 8) | u64::from(b))), | |
| 153 | + | _ => Element::Other, | |
| 154 | + | }, | |
| 155 | + | 3 => Element::Uuid(Uuid::from_sdp(data)?), | |
| 156 | + | 6 | 7 => { | |
| 157 | + | let mut inner = Reader::new(data, "SDP sequence"); | |
| 158 | + | let mut items = Vec::new(); | |
| 159 | + | while !inner.is_empty() { | |
| 160 | + | items.push(element(&mut inner, depth + 1)?); | |
| 161 | + | } | |
| 162 | + | Element::List(items) | |
| 163 | + | } | |
| 164 | + | _ => Element::Other, | |
| 165 | + | }) | |
| 166 | + | } | |
| 167 | + | ||
| 168 | + | /// The RFCOMM channel in the (joined) AttributeLists of a ServiceSearchAttributeResponse. | |
| 169 | + | /// Spec: transport.md#sdp-rfcomm-channel | |
| 170 | + | fn channel_from_attribute_lists(bytes: &[u8]) -> Result<Option<u8>> { | |
| 171 | + | let mut r = Reader::new(bytes, "SDP attribute lists"); | |
| 172 | + | let Element::List(records) = element(&mut r, 0)? else { | |
| 173 | + | return Err(Error::Protocol("SDP attribute lists are not a sequence".to_owned())); | |
| 174 | + | }; | |
| 175 | + | for record in &records { | |
| 176 | + | let Element::List(attributes) = record else { continue }; | |
| 177 | + | for pair in attributes.chunks(2) { | |
| 178 | + | if let [Element::Uint(id), value] = pair | |
| 179 | + | && *id == u64::from(PROTOCOL_DESCRIPTOR_LIST) | |
| 180 | + | && let Some(channel) = find_rfcomm(value) | |
| 181 | + | { | |
| 182 | + | return u8::try_from(channel) | |
| 183 | + | .map(Some) | |
| 184 | + | .map_err(|_| Error::Protocol(format!("RFCOMM channel {channel} out of range"))); | |
| 185 | + | } | |
| 186 | + | } | |
| 187 | + | } | |
| 188 | + | Ok(None) | |
| 189 | + | } | |
| 190 | + | ||
| 191 | + | /// A protocol descriptor is a sequence that starts with the protocol's UUID; for RFCOMM the | |
| 192 | + | /// channel number comes next. Searching nested lists also covers records with alternatives. | |
| 193 | + | fn find_rfcomm(element: &Element) -> Option<u64> { | |
| 194 | + | let Element::List(items) = element else { return None }; | |
| 195 | + | if let [Element::Uuid(uuid), Element::Uint(channel), ..] = items.as_slice() | |
| 196 | + | && *uuid == Uuid::RFCOMM | |
| 197 | + | { | |
| 198 | + | return Some(*channel); | |
| 199 | + | } | |
| 200 | + | items.iter().find_map(find_rfcomm) | |
| 201 | + | } | |
| 202 | + | ||
| 203 | + | #[cfg(test)] | |
| 204 | + | mod tests { | |
| 205 | + | use super::*; | |
| 206 | + | use crate::transport::mock::hex; | |
| 207 | + | ||
| 208 | + | const SERVICE: Uuid = Uuid::from_u128(0x0000_079A_D102_11E1_9B23_0002_5B00_A5A5); | |
| 209 | + | ||
| 210 | + | /// One record: ProtocolDescriptorList = (L2CAP), (RFCOMM, channel 15). | |
| 211 | + | /// Spec: transport.md#sdp-rfcomm-channel | |
| 212 | + | const ATTRIBUTE_LISTS: &str = "35 13 35 11 09 00 04 35 0C 35 03 19 01 00 35 05 19 00 03 08 0F"; | |
| 213 | + | ||
| 214 | + | #[test] | |
| 215 | + | fn request_layout() { | |
| 216 | + | let pdu = search_attribute_request(1, SERVICE, &[]).unwrap(); | |
| 217 | + | let mut expected = hex("06 00 01 00 1B 35 11 1C"); | |
| 218 | + | expected.extend(SERVICE.to_be_bytes()); | |
| 219 | + | expected.extend(hex("FF FF 35 03 09 00 04 00")); | |
| 220 | + | assert_eq!(pdu, expected); | |
| 221 | + | ||
| 222 | + | let next = search_attribute_request(2, SERVICE, &[0xAB, 0xCD]).unwrap(); | |
| 223 | + | assert_eq!(next.get(1..5), Some(&hex("00 02 00 1D")[..])); | |
| 224 | + | assert!(next.ends_with(&hex("00 04 02 AB CD"))); | |
| 225 | + | } | |
| 226 | + | ||
| 227 | + | #[test] | |
| 228 | + | fn finds_the_channel_in_one_response() { | |
| 229 | + | let mut pdu = hex("07 00 01 00 18 00 15"); | |
| 230 | + | pdu.extend(hex(ATTRIBUTE_LISTS)); | |
| 231 | + | pdu.push(0x00); | |
| 232 | + | let response = parse_response(&pdu, 1).unwrap(); | |
| 233 | + | assert!(response.continuation.is_empty()); | |
| 234 | + | assert_eq!(channel_from_attribute_lists(response.attributes).unwrap(), Some(15)); | |
| 235 | + | } | |
| 236 | + | ||
| 237 | + | #[test] | |
| 238 | + | fn joins_continued_responses() { | |
| 239 | + | let lists = hex(ATTRIBUTE_LISTS); | |
| 240 | + | let (first, second) = lists.split_at(9); | |
| 241 | + | let mut pdu1 = vec![0x07, 0x00, 0x01, 0x00, 0x0E, 0x00, 0x09]; | |
| 242 | + | pdu1.extend(first); | |
| 243 | + | pdu1.extend([0x02, 0xAB, 0xCD]); | |
| 244 | + | let r1 = parse_response(&pdu1, 1).unwrap(); | |
| 245 | + | assert_eq!(r1.continuation, &[0xAB, 0xCD]); | |
| 246 | + | ||
| 247 | + | let mut pdu2 = vec![0x07, 0x00, 0x02, 0x00, 0x0F, 0x00, 0x0C]; | |
| 248 | + | pdu2.extend(second); | |
| 249 | + | pdu2.push(0x00); | |
| 250 | + | let r2 = parse_response(&pdu2, 2).unwrap(); | |
| 251 | + | ||
| 252 | + | let joined = [r1.attributes, r2.attributes].concat(); | |
| 253 | + | assert_eq!(channel_from_attribute_lists(&joined).unwrap(), Some(15)); | |
| 254 | + | } | |
| 255 | + | ||
| 256 | + | #[test] | |
| 257 | + | fn no_rfcomm_descriptor_means_no_channel() { | |
| 258 | + | // ProtocolDescriptorList with L2CAP only. | |
| 259 | + | let lists = hex("35 0C 35 0A 09 00 04 35 05 35 03 19 01 00"); | |
| 260 | + | assert_eq!(channel_from_attribute_lists(&lists).unwrap(), None); | |
| 261 | + | // No matching record at all. | |
| 262 | + | assert_eq!(channel_from_attribute_lists(&hex("35 00")).unwrap(), None); | |
| 263 | + | } | |
| 264 | + | ||
| 265 | + | #[test] | |
| 266 | + | fn errors_and_garbage_are_protocol_errors() { | |
| 267 | + | assert!(matches!( | |
| 268 | + | parse_response(&hex("01 00 01 00 02 00 03"), 1), | |
| 269 | + | Err(Error::Protocol(_)) | |
| 270 | + | )); | |
| 271 | + | assert!(matches!( | |
| 272 | + | parse_response(&hex("07 00 09 00 03 00 00 00"), 1), | |
| 273 | + | Err(Error::Protocol(_)) | |
| 274 | + | )); | |
| 275 | + | assert!(parse_response(&hex("07 00 01 00 05 00 09"), 1).is_err()); | |
| 276 | + | assert!(channel_from_attribute_lists(&hex("35 05 35")).is_err()); | |
| 277 | + | assert!(channel_from_attribute_lists(&hex("09 00 04")).is_err()); | |
| 278 | + | // Deep nesting is refused instead of recursing without bound. | |
| 279 | + | let mut nested = Vec::new(); | |
| 280 | + | for _ in 0..20 { | |
| 281 | + | let mut outer = vec![0x35, u8::try_from(nested.len()).unwrap()]; | |
| 282 | + | outer.extend(nested); | |
| 283 | + | nested = outer; | |
| 284 | + | } | |
| 285 | + | assert!(channel_from_attribute_lists(&nested).is_err()); | |
| 286 | + | } | |
| 287 | + | } | |
| @@ -0,0 +1,197 @@ | |||
| 1 | + | //! Raw Linux Bluetooth sockets through libc. This is the only module in budctl allowed to use | |
| 2 | + | //! `unsafe`; everything above it gets safe functions that return `io::Result`. | |
| 3 | + | //! Constants and struct layouts: docs/protocol/transport.md#sockets. | |
| 4 | + | #![allow(unsafe_code)] | |
| 5 | + | ||
| 6 | + | use std::io; | |
| 7 | + | use std::mem::size_of; | |
| 8 | + | use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; | |
| 9 | + | use std::time::{Duration, Instant}; | |
| 10 | + | ||
| 11 | + | use crate::bt::BdAddr; | |
| 12 | + | ||
| 13 | + | /// Spec: transport.md#sockets | |
| 14 | + | const BTPROTO_L2CAP: libc::c_int = 0; | |
| 15 | + | /// Spec: transport.md#sockets | |
| 16 | + | const BTPROTO_RFCOMM: libc::c_int = 3; | |
| 17 | + | ||
| 18 | + | /// `struct sockaddr_rc`. Spec: transport.md#sockets | |
| 19 | + | #[repr(C)] | |
| 20 | + | struct SockaddrRc { | |
| 21 | + | family: libc::sa_family_t, | |
| 22 | + | bdaddr: [u8; 6], | |
| 23 | + | channel: u8, | |
| 24 | + | } | |
| 25 | + | ||
| 26 | + | /// `struct sockaddr_l2`. Spec: transport.md#sockets | |
| 27 | + | #[repr(C)] | |
| 28 | + | struct SockaddrL2 { | |
| 29 | + | family: libc::sa_family_t, | |
| 30 | + | psm: u16, | |
| 31 | + | bdaddr: [u8; 6], | |
| 32 | + | cid: u16, | |
| 33 | + | bdaddr_type: u8, | |
| 34 | + | } | |
| 35 | + | ||
| 36 | + | pub(crate) enum Target { | |
| 37 | + | /// A stream socket to an RFCOMM channel. | |
| 38 | + | Rfcomm { channel: u8 }, | |
| 39 | + | /// A packet socket to an L2CAP PSM (SDP is PSM 1). | |
| 40 | + | L2cap { psm: u16 }, | |
| 41 | + | } | |
| 42 | + | ||
| 43 | + | /// Open a Bluetooth socket and connect it. `timeout` bounds the connect and every later send. | |
| 44 | + | pub(crate) fn connect(address: BdAddr, target: Target, timeout: Duration) -> io::Result<OwnedFd> { | |
| 45 | + | let (kind, protocol) = match target { | |
| 46 | + | Target::Rfcomm { .. } => (libc::SOCK_STREAM, BTPROTO_RFCOMM), | |
| 47 | + | Target::L2cap { .. } => (libc::SOCK_SEQPACKET, BTPROTO_L2CAP), | |
| 48 | + | }; | |
| 49 | + | // SAFETY: a plain syscall with constant arguments; the result is checked below. | |
| 50 | + | let raw = unsafe { libc::socket(libc::AF_BLUETOOTH, kind | libc::SOCK_CLOEXEC, protocol) }; | |
| 51 | + | if raw < 0 { | |
| 52 | + | return Err(io::Error::last_os_error()); | |
| 53 | + | } | |
| 54 | + | // SAFETY: `raw` is a fresh, valid descriptor that nothing else owns. | |
| 55 | + | let fd = unsafe { OwnedFd::from_raw_fd(raw) }; | |
| 56 | + | ||
| 57 | + | // A blocking connect waits at most SO_SNDTIMEO, then fails with EINPROGRESS. | |
| 58 | + | // Spec: transport.md#connect-timeout | |
| 59 | + | set_timeout(&fd, libc::SO_SNDTIMEO, timeout)?; | |
| 60 | + | ||
| 61 | + | let family = libc::sa_family_t::try_from(libc::AF_BLUETOOTH).map_err(io::Error::other)?; | |
| 62 | + | let bdaddr = address.kernel_order(); | |
| 63 | + | match target { | |
| 64 | + | Target::Rfcomm { channel } => connect_to( | |
| 65 | + | &fd, | |
| 66 | + | &SockaddrRc { | |
| 67 | + | family, | |
| 68 | + | bdaddr, | |
| 69 | + | channel, | |
| 70 | + | }, | |
| 71 | + | )?, | |
| 72 | + | Target::L2cap { psm } => connect_to( | |
| 73 | + | &fd, | |
| 74 | + | &SockaddrL2 { | |
| 75 | + | family, | |
| 76 | + | psm: psm.to_le(), | |
| 77 | + | bdaddr, | |
| 78 | + | cid: 0, | |
| 79 | + | bdaddr_type: 0, | |
| 80 | + | }, | |
| 81 | + | )?, | |
| 82 | + | } | |
| 83 | + | Ok(fd) | |
| 84 | + | } | |
| 85 | + | ||
| 86 | + | fn connect_to<T>(fd: &OwnedFd, address: &T) -> io::Result<()> { | |
| 87 | + | let len = libc::socklen_t::try_from(size_of::<T>()).map_err(io::Error::other)?; | |
| 88 | + | // SAFETY: `address` points to a live, initialised #[repr(C)] sockaddr of exactly `len` bytes. | |
| 89 | + | let rc = unsafe { | |
| 90 | + | libc::connect( | |
| 91 | + | fd.as_raw_fd(), | |
| 92 | + | std::ptr::from_ref(address).cast::<libc::sockaddr>(), | |
| 93 | + | len, | |
| 94 | + | ) | |
| 95 | + | }; | |
| 96 | + | if rc < 0 { | |
| 97 | + | Err(io::Error::last_os_error()) | |
| 98 | + | } else { | |
| 99 | + | Ok(()) | |
| 100 | + | } | |
| 101 | + | } | |
| 102 | + | ||
| 103 | + | fn set_timeout(fd: &OwnedFd, option: libc::c_int, timeout: Duration) -> io::Result<()> { | |
| 104 | + | let tv = libc::timeval { | |
| 105 | + | tv_sec: libc::time_t::try_from(timeout.as_secs()).map_err(io::Error::other)?, | |
| 106 | + | tv_usec: libc::suseconds_t::from(timeout.subsec_micros()), | |
| 107 | + | }; | |
| 108 | + | let len = libc::socklen_t::try_from(size_of::<libc::timeval>()).map_err(io::Error::other)?; | |
| 109 | + | // SAFETY: `tv` lives for the duration of the call and `len` is its size. | |
| 110 | + | let rc = unsafe { | |
| 111 | + | libc::setsockopt( | |
| 112 | + | fd.as_raw_fd(), | |
| 113 | + | libc::SOL_SOCKET, | |
| 114 | + | option, | |
| 115 | + | std::ptr::from_ref(&tv).cast::<libc::c_void>(), | |
| 116 | + | len, | |
| 117 | + | ) | |
| 118 | + | }; | |
| 119 | + | if rc < 0 { | |
| 120 | + | Err(io::Error::last_os_error()) | |
| 121 | + | } else { | |
| 122 | + | Ok(()) | |
| 123 | + | } | |
| 124 | + | } | |
| 125 | + | ||
| 126 | + | /// Wait until the socket has something to read (data, end of stream or an error). | |
| 127 | + | /// `Ok(false)` means `deadline` passed first. | |
| 128 | + | pub(crate) fn wait_readable(fd: &OwnedFd, deadline: Instant) -> io::Result<bool> { | |
| 129 | + | loop { | |
| 130 | + | let left = deadline.saturating_duration_since(Instant::now()); | |
| 131 | + | let ms = libc::c_int::try_from(left.as_millis()).unwrap_or(libc::c_int::MAX); | |
| 132 | + | let mut poll = libc::pollfd { | |
| 133 | + | fd: fd.as_raw_fd(), | |
| 134 | + | events: libc::POLLIN, | |
| 135 | + | revents: 0, | |
| 136 | + | }; | |
| 137 | + | // SAFETY: `poll` is one valid pollfd that lives for the duration of the call. | |
| 138 | + | let rc = unsafe { libc::poll(&mut poll, 1, ms) }; | |
| 139 | + | if rc >= 0 { | |
| 140 | + | return Ok(rc > 0); | |
| 141 | + | } | |
| 142 | + | let error = io::Error::last_os_error(); | |
| 143 | + | if error.kind() != io::ErrorKind::Interrupted { | |
| 144 | + | return Err(error); | |
| 145 | + | } | |
| 146 | + | } | |
| 147 | + | } | |
| 148 | + | ||
| 149 | + | /// One `recv()`. Returns 0 when the other side closed the connection. | |
| 150 | + | pub(crate) fn read(fd: &OwnedFd, buffer: &mut [u8]) -> io::Result<usize> { | |
| 151 | + | loop { | |
| 152 | + | // SAFETY: `buffer` is valid for writes of `buffer.len()` bytes. | |
| 153 | + | let n = unsafe { libc::recv(fd.as_raw_fd(), buffer.as_mut_ptr().cast(), buffer.len(), 0) }; | |
| 154 | + | if let Ok(n) = usize::try_from(n) { | |
| 155 | + | return Ok(n); | |
| 156 | + | } | |
| 157 | + | let error = io::Error::last_os_error(); | |
| 158 | + | if error.kind() != io::ErrorKind::Interrupted { | |
| 159 | + | return Err(error); | |
| 160 | + | } | |
| 161 | + | } | |
| 162 | + | } | |
| 163 | + | ||
| 164 | + | /// Send every byte. `MSG_NOSIGNAL` turns a dead link into `EPIPE` instead of `SIGPIPE`. | |
| 165 | + | pub(crate) fn write_all(fd: &OwnedFd, bytes: &[u8]) -> io::Result<()> { | |
| 166 | + | let mut rest = bytes; | |
| 167 | + | while !rest.is_empty() { | |
| 168 | + | // SAFETY: `rest` is valid for reads of `rest.len()` bytes. | |
| 169 | + | let n = unsafe { libc::send(fd.as_raw_fd(), rest.as_ptr().cast(), rest.len(), libc::MSG_NOSIGNAL) }; | |
| 170 | + | match usize::try_from(n) { | |
| 171 | + | Ok(0) => return Err(io::ErrorKind::WriteZero.into()), | |
| 172 | + | Ok(sent) => rest = rest.get(sent..).unwrap_or_default(), | |
| 173 | + | Err(_) => { | |
| 174 | + | let error = io::Error::last_os_error(); | |
| 175 | + | if error.kind() != io::ErrorKind::Interrupted { | |
| 176 | + | return Err(error); | |
| 177 | + | } | |
| 178 | + | } | |
| 179 | + | } | |
| 180 | + | } | |
| 181 | + | Ok(()) | |
| 182 | + | } | |
| 183 | + | ||
| 184 | + | #[cfg(test)] | |
| 185 | + | mod tests { | |
| 186 | + | use super::*; | |
| 187 | + | ||
| 188 | + | #[test] | |
| 189 | + | fn sockaddr_layouts_match_the_kernel() { | |
| 190 | + | // Spec: transport.md#sockets | |
| 191 | + | assert_eq!(size_of::<SockaddrRc>(), 10); | |
| 192 | + | assert_eq!(size_of::<SockaddrL2>(), 14); | |
| 193 | + | assert_eq!(std::mem::offset_of!(SockaddrRc, channel), 8); | |
| 194 | + | assert_eq!(std::mem::offset_of!(SockaddrL2, cid), 10); | |
| 195 | + | assert_eq!(std::mem::offset_of!(SockaddrL2, bdaddr_type), 12); | |
| 196 | + | } | |
| 197 | + | } | |
| @@ -0,0 +1,155 @@ | |||
| 1 | + | //! Checks for the CLAUDE.md hard rules that the compiler and clippy cannot make on their own. | |
| 2 | + | //! | |
| 3 | + | //! - Rule 1: no network code in our sources, and no banned crate (deny.toml) in Cargo.lock. | |
| 4 | + | //! - Rule 3: every `Spec: <file>.md#<anchor>` comment points at an anchor that exists. | |
| 5 | + | //! | |
| 6 | + | //! The CLI's exit codes are checked in crates/budctl-cli/tests/cli.rs. | |
| 7 | + | ||
| 8 | + | // Test-only file: helpers may panic (clippy.toml exempts only #[test] functions themselves). | |
| 9 | + | #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)] | |
| 10 | + | ||
| 11 | + | use std::collections::BTreeSet; | |
| 12 | + | use std::fs; | |
| 13 | + | use std::path::{Path, PathBuf}; | |
| 14 | + | ||
| 15 | + | fn workspace() -> PathBuf { | |
| 16 | + | Path::new(env!("CARGO_MANIFEST_DIR")).join("../..") | |
| 17 | + | } | |
| 18 | + | ||
| 19 | + | /// Every `.rs` file under `crates/*/src`. | |
| 20 | + | fn sources() -> Vec<PathBuf> { | |
| 21 | + | fn walk(dir: &Path, out: &mut Vec<PathBuf>) { | |
| 22 | + | for entry in fs::read_dir(dir).unwrap() { | |
| 23 | + | let path = entry.unwrap().path(); | |
| 24 | + | if path.is_dir() { | |
| 25 | + | walk(&path, out); | |
| 26 | + | } else if path.extension().is_some_and(|e| e == "rs") { | |
| 27 | + | out.push(path); | |
| 28 | + | } | |
| 29 | + | } | |
| 30 | + | } | |
| 31 | + | let mut files = Vec::new(); | |
| 32 | + | for krate in fs::read_dir(workspace().join("crates")).unwrap() { | |
| 33 | + | let src = krate.unwrap().path().join("src"); | |
| 34 | + | if src.is_dir() { | |
| 35 | + | walk(&src, &mut files); | |
| 36 | + | } | |
| 37 | + | } | |
| 38 | + | assert!(!files.is_empty(), "found no sources to check"); | |
| 39 | + | files | |
| 40 | + | } | |
| 41 | + | ||
| 42 | + | #[test] | |
| 43 | + | fn no_network_code_in_sources() { | |
| 44 | + | // Built from pieces so this file does not trip its own check. | |
| 45 | + | let banned = [ | |
| 46 | + | ["std", "::net"].concat(), | |
| 47 | + | ["Tcp", "Stream"].concat(), | |
| 48 | + | ["Tcp", "Listener"].concat(), | |
| 49 | + | ["Udp", "Socket"].concat(), | |
| 50 | + | ["ToSocket", "Addrs"].concat(), | |
| 51 | + | ["AF_", "INET"].concat(), | |
| 52 | + | ]; | |
| 53 | + | let mut hits = Vec::new(); | |
| 54 | + | for file in sources() { | |
| 55 | + | let text = fs::read_to_string(&file).unwrap(); | |
| 56 | + | for (n, line) in text.lines().enumerate() { | |
| 57 | + | for word in &banned { | |
| 58 | + | if line.contains(word.as_str()) { | |
| 59 | + | hits.push(format!("{}:{}: {word}", file.display(), n + 1)); | |
| 60 | + | } | |
| 61 | + | } | |
| 62 | + | } | |
| 63 | + | } | |
| 64 | + | assert!( | |
| 65 | + | hits.is_empty(), | |
| 66 | + | "network code is not allowed (CLAUDE.md rule 1):\n{}", | |
| 67 | + | hits.join("\n") | |
| 68 | + | ); | |
| 69 | + | } | |
| 70 | + | ||
| 71 | + | /// The crate names in deny.toml's `[bans] deny` list. | |
| 72 | + | fn banned_crates() -> BTreeSet<String> { | |
| 73 | + | let text = fs::read_to_string(workspace().join("deny.toml")).unwrap(); | |
| 74 | + | let mut names = BTreeSet::new(); | |
| 75 | + | let mut in_bans = false; | |
| 76 | + | for line in text.lines() { | |
| 77 | + | let line = line.trim(); | |
| 78 | + | if line.starts_with('[') { | |
| 79 | + | in_bans = line == "[bans]"; | |
| 80 | + | continue; | |
| 81 | + | } | |
| 82 | + | if !in_bans { | |
| 83 | + | continue; | |
| 84 | + | } | |
| 85 | + | if let Some(rest) = line.strip_prefix("{ crate = \"") { | |
| 86 | + | let name = rest.split('"').next().unwrap(); | |
| 87 | + | names.insert(name.to_owned()); | |
| 88 | + | } | |
| 89 | + | } | |
| 90 | + | assert!( | |
| 91 | + | names.contains("reqwest"), | |
| 92 | + | "could not read the [bans] deny list from deny.toml" | |
| 93 | + | ); | |
| 94 | + | names | |
| 95 | + | } | |
| 96 | + | ||
| 97 | + | #[test] | |
| 98 | + | fn no_banned_crate_in_lockfile() { | |
| 99 | + | let lock = fs::read_to_string(workspace().join("Cargo.lock")).unwrap(); | |
| 100 | + | let locked: BTreeSet<&str> = lock | |
| 101 | + | .lines() | |
| 102 | + | .filter_map(|l| l.strip_prefix("name = \"")) | |
| 103 | + | .filter_map(|l| l.strip_suffix('"')) | |
| 104 | + | .collect(); | |
| 105 | + | assert!( | |
| 106 | + | locked.contains("budctl-core"), | |
| 107 | + | "could not read crate names from Cargo.lock" | |
| 108 | + | ); | |
| 109 | + | let found: Vec<String> = banned_crates() | |
| 110 | + | .into_iter() | |
| 111 | + | .filter(|b| locked.contains(b.as_str())) | |
| 112 | + | .collect(); | |
| 113 | + | assert!( | |
| 114 | + | found.is_empty(), | |
| 115 | + | "banned crates in Cargo.lock (see deny.toml): {found:?}" | |
| 116 | + | ); | |
| 117 | + | } | |
| 118 | + | ||
| 119 | + | #[test] | |
| 120 | + | fn spec_references_point_at_existing_anchors() { | |
| 121 | + | let docs = workspace().join("docs/protocol"); | |
| 122 | + | let marker = "Spec: "; | |
| 123 | + | let mut checked = 0; | |
| 124 | + | let mut broken = Vec::new(); | |
| 125 | + | for file in sources() { | |
| 126 | + | let text = fs::read_to_string(&file).unwrap(); | |
| 127 | + | for (n, line) in text.lines().enumerate() { | |
| 128 | + | let mut rest = line; | |
| 129 | + | while let Some(at) = rest.find(marker) { | |
| 130 | + | rest = &rest[at + marker.len()..]; | |
| 131 | + | let reference: String = rest | |
| 132 | + | .chars() | |
| 133 | + | .take_while(|c| c.is_ascii_alphanumeric() || "._-#".contains(*c)) | |
| 134 | + | .collect(); | |
| 135 | + | let Some((doc, anchor)) = reference.split_once('#') else { | |
| 136 | + | continue; | |
| 137 | + | }; | |
| 138 | + | if !doc.ends_with(".md") { | |
| 139 | + | continue; | |
| 140 | + | } | |
| 141 | + | checked += 1; | |
| 142 | + | let spec = fs::read_to_string(docs.join(doc)).unwrap_or_default(); | |
| 143 | + | if !spec.contains(&format!("id=\"{anchor}\"")) { | |
| 144 | + | broken.push(format!("{}:{}: {reference}", file.display(), n + 1)); | |
| 145 | + | } | |
| 146 | + | } | |
| 147 | + | } | |
| 148 | + | } | |
| 149 | + | assert!(checked > 0, "found no Spec: references at all"); | |
| 150 | + | assert!( | |
| 151 | + | broken.is_empty(), | |
| 152 | + | "Spec: references with no matching anchor:\n{}", | |
| 153 | + | broken.join("\n") | |
| 154 | + | ); | |
| 155 | + | } | |
| @@ -0,0 +1,75 @@ | |||
| 1 | + | # cargo-deny policy (`cargo deny check bans licenses sources`). | |
| 2 | + | # CLAUDE.md hard rule 1: no network code anywhere in the dependency tree. | |
| 3 | + | # crates/budctl-core/tests/guards.rs reads the [bans] list below and checks Cargo.lock against | |
| 4 | + | # it, so the rule also holds where cargo-deny is not installed. | |
| 5 | + | ||
| 6 | + | [graph] | |
| 7 | + | targets = ["x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"] | |
| 8 | + | all-features = true | |
| 9 | + | ||
| 10 | + | [advisories] | |
| 11 | + | # Note: this check downloads the RustSec database (a dev-tool network access, not budctl's). | |
| 12 | + | version = 2 | |
| 13 | + | ||
| 14 | + | [licenses] | |
| 15 | + | version = 2 | |
| 16 | + | confidence-threshold = 0.9 | |
| 17 | + | # Everything here is compatible with GPL-3.0-or-later. | |
| 18 | + | allow = [ | |
| 19 | + | "GPL-3.0-or-later", | |
| 20 | + | "MIT", | |
| 21 | + | "Apache-2.0", | |
| 22 | + | "Apache-2.0 WITH LLVM-exception", | |
| 23 | + | "BSD-2-Clause", | |
| 24 | + | "BSD-3-Clause", | |
| 25 | + | "ISC", | |
| 26 | + | "Zlib", | |
| 27 | + | "Unicode-3.0", | |
| 28 | + | "MPL-2.0", | |
| 29 | + | ] | |
| 30 | + | ||
| 31 | + | [bans] | |
| 32 | + | multiple-versions = "warn" | |
| 33 | + | wildcards = "deny" | |
| 34 | + | allow-wildcard-paths = true | |
| 35 | + | deny = [ | |
| 36 | + | # HTTP clients and servers | |
| 37 | + | { crate = "reqwest", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 38 | + | { crate = "hyper", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 39 | + | { crate = "hyper-util", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 40 | + | { crate = "h2", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 41 | + | { crate = "h3", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 42 | + | { crate = "quinn", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 43 | + | { crate = "ureq", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 44 | + | { crate = "surf", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 45 | + | { crate = "isahc", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 46 | + | { crate = "curl", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 47 | + | { crate = "curl-sys", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 48 | + | { crate = "attohttpc", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 49 | + | { crate = "minreq", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 50 | + | { crate = "tiny_http", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 51 | + | { crate = "axum", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 52 | + | { crate = "warp", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 53 | + | { crate = "actix-web", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 54 | + | { crate = "tungstenite", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 55 | + | { crate = "tokio-tungstenite", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 56 | + | # TLS | |
| 57 | + | { crate = "rustls", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 58 | + | { crate = "native-tls", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 59 | + | { crate = "openssl", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 60 | + | { crate = "openssl-sys", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 61 | + | { crate = "aws-lc-rs", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 62 | + | # DNS, telemetry, self-update | |
| 63 | + | { crate = "hickory-resolver", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 64 | + | { crate = "trust-dns-resolver", reason = "no network code (CLAUDE.md rule 1)" }, | |
| 65 | + | { crate = "sentry", reason = "no telemetry (CLAUDE.md non-goals)" }, | |
| 66 | + | { crate = "opentelemetry", reason = "no telemetry (CLAUDE.md non-goals)" }, | |
| 67 | + | { crate = "self_update", reason = "no update checks (CLAUDE.md non-goals)" }, | |
| 68 | + | # Keeps zbus on its own small executor instead of pulling in a whole async runtime. | |
| 69 | + | { crate = "tokio", reason = "not needed; keep the dependency tree small" }, | |
| 70 | + | ] | |
| 71 | + | ||
| 72 | + | [sources] | |
| 73 | + | unknown-registry = "deny" | |
| 74 | + | unknown-git = "deny" | |
| 75 | + | allow-registry = ["https://github.com/rust-lang/crates.io-index"] | |
| @@ -0,0 +1,532 @@ | |||
| 1 | + | # realme Buds T310: control protocol | |
| 2 | + | ||
| 3 | + | This is budctl's clean-room description of how to control the realme Buds T310. Code in `crates/budctl-core/src/devices/realme_t310/` is written from this file, not from any other project's source (CLAUDE.md rules 2 and 3). Each constant in that module cites an anchor here (`Spec: realme_t310.md#anchor`). | |
| 4 | + | ||
| 5 | + | The T310 speaks the protocol family shared by many OPPO, OnePlus and realme buds. Linux socket, SDP and BlueZ details are in [`transport.md`](transport.md). | |
| 6 | + | ||
| 7 | + | <a id="sources"></a> | |
| 8 | + | ## 0. Evidence | |
| 9 | + | ||
| 10 | + | Every fact carries an evidence level that says how far it can be trusted. A fact that is not yet *ours* is tested on the owner's buds before budctl relies on it (CLAUDE.md rule 4). | |
| 11 | + | ||
| 12 | + | | Level | Meaning | | |
| 13 | + | |---|---| | |
| 14 | + | | **t310** | seen on a real T310 by other users, in a report or log. Not yet verified by budctl | | |
| 15 | + | | **ours-YYYY-MM-DD** | verified by budctl on the owner's T310 (see the [verification log](#verification-log)) | | |
| 16 | + | | **vendor** | how the vendor apps (realme Link, HeyMelody) behave. Not seen on a T310 | | |
| 17 | + | | **buds4** | seen on a OnePlus Buds 4. The framing is shared, but the values may differ on the T310 | | |
| 18 | + | | **derived** | computed by us from the facts above. Never seen on the wire | | |
| 19 | + | | **guess** | unverified anywhere. budctl must not send it | | |
| 20 | + | ||
| 21 | + | <a id="identity"></a> | |
| 22 | + | ## 1. Identity | |
| 23 | + | ||
| 24 | + | - **Bluetooth name:** `realme Buds T310`. budctl recognizes the buds by BlueZ's `Name` property, compared exactly. *vendor* | |
| 25 | + | - **Product id:** `063C12`. The reply to `0x0103` should be `00 12 3C 06`, which is the id in 3 bytes, little endian. The reply format is *buds4*; the T310 bytes are *derived*. | |
| 26 | + | - **Not a T310.** If the product id is different, budctl stops: the device is renamed, or it is some other model. | |
| 27 | + | ||
| 28 | + | <a id="transport"></a> | |
| 29 | + | ## 2. Transport | |
| 30 | + | ||
| 31 | + | - **Link:** classic Bluetooth RFCOMM (SPP), not BLE. The connection is one long-lived byte stream, and the buds may send at any time. | |
| 32 | + | - **Service UUIDs.** Try them in this order; each is resolved to a channel through SDP ([transport.md#sdp](transport.md#sdp)). The owner's T310 offers the first, on channel 6 (*ours-2026-10-27*). | |
| 33 | + | 1. `0000079A-D102-11E1-9B23-00025B00A5A5`. The vendor app tries it first. *buds4/vendor* | |
| 34 | + | 2. `00001107-D102-11E1-9B23-00025B00A5A5`. It is kept for other models; on Buds 4 it never connects. | |
| 35 | + | - **Fixed channel.** Android clients sometimes use a fixed channel 15. budctl does not use a fixed channel. | |
| 36 | + | - **One client at a time.** The buds serve one control app at a time. budctl reports a busy channel instead of retrying. | |
| 37 | + | - **Lid close.** Closing the case lid ends the link. *buds4* | |
| 38 | + | ||
| 39 | + | <a id="frame"></a> | |
| 40 | + | ## 3. Frame format | |
| 41 | + | ||
| 42 | + | Every message is wrapped in one frame. | |
| 43 | + | ||
| 44 | + | ``` | |
| 45 | + | AA len slice 00 [fsn] cmd(2, LE) seq paylen(2, LE) payload | |
| 46 | + | ``` | |
| 47 | + | ||
| 48 | + | | Field | Size | Meaning | | |
| 49 | + | |---|---|---| | |
| 50 | + | | `AA` | 1 | start of frame | | |
| 51 | + | | len | 1-3 | **LEB128**: 7 bits per byte, low bits first, top bit = another byte follows. It counts every byte after the length itself | | |
| 52 | + | | slice | 1 | `00` = the whole message in one frame; `01` / `02` / `03` = first / middle / last slice of a long message | | |
| 53 | + | | `00` | 1 | always zero | | |
| 54 | + | | fsn | 1 | slice number from `00`; present only in slices (`01`-`03`) | | |
| 55 | + | | cmd | 2 | command id, little endian | | |
| 56 | + | | seq | 1 | sequence byte (see [§4](#seq)) | | |
| 57 | + | | paylen | 2 | payload length, little endian | | |
| 58 | + | | payload | paylen | message body | | |
| 59 | + | ||
| 60 | + | <a id="frame-whole"></a> | |
| 61 | + | **Whole message.** `len = 7 + paylen`. There is no checksum. *buds4* | |
| 62 | + | ||
| 63 | + | Examples (*buds4*): | |
| 64 | + | ||
| 65 | + | ``` | |
| 66 | + | AA 07 00 00 00 01 01 00 00 handshake 0x0100, seq 01, no payload | |
| 67 | + | AA 0A 00 00 04 04 06 03 00 01 01 01 0x0404 seq 06, payload 01 01 01 | |
| 68 | + | AA 0C 00 00 04 02 FF 05 00 03 01 01 08 00 0x0204 push (seq FF), payload 03 01 01 08 00 | |
| 69 | + | ``` | |
| 70 | + | ||
| 71 | + | <a id="frame-long"></a> | |
| 72 | + | **Long lengths.** A 124-byte payload gives `len = 131`, sent as `AA 83 01`. A 250-byte reply arrives as `AA 81 02` (257). *buds4* | |
| 73 | + | ||
| 74 | + | <a id="frame-slices"></a> | |
| 75 | + | **Slices** (*vendor*): | |
| 76 | + | - A slice frame is `AA len slice 00 fsn <part of cmd/seq/paylen/payload>`, with `len = 3 + part length`. | |
| 77 | + | - The receiver joins the parts in order and parses the result when the `03` slice arrives. A middle or last slice with no first slice is dropped. | |
| 78 | + | - Senders slice only above about 660 bytes, so budctl never sends slices. | |
| 79 | + | ||
| 80 | + | <a id="frame-from-buds"></a> | |
| 81 | + | **Frames the buds start** (*ours-2026-10-27*). On the owner's T310, every frame the buds send on their own (requests such as `0x0501` and `0x0204` pushes) has `08` in the slice byte, not `00`. The rest of the frame is laid out as a whole message, and `len = 7 + paylen` holds. Replies carry `00`. budctl therefore reads a slice byte of `00` or `08` as a whole message. Other values are not seen and are still dropped. Captured examples: | |
| 82 | + | ||
| 83 | + | ``` | |
| 84 | + | AA 07 08 00 01 05 0F 00 00 0x0501 seq 0F, no payload | |
| 85 | + | AA 0F 08 00 04 02 10 08 00 01 03 02 64 01 64 03 00 0x0204 seq 10, battery push 01 03 02 64 01 64 03 00 | |
| 86 | + | ``` | |
| 87 | + | ||
| 88 | + | <a id="frame-receive"></a> | |
| 89 | + | **Receiving**: | |
| 90 | + | - Treat the input as a byte stream: one read may hold several frames or part of one. | |
| 91 | + | - Throw away bytes before `AA`. | |
| 92 | + | - If the length is implausible (more than 3 length bytes, below 4, or above 4096), drop that `AA` and look for the next one. | |
| 93 | + | - If the paylen claims more bytes than the frame holds, keep the bytes that are there. | |
| 94 | + | ||
| 95 | + | <a id="seq"></a> | |
| 96 | + | ## 4. Sequence numbers and replies | |
| 97 | + | ||
| 98 | + | - **Replies.** The sender picks `seq`. The reply has the same seq and the command id with bit 15 set (`0x0106` → `0x8106`). budctl matches a reply on (seq, cmd), which is also how HeyMelody does it. *buds4/vendor* | |
| 99 | + | - **budctl's seq values.** budctl uses `01`-`BF`, counting up and wrapping. Pushes from Buds 4 use `FF` (*buds4*); the T310 uses its own counter ([§3](#frame-from-buds)). | |
| 100 | + | - **Status byte.** The first payload byte of a reply is a status, and `00` means success. A read reply with any other status carries no data. | |
| 101 | + | - **Command groups:** | |
| 102 | + | ||
| 103 | + | | Range | Group | | |
| 104 | + | |---|---| | |
| 105 | + | | `0x01xx` | queries | | |
| 106 | + | | `0x02xx` | event registration and pushes | | |
| 107 | + | | `0x03xx` | firmware update (budctl never sends these; see the non-goals) | | |
| 108 | + | | `0x04xx` | writes | | |
| 109 | + | | `0x05xx` | requests from the buds | | |
| 110 | + | | `0x0Fxx` | private | | |
| 111 | + | ||
| 112 | + | <a id="bitmap"></a> | |
| 113 | + | ## 5. Command bitmap | |
| 114 | + | ||
| 115 | + | - **Reading it.** The reply to the handshake `0x0100` is `00` followed by the bitmap bytes. Read them least-significant bit first: bit *n* is bit `n % 8` of byte `n / 8`. | |
| 116 | + | - **Using it.** A set bit enables a fixed group of commands. **budctl never sends a command whose bit is clear**, as the vendor apps don't. Bits beyond the end of the bitmap count as clear. *vendor* | |
| 117 | + | - **Always allowed:** `0x0100`-`0x0104`, `0x0106`, `0x010B`, `0x010D`. `0x0200` belongs to no bit; the vendor app sends it on every connect. *vendor/buds4* | |
| 118 | + | ||
| 119 | + | Gate table for every command budctl uses or documents here: | |
| 120 | + | ||
| 121 | + | | Command(s) | Gate | | |
| 122 | + | |---|---| | |
| 123 | + | | `0x0100` handshake, `0x0103` product id, `0x0106` battery, `0x010D` switch read, `0x0200` offered events | always | | |
| 124 | + | | `0x0105` firmware | bit 0 | | |
| 125 | + | | `0x0108` gesture read, `0x0401` gesture write | bit 3 | | |
| 126 | + | | `0x0109` wearing | bit 4 | | |
| 127 | + | | `0x0400` find my earbuds | bit 5 | | |
| 128 | + | | `0x0403` switch write | bit 7 | | |
| 129 | + | | `0x010C` noise-control read, `0x0404` noise-control write | bit 8 | | |
| 130 | + | | `0x0405` fit test | bit 9 | | |
| 131 | + | | `0x010F` EQ read, `0x0406` EQ select | bit 10 | | |
| 132 | + | | `0x0114` current codec | bit 17 | | |
| 133 | + | | `0x0205` subscribe | bit 22 | | |
| 134 | + | | `0x0122` custom EQ list, `0x0418` custom EQ write | bit 34 | | |
| 135 | + | | `0x0124` bass level read, `0x041B` bass level write | bit 38 | | |
| 136 | + | ||
| 137 | + | <a id="bitmap-t310"></a> | |
| 138 | + | **The T310's command set** (*t310*), from a log of a real T310, as a decoded list: | |
| 139 | + | ||
| 140 | + | `0100 0101 0102 0103 0104 0105 0106 0107 0108 0109 010B 010C 010D 010F 0112 0114 0115 0116 0122 0124 0205 0400 0401 0403 0404 0405 0406 0407 040B 040D 040E 040F 0416 0418 041B 0F00 0F03 0F04 EF02` | |
| 141 | + | ||
| 142 | + | - **Bits that must be set** for that list (*derived*): 0, 2, 3, 4, 5, 7, 8, 9, 10, 11, 17, 19, 20, 22, 29, 34, 38, 42. | |
| 143 | + | - **A bitmap reply with exactly those bits:** `00 BD 0F 5A 20 44 04` (*derived*). | |
| 144 | + | - **The owner's T310 answers** `00 BF 1F 5A 20 45 04 40 00` (*ours-2026-10-27*; the unit tests use it). That is every bit above plus bits 1, 12, 32 and 54, which gate no command budctl uses. Every bit listed under "what the T310 lacks" is clear. | |
| 145 | + | - **What the T310 lacks.** These commands are absent, so budctl never sends them: | |
| 146 | + | - `0x012F` batch query (bit 56): every read goes out alone. | |
| 147 | + | - `0x041E` 3D-audio source (bit 43). | |
| 148 | + | - `0x0413` phone state (bit 27). | |
| 149 | + | - `0x0130`/`0x0427` alert volume (bit 57). | |
| 150 | + | - `0x0133`/`0x042D` tap sensitivity (bit 61). | |
| 151 | + | - `0x0423` game sound (bit 49). | |
| 152 | + | - `0x012A`/`0x0422` spatial type (bit 47). | |
| 153 | + | ||
| 154 | + | <a id="init"></a> | |
| 155 | + | ## 6. Session start | |
| 156 | + | ||
| 157 | + | **The vendor sequence** (*buds4*, matching HeyMelody): | |
| 158 | + | - Wait 300 ms after the socket connects, then send one message every 200 ms. | |
| 159 | + | - Order: `0x0100` → `0x0103` → `0x0200` → `0x0205` → reads. | |
| 160 | + | - There is no authentication or key exchange. | |
| 161 | + | ||
| 162 | + | **budctl does:** | |
| 163 | + | 1. Connect, then wait 300 ms. During the wait, keep answering the buds' requests ([§7](#buds-requests)). | |
| 164 | + | 2. `0x0100`. Keep the bitmap. | |
| 165 | + | 3. `0x0103`. The id must be `063C12` ([§1](#identity)). | |
| 166 | + | 4. <a id="events-offered"></a>`0x0200` → `00 <count> <codes...>`: the event codes the buds can push. Buds 4 offers `01 02 03 04 08 0B F1 F2 F3` (*buds4*). The owner's T310 offers `01 02 03 04 05 06 0D F1 F4` (*ours-2026-10-27*). | |
| 167 | + | 5. <a id="subscribe"></a>`0x0205 <count> <codes...>` (count first) subscribes. budctl asks for these codes, keeping only the ones the buds offered (*vendor*): | |
| 168 | + | - `01` battery, `02` wearing and `03` noise control; | |
| 169 | + | - `04` (fit-test result) if `0x0405` is allowed. | |
| 170 | + | ||
| 171 | + | Other clients also subscribe to `08` when `0x040D` is allowed. budctl does not: this spec does not say what event `08` carries or what `0x040D` does, and budctl handles no such event. Add it only once both are documented here with a source. | |
| 172 | + | ||
| 173 | + | Never send `01 01 02 02`: that means "count 1, code 01". The `0x8205` ack may never arrive (*buds4*, Nord Buds 3 Pro), so budctl does not wait for it. The T310 does send it, about 50 ms later: `00 04 01 00 02 00 03 00 04 00`, a `00` result for each code (*ours-2026-10-27*). | |
| 174 | + | 6. Reads, one per request. | |
| 175 | + | ||
| 176 | + | **Spacing.** budctl keeps the captured spacing: at least **200 ms** between any two frames it sends. It waits for each reply before sending the next request. | |
| 177 | + | ||
| 178 | + | <a id="buds-requests"></a> | |
| 179 | + | ## 7. Requests from the buds | |
| 180 | + | ||
| 181 | + | The buds send some requests of their own. The answer repeats the request's seq and sets bit 15 of its command. Some firmware resets the link 3-5 s after connecting if the time request goes unanswered (Nord Buds 3 Pro, *buds4*-family capture). | |
| 182 | + | ||
| 183 | + | | From the buds | budctl answers | Meaning | | |
| 184 | + | |---|---|---| | |
| 185 | + | | <a id="time-request"></a>`0x0500` | `00 <Unix seconds, u32 LE>` | time request, sent on connect | | |
| 186 | + | | `0x050C` | `00 01 00` | "is the foreground app on my list?" — no | | |
| 187 | + | | `0x051C` | `00 00 00` | host app capabilities: fast discovery off | | |
| 188 | + | | `0x051D` | `01` | the phone's spatial mode (budctl always answers `01`) | | |
| 189 | + | | a command outside groups `01`-`05` and `0F` | `01` | unknown request | | |
| 190 | + | ||
| 191 | + | - **Test vector** (*buds4*): at Unix time 1750000000, the request `AA 07 00 00 00 05 02 00 00` gets the answer `AA 0C 00 00 00 85 02 05 00 00 80 E1 4E 68`. | |
| 192 | + | - **Not answered:** other `0x05xx` messages and all pushes. Neither vendor app answers them. | |
| 193 | + | - **Pushes `F2` and `F4`:** other clients acknowledge these. budctl does not yet; see [open questions](#open). | |
| 194 | + | - **On the T310** (*ours-2026-10-27*): right after connecting, the buds send `0x0501` with no payload (slice byte `08`, their own seq). budctl does not answer it (it is an "other `0x05xx`" message), and no link reset followed in a 5 s session. No `0x0500` time request was seen. | |
| 195 | + | ||
| 196 | + | <a id="pushes"></a> | |
| 197 | + | ## 8. Pushes | |
| 198 | + | ||
| 199 | + | budctl reads none of these yet. It skips them while waiting for replies (and prints them with `--debug`). | |
| 200 | + | ||
| 201 | + | - **`0x0204` event push.** Seq is `FF`; classify by cmd, because one Buds 4 push used another seq. `payload[0]` is the event code: | |
| 202 | + | ||
| 203 | + | | Code | Event | Layout after the code | | |
| 204 | + | |---|---|---| | |
| 205 | + | | `01` | battery | `<count> (<part> <raw>)…` (as in [§9.1](#battery)) | | |
| 206 | + | | `02` | wearing | `<count> (<part> <state>)…` | | |
| 207 | + | | `03` | noise control | `01 01 <mask LE>` = new mode; `02 <kind> <mask>` = new hold cycle (not a mode) | | |
| 208 | + | | `04` | fit-test result | `(<dev> <result>)…` | | |
| 209 | + | | `05` | game mode | `<state>`. **The T310 never sends this** (*t310*) | | |
| 210 | + | | `F1` | a gesture fired | `<side> <button> <act> <fn> …`. Diagnostic only | | |
| 211 | + | ||
| 212 | + | - **`0x0503`** `<count> (<id> <value>)…`: switch values changed (*vendor*, other realme models). | |
| 213 | + | - **`0x0504`** `<id>`: the EQ preset changed. | |
| 214 | + | ||
| 215 | + | <a id="reads"></a> | |
| 216 | + | ## 9. Reads | |
| 217 | + | ||
| 218 | + | <a id="battery"></a> | |
| 219 | + | ### 9.1 Battery: `0x0106` | |
| 220 | + | ||
| 221 | + | This command is always allowed. Battery reading is confirmed on a T310 (*t310*); the byte layout is *buds4*. | |
| 222 | + | ||
| 223 | + | - **Request:** no payload. | |
| 224 | + | - **Reply:** `00 <count> (<part> <raw>)…`. | |
| 225 | + | - `part` is `01` left, `02` right or `03` case. | |
| 226 | + | - `level = raw & 0x7F` (percent). `charging = raw & 0x80`. | |
| 227 | + | - A level of 0 means "not known", so leave that part out. | |
| 228 | + | - **Example:** `00 03 01 64 02 64 03 50` → left 100 %, right 100 %, case 80 %. | |
| 229 | + | - **No list.** A count of 0, or pairs that run past the end, mean no list. | |
| 230 | + | - **Lid closed.** The case, and a bud inside it, report only while the lid is open (*buds4*). | |
| 231 | + | ||
| 232 | + | <a id="firmware"></a> | |
| 233 | + | ### 9.2 Firmware: `0x0105` | |
| 234 | + | ||
| 235 | + | Evidence: *buds4* | |
| 236 | + | ||
| 237 | + | - **Reply:** `00 <count> <UTF-8 text>`. The text is a comma-separated list of `device,kind,version` triples, where device `1` is left, `2` right and `3` case. | |
| 238 | + | - **Display.** Show the versions of kind `2`, in reply order, joined with dots. HeyMelody shows them this way. If there are none, show the raw text. | |
| 239 | + | - **Example:** `1,2,138,2,2,138,3,1,01,3,2,105` → `138.138.105`. | |
| 240 | + | - **On the T310** (*ours-2026-10-27*): `00 02` then `1,2,1.1.0.43,2,2,1.1.0.43`. Each version is already a full dotted version, so joining them with dots would be misleading. When any version contains a dot, budctl shows each distinct version once, joined with ` / `: here `1.1.0.43`. | |
| 241 | + | ||
| 242 | + | <a id="codec"></a> | |
| 243 | + | ### 9.3 Codec in use: `0x0114` | |
| 244 | + | ||
| 245 | + | Evidence: *buds4* | |
| 246 | + | ||
| 247 | + | - **Reply:** `00 <codec>`. | |
| 248 | + | - **Codec values:** `01` SBC, `02` AAC, `03` LDAC, `04` aptX, `05` aptX HD, `06` aptX Adaptive, `07` LHDC, `08` LHDC V5. | |
| 249 | + | - The T310 offers AAC and SBC (*vendor*). | |
| 250 | + | ||
| 251 | + | <a id="anc-read"></a> | |
| 252 | + | ### 9.4 Noise control: `0x010C 01 01` | |
| 253 | + | ||
| 254 | + | - **Reply:** `00 01 01 <mask LE>`. The mask is 1-4 bytes; the T310's width is unknown, so read every byte that is there. | |
| 255 | + | - **Values.** On realme buds the value read back uses the same bits as the write (*vendor*; tested on the Air7 Pro only): | |
| 256 | + | ||
| 257 | + | | Mask | T310 mode | | |
| 258 | + | |---|---| | |
| 259 | + | | `01` | off | | |
| 260 | + | | `02` | transparency | | |
| 261 | + | | `04` | noise cancelling, light | | |
| 262 | + | | `08` | noise cancelling, deep. Also plain "noise cancelling on": both are the same value | | |
| 263 | + | | `10` | noise cancelling, medium | | |
| 264 | + | ||
| 265 | + | - **No Smart.** The T310 has no Smart level (`20`). | |
| 266 | + | - **Decoding `08`.** budctl shows `08` as noise cancelling with level *deep*. This still needs a hardware check (see [open questions](#open)). | |
| 267 | + | - Noise control as a whole is confirmed on a T310 (*t310*). The bit values above are *vendor*. | |
| 268 | + | ||
| 269 | + | <a id="switches"></a> | |
| 270 | + | ### 9.5 Switches: `0x010D` | |
| 271 | + | ||
| 272 | + | - **Request:** `<count> <ids…>`. budctl asks only for the T310's ids: `05 06 11 1A 1B 1D`. | |
| 273 | + | - `05 06 11 1B 1D` is the vendor app's query list for the T310 (*vendor*). | |
| 274 | + | - `1A` is added because the model has the wind-noise row (`windMode`). | |
| 275 | + | - **Reply:** `00 <count> (<id> <value>)…`. A value of `01` means on, `00` off. | |
| 276 | + | ||
| 277 | + | | Id | Switch | Evidence | | |
| 278 | + | |---|---|---| | |
| 279 | + | | `05` | unknown. The vendor apps always ask it first and ignore the value | *vendor* | | |
| 280 | + | | <a id="switch-game"></a>`06` | game mode ("low latency") | confirmed on a T310, *t310* | | |
| 281 | + | | <a id="switch-dual"></a>`11` | dual connection | seen in a T310 log, *t310* | | |
| 282 | + | | <a id="switch-wind"></a>`1A` | wind-noise reduction | realme Link shows it for the T310 (*vendor*). The T310 answers this id (*ours-2026-10-27*) | | |
| 283 | + | | <a id="switch-spatial"></a>`1B` | 3D sound | seen in a T310 log, *t310* | | |
| 284 | + | | <a id="switch-bass"></a>`1D` | bass boost ("BassWave", "dynamic sound") | seen in a T310 log, *t310* | | |
| 285 | + | ||
| 286 | + | - **The T310 answers every id it is asked, even ids it lacks** (a T310 log: all 23 ids came back). A switch being in the reply therefore proves nothing. | |
| 287 | + | - Writing ids `04 0B 18 27 35` got status `01`, "the buds lack this id" (*t310*). | |
| 288 | + | - That is why budctl asks only for the ids above. | |
| 289 | + | ||
| 290 | + | <a id="eq-read"></a> | |
| 291 | + | ### 9.6 EQ preset: `0x010F` | |
| 292 | + | ||
| 293 | + | Preset names are the vendor app's (*vendor*). | |
| 294 | + | ||
| 295 | + | - **Reply:** `00 <id>`. | |
| 296 | + | - **Built-in presets** on realme buds (*vendor*, unverified on the T310): | |
| 297 | + | ||
| 298 | + | | id | Preset | | |
| 299 | + | |---|---| | |
| 300 | + | | `00` | Pure raw | | |
| 301 | + | | `01` | Deep bass | | |
| 302 | + | | `02` | Pure vocals | | |
| 303 | + | | `03` | Pure bass | | |
| 304 | + | ||
| 305 | + | - **Any other id** is a custom preset. On Buds 4, custom ids start at `04` (*buds4*). | |
| 306 | + | ||
| 307 | + | <a id="bass-read"></a> | |
| 308 | + | ### 9.7 Bass level: `0x0124` | |
| 309 | + | ||
| 310 | + | Evidence: *vendor*; the T310's command set lists it. | |
| 311 | + | ||
| 312 | + | - **Reply:** `00 <min s8> <max s8> <level s8>`. The usual range bytes are `FB 05`, meaning -5..+5. | |
| 313 | + | - **The T310 does not answer it** (*ours-2026-10-27*): an empty `0x0124` got no reply within 3 s, although bit 38 is set. budctl no longer sends it. Bass level returns at W6, from an Android HCI snoop of realme Link reading it. | |
| 314 | + | ||
| 315 | + | <a id="gestures"></a> | |
| 316 | + | ### 9.8 Touch controls: `0x0108` | |
| 317 | + | ||
| 318 | + | - **Reply:** `00 <count> (<dev> <btn> <act> <fn>)…`. Each entry is 4 bytes. | |
| 319 | + | - **`dev`:** `01` left, `02` right, `04` both (on-call rows). | |
| 320 | + | - **`btn`:** `01` main gestures, `06` the on-call group. | |
| 321 | + | - **`act`:** `01` single tap, `02` double tap, `03` triple tap, `04` hold, `05` slide, `06` long hold. | |
| 322 | + | - **`fn` values** (measured on *buds4*; realme uses the same values per *vendor*): | |
| 323 | + | ||
| 324 | + | | `fn` | Function | | |
| 325 | + | |---|---| | |
| 326 | + | | `00` | none | | |
| 327 | + | | `01` | play/pause | | |
| 328 | + | | `03` | voice assistant | | |
| 329 | + | | `05` | previous track | | |
| 330 | + | | `06` | next track | | |
| 331 | + | | `07` | volume (slide) | | |
| 332 | + | | `08` | noise-control cycle | | |
| 333 | + | | `09` | favourite music | | |
| 334 | + | | `0A` | switch track (slide) | | |
| 335 | + | | `0B` | volume up | | |
| 336 | + | | `0C` | volume down | | |
| 337 | + | | `0D` | switch devices | | |
| 338 | + | | `11` | game mode | | |
| 339 | + | | `1C` | decline call | | |
| 340 | + | | `1D` | answer/end call | | |
| 341 | + | ||
| 342 | + | - **What realme Link offers for the T310** (*vendor*). Each bud is set on its own, as `dev` 01/02 with `btn` 01: | |
| 343 | + | ||
| 344 | + | | Gesture | Choices | | |
| 345 | + | |---|---| | |
| 346 | + | | double tap | none, play/pause, next, voice assistant | | |
| 347 | + | | triple tap | none, previous, next, voice assistant, volume up, volume down, game mode | | |
| 348 | + | | hold | none, noise-control cycle, voice assistant, game mode | | |
| 349 | + | ||
| 350 | + | - **Table shape.** No T310 gesture table has ever been captured. Its shape is unknown, so budctl shows every entry it receives. | |
| 351 | + | ||
| 352 | + | <a id="hold-cycle"></a> | |
| 353 | + | ### 9.9 Hold noise-control cycle: `0x010C 02 01` | |
| 354 | + | ||
| 355 | + | Evidence: *vendor* | |
| 356 | + | ||
| 357 | + | - **Reply:** `00 02 01 <mask LE>`. The mask lists which modes a hold steps through, using the noise-control bits: `01` off, `02` transparency, `08` noise cancelling. | |
| 358 | + | - **Both buds.** On realme buds one setting covers both buds (kind `01`). | |
| 359 | + | - **When it applies.** The cycle is used only where a bud's hold gesture is `fn 08`. | |
| 360 | + | ||
| 361 | + | <a id="writes"></a> | |
| 362 | + | ## 10. Writes | |
| 363 | + | ||
| 364 | + | **Not sent by budctl yet.** Each write is enabled only after its hardware checkpoint passes (see the [roadmap](#roadmap)). | |
| 365 | + | ||
| 366 | + | **General rule**: | |
| 367 | + | - A write reply is `0x84xx <status …>`, and `00` means accepted. | |
| 368 | + | - Accepted is not the same as applied. **Always read the state back** and compare it. | |
| 369 | + | ||
| 370 | + | <a id="anc-write"></a> | |
| 371 | + | ### 10.1 Noise control: `0x0404 01 01 <mask>` | |
| 372 | + | ||
| 373 | + | - **Payload:** one bit set, in the fewest bytes, little endian. The T310 masks are the same as for [§9.4](#anc-read): off `01`, transparency `02`, light `04`, deep or "on" `08`, medium `10`. | |
| 374 | + | - **Reply:** `0x8404 <status>`. | |
| 375 | + | - Status `0E` means no bud is in an ear (*buds4*). The T310 has no in-ear sensor (*t310*), so it may never send it. | |
| 376 | + | - **Check:** read `0x010C 01 01` again. | |
| 377 | + | ||
| 378 | + | <a id="switch-write"></a> | |
| 379 | + | ### 10.2 Switches: `0x0403 <id> <01|00>` | |
| 380 | + | ||
| 381 | + | - **Reply:** `0x8403 <status>`: | |
| 382 | + | - `00` accepted | |
| 383 | + | - `01` the buds lack this id | |
| 384 | + | - `02` or anything else: refused for now | |
| 385 | + | - **Check:** read `0x010D` again. | |
| 386 | + | - **Game mode on the T310.** The buds never push the new value (*t310*). On Buds 4 the change lands about 1 s after the ack, and a read sooner still returns the old value (*buds4*). So budctl reads back after about 1 s, and again up to 3 s later. | |
| 387 | + | - **Dual connection.** Other clients also send `0x0413` afterwards. The T310's bitmap lacks it, so budctl sends only `0x0403 11`. Turning dual connection off may drop the link to one host, so it is tested last. | |
| 388 | + | ||
| 389 | + | <a id="eq-write"></a> | |
| 390 | + | ### 10.3 EQ preset: `0x0406 <id>` | |
| 391 | + | ||
| 392 | + | Evidence: *vendor* | |
| 393 | + | ||
| 394 | + | - **Reply:** `0x8406 <status>`. | |
| 395 | + | - **Check:** read `0x010F` again. | |
| 396 | + | ||
| 397 | + | <a id="bass-write"></a> | |
| 398 | + | ### 10.4 Bass level: `0x041B FB 05 <level s8>` | |
| 399 | + | ||
| 400 | + | Evidence: *vendor* | |
| 401 | + | ||
| 402 | + | - **Range:** -5..+5. | |
| 403 | + | - **Check:** read `0x0124` again. | |
| 404 | + | ||
| 405 | + | <a id="find"></a> | |
| 406 | + | ### 10.5 Find my earbuds: `0x0400 01` / `0x0400 00` | |
| 407 | + | ||
| 408 | + | Evidence: *buds4* | |
| 409 | + | ||
| 410 | + | - `01` starts ringing both buds and `00` stops it. The reply is `0x8400 00`. | |
| 411 | + | - **It is loud**, so budctl warns before ringing. | |
| 412 | + | - Only the ack can be checked: there is no state to read back. | |
| 413 | + | ||
| 414 | + | <a id="gesture-write"></a> | |
| 415 | + | ### 10.6 Touch controls: `0x0401 <count> (<dev> <btn> <act> <fn>)…` | |
| 416 | + | ||
| 417 | + | The command and layout are *buds4*; the realme rules are *vendor*. | |
| 418 | + | ||
| 419 | + | - **Whole table.** The write carries the whole table. Start from a table read in the same session and change only the targeted entries. | |
| 420 | + | - **Reply:** `0x8401 00`. | |
| 421 | + | - **Check:** read `0x0108` again after about 600 ms and compare. | |
| 422 | + | - **Wrong command ids fail silently.** For example, `0x0402` gets no reply at all. | |
| 423 | + | ||
| 424 | + | <a id="hold-cycle-write"></a> | |
| 425 | + | ### 10.7 Hold cycle: `0x0404 02 01 <mask>` | |
| 426 | + | ||
| 427 | + | Evidence: *vendor* | |
| 428 | + | ||
| 429 | + | - **Mask:** the fewest bytes that hold it, and at least 2 modes (*vendor*). | |
| 430 | + | - **Level bits.** The buds silently drop level bits (*buds4*). | |
| 431 | + | - **Check:** read `0x010C 02 01`. | |
| 432 | + | ||
| 433 | + | <a id="fit-test"></a> | |
| 434 | + | ### 10.8 Fit test: `0x0405 01` / `0x0405 00` | |
| 435 | + | ||
| 436 | + | Evidence: *buds4* | |
| 437 | + | ||
| 438 | + | - `01` starts the test and `00` stops it. | |
| 439 | + | - **Result:** arrives as push `04 (<dev> <result>)…`, where `1` = good, `0` = average and `6` = poor. The push needs event `04` subscribed. | |
| 440 | + | - **Timing:** about 8.6 s on Buds 4. Both buds must be in the ears. | |
| 441 | + | ||
| 442 | + | <a id="custom-eq"></a> | |
| 443 | + | ### 10.9 Custom EQ: list `0x0122`, write `0x0418` | |
| 444 | + | ||
| 445 | + | Evidence: *vendor* | |
| 446 | + | ||
| 447 | + | - **List reply:** `00 <count>` then, per preset: `<selected> <min> <max> <id> <nameLen> <name> <bands> (<freq u16 LE> <gain s8>)…`. | |
| 448 | + | - **Write:** `0x0418 <action> <min> <max> <id> <nameLen> <name> <bands> (<freq> <gain>)…`. The reply is `0x8418 00 <id>`. | |
| 449 | + | - `01` creates a preset; send id `00` and the buds assign one. | |
| 450 | + | - `02` saves the whole preset and selects it. | |
| 451 | + | - `03` deletes it. | |
| 452 | + | - **Ids are renumbered** after a create or delete, so read the list again each time. | |
| 453 | + | - **Defaults:** 6 bands at 62, 250, 1000, 4000, 8000 and 16000 Hz. Range bytes `FA 06` mean -6..+6 dB. At most 3 presets. | |
| 454 | + | ||
| 455 | + | <a id="absent"></a> | |
| 456 | + | ## 11. Not on the T310 | |
| 457 | + | ||
| 458 | + | - **Wear detection.** Id `04` was refused with `01` (*t310*), and there is no in-ear sensor. A bud out of the case reads as "out" in every state. | |
| 459 | + | - **Hi-Res** `18`, **hearing profile** `0B`, **game sound** `27`, **hold volume** `35`: refused with `01` (*t310*). | |
| 460 | + | - **Not in the T310 bitmap** ([§5](#bitmap-t310)): alert volume, tap sensitivity, spatial type, 3D-audio source, game EQ, head gestures, personalised ANC and batch query. | |
| 461 | + | ||
| 462 | + | <a id="open"></a> | |
| 463 | + | ## 12. Open questions (need a capture or a test on the owner's buds) | |
| 464 | + | ||
| 465 | + | 1. ~~Which service UUID the T310 offers, and its RFCOMM channel.~~ Answered at HW1: `0000079a-d102-11e1-9b23-00025b00a5a5` on channel 6. | |
| 466 | + | 2. ~~The real bitmap bytes, the product-id reply and the offered events.~~ Answered at HW1; see [§5](#bitmap-t310) and [§6](#events-offered). | |
| 467 | + | 3. Partly answered at HW1: no `0x0500`, but an unanswered `0x0501` with no reset ([§7](#buds-requests)). `F2`/`F4` were offered but not subscribed, so none arrived. What `0x0501` asks for is unknown. | |
| 468 | + | 4. What "busy" looks like when the phone holds the channel: the connect is refused, the connect succeeds and the buds stay silent, or the buds drop the laptop's link. A local holder gives `EBUSY` (HW1). Until the phone case is tested, budctl also treats a silent handshake as "channel busy" (exit 3). | |
| 469 | + | 5. The width of the noise-control value, and whether `08` reads back as deep. | |
| 470 | + | 6. ~~Whether the T310 answers id `1A` (wind).~~ It does (HW1). What id `05` means is still open: it reads `00`. | |
| 471 | + | 7. How long after the game-mode ack the new value shows up in `0x010D`. | |
| 472 | + | 8. The shape of the T310 gesture table is answered at HW1: six entries, `<side> <group> <act> <fn>`, double tap, triple tap and hold for each bud. The names of the EQ presets in realme Link are still open. | |
| 473 | + | 10. Why the T310 ignores `0x0124` although bit 38 is set ([§9.7](#bass-read)). Needs a realme Link capture before W6. | |
| 474 | + | 9. Whether the minimum 200 ms spacing between sends is needed. | |
| 475 | + | ||
| 476 | + | <a id="roadmap"></a> | |
| 477 | + | ## 13. Roadmap and hardware checkpoints | |
| 478 | + | ||
| 479 | + | The owner runs each checkpoint with `--debug` and pastes the output. Results go into the [verification log](#verification-log). | |
| 480 | + | ||
| 481 | + | **HW1, read-only:** | |
| 482 | + | - Run `budctl list`, `budctl --debug status`, `budctl --json status` and `budctl --debug touch`. | |
| 483 | + | - Then run `status` again twice: once while the phone app is connected (the busy path), and once with the case lid closed (the not-connected path). | |
| 484 | + | ||
| 485 | + | **Writes, one per checkpoint, in this order:** | |
| 486 | + | ||
| 487 | + | | Step | Write | | |
| 488 | + | |---|---| | |
| 489 | + | | W1 | `anc off/transparency/on` | | |
| 490 | + | | W2 | `anc light/medium/deep` | | |
| 491 | + | | W3 | `game on/off` | | |
| 492 | + | | W4 | `eq <preset>` | | |
| 493 | + | | W5 | `set bass-boost` → `set spatial` → `set wind` → `set dual`, each one checkpoint | | |
| 494 | + | | W6 | `bass <level>` | | |
| 495 | + | | W7 | `find` | | |
| 496 | + | | W8 | `touch <side> <gesture> <action>` (`--dry-run` first) | | |
| 497 | + | | W9 | `touch cycle` | | |
| 498 | + | | W10 | `fit-test` | | |
| 499 | + | | W11 | custom EQ (create, then save, then delete) | | |
| 500 | + | ||
| 501 | + | Ask for an Android HCI snoop of realme Link before W11, and for any write that does nothing. | |
| 502 | + | ||
| 503 | + | <a id="verification-log"></a> | |
| 504 | + | ## 14. Verification log | |
| 505 | + | ||
| 506 | + | | Date | Checkpoint | Result | Notes | | |
| 507 | + | |---|---|---|---| | |
| 508 | + | | 2026-10-27 | HW1 `list`, `status`, `--json status`, `touch`, not-connected path, busy path (local holder) | pass, with fixes | See below. Busy with the phone app as the holder is still untested | | |
| 509 | + | ||
| 510 | + | **HW1, 2026-10-27** (budctl 0.1.0, `--debug` output pasted by the owner): | |
| 511 | + | - `list` finds `realme Buds T310` at `88:0E:85:46:FE:5C`, connected, recognized by `Name`. | |
| 512 | + | - SDP: service `0000079a-d102-11e1-9b23-00025b00a5a5` on RFCOMM channel 6. | |
| 513 | + | - Handshake: bitmap `00 BF 1F 5A 20 45 04 40 00`, product id `00 12 3C 06` (`063C12`), events offered `01 02 03 04 05 06 0D F1 F4`. The subscribe `04 01 02 03 04` is acked. | |
| 514 | + | - Reads that answered, with what budctl showed: | |
| 515 | + | - battery `00 03 02 64 01 64 03 00`: left and right 100 %, case unknown; | |
| 516 | + | - noise control `00 01 01 08`: anc, deep; | |
| 517 | + | - switches `00 06 05 00 06 00 11 01 1A 01 1B 00 1D 00`: game off, dual on, wind on, 3D off, bass boost off; | |
| 518 | + | - EQ `00 03`: pure-bass; | |
| 519 | + | - codec `00 01`: SBC; | |
| 520 | + | - firmware `1,2,1.1.0.43,2,2,1.1.0.43`; | |
| 521 | + | - gestures: both buds double tap play/pause, triple tap next, hold noise cycle; | |
| 522 | + | - hold cycle `00 02 01 0A`: transparency and anc. | |
| 523 | + | - Every reply came 50-90 ms after its request. | |
| 524 | + | - `0x0124` (bass level) got no reply in 3 s. | |
| 525 | + | - Lid closed: `status` reports "paired but not connected" and exits 2. | |
| 526 | + | - Busy path, first try: with the phone app connected, BlueZ listed the buds as not connected to the laptop, so budctl stopped before RFCOMM (exit 2). This is inconclusive: the laptop's link was down, so the control channel was never tried. | |
| 527 | + | - Busy path, local variant: a second socket on the laptop connected to channel 6 and held it, sending nothing. budctl's connect then failed with `EBUSY` (os error 16), and budctl reported "control channel busy" and exited 3. budctl sent nothing to the buds. This shows that a local client holding the channel gives exit 3. When the phone holds it, the buds decide what happens, and that is still untested. | |
| 528 | + | - Fixes made from this checkpoint: | |
| 529 | + | - the parser accepts slice byte `08` ([§3](#frame-from-buds)); before, it silently dropped every frame the buds start; | |
| 530 | + | - `0x0124` is no longer sent; | |
| 531 | + | - firmware display ([§9.2](#firmware)). | |
| 532 | + | - Still to confirm by the owner against the phone app: the noise-control mode and level, the EQ preset, the dual and wind switches, the gestures and the hold cycle. | |
| @@ -0,0 +1,140 @@ | |||
| 1 | + | # Transport: Linux Bluetooth sockets, SDP and BlueZ | |
| 2 | + | ||
| 3 | + | This file covers the parts of the link that are the same for every device: finding paired devices, finding the RFCOMM channel and opening sockets. Device protocols are in `<device>.md`. | |
| 4 | + | ||
| 5 | + | All of this is public, standard material: | |
| 6 | + | - the Bluetooth Core Specification (SDP: Vol 3, Part B); | |
| 7 | + | - the Linux kernel's Bluetooth socket headers (`include/net/bluetooth/{bluetooth,l2cap,rfcomm}.h`); | |
| 8 | + | - BlueZ's D-Bus API documentation (`doc/org.bluez.Device.rst`, `doc/org.freedesktop.DBus.ObjectManager`). | |
| 9 | + | ||
| 10 | + | ||
| 11 | + | ||
| 12 | + | <a id="paired-devices"></a> | |
| 13 | + | ## 1. Paired devices (BlueZ over D-Bus) | |
| 14 | + | ||
| 15 | + | - **Connection.** budctl talks to BlueZ only over the **system bus**. The D-Bus specification gives its default address as `unix:path=/var/run/dbus/system_bus_socket`. budctl connects to that path itself and hands the stream to zbus. It never reads `DBUS_SYSTEM_BUS_ADDRESS`, which could name a TCP address (CLAUDE.md rule 1). | |
| 16 | + | - **Listing devices.** Call `org.freedesktop.DBus.ObjectManager.GetManagedObjects` on service `org.bluez`, path `/`. Each object that has the interface `org.bluez.Device1` is a known device. | |
| 17 | + | - **Device1 properties used:** | |
| 18 | + | ||
| 19 | + | | Property | Type | Use | | |
| 20 | + | |---|---|---| | |
| 21 | + | | `Address` | string `"AA:BB:CC:DD:EE:FF"` | the device to connect to | | |
| 22 | + | | `Name` | string | the name the device reports. Recognition uses this, because the user can rename `Alias` | | |
| 23 | + | | `Alias` | string | shown to the user | | |
| 24 | + | | `Paired` | bool | only paired devices are listed | | |
| 25 | + | | `Connected` | bool | budctl only opens a control link when the audio link is already up | | |
| 26 | + | | `UUIDs` | array of strings | service UUIDs from the device's SDP record, as BlueZ caches them (lowercase) | | |
| 27 | + | ||
| 28 | + | - **Shutdown.** Drop the D-Bus connection before opening Bluetooth sockets. zbus runs an internal thread while a connection is alive. | |
| 29 | + | ||
| 30 | + | <a id="sockets"></a> | |
| 31 | + | ## 2. Linux Bluetooth sockets | |
| 32 | + | ||
| 33 | + | **Constants** (from `<sys/socket.h>` and the kernel Bluetooth headers): | |
| 34 | + | ||
| 35 | + | | Name | Value | | |
| 36 | + | |---|---| | |
| 37 | + | | `AF_BLUETOOTH` | 31 | | |
| 38 | + | | `BTPROTO_L2CAP` | 0 (used with `SOCK_SEQPACKET`, for SDP) | | |
| 39 | + | | `BTPROTO_RFCOMM` | 3 (used with `SOCK_STREAM`, for the control link) | | |
| 40 | + | ||
| 41 | + | **Address byte order.** A `bdaddr_t` holds the address **reversed**: `AA:BB:CC:DD:EE:FF` is stored as bytes `FF EE DD CC BB AA`. | |
| 42 | + | ||
| 43 | + | `struct sockaddr_rc` is 10 bytes: | |
| 44 | + | ||
| 45 | + | | Offset | Field | Type | | |
| 46 | + | |---|---|---| | |
| 47 | + | | 0 | `rc_family` | u16, `AF_BLUETOOTH` | | |
| 48 | + | | 2 | `rc_bdaddr` | 6 bytes, reversed address | | |
| 49 | + | | 8 | `rc_channel` | u8 | | |
| 50 | + | | 9 | padding | — | | |
| 51 | + | ||
| 52 | + | `struct sockaddr_l2` is 14 bytes: | |
| 53 | + | ||
| 54 | + | | Offset | Field | Type | | |
| 55 | + | |---|---|---| | |
| 56 | + | | 0 | `l2_family` | u16 | | |
| 57 | + | | 2 | `l2_psm` | u16, little endian | | |
| 58 | + | | 4 | `l2_bdaddr` | 6 bytes, reversed address | | |
| 59 | + | | 10 | `l2_cid` | u16, little endian, 0 | | |
| 60 | + | | 12 | `l2_bdaddr_type` | u8, 0 = BR/EDR | | |
| 61 | + | | 13 | padding | — | | |
| 62 | + | ||
| 63 | + | The SDP server always listens on **PSM 1**. | |
| 64 | + | ||
| 65 | + | <a id="connect-timeout"></a> | |
| 66 | + | **Connect timeout.** | |
| 67 | + | - For Bluetooth sockets, a blocking `connect()` waits at most the socket's `SO_SNDTIMEO`. | |
| 68 | + | - When that time runs out, the kernel returns **`EINPROGRESS`** (`bt_sock_wait_state`), not `ETIMEDOUT`. budctl treats both as a timeout. | |
| 69 | + | ||
| 70 | + | <a id="errno"></a> | |
| 71 | + | **What budctl makes of errno.** This mapping is our own choice. It decides the exit code. | |
| 72 | + | ||
| 73 | + | | errno | Meaning for budctl | Exit | | |
| 74 | + | |---|---|---| | |
| 75 | + | | `EBUSY`, `EADDRINUSE`, `ECONNREFUSED` on the RFCOMM connect | another client holds the control channel | 3 | | |
| 76 | + | | `EHOSTDOWN`, `EHOSTUNREACH`, `ENOTCONN`, `ECONNRESET`, `ECONNABORTED`, `EPIPE`, `ENODEV`, `ENETDOWN` | buds out of range, adapter off, or link dropped (for example, the case lid closed) | 2 | | |
| 77 | + | | `ETIMEDOUT`, `EINPROGRESS`, `EAGAIN` | no answer in time | 4 | | |
| 78 | + | | anything else | OS error, reported with its text | 2 | | |
| 79 | + | ||
| 80 | + | **Reads** use `poll(POLLIN)` with the time left until the deadline. A `read()` that returns 0 bytes means the buds closed the link. | |
| 81 | + | ||
| 82 | + | **Writes** use `send(..., MSG_NOSIGNAL)`, so a dead link gives `EPIPE` instead of killing the process with `SIGPIPE`. | |
| 83 | + | ||
| 84 | + | <a id="sdp"></a> | |
| 85 | + | ## 3. Finding the RFCOMM channel with SDP | |
| 86 | + | ||
| 87 | + | The buds publish their control service in their SDP record. budctl asks for that record over L2CAP PSM 1 and reads the RFCOMM channel number out of it. It never uses a fixed channel. | |
| 88 | + | ||
| 89 | + | <a id="sdp-pdu"></a> | |
| 90 | + | **PDU header** (Core Spec Vol 3 Part B §4.2). All multi-byte fields are **big endian**. | |
| 91 | + | ||
| 92 | + | | Field | Size | | |
| 93 | + | |---|---| | |
| 94 | + | | PDU id | 1 | | |
| 95 | + | | transaction id | 2 | | |
| 96 | + | | parameter length | 2 | | |
| 97 | + | | parameters | n | | |
| 98 | + | ||
| 99 | + | | PDU id | Name | | |
| 100 | + | |---|---| | |
| 101 | + | | `0x01` | ErrorResponse; parameters: error code (u16) | | |
| 102 | + | | `0x06` | ServiceSearchAttributeRequest | | |
| 103 | + | | `0x07` | ServiceSearchAttributeResponse | | |
| 104 | + | ||
| 105 | + | <a id="sdp-request"></a> | |
| 106 | + | **ServiceSearchAttributeRequest parameters** (§4.7.1): | |
| 107 | + | 1. ServiceSearchPattern: a data-element sequence of UUIDs. budctl sends one 128-bit UUID: `35 11 1C <16 UUID bytes>`. | |
| 108 | + | 2. MaximumAttributeByteCount (u16): `FF FF`. The server still splits a long answer with continuation state. | |
| 109 | + | 3. AttributeIDList: a data-element sequence of attribute ids. budctl asks only for `0x0004`, the ProtocolDescriptorList: `35 03 09 00 04`. | |
| 110 | + | 4. ContinuationState: 1 length byte followed by that many bytes. It is `00` on the first request, and on each later request it is copied from the previous response. | |
| 111 | + | ||
| 112 | + | <a id="sdp-response"></a> | |
| 113 | + | **ServiceSearchAttributeResponse parameters** (§4.7.2): | |
| 114 | + | 1. AttributeListsByteCount (u16). | |
| 115 | + | 2. AttributeLists: that many bytes. This is one part of a data element. Joined across all responses, it forms the complete data element. | |
| 116 | + | 3. ContinuationState. If its length byte is not 0, send the request again with this state. budctl gives up after 16 rounds. | |
| 117 | + | ||
| 118 | + | <a id="sdp-data-elements"></a> | |
| 119 | + | **Data elements** (§3). | |
| 120 | + | - **Header byte:** `type = byte >> 3`, `size index = byte & 7`. | |
| 121 | + | - **Types used here:** 0 nil, 1 unsigned int, 2 signed int, 3 UUID, 4 text, 5 bool, 6 sequence, 7 alternative, 8 URL. | |
| 122 | + | - **Size index:** | |
| 123 | + | - 0 → 1 byte of data (nil: 0 bytes) | |
| 124 | + | - 1 → 2 bytes | |
| 125 | + | - 2 → 4 bytes | |
| 126 | + | - 3 → 8 bytes | |
| 127 | + | - 4 → 16 bytes | |
| 128 | + | - 5, 6, 7 → the data length is in the next 1, 2 or 4 bytes (big endian), then the data follows. | |
| 129 | + | - **UUIDs** are 2, 4 or 16 bytes. A short UUID `xxxx` or `xxxxxxxx` stands for `xxxxxxxx-0000-1000-8000-00805F9B34FB` (the Bluetooth base UUID). | |
| 130 | + | ||
| 131 | + | <a id="sdp-rfcomm-channel"></a> | |
| 132 | + | **Reading the channel.** | |
| 133 | + | - The joined AttributeLists is a sequence with one item per matching service record. Each item is a sequence of (attribute id, value) pairs. | |
| 134 | + | - For attribute `0x0004`, the value is a sequence of protocol descriptors, each itself a sequence that starts with a UUID. | |
| 135 | + | - The descriptor whose UUID is **RFCOMM (`0x0003`)** has the channel number next, as an unsigned 8-bit integer. | |
| 136 | + | - Example: | |
| 137 | + | `35 0C 35 03 19 01 00 35 05 19 00 03 08 0F` | |
| 138 | + | - `35 03 19 01 00` is L2CAP (`0x0100`). | |
| 139 | + | - `35 05 19 00 03 08 0F` is RFCOMM, channel 15. | |
| 140 | + | - budctl walks the data elements properly. It does not search for a byte pattern. | |
| @@ -0,0 +1,2 @@ | |||
| 1 | + | # Matches the width the code was written at. | |
| 2 | + | max_width = 120 | |