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/__init__.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""btsh - an ssh-like shell that rides on a Bluetooth speaker's audio codec."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
|
|
7
|
+
from .channel import Channel, ChannelError # noqa: E402
|
|
8
|
+
from .client import Client # noqa: E402
|
|
9
|
+
from .server import ShellConfig, ShellServer, execute # noqa: E402
|
|
10
|
+
from .session import AuthError, Session # noqa: E402
|
|
11
|
+
from .transport import ( # noqa: E402
|
|
12
|
+
AcousticTransport,
|
|
13
|
+
CodecTransport,
|
|
14
|
+
FifoTransport,
|
|
15
|
+
LoopbackTransport,
|
|
16
|
+
Transport,
|
|
17
|
+
TransportError,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
__all__ = [
|
|
21
|
+
"__version__",
|
|
22
|
+
"AcousticTransport",
|
|
23
|
+
"AuthError",
|
|
24
|
+
"Channel",
|
|
25
|
+
"ChannelError",
|
|
26
|
+
"Client",
|
|
27
|
+
"CodecTransport",
|
|
28
|
+
"FifoTransport",
|
|
29
|
+
"LoopbackTransport",
|
|
30
|
+
"Session",
|
|
31
|
+
"ShellConfig",
|
|
32
|
+
"ShellServer",
|
|
33
|
+
"Transport",
|
|
34
|
+
"TransportError",
|
|
35
|
+
"execute",
|
|
36
|
+
]
|
btsh/__main__.py
ADDED
btsh/audio.py
ADDED
|
@@ -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
|
btsh/ble.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""BLE GATT transport: the channel an Android app can actually serve.
|
|
2
|
+
|
|
3
|
+
Why BLE and not A2DP: an Android app cannot be an A2DP sink (`A2dpSinkService`
|
|
4
|
+
enforces ``BLUETOOTH_PRIVILEGED``), and even the system-side sink never hands
|
|
5
|
+
the decoded audio to an app. A GATT server, on the other hand, is a normal app
|
|
6
|
+
capability, and ``bleak`` drives it from Linux, macOS and Windows.
|
|
7
|
+
|
|
8
|
+
Wire format on the radio (no modem: the link is already digital):
|
|
9
|
+
|
|
10
|
+
write/notify chunk = [4 byte big endian length][length bytes of wire frame]
|
|
11
|
+
|
|
12
|
+
The frame itself is the same ``btsh`` frame (version, type, seq, flags,
|
|
13
|
+
length, payload, crc32), so the session, the chunking, the ARQ and the
|
|
14
|
+
pre-shared-key tag are shared with the acoustic transport.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import asyncio
|
|
20
|
+
import queue
|
|
21
|
+
import struct
|
|
22
|
+
import threading
|
|
23
|
+
import time
|
|
24
|
+
|
|
25
|
+
from .transport import Transport, TransportError
|
|
26
|
+
|
|
27
|
+
SERVICE_UUID = "6d5f0001-8b1e-4a4f-9d4e-1b3a5c7e9f01"
|
|
28
|
+
RX_UUID = "6d5f0002-8b1e-4a4f-9d4e-1b3a5c7e9f02" # client writes requests here
|
|
29
|
+
TX_UUID = "6d5f0003-8b1e-4a4f-9d4e-1b3a5c7e9f03" # server notifies answers here
|
|
30
|
+
DEFAULT_NAME = "btsh"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _loop_thread() -> tuple[asyncio.AbstractEventLoop, threading.Thread]:
|
|
34
|
+
loop = asyncio.new_event_loop()
|
|
35
|
+
thread = threading.Thread(target=loop.run_forever, name="btsh-ble-loop", daemon=True)
|
|
36
|
+
thread.start()
|
|
37
|
+
return loop, thread
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class BleTransport(Transport):
|
|
41
|
+
"""GATT client: connect to an address, write to RX, listen on TX."""
|
|
42
|
+
|
|
43
|
+
name = "ble"
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
address: str,
|
|
48
|
+
service_uuid: str = SERVICE_UUID,
|
|
49
|
+
rx_uuid: str = RX_UUID,
|
|
50
|
+
tx_uuid: str = TX_UUID,
|
|
51
|
+
connect_timeout: float = 25.0,
|
|
52
|
+
) -> None:
|
|
53
|
+
try:
|
|
54
|
+
from bleak import BleakClient # noqa: PLC0415 - optional dependency
|
|
55
|
+
except ImportError as exc: # pragma: no cover
|
|
56
|
+
raise TransportError("install btsh[ble] (pip install bleak)") from exc
|
|
57
|
+
self.address = address
|
|
58
|
+
self.service_uuid = service_uuid
|
|
59
|
+
self.rx_uuid = rx_uuid
|
|
60
|
+
self.tx_uuid = tx_uuid
|
|
61
|
+
self.mtu = 20
|
|
62
|
+
self._buffer = bytearray()
|
|
63
|
+
self._chunks: queue.Queue[bytes] = queue.Queue()
|
|
64
|
+
self._loop, _thread = _loop_thread()
|
|
65
|
+
self._client = BleakClient(address, timeout=connect_timeout)
|
|
66
|
+
try:
|
|
67
|
+
self._call(self._client.connect(), connect_timeout + 5)
|
|
68
|
+
except Exception as exc: # pragma: no cover - needs hardware
|
|
69
|
+
raise TransportError(f"BLE connect to {address} failed: {exc}") from exc
|
|
70
|
+
self._call(self._client.start_notify(tx_uuid, self._on_notify), 10)
|
|
71
|
+
mtu = getattr(self._client, "mtu_size", 23)
|
|
72
|
+
self.mtu = max(20, int(mtu) - 3)
|
|
73
|
+
|
|
74
|
+
# -- asyncio bridge --------------------------------------------------
|
|
75
|
+
def _call(self, coro, timeout: float = 20.0):
|
|
76
|
+
future = asyncio.run_coroutine_threadsafe(coro, self._loop)
|
|
77
|
+
return future.result(timeout=timeout)
|
|
78
|
+
|
|
79
|
+
def _on_notify(self, _sender, data: bytearray) -> None: # noqa: ANN001 - bleak signature
|
|
80
|
+
self._chunks.put(bytes(data))
|
|
81
|
+
|
|
82
|
+
# -- transport -------------------------------------------------------
|
|
83
|
+
def send_burst(self, frame: bytes) -> None:
|
|
84
|
+
body = struct.pack(">I", len(frame)) + frame
|
|
85
|
+
try:
|
|
86
|
+
for offset in range(0, len(body), self.mtu):
|
|
87
|
+
chunk = body[offset : offset + self.mtu]
|
|
88
|
+
self._call(self._client.write_gatt_char(self.rx_uuid, chunk, response=False), 15)
|
|
89
|
+
except Exception as exc: # pragma: no cover - link dropped
|
|
90
|
+
raise TransportError(f"BLE write failed: {exc}") from exc
|
|
91
|
+
|
|
92
|
+
def recv_burst(self, timeout: float = 5.0) -> bytes | None:
|
|
93
|
+
deadline = time.monotonic() + timeout
|
|
94
|
+
while time.monotonic() < deadline:
|
|
95
|
+
if len(self._buffer) >= 4:
|
|
96
|
+
(length,) = struct.unpack(">I", bytes(self._buffer[:4]))
|
|
97
|
+
if 0 < length <= 65535 and len(self._buffer) >= 4 + length:
|
|
98
|
+
frame = bytes(self._buffer[4 : 4 + length])
|
|
99
|
+
del self._buffer[: 4 + length]
|
|
100
|
+
return frame
|
|
101
|
+
if length > 65535:
|
|
102
|
+
self._buffer.clear()
|
|
103
|
+
try:
|
|
104
|
+
self._buffer.extend(self._chunks.get(timeout=max(0.01, deadline - time.monotonic())))
|
|
105
|
+
except queue.Empty:
|
|
106
|
+
break
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
def describe(self) -> dict:
|
|
110
|
+
out = super().describe()
|
|
111
|
+
out.update({"address": self.address, "mtu": self.mtu, "service": self.service_uuid})
|
|
112
|
+
return out
|
|
113
|
+
|
|
114
|
+
def close(self) -> None:
|
|
115
|
+
try:
|
|
116
|
+
self._call(self._client.disconnect(), 10)
|
|
117
|
+
except Exception: # pragma: no cover
|
|
118
|
+
pass
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def scan(timeout: float = 8.0) -> list[dict]:
|
|
122
|
+
"""Discover BLE peripherals, ``[{"address", "name", "rssi"}]``."""
|
|
123
|
+
try:
|
|
124
|
+
from bleak import BleakScanner # noqa: PLC0415
|
|
125
|
+
except ImportError as exc: # pragma: no cover
|
|
126
|
+
raise TransportError("install btsh[ble] (pip install bleak)") from exc
|
|
127
|
+
|
|
128
|
+
async def _discover() -> list[dict]:
|
|
129
|
+
found = await BleakScanner.discover(timeout=timeout)
|
|
130
|
+
return [
|
|
131
|
+
{"address": device.address, "name": device.name or "", "rssi": getattr(device, "rssi", None)}
|
|
132
|
+
for device in found
|
|
133
|
+
]
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
return asyncio.run(_discover())
|
|
137
|
+
except Exception as exc: # noqa: BLE001 - DBus, permissions, no adapter
|
|
138
|
+
raise TransportError(f"BLE scan failed: {exc}") from exc
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def find(needle: str, timeout: float = 8.0) -> str:
|
|
142
|
+
"""Return the address of the first peripheral whose name matches."""
|
|
143
|
+
needle = needle.lower()
|
|
144
|
+
for device in scan(timeout):
|
|
145
|
+
if needle in (device["name"] or "").lower():
|
|
146
|
+
return device["address"]
|
|
147
|
+
raise TransportError(f"no BLE peripheral named {needle!r}")
|
btsh/bt.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Bluetooth device discovery and connection helpers (BlueZ via bluetoothctl)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import subprocess
|
|
7
|
+
|
|
8
|
+
MAC_RE = re.compile(r"^([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}$")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class BluetoothError(Exception):
|
|
12
|
+
"""Raised when bluetoothctl cannot be driven."""
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _run(args: list[str], timeout: float = 20.0) -> str:
|
|
16
|
+
try:
|
|
17
|
+
proc = subprocess.run(args, capture_output=True, text=True, timeout=timeout)
|
|
18
|
+
except FileNotFoundError as exc:
|
|
19
|
+
raise BluetoothError("bluetoothctl not found") from exc
|
|
20
|
+
except subprocess.TimeoutExpired as exc:
|
|
21
|
+
raise BluetoothError(f"{' '.join(args)} timed out") from exc
|
|
22
|
+
if proc.returncode != 0:
|
|
23
|
+
raise BluetoothError(proc.stderr.strip() or f"{' '.join(args)} failed")
|
|
24
|
+
return proc.stdout
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def devices() -> list[dict]:
|
|
28
|
+
"""Paired and known devices, as ``[{"mac", "name"}]``."""
|
|
29
|
+
out: list[dict] = []
|
|
30
|
+
for line in _run(["bluetoothctl", "devices"]).splitlines():
|
|
31
|
+
parts = line.split(maxsplit=2)
|
|
32
|
+
if len(parts) >= 2 and parts[0] == "Device":
|
|
33
|
+
name = parts[2] if len(parts) > 2 else ""
|
|
34
|
+
out.append({"mac": parts[1].upper(), "name": name})
|
|
35
|
+
return out
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def info(mac: str) -> dict:
|
|
39
|
+
data: dict[str, str | bool | list[str]] = {}
|
|
40
|
+
connected = False
|
|
41
|
+
uuids: list[str] = []
|
|
42
|
+
for raw in _run(["bluetoothctl", "info", mac]).splitlines():
|
|
43
|
+
line = raw.strip()
|
|
44
|
+
if not line:
|
|
45
|
+
continue
|
|
46
|
+
if line.startswith("UUID:"):
|
|
47
|
+
uuids.append(line[5:].strip())
|
|
48
|
+
continue
|
|
49
|
+
if ":" not in line:
|
|
50
|
+
continue
|
|
51
|
+
key, value = line.split(":", 1)
|
|
52
|
+
value = value.strip()
|
|
53
|
+
if key == "Connected":
|
|
54
|
+
connected = value == "yes"
|
|
55
|
+
data[key.strip()] = False if value == "no" else True if value == "yes" else value
|
|
56
|
+
data["connected"] = connected
|
|
57
|
+
data["uuids"] = uuids
|
|
58
|
+
data["mac"] = mac.upper()
|
|
59
|
+
return data
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def resolve(name_or_mac: str) -> dict:
|
|
63
|
+
"""Find a device by MAC or by (case insensitive) name substring."""
|
|
64
|
+
if MAC_RE.match(name_or_mac):
|
|
65
|
+
return {"mac": name_or_mac.upper(), "name": ""}
|
|
66
|
+
needle = name_or_mac.lower()
|
|
67
|
+
for device in devices():
|
|
68
|
+
if needle in device["name"].lower():
|
|
69
|
+
return device
|
|
70
|
+
raise BluetoothError(f"no bluetooth device matches {name_or_mac!r}")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def connect(name_or_mac: str) -> str:
|
|
74
|
+
device = resolve(name_or_mac)
|
|
75
|
+
return _run(["bluetoothctl", "connect", device["mac"]], timeout=30.0).strip()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def disconnect(name_or_mac: str) -> str:
|
|
79
|
+
device = resolve(name_or_mac)
|
|
80
|
+
return _run(["bluetoothctl", "disconnect", device["mac"]], timeout=30.0).strip()
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def profiles(device_info: dict) -> dict[str, bool]:
|
|
84
|
+
"""Which of the two interesting profiles the device offers."""
|
|
85
|
+
joined = " ".join(str(item) for item in device_info.get("uuids", []))
|
|
86
|
+
return {
|
|
87
|
+
"a2dp_sink": "0000110b" in joined, # device can play audio we send
|
|
88
|
+
"hfp_hf": "0000111e" in joined, # device has a microphone (duplex)
|
|
89
|
+
"a2dp_source": "0000110a" in joined,
|
|
90
|
+
}
|
btsh/channel.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Burst channel: framing + modem + optional codec + stop-and-wait ARQ."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
from . import framing, modem
|
|
8
|
+
from .framing import Frame
|
|
9
|
+
from .transport import CodecTransport, Transport
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ChannelError(Exception):
|
|
13
|
+
"""Raised when a frame cannot be delivered after all retries."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Channel:
|
|
17
|
+
"""Reliable frame exchange over a lossy, half-duplex burst transport."""
|
|
18
|
+
|
|
19
|
+
def __init__(
|
|
20
|
+
self,
|
|
21
|
+
transport: Transport,
|
|
22
|
+
codec: str = "none",
|
|
23
|
+
bitrate: int = 200_000,
|
|
24
|
+
retries: int = 6,
|
|
25
|
+
ack_timeout: float = 6.0,
|
|
26
|
+
verbose: bool = False,
|
|
27
|
+
mode: str = "acoustic",
|
|
28
|
+
) -> None:
|
|
29
|
+
if mode not in ("acoustic", "raw"):
|
|
30
|
+
raise ValueError(f"bad mode {mode!r}")
|
|
31
|
+
self.mode = mode
|
|
32
|
+
self.transport = CodecTransport(transport, codec, bitrate) if codec != "none" and mode == "acoustic" else transport
|
|
33
|
+
self.retries = retries
|
|
34
|
+
self.ack_timeout = ack_timeout
|
|
35
|
+
self.verbose = verbose
|
|
36
|
+
self.seq = 0
|
|
37
|
+
self.stats = {"sent": 0, "retries": 0, "acks": 0, "bad_frames": 0, "recv": 0}
|
|
38
|
+
|
|
39
|
+
# -- logging ---------------------------------------------------------
|
|
40
|
+
def _log(self, message: str) -> None:
|
|
41
|
+
if self.verbose:
|
|
42
|
+
print(f"[btsh] {message}", flush=True)
|
|
43
|
+
|
|
44
|
+
# -- internal --------------------------------------------------------
|
|
45
|
+
def _next_seq(self) -> int:
|
|
46
|
+
self.seq = (self.seq + 1) & 0xFF
|
|
47
|
+
return self.seq
|
|
48
|
+
|
|
49
|
+
def _transmit(self, frame: Frame) -> None:
|
|
50
|
+
wire = framing.pack(frame)
|
|
51
|
+
payload = wire if self.mode == "raw" else modem.modulate(wire)
|
|
52
|
+
self.transport.send_burst(payload)
|
|
53
|
+
self.stats["sent"] += 1
|
|
54
|
+
|
|
55
|
+
def _expect_ack(self, seq: int, deadline: float) -> bool:
|
|
56
|
+
while time.monotonic() < deadline:
|
|
57
|
+
frame = self.recv(deadline - time.monotonic())
|
|
58
|
+
if frame is None:
|
|
59
|
+
return False
|
|
60
|
+
if frame.ftype == framing.FT_ACK and frame.seq == seq:
|
|
61
|
+
self.stats["acks"] += 1
|
|
62
|
+
return True
|
|
63
|
+
return False
|
|
64
|
+
|
|
65
|
+
# -- public ----------------------------------------------------------
|
|
66
|
+
def send(
|
|
67
|
+
self,
|
|
68
|
+
ftype: int,
|
|
69
|
+
payload: bytes = b"",
|
|
70
|
+
flags: int = 0,
|
|
71
|
+
expect_ack: bool = True,
|
|
72
|
+
seq: int | None = None,
|
|
73
|
+
) -> int:
|
|
74
|
+
"""Send one frame, retransmitting until acknowledged. Returns its seq."""
|
|
75
|
+
seq = self._next_seq() if seq is None else (seq & 0xFF)
|
|
76
|
+
frame = Frame(ftype=ftype, seq=seq, payload=payload, flags=flags)
|
|
77
|
+
attempts = self.retries + 1
|
|
78
|
+
for attempt in range(attempts):
|
|
79
|
+
self._transmit(frame)
|
|
80
|
+
if not expect_ack:
|
|
81
|
+
return seq
|
|
82
|
+
if self._expect_ack(seq, time.monotonic() + self.ack_timeout):
|
|
83
|
+
return seq
|
|
84
|
+
self.stats["retries"] += 1
|
|
85
|
+
self._log(f"retry {attempt + 1}/{attempts} seq={seq} {frame.type_name}")
|
|
86
|
+
raise ChannelError(f"no ack for {frame.type_name} seq={seq} after {attempts} attempts")
|
|
87
|
+
|
|
88
|
+
def recv(self, timeout: float = 5.0) -> Frame | None:
|
|
89
|
+
"""Receive one frame and ACK it. Returns None on timeout or corruption."""
|
|
90
|
+
pcm = self.transport.recv_burst(timeout)
|
|
91
|
+
if not pcm:
|
|
92
|
+
return None
|
|
93
|
+
try:
|
|
94
|
+
wire = pcm if self.mode == "raw" else modem.demodulate(pcm)
|
|
95
|
+
frame = framing.unpack(wire)
|
|
96
|
+
except (modem.ModemError, framing.FrameError) as exc:
|
|
97
|
+
self.stats["bad_frames"] += 1
|
|
98
|
+
self._log(f"drop burst: {exc}")
|
|
99
|
+
return None
|
|
100
|
+
self.stats["recv"] += 1
|
|
101
|
+
self._log(f"recv {frame}")
|
|
102
|
+
if frame.ftype not in (framing.FT_ACK, framing.FT_NAK):
|
|
103
|
+
try:
|
|
104
|
+
self.send(framing.FT_ACK, expect_ack=False, seq=frame.seq)
|
|
105
|
+
except Exception: # noqa: BLE001 - an ack is best effort
|
|
106
|
+
pass
|
|
107
|
+
return frame
|
|
108
|
+
|
|
109
|
+
def describe(self) -> dict:
|
|
110
|
+
out = self.transport.describe()
|
|
111
|
+
out.update({"stats": dict(self.stats), "codec_applied": getattr(self.transport, "applied", 0)})
|
|
112
|
+
return out
|
btsh/channels.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Channels: named, ACL'd command topics, the WebSocket-like part of btsh.
|
|
2
|
+
|
|
3
|
+
A channel is a topic. Subscribing means "run every command published on this
|
|
4
|
+
topic". Publishing means "send this command line to every subscriber".
|
|
5
|
+
|
|
6
|
+
A subscribes to #from-b -> whatever B publishes there runs on A
|
|
7
|
+
B subscribes to #from-a -> whatever A publishes there runs on B
|
|
8
|
+
A creates #from-a and allows B to publish; B creates #from-b and allows A.
|
|
9
|
+
|
|
10
|
+
That is exactly the RabbitMQ/WebSocket shape, minus the broker: the hub only
|
|
11
|
+
keeps the subscriber list and relays, it does not need to understand payloads.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import time
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ChannelError(Exception):
|
|
21
|
+
"""Raised for an unknown channel or a refused publication."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def normalise(name: str) -> str:
|
|
25
|
+
name = name.strip()
|
|
26
|
+
if not name:
|
|
27
|
+
raise ChannelError("empty channel name")
|
|
28
|
+
if name.startswith("#"):
|
|
29
|
+
name = name[1:]
|
|
30
|
+
if "/" in name or " " in name:
|
|
31
|
+
raise ChannelError(f"invalid channel name: {name!r}")
|
|
32
|
+
return name
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class Channel:
|
|
37
|
+
name: str
|
|
38
|
+
owner: str
|
|
39
|
+
subscribers: list[str] = field(default_factory=list)
|
|
40
|
+
publishers: list[str] = field(default_factory=list)
|
|
41
|
+
created_at: float = field(default_factory=time.time)
|
|
42
|
+
published: int = 0
|
|
43
|
+
|
|
44
|
+
def allows_publish(self, peer: str) -> bool:
|
|
45
|
+
return peer == self.owner or peer in self.publishers
|
|
46
|
+
|
|
47
|
+
def describe(self) -> dict:
|
|
48
|
+
return {
|
|
49
|
+
"channel": f"#{self.name}",
|
|
50
|
+
"owner": self.owner,
|
|
51
|
+
"subscribers": list(self.subscribers),
|
|
52
|
+
"publishers": sorted({self.owner, *self.publishers}),
|
|
53
|
+
"published": self.published,
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class ChannelRegistry:
|
|
58
|
+
def __init__(self) -> None:
|
|
59
|
+
self.channels: dict[str, Channel] = {}
|
|
60
|
+
|
|
61
|
+
def get(self, name: str) -> Channel:
|
|
62
|
+
key = normalise(name)
|
|
63
|
+
if key not in self.channels:
|
|
64
|
+
raise ChannelError(f"no such channel: #{key}")
|
|
65
|
+
return self.channels[key]
|
|
66
|
+
|
|
67
|
+
def create(self, name: str, owner: str, publishers: list[str] | None = None) -> Channel:
|
|
68
|
+
key = normalise(name)
|
|
69
|
+
if key in self.channels:
|
|
70
|
+
return self.channels[key]
|
|
71
|
+
channel = Channel(name=key, owner=owner, publishers=list(publishers or []))
|
|
72
|
+
self.channels[key] = channel
|
|
73
|
+
return channel
|
|
74
|
+
|
|
75
|
+
def subscribe(self, name: str, peer: str, owner_of_new: str | None = None) -> Channel:
|
|
76
|
+
try:
|
|
77
|
+
channel = self.get(name)
|
|
78
|
+
except ChannelError:
|
|
79
|
+
channel = self.create(name, owner_of_new or peer)
|
|
80
|
+
if peer not in channel.subscribers:
|
|
81
|
+
channel.subscribers.append(peer)
|
|
82
|
+
return channel
|
|
83
|
+
|
|
84
|
+
def unsubscribe(self, name: str, peer: str) -> Channel:
|
|
85
|
+
channel = self.get(name)
|
|
86
|
+
if peer in channel.subscribers:
|
|
87
|
+
channel.subscribers.remove(peer)
|
|
88
|
+
return channel
|
|
89
|
+
|
|
90
|
+
def allow(self, name: str, requester: str, peer: str) -> Channel:
|
|
91
|
+
channel = self.get(name)
|
|
92
|
+
if requester != channel.owner:
|
|
93
|
+
raise ChannelError(f"only the owner ({channel.owner}) can change #{channel.name}")
|
|
94
|
+
if peer not in channel.publishers:
|
|
95
|
+
channel.publishers.append(peer)
|
|
96
|
+
return channel
|
|
97
|
+
|
|
98
|
+
def deny(self, name: str, requester: str, peer: str) -> Channel:
|
|
99
|
+
channel = self.get(name)
|
|
100
|
+
if requester != channel.owner:
|
|
101
|
+
raise ChannelError(f"only the owner ({channel.owner}) can change #{channel.name}")
|
|
102
|
+
if peer in channel.publishers:
|
|
103
|
+
channel.publishers.remove(peer)
|
|
104
|
+
return channel
|
|
105
|
+
|
|
106
|
+
def targets(self, name: str, publisher: str) -> list[str]:
|
|
107
|
+
channel = self.get(name)
|
|
108
|
+
if not channel.allows_publish(publisher):
|
|
109
|
+
raise ChannelError(f"{publisher} may not publish on #{channel.name}")
|
|
110
|
+
channel.published += 1
|
|
111
|
+
return [peer for peer in channel.subscribers]
|
|
112
|
+
|
|
113
|
+
def drop_peer(self, peer: str) -> None:
|
|
114
|
+
for channel in self.channels.values():
|
|
115
|
+
if peer in channel.subscribers:
|
|
116
|
+
channel.subscribers.remove(peer)
|
|
117
|
+
|
|
118
|
+
def describe(self) -> list[dict]:
|
|
119
|
+
return [channel.describe() for channel in self.channels.values()]
|