From b2f415dfbad018ad272402a90084c8fc58d0d9ab Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:28:33 -0700 Subject: [PATCH] radio replay; modem lines in sniffed captures; never write over a capture radio replay sends the requests RPM sent in a captured read to the radio again and compares each answer with the one RPM got: the first test of reading a radio without RPM. It stops at the first answer that differs (--keep-going carries on), when the radio does not answer, or as soon as an answer is longer than RPM's. It keeps RPM's pauses where RPM got no answer and RPM's DTR/RTS. Only reads are replayed: the radio's answers must hold a personality, RPM's requests must not, and RPM must have sent less than the radio; anything else is refused before the port is opened. radio sniff records each side's RFCOMM modem status commands as line events. Capture files are never written over: the next free name is used (sniff and relay default to session.jsonl, so a second session replaced the first). --- CHANGELOG.md | 3 + README.md | 4 +- docs/bluetooth.md | 46 ++++++- quickprs/cli.py | 31 ++++- quickprs/radio/__init__.py | 6 +- quickprs/radio/capture.py | 28 +++- quickprs/radio/commands.py | 71 +++++++++- quickprs/radio/hci.py | 30 ++++- quickprs/radio/replay.py | 184 +++++++++++++++++++++++++ tests/test_radio.py | 269 ++++++++++++++++++++++++++++++++++++- tests/test_radio_hci.py | 69 ++++++++++ 11 files changed, 713 insertions(+), 28 deletions(-) create mode 100644 quickprs/radio/replay.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ade82c..bfd94ea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ All notable changes to QuickPRS will be documented in this file. ### Added - `quickprs radio sniff`: record RPM's session with the radio from a Bluetooth trace served by Microsoft's Bluetooth Virtual Sniffer (or a saved pcap/pcapng file), without a virtual COM port driver. It keeps only the serial bytes RPM and the radio exchange, in the capture format `analyze` reads, reads traces with or without direction headers, and ends with a report of what the trace held (and why, when it found no serial data). com0com, which the relay needs, cannot load while Windows 11's Memory Integrity is on - `quickprs radio analyze --transcript`: the conversation in a capture, message by message (chunks going the same way within 50 ms are one message), and the common message sizes and first bytes in each direction +- `quickprs radio replay`: send RPM's requests from a captured read to the radio again and compare each answer with the one RPM got, the first test of reading a radio without RPM. It stops at the first answer that differs (`--keep-going` carries on) or when the radio does not answer, keeps RPM's pauses and modem lines, and refuses any capture that is not a read (the radio's answers must hold a personality and RPM's requests must not) +- `radio sniff` records each side's modem lines (RFCOMM modem status) as events - `--skip-encrypted` for `import-rr`, `auto-setup` and `import-paste`: leave out talkgroups RadioReference lists as fully encrypted ### Fixed @@ -19,6 +21,7 @@ All notable changes to QuickPRS will be documented in this file. - GUI: Save always kept a backup whatever the auto backup setting said; sixteen settings nothing read (a default NAC, a scan limit, an export folder and thirteen P25 system options QuickPRS cannot write) are gone - GUI: editors that change only the open personality say Apply, not Save; a failure writing the recent files list no longer fails a save - Shell completions listed 33 of the 63 commands and stale flags; they are now read from the CLI's parser +- `radio probe`, `relay` and `sniff` wrote over an existing capture file (`sniff` and `relay` default to `session.jsonl`, so a second session replaced the first); a capture is now never written over, and the next free name is used ## [1.2.0] - 2026-10-28 diff --git a/README.md b/README.md index 01c6a96..8520756 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Generate and edit Harris XG-100P personality (.PRS) files without Harris RPM sof > **STATUS: In Development.** This tool is under active development. While the binary format has been extensively reverse-engineered and tested against known-good RPM files, it has NOT been exhaustively tested on all XG-100P hardware revisions and firmware versions. Test on non-critical equipment first. -> **IMPORTANT: This tool does NOT load mission plans onto radios.** QuickPRS generates and edits .PRS personality files. To actually load a personality onto an XG-100P radio, you still need Harris RPM software (for now). The `quickprs radio` commands are groundwork for reading radios directly over Bluetooth: they find the radio and record RPM's sessions with it, and never send bytes of their own (see [docs/bluetooth.md](docs/bluetooth.md)). +> **IMPORTANT: This tool does NOT load mission plans onto radios.** QuickPRS generates and edits .PRS personality files. To actually load a personality onto an XG-100P radio, you still need Harris RPM software (for now). The `quickprs radio` commands are groundwork for reading radios directly over Bluetooth: they find the radio, record RPM's sessions with it and replay a recorded read to test reading without RPM, and never send bytes of their own (see [docs/bluetooth.md](docs/bluetooth.md)). ## RadioReference Integration @@ -70,7 +70,7 @@ The GUI includes a dedicated RadioReference import wizard (File > Import Wizard) - Full GUI with tree view, inline editing, drag-and-drop, and RadioReference import wizard - Built-in channel templates (MURS, GMRS, FRS, Marine, NOAA, Interop, Public Safety) - Built-in list of 28 US P25 systems as a starting point (IDs unverified except where marked: confirm them before programming) -- Bluetooth groundwork: find a paired radio and record RPM's sessions with it (`quickprs radio`) +- Bluetooth groundwork: find a paired radio, record RPM's sessions with it and replay a read (`quickprs radio`) - JSON export/import for human-editable radio configs - Export to CHIRP CSV, Uniden CSV, SDRTrunk, DSD+, Markdown, INI - Merge, clone, and compare PRS files diff --git a/docs/bluetooth.md b/docs/bluetooth.md index 9548f00..b9251ea 100644 --- a/docs/bluetooth.md +++ b/docs/bluetooth.md @@ -6,7 +6,12 @@ what RPM and the radio say to each other, so the programming protocol can be learned from real sessions instead of guessed. **None of these commands sends a byte of its own to the radio.** The relay -forwards only what RPM sends. +forwards only what RPM sends, and `replay` sends only the requests RPM sent +in a captured read. + +A capture is never written over: when the file named with `--log` exists, +the command takes the next free name (`read-2.jsonl`, `read-3.jsonl` ...) +and says which. ## Bluetooth Classic, not BLE @@ -92,8 +97,10 @@ After Ctrl+C the report should list RFCOMM frames (the channel opening and closing) even though nothing was sent. A full trace holds more than the serial data (Bluetooth link keys among -it); QuickPRS writes only the serial bytes, and only from the radio's link -once the trace has shown which link that is. `--pcap trace.pcapng` reads a +it); QuickPRS writes only the serial bytes and each side's modem lines (the +PC's DTR and RTS, the radio's DSR, CTS, RI and DCD, from RFCOMM's modem +status commands), and only from the radio's link once the trace has shown +which link that is. `--pcap trace.pcapng` reads a trace saved from Wireshark instead. Traces with or without a direction header (pcap link types 201 and 187) both work. @@ -146,13 +153,40 @@ A capture is a JSON Lines file: a header line, then one line per chunk read (`t` seconds since the start, `dir` `pc>radio` or `radio>pc`, `hex` bytes) and modem-line events. +## Replay a read + +```bash +quickprs radio replay read.jsonl --requests 3 +quickprs radio replay read.jsonl +``` + +`replay` sends the requests RPM sent in a captured read to the radio again, +in order, and compares each answer with the one RPM got. It is the first +test of whether QuickPRS can read the radio by itself: when every answer is +the same, RPM's requests can become QuickPRS's own read command. At the +first answer that differs it stops and says where (`--keep-going` sends the +rest anyway): something in the session changes each time, a counter, a time +or a challenge, and those bytes need decoding first. It also stops when the +radio does not answer. `--requests N` sends only the first N requests. + +Only reads are replayed. The capture must show the radio sending a +personality and RPM sending none, and RPM must have sent less than the +radio. A write, an activate or a remove changes the radio, so a capture of +one is refused before the port is opened. + +Where RPM got no answer to a request, `replay` keeps RPM's pause before the +next one (up to 5 seconds), and it sets DTR and RTS as RPM did when the +capture recorded them. The replay is saved as a capture too +(`replay.jsonl` by default), so `analyze` and `--extract` work on it. + ## Next steps ```mermaid flowchart LR - A["capture RPM
extracting"] --> B["decode the
framing and commands"] - B --> C["read a radio
with QuickPRS"] - C --> D["capture RPM
writing"] --> E["write a radio
with QuickPRS"] + A["capture RPM
extracting"] --> B["replay the read"] + B -->|"same answers"| C["read a radio
with QuickPRS"] + B -->|"answers differ"| D["decode the
framing and commands"] --> C + C --> E["capture RPM
writing"] --> F["write a radio
with QuickPRS"] ``` Writing comes last and only after reading works and the write session is diff --git a/quickprs/cli.py b/quickprs/cli.py index fa105ff..9708da9 100644 --- a/quickprs/cli.py +++ b/quickprs/cli.py @@ -4411,13 +4411,16 @@ def build_parser(): # radio (Bluetooth / serial link to the radio itself) p_radio = sub.add_parser( "radio", - help="Find a paired radio, listen to it, or log RPM talking to it", + help="Find a paired radio, listen to it, log RPM talking to it " + "or replay a read", formatter_class=fmt, epilog="The XG-100P's Bluetooth is Classic (serial port profile), " "which RPM\n" "programs over just like the USB cable. These commands " "never send\n" - "their own bytes to the radio.\n" + "their own bytes to the radio; replay sends only RPM's " + "requests from a\n" + "captured read.\n" "Examples:\n" " quickprs radio scan\n" " quickprs radio probe --port COM6 --seconds 15 " @@ -4426,6 +4429,7 @@ def build_parser(): " quickprs radio relay --pc-port COM21 --radio-port COM6 " "--log read.jsonl\n" " quickprs radio analyze read.jsonl --transcript 60\n" + " quickprs radio replay read.jsonl --requests 3\n" " quickprs radio analyze read.jsonl --extract radio.PRS") radio_sub = p_radio.add_subparsers(dest="radio_cmd") p_rscan = radio_sub.add_parser( @@ -4484,6 +4488,24 @@ def build_parser(): p_ranalyze.add_argument("--extract", default=None, help="Write a personality archive found in the " "radio's replies to this .PRS path") + p_rreplay = radio_sub.add_parser( + "replay", + help="Send RPM's requests from a captured read to the radio again " + "and compare the answers") + p_rreplay.add_argument("capture", + help="Capture (.jsonl) of RPM reading the radio") + p_rreplay.add_argument("--port", default=None, + help="COM port (default: the one paired radio)") + p_rreplay.add_argument("--log", default="replay.jsonl", + help="Capture file for the replay (default " + "replay.jsonl, or the next free name)") + p_rreplay.add_argument("--requests", type=int, default=None, + metavar="N", help="Send only the first N requests") + p_rreplay.add_argument("--timeout", type=float, default=3.0, + help="Seconds to wait for an answer (default 3)") + p_rreplay.add_argument("--keep-going", action="store_true", + help="Carry on past answers that are not the " + "ones RPM got") p_icsv = sub.add_parser( "import-csv", @@ -5776,6 +5798,11 @@ def run_cli(args=None): return radio_commands.cmd_radio_analyze( parsed.capture, extract=parsed.extract, transcript=parsed.transcript) + if parsed.radio_cmd == "replay": + return radio_commands.cmd_radio_replay( + parsed.capture, port=parsed.port, log=parsed.log, + requests=parsed.requests, timeout=parsed.timeout, + keep_going=parsed.keep_going) subcommand_parsers["radio"].print_help() return 1 elif parsed.command == "import-csv": diff --git a/quickprs/radio/__init__.py b/quickprs/radio/__init__.py index f009b29..5e17d9e 100644 --- a/quickprs/radio/__init__.py +++ b/quickprs/radio/__init__.py @@ -16,6 +16,10 @@ * ``probe`` open the radio's port and listen; never transmits * ``relay`` sit between RPM and the radio and log what they say * ``analyze`` summarise a capture and pull out any personality in it +* ``hci`` the serial bytes in a Bluetooth HCI trace (``sniff``) +* ``replay`` send RPM's requests from a captured read to the radio + again, and compare the answers with RPM's -Nothing here sends a byte of its own to the radio. +Nothing here sends a byte of its own to the radio: ``replay`` sends only +what RPM sent, and only from a session that read a personality. """ diff --git a/quickprs/radio/capture.py b/quickprs/radio/capture.py index fc8e8e8..af64fe0 100644 --- a/quickprs/radio/capture.py +++ b/quickprs/radio/capture.py @@ -9,7 +9,9 @@ {"t": 0.0456, "dir": "radio>pc", "hex": "5a 01 ..."} {"t": 0.0460, "event": "pc dtr=1 rts=0"} -``t`` is seconds since the session started. Directions are named from the +``t`` is seconds since the session started. A capture is never +written over: when the file exists, the writer takes the next free name +(``read-2.jsonl``, ``read-3.jsonl`` ...) and says so in ``path``. Directions are named from the radio's side of the conversation: ``pc>radio`` is what RPM (or the PC) sent, ``radio>pc`` what the radio answered. """ @@ -17,6 +19,7 @@ from dataclasses import dataclass, field from datetime import datetime, timezone import json +from pathlib import Path import threading import time @@ -48,8 +51,21 @@ def total(self, direction=None): if direction is None or c.direction == direction) +def _create(path): + """A new file at ``path``, or at the next free numbered name when that + is taken, and the path used.""" + first = Path(path) + p, n = first, 1 + while True: + try: + return open(p, "x", encoding="utf-8", newline="\n"), p + except FileExistsError: + n += 1 + p = first.with_name(f"{first.stem}-{n}{first.suffix}") + + class CaptureWriter: - """Append chunks to a capture file as they happen. + """Append chunks to a new capture file as they happen. Each line is flushed at once, so a crash or Ctrl+C keeps everything read so far, and a lock keeps lines whole when two threads (the two @@ -57,7 +73,7 @@ class CaptureWriter: """ def __init__(self, path, note=""): - self._f = open(path, "w", encoding="utf-8", newline="\n") + self._f, self.path = _create(path) self._t0 = time.monotonic() self._lock = threading.Lock() header = {"capture": "quickprs", "version": 1, @@ -85,8 +101,10 @@ def add(self, direction, data, t=None): self._write({"t": self._now() if t is None else t, "dir": direction, "hex": data.hex(" ")}) - def event(self, text): - self._write({"t": self._now(), "event": str(text)}) + def event(self, text, t=None): + """Log an event, such as a modem-line change; ``t`` as for add.""" + self._write({"t": self._now() if t is None else t, + "event": str(text)}) def close(self): self._f.close() diff --git a/quickprs/radio/commands.py b/quickprs/radio/commands.py index 660fd09..ab909b7 100644 --- a/quickprs/radio/commands.py +++ b/quickprs/radio/commands.py @@ -100,8 +100,8 @@ def show(data): if writer is not None: writer.close() print(f"Received {offset[0]} bytes: {classify(data)}.") - if log: - print(f"Capture saved to {log}") + if writer is not None: + print(f"Capture saved to {writer.path}") return 0 @@ -128,11 +128,11 @@ def cmd_radio_relay(pc_port, radio_port=None, log="session.jsonl", def tally(direction, data): counts[direction] += len(data) - print(f"Relaying {pc_port} (RPM side) <-> {radio_port} (radio), " - f"logging to {log}. Point RPM at the other end of the virtual " - f"pair, run the operation, then press Ctrl+C here.") with CaptureWriter(log, note=note or f"relay {pc_port} <-> {radio_port}") as writer: + print(f"Relaying {pc_port} (RPM side) <-> {radio_port} (radio), " + f"logging to {writer.path}. Point RPM at the other end of the " + f"virtual pair, run the operation, then press Ctrl+C here.") try: errors = run_relay(pc, radio, writer=writer, on_chunk=tally) finally: @@ -142,7 +142,7 @@ def tally(direction, data): f"RPM: {counts['radio>pc']:,} bytes.") for direction, e in errors: print(f" {direction} ended: {e}", file=sys.stderr) - print(f"Analyze with: quickprs radio analyze {log}") + print(f"Analyze with: quickprs radio analyze {writer.path}") return 0 @@ -192,10 +192,14 @@ def cmd_radio_sniff(host="127.0.0.1", port=24352, log="session.jsonl", stats = TraceStats() with CaptureWriter(log, note=note) as writer: + print(f"Writing the serial data to {writer.path}") try: for t, direction, data in serial_chunks(read_packets(stream), address=address, stats=stats): + if isinstance(data, str): # a modem line change + writer.event(data, t=t) + continue writer.add(direction, data, t=t) counts[direction] += len(data) except KeyboardInterrupt: @@ -208,10 +212,63 @@ def cmd_radio_sniff(host="127.0.0.1", port=24352, log="session.jsonl", print(line) print(f"RPM to radio: {counts['pc>radio']:,} bytes; radio to RPM: " f"{counts['radio>pc']:,} bytes.") - print(f"Analyze with: quickprs radio analyze {log}") + print(f"Analyze with: quickprs radio analyze {writer.path}") return 0 +def cmd_radio_replay(capture_path, port=None, log="replay.jsonl", + requests=None, timeout=3.0, keep_going=False, + quiet=0.3): + """Send RPM's requests from a captured read to the radio again and + compare the answers with the ones RPM got.""" + from .replay import capture_lines, replay, steps, why_refused + if requests is not None and requests < 1: + print("Error: --requests must be at least 1", file=sys.stderr) + return 1 + try: + cap = read_capture(capture_path) + except (OSError, ValueError) as e: + print(f"Error: {e}", file=sys.stderr) + return 1 + reason = why_refused(cap) + if reason: + print(f"Not replaying {capture_path}: {reason}.", file=sys.stderr) + return 1 + plan = steps(cap) + if requests is not None: + plan = plan[:requests] + port = _pick_port(port) + if port is None: + return 1 + lines = capture_lines(cap) + dtr, rts = lines or (False, False) + try: + link = open_serial(port, dtr=dtr, rts=rts) + except LinkError as e: + print(f"Error: {e}", file=sys.stderr) + return 1 + with CaptureWriter(log, note=f"replay of {capture_path} on " + f"{port}") as writer: + print(f"Sending RPM's {len(plan)} requests " + f"({sum(len(s.request) for s in plan):,} bytes) to {port} " + f"and comparing each answer with the one RPM got; logging " + f"to {writer.path}.") + try: + result = replay(link, plan, writer=writer, timeout=timeout, + quiet=quiet, keep_going=keep_going) + finally: + link.close() + for d in result.differences: + print(f" request {d.step + 1}: {d.describe()}") + print(f"Sent {result.sent} of {len(plan)} requests; {result.same} " + f"answers were the ones RPM got.") + if result.stopped: + print(f"Stopped: {result.stopped}.") + print(f"Analyze with: quickprs radio analyze {writer.path} " + f"--extract radio.PRS") + return 0 if result.same == len(plan) else 1 + + def cmd_radio_analyze(capture_path, extract=None, transcript=None): try: cap = read_capture(capture_path) diff --git a/quickprs/radio/hci.py b/quickprs/radio/hci.py index 4f6fa4e..6c6043c 100644 --- a/quickprs/radio/hci.py +++ b/quickprs/radio/hci.py @@ -24,6 +24,10 @@ LINKTYPE_H4 = 187 # H4 packet, no direction LINKTYPE_H4_WITH_PHDR = 201 # 4-byte direction (0 = sent, 1 = received) +# RFCOMM multiplexer control: modem status command (type 0x38, with the +# C/R and EA bits set) +MSC_COMMAND = 0xE3 + # H4 packet types H4_COMMAND, H4_ACL, H4_SCO, H4_EVENT = 1, 2, 3, 4 @@ -346,10 +350,16 @@ def _l2cap(self, link, direction, cid, payload): name = FRAME_NAMES.get(frame.frame_type, hex(frame.frame_type)) self.stats.rfcomm_frames[name] = self.stats.rfcomm_frames.get( name, 0) + 1 - if frame.frame_type != RFCOMM_UIH or not frame.dlci: + if frame.frame_type != RFCOMM_UIH: return [] if direction is None: direction = SENT if frame.cr else RECEIVED + if not frame.dlci: + # the multiplexer's control channel, on a channel already + # known to be RFCOMM's + if cid in link.cid_dirs or link.learned.get(direction) == cid: + return modem_status(direction, frame.payload) + return [] if cid not in link.cid_dirs: # no connection setup seen: the first data frame each way # names that way's CID @@ -384,6 +394,21 @@ def _signaling(self, link, direction, data): link.cid_dirs[dcid] = SENT if pc_asked else RECEIVED +def modem_status(direction, data): + """A line event for a modem status command on RFCOMM's control channel + (TS 07.10 5.4.6.3.7), as (direction, text). Each side sends its own + lines: the PC its DTR and RTS, the radio what the PC sees as DSR, CTS, + RI and DCD. The answers, which only echo a command, are left out.""" + if len(data) < 4 or data[0] != MSC_COMMAND or data[1] >> 1 < 2: + return [] + signals = data[3] + rtc, rtr = (signals >> 2) & 1, (signals >> 3) & 1 + if direction == SENT: + return [(direction, f"pc dtr={rtc} rts={rtr}")] + ic, dv = (signals >> 6) & 1, (signals >> 7) & 1 + return [(direction, f"radio dsr={rtc} cts={rtr} ri={ic} dcd={dv}")] + + def h4_with_direction(linktype, data): """(direction, H4 packet) from a pcap record, or None for link types this reader does not handle. A trace without a direction header @@ -400,7 +425,8 @@ def h4_with_direction(linktype, data): def serial_chunks(packets, address=None, stats=None): """(seconds since the first packet, direction, bytes) for every serial - chunk in an iterable of (timestamp, linktype, data) pcap records. + chunk in an iterable of (timestamp, linktype, data) pcap records, and + (seconds, direction, text) for every modem status change. ``stats``, a TraceStats, is filled in as the trace is read.""" decoder = SerialFromHci(address, stats) stats = decoder.stats diff --git a/quickprs/radio/replay.py b/quickprs/radio/replay.py new file mode 100644 index 0000000..7c2c6ef --- /dev/null +++ b/quickprs/radio/replay.py @@ -0,0 +1,184 @@ +"""Send RPM's side of a recorded read session to the radio again. + +The first test of whether QuickPRS can read a radio without RPM. It sends +the requests RPM sent, in order, waits for the radio's answer to each and +compares it with the answer the radio gave RPM. Identical answers mean +RPM's requests can become QuickPRS's own read command. An answer that +differs means the session holds something that changes from one session to +the next (a counter, a time, a challenge); the replay stops there, unless +told to keep going, rather than send requests that no longer fit what the +radio said. + +Only sessions that read a personality are replayed: the radio's answers +must hold one (a CPersonality archive header) and RPM's requests must not. +Anything else (a write, an activate, a remove) changes the radio, and +replaying it would do that again with whatever the capture held. +""" + +from dataclasses import dataclass, field +import re +import time + +from .analyze import find_class_headers, messages +from .capture import PC_TO_RADIO, RADIO_TO_PC + + +@dataclass +class Step: + """A request RPM sent, and what the radio answered before RPM's next + request.""" + request: bytes + reply: bytes = b"" + pause: float = 0.0 # seconds until RPM's next request + + +def steps(capture, gap=0.05): + """The capture's requests and answers, in order. Anything the radio + said before the first request is left out.""" + out, replies, times = [], [], [] + for m in messages(capture, gap): + if m.direction == PC_TO_RADIO: + out.append(Step(m.data)) + replies.append([]) + times.append(m.t) + elif out: + replies[-1].append(m.data) + for step, parts in zip(out, replies): + step.reply = b"".join(parts) + for step, t, t_next in zip(out, times, times[1:]): + step.pause = round(t_next - t, 6) + return out + + +def _has_personality(data): + return any(h.name == "CPersonality" for h in find_class_headers(data)) + + +def why_refused(capture): + """None when ``capture`` is a session that read a personality, else + why it is not replayed.""" + sent = capture.stream(PC_TO_RADIO) + answers = capture.stream(RADIO_TO_PC) + if not sent: + return "RPM sent nothing in it" + if _has_personality(sent): + return "RPM sent a personality in it: it is a write" + if not _has_personality(answers): + return ("the radio's answers hold no personality, so it is not a " + "read QuickPRS can recognise (a write, activate or remove " + "changes the radio, and is never replayed)") + if len(sent) > len(answers): + return (f"RPM sent more than the radio answered ({len(sent):,} " + f"against {len(answers):,} bytes): it looks like a write") + return None + + +def capture_lines(capture): + """RPM's (DTR, RTS) from the capture's first 'pc dtr=.. rts=..' event, + or None when it recorded none.""" + for _, text in capture.events: + m = re.match(r"pc dtr=([01]) rts=([01])", text) + if m: + return m.group(1) == "1", m.group(2) == "1" + return None + + +@dataclass +class Difference: + """An answer that was not the one RPM got.""" + step: int # index of the request + expected: bytes + got: bytes + + @property + def offset(self): + """The first byte that differs, or the shorter length when one + answer starts the other.""" + for i, (a, b) in enumerate(zip(self.expected, self.got)): + if a != b: + return i + return min(len(self.expected), len(self.got)) + + def describe(self): + if not self.got: + return f"no answer (RPM got {len(self.expected):,} bytes)" + i = self.offset + if i < min(len(self.expected), len(self.got)): + return (f"byte {i} differs: RPM got {self.expected[i]:02x}, " + f"this time {self.got[i]:02x} ({len(self.got):,} " + f"bytes, RPM got {len(self.expected):,})") + return (f"{len(self.got):,} bytes where RPM got " + f"{len(self.expected):,}; the first {i:,} are the same") + + +@dataclass +class ReplayResult: + sent: int = 0 # requests sent + same: int = 0 # answers identical to RPM's + differences: list = field(default_factory=list) + stopped: str = "" # why it stopped early, if it did + + +def read_answer(link, expected, timeout, quiet, clock=time.monotonic, + on_data=None): + """The radio's answer: read until ``expected`` bytes have come and the + radio has then been quiet for ``quiet`` seconds, or until it has been + silent for ``timeout`` seconds short of that. More than ``expected`` + bytes is already not RPM's answer, so reading stops there: a radio that + keeps talking (GPS output, say) cannot hold the replay up.""" + got = bytearray() + last = clock() + while True: + data = link.read(max(1, getattr(link, "in_waiting", 0) or 1)) + now = clock() + if data: + got += data + last = now + if on_data is not None: + on_data(data) + if len(got) > expected: + return bytes(got) + continue + if now - last >= (quiet if len(got) >= expected else timeout): + return bytes(got) + + +def replay(link, plan, writer=None, timeout=3.0, quiet=0.3, + keep_going=False, max_pause=5.0, clock=time.monotonic): + """Send each request in ``plan`` (Steps) and compare the answer with + the reply RPM got. + + Where RPM got no answer, RPM's pause before its next request (up to + ``max_pause``) is kept: the radio may have needed it. Stops when the + radio does not answer, and at the first answer that differs unless + ``keep_going``. + """ + result = ReplayResult() + log = None + if writer is not None: + def log(data): + writer.add(RADIO_TO_PC, data) + try: + for i, step in enumerate(plan): + link.write(step.request) + if writer is not None: + writer.add(PC_TO_RADIO, step.request) + result.sent += 1 + wait = quiet if step.reply else max(quiet, + min(step.pause, max_pause)) + got = read_answer(link, len(step.reply), timeout, wait, clock, + log) + if got == step.reply: + result.same += 1 + continue + result.differences.append(Difference(i, step.reply, got)) + if not got: + result.stopped = f"the radio did not answer request {i + 1}" + break + if not keep_going: + result.stopped = (f"the answer to request {i + 1} is not " + f"the one RPM got") + break + except KeyboardInterrupt: + result.stopped = "stopped with Ctrl+C" + return result diff --git a/tests/test_radio.py b/tests/test_radio.py index 688a3b5..14f2f47 100644 --- a/tests/test_radio.py +++ b/tests/test_radio.py @@ -1,5 +1,5 @@ """quickprs.radio: Bluetooth port discovery, capture files, the listen-only -probe, the RPM relay and capture analysis. No radio or Bluetooth adapter +probe, the RPM relay, capture analysis and the replay of a read. No radio or Bluetooth adapter is needed: ports and links are stand-ins.""" import threading @@ -8,7 +8,9 @@ import pytest -from quickprs.radio import analyze, bluetooth, capture, probe, relay +from quickprs.radio import ( + analyze, bluetooth, capture, probe, relay, replay, +) from quickprs.radio.capture import PC_TO_RADIO, RADIO_TO_PC # Hardware IDs in the form Windows reports for a paired XG-100P @@ -59,6 +61,19 @@ def test_capture_round_trip(tmp_path): assert cap.stream(RADIO_TO_PC) == b"\xa5\x5a\x00" +def test_captures_are_never_written_over(tmp_path): + path = tmp_path / "read.jsonl" + path.write_text("an earlier capture\n") + with capture.CaptureWriter(path) as w: + w.add(PC_TO_RADIO, b"x") + assert path.read_text() == "an earlier capture\n" + assert w.path == tmp_path / "read-2.jsonl" + assert capture.read_capture(w.path).stream(PC_TO_RADIO) == b"x" + with capture.CaptureWriter(path) as w3: + pass + assert w3.path == tmp_path / "read-3.jsonl" + + def test_capture_lines_stay_whole_across_threads(tmp_path): path = tmp_path / "t.jsonl" w = capture.CaptureWriter(path) @@ -203,7 +218,7 @@ def _conversation(tmp_path): w.add(RADIO_TO_PC, b"!", t=0.03) w.add(RADIO_TO_PC, b"\x15", t=0.5) w.add(PC_TO_RADIO, b"\x02NEXT", t=0.51) - return capture.read_capture(path) + return capture.read_capture(w.path) def test_messages_join_chunks_going_one_way(tmp_path): @@ -248,6 +263,254 @@ def test_cli_analyze_transcript(tmp_path, capsys): assert "|.NEXT|" not in out and "... 2 more messages" in out +# ─── replay ────────────────────────────────────────────────────────── + +def _read_session(tmp_path, name="read.jsonl"): + """RPM reading a radio: a hello, a request the radio does not answer + (RPM then waits half a second), the personality in three parts (the + last after a pause, so the answer is two messages) and a goodbye.""" + prs = _blank_bytes() + third = len(prs) // 3 + with capture.CaptureWriter(tmp_path / name, note="RPM extract") as w: + w.event("pc dtr=1 rts=0", t=0.0) + w.add(RADIO_TO_PC, b"\x00", t=0.0) # before the first request + w.add(PC_TO_RADIO, b"\x02HELLO", t=0.1) + w.add(RADIO_TO_PC, b"\x06XG-100P", t=0.12) + w.add(PC_TO_RADIO, b"\x02MODE", t=0.2) + w.add(PC_TO_RADIO, b"\x02READ", t=0.7) + w.add(RADIO_TO_PC, prs[:third], t=0.72) + w.add(RADIO_TO_PC, prs[third:2 * third], t=0.73) + w.add(RADIO_TO_PC, prs[2 * third:], t=0.85) + w.add(PC_TO_RADIO, b"\x02BYE", t=0.9) + w.add(RADIO_TO_PC, b"\x06", t=0.91) + return capture.read_capture(w.path), prs + + +class FakeRadio: + """Answers each request with the parts scripted for it; a number in + the script is a pause. Time is a fake clock that a read moves on by + the port's timeout when nothing has come.""" + + def __init__(self, answers, timeout=0.2): + self.answers = answers + self.pending = [] + self.written = [] # (time, request) + self.now = 0.0 + self.timeout = timeout + + def clock(self): + return self.now + + @property + def in_waiting(self): + if self.pending and isinstance(self.pending[0], bytes): + return len(self.pending[0]) + return 0 + + def write(self, data): + self.written.append((self.now, bytes(data))) + self.pending.extend(self.answers.get(bytes(data), [])) + + def read(self, n): + if self.pending: + part = self.pending.pop(0) + if isinstance(part, bytes): + self.now += 0.001 + return part + self.now += part + return b"" + self.now += self.timeout + return b"" + + +def _answers(prs, read=None): + return {b"\x02HELLO": [b"\x06XG-100P"], + b"\x02READ": read if read is not None else [prs[:500], + prs[500:]], + b"\x02BYE": [b"\x06"]} + + +def test_steps_pair_requests_with_answers(tmp_path): + cap, prs = _read_session(tmp_path) + plan = replay.steps(cap) + assert [(s.request, s.reply) for s in plan] == [ + (b"\x02HELLO", b"\x06XG-100P"), + (b"\x02MODE", b""), + (b"\x02READ", prs), + (b"\x02BYE", b"\x06"), + ] + assert [s.pause for s in plan] == [0.1, 0.5, 0.2, 0.0] + + +def test_only_reads_are_replayed(tmp_path): + cap, prs = _read_session(tmp_path) + assert replay.why_refused(cap) is None + with capture.CaptureWriter(tmp_path / "w.jsonl") as w: + w.add(PC_TO_RADIO, b"\x02WRITE" + prs) + w.add(RADIO_TO_PC, b"\x06") + assert "it is a write" in replay.why_refused( + capture.read_capture(w.path)) + assert "hold no personality" in replay.why_refused( + _conversation(tmp_path)) + with capture.CaptureWriter(tmp_path / "big.jsonl") as w: + w.add(PC_TO_RADIO, b"\x00" * (len(prs) + 1)) + w.add(RADIO_TO_PC, prs) + assert "sent more than the radio answered" in replay.why_refused( + capture.read_capture(w.path)) + with capture.CaptureWriter(tmp_path / "quiet.jsonl") as w: + w.add(RADIO_TO_PC, prs) + assert "sent nothing" in replay.why_refused( + capture.read_capture(w.path)) + + +def test_capture_lines(tmp_path): + cap, _ = _read_session(tmp_path) + assert replay.capture_lines(cap) == (True, False) + assert replay.capture_lines(_conversation(tmp_path)) is None + + +def test_replay_gets_the_same_answers(tmp_path): + cap, prs = _read_session(tmp_path) + radio = FakeRadio(_answers(prs)) + with capture.CaptureWriter(tmp_path / "again.jsonl") as w: + result = replay.replay(radio, replay.steps(cap), writer=w, + clock=radio.clock) + assert (result.sent, result.same, result.differences, + result.stopped) == (4, 4, [], "") + assert [r for _, r in radio.written] == [ + b"\x02HELLO", b"\x02MODE", b"\x02READ", b"\x02BYE"] + # RPM waited half a second after the request the radio did not answer + assert radio.written[2][0] - radio.written[1][0] >= 0.5 + again = capture.read_capture(w.path) + assert again.stream(PC_TO_RADIO) == cap.stream(PC_TO_RADIO) + assert again.stream(RADIO_TO_PC) == cap.stream(RADIO_TO_PC)[1:] + + +def test_replay_waits_for_a_slow_answer(tmp_path): + cap, prs = _read_session(tmp_path) + radio = FakeRadio(_answers(prs, read=[prs[:500], 1.0, prs[500:]])) + result = replay.replay(radio, replay.steps(cap), clock=radio.clock) + assert (result.sent, result.same) == (4, 4) + + +def test_replay_stops_at_an_answer_that_differs(tmp_path): + cap, prs = _read_session(tmp_path) + changed = prs[:100] + bytes([prs[100] ^ 0xFF]) + prs[101:] + radio = FakeRadio(_answers(prs, read=[changed])) + result = replay.replay(radio, replay.steps(cap), clock=radio.clock) + assert (result.sent, result.same) == (3, 2) + assert "request 3 is not the one RPM got" in result.stopped + assert [r for _, r in radio.written][-1] == b"\x02READ" + (d,) = result.differences + assert (d.step, d.offset) == (2, 100) + assert d.describe().startswith( + f"byte 100 differs: RPM got {prs[100]:02x}, this time " + f"{changed[100]:02x}") + radio = FakeRadio(_answers(prs, read=[changed])) + result = replay.replay(radio, replay.steps(cap), keep_going=True, + clock=radio.clock) + assert (result.sent, result.same, result.stopped) == (4, 3, "") + + +def test_replay_stops_when_the_radio_does_not_answer(tmp_path): + cap, prs = _read_session(tmp_path) + for keep_going in (False, True): + radio = FakeRadio({}) + result = replay.replay(radio, replay.steps(cap), + keep_going=keep_going, clock=radio.clock) + assert (result.sent, result.same) == (1, 0) + assert result.stopped == "the radio did not answer request 1" + assert result.differences[0].describe() == ( + "no answer (RPM got 8 bytes)") + radio = FakeRadio({b"\x02HELLO": [b"\x06XG"]}) + result = replay.replay(radio, replay.steps(cap), clock=radio.clock) + assert result.differences[0].describe() == ( + "3 bytes where RPM got 8; the first 3 are the same") + + +def test_replay_does_not_wait_for_a_radio_that_keeps_talking(tmp_path): + cap, prs = _read_session(tmp_path) + nmea = b"$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,,*47\r\n" + radio = FakeRadio({b"\x02HELLO": [nmea] * 1000}) + result = replay.replay(radio, replay.steps(cap), keep_going=True, + clock=radio.clock) + # the answer was cut as soon as it was longer than RPM's, and so was + # every answer after it while the radio went on talking + assert result.same == 0 + assert len(radio.pending) > 900 + + +class _Opener: + """Stands in for open_serial: hands out a FakeRadio, remembers how + the port was opened.""" + + def __init__(self, radio): + self.radio = radio + self.calls = [] + + def __call__(self, port, **kw): + self.calls.append((port, kw)) + self.radio.close = lambda: None + return self.radio + + +class _RealTimeRadio(FakeRadio): + def read(self, n): + if not self.pending or not isinstance(self.pending[0], bytes): + time.sleep(0.001) + return super().read(n) + + +def test_cli_replay(tmp_path, capsys, monkeypatch): + from quickprs.cli import run_cli + from quickprs.radio import commands + monkeypatch.chdir(tmp_path) # the default --log lands here + cap, prs = _read_session(tmp_path) + opener = _Opener(_RealTimeRadio(_answers(prs))) + monkeypatch.setattr(commands, "open_serial", opener) + log = tmp_path / "again.jsonl" + assert commands.cmd_radio_replay(str(tmp_path / "read.jsonl"), + port="COM99", log=str(log), + quiet=0.01) == 0 + assert opener.calls == [("COM99", {"dtr": True, "rts": False})] + out = capsys.readouterr().out + assert "Sent 4 of 4 requests; 4 answers were the ones RPM got." in out + assert capture.read_capture(log).stream(RADIO_TO_PC) == ( + b"\x06XG-100P" + prs + b"\x06") + + # only the first two requests + opener.radio = _RealTimeRadio(_answers(prs)) + assert commands.cmd_radio_replay(str(tmp_path / "read.jsonl"), + port="COM99", log=str(log), + requests=2, quiet=0.01) == 0 + assert [r for _, r in opener.radio.written] == [b"\x02HELLO", + b"\x02MODE"] + assert "Sent 2 of 2 requests" in capsys.readouterr().out + + # an answer that differs + changed = prs[:7] + b"?" + prs[8:] + opener.radio = _RealTimeRadio(_answers(prs, read=[changed])) + assert commands.cmd_radio_replay(str(tmp_path / "read.jsonl"), + port="COM99", log=str(log), + quiet=0.01) == 1 + out = capsys.readouterr().out + assert "request 3: byte 7 differs" in out + assert "Stopped: the answer to request 3 is not the one RPM got." in out + + # a write is refused before any port is opened + opener.calls.clear() + assert commands.cmd_radio_replay(str(tmp_path / "read.jsonl"), + port="COM99", requests=0) == 1 + assert "at least 1" in capsys.readouterr().err + with capture.CaptureWriter(tmp_path / "w.jsonl") as w: + w.add(PC_TO_RADIO, b"\x02WRITE" + prs) + w.add(RADIO_TO_PC, b"\x06") + assert run_cli(["radio", "replay", str(w.path), "--port", + "COM99"]) == 1 + assert "it is a write" in capsys.readouterr().err + assert opener.calls == [] + + def test_cli_analyze_extracts(tmp_path, capsys): from quickprs.cli import run_cli prs = _blank_bytes() diff --git a/tests/test_radio_hci.py b/tests/test_radio_hci.py index 120d698..fccd5f9 100644 --- a/tests/test_radio_hci.py +++ b/tests/test_radio_hci.py @@ -212,6 +212,20 @@ def test_sniff_command_from_a_file(tmp_path, capsys): assert "radio to RPM: 300 bytes" in capsys.readouterr().out +def test_sniff_never_writes_over_a_capture(tmp_path, capsys): + from quickprs.radio.commands import cmd_radio_sniff + trace = tmp_path / "trace.pcap" + trace.write_bytes(pcap(session()[1])) + log = tmp_path / "read.jsonl" + log.write_text("an earlier capture\n") + assert cmd_radio_sniff(pcap=str(trace), log=str(log), + address=RADIO) == 0 + assert log.read_text() == "an earlier capture\n" + assert read_capture(tmp_path / "read-2.jsonl").stream("pc>radio") == ( + b"hello") + assert "read-2.jsonl" in capsys.readouterr().out + + def test_sniff_command_live(tmp_path): """The sniffer serves the trace on TCP and closes when it stops.""" from quickprs.radio.commands import cmd_radio_sniff @@ -305,3 +319,58 @@ def test_trace_report_says_why_nothing_was_found(records, linktype, words): list(hci.serial_chunks(hci.read_packets(io.BytesIO( pcap(records, linktype=linktype))), stats=stats)) assert words in "\n".join(hci.describe(stats)) + + +# ── modem lines ─────────────────────────────────────────────────────── + +def msc(signals, command=True, dlci=2): + """An RFCOMM modem status message for the control channel.""" + return bytes([hci.MSC_COMMAND if command else 0xE1, (2 << 1) | 1, + (dlci << 2) | 0b11, signals]) + + +def control(cid, payload, cr): + return l2cap(cid, rfcomm(0, hci.RFCOMM_UIH, payload, cr=cr)) + + +def test_modem_lines_from_the_control_channel(tmp_path): + """Each side's modem status command becomes a line event; the answers + that echo them are left out.""" + _, records = session() + records = records[:5] + [ + # the PC: DTR on, RTS off + (100.45, SENT, acl(H, control(0x0041, msc(0x05), cr=1))), + (100.46, RECV, acl(H, control(0x0040, msc(0x05, command=False), + cr=0))), + # the radio: CTS and RI on + (100.47, RECV, acl(H, control(0x0040, msc(0x49), cr=0))), + ] + records[5:] + out = chunks(records, address=RADIO) + assert [(d, x) for d, x in out if isinstance(x, str)] == [ + ("pc>radio", "pc dtr=1 rts=0"), + ("radio>pc", "radio dsr=0 cts=1 ri=1 dcd=0"), + ] + assert b"".join(x for d, x in out if d == "pc>radio" + and isinstance(x, bytes)) == b"hello" + + from quickprs.radio.commands import cmd_radio_sniff + trace = tmp_path / "trace.pcap" + trace.write_bytes(pcap(records)) + log = tmp_path / "read.jsonl" + assert cmd_radio_sniff(pcap=str(trace), log=str(log), + address=RADIO) == 0 + assert read_capture(log).events == [ + (0.45, "pc dtr=1 rts=0"), (0.47, "radio dsr=0 cts=1 ri=1 dcd=0")] + + +def test_modem_lines_mid_session(): + """Without the connection setup, the control channel counts once a + data frame has shown which channel RFCOMM is on.""" + records = [ + (1.0, SENT, acl(H, control(0x0041, msc(0x0D), cr=1))), + (1.1, SENT, acl(H, l2cap(0x0041, rfcomm( + 2, hci.RFCOMM_UIH, b"hi", pf=True, credits=1)))), + (1.2, SENT, acl(H, control(0x0041, msc(0x01), cr=1))), + ] + assert chunks(records) == [("pc>radio", b"hi"), + ("pc>radio", "pc dtr=0 rts=0")]