datap-0.4 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. datap_0_4-0.4.0/PKG-INFO +219 -0
  2. datap_0_4-0.4.0/README.md +199 -0
  3. datap_0_4-0.4.0/pyproject.toml +29 -0
  4. datap_0_4-0.4.0/setup.cfg +4 -0
  5. datap_0_4-0.4.0/src/btsh/__init__.py +42 -0
  6. datap_0_4-0.4.0/src/btsh/__main__.py +5 -0
  7. datap_0_4-0.4.0/src/btsh/audio.py +143 -0
  8. datap_0_4-0.4.0/src/btsh/auto.py +443 -0
  9. datap_0_4-0.4.0/src/btsh/ble.py +147 -0
  10. datap_0_4-0.4.0/src/btsh/bt.py +90 -0
  11. datap_0_4-0.4.0/src/btsh/channel.py +116 -0
  12. datap_0_4-0.4.0/src/btsh/channels.py +119 -0
  13. datap_0_4-0.4.0/src/btsh/cli.py +811 -0
  14. datap_0_4-0.4.0/src/btsh/client.py +82 -0
  15. datap_0_4-0.4.0/src/btsh/codec.py +204 -0
  16. datap_0_4-0.4.0/src/btsh/crypto.py +259 -0
  17. datap_0_4-0.4.0/src/btsh/framing.py +96 -0
  18. datap_0_4-0.4.0/src/btsh/hub.py +266 -0
  19. datap_0_4-0.4.0/src/btsh/mcp.py +213 -0
  20. datap_0_4-0.4.0/src/btsh/modem.py +199 -0
  21. datap_0_4-0.4.0/src/btsh/node.py +190 -0
  22. datap_0_4-0.4.0/src/btsh/py.typed +0 -0
  23. datap_0_4-0.4.0/src/btsh/server.py +194 -0
  24. datap_0_4-0.4.0/src/btsh/session.py +224 -0
  25. datap_0_4-0.4.0/src/btsh/setup.py +208 -0
  26. datap_0_4-0.4.0/src/btsh/tcp.py +75 -0
  27. datap_0_4-0.4.0/src/btsh/transport.py +325 -0
  28. datap_0_4-0.4.0/src/datap_0.4.egg-info/PKG-INFO +219 -0
  29. datap_0_4-0.4.0/src/datap_0.4.egg-info/SOURCES.txt +37 -0
  30. datap_0_4-0.4.0/src/datap_0.4.egg-info/dependency_links.txt +1 -0
  31. datap_0_4-0.4.0/src/datap_0.4.egg-info/entry_points.txt +2 -0
  32. datap_0_4-0.4.0/src/datap_0.4.egg-info/requires.txt +14 -0
  33. datap_0_4-0.4.0/src/datap_0.4.egg-info/top_level.txt +1 -0
  34. datap_0_4-0.4.0/tests/test_channels.py +182 -0
  35. datap_0_4-0.4.0/tests/test_crypto.py +102 -0
  36. datap_0_4-0.4.0/tests/test_e2e.py +132 -0
  37. datap_0_4-0.4.0/tests/test_framing.py +33 -0
  38. datap_0_4-0.4.0/tests/test_mesh.py +158 -0
  39. datap_0_4-0.4.0/tests/test_modem.py +52 -0
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: datap-0.4
3
+ Version: 0.4.0
4
+ Summary: Shell over a Bluetooth speaker's audio codec: run commands without an SSH server
5
+ Author: Marc Partensky
6
+ License: MIT
7
+ Keywords: bluetooth,a2dp,sbc,modem,shell,ssh
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: av>=12
11
+ Provides-Extra: sbc
12
+ Requires-Dist: av>=12; extra == "sbc"
13
+ Provides-Extra: portaudio
14
+ Requires-Dist: sounddevice>=0.4; extra == "portaudio"
15
+ Provides-Extra: ble
16
+ Requires-Dist: bleak>=0.21; extra == "ble"
17
+ Provides-Extra: all
18
+ Requires-Dist: sounddevice>=0.4; extra == "all"
19
+ Requires-Dist: bleak>=0.21; extra == "all"
20
+
21
+ # btsh
22
+
23
+ A shell that rides on a Bluetooth link, no SSH server anywhere.
24
+
25
+ `btsh` puts a framed, acknowledged, optionally authenticated protocol on top of
26
+ whatever Bluetooth channel you can actually use, and turns it into `exec` and
27
+ `shell` commands on the peer. Three links ship:
28
+
29
+ | Link | Carries | Works on | Server side |
30
+ |---|---|---|---|
31
+ | `portaudio` | 4-FSK modem over the speaker codec (SBC verified) | Linux, macOS, Windows | any of the three |
32
+ | `pw` | same modem, PipeWire nodes, codec read from `pw-dump` | Linux | Linux |
33
+ | `ble` | same frames, no modem, GATT write/notify | Linux, macOS, Windows | Android app (`android/`) |
34
+ | `fifo` | same modem, two named pipes | any | any (two local processes, tests) |
35
+
36
+ ## The honest part about Android
37
+
38
+ The intended topology ("an Android app that pretends to be AirPods, plays music
39
+ and runs the shell") cannot use A2DP audio on an unrooted phone:
40
+
41
+ * `A2dpSinkService` is a system service and every entry point enforces
42
+ `BLUETOOTH_PRIVILEGED` (see AOSP `packages/modules/Bluetooth`,
43
+ `a2dpsink/A2dpSinkService.java`). A normal app cannot register as an A2DP
44
+ sink, so the phone cannot be the "speaker".
45
+ * Even the system sink never hands the decoded stream to an app: A2DP audio is
46
+ routed inside the Bluetooth stack to the audio HAL. There is no
47
+ `AudioRecord`/`AudioTrack` path for it.
48
+ * HFP is the same story: SCO audio belongs to the telephony stack.
49
+
50
+ So the Android app in `android/` is a **BLE GATT peripheral** that advertises as
51
+ `AirPods Pro` (name plus Apple manufacturer data in the scan response) and
52
+ serves the exact same frames. That is the only radio channel an app may serve
53
+ on Android, and `bleak` drives it from all three desktop OSes. The acoustic
54
+ modem stays available where the OS does expose the stream (desktops), and it is
55
+ what makes "the speaker's codec carries your shell" literal.
56
+
57
+ ## Install
58
+
59
+ ```bash
60
+ pip install -e . # core, stdlib only
61
+ pip install -e ".[all]" # + sounddevice (PortAudio) and bleak
62
+ ```
63
+
64
+ `ffmpeg` is only needed for `--codec sbc` and `btsh selftest`: it is what pushes
65
+ a burst through the same SBC transform a Bluetooth speaker applies.
66
+
67
+ ## Quick start
68
+
69
+ In-process demo, commands really executed, every burst pushed through SBC:
70
+
71
+ ```bash
72
+ btsh demo
73
+ ```
74
+
75
+ Two processes on one host, no socket and no SSH, still through SBC:
76
+
77
+ ```bash
78
+ btsh serve --transport fifo --codec sbc --key ~/.btsh.key &
79
+ btsh exec --transport fifo --codec sbc --key ~/.btsh.key -- "uname -a | head -1"
80
+ ```
81
+
82
+ Real speaker, PipeWire (Linux):
83
+
84
+ ```bash
85
+ btsh doctor # devices, nodes, negotiated codec
86
+ btsh connect --device "Xiaomi OpenWear"
87
+ btsh serve --transport pw --codec sbc --target bluez_output.14:6C:27:05:D3:BE.1
88
+ btsh exec --transport pw --codec sbc --target bluez_output.14:6C:27:05:D3:BE.1 -- "id -un"
89
+ ```
90
+
91
+ Real speaker, any OS (PortAudio): make the speaker the default output device,
92
+ and for duplex its microphone the default input device, then:
93
+
94
+ ```bash
95
+ btsh devices # pick indexes or names
96
+ btsh serve --transport portaudio --output-device 4 --input-device 4
97
+ btsh exec --transport portaudio --output-device 4 --input-device 4 -- "uname -sr"
98
+ ```
99
+
100
+ Android server over BLE:
101
+
102
+ ```bash
103
+ btsh scan --timeout 10 # the app advertises as "AirPods Pro"
104
+ btsh exec --transport ble --ble-name "AirPods" -- "id"
105
+ btsh shell --transport ble --ble-name "AirPods"
106
+ ```
107
+
108
+ ## CLI
109
+
110
+ ```
111
+ btsh doctor [--json] devices, BlueZ nodes + codec, PortAudio devices
112
+ btsh connect --device NAME connect a Bluetooth device (BlueZ)
113
+ btsh devices [--json] list audio devices (PortAudio)
114
+ btsh scan [--timeout N] scan BLE peripherals
115
+ btsh serve [link options] run the shell side
116
+ btsh exec [link options] -- CMD run one command
117
+ btsh shell [link options] interactive REPL
118
+ btsh demo [--codec sbc] in-process end to end test
119
+ btsh selftest [--frames N] frame recovery, clean and through SBC
120
+ ```
121
+
122
+ `serve` options: `--cwd`, `--timeout`, `--max-output`, `--allow REGEX`,
123
+ `--deny REGEX`, `--key FILE`. Link options: `--transport`,
124
+ `--codec none|sbc`, `--key`, `--retries`, `--ack-timeout`, `--verbose`, plus
125
+ `--target/--target-in` (pw), `--output-device/--input-device` (portaudio),
126
+ `--ble-address/--ble-name` (ble), `--fifo-dir` (fifo).
127
+
128
+ ## Protocol
129
+
130
+ One frame, 12 bytes of overhead:
131
+
132
+ ```
133
+ 0 version 1
134
+ 1 type 0 DATA, 1 ACK, 2 NAK, 4 HELLO, 5 HELLO_ACK, 6 BYE
135
+ 2 seq mod 256
136
+ 3 flags 1 START, 2 END
137
+ 4 length payload length, big endian, 2 bytes (max 240)
138
+ 6 payload [16 byte HMAC tag][JSON chunk]
139
+ .. crc32 over version..payload
140
+ ```
141
+
142
+ * Acoustic link: each frame is modulated as 4-FSK (32 sample symbols at
143
+ 48 kHz, 1500 symbols/s, 1000/2500/4000/5500 Hz, 2 bits per symbol), 24 ms of
144
+ lead silence, 12 symbol preamble, 32 bit sync word. Measured with ffmpeg SBC,
145
+ 20 frames per point: 40 B and 224 B payloads recover 20/20 at 128, 200 and
146
+ 328 kbit/s, and 0/20 at 64 kbit/s, which cuts the band above ~5 kHz. ~300 B/s
147
+ of payload.
148
+ * Stop-and-wait ARQ: a frame is resent until ACKed (`--retries`, `--ack-timeout`).
149
+ * Messages are JSON, chunked into 224 byte bodies, reassembled with START/END.
150
+ * Auth is a pre-shared key file (`--key`), HMAC-SHA256 over `seq || body`,
151
+ truncated to 16 bytes, plus a nonce handshake. It replaces sshd, not SSH's
152
+ asymmetric crypto: no forward secrecy, no host key pinning. Keep it on a link
153
+ you already trust, or treat it as "not open to the room".
154
+
155
+ ## Limits, stated plainly
156
+
157
+ * Payload throughput is ~300 B/s on the acoustic link. It is a shell for small
158
+ commands, not for `tar | gzip` over the air.
159
+ * A2DP is one way: a full session needs HFP (the speaker's microphone) or two
160
+ paired devices. `pw` and `portaudio` record from the same node/device they
161
+ play into, so duplex means a headset, not a plain speaker.
162
+ * The Android server runs commands in the app sandbox via `/system/bin/sh`; it
163
+ tries `su -c` when the device is rooted. No root, no bash, no `/etc`.
164
+ * BLE needs a central that keeps the connection: `bleak` does, macOS needs the
165
+ app to be foregrounded once to grant Bluetooth permission.
166
+ * Nothing here is tested against a physical speaker in CI: the codec path is
167
+ verified through ffmpeg's SBC encoder/decoder, the Android app is source only
168
+ (no SDK on the machine that generated this repo).
169
+
170
+ ## Tests
171
+
172
+ ```bash
173
+ PYTHONPATH=src python -m unittest discover -s tests -v
174
+ btsh selftest --frames 12
175
+ ```
176
+
177
+ ## Android app
178
+
179
+ ```
180
+ android/app/src/main/java/com/marcpartensky/btsh/
181
+ ├── Protocol.kt frame pack/unpack, same bytes as Python
182
+ ├── ShellRunner.kt /system/bin/sh or su -c, output capped
183
+ ├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC, AirPods advertising
184
+ ├── BtshService.kt foreground service, keeps advertising alive
185
+ └── MainActivity.kt key field, start/stop, log
186
+ ```
187
+
188
+ Build on a machine with the Android SDK (not on tower):
189
+
190
+ ```bash
191
+ cd android && ./gradlew assembleDebug # needs gradle wrapper, see below
192
+ ```
193
+
194
+ No gradle wrapper is committed: run `gradle wrapper` once, or open the folder in
195
+ Android Studio. Install with `adb install app/build/outputs/apk/debug/app-debug.apk`,
196
+ then start it, set the same key as the client, and connect from the desktop:
197
+
198
+ ```bash
199
+ btsh exec --transport ble --ble-name "AirPods" --key ~/.btsh.key -- "getprop ro.product.model"
200
+ ```
201
+
202
+ ## Nix
203
+
204
+ ```bash
205
+ nix build .# # the package
206
+ nix run .# -- demo
207
+ ```
208
+
209
+ `module.nix` installs the CLI and can run a `btsh serve` unit:
210
+
211
+ ```nix
212
+ services.btsh = {
213
+ enable = true;
214
+ user = "marc";
215
+ keyFile = "/run/secrets/btsh.key";
216
+ cwd = "/home/marc";
217
+ allow = [ "^ls" "^cat" "^uname" ];
218
+ };
219
+ ```
@@ -0,0 +1,199 @@
1
+ # btsh
2
+
3
+ A shell that rides on a Bluetooth link, no SSH server anywhere.
4
+
5
+ `btsh` puts a framed, acknowledged, optionally authenticated protocol on top of
6
+ whatever Bluetooth channel you can actually use, and turns it into `exec` and
7
+ `shell` commands on the peer. Three links ship:
8
+
9
+ | Link | Carries | Works on | Server side |
10
+ |---|---|---|---|
11
+ | `portaudio` | 4-FSK modem over the speaker codec (SBC verified) | Linux, macOS, Windows | any of the three |
12
+ | `pw` | same modem, PipeWire nodes, codec read from `pw-dump` | Linux | Linux |
13
+ | `ble` | same frames, no modem, GATT write/notify | Linux, macOS, Windows | Android app (`android/`) |
14
+ | `fifo` | same modem, two named pipes | any | any (two local processes, tests) |
15
+
16
+ ## The honest part about Android
17
+
18
+ The intended topology ("an Android app that pretends to be AirPods, plays music
19
+ and runs the shell") cannot use A2DP audio on an unrooted phone:
20
+
21
+ * `A2dpSinkService` is a system service and every entry point enforces
22
+ `BLUETOOTH_PRIVILEGED` (see AOSP `packages/modules/Bluetooth`,
23
+ `a2dpsink/A2dpSinkService.java`). A normal app cannot register as an A2DP
24
+ sink, so the phone cannot be the "speaker".
25
+ * Even the system sink never hands the decoded stream to an app: A2DP audio is
26
+ routed inside the Bluetooth stack to the audio HAL. There is no
27
+ `AudioRecord`/`AudioTrack` path for it.
28
+ * HFP is the same story: SCO audio belongs to the telephony stack.
29
+
30
+ So the Android app in `android/` is a **BLE GATT peripheral** that advertises as
31
+ `AirPods Pro` (name plus Apple manufacturer data in the scan response) and
32
+ serves the exact same frames. That is the only radio channel an app may serve
33
+ on Android, and `bleak` drives it from all three desktop OSes. The acoustic
34
+ modem stays available where the OS does expose the stream (desktops), and it is
35
+ what makes "the speaker's codec carries your shell" literal.
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install -e . # core, stdlib only
41
+ pip install -e ".[all]" # + sounddevice (PortAudio) and bleak
42
+ ```
43
+
44
+ `ffmpeg` is only needed for `--codec sbc` and `btsh selftest`: it is what pushes
45
+ a burst through the same SBC transform a Bluetooth speaker applies.
46
+
47
+ ## Quick start
48
+
49
+ In-process demo, commands really executed, every burst pushed through SBC:
50
+
51
+ ```bash
52
+ btsh demo
53
+ ```
54
+
55
+ Two processes on one host, no socket and no SSH, still through SBC:
56
+
57
+ ```bash
58
+ btsh serve --transport fifo --codec sbc --key ~/.btsh.key &
59
+ btsh exec --transport fifo --codec sbc --key ~/.btsh.key -- "uname -a | head -1"
60
+ ```
61
+
62
+ Real speaker, PipeWire (Linux):
63
+
64
+ ```bash
65
+ btsh doctor # devices, nodes, negotiated codec
66
+ btsh connect --device "Xiaomi OpenWear"
67
+ btsh serve --transport pw --codec sbc --target bluez_output.14:6C:27:05:D3:BE.1
68
+ btsh exec --transport pw --codec sbc --target bluez_output.14:6C:27:05:D3:BE.1 -- "id -un"
69
+ ```
70
+
71
+ Real speaker, any OS (PortAudio): make the speaker the default output device,
72
+ and for duplex its microphone the default input device, then:
73
+
74
+ ```bash
75
+ btsh devices # pick indexes or names
76
+ btsh serve --transport portaudio --output-device 4 --input-device 4
77
+ btsh exec --transport portaudio --output-device 4 --input-device 4 -- "uname -sr"
78
+ ```
79
+
80
+ Android server over BLE:
81
+
82
+ ```bash
83
+ btsh scan --timeout 10 # the app advertises as "AirPods Pro"
84
+ btsh exec --transport ble --ble-name "AirPods" -- "id"
85
+ btsh shell --transport ble --ble-name "AirPods"
86
+ ```
87
+
88
+ ## CLI
89
+
90
+ ```
91
+ btsh doctor [--json] devices, BlueZ nodes + codec, PortAudio devices
92
+ btsh connect --device NAME connect a Bluetooth device (BlueZ)
93
+ btsh devices [--json] list audio devices (PortAudio)
94
+ btsh scan [--timeout N] scan BLE peripherals
95
+ btsh serve [link options] run the shell side
96
+ btsh exec [link options] -- CMD run one command
97
+ btsh shell [link options] interactive REPL
98
+ btsh demo [--codec sbc] in-process end to end test
99
+ btsh selftest [--frames N] frame recovery, clean and through SBC
100
+ ```
101
+
102
+ `serve` options: `--cwd`, `--timeout`, `--max-output`, `--allow REGEX`,
103
+ `--deny REGEX`, `--key FILE`. Link options: `--transport`,
104
+ `--codec none|sbc`, `--key`, `--retries`, `--ack-timeout`, `--verbose`, plus
105
+ `--target/--target-in` (pw), `--output-device/--input-device` (portaudio),
106
+ `--ble-address/--ble-name` (ble), `--fifo-dir` (fifo).
107
+
108
+ ## Protocol
109
+
110
+ One frame, 12 bytes of overhead:
111
+
112
+ ```
113
+ 0 version 1
114
+ 1 type 0 DATA, 1 ACK, 2 NAK, 4 HELLO, 5 HELLO_ACK, 6 BYE
115
+ 2 seq mod 256
116
+ 3 flags 1 START, 2 END
117
+ 4 length payload length, big endian, 2 bytes (max 240)
118
+ 6 payload [16 byte HMAC tag][JSON chunk]
119
+ .. crc32 over version..payload
120
+ ```
121
+
122
+ * Acoustic link: each frame is modulated as 4-FSK (32 sample symbols at
123
+ 48 kHz, 1500 symbols/s, 1000/2500/4000/5500 Hz, 2 bits per symbol), 24 ms of
124
+ lead silence, 12 symbol preamble, 32 bit sync word. Measured with ffmpeg SBC,
125
+ 20 frames per point: 40 B and 224 B payloads recover 20/20 at 128, 200 and
126
+ 328 kbit/s, and 0/20 at 64 kbit/s, which cuts the band above ~5 kHz. ~300 B/s
127
+ of payload.
128
+ * Stop-and-wait ARQ: a frame is resent until ACKed (`--retries`, `--ack-timeout`).
129
+ * Messages are JSON, chunked into 224 byte bodies, reassembled with START/END.
130
+ * Auth is a pre-shared key file (`--key`), HMAC-SHA256 over `seq || body`,
131
+ truncated to 16 bytes, plus a nonce handshake. It replaces sshd, not SSH's
132
+ asymmetric crypto: no forward secrecy, no host key pinning. Keep it on a link
133
+ you already trust, or treat it as "not open to the room".
134
+
135
+ ## Limits, stated plainly
136
+
137
+ * Payload throughput is ~300 B/s on the acoustic link. It is a shell for small
138
+ commands, not for `tar | gzip` over the air.
139
+ * A2DP is one way: a full session needs HFP (the speaker's microphone) or two
140
+ paired devices. `pw` and `portaudio` record from the same node/device they
141
+ play into, so duplex means a headset, not a plain speaker.
142
+ * The Android server runs commands in the app sandbox via `/system/bin/sh`; it
143
+ tries `su -c` when the device is rooted. No root, no bash, no `/etc`.
144
+ * BLE needs a central that keeps the connection: `bleak` does, macOS needs the
145
+ app to be foregrounded once to grant Bluetooth permission.
146
+ * Nothing here is tested against a physical speaker in CI: the codec path is
147
+ verified through ffmpeg's SBC encoder/decoder, the Android app is source only
148
+ (no SDK on the machine that generated this repo).
149
+
150
+ ## Tests
151
+
152
+ ```bash
153
+ PYTHONPATH=src python -m unittest discover -s tests -v
154
+ btsh selftest --frames 12
155
+ ```
156
+
157
+ ## Android app
158
+
159
+ ```
160
+ android/app/src/main/java/com/marcpartensky/btsh/
161
+ ├── Protocol.kt frame pack/unpack, same bytes as Python
162
+ ├── ShellRunner.kt /system/bin/sh or su -c, output capped
163
+ ├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC, AirPods advertising
164
+ ├── BtshService.kt foreground service, keeps advertising alive
165
+ └── MainActivity.kt key field, start/stop, log
166
+ ```
167
+
168
+ Build on a machine with the Android SDK (not on tower):
169
+
170
+ ```bash
171
+ cd android && ./gradlew assembleDebug # needs gradle wrapper, see below
172
+ ```
173
+
174
+ No gradle wrapper is committed: run `gradle wrapper` once, or open the folder in
175
+ Android Studio. Install with `adb install app/build/outputs/apk/debug/app-debug.apk`,
176
+ then start it, set the same key as the client, and connect from the desktop:
177
+
178
+ ```bash
179
+ btsh exec --transport ble --ble-name "AirPods" --key ~/.btsh.key -- "getprop ro.product.model"
180
+ ```
181
+
182
+ ## Nix
183
+
184
+ ```bash
185
+ nix build .# # the package
186
+ nix run .# -- demo
187
+ ```
188
+
189
+ `module.nix` installs the CLI and can run a `btsh serve` unit:
190
+
191
+ ```nix
192
+ services.btsh = {
193
+ enable = true;
194
+ user = "marc";
195
+ keyFile = "/run/secrets/btsh.key";
196
+ cwd = "/home/marc";
197
+ allow = [ "^ls" "^cat" "^uname" ];
198
+ };
199
+ ```
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "datap-0.4"
7
+ version = "0.4.0"
8
+ description = "Shell over a Bluetooth speaker's audio codec: run commands without an SSH server"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Marc Partensky" }]
13
+ keywords = ["bluetooth", "a2dp", "sbc", "modem", "shell", "ssh"]
14
+ dependencies = ["av>=12"]
15
+
16
+ [project.optional-dependencies]
17
+ sbc = ["av>=12"]
18
+ portaudio = ["sounddevice>=0.4"]
19
+ ble = ["bleak>=0.21"]
20
+ all = ["sounddevice>=0.4", "bleak>=0.21"]
21
+
22
+ [project.scripts]
23
+ btsh = "btsh.cli:main"
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src"]
27
+
28
+ [tool.setuptools.package-data]
29
+ btsh = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,42 @@
1
+ """btsh - an ssh-like shell that rides on a Bluetooth speaker's audio codec."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError
6
+ from importlib.metadata import version as _distribution_version
7
+
8
+ try: # installed from PyPI or a wheel
9
+ __version__ = _distribution_version("datap")
10
+ except PackageNotFoundError: # running from a source tree, keep in sync with pyproject.toml
11
+ __version__ = "0.3.0"
12
+
13
+ from .channel import Channel, ChannelError # noqa: E402
14
+ from .client import Client # noqa: E402
15
+ from .server import ShellConfig, ShellServer, execute # noqa: E402
16
+ from .session import AuthError, Session # noqa: E402
17
+ from .transport import ( # noqa: E402
18
+ AcousticTransport,
19
+ CodecTransport,
20
+ FifoTransport,
21
+ LoopbackTransport,
22
+ Transport,
23
+ TransportError,
24
+ )
25
+
26
+ __all__ = [
27
+ "__version__",
28
+ "AcousticTransport",
29
+ "AuthError",
30
+ "Channel",
31
+ "ChannelError",
32
+ "Client",
33
+ "CodecTransport",
34
+ "FifoTransport",
35
+ "LoopbackTransport",
36
+ "Session",
37
+ "ShellConfig",
38
+ "ShellServer",
39
+ "Transport",
40
+ "TransportError",
41
+ "execute",
42
+ ]
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m btsh``."""
2
+
3
+ from .cli import main
4
+
5
+ raise SystemExit(main())
@@ -0,0 +1,143 @@
1
+ """Cross-platform audio transport: PortAudio through ``sounddevice``.
2
+
3
+ One backend for Linux, macOS and Windows, unlike the PipeWire transport which
4
+ is Linux only. The Bluetooth device just has to be the system's output device
5
+ (and, for duplex, its input device): the OS does the A2DP/HFP plumbing, we
6
+ speak into it and listen from it.
7
+
8
+ Linux pactl list short sinks -> device index or name
9
+ macOS system output / input -> the AirPods show up as one device
10
+ Windows WASAPI/MME device names -> the AirPods output, not "Stereo Mix"
11
+
12
+ ``sounddevice`` needs the PortAudio shared library: package ``portaudio`` on
13
+ Debian/Fedora, ``portaudio`` on Homebrew, nothing on Windows (bundled).
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import queue
19
+ import time
20
+
21
+ from .modem import SAMPLE_RATE
22
+ from .transport import Transport, TransportError
23
+
24
+
25
+ def _sd():
26
+ try:
27
+ import sounddevice # noqa: PLC0415 - optional dependency
28
+ except OSError as exc: # pragma: no cover - depends on the host
29
+ raise TransportError(f"PortAudio missing: {exc}") from exc
30
+ except ImportError as exc: # pragma: no cover
31
+ raise TransportError("install btsh[audio] (pip install sounddevice)") from exc
32
+ return sounddevice
33
+
34
+
35
+ def list_devices() -> list[dict]:
36
+ """Audio devices, with the default input/output flagged."""
37
+ sd = _sd()
38
+ try:
39
+ raw = sd.query_devices()
40
+ default_in, default_out = sd.default.device
41
+ except Exception as exc: # pragma: no cover - host dependent
42
+ raise TransportError(f"could not enumerate audio devices: {exc}") from exc
43
+ devices = []
44
+ for index, device in enumerate(raw):
45
+ devices.append(
46
+ {
47
+ "index": index,
48
+ "name": device["name"],
49
+ "inputs": int(device["max_input_channels"]),
50
+ "outputs": int(device["max_output_channels"]),
51
+ "default_input": index == default_in,
52
+ "default_output": index == default_out,
53
+ "host_api": sd.query_hostapis(device["hostapi"])["name"],
54
+ }
55
+ )
56
+ return devices
57
+
58
+
59
+ class PortAudioTransport(Transport):
60
+ """Duplex PCM over the system's default (or named) audio devices."""
61
+
62
+ name = "portaudio"
63
+
64
+ def __init__(
65
+ self,
66
+ output_device: str | int | None = None,
67
+ input_device: str | int | None = None,
68
+ rate: int = SAMPLE_RATE,
69
+ blocksize: int = 480,
70
+ ) -> None:
71
+ self.sd = _sd()
72
+ self.rate = rate
73
+ self.output_device = output_device
74
+ self.input_device = input_device
75
+ self._queue: queue.Queue[bytes] = queue.Queue()
76
+ self._min_burst = int(rate * 0.25) * 2 # 250 ms of s16
77
+ try:
78
+ self._out = self.sd.RawOutputStream(
79
+ samplerate=rate,
80
+ blocksize=blocksize,
81
+ device=output_device,
82
+ channels=1,
83
+ dtype="int16",
84
+ )
85
+ self._in = self.sd.RawInputStream(
86
+ samplerate=rate,
87
+ blocksize=blocksize,
88
+ device=input_device,
89
+ channels=1,
90
+ dtype="int16",
91
+ callback=self._callback,
92
+ )
93
+ except Exception as exc: # pragma: no cover - host dependent
94
+ raise TransportError(f"could not open audio devices: {exc}") from exc
95
+ self._out.start()
96
+ self._in.start()
97
+
98
+ def _callback(self, indata, frames, time_info, status) -> None: # noqa: ANN001 - PortAudio signature
99
+ self._queue.put(bytes(indata))
100
+
101
+ def send_burst(self, pcm: bytes) -> None:
102
+ try:
103
+ self._out.write(pcm)
104
+ except Exception as exc: # pragma: no cover - device unplugged
105
+ raise TransportError(f"playback failed: {exc}") from exc
106
+
107
+ def recv_burst(self, timeout: float = 5.0) -> bytes | None:
108
+ deadline = time.monotonic() + timeout
109
+ buffer = bytearray()
110
+ while time.monotonic() < deadline:
111
+ try:
112
+ buffer.extend(self._queue.get(timeout=max(0.01, deadline - time.monotonic())))
113
+ except queue.Empty:
114
+ break
115
+ if len(buffer) >= self._min_burst:
116
+ while True:
117
+ try:
118
+ buffer.extend(self._queue.get_nowait())
119
+ except queue.Empty:
120
+ break
121
+ break
122
+ return bytes(buffer) or None
123
+
124
+ def describe(self) -> dict:
125
+ out = super().describe()
126
+ out.update(
127
+ {
128
+ "output_device": self.output_device,
129
+ "input_device": self.input_device,
130
+ "rate": self.rate,
131
+ }
132
+ )
133
+ return out
134
+
135
+ def close(self) -> None:
136
+ for stream in (getattr(self, "_in", None), getattr(self, "_out", None)):
137
+ if stream is None:
138
+ continue
139
+ try:
140
+ stream.stop()
141
+ stream.close()
142
+ except Exception: # pragma: no cover
143
+ pass