From eca9084ed2ea477dd47e520b560495240132582f Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:04:08 -0700 Subject: [PATCH 1/3] radio sniff: traces without directions; say what the trace held Which pcap link type Microsoft's Bluetooth Virtual Sniffer writes is not documented. Without a direction header (link type 187) the decoder now takes directions from the L2CAP connection setup (the side asking for the RFCOMM channel is the PC) or, without it, from RFCOMM's command/response bit, and a channel the radio opened is handled too. sniff ends with a report of what the trace held (packets per link type, ACL data, RFCOMM frames, serial channels) and, when it found no serial data, the likely reason, so a test run shows whether the setup works before a real session. --- quickprs/radio/commands.py | 13 ++-- quickprs/radio/hci.py | 141 ++++++++++++++++++++++++++++--------- tests/test_radio_hci.py | 74 +++++++++++++++++++ 3 files changed, 190 insertions(+), 38 deletions(-) diff --git a/quickprs/radio/commands.py b/quickprs/radio/commands.py index 1d5f1b8..e472c25 100644 --- a/quickprs/radio/commands.py +++ b/quickprs/radio/commands.py @@ -161,7 +161,8 @@ def cmd_radio_sniff(host="127.0.0.1", port=24352, log="session.jsonl", pcapng file saved from it. Only the serial (RFCOMM) bytes are kept. """ import socket - from .hci import read_packets, serial_chunks, PcapError + from .hci import (read_packets, serial_chunks, PcapError, TraceStats, + describe) if not all_links and address is None: address = _radio_address() @@ -189,10 +190,12 @@ def cmd_radio_sniff(host="127.0.0.1", port=24352, log="session.jsonl", + (f", link to {address}" if address else "") + f". Run the operation in RPM, then press Ctrl+C here.") + stats = TraceStats() with CaptureWriter(log, note=note) as writer: try: for t, direction, data in serial_chunks(read_packets(stream), - address=address): + address=address, + stats=stats): writer.add(direction, data, t=t) counts[direction] += len(data) except KeyboardInterrupt: @@ -201,12 +204,10 @@ def cmd_radio_sniff(host="127.0.0.1", port=24352, log="session.jsonl", print(f"Error: {e}", file=sys.stderr) finally: stream.close() + for line in describe(stats, address): + print(line) print(f"RPM to radio: {counts['pc>radio']:,} bytes; radio to RPM: " f"{counts['radio>pc']:,} bytes.") - if not any(counts.values()): - print("No serial data found. Was Full Packet Logging on in the " - "sniffer, and did RPM talk to the radio while it ran?", - file=sys.stderr) print(f"Analyze with: quickprs radio analyze {log}") return 0 diff --git a/quickprs/radio/hci.py b/quickprs/radio/hci.py index 0c1a87a..4f6fa4e 100644 --- a/quickprs/radio/hci.py +++ b/quickprs/radio/hci.py @@ -187,6 +187,11 @@ class RfcommFrame: pf: bool payload: bytes credits: int = 0 + cr: bool = False # command/response bit of the address + + +FRAME_NAMES = {RFCOMM_SABM: "SABM", RFCOMM_UA: "UA", RFCOMM_DM: "DM", + RFCOMM_DISC: "DISC", RFCOMM_UIH: "UIH"} def parse_rfcomm(data, credit_flow=True): @@ -222,18 +227,32 @@ def parse_rfcomm(data, credit_flow=True): if rfcomm_fcs(checked) != data[-1]: return None return RfcommFrame(dlci, frame_type, pf, bytes(data[pos:pos + length]), - credits) + credits, bool(addr & 2)) # ── HCI and L2CAP ───────────────────────────────────────────────────── +@dataclass +class TraceStats: + """What a trace held, so a run that finds no serial data says why.""" + packets: int = 0 + linktypes: dict = field(default_factory=dict) # link type -> count + acl_packets: int = 0 + rfcomm_frames: dict = field(default_factory=dict) # frame name -> count + dlcis: set = field(default_factory=set) # data channels seen + serial_bytes: dict = field( + default_factory=lambda: {SENT: 0, RECEIVED: 0}) + + @dataclass class _Link: """One ACL connection (an HCI handle).""" address: str = "" - partial: dict = field(default_factory=dict) # direction -> bytes - rfcomm_cids: dict = field(default_factory=dict) # direction -> CID - pending: dict = field(default_factory=dict) # (dir, id) -> SCID + partial: dict = field(default_factory=dict) # direction -> bytes + cid_dirs: dict = field(default_factory=dict) # CID -> direction of the + # packets sent to it + learned: dict = field(default_factory=dict) # direction -> CID + pending: dict = field(default_factory=dict) # ident -> (dir, SCID) def format_address(raw6): @@ -244,16 +263,23 @@ def format_address(raw6): class SerialFromHci: """Turn HCI packets into the serial data of RFCOMM channels. - feed() takes one H4 packet with its direction and returns the serial - chunks it completes, as (direction, bytes). When ``address`` is given, - only the link to that device counts (once HCI has said which handle - that is; a trace started after the connection never says, and then - every link's RFCOMM data counts). + feed() takes one H4 packet with its direction (None when the trace has + no direction header) and returns the serial chunks it completes, as + (direction, bytes). When ``address`` is given, only the link to that + device counts (once HCI has said which handle that is; a trace started + after the connection never says, and then every link's RFCOMM data + counts). + + Where a trace has no directions, the L2CAP connection setup gives + them (the side that asked for the RFCOMM channel is taken to be the + PC, which opens it), and without that, RFCOMM's command/response bit + does: the PC is the initiator, whose UIH frames carry C/R = 1. """ - def __init__(self, address=None): + def __init__(self, address=None, stats=None): self.address = address.upper() if address else None self.links = {} + self.stats = stats if stats is not None else TraceStats() def _link(self, handle): return self.links.setdefault(handle, _Link()) @@ -267,6 +293,7 @@ def feed(self, direction, packet): return [] if kind != H4_ACL or len(packet) < 5: return [] + self.stats.acl_packets += 1 head, length = struct.unpack_from("> 12) & 0x3 data = packet[5:5 + length] @@ -309,18 +336,31 @@ def _l2cap(self, link, direction, cid, payload): return [] if cid < 0x0040: return [] - known = link.rfcomm_cids.get(direction) - if known is not None and cid != known: - return [] + if cid in link.cid_dirs: # from the connection setup + direction = link.cid_dirs[cid] + elif link.cid_dirs: + return [] # another channel than RFCOMM's frame = parse_rfcomm(payload) if frame is None: return [] - if known is None: - # no connection setup seen: a valid RFCOMM frame names the CID - link.rfcomm_cids[direction] = cid - if frame.frame_type == RFCOMM_UIH and frame.dlci and frame.payload: - return [(direction, frame.payload)] - return [] + 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: + return [] + if direction is None: + direction = SENT if frame.cr else RECEIVED + if cid not in link.cid_dirs: + # no connection setup seen: the first data frame each way + # names that way's CID + known = link.learned.setdefault(direction, cid) + if known != cid: + return [] + self.stats.dlcis.add(frame.dlci) + if not frame.payload: + return [] + self.stats.serial_bytes[direction] += len(frame.payload) + return [(direction, frame.payload)] def _signaling(self, link, direction, data): pos = 0 @@ -331,41 +371,78 @@ def _signaling(self, link, direction, data): if code == L2CAP_CONN_REQ and len(body) >= 4: psm, scid = struct.unpack_from("= 8: dcid, scid, result = struct.unpack_from("I", data)[0] return (RECEIVED if flag & 1 else SENT), data[4:] if linktype == LINKTYPE_H4: - return RECEIVED, data + return None, data return None -def serial_chunks(packets, address=None): +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.""" - decoder = SerialFromHci(address) + chunk in an iterable of (timestamp, linktype, data) pcap records. + ``stats``, a TraceStats, is filled in as the trace is read.""" + decoder = SerialFromHci(address, stats) + stats = decoder.stats t0 = None for ts, linktype, data in packets: if t0 is None: t0 = ts + stats.packets += 1 + stats.linktypes[linktype] = stats.linktypes.get(linktype, 0) + 1 split = h4_with_direction(linktype, data) if split is None: continue for direction, chunk in decoder.feed(*split): yield round(ts - t0, 6), direction, chunk + + +def describe(stats, address=None): + """Lines saying what a trace held, and why when it held no serial + data.""" + kinds = {LINKTYPE_H4_WITH_PHDR: "HCI H4 with direction", + LINKTYPE_H4: "HCI H4"} + types = ", ".join(f"{n:,} {kinds.get(t, f'link type {t} (not read)')}" + for t, n in sorted(stats.linktypes.items())) + lines = [f"Trace: {stats.packets:,} packets ({types or 'none'}), " + f"{stats.acl_packets:,} ACL data."] + if stats.rfcomm_frames: + frames = ", ".join(f"{n:,} {name}" for name, n in + sorted(stats.rfcomm_frames.items())) + channels = ", ".join(str(d >> 1) for d in sorted(stats.dlcis)) + lines.append(f"RFCOMM frames: {frames}" + + (f"; serial channel(s) {channels}" if channels + else "")) + elif not stats.packets: + lines.append("The sniffer sent nothing: is btvs.exe -Mode " + "Wireshark running?") + elif not stats.acl_packets: + lines.append("No Bluetooth data packets: did anything talk to the " + "radio while this ran?") + else: + lines.append("No RFCOMM frames" + + (f" on the link to {address}" if address else "") + + ": was Full Packet Logging on in the sniffer, and " + "did RPM (or quickprs radio probe) connect to the " + "radio while this ran?") + return lines diff --git a/tests/test_radio_hci.py b/tests/test_radio_hci.py index 1acb1fe..120d698 100644 --- a/tests/test_radio_hci.py +++ b/tests/test_radio_hci.py @@ -231,3 +231,77 @@ def serve(): log = tmp_path / "live.jsonl" assert cmd_radio_sniff(port=port, log=str(log), address=RADIO) == 0 assert read_capture(log).stream("radio>pc") == reply + + +# ── traces without directions, and the trace report ────────────────── + +def pcap_h4(records): + """The same records as link type 187: no direction header.""" + out = struct.pack("radio", b"hello"), + ("radio>pc", reply)] + + +def test_no_direction_header_mid_session(): + """Without the setup, RFCOMM's C/R bit says who sent a frame: the PC + opened the channel, and its UIH frames carry C/R = 1.""" + reply, records = session() + assert chunks_h4(records[5:]) == [("pc>radio", b"hello"), + ("radio>pc", reply)] + + +def test_radio_opened_channel_with_directions(): + """When the radio asks for the channel, the CIDs swap roles.""" + records = [ + (1.0, RECV, acl(H, conn_req(9, 0x0070))), + (1.1, SENT, acl(H, conn_rsp(9, 0x0071, 0x0070))), + (1.2, SENT, acl(H, l2cap(0x0070, rfcomm( + 2, hci.RFCOMM_UIH, b"to radio", cr=0)))), + (1.3, RECV, acl(H, l2cap(0x0071, rfcomm( + 2, hci.RFCOMM_UIH, b"to pc")))), + ] + assert chunks(records) == [("pc>radio", b"to radio"), + ("radio>pc", b"to pc")] + + +def test_trace_report(): + reply, records = session() + stats = hci.TraceStats() + list(hci.serial_chunks(hci.read_packets(io.BytesIO(pcap(records))), + stats=stats)) + assert stats.packets == len(records) + assert stats.serial_bytes == {"pc>radio": 5, "radio>pc": len(reply)} + assert stats.rfcomm_frames == {"SABM": 1, "UA": 1, "UIH": 3} + lines = hci.describe(stats) + assert "9 packets (9 HCI H4 with direction)" in lines[0] + assert "serial channel(s) 1" in lines[1] + + +@pytest.mark.parametrize("records, linktype, words", [ + ([], hci.LINKTYPE_H4_WITH_PHDR, "is btvs.exe"), + ([(1.0, RECV, conn_complete(H, RADIO))], hci.LINKTYPE_H4_WITH_PHDR, + "No Bluetooth data packets"), + ([(1.0, SENT, acl(H, l2cap(0x0050, b"\x01\x02\x03\x04\x05")))], + hci.LINKTYPE_H4_WITH_PHDR, "Full Packet Logging"), + ([(1.0, SENT, b"\x02\x0b\x20\x00\x00")], 1, "link type 1 (not read)"), +]) +def test_trace_report_says_why_nothing_was_found(records, linktype, words): + stats = hci.TraceStats() + list(hci.serial_chunks(hci.read_packets(io.BytesIO( + pcap(records, linktype=linktype))), stats=stats)) + assert words in "\n".join(hci.describe(stats)) From d6c79d382c92d22e50c7907cbb129df51c49bdf5 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:05:20 -0700 Subject: [PATCH 2/3] Ignore local/; Bluetooth notes: check the setup with a probe CONTRIBUTING said local/ is gitignored, and it was not. The Bluetooth notes describe sniff's report and a setup check that needs no RPM: open the radio's port with radio probe while sniff runs. --- .gitignore | 3 +++ CHANGELOG.md | 2 +- docs/bluetooth.md | 17 ++++++++++++++++- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 82d1138..0b5be1d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ # Build artifacts dist/ build/ + +# Developer scratch files (see CONTRIBUTING.md) +local/ *.spec *.exe diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d06133..40c6240 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ All notable changes to QuickPRS will be documented in this file. ## [1.3.0] - 2026-10-28 ### 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. com0com, which the relay needs, cannot load while Windows 11's Memory Integrity is on +- `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 - `--skip-encrypted` for `import-rr`, `auto-setup` and `import-paste`: leave out talkgroups RadioReference lists as fully encrypted ### Fixed diff --git a/docs/bluetooth.md b/docs/bluetooth.md index b4ddb06..73fe4bf 100644 --- a/docs/bluetooth.md +++ b/docs/bluetooth.md @@ -77,10 +77,25 @@ flowchart LR 4. Turn the radio on, and in RPM extract it over its Bluetooth COM port. 5. Press Ctrl+C in QuickPRS, then close BTVS. +When it stops, `sniff` reports what the trace held (packets, Bluetooth +data packets, RFCOMM frames and serial channels) and, if it found no serial +data, the likely reason. + +To check the setup before a real session, run steps 2 and 3, then with the +radio on open its port for a few seconds from another console: + +```bash +quickprs radio probe --port COM6 --seconds 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 -trace saved from Wireshark instead. +trace saved from Wireshark instead. Traces with or without a direction +header (pcap link types 201 and 187) both work. ### Through a virtual null-modem pair From 8f00bf8ff9409e14794150ae6450e521d8eecea3 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:12:12 -0700 Subject: [PATCH 3/3] radio analyze: messages and --transcript Chunks going the same way less than 50 ms apart are one message, since a serial read returns whatever has arrived. The report counts messages and lists their common sizes and first bytes; --transcript N lists the first N messages with time, direction, length and first bytes. --- CHANGELOG.md | 1 + docs/bluetooth.md | 12 ++++++-- quickprs/cli.py | 8 +++++- quickprs/radio/analyze.py | 52 ++++++++++++++++++++++++++++++++++- quickprs/radio/commands.py | 8 +++++- tests/test_radio.py | 56 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 131 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40c6240..4ade82c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ 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 - `--skip-encrypted` for `import-rr`, `auto-setup` and `import-paste`: leave out talkgroups RadioReference lists as fully encrypted ### Fixed diff --git a/docs/bluetooth.md b/docs/bluetooth.md index 73fe4bf..9548f00 100644 --- a/docs/bluetooth.md +++ b/docs/bluetooth.md @@ -127,12 +127,18 @@ Memory Integrity off. ```bash quickprs radio analyze read.jsonl +quickprs radio analyze read.jsonl --transcript 60 quickprs radio analyze read.jsonl --extract radio.PRS ``` -`analyze` counts bytes in each direction, lists readable strings and the -MFC class names it finds, and `--extract` writes out a personality found in -the radio's replies. Protocol bytes after the personality can end up in that +`analyze` counts bytes and messages in each direction, lists the common +message sizes and first bytes, readable strings and the MFC class names it +finds. A message is a run of chunks going the same way with less than +50 ms between them: a serial read returns whatever has arrived, so one +message often comes in several chunks. `--transcript N` lists the first N +messages (40 without a number) with their time, direction, length and first +bytes, which is where a protocol's framing usually shows first. +`--extract` writes out a personality found in the radio's replies. Protocol bytes after the personality can end up in that file, so treat it as something to compare with the .PRS RPM saved for the same session, not as a finished file. diff --git a/quickprs/cli.py b/quickprs/cli.py index e21d2e9..fa105ff 100644 --- a/quickprs/cli.py +++ b/quickprs/cli.py @@ -4425,6 +4425,7 @@ def build_parser(): " quickprs radio sniff --log read.jsonl\n" " quickprs radio relay --pc-port COM21 --radio-port COM6 " "--log read.jsonl\n" + " quickprs radio analyze read.jsonl --transcript 60\n" " quickprs radio analyze read.jsonl --extract radio.PRS") radio_sub = p_radio.add_subparsers(dest="radio_cmd") p_rscan = radio_sub.add_parser( @@ -4476,6 +4477,10 @@ def build_parser(): p_ranalyze = radio_sub.add_parser( "analyze", help="Summarise a capture file") p_ranalyze.add_argument("capture", help="Capture (.jsonl) file") + p_ranalyze.add_argument("--transcript", type=int, nargs="?", + const=40, default=None, metavar="N", + help="Show the first N messages of the " + "conversation (default 40)") p_ranalyze.add_argument("--extract", default=None, help="Write a personality archive found in the " "radio's replies to this .PRS path") @@ -5769,7 +5774,8 @@ def run_cli(args=None): all_links=parsed.all_links, note=parsed.note) if parsed.radio_cmd == "analyze": return radio_commands.cmd_radio_analyze( - parsed.capture, extract=parsed.extract) + parsed.capture, extract=parsed.extract, + transcript=parsed.transcript) subcommand_parsers["radio"].print_help() return 1 elif parsed.command == "import-csv": diff --git a/quickprs/radio/analyze.py b/quickprs/radio/analyze.py index f547513..634be4f 100644 --- a/quickprs/radio/analyze.py +++ b/quickprs/radio/analyze.py @@ -77,6 +77,48 @@ def summarize(capture, opener_len=2): return out +@dataclass +class Message: + t: float + direction: str + data: bytes + + +def messages(capture, gap=0.05): + """The conversation as messages: consecutive chunks going the same way + with less than ``gap`` seconds between them are one message (a serial + read returns whatever has arrived, so one message often comes in + several chunks).""" + out = [] + last_t = None + for c in capture.chunks: + if (out and out[-1].direction == c.direction + and last_t is not None and c.t - last_t < gap): + out[-1].data.extend(c.data) + else: + out.append(Message(c.t, c.direction, bytearray(c.data))) + last_t = c.t + for m in out: + m.data = bytes(m.data) + return out + + +def transcript(capture, limit=40, width=32, gap=0.05): + """The first ``limit`` messages, one line each: time, direction, + length, and the first ``width`` bytes in hex and as text.""" + lines = [] + msgs = messages(capture, gap) + for m in msgs[:limit]: + head = m.data[:width] + text = "".join(chr(b) if 32 <= b < 127 else "." for b in head) + more = " ..." if len(m.data) > width else "" + lines.append(f"{m.t:9.3f} {m.direction:8s} {len(m.data):6,} B " + f"{head.hex(' ')}{more} |{text}|") + if len(msgs) > limit: + lines.append(f"... {len(msgs) - limit} more messages") + return lines + + def extract_personality(data): """Bytes of a .PRS archive found in ``data``, or None. @@ -110,12 +152,20 @@ def report(capture, top=8): span = capture.chunks[-1].t - capture.chunks[0].t lines.append(f"{len(capture.chunks)} chunks over {span:.1f} s, " f"{len(capture.events)} line events") + msgs = messages(capture) for direction, s in summarize(capture).items(): lines.append("") + mine = [m for m in msgs if m.direction == direction] lines.append(f"{direction}: {s.total_bytes:,} bytes in " - f"{s.chunks} chunks") + f"{s.chunks} chunks, {len(mine)} messages") if not s.chunks: continue + sizes = Counter(len(m.data) for m in mine) + openers = Counter(m.data[:2].hex(" ") for m in mine) + lines.append(" common message sizes: " + ", ".join( + f"{size} B x{n}" for size, n in sizes.most_common(top))) + lines.append(" common message openers: " + ", ".join( + f"[{k}] x{n}" for k, n in openers.most_common(top))) sizes = ", ".join(f"{size} B x{n}" for size, n in s.chunk_sizes.most_common(top)) lines.append(f" common chunk sizes: {sizes}") diff --git a/quickprs/radio/commands.py b/quickprs/radio/commands.py index e472c25..660fd09 100644 --- a/quickprs/radio/commands.py +++ b/quickprs/radio/commands.py @@ -212,7 +212,7 @@ def cmd_radio_sniff(host="127.0.0.1", port=24352, log="session.jsonl", return 0 -def cmd_radio_analyze(capture_path, extract=None): +def cmd_radio_analyze(capture_path, extract=None, transcript=None): try: cap = read_capture(capture_path) except (OSError, ValueError) as e: @@ -220,6 +220,12 @@ def cmd_radio_analyze(capture_path, extract=None): return 1 for line in report(cap): print(line) + if transcript: + from .analyze import transcript as conversation + print() + print("Conversation (consecutive chunks one way are one message):") + for line in conversation(cap, limit=transcript): + print(line) if extract: data = extract_personality(cap.stream(RADIO_TO_PC)) if data is None: diff --git a/tests/test_radio.py b/tests/test_radio.py index 5f86033..688a3b5 100644 --- a/tests/test_radio.py +++ b/tests/test_radio.py @@ -192,6 +192,62 @@ def test_report_mentions_archive_and_text(tmp_path): assert "'READ PERSONALITY'" in text +def _conversation(tmp_path): + """A request in two chunks, a reply in two chunks, a late chunk the + radio sends on its own, and the next request.""" + path = tmp_path / "talk.jsonl" + with capture.CaptureWriter(path, note="talk") as w: + w.add(PC_TO_RADIO, b"\x02RE", t=0.0) + w.add(PC_TO_RADIO, b"AD", t=0.01) + w.add(RADIO_TO_PC, b"\x06ok", t=0.02) + 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) + + +def test_messages_join_chunks_going_one_way(tmp_path): + msgs = analyze.messages(_conversation(tmp_path)) + assert [(m.direction, m.data) for m in msgs] == [ + (PC_TO_RADIO, b"\x02READ"), + (RADIO_TO_PC, b"\x06ok!"), + (RADIO_TO_PC, b"\x15"), # after a pause: its own message + (PC_TO_RADIO, b"\x02NEXT"), + ] + assert [m.t for m in msgs] == [0.0, 0.02, 0.5, 0.51] + + +def test_transcript_lines(tmp_path): + lines = analyze.transcript(_conversation(tmp_path), limit=3) + assert len(lines) == 4 + assert lines[0].split() == ["0.000", PC_TO_RADIO, "5", "B", + "02", "52", "45", "41", "44", "|.READ|"] + assert lines[2].split()[1:3] == [RADIO_TO_PC, "1"] + assert lines[3] == "... 1 more messages" + long = analyze.transcript(_conversation(tmp_path), width=2) + assert "02 52 ..." in long[0] and "|.R|" in long[0] + assert len(long) == 4 # no "more" line when all fit + + +def test_report_counts_messages(tmp_path): + text = "\n".join(analyze.report(_conversation(tmp_path))) + assert f"{PC_TO_RADIO}: 10 bytes in 3 chunks, 2 messages" in text + assert f"{RADIO_TO_PC}: 5 bytes in 3 chunks, 2 messages" in text + assert "common message sizes: 5 B x2" in text + assert "common message openers: [06 6f] x1, [15] x1" in text + + +def test_cli_analyze_transcript(tmp_path, capsys): + from quickprs.cli import run_cli + _conversation(tmp_path) + assert run_cli(["radio", "analyze", str(tmp_path / "talk.jsonl"), + "--transcript", "2"]) == 0 + out = capsys.readouterr().out + assert "Conversation" in out + assert "|.READ|" in out and "|.ok!|" in out + assert "|.NEXT|" not in out and "... 2 more messages" in out + + def test_cli_analyze_extracts(tmp_path, capsys): from quickprs.cli import run_cli prs = _blank_bytes()