datap 0.1.0__py3-none-any.whl
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.
- btsh/__init__.py +36 -0
- btsh/__main__.py +5 -0
- btsh/audio.py +143 -0
- btsh/ble.py +147 -0
- btsh/bt.py +90 -0
- btsh/channel.py +112 -0
- btsh/channels.py +119 -0
- btsh/cli.py +528 -0
- btsh/client.py +75 -0
- btsh/codec.py +120 -0
- btsh/crypto.py +233 -0
- btsh/framing.py +96 -0
- btsh/hub.py +266 -0
- btsh/mcp.py +213 -0
- btsh/modem.py +196 -0
- btsh/node.py +190 -0
- btsh/py.typed +0 -0
- btsh/server.py +194 -0
- btsh/session.py +187 -0
- btsh/transport.py +325 -0
- datap-0.1.0.dist-info/METADATA +207 -0
- datap-0.1.0.dist-info/RECORD +25 -0
- datap-0.1.0.dist-info/WHEEL +5 -0
- datap-0.1.0.dist-info/entry_points.txt +2 -0
- datap-0.1.0.dist-info/top_level.txt +1 -0
btsh/transport.py
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""Transports that carry PCM bursts between the two ends.
|
|
2
|
+
|
|
3
|
+
A transport is half duplex: it can play one burst, then listen for one burst.
|
|
4
|
+
Three implementations ship:
|
|
5
|
+
|
|
6
|
+
* ``loopback`` - two ends wired together in memory (tests, demo, one host)
|
|
7
|
+
* ``fifo`` - two length prefixed FIFOs, one per direction (two processes
|
|
8
|
+
on the same host, no socket, no SSH)
|
|
9
|
+
* ``acoustic`` - the real thing: ``pw-play`` into a Bluetooth node and
|
|
10
|
+
``pw-record`` from the same (HFP) or another (A2DP) device
|
|
11
|
+
|
|
12
|
+
The burst is always raw PCM: s16le, mono, 48 kHz. Nothing is resampled here,
|
|
13
|
+
the Bluetooth codec (SBC/AAC/...) is whatever PipeWire negotiated for the
|
|
14
|
+
device, and it is applied by the sender's audio graph.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import os
|
|
20
|
+
import queue
|
|
21
|
+
import select
|
|
22
|
+
import struct
|
|
23
|
+
import subprocess
|
|
24
|
+
import threading
|
|
25
|
+
import time
|
|
26
|
+
from abc import ABC, abstractmethod
|
|
27
|
+
|
|
28
|
+
from .modem import SAMPLE_RATE
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class TransportError(Exception):
|
|
32
|
+
"""Raised when a transport cannot be opened or breaks."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class Transport(ABC):
|
|
36
|
+
name = "abstract"
|
|
37
|
+
sample_rate = SAMPLE_RATE
|
|
38
|
+
|
|
39
|
+
@abstractmethod
|
|
40
|
+
def send_burst(self, pcm: bytes) -> None:
|
|
41
|
+
"""Play one burst of PCM."""
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def recv_burst(self, timeout: float = 5.0) -> bytes | None:
|
|
45
|
+
"""Return the next burst of PCM, or None on timeout."""
|
|
46
|
+
|
|
47
|
+
def describe(self) -> dict:
|
|
48
|
+
return {"transport": self.name, "sample_rate": self.sample_rate}
|
|
49
|
+
|
|
50
|
+
def close(self) -> None: # pragma: no cover - trivial
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class LoopbackTransport(Transport):
|
|
55
|
+
"""One end of an in-memory pair. Use :meth:`pair` to build both ends."""
|
|
56
|
+
|
|
57
|
+
name = "loopback"
|
|
58
|
+
|
|
59
|
+
def __init__(self, inbox: queue.Queue, outbox: queue.Queue, label: str) -> None:
|
|
60
|
+
self._inbox = inbox
|
|
61
|
+
self._outbox = outbox
|
|
62
|
+
self.label = label
|
|
63
|
+
self.sent = 0
|
|
64
|
+
self.received = 0
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def pair(cls) -> tuple["LoopbackTransport", "LoopbackTransport"]:
|
|
68
|
+
a = queue.Queue()
|
|
69
|
+
b = queue.Queue()
|
|
70
|
+
return cls(b, a, "a"), cls(a, b, "b")
|
|
71
|
+
|
|
72
|
+
def send_burst(self, pcm: bytes) -> None:
|
|
73
|
+
self._outbox.put(pcm)
|
|
74
|
+
self.sent += len(pcm)
|
|
75
|
+
|
|
76
|
+
def recv_burst(self, timeout: float = 5.0) -> bytes | None:
|
|
77
|
+
try:
|
|
78
|
+
pcm = self._inbox.get(timeout=timeout)
|
|
79
|
+
except queue.Empty:
|
|
80
|
+
return None
|
|
81
|
+
self.received += len(pcm)
|
|
82
|
+
return pcm
|
|
83
|
+
|
|
84
|
+
def describe(self) -> dict:
|
|
85
|
+
out = super().describe()
|
|
86
|
+
out.update({"label": self.label, "sent_bytes": self.sent, "received_bytes": self.received})
|
|
87
|
+
return out
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class FifoTransport(Transport):
|
|
91
|
+
"""Bursts over two named pipes: 4 byte big endian length, then PCM.
|
|
92
|
+
|
|
93
|
+
``in_path`` is what this end reads, ``out_path`` is what it writes. Create
|
|
94
|
+
the FIFOs with ``os.mkfifo`` before starting either end.
|
|
95
|
+
"""
|
|
96
|
+
|
|
97
|
+
name = "fifo"
|
|
98
|
+
|
|
99
|
+
def __init__(self, in_path: str, out_path: str) -> None:
|
|
100
|
+
self.in_path = in_path
|
|
101
|
+
self.out_path = out_path
|
|
102
|
+
for path in (in_path, out_path):
|
|
103
|
+
if not os.path.exists(path):
|
|
104
|
+
raise TransportError(f"missing fifo: {path}")
|
|
105
|
+
self._read_fd = os.open(in_path, os.O_RDONLY | os.O_NONBLOCK)
|
|
106
|
+
self._write_fd = self._open_writer(out_path)
|
|
107
|
+
|
|
108
|
+
@staticmethod
|
|
109
|
+
def _open_writer(path: str, wait: float = 15.0) -> int:
|
|
110
|
+
"""O_WRONLY fails with ENXIO until the other end is reading; wait for it."""
|
|
111
|
+
deadline = time.monotonic() + wait
|
|
112
|
+
while True:
|
|
113
|
+
try:
|
|
114
|
+
return os.open(path, os.O_WRONLY | os.O_NONBLOCK)
|
|
115
|
+
except OSError as exc:
|
|
116
|
+
if time.monotonic() > deadline:
|
|
117
|
+
raise TransportError(f"no reader on {path}: {exc}") from exc
|
|
118
|
+
time.sleep(0.05)
|
|
119
|
+
|
|
120
|
+
def _read_exact(self, count: int, deadline: float) -> bytes | None:
|
|
121
|
+
chunks = bytearray()
|
|
122
|
+
while len(chunks) < count:
|
|
123
|
+
remaining = deadline - time.monotonic()
|
|
124
|
+
if remaining <= 0:
|
|
125
|
+
return None
|
|
126
|
+
ready, _, _ = select.select([self._read_fd], [], [], remaining)
|
|
127
|
+
if not ready:
|
|
128
|
+
return None
|
|
129
|
+
try:
|
|
130
|
+
data = os.read(self._read_fd, count - len(chunks))
|
|
131
|
+
except BlockingIOError:
|
|
132
|
+
continue
|
|
133
|
+
if not data:
|
|
134
|
+
time.sleep(0.01)
|
|
135
|
+
continue
|
|
136
|
+
chunks.extend(data)
|
|
137
|
+
return bytes(chunks)
|
|
138
|
+
|
|
139
|
+
def send_burst(self, pcm: bytes) -> None:
|
|
140
|
+
payload = struct.pack(">I", len(pcm)) + pcm
|
|
141
|
+
offset = 0
|
|
142
|
+
while offset < len(payload):
|
|
143
|
+
try:
|
|
144
|
+
written = os.write(self._write_fd, payload[offset:])
|
|
145
|
+
except BlockingIOError:
|
|
146
|
+
time.sleep(0.002)
|
|
147
|
+
continue
|
|
148
|
+
except BrokenPipeError as exc:
|
|
149
|
+
raise TransportError(f"fifo closed: {self.out_path}") from exc
|
|
150
|
+
offset += written
|
|
151
|
+
|
|
152
|
+
def recv_burst(self, timeout: float = 5.0) -> bytes | None:
|
|
153
|
+
deadline = time.monotonic() + timeout
|
|
154
|
+
header = self._read_exact(4, deadline)
|
|
155
|
+
if header is None:
|
|
156
|
+
return None
|
|
157
|
+
(length,) = struct.unpack(">I", header)
|
|
158
|
+
if length == 0 or length > 8 * 1024 * 1024:
|
|
159
|
+
raise TransportError(f"bad burst length {length}")
|
|
160
|
+
return self._read_exact(length, deadline)
|
|
161
|
+
|
|
162
|
+
def describe(self) -> dict:
|
|
163
|
+
out = super().describe()
|
|
164
|
+
out.update({"in": self.in_path, "out": self.out_path})
|
|
165
|
+
return out
|
|
166
|
+
|
|
167
|
+
def close(self) -> None:
|
|
168
|
+
for fd in (self._read_fd, self._write_fd):
|
|
169
|
+
try:
|
|
170
|
+
os.close(fd)
|
|
171
|
+
except OSError:
|
|
172
|
+
pass
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class AcousticTransport(Transport):
|
|
176
|
+
"""Real air path: ``pw-play`` out to a node, ``pw-record`` back from a node.
|
|
177
|
+
|
|
178
|
+
``target`` is a PipeWire node name (``bluez_output.<MAC>.1``) or any name
|
|
179
|
+
``pw-play`` accepts (an alias, an id, a sink name). The recorder runs in a
|
|
180
|
+
thread and keeps a rolling buffer; :meth:`recv_burst` hands back whatever
|
|
181
|
+
arrived during the window, the modem finds the burst inside it.
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
name = "acoustic"
|
|
185
|
+
|
|
186
|
+
def __init__(self, playback_target: str, capture_target: str | None = None, rate: int = SAMPLE_RATE) -> None:
|
|
187
|
+
self.rate = rate
|
|
188
|
+
self.playback_target = playback_target
|
|
189
|
+
self.capture_target = capture_target or playback_target
|
|
190
|
+
self._buffer = bytearray()
|
|
191
|
+
self._lock = threading.Lock()
|
|
192
|
+
self._stop = threading.Event()
|
|
193
|
+
self._record = subprocess.Popen(
|
|
194
|
+
[
|
|
195
|
+
"pw-record",
|
|
196
|
+
"--target",
|
|
197
|
+
self.capture_target,
|
|
198
|
+
"--rate",
|
|
199
|
+
str(rate),
|
|
200
|
+
"--channels",
|
|
201
|
+
"1",
|
|
202
|
+
"--format",
|
|
203
|
+
"s16",
|
|
204
|
+
"-",
|
|
205
|
+
],
|
|
206
|
+
stdin=subprocess.DEVNULL,
|
|
207
|
+
stdout=subprocess.PIPE,
|
|
208
|
+
stderr=subprocess.DEVNULL,
|
|
209
|
+
)
|
|
210
|
+
self._play = subprocess.Popen(
|
|
211
|
+
[
|
|
212
|
+
"pw-play",
|
|
213
|
+
"--target",
|
|
214
|
+
self.playback_target,
|
|
215
|
+
"--rate",
|
|
216
|
+
str(rate),
|
|
217
|
+
"--channels",
|
|
218
|
+
"1",
|
|
219
|
+
"--format",
|
|
220
|
+
"s16",
|
|
221
|
+
"-",
|
|
222
|
+
],
|
|
223
|
+
stdin=subprocess.PIPE,
|
|
224
|
+
stdout=subprocess.DEVNULL,
|
|
225
|
+
stderr=subprocess.DEVNULL,
|
|
226
|
+
)
|
|
227
|
+
if self._record.stdout is None or self._play.stdin is None:
|
|
228
|
+
raise TransportError("could not open pw-record/pw-play")
|
|
229
|
+
self._reader = threading.Thread(target=self._pump, name="btsh-record", daemon=True)
|
|
230
|
+
self._reader.start()
|
|
231
|
+
|
|
232
|
+
def _pump(self) -> None:
|
|
233
|
+
stdout = self._record.stdout
|
|
234
|
+
assert stdout is not None
|
|
235
|
+
while not self._stop.is_set():
|
|
236
|
+
chunk = stdout.read(4096)
|
|
237
|
+
if not chunk:
|
|
238
|
+
break
|
|
239
|
+
with self._lock:
|
|
240
|
+
self._buffer.extend(chunk)
|
|
241
|
+
if len(self._buffer) > self.rate * 2 * 30:
|
|
242
|
+
del self._buffer[: len(self._buffer) - self.rate * 2 * 30]
|
|
243
|
+
|
|
244
|
+
def send_burst(self, pcm: bytes) -> None:
|
|
245
|
+
stdin = self._play.stdin
|
|
246
|
+
assert stdin is not None
|
|
247
|
+
try:
|
|
248
|
+
stdin.write(pcm)
|
|
249
|
+
stdin.flush()
|
|
250
|
+
except BrokenPipeError as exc:
|
|
251
|
+
raise TransportError("pw-play died") from exc
|
|
252
|
+
|
|
253
|
+
def recv_burst(self, timeout: float = 5.0) -> bytes | None:
|
|
254
|
+
deadline = time.monotonic() + timeout
|
|
255
|
+
while time.monotonic() < deadline:
|
|
256
|
+
with self._lock:
|
|
257
|
+
if len(self._buffer) >= self.rate // 2:
|
|
258
|
+
pcm = bytes(self._buffer)
|
|
259
|
+
self._buffer.clear()
|
|
260
|
+
return pcm
|
|
261
|
+
time.sleep(0.01)
|
|
262
|
+
with self._lock:
|
|
263
|
+
pcm = bytes(self._buffer)
|
|
264
|
+
self._buffer.clear()
|
|
265
|
+
return pcm or None
|
|
266
|
+
|
|
267
|
+
def describe(self) -> dict:
|
|
268
|
+
out = super().describe()
|
|
269
|
+
out.update({"playback": self.playback_target, "capture": self.capture_target, "rate": self.rate})
|
|
270
|
+
return out
|
|
271
|
+
|
|
272
|
+
def close(self) -> None:
|
|
273
|
+
self._stop.set()
|
|
274
|
+
for proc in (self._record, self._play):
|
|
275
|
+
try:
|
|
276
|
+
proc.terminate()
|
|
277
|
+
proc.wait(timeout=2)
|
|
278
|
+
except Exception:
|
|
279
|
+
proc.kill()
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
class CodecTransport(Transport):
|
|
283
|
+
"""Decorator that runs every outgoing burst through the device codec.
|
|
284
|
+
|
|
285
|
+
Used to prove that the modulation survives the lossy transform a Bluetooth
|
|
286
|
+
speaker applies, without needing the speaker: ``codec="sbc"`` pushes the
|
|
287
|
+
PCM through ffmpeg's SBC encoder and decoder at the negotiated bitrate.
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
def __init__(self, inner: Transport, codec: str = "sbc", bitrate: int = 200_000) -> None:
|
|
291
|
+
self.inner = inner
|
|
292
|
+
self.codec = codec
|
|
293
|
+
self.bitrate = bitrate
|
|
294
|
+
self.name = f"{inner.name}+{codec}"
|
|
295
|
+
self.applied = 0
|
|
296
|
+
|
|
297
|
+
def send_burst(self, pcm: bytes) -> None:
|
|
298
|
+
from .codec import apply_codec
|
|
299
|
+
|
|
300
|
+
self.inner.send_burst(apply_codec(pcm, self.codec, self.bitrate, self.sample_rate))
|
|
301
|
+
self.applied += 1
|
|
302
|
+
|
|
303
|
+
def recv_burst(self, timeout: float = 5.0) -> bytes | None:
|
|
304
|
+
return self.inner.recv_burst(timeout)
|
|
305
|
+
|
|
306
|
+
def describe(self) -> dict:
|
|
307
|
+
out = self.inner.describe()
|
|
308
|
+
out.update({"codec": self.codec, "codec_applied": self.applied, "wrapped": self.inner.name})
|
|
309
|
+
return out
|
|
310
|
+
|
|
311
|
+
def close(self) -> None:
|
|
312
|
+
self.inner.close()
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def make_fifo_pair(directory: str) -> tuple[str, str, str, str]:
|
|
316
|
+
"""Create the two FIFOs used by a client/server pair and return their paths."""
|
|
317
|
+
os.makedirs(directory, exist_ok=True)
|
|
318
|
+
paths = {
|
|
319
|
+
"c2s": os.path.join(directory, "client-to-server.fifo"),
|
|
320
|
+
"s2c": os.path.join(directory, "server-to-client.fifo"),
|
|
321
|
+
}
|
|
322
|
+
for path in paths.values():
|
|
323
|
+
if not os.path.exists(path):
|
|
324
|
+
os.mkfifo(path, 0o600)
|
|
325
|
+
return paths["c2s"], paths["s2c"], paths["c2s"], paths["s2c"]
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datap
|
|
3
|
+
Version: 0.1.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
|
+
|
|
11
|
+
# btsh
|
|
12
|
+
|
|
13
|
+
A shell that rides on a Bluetooth link, no SSH server anywhere.
|
|
14
|
+
|
|
15
|
+
`btsh` puts a framed, acknowledged, optionally authenticated protocol on top of
|
|
16
|
+
whatever Bluetooth channel you can actually use, and turns it into `exec` and
|
|
17
|
+
`shell` commands on the peer. Three links ship:
|
|
18
|
+
|
|
19
|
+
| Link | Carries | Works on | Server side |
|
|
20
|
+
|---|---|---|---|
|
|
21
|
+
| `portaudio` | 4-FSK modem over the speaker codec (SBC verified) | Linux, macOS, Windows | any of the three |
|
|
22
|
+
| `pw` | same modem, PipeWire nodes, codec read from `pw-dump` | Linux | Linux |
|
|
23
|
+
| `ble` | same frames, no modem, GATT write/notify | Linux, macOS, Windows | Android app (`android/`) |
|
|
24
|
+
| `fifo` | same modem, two named pipes | any | any (two local processes, tests) |
|
|
25
|
+
|
|
26
|
+
## The honest part about Android
|
|
27
|
+
|
|
28
|
+
The intended topology ("an Android app that pretends to be AirPods, plays music
|
|
29
|
+
and runs the shell") cannot use A2DP audio on an unrooted phone:
|
|
30
|
+
|
|
31
|
+
* `A2dpSinkService` is a system service and every entry point enforces
|
|
32
|
+
`BLUETOOTH_PRIVILEGED` (see AOSP `packages/modules/Bluetooth`,
|
|
33
|
+
`a2dpsink/A2dpSinkService.java`). A normal app cannot register as an A2DP
|
|
34
|
+
sink, so the phone cannot be the "speaker".
|
|
35
|
+
* Even the system sink never hands the decoded stream to an app: A2DP audio is
|
|
36
|
+
routed inside the Bluetooth stack to the audio HAL. There is no
|
|
37
|
+
`AudioRecord`/`AudioTrack` path for it.
|
|
38
|
+
* HFP is the same story: SCO audio belongs to the telephony stack.
|
|
39
|
+
|
|
40
|
+
So the Android app in `android/` is a **BLE GATT peripheral** that advertises as
|
|
41
|
+
`AirPods Pro` (name plus Apple manufacturer data in the scan response) and
|
|
42
|
+
serves the exact same frames. That is the only radio channel an app may serve
|
|
43
|
+
on Android, and `bleak` drives it from all three desktop OSes. The acoustic
|
|
44
|
+
modem stays available where the OS does expose the stream (desktops), and it is
|
|
45
|
+
what makes "the speaker's codec carries your shell" literal.
|
|
46
|
+
|
|
47
|
+
## Install
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
pip install -e . # core, stdlib only
|
|
51
|
+
pip install -e ".[all]" # + sounddevice (PortAudio) and bleak
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
`ffmpeg` is only needed for `--codec sbc` and `btsh selftest`: it is what pushes
|
|
55
|
+
a burst through the same SBC transform a Bluetooth speaker applies.
|
|
56
|
+
|
|
57
|
+
## Quick start
|
|
58
|
+
|
|
59
|
+
In-process demo, commands really executed, every burst pushed through SBC:
|
|
60
|
+
|
|
61
|
+
```bash
|
|
62
|
+
btsh demo
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Two processes on one host, no socket and no SSH, still through SBC:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
btsh serve --transport fifo --codec sbc --key ~/.btsh.key &
|
|
69
|
+
btsh exec --transport fifo --codec sbc --key ~/.btsh.key -- "uname -a | head -1"
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Real speaker, PipeWire (Linux):
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
btsh doctor # devices, nodes, negotiated codec
|
|
76
|
+
btsh connect --device "Xiaomi OpenWear"
|
|
77
|
+
btsh serve --transport pw --codec sbc --target bluez_output.14:6C:27:05:D3:BE.1
|
|
78
|
+
btsh exec --transport pw --codec sbc --target bluez_output.14:6C:27:05:D3:BE.1 -- "id -un"
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Real speaker, any OS (PortAudio): make the speaker the default output device,
|
|
82
|
+
and for duplex its microphone the default input device, then:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
btsh devices # pick indexes or names
|
|
86
|
+
btsh serve --transport portaudio --output-device 4 --input-device 4
|
|
87
|
+
btsh exec --transport portaudio --output-device 4 --input-device 4 -- "uname -sr"
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Android server over BLE:
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
btsh scan --timeout 10 # the app advertises as "AirPods Pro"
|
|
94
|
+
btsh exec --transport ble --ble-name "AirPods" -- "id"
|
|
95
|
+
btsh shell --transport ble --ble-name "AirPods"
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## CLI
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
btsh doctor [--json] devices, BlueZ nodes + codec, PortAudio devices
|
|
102
|
+
btsh connect --device NAME connect a Bluetooth device (BlueZ)
|
|
103
|
+
btsh devices [--json] list audio devices (PortAudio)
|
|
104
|
+
btsh scan [--timeout N] scan BLE peripherals
|
|
105
|
+
btsh serve [link options] run the shell side
|
|
106
|
+
btsh exec [link options] -- CMD run one command
|
|
107
|
+
btsh shell [link options] interactive REPL
|
|
108
|
+
btsh demo [--codec sbc] in-process end to end test
|
|
109
|
+
btsh selftest [--frames N] frame recovery, clean and through SBC
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
`serve` options: `--cwd`, `--timeout`, `--max-output`, `--allow REGEX`,
|
|
113
|
+
`--deny REGEX`, `--key FILE`. Link options: `--transport`,
|
|
114
|
+
`--codec none|sbc`, `--key`, `--retries`, `--ack-timeout`, `--verbose`, plus
|
|
115
|
+
`--target/--target-in` (pw), `--output-device/--input-device` (portaudio),
|
|
116
|
+
`--ble-address/--ble-name` (ble), `--fifo-dir` (fifo).
|
|
117
|
+
|
|
118
|
+
## Protocol
|
|
119
|
+
|
|
120
|
+
One frame, 12 bytes of overhead:
|
|
121
|
+
|
|
122
|
+
```
|
|
123
|
+
0 version 1
|
|
124
|
+
1 type 0 DATA, 1 ACK, 2 NAK, 4 HELLO, 5 HELLO_ACK, 6 BYE
|
|
125
|
+
2 seq mod 256
|
|
126
|
+
3 flags 1 START, 2 END
|
|
127
|
+
4 length payload length, big endian, 2 bytes (max 240)
|
|
128
|
+
6 payload [16 byte HMAC tag][JSON chunk]
|
|
129
|
+
.. crc32 over version..payload
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
* Acoustic link: each frame is modulated as 4-FSK (2 ms symbols, 1000/2000/
|
|
133
|
+
3000/4000 Hz, 2 bits per symbol), 24 ms of lead silence, 12 symbol preamble,
|
|
134
|
+
32 bit sync word. Measured: 8/8 frames recovered through ffmpeg SBC at 128,
|
|
135
|
+
200 and 328 kbit/s. ~108 B/s of payload.
|
|
136
|
+
* Stop-and-wait ARQ: a frame is resent until ACKed (`--retries`, `--ack-timeout`).
|
|
137
|
+
* Messages are JSON, chunked into 224 byte bodies, reassembled with START/END.
|
|
138
|
+
* Auth is a pre-shared key file (`--key`), HMAC-SHA256 over `seq || body`,
|
|
139
|
+
truncated to 16 bytes, plus a nonce handshake. It replaces sshd, not SSH's
|
|
140
|
+
asymmetric crypto: no forward secrecy, no host key pinning. Keep it on a link
|
|
141
|
+
you already trust, or treat it as "not open to the room".
|
|
142
|
+
|
|
143
|
+
## Limits, stated plainly
|
|
144
|
+
|
|
145
|
+
* Payload throughput is ~108 B/s on the acoustic link. It is a shell for small
|
|
146
|
+
commands, not for `tar | gzip` over the air.
|
|
147
|
+
* A2DP is one way: a full session needs HFP (the speaker's microphone) or two
|
|
148
|
+
paired devices. `pw` and `portaudio` record from the same node/device they
|
|
149
|
+
play into, so duplex means a headset, not a plain speaker.
|
|
150
|
+
* The Android server runs commands in the app sandbox via `/system/bin/sh`; it
|
|
151
|
+
tries `su -c` when the device is rooted. No root, no bash, no `/etc`.
|
|
152
|
+
* BLE needs a central that keeps the connection: `bleak` does, macOS needs the
|
|
153
|
+
app to be foregrounded once to grant Bluetooth permission.
|
|
154
|
+
* Nothing here is tested against a physical speaker in CI: the codec path is
|
|
155
|
+
verified through ffmpeg's SBC encoder/decoder, the Android app is source only
|
|
156
|
+
(no SDK on the machine that generated this repo).
|
|
157
|
+
|
|
158
|
+
## Tests
|
|
159
|
+
|
|
160
|
+
```bash
|
|
161
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
162
|
+
btsh selftest --frames 12
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
## Android app
|
|
166
|
+
|
|
167
|
+
```
|
|
168
|
+
android/app/src/main/java/com/marcpartensky/btsh/
|
|
169
|
+
├── Protocol.kt frame pack/unpack, same bytes as Python
|
|
170
|
+
├── ShellRunner.kt /system/bin/sh or su -c, output capped
|
|
171
|
+
├── BtshGattServer.kt GATT service, ACKs, chunking, HMAC, AirPods advertising
|
|
172
|
+
├── BtshService.kt foreground service, keeps advertising alive
|
|
173
|
+
└── MainActivity.kt key field, start/stop, log
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
Build on a machine with the Android SDK (not on tower):
|
|
177
|
+
|
|
178
|
+
```bash
|
|
179
|
+
cd android && ./gradlew assembleDebug # needs gradle wrapper, see below
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
No gradle wrapper is committed: run `gradle wrapper` once, or open the folder in
|
|
183
|
+
Android Studio. Install with `adb install app/build/outputs/apk/debug/app-debug.apk`,
|
|
184
|
+
then start it, set the same key as the client, and connect from the desktop:
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
btsh exec --transport ble --ble-name "AirPods" --key ~/.btsh.key -- "getprop ro.product.model"
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Nix
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
nix build .# # the package
|
|
194
|
+
nix run .# -- demo
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`module.nix` installs the CLI and can run a `btsh serve` unit:
|
|
198
|
+
|
|
199
|
+
```nix
|
|
200
|
+
services.btsh = {
|
|
201
|
+
enable = true;
|
|
202
|
+
user = "marc";
|
|
203
|
+
keyFile = "/run/secrets/btsh.key";
|
|
204
|
+
cwd = "/home/marc";
|
|
205
|
+
allow = [ "^ls" "^cat" "^uname" ];
|
|
206
|
+
};
|
|
207
|
+
```
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
btsh/__init__.py,sha256=UPUhccd-hUURhlrU0I4MHtfaqkAVnbAicT4PXMczugY,821
|
|
2
|
+
btsh/__main__.py,sha256=ZIU-8Kr05uGYHRCMDt0HAGUNAypokKknKzpvVYzJLdY,81
|
|
3
|
+
btsh/audio.py,sha256=mrBiT9Eojau5_1zu_y5B7l7jebPfOYMiSydnhOMLIFA,5037
|
|
4
|
+
btsh/ble.py,sha256=wfptFJ1yMvPnvs0sU7sZO91Z8heCIDLwVRkR3Nz1Eug,5834
|
|
5
|
+
btsh/bt.py,sha256=ARE5PYSQ3u7HvVGo17Sptih6Nwu0KLGeZNFkeenKn1g,3089
|
|
6
|
+
btsh/channel.py,sha256=LOKxoSY10wITxEmjvzvXpxvFaZmLcYcp3YPibHYdpuA,4147
|
|
7
|
+
btsh/channels.py,sha256=4QK8TB908vVrWVc5-veHVau6EhNNRz_mRvuaFneDNkg,4238
|
|
8
|
+
btsh/cli.py,sha256=3cTn9erhcbTJ-agaKCtc5beT0EfoZM_vBJA4_QShWg4,20693
|
|
9
|
+
btsh/client.py,sha256=qswYgL6UblYq6Xe2VW80JSfmA35HOSMwv2FvOmyek1Q,2598
|
|
10
|
+
btsh/codec.py,sha256=d3YeIr2SdX3fKiEP28myP61UjABZQ65rg2M3U5kkO2k,4413
|
|
11
|
+
btsh/crypto.py,sha256=hARgc6-U9hlE7EgHgL_OfPCpQCIb1SYqQ3UByWNDZfw,8663
|
|
12
|
+
btsh/framing.py,sha256=SCaEbah6UKh_l2KAjxOcqQ2GaByNLH_Kkk7_LYNm9ag,2728
|
|
13
|
+
btsh/hub.py,sha256=einwy5KNE2nEK1LtFY2syKkb_t-KelcV5e0a9jpU0J4,11031
|
|
14
|
+
btsh/mcp.py,sha256=I0cEDkwvjGMgZQLz0jrLB54XmOkpMZWcHqkJfIN6dBU,9163
|
|
15
|
+
btsh/modem.py,sha256=xxXHBclhhliLAlf4uWIfef8tqUGjl0IizHkyD-yGSOw,6348
|
|
16
|
+
btsh/node.py,sha256=614v2F2s8PqRRjAyzDZBocaaLeiIJ5LqlgjtCGalBJQ,7564
|
|
17
|
+
btsh/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
18
|
+
btsh/server.py,sha256=8RMYFisXJayB_pvQwdP1OoYF4Gx1Bts_axlZLFRGkjU,6876
|
|
19
|
+
btsh/session.py,sha256=CStHbko7bfOYquwqRtJKJgl0EPsGzoOTlyJKVWY01gc,7908
|
|
20
|
+
btsh/transport.py,sha256=lu-qw_dwBGWX_Y3KxDkiyCqsbc7yqYf73jiaM7Qh9Ys,11021
|
|
21
|
+
datap-0.1.0.dist-info/METADATA,sha256=G9Sb6i0hnI0H0Fz-XdFnyB577L0Kg919436SZDKUKDE,7926
|
|
22
|
+
datap-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
23
|
+
datap-0.1.0.dist-info/entry_points.txt,sha256=A94kkkFmU1Q_e3NmKkbFNE--NwsPxWyYcehEZy58ATU,39
|
|
24
|
+
datap-0.1.0.dist-info/top_level.txt,sha256=26tPOnsiMnwzQjoKBUm2pt1TlnwL3n4-v5r8O7Hz6bc,5
|
|
25
|
+
datap-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
btsh
|