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/hub.py ADDED
@@ -0,0 +1,266 @@
1
+ """Hub: one process that several peers connect to, and that routes between them.
2
+
3
+ Topology this implements (the one the Android app does over BLE):
4
+
5
+ client A ----> hub ----> client B A: exec "uname" on B
6
+ client A <---- hub <---- client B result comes back through the hub
7
+ |
8
+ +-> local shell (op=exec with no "to")
9
+
10
+ Routing key is the peer name sent in HELLO. A message with ``"to": "<name>"``
11
+ is forwarded to that peer and its answer is relayed back; without ``to`` (or
12
+ with ``"to": "server"``) the hub executes the command itself.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import secrets
19
+ import time
20
+ from dataclasses import dataclass, field
21
+
22
+ from . import crypto, framing
23
+ from .channel import Channel
24
+ from .channels import ChannelError, ChannelRegistry
25
+ from .server import ShellConfig, execute
26
+ from .session import Session
27
+
28
+
29
+ @dataclass
30
+ class Peer:
31
+ channel: Channel
32
+ session: Session
33
+ name: str = ""
34
+ address: str = ""
35
+ served: int = 0
36
+ connected_at: float = field(default_factory=time.time)
37
+
38
+
39
+ class Hub:
40
+ def __init__(
41
+ self,
42
+ config: ShellConfig | None = None,
43
+ key: bytes | None = None,
44
+ name: str = "server",
45
+ route_timeout: float = 120.0,
46
+ verbose: bool = False,
47
+ identity: "crypto.Identity | None" = None,
48
+ ) -> None:
49
+ self.config = config or ShellConfig()
50
+ self.key = key
51
+ self.identity = identity
52
+ self.channels = ChannelRegistry()
53
+ self.name = name
54
+ self.route_timeout = route_timeout
55
+ self.verbose = verbose
56
+ self.peers: list[Peer] = []
57
+
58
+ # -- peers -----------------------------------------------------------
59
+ def add(self, channel: Channel, name: str = "", address: str = "") -> Peer:
60
+ peer = Peer(
61
+ channel=channel,
62
+ session=Session(channel, key=self.key, identity=self.identity, verbose=self.verbose),
63
+ name=name,
64
+ address=address,
65
+ )
66
+ self.peers.append(peer)
67
+ self._log(f"peer added: {name or address or len(self.peers)}")
68
+ return peer
69
+
70
+ def find(self, name: str) -> Peer | None:
71
+ for peer in self.peers:
72
+ if peer.name == name or (peer.address and peer.address == name):
73
+ return peer
74
+ return None
75
+
76
+ def roster(self) -> list[dict]:
77
+ own = self.identity.fingerprint if self.identity is not None else ""
78
+ roster = [{"name": self.name, "address": "local", "served": 0, "fingerprint": own, "sealed": self.identity is not None}]
79
+ for index, peer in enumerate(self.peers):
80
+ roster.append(
81
+ {
82
+ "name": peer.name or peer.address or f"peer{index}",
83
+ "address": peer.address,
84
+ "served": peer.served,
85
+ "fingerprint": self._fingerprint(peer.session.peer_public),
86
+ "sealed": peer.session.sealed,
87
+ }
88
+ )
89
+ return roster
90
+
91
+ @staticmethod
92
+ def _fingerprint(public: bytes | None) -> str:
93
+ return hashlib.sha256(public).hexdigest()[:16] if public else ""
94
+
95
+ def _log(self, message: str) -> None:
96
+ if self.verbose:
97
+ print(f"[btsh hub] {message}", flush=True)
98
+
99
+ # -- loop ------------------------------------------------------------
100
+ def serve_forever(self, stop=None, poll: float = 0.2) -> None:
101
+ while True:
102
+ if stop is not None and stop():
103
+ return
104
+ for peer in list(self.peers):
105
+ try:
106
+ frame = peer.channel.recv(poll)
107
+ except Exception as exc: # noqa: BLE001 - keep the hub alive
108
+ self._log(f"link error on {peer.name}: {exc}")
109
+ continue
110
+ if frame is None:
111
+ continue
112
+ try:
113
+ self.handle(peer, frame)
114
+ except Exception as exc: # noqa: BLE001
115
+ self._log(f"error from {peer.name or peer.address}: {exc}")
116
+
117
+ def handle(self, peer: Peer, frame: framing.Frame) -> None:
118
+ if frame.ftype == framing.FT_HELLO:
119
+ self._hello(peer, frame)
120
+ return
121
+ if frame.ftype == framing.FT_BYE:
122
+ self._log(f"bye from {peer.name or peer.address}")
123
+ self.peers = [item for item in self.peers if item is not peer]
124
+ return
125
+ if frame.ftype != framing.FT_DATA:
126
+ return
127
+ message = peer.session.receive_from(frame, self.route_timeout)
128
+ if message is None:
129
+ return
130
+ self.dispatch(peer, message)
131
+
132
+ def _hello(self, peer: Peer, frame: framing.Frame) -> None:
133
+ peer.session.answer_hello(frame)
134
+ if peer.session.peer_name:
135
+ peer.name = peer.session.peer_name
136
+ elif not peer.name:
137
+ peer.name = peer.address or f"peer{len(self.peers)}"
138
+ self._log(f"hello {peer.name}")
139
+
140
+ # -- routing ---------------------------------------------------------
141
+ def dispatch(self, peer: Peer, message: dict) -> None:
142
+ op = message.get("op")
143
+ rid = message.get("rid") or ""
144
+ if op == "peers":
145
+ peer.session.send_message({"op": "peers", "peers": self.roster(), "channels": self.channels.describe()})
146
+ return
147
+ if op == "ping":
148
+ peer.session.send_message({"op": "pong", "ts": int(time.time()), "peer": self.name})
149
+ return
150
+ if op == "bye":
151
+ peer.session.send_message({"op": "bye"})
152
+ return
153
+ if op == "channels":
154
+ peer.session.send_message({"op": "channels", "channels": self.channels.describe(), "peers": self.roster()})
155
+ return
156
+ if op in ("sub", "subscribe"):
157
+ self._subscribe(peer, message)
158
+ return
159
+ if op in ("unsub", "unsubscribe"):
160
+ self._unsubscribe(peer, message)
161
+ return
162
+ if op in ("allow", "deny"):
163
+ self._policy(peer, message, op)
164
+ return
165
+ if op in ("pub", "publish"):
166
+ self._publish(peer, message)
167
+ return
168
+ if op != "exec":
169
+ peer.session.send_message({"op": "error", "error": f"unknown op {op!r}", "rid": rid})
170
+ return
171
+
172
+ target_name = str(message.get("to") or "")
173
+ command = str(message.get("cmd") or "")
174
+ if target_name in ("", "server", self.name):
175
+ self._log(f"{peer.name}: exec {command!r} locally")
176
+ peer.served += 1
177
+ peer.session.send_message(execute(command, self.config))
178
+ return
179
+
180
+ target = self.find(target_name)
181
+ if target is None or target is peer:
182
+ peer.session.send_message({"op": "error", "error": f"no such peer: {target_name}", "peers": self.roster()})
183
+ return
184
+ self._log(f"{peer.name} -> {target.name}: {command!r}")
185
+ try:
186
+ target.session.send_message({"op": "exec", "from": peer.name, "cmd": command, "rid": secrets.token_hex(8)})
187
+ answer = target.session.recv_message(self.route_timeout)
188
+ if answer is None:
189
+ answer = {"op": "error", "error": f"{target.name} did not answer"}
190
+ except Exception as exc: # noqa: BLE001 - report, do not die
191
+ answer = {"op": "error", "error": f"{target.name}: {exc}"}
192
+ answer = dict(answer)
193
+ answer["from"] = target.name
194
+ answer["via"] = self.name
195
+ peer.session.send_message(answer)
196
+
197
+ # -- channels --------------------------------------------------------
198
+ @staticmethod
199
+ def _channel_name(message: dict) -> str:
200
+ return str(message.get("channel") or message.get("ch") or "")
201
+
202
+ def _subscribe(self, peer: Peer, message: dict) -> None:
203
+ name = self._channel_name(message)
204
+ try:
205
+ channel = self.channels.subscribe(name, peer.name, owner_of_new=peer.name)
206
+ except ChannelError as exc:
207
+ peer.session.send_message({"op": "error", "error": str(exc), "channel": name})
208
+ return
209
+ self._log(f"{peer.name} subscribes to #{channel.name}")
210
+ peer.session.send_message({"op": "subscribed", "channel": channel.describe(), "publishers": channel.describe()["publishers"]})
211
+
212
+ def _unsubscribe(self, peer: Peer, message: dict) -> None:
213
+ name = self._channel_name(message)
214
+ try:
215
+ channel = self.channels.unsubscribe(name, peer.name)
216
+ except ChannelError as exc:
217
+ peer.session.send_message({"op": "error", "error": str(exc), "channel": name})
218
+ return
219
+ peer.session.send_message({"op": "unsubscribed", "channel": channel.describe()})
220
+
221
+ def _policy(self, peer: Peer, message: dict, action: str) -> None:
222
+ name = self._channel_name(message)
223
+ subject = str(message.get("peer") or "")
224
+ try:
225
+ if action == "allow":
226
+ channel = self.channels.allow(name, peer.name, subject)
227
+ else:
228
+ channel = self.channels.deny(name, peer.name, subject)
229
+ except ChannelError as exc:
230
+ peer.session.send_message({"op": "error", "error": str(exc), "channel": name})
231
+ return
232
+ self._log(f"{action} {subject} on #{channel.name}")
233
+ peer.session.send_message({"op": action, "channel": channel.describe()})
234
+
235
+ def _publish(self, peer: Peer, message: dict) -> None:
236
+ name = self._channel_name(message)
237
+ command = str(message.get("cmd") or "")
238
+ rid = str(message.get("rid") or "")
239
+ try:
240
+ targets = self.channels.targets(name, peer.name)
241
+ label = f"#{self.channels.get(name).name}"
242
+ except ChannelError as exc:
243
+ peer.session.send_message({"op": "error", "error": str(exc), "channel": name, "rid": rid})
244
+ return
245
+ self._log(f"publish on {label} from {peer.name} to {targets}")
246
+ results = []
247
+ for target_name in targets:
248
+ if target_name in ("server", self.name):
249
+ result = execute(command, self.config)
250
+ results.append({"peer": self.name, **result})
251
+ continue
252
+ target = self.find(target_name)
253
+ if target is None:
254
+ results.append({"peer": target_name, "op": "error", "error": "not connected"})
255
+ continue
256
+ try:
257
+ target.session.send_message(
258
+ {"op": "exec", "channel": label, "from": peer.name, "cmd": command, "rid": secrets.token_hex(4)}
259
+ )
260
+ answer = target.session.recv_message(self.route_timeout)
261
+ if answer is None:
262
+ raise RuntimeError("no answer")
263
+ results.append({"peer": target_name, **answer})
264
+ except Exception as exc: # noqa: BLE001
265
+ results.append({"peer": target_name, "op": "error", "error": str(exc)})
266
+ peer.session.send_message({"op": "result", "channel": label, "results": results, "rid": rid})
btsh/mcp.py ADDED
@@ -0,0 +1,213 @@
1
+ """MCP server: exposes btsh peers as tools an agent can call.
2
+
3
+ Transport is stdio with newline delimited JSON-RPC 2.0, the MCP baseline, and
4
+ nothing but the standard library is required.
5
+
6
+ Tools
7
+ -----
8
+ ``btsh_peers`` list the peers reachable through the hub
9
+ ``btsh_exec`` run a command on a peer (``peer="server"`` runs it on the hub)
10
+ ``btsh_local`` run a command on the machine hosting this MCP process
11
+ ``btsh_ping`` round trip to one peer
12
+
13
+ Where to run it: one MCP per machine that hosts an agent is enough. The MCP is
14
+ itself a node of the mesh, so from that single process you can reach every peer
15
+ the hub knows, including the Android app if it advertises itself as a peer.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import sys
22
+ import time
23
+
24
+ PROTOCOL_VERSION = "2024-11-05"
25
+
26
+ TOOLS = [
27
+ {
28
+ "name": "btsh_peers",
29
+ "description": "List the btsh peers reachable through the hub (name, address, served count).",
30
+ "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
31
+ },
32
+ {
33
+ "name": "btsh_exec",
34
+ "description": "Run a shell command on another btsh peer and return its stdout, stderr and exit code. Use peer='server' to run it on the hub itself.",
35
+ "inputSchema": {
36
+ "type": "object",
37
+ "properties": {
38
+ "peer": {"type": "string", "description": "peer name, as returned by btsh_peers, or 'server'"},
39
+ "command": {"type": "string", "description": "command line handed to the peer's shell"},
40
+ "timeout_s": {"type": "number", "description": "how long to wait for the answer", "default": 180},
41
+ },
42
+ "required": ["peer", "command"],
43
+ "additionalProperties": False,
44
+ },
45
+ },
46
+ {
47
+ "name": "btsh_channels",
48
+ "description": "List the channels of the mesh, with their owner, subscribers and who may publish.",
49
+ "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False},
50
+ },
51
+ {
52
+ "name": "btsh_publish",
53
+ "description": "Publish a command line on a channel: every subscriber runs it and the results come back per peer. This is how A runs a command on B on B's channel.",
54
+ "inputSchema": {
55
+ "type": "object",
56
+ "properties": {
57
+ "channel": {"type": "string", "description": "channel name, with or without the leading #"},
58
+ "command": {"type": "string"},
59
+ "timeout_s": {"type": "number", "default": 180},
60
+ },
61
+ "required": ["channel", "command"],
62
+ "additionalProperties": False,
63
+ },
64
+ },
65
+ {
66
+ "name": "btsh_subscribe",
67
+ "description": "Subscribe this machine to a channel, so it runs whatever is published there.",
68
+ "inputSchema": {
69
+ "type": "object",
70
+ "properties": {"channel": {"type": "string"}},
71
+ "required": ["channel"],
72
+ "additionalProperties": False,
73
+ },
74
+ },
75
+ {
76
+ "name": "btsh_local",
77
+ "description": "Run a shell command on the machine hosting this MCP server (no Bluetooth hop).",
78
+ "inputSchema": {
79
+ "type": "object",
80
+ "properties": {"command": {"type": "string"}},
81
+ "required": ["command"],
82
+ "additionalProperties": False,
83
+ },
84
+ },
85
+ {
86
+ "name": "btsh_ping",
87
+ "description": "Check that a peer answers, with a round trip time in milliseconds.",
88
+ "inputSchema": {
89
+ "type": "object",
90
+ "properties": {"peer": {"type": "string"}},
91
+ "required": ["peer"],
92
+ "additionalProperties": False,
93
+ },
94
+ },
95
+ ]
96
+
97
+
98
+ class UnknownTool(Exception):
99
+ """Raised for a tool name this server does not expose."""
100
+
101
+
102
+ def _text(payload: dict) -> dict:
103
+ stdout = payload.get("stdout") or ""
104
+ stderr = payload.get("stderr") or ""
105
+ rc = payload.get("rc")
106
+ header = f"rc={rc}" if rc is not None else f"op={payload.get('op')}"
107
+ if payload.get("from"):
108
+ header += f" from={payload['from']}"
109
+ if payload.get("error"):
110
+ header += f" error={payload['error']}"
111
+ body = [header]
112
+ if stdout:
113
+ body.append("--- stdout\n" + stdout)
114
+ if stderr:
115
+ body.append("--- stderr\n" + stderr)
116
+ if payload.get("truncated"):
117
+ body.append("--- output truncated by the peer")
118
+ text = "\n".join(body)
119
+ return {"content": [{"type": "text", "text": text}], "isError": bool(payload.get("error")) or bool(rc)}
120
+
121
+
122
+ class McpServer:
123
+ """JSON-RPC dispatcher; transport-agnostic so tests can drive it."""
124
+
125
+ def __init__(self, backend, name: str = "btsh") -> None:
126
+ self.backend = backend
127
+ self.name = name
128
+
129
+ def handle(self, request: dict) -> dict | None:
130
+ method = request.get("method")
131
+ request_id = request.get("id")
132
+ params = request.get("params") or {}
133
+ if request_id is None:
134
+ return None # notification: nothing to answer
135
+ try:
136
+ result = self.dispatch(method, params)
137
+ except (KeyError, UnknownTool) as exc:
138
+ return self._error(request_id, -32602, f"invalid params: {exc}")
139
+ except Exception as exc: # noqa: BLE001 - never drop the session
140
+ return self._error(request_id, -32603, f"{type(exc).__name__}: {exc}")
141
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
142
+
143
+ def dispatch(self, method: str, params: dict):
144
+ if method == "initialize":
145
+ return {
146
+ "protocolVersion": PROTOCOL_VERSION,
147
+ "capabilities": {"tools": {"listChanged": False}},
148
+ "serverInfo": {"name": self.name, "version": "0.2.0"},
149
+ "instructions": "btsh exposes a meshed shell over Bluetooth. Use btsh_peers first, then btsh_exec.",
150
+ }
151
+ if method == "tools/list":
152
+ return {"tools": TOOLS}
153
+ if method == "ping":
154
+ return {}
155
+ if method == "tools/call":
156
+ tool = params.get("name", "")
157
+ if tool not in {entry["name"] for entry in TOOLS}:
158
+ raise UnknownTool(f"unknown tool {tool!r}")
159
+ return self.call(tool, params.get("arguments") or {})
160
+ raise NotImplementedError(method)
161
+
162
+ def call(self, tool: str, arguments: dict) -> dict:
163
+ if tool == "btsh_peers":
164
+ return {"content": [{"type": "text", "text": json.dumps(self.backend.peers(), indent=2)}], "isError": False}
165
+ if tool == "btsh_exec":
166
+ target = str(arguments["peer"])
167
+ command = str(arguments["command"])
168
+ timeout = float(arguments.get("timeout_s") or 180)
169
+ return _text(self.backend.exec_on(target, command, timeout))
170
+ if tool == "btsh_channels":
171
+ answer = self.backend.channels()
172
+ return {"content": [{"type": "text", "text": json.dumps(answer, indent=2)}], "isError": False}
173
+ if tool == "btsh_publish":
174
+ answer = self.backend.publish(str(arguments["channel"]), str(arguments["command"]), float(arguments.get("timeout_s") or 180))
175
+ failed = answer.get("op") == "error" or any(item.get("rc") != 0 for item in answer.get("results") or [])
176
+ text = json.dumps(answer, indent=2)
177
+ return {"content": [{"type": "text", "text": text}], "isError": bool(failed)}
178
+ if tool == "btsh_subscribe":
179
+ answer = self.backend.subscribe(str(arguments["channel"]))
180
+ return {"content": [{"type": "text", "text": json.dumps(answer, indent=2)}], "isError": answer.get("op") != "subscribed"}
181
+ if tool == "btsh_local":
182
+ return _text(self.backend.local(str(arguments["command"])))
183
+ if tool == "btsh_ping":
184
+ started = time.monotonic()
185
+ answer = self.backend.exec_on(str(arguments["peer"]), "echo pong", 30)
186
+ elapsed = int((time.monotonic() - started) * 1000)
187
+ payload = dict(answer)
188
+ payload["stdout"] = f"{(answer.get('stdout') or '').strip()} in {elapsed} ms"
189
+ return _text(payload)
190
+ raise NotImplementedError(tool)
191
+
192
+ def _error(self, request_id, code: int, message: str) -> dict:
193
+ if message.startswith("NotImplementedError: "):
194
+ code, message = -32601, message.removeprefix("NotImplementedError: ")
195
+ return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
196
+
197
+ def serve(self, stdin=None, stdout=None) -> None:
198
+ stdin = stdin or sys.stdin
199
+ stdout = stdout or sys.stdout
200
+ for line in stdin:
201
+ line = line.strip()
202
+ if not line:
203
+ continue
204
+ try:
205
+ request = json.loads(line)
206
+ except json.JSONDecodeError as exc:
207
+ response = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}}
208
+ else:
209
+ response = self.handle(request) if isinstance(request, dict) else None
210
+ if response is None:
211
+ continue
212
+ stdout.write(json.dumps(response) + "\n")
213
+ stdout.flush()
btsh/modem.py ADDED
@@ -0,0 +1,196 @@
1
+ """Acoustic modem: bytes in, 48 kHz s16le mono PCM out, and back.
2
+
3
+ The waveform is a 4-FSK modulation chosen to survive lossy Bluetooth codecs
4
+ (SBC/AAC/aptX) that resample and requantise the signal:
5
+
6
+ sample rate 48 kHz
7
+ symbol 2 ms (96 samples), 500 symbols/s
8
+ tones 1000 / 2000 / 3000 / 4000 Hz, 1000 Hz apart
9
+ bits per symbol 2 (500 * 2 = 1000 bit/s, ~108 bytes/s of payload)
10
+
11
+ Measured with ffmpeg SBC at 128/200/328 kbit/s: 8 frames of 8 recovered per 8
12
+ sent, clean and through the codec. The wider tone spacing is what buys the
13
+ speed: 600 Hz spaced tones at 2 ms collide inside one SBC band.
14
+
15
+ Every burst starts with 24 ms of silence, a 12 symbol preamble and the 32 bit
16
+ sync word, so the receiver can find the burst and align its symbol clock
17
+ without any clock sharing.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import array
23
+ import math
24
+
25
+ SAMPLE_RATE = 48000
26
+ SYMBOL_SAMPLES = 96
27
+ TONES = (1000.0, 2000.0, 3000.0, 4000.0)
28
+ SYNC_WORD = 0x1ACFFC1D
29
+ PREAMBLE = (3, 0, 3, 0, 3, 0, 3, 0, 3, 0, 3, 0)
30
+ LEAD_SILENCE = 1152 # 24 ms, lets the receiver see a clean onset
31
+ TAIL_SILENCE = 2304 # 48 ms, drains the codec and the speaker
32
+ RAMP = 16 # raised-cosine ramp at each symbol edge, limits spectral splatter
33
+
34
+
35
+ class ModemError(Exception):
36
+ """Raised when a frame cannot be recovered from the waveform."""
37
+
38
+
39
+ def _bits(data: bytes) -> list[int]:
40
+ out: list[int] = []
41
+ for byte in data:
42
+ for shift in (6, 4, 2, 0):
43
+ out.append((byte >> shift) & 0x03)
44
+ return out
45
+
46
+
47
+ def _symbols(data: bytes) -> list[int]:
48
+ return _bits(data)
49
+
50
+
51
+ def _sync_symbols() -> list[int]:
52
+ return _bits(SYNC_WORD.to_bytes(4, "big"))
53
+
54
+
55
+ def _goertzel_coeff(freq: float, n: int) -> tuple[float, float]:
56
+ k = int(0.5 + n * freq / SAMPLE_RATE)
57
+ w = 2.0 * math.pi * k / n
58
+ return 2.0 * math.cos(w), w
59
+
60
+
61
+ _COEFF_CACHE: dict[tuple[float, int], float] = {}
62
+
63
+
64
+ def _mags(window: array.array) -> list[float]:
65
+ n = len(window)
66
+ out = []
67
+ for freq in TONES:
68
+ key = (freq, n)
69
+ c = _COEFF_CACHE.get(key)
70
+ if c is None:
71
+ c, _w = _goertzel_coeff(freq, n)
72
+ _COEFF_CACHE[key] = c
73
+ s0 = s1 = s2 = 0.0
74
+ for value in window:
75
+ s0 = value + c * s1 - s2
76
+ s2 = s1
77
+ s1 = s0
78
+ out.append(abs(s1 * s1 + s2 * s2 - c * s1 * s2))
79
+ return out
80
+
81
+
82
+ def modulate(wire: bytes, amplitude: float = 0.6) -> bytes:
83
+ """Modulate a wire frame into PCM (s16le, mono, 48 kHz)."""
84
+ symbols = list(PREAMBLE) + _sync_symbols() + _symbols(wire)
85
+ out = array.array("h")
86
+ out.extend(array.array("h", [0] * LEAD_SILENCE))
87
+ phase = 0.0
88
+ level = int(max(0.0, min(1.0, amplitude)) * 32767)
89
+ for symbol in symbols:
90
+ step = 2.0 * math.pi * TONES[symbol] / SAMPLE_RATE
91
+ for n in range(SYMBOL_SAMPLES):
92
+ if n < RAMP:
93
+ env = 0.5 - 0.5 * math.cos(math.pi * n / RAMP)
94
+ elif n >= SYMBOL_SAMPLES - RAMP:
95
+ env = 0.5 - 0.5 * math.cos(math.pi * (SYMBOL_SAMPLES - n) / RAMP)
96
+ else:
97
+ env = 1.0
98
+ out.append(int(level * env * math.sin(phase)))
99
+ phase += step
100
+ if phase > 2.0 * math.pi:
101
+ phase -= 2.0 * math.pi
102
+ out.extend(array.array("h", [0] * TAIL_SILENCE))
103
+ return out.tobytes()
104
+
105
+
106
+ def _symbol_at(samples: array.array, start: int) -> int:
107
+ window = samples[start : start + SYMBOL_SAMPLES]
108
+ mags = _mags(window)
109
+ return max(range(4), key=mags.__getitem__)
110
+
111
+
112
+ def _onset(samples: array.array, ratio: float = 0.2) -> int:
113
+ peak = max(max(samples), -min(samples))
114
+ if peak < 500:
115
+ raise ModemError("no signal")
116
+ threshold = peak * ratio
117
+ for index, value in enumerate(samples):
118
+ if value > threshold or -value > threshold:
119
+ return max(0, index - RAMP)
120
+ raise ModemError("no signal")
121
+
122
+
123
+ def _score(samples: array.array, start: int, expected: list[int], picks: list[int]) -> int:
124
+ score = 0
125
+ for symbol_index in picks:
126
+ pos = start + symbol_index * SYMBOL_SAMPLES
127
+ if pos + SYMBOL_SAMPLES > len(samples):
128
+ break
129
+ if _symbol_at(samples, pos) == expected[symbol_index]:
130
+ score += _WEIGHTS.get(symbol_index, 1)
131
+ return score
132
+
133
+
134
+ _WEIGHTS: dict[int, int] = {}
135
+
136
+
137
+ def demodulate(pcm: bytes) -> bytes:
138
+ """Recover a wire frame from PCM. Raises ModemError if nothing is decodable."""
139
+ if len(pcm) < 2:
140
+ raise ModemError("empty burst")
141
+ samples = array.array("h")
142
+ samples.frombytes(pcm[: len(pcm) // 2 * 2])
143
+ expected = list(PREAMBLE) + _sync_symbols()
144
+ total = len(expected)
145
+
146
+ onset = _onset(samples)
147
+ if onset + total * SYMBOL_SAMPLES > len(samples):
148
+ raise ModemError("burst too short")
149
+
150
+ coarse_picks = [0, 2, 4, 6, 8, 10, 12, 13]
151
+ best_start, best_score = onset, -1
152
+ for offset in range(-3 * SYMBOL_SAMPLES, 3 * SYMBOL_SAMPLES + 1, 16):
153
+ start = onset + offset
154
+ if start < 0:
155
+ continue
156
+ score = _score(samples, start, expected, coarse_picks)
157
+ if score > best_score:
158
+ best_start, best_score = start, score
159
+
160
+ start = best_start
161
+ best_score = -1
162
+ for offset in range(-16, 17, 2):
163
+ candidate = best_start + offset
164
+ if candidate < 0:
165
+ continue
166
+ score = _score(samples, candidate, expected, list(range(total)))
167
+ if score > best_score:
168
+ start, best_score = candidate, score
169
+
170
+ if best_score < total - 4:
171
+ raise ModemError(f"sync lost ({best_score}/{total})")
172
+
173
+ position = start + total * SYMBOL_SAMPLES
174
+
175
+ def read_bytes(count: int) -> bytes:
176
+ nonlocal position
177
+ out = bytearray()
178
+ for _ in range(count):
179
+ if position + SYMBOL_SAMPLES > len(samples):
180
+ raise ModemError("truncated burst")
181
+ byte = 0
182
+ for _ in range(4):
183
+ byte = (byte << 2) | _symbol_at(samples, position)
184
+ position += SYMBOL_SAMPLES
185
+ out.append(byte)
186
+ return bytes(out)
187
+
188
+ from . import framing
189
+
190
+ header = read_bytes(framing.HEADER_LEN)
191
+ try:
192
+ payload_len, ftype, seq, flags = framing.peek_header(header)
193
+ except framing.FrameError as exc:
194
+ raise ModemError(str(exc)) from exc
195
+ body = read_bytes(payload_len + 4)
196
+ return header + body