datap-0.6 0.6.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 (41) hide show
  1. datap_0_6-0.6.0/PKG-INFO +221 -0
  2. datap_0_6-0.6.0/README.md +203 -0
  3. datap_0_6-0.6.0/pyproject.toml +28 -0
  4. datap_0_6-0.6.0/setup.cfg +4 -0
  5. datap_0_6-0.6.0/src/btsh/__init__.py +51 -0
  6. datap_0_6-0.6.0/src/btsh/__main__.py +5 -0
  7. datap_0_6-0.6.0/src/btsh/audio.py +143 -0
  8. datap_0_6-0.6.0/src/btsh/auto.py +478 -0
  9. datap_0_6-0.6.0/src/btsh/ble.py +263 -0
  10. datap_0_6-0.6.0/src/btsh/bt.py +90 -0
  11. datap_0_6-0.6.0/src/btsh/channel.py +116 -0
  12. datap_0_6-0.6.0/src/btsh/channels.py +119 -0
  13. datap_0_6-0.6.0/src/btsh/cli.py +878 -0
  14. datap_0_6-0.6.0/src/btsh/client.py +166 -0
  15. datap_0_6-0.6.0/src/btsh/codec.py +204 -0
  16. datap_0_6-0.6.0/src/btsh/crypto.py +259 -0
  17. datap_0_6-0.6.0/src/btsh/framing.py +96 -0
  18. datap_0_6-0.6.0/src/btsh/hub.py +266 -0
  19. datap_0_6-0.6.0/src/btsh/mcp.py +213 -0
  20. datap_0_6-0.6.0/src/btsh/modem.py +199 -0
  21. datap_0_6-0.6.0/src/btsh/node.py +190 -0
  22. datap_0_6-0.6.0/src/btsh/py.typed +0 -0
  23. datap_0_6-0.6.0/src/btsh/server.py +194 -0
  24. datap_0_6-0.6.0/src/btsh/session.py +224 -0
  25. datap_0_6-0.6.0/src/btsh/setup.py +207 -0
  26. datap_0_6-0.6.0/src/btsh/transport.py +325 -0
  27. datap_0_6-0.6.0/src/datap_0.6.egg-info/PKG-INFO +221 -0
  28. datap_0_6-0.6.0/src/datap_0.6.egg-info/SOURCES.txt +39 -0
  29. datap_0_6-0.6.0/src/datap_0.6.egg-info/dependency_links.txt +1 -0
  30. datap_0_6-0.6.0/src/datap_0.6.egg-info/entry_points.txt +2 -0
  31. datap_0_6-0.6.0/src/datap_0.6.egg-info/requires.txt +11 -0
  32. datap_0_6-0.6.0/src/datap_0.6.egg-info/top_level.txt +1 -0
  33. datap_0_6-0.6.0/tests/test_auto.py +124 -0
  34. datap_0_6-0.6.0/tests/test_channels.py +182 -0
  35. datap_0_6-0.6.0/tests/test_client_shell.py +109 -0
  36. datap_0_6-0.6.0/tests/test_crypto.py +103 -0
  37. datap_0_6-0.6.0/tests/test_e2e.py +132 -0
  38. datap_0_6-0.6.0/tests/test_framing.py +33 -0
  39. datap_0_6-0.6.0/tests/test_mesh.py +158 -0
  40. datap_0_6-0.6.0/tests/test_modem.py +52 -0
  41. datap_0_6-0.6.0/tests/test_setup.py +137 -0
@@ -0,0 +1,221 @@
1
+ Metadata-Version: 2.4
2
+ Name: datap-0.6
3
+ Version: 0.6.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
+ Requires-Dist: bleak>=0.21
12
+ Provides-Extra: sbc
13
+ Requires-Dist: av>=12; extra == "sbc"
14
+ Provides-Extra: portaudio
15
+ Requires-Dist: sounddevice>=0.4; extra == "portaudio"
16
+ Provides-Extra: all
17
+ Requires-Dist: sounddevice>=0.4; extra == "all"
18
+
19
+ # btsh
20
+
21
+ A shell that rides on a Bluetooth link, no SSH server anywhere.
22
+
23
+ `btsh` puts a framed, acknowledged, optionally authenticated protocol on top of
24
+ whatever Bluetooth channel you can actually use, and turns it into `exec` and
25
+ `shell` commands on the peer. Three links ship:
26
+
27
+ | Link | Carries | Works on | Server side |
28
+ |---|---|---|---|
29
+ | `portaudio` | 4-FSK modem over the speaker codec (SBC verified) | Linux, macOS, Windows | any of the three |
30
+ | `pw` | same modem, PipeWire nodes, codec read from `pw-dump` | Linux | Linux |
31
+ | `ble` | same frames, no modem, GATT write/notify | Linux, macOS, Windows | Android app (`android/`) |
32
+ | `fifo` | same modem, two named pipes | any | any (two local processes, tests) |
33
+
34
+ ## The honest part about Android
35
+
36
+ The intended topology ("an Android app that pretends to be AirPods, plays music
37
+ and runs the shell") cannot use A2DP audio on an unrooted phone:
38
+
39
+ * `A2dpSinkService` is a system service and every entry point enforces
40
+ `BLUETOOTH_PRIVILEGED` (see AOSP `packages/modules/Bluetooth`,
41
+ `a2dpsink/A2dpSinkService.java`). A normal app cannot register as an A2DP
42
+ sink, so the phone cannot be the "speaker".
43
+ * Even the system sink never hands the decoded stream to an app: A2DP audio is
44
+ routed inside the Bluetooth stack to the audio HAL. There is no
45
+ `AudioRecord`/`AudioTrack` path for it.
46
+ * HFP is the same story: SCO audio belongs to the telephony stack.
47
+
48
+ So the Android app in `android/` is a **BLE GATT peripheral** that advertises as
49
+ `AirPods Pro` (name plus Apple manufacturer data in the scan response) and
50
+ serves the exact same frames. That is the only radio channel an app may serve
51
+ on Android, and `bleak` drives it from all three desktop OSes. The acoustic
52
+ modem stays available where the OS does expose the stream (desktops), and it is
53
+ what makes "the speaker's codec carries your shell" literal.
54
+
55
+ ## Install
56
+
57
+ ```bash
58
+ pip install -e . # core: av (SBC) and bleak (Bluetooth LE) come along
59
+ pip install -e ".[all]" # + sounddevice (PortAudio)
60
+ ```
61
+
62
+ Bluetooth LE is the default link, so `bleak` is a hard dependency: `btsh` with no
63
+ argument scans for a hub, links to the first one that advertises the service, and
64
+ remembers it. There is no TCP transport and no interactive menu.
65
+
66
+ `ffmpeg` is only needed for `--codec sbc` and `btsh selftest`: it is what pushes
67
+ a burst through the same SBC transform a Bluetooth speaker applies.
68
+
69
+ ## Quick start
70
+
71
+ In-process demo, commands really executed, every burst pushed through SBC:
72
+
73
+ ```bash
74
+ btsh demo
75
+ ```
76
+
77
+ Two processes on one host, no socket and no SSH, still through SBC:
78
+
79
+ ```bash
80
+ btsh serve --transport fifo --codec sbc --key ~/.btsh.key &
81
+ btsh exec --transport fifo --codec sbc --key ~/.btsh.key -- "uname -a | head -1"
82
+ ```
83
+
84
+ Real speaker, PipeWire (Linux):
85
+
86
+ ```bash
87
+ btsh doctor # devices, nodes, negotiated codec
88
+ btsh connect --device "Xiaomi OpenWear"
89
+ btsh serve --transport pw --codec sbc --target bluez_output.14:6C:27:05:D3:BE.1
90
+ btsh exec --transport pw --codec sbc --target bluez_output.14:6C:27:05:D3:BE.1 -- "id -un"
91
+ ```
92
+
93
+ Real speaker, any OS (PortAudio): make the speaker the default output device,
94
+ and for duplex its microphone the default input device, then:
95
+
96
+ ```bash
97
+ btsh devices # pick indexes or names
98
+ btsh serve --transport portaudio --output-device 4 --input-device 4
99
+ btsh exec --transport portaudio --output-device 4 --input-device 4 -- "uname -sr"
100
+ ```
101
+
102
+ Android server over BLE:
103
+
104
+ ```bash
105
+ btsh scan --timeout 10 # the app advertises as "AirPods Pro"
106
+ btsh exec --transport ble --ble-name "AirPods" -- "id"
107
+ btsh shell --transport ble --ble-name "AirPods"
108
+ ```
109
+
110
+ ## CLI
111
+
112
+ ```
113
+ btsh doctor [--json] devices, BlueZ nodes + codec, PortAudio devices
114
+ btsh connect --device NAME connect a Bluetooth device (BlueZ)
115
+ btsh devices [--json] list audio devices (PortAudio)
116
+ btsh scan [--timeout N] scan BLE peripherals
117
+ btsh serve [link options] run the shell side
118
+ btsh exec [link options] -- CMD run one command
119
+ btsh shell [link options] interactive REPL
120
+ btsh demo [--codec sbc] in-process end to end test
121
+ btsh selftest [--frames N] frame recovery, clean and through SBC
122
+ ```
123
+
124
+ `serve` options: `--cwd`, `--timeout`, `--max-output`, `--allow REGEX`,
125
+ `--deny REGEX`, `--key FILE`. Link options: `--transport`,
126
+ `--codec none|sbc`, `--key`, `--retries`, `--ack-timeout`, `--verbose`, plus
127
+ `--target/--target-in` (pw), `--output-device/--input-device` (portaudio),
128
+ `--ble-address/--ble-name` (ble), `--fifo-dir` (fifo).
129
+
130
+ ## Protocol
131
+
132
+ One frame, 12 bytes of overhead:
133
+
134
+ ```
135
+ 0 version 1
136
+ 1 type 0 DATA, 1 ACK, 2 NAK, 4 HELLO, 5 HELLO_ACK, 6 BYE
137
+ 2 seq mod 256
138
+ 3 flags 1 START, 2 END
139
+ 4 length payload length, big endian, 2 bytes (max 240)
140
+ 6 payload [16 byte HMAC tag][JSON chunk]
141
+ .. crc32 over version..payload
142
+ ```
143
+
144
+ * Acoustic link: each frame is modulated as 4-FSK (32 sample symbols at
145
+ 48 kHz, 1500 symbols/s, 1000/2500/4000/5500 Hz, 2 bits per symbol), 24 ms of
146
+ lead silence, 12 symbol preamble, 32 bit sync word. Measured with ffmpeg SBC,
147
+ 20 frames per point: 40 B and 224 B payloads recover 20/20 at 128, 200 and
148
+ 328 kbit/s, and 0/20 at 64 kbit/s, which cuts the band above ~5 kHz. ~300 B/s
149
+ of payload.
150
+ * Stop-and-wait ARQ: a frame is resent until ACKed (`--retries`, `--ack-timeout`).
151
+ * Messages are JSON, chunked into 224 byte bodies, reassembled with START/END.
152
+ * Auth is a pre-shared key file (`--key`), HMAC-SHA256 over `seq || body`,
153
+ truncated to 16 bytes, plus a nonce handshake. It replaces sshd, not SSH's
154
+ asymmetric crypto: no forward secrecy, no host key pinning. Keep it on a link
155
+ you already trust, or treat it as "not open to the room".
156
+
157
+ ## Limits, stated plainly
158
+
159
+ * Payload throughput is ~300 B/s on the acoustic link. It is a shell for small
160
+ commands, not for `tar | gzip` over the air.
161
+ * A2DP is one way: a full session needs HFP (the speaker's microphone) or two
162
+ paired devices. `pw` and `portaudio` record from the same node/device they
163
+ play into, so duplex means a headset, not a plain speaker.
164
+ * The Android server runs commands in the app sandbox via `/system/bin/sh`; it
165
+ tries `su -c` when the device is rooted. No root, no bash, no `/etc`.
166
+ * BLE needs a central that keeps the connection: `bleak` does, macOS needs the
167
+ app to be foregrounded once to grant Bluetooth permission.
168
+ * Nothing here is tested against a physical speaker in CI: the codec path is
169
+ verified through ffmpeg's SBC encoder/decoder, the Android app is source only
170
+ (no SDK on the machine that generated this repo).
171
+
172
+ ## Tests
173
+
174
+ ```bash
175
+ PYTHONPATH=src python -m unittest discover -s tests -v
176
+ btsh selftest --frames 12
177
+ ```
178
+
179
+ ## Android app
180
+
181
+ ```
182
+ android/app/src/main/java/com/marcpartensky/btsh/
183
+ ├── Protocol.kt frame pack/unpack, same bytes as Python
184
+ ├── ShellRunner.kt /system/bin/sh or su -c, output capped
185
+ ├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC, AirPods advertising
186
+ ├── BtshService.kt foreground service, keeps advertising alive
187
+ └── MainActivity.kt key field, start/stop, log
188
+ ```
189
+
190
+ Build on a machine with the Android SDK (not on tower):
191
+
192
+ ```bash
193
+ cd android && ./gradlew assembleDebug # needs gradle wrapper, see below
194
+ ```
195
+
196
+ No gradle wrapper is committed: run `gradle wrapper` once, or open the folder in
197
+ Android Studio. Install with `adb install app/build/outputs/apk/debug/app-debug.apk`,
198
+ then start it, set the same key as the client, and connect from the desktop:
199
+
200
+ ```bash
201
+ btsh exec --transport ble --ble-name "AirPods" --key ~/.btsh.key -- "getprop ro.product.model"
202
+ ```
203
+
204
+ ## Nix
205
+
206
+ ```bash
207
+ nix build .# # the package
208
+ nix run .# -- demo
209
+ ```
210
+
211
+ `module.nix` installs the CLI and can run a `btsh serve` unit:
212
+
213
+ ```nix
214
+ services.btsh = {
215
+ enable = true;
216
+ user = "marc";
217
+ keyFile = "/run/secrets/btsh.key";
218
+ cwd = "/home/marc";
219
+ allow = [ "^ls" "^cat" "^uname" ];
220
+ };
221
+ ```
@@ -0,0 +1,203 @@
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: av (SBC) and bleak (Bluetooth LE) come along
41
+ pip install -e ".[all]" # + sounddevice (PortAudio)
42
+ ```
43
+
44
+ Bluetooth LE is the default link, so `bleak` is a hard dependency: `btsh` with no
45
+ argument scans for a hub, links to the first one that advertises the service, and
46
+ remembers it. There is no TCP transport and no interactive menu.
47
+
48
+ `ffmpeg` is only needed for `--codec sbc` and `btsh selftest`: it is what pushes
49
+ a burst through the same SBC transform a Bluetooth speaker applies.
50
+
51
+ ## Quick start
52
+
53
+ In-process demo, commands really executed, every burst pushed through SBC:
54
+
55
+ ```bash
56
+ btsh demo
57
+ ```
58
+
59
+ Two processes on one host, no socket and no SSH, still through SBC:
60
+
61
+ ```bash
62
+ btsh serve --transport fifo --codec sbc --key ~/.btsh.key &
63
+ btsh exec --transport fifo --codec sbc --key ~/.btsh.key -- "uname -a | head -1"
64
+ ```
65
+
66
+ Real speaker, PipeWire (Linux):
67
+
68
+ ```bash
69
+ btsh doctor # devices, nodes, negotiated codec
70
+ btsh connect --device "Xiaomi OpenWear"
71
+ btsh serve --transport pw --codec sbc --target bluez_output.14:6C:27:05:D3:BE.1
72
+ btsh exec --transport pw --codec sbc --target bluez_output.14:6C:27:05:D3:BE.1 -- "id -un"
73
+ ```
74
+
75
+ Real speaker, any OS (PortAudio): make the speaker the default output device,
76
+ and for duplex its microphone the default input device, then:
77
+
78
+ ```bash
79
+ btsh devices # pick indexes or names
80
+ btsh serve --transport portaudio --output-device 4 --input-device 4
81
+ btsh exec --transport portaudio --output-device 4 --input-device 4 -- "uname -sr"
82
+ ```
83
+
84
+ Android server over BLE:
85
+
86
+ ```bash
87
+ btsh scan --timeout 10 # the app advertises as "AirPods Pro"
88
+ btsh exec --transport ble --ble-name "AirPods" -- "id"
89
+ btsh shell --transport ble --ble-name "AirPods"
90
+ ```
91
+
92
+ ## CLI
93
+
94
+ ```
95
+ btsh doctor [--json] devices, BlueZ nodes + codec, PortAudio devices
96
+ btsh connect --device NAME connect a Bluetooth device (BlueZ)
97
+ btsh devices [--json] list audio devices (PortAudio)
98
+ btsh scan [--timeout N] scan BLE peripherals
99
+ btsh serve [link options] run the shell side
100
+ btsh exec [link options] -- CMD run one command
101
+ btsh shell [link options] interactive REPL
102
+ btsh demo [--codec sbc] in-process end to end test
103
+ btsh selftest [--frames N] frame recovery, clean and through SBC
104
+ ```
105
+
106
+ `serve` options: `--cwd`, `--timeout`, `--max-output`, `--allow REGEX`,
107
+ `--deny REGEX`, `--key FILE`. Link options: `--transport`,
108
+ `--codec none|sbc`, `--key`, `--retries`, `--ack-timeout`, `--verbose`, plus
109
+ `--target/--target-in` (pw), `--output-device/--input-device` (portaudio),
110
+ `--ble-address/--ble-name` (ble), `--fifo-dir` (fifo).
111
+
112
+ ## Protocol
113
+
114
+ One frame, 12 bytes of overhead:
115
+
116
+ ```
117
+ 0 version 1
118
+ 1 type 0 DATA, 1 ACK, 2 NAK, 4 HELLO, 5 HELLO_ACK, 6 BYE
119
+ 2 seq mod 256
120
+ 3 flags 1 START, 2 END
121
+ 4 length payload length, big endian, 2 bytes (max 240)
122
+ 6 payload [16 byte HMAC tag][JSON chunk]
123
+ .. crc32 over version..payload
124
+ ```
125
+
126
+ * Acoustic link: each frame is modulated as 4-FSK (32 sample symbols at
127
+ 48 kHz, 1500 symbols/s, 1000/2500/4000/5500 Hz, 2 bits per symbol), 24 ms of
128
+ lead silence, 12 symbol preamble, 32 bit sync word. Measured with ffmpeg SBC,
129
+ 20 frames per point: 40 B and 224 B payloads recover 20/20 at 128, 200 and
130
+ 328 kbit/s, and 0/20 at 64 kbit/s, which cuts the band above ~5 kHz. ~300 B/s
131
+ of payload.
132
+ * Stop-and-wait ARQ: a frame is resent until ACKed (`--retries`, `--ack-timeout`).
133
+ * Messages are JSON, chunked into 224 byte bodies, reassembled with START/END.
134
+ * Auth is a pre-shared key file (`--key`), HMAC-SHA256 over `seq || body`,
135
+ truncated to 16 bytes, plus a nonce handshake. It replaces sshd, not SSH's
136
+ asymmetric crypto: no forward secrecy, no host key pinning. Keep it on a link
137
+ you already trust, or treat it as "not open to the room".
138
+
139
+ ## Limits, stated plainly
140
+
141
+ * Payload throughput is ~300 B/s on the acoustic link. It is a shell for small
142
+ commands, not for `tar | gzip` over the air.
143
+ * A2DP is one way: a full session needs HFP (the speaker's microphone) or two
144
+ paired devices. `pw` and `portaudio` record from the same node/device they
145
+ play into, so duplex means a headset, not a plain speaker.
146
+ * The Android server runs commands in the app sandbox via `/system/bin/sh`; it
147
+ tries `su -c` when the device is rooted. No root, no bash, no `/etc`.
148
+ * BLE needs a central that keeps the connection: `bleak` does, macOS needs the
149
+ app to be foregrounded once to grant Bluetooth permission.
150
+ * Nothing here is tested against a physical speaker in CI: the codec path is
151
+ verified through ffmpeg's SBC encoder/decoder, the Android app is source only
152
+ (no SDK on the machine that generated this repo).
153
+
154
+ ## Tests
155
+
156
+ ```bash
157
+ PYTHONPATH=src python -m unittest discover -s tests -v
158
+ btsh selftest --frames 12
159
+ ```
160
+
161
+ ## Android app
162
+
163
+ ```
164
+ android/app/src/main/java/com/marcpartensky/btsh/
165
+ ├── Protocol.kt frame pack/unpack, same bytes as Python
166
+ ├── ShellRunner.kt /system/bin/sh or su -c, output capped
167
+ ├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC, AirPods advertising
168
+ ├── BtshService.kt foreground service, keeps advertising alive
169
+ └── MainActivity.kt key field, start/stop, log
170
+ ```
171
+
172
+ Build on a machine with the Android SDK (not on tower):
173
+
174
+ ```bash
175
+ cd android && ./gradlew assembleDebug # needs gradle wrapper, see below
176
+ ```
177
+
178
+ No gradle wrapper is committed: run `gradle wrapper` once, or open the folder in
179
+ Android Studio. Install with `adb install app/build/outputs/apk/debug/app-debug.apk`,
180
+ then start it, set the same key as the client, and connect from the desktop:
181
+
182
+ ```bash
183
+ btsh exec --transport ble --ble-name "AirPods" --key ~/.btsh.key -- "getprop ro.product.model"
184
+ ```
185
+
186
+ ## Nix
187
+
188
+ ```bash
189
+ nix build .# # the package
190
+ nix run .# -- demo
191
+ ```
192
+
193
+ `module.nix` installs the CLI and can run a `btsh serve` unit:
194
+
195
+ ```nix
196
+ services.btsh = {
197
+ enable = true;
198
+ user = "marc";
199
+ keyFile = "/run/secrets/btsh.key";
200
+ cwd = "/home/marc";
201
+ allow = [ "^ls" "^cat" "^uname" ];
202
+ };
203
+ ```
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "datap-0.6"
7
+ version = "0.6.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", "bleak>=0.21"]
15
+
16
+ [project.optional-dependencies]
17
+ sbc = ["av>=12"]
18
+ portaudio = ["sounddevice>=0.4"]
19
+ all = ["sounddevice>=0.4"]
20
+
21
+ [project.scripts]
22
+ btsh = "btsh.cli:main"
23
+
24
+ [tool.setuptools.packages.find]
25
+ where = ["src"]
26
+
27
+ [tool.setuptools.package-data]
28
+ btsh = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,51 @@
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
+ # The project has been published under several names; take whichever one
10
+ # is actually installed instead of guessing a single distribution name.
11
+ for _name in ("datap", "datap-0.6", "datap-0.5", "datap-0.4", "datap-0.3"):
12
+ try:
13
+ __version__ = _distribution_version(_name)
14
+ break
15
+ except PackageNotFoundError:
16
+ continue
17
+ else: # pragma: no cover - defensive, the loop always ends somewhere
18
+ raise PackageNotFoundError
19
+ except PackageNotFoundError: # running from a source tree, keep in sync with pyproject.toml
20
+ __version__ = "0.6.0"
21
+
22
+ from .channel import Channel, ChannelError # noqa: E402
23
+ from .client import Client # noqa: E402
24
+ from .server import ShellConfig, ShellServer, execute # noqa: E402
25
+ from .session import AuthError, Session # noqa: E402
26
+ from .transport import ( # noqa: E402
27
+ AcousticTransport,
28
+ CodecTransport,
29
+ FifoTransport,
30
+ LoopbackTransport,
31
+ Transport,
32
+ TransportError,
33
+ )
34
+
35
+ __all__ = [
36
+ "__version__",
37
+ "AcousticTransport",
38
+ "AuthError",
39
+ "Channel",
40
+ "ChannelError",
41
+ "Client",
42
+ "CodecTransport",
43
+ "FifoTransport",
44
+ "LoopbackTransport",
45
+ "Session",
46
+ "ShellConfig",
47
+ "ShellServer",
48
+ "Transport",
49
+ "TransportError",
50
+ "execute",
51
+ ]
@@ -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