From d6113edf2982ddd1d2597bf3a677e720662d3810 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:30:24 -0700 Subject: [PATCH 01/14] v1.0.3: section-index guards, receive-only NOAA channels, docs Section replacement helpers now raise instead of writing at index -1 when an expected section is missing, empty set lists are rejected, NOAA weather channels are receive-only, and make_conv_channel / make_conv_set accept tx and scan flags. README gains a RadioReference section. --- CHANGELOG.md | 14 +++++++++ README.md | 69 +++++++++++++++++++++++++++++++++++++++---- quickprs/__init__.py | 2 +- quickprs/injector.py | 26 +++++++++++++++- quickprs/templates.py | 10 ++++--- 5 files changed, 110 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 44ec2ea..8d2eab0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,20 @@ All notable changes to QuickPRS will be documented in this file. +## [1.0.3] - 2026-03-16 + +### Added +- README: Dedicated RadioReference integration section with auto-setup, paste import, and GUI wizard documentation +- README: Updated Quick Start to lead with RadioReference one-command workflow + +### Fixed +- Section replacement functions now validate section indices before writing, preventing silent data corruption if expected sections are missing +- Added empty set guards to prevent IndexError when trunk, group, or conv sets are unexpectedly empty +- NOAA weather channels now correctly set as receive-only (TX disabled) +- Interop template docstring corrected to document 156.7 Hz PL tone usage and accurate frequency ranges +- `make_conv_channel()` and `make_conv_set()` now support `tx` and `scan` flags from template data +- Updated test count to 5,300+ in README + ## [1.0.2] - 2026-03-15 ### Added diff --git a/README.md b/README.md index c040e90..27f24b8 100644 --- a/README.md +++ b/README.md @@ -8,14 +8,64 @@ Generate and edit Harris XG-100P personality (.PRS) files without Harris RPM sof > **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). QuickPRS replaces the personality *creation and editing* workflow, not the radio flashing process. +## RadioReference Integration + +QuickPRS can pull P25 trunked system data directly from [RadioReference.com](https://www.radioreference.com/) and automatically build a complete radio personality — talkgroups, frequencies, IDEN tables, control channels, and WAN config — in a single command. + +### One-Click Auto Setup (API) + +With a RadioReference premium account and API key: + +```bash +# Fetch a P25 system and build the entire personality automatically +quickprs create radio.PRS --name "PATROL" +quickprs auto-setup radio.PRS --sid 8155 --username YOUR_USER --apikey YOUR_KEY +quickprs validate radio.PRS +``` + +This single `auto-setup` command: +1. Fetches the full system from RadioReference (talkgroups, sites, frequencies) +2. Creates the trunk frequency set with all site frequencies +3. Creates the talkgroup set with smart short name generation +4. Auto-detects and creates IDEN frequency parameters (base freq, spacing, bandwidth, FDMA/TDMA) +5. Builds Enhanced Control Channel (ECC) entries from site control channels +6. Configures the P25 trunked system with WACN, SysID, and WAN settings +7. Runs validation to catch any hardware limit issues + +### Import by Pasting from the Website + +No API key? Just copy talkgroup/frequency tables from RadioReference and paste them in: + +```bash +# Paste talkgroup data from the website +quickprs import-paste radio.PRS --name PSERN --sysid 892 --tgs-file tgs.txt + +# Or import site/frequency data +quickprs import-paste radio.PRS --name PSERN --sites-file sites.txt +``` + +### GUI Import Wizard + +The GUI includes a dedicated RadioReference import wizard (File > Import Wizard) that walks you through system selection, talkgroup filtering by category and service tag, and previews everything before injection. + +### What Gets Imported + +| Data | Source | Details | +|------|--------|---------| +| Talkgroups | Categories + service tags | ID, short name, description, mode, encryption status | +| Frequencies | All sites | TX/RX pairs with LCN mapping | +| IDEN Parameters | Channel identifiers | Base freq, spacing, bandwidth, FDMA/TDMA auto-detected | +| Control Channels | Site details | Enhanced CC entries with NAC and RFSS | +| System Config | System metadata | WACN, SysID, system type, WAN configuration | + ## Features - 100% binary format decoded (49 section types, 27 option sections, 514+ fields) - Create PRS files from scratch or INI config files -- Import from RadioReference (SOAP API or paste from website) +- **RadioReference integration** — auto-setup P25 systems via SOAP API, web scraping, or paste - Import from scanner formats (CHIRP, Uniden Sentinel, SDRTrunk) - 45+ CLI commands for scripting and batch processing -- Full GUI with tree view, inline editing, drag-and-drop, RadioReference import +- 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 P25 system database (30 major US systems) - JSON export/import for human-editable radio configs @@ -34,11 +84,20 @@ Generate and edit Harris XG-100P personality (.PRS) files without Harris RPM sof - Comprehensive validation against XG-100P hardware limits - File repair and data salvage for damaged PRS files - Lossless binary roundtrip (parse and rewrite produces byte-identical output) -- 4,000+ automated tests +- 5,300+ automated tests ## Quick Start -### Build a radio config from an INI file: +### One-command P25 setup from RadioReference: + +```bash +quickprs create radio.PRS --name "PATROL" +quickprs auto-setup radio.PRS --sid 8155 --username USER --apikey KEY +quickprs inject radio.PRS conv --template interop +quickprs validate radio.PRS +``` + +### Build from an INI config file: ```bash quickprs build patrol.ini -o radio.PRS @@ -46,7 +105,7 @@ quickprs set-option radio.PRS gps.gpsMode ON quickprs validate radio.PRS ``` -### Or use individual commands: +### Build step by step: ```bash quickprs create radio.PRS --name "PATROL" diff --git a/quickprs/__init__.py b/quickprs/__init__.py index e247915..da70d26 100644 --- a/quickprs/__init__.py +++ b/quickprs/__init__.py @@ -1,3 +1,3 @@ """QuickPRS - Harris RPM Personality File Tool""" -__version__ = "1.0.2" +__version__ = "1.0.3" diff --git a/quickprs/injector.py b/quickprs/injector.py index b5388fd..94abfcc 100644 --- a/quickprs/injector.py +++ b/quickprs/injector.py @@ -144,12 +144,16 @@ def add_trunk_channels(prs, set_name, channels): def _replace_trunk_sections(prs, sets, byte1, byte2, set_byte1, set_byte2): """Replace CTrunkChannel and CTrunkSet sections with rebuilt data.""" + if not sets: + raise ValueError("No trunk sets to write") new_ch_raw = _build_trunk_channel_raw(sets, byte1, byte2) new_set_raw = _rebuild_set_section("CTrunkSet", len(sets[0].channels), set_byte1, set_byte2) ch_idx = _find_section_index(prs, "CTrunkChannel") set_idx = _find_section_index(prs, "CTrunkSet") + if ch_idx < 0 or set_idx < 0: + raise ValueError("CTrunkChannel or CTrunkSet section not found") prs.sections[ch_idx] = Section(offset=0, raw=new_ch_raw, class_name="CTrunkChannel") prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, @@ -255,6 +259,8 @@ def add_talkgroups(prs, set_name, groups): def _replace_group_sections(prs, sets, byte1, byte2, set_byte1, set_byte2): """Replace CP25Group and CP25GroupSet sections with rebuilt data.""" + if not sets: + raise ValueError("No group sets to write") new_grp_raw = _build_group_raw(sets, byte1, byte2) new_set_raw = _rebuild_set_section("CP25GroupSet", len(sets[0].groups), @@ -262,6 +268,8 @@ def _replace_group_sections(prs, sets, byte1, byte2, set_byte1, set_byte2): grp_idx = _find_section_index(prs, "CP25Group") set_idx = _find_section_index(prs, "CP25GroupSet") + if grp_idx < 0 or set_idx < 0: + raise ValueError("CP25Group or CP25GroupSet section not found") prs.sections[grp_idx] = Section(offset=0, raw=new_grp_raw, class_name="CP25Group") prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, @@ -331,6 +339,8 @@ def add_iden_set(prs, iden_set): elem_idx = _find_section_index(prs, "CDefaultIdenElem") set_idx = _find_section_index(prs, "CIdenDataSet") + if elem_idx < 0 or set_idx < 0: + raise ValueError("CDefaultIdenElem or CIdenDataSet section not found") prs.sections[elem_idx] = Section(offset=0, raw=new_elem_raw, class_name="CDefaultIdenElem") prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, @@ -677,12 +687,16 @@ def add_conv_set(prs, conv_set): def _replace_conv_sections(prs, sets, byte1, byte2, set_byte1, set_byte2): """Replace CConvChannel and CConvSet sections with rebuilt data.""" + if not sets: + raise ValueError("No conv sets to write") new_ch_raw = _build_conv_channel_raw(sets, byte1, byte2) new_set_raw = _rebuild_set_section("CConvSet", len(sets[0].channels), set_byte1, set_byte2) ch_idx = _find_section_index(prs, "CConvChannel") set_idx = _find_section_index(prs, "CConvSet") + if ch_idx < 0 or set_idx < 0: + raise ValueError("CConvChannel or CConvSet section not found") prs.sections[ch_idx] = Section(offset=0, raw=new_ch_raw, class_name="CConvChannel") prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, @@ -1225,6 +1239,8 @@ def edit_personality(prs, filename=None, saved_by=None): new_raw = build_personality_section(personality) idx = _find_section_index(prs, "CPersonality") + if idx < 0: + raise ValueError("CPersonality section not found") prs.sections[idx] = Section(offset=0, raw=new_raw, class_name="CPersonality") return True @@ -1661,6 +1677,8 @@ def set_p25_conv_nac(prs, set_name, channel_index, nac_tx=None, nac_rx=None): ch_idx = _find_section_index(prs, "CP25ConvChannel") set_idx = _find_section_index(prs, "CP25ConvSet") + if ch_idx < 0 or set_idx < 0: + raise ValueError("CP25ConvChannel or CP25ConvSet section not found") prs.sections[ch_idx] = Section(offset=0, raw=new_ch_raw, class_name="CP25ConvChannel") prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, @@ -1808,7 +1826,8 @@ def make_group_set(name, talkgroups, tx_default=False, scan_default=True): def make_conv_channel(short_name, tx_freq, rx_freq=None, - tx_tone="", rx_tone="", long_name=""): + tx_tone="", rx_tone="", long_name="", + tx=True, scan=True): """Create a ConvChannel with default flags. Args: @@ -1818,6 +1837,8 @@ def make_conv_channel(short_name, tx_freq, rx_freq=None, tx_tone: CTCSS/DCS tone string (e.g., "250.3", "" for none) rx_tone: CTCSS/DCS tone string long_name: 16-char max long name (defaults to short_name) + tx: transmit enable (False for receive-only channels like NOAA) + scan: scan enable """ if rx_freq is None: rx_freq = tx_freq @@ -1831,6 +1852,7 @@ def make_conv_channel(short_name, tx_freq, rx_freq=None, return ConvChannel( short_name=short_name, tx_freq=tx_freq, rx_freq=rx_freq, tx_tone=tx_tone, rx_tone=rx_tone, long_name=long_name, + tx=tx, scan=scan, ) @@ -1852,6 +1874,8 @@ def make_conv_set(name, channels_data): tx_tone=ch.get('tx_tone', ''), rx_tone=ch.get('rx_tone', ''), long_name=ch.get('long_name', ''), + tx=ch.get('tx', True), + scan=ch.get('scan', True), )) return ConvSet(name=name[:8], channels=channels) diff --git a/quickprs/templates.py b/quickprs/templates.py index 12f808b..8f5cb8d 100644 --- a/quickprs/templates.py +++ b/quickprs/templates.py @@ -234,6 +234,7 @@ def get_noaa_channels(): 'short_name': f'WX {i}', 'tx_freq': freq, 'long_name': f'NOAA Weather {i}', + 'tx': False, }) return channels @@ -246,13 +247,14 @@ def get_interop_channels(): - VCALL10 (155.7525 MHz, VHF calling channel) - VTAC11-14 (155.7675-156.0375 MHz, VHF tactical) - UCALL40 (453.2125 MHz, UHF calling) - - UTAC41-44 (453.4625-453.8625 MHz, UHF tactical) + - UTAC41-44 (453.4625-453.8875 MHz, UHF tactical) - 8CALL90 (866.0125 MHz, 800 MHz calling) - - 8TAC91-94 (866.5125-867.5125 MHz, 800 MHz tactical) + - 8TAC91-94 (866.5125-868.0125 MHz, 800 MHz tactical) - 7CALL50 (769.24375 MHz, 700 MHz calling) - - 7TAC51-54 (769.74375-770.74375 MHz, 700 MHz tactical) + - 7TAC51-54 (769.74375-771.24375 MHz, 700 MHz tactical) - All simplex, no CTCSS/DCS tones (interop standard). + VHF/UHF/800 channels use 156.7 Hz PL tone (NPSPAC standard). + 700 MHz channels are P25 digital (no PL tone). """ return [ # VHF Interop (NPSPAC) From 436372caaccda74a158c2b1c0ce95babc119d673 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:26:53 -0700 Subject: [PATCH 02/14] Write personalities RPM can open: follow the MFC archive format A .PRS file is an MFC CArchive. Every class and object takes the next map index, later objects of a class are written as the tag 0x8000 | class_index, and every list is preceded by its WORD count. The "separators" and "set markers" QuickPRS copied from the source file are those tags, so any edit that added or removed an object left every later tag pointing at the wrong index, and list counts were not updated. RPM's loader rejects both. `quickprs create` also produced a file whose system count, list counts and empty WAN object did not match its contents. - archive.py reads a personality into an object tree that keeps every byte, and writes it back with headers, tags, counts and schemas regenerated. All 36 RPM-saved test files read and re-serialize byte for byte; the PAWSOVERMAWS tags match the computed indices exactly (CTrunkSet 104 ... CDefaultIdenElem 907). - The injector's set, system, WAN and ECC edits go through the tree; first-of-kind sets, emptied lists and new systems of every type now produce consistent files. - create_blank_prs builds a real document. - write_prs rewrites stale tags and counts before saving and refuses to save an edit that broke a readable file. - validate reports stale tags and counts as errors; repair fixes them. - Parsers no longer compare against PAWSOVERMAWS tag values; systems are listed by the type byte in front of each config, so tagged systems after another class's header are no longer mislabelled. - FF FF inside talkgroup, channel and IDEN data no longer splits the list that holds it (a talkgroup ID of 65535 used to truncate it). - The GUI no longer crashes on start (get_recent_files argument). --- quickprs/archive.py | 878 +++++++++++++++++++++++++++++++ quickprs/builder.py | 94 ++-- quickprs/cli.py | 10 +- quickprs/gui/app.py | 2 +- quickprs/gui/personality_view.py | 51 +- quickprs/injector.py | 699 ++++++++++-------------- quickprs/json_io.py | 34 +- quickprs/prs_parser.py | 52 +- quickprs/prs_writer.py | 46 +- quickprs/record_types.py | 187 +++++-- quickprs/repair.py | 51 +- quickprs/reports.py | 47 +- quickprs/validation.py | 59 ++- tests/test_archive.py | 232 ++++++++ tests/test_builder.py | 20 +- tests/test_injection.py | 97 ++-- tests/test_prs_writer.py | 48 +- tests/test_repair.py | 10 +- tests/test_validation.py | 47 +- 19 files changed, 1953 insertions(+), 711 deletions(-) create mode 100644 quickprs/archive.py create mode 100644 tests/test_archive.py diff --git a/quickprs/archive.py b/quickprs/archive.py new file mode 100644 index 0000000..a93a8e7 --- /dev/null +++ b/quickprs/archive.py @@ -0,0 +1,878 @@ +"""MFC CArchive structure of .PRS files: walk, check, repair, rebuild. + +RPM saves a personality with MFC's ``CArchive``. Two rules of that format +matter whenever anything is added to or removed from a personality: + +* Every class and every object takes the next index in the archive's map + (index 0 is the null object, so the first class is 1). The first object + of a class is written as ``FF FF`` + schema + name, and every later object + of that class as the 2-byte tag ``0x8000 | class_index``. Older QuickPRS + code called these tags "separators" and "set markers" and copied them from + the source file, which only works while nothing in front of them changes. +* Every list is written as a WORD count followed by its objects, so a list's + count sits in the 2 bytes in front of its first object. + +Adding one talkgroup therefore moves the index of every class first written +after it, so every later tag must change, and the count in front of the +list must follow its length. RPM's loader (``CArchive::ReadObject``) throws +``badIndex`` or ``badClass`` on a tag that does not name the expected class, +and ``badSchema`` on a class written with the wrong schema, so such a file +does not open in RPM. + +This module reads a file into a :class:`Document`, a tree of :class:`Obj` +and :class:`ObjList` nodes that keeps every byte, and writes it back with +fresh tags and counts, so edits made on the tree come out right by +construction. :func:`check` lists the tags and counts a file has wrong and +:func:`repair` rewrites them. + +Document layout, in the order RPM writes it:: + + CPersonality header fields and radio type list + systems list (CConvSystem / CP25TrkSystem / + CP25ConvSystem; P25 trunked + systems hold their ECC list) + trunk sets list (CTrunkSet -> CTrunkChannel) + 6 bytes + conv sets list (CConvSet -> CConvChannel) + options list (CGenRadioOpts, CP25tWanOpts ...) + personality name, user, band limits, radio type + group sets list (CP25GroupSet -> CP25Group) + P25 conv sets list (CP25ConvSet -> CP25ConvChannel) + a list that is empty in every file seen so far + IDEN sets list (CIdenDataSet -> CDefaultIdenElem) + remaining fields (XML platform config, terminator) +""" + +from dataclasses import dataclass, field +import struct + +NULL_TAG = 0x0000 +NEW_CLASS_TAG = 0xFFFF +CLASS_TAG = 0x8000 +BIG_OBJECT_TAG = 0x7FFF + +# Class schemas exactly as RPM 14 writes them (one value per class across +# every RPM-saved file in the test corpus). MFC refuses a class whose +# schema does not match (CArchiveException::badSchema). +SCHEMAS = { + "CPersonality": 133, + "CConvSystem": 141, + "CP25TrkSystem": 141, + "CP25ConvSystem": 141, + "CPreferredSystemTableEntry": 100, + "CTrunkSet": 100, + "CTrunkChannel": 101, + "CConvSet": 101, + "CConvChannel": 106, + "CP25GroupSet": 106, + "CP25Group": 106, + "CP25ConvSet": 102, + "CP25ConvChannel": 113, + "CIdenDataSet": 102, + "CDefaultIdenElem": 102, + "CAccessoryDevice": 101, + "CAlertOpts": 103, + "CConvScanOpts": 101, + "CCustomScanList": 101, + "CDTMFOpts": 101, + "CDataOpts": 105, + "CDiagnosticOpts": 100, + "CDisplayOpts": 102, + "CGEstarOpts": 101, + "CGenRadioOpts": 113, + "CICall": 101, + "CIgnitionOpts": 101, + "CKeypadCtrlOpts": 101, + "CMdcOpts": 103, + "CMmsOpts": 100, + "CMrkOpts": 102, + "CNetworkOpts": 101, + "CP25TrkWan": 100, + "CP25tWanOpts": 100, + "CPhoneCall": 101, + "CPowerUpOpts": 104, + "CPrgrmICall": 100, + "CPrgrmPhoneCall": 100, + "CProFileOpts": 100, + "CProSoundOpts": 100, + "CProgButtons": 100, + "CScanOpts": 100, + "CSecurityPolicy": 100, + "CSndcpOpts": 100, + "CStatus": 101, + "CSupervisoryOpts": 103, + "CSystemScanOpts": 100, + "CT99": 100, + "CTimerOpts": 104, + "CType99Opts": 100, + "CVgOpts": 104, + "CVoiceAnnunciation": 101, +} + +# Data bytes of option objects that hold no other objects, measured on +# RPM-saved files. +OPTION_DATA_SIZES = { + "CGenRadioOpts": 88, + "CCustomScanList": 8, + "CDTMFOpts": 56, + "CTimerOpts": 82, + "CPowerUpOpts": 36, + "CDataOpts": 41, + "CSupervisoryOpts": 36, + "CScanOpts": 33, + "CConvScanOpts": 30, + "CAlertOpts": 19, + "CProSoundOpts": 28, + "CKeypadCtrlOpts": 20, + "CIgnitionOpts": 10, + "CMrkOpts": 16, + "CDiagnosticOpts": 8, + "CNetworkOpts": 38, + "CDisplayOpts": 37, + "CGEstarOpts": 35, + "CMmsOpts": 13, + "CSndcpOpts": 8, + "CAccessoryDevice": 8, + "CSystemScanOpts": 24, + "CSecurityPolicy": 2, + "CVgOpts": 54, + "CVoiceAnnunciation": 12, + "CStatus": 7, + "CProFileOpts": 3, + "CMdcOpts": 24, + "CProgButtons": 2, +} + +SYSTEM_TYPE_CLASSES = { + 0x01: "CConvSystem", + 0x03: "CP25ConvSystem", + 0x05: "CP25TrkSystem", +} +SYSTEM_CLASSES = frozenset(SYSTEM_TYPE_CLASSES.values()) + +# set list name -> (set class, item class, fixed item size or None) +SET_LISTS = { + "trunk sets": ("CTrunkSet", "CTrunkChannel", 23), + "conv sets": ("CConvSet", "CConvChannel", None), + "group sets": ("CP25GroupSet", "CP25Group", None), + "P25 conv sets": ("CP25ConvSet", "CP25ConvChannel", None), + "IDEN sets": ("CIdenDataSet", "CDefaultIdenElem", 15), +} + +CONV_SET_META_SIZE = 60 # bytes after a conventional set's name +MAX_SET_PADDING = 64 # extra bytes searched for after that (issue #1) +MAX_ITEMS = 2048 # sanity bound on a probed count + + +class WalkError(ValueError): + """The bytes do not follow the archive layout QuickPRS knows.""" + + +# ── document tree ───────────────────────────────────────────────────── + +@dataclass +class Obj: + """One archived object: its class and its data. + + ``parts`` holds the object's data in order: plain ``bytes`` and the + :class:`ObjList` s nested in it. Headers, tags and counts are not + stored; :func:`serialize` writes them. + """ + cls: str + parts: list = field(default_factory=list) + + def lists(self): + return [p for p in self.parts if isinstance(p, ObjList)] + + def data(self): + """The object's bytes with nested lists left out.""" + return b"".join(p for p in self.parts if isinstance(p, bytes)) + + +@dataclass +class ObjList: + """A list of objects. ``counted`` lists carry a WORD count in front; + fixed arrays (the three CT99 objects) do not. ``None`` items are NULL + object pointers.""" + name: str + items: list = field(default_factory=list) + counted: bool = True + + +@dataclass +class TagSite: + offset: int + class_name: str + value: int # index the file holds + + +@dataclass +class CountSite: + offset: int + name: str + value: int # count the file holds + items: int # objects the walk found + + +@dataclass +class Document: + """A whole personality as an object tree (see the module docstring).""" + root: Obj + schemas: dict = field(default_factory=dict) + + def list(self, name): + """The top-level list called ``name`` ("trunk sets", "systems" ...).""" + for p in self.root.parts: + if isinstance(p, ObjList) and p.name == name: + return p + raise KeyError(name) + + def option(self, cls): + """The option object of class ``cls``, or None.""" + for o in self.list("options").items: + if o is not None and o.cls == cls: + return o + return None + + def to_bytes(self): + return serialize(self) + + +@dataclass +class WalkReport: + tags: list = field(default_factory=list) + counts: list = field(default_factory=list) + class_index: dict = field(default_factory=dict) + class_order: list = field(default_factory=list) + padding: list = field(default_factory=list) # (offset, bytes) + entries: int = 0 + tail_offset: int = 0 + + +# ── reader ──────────────────────────────────────────────────────────── + +class _Walker: + """Reads the archive in RPM's Serialize order and builds the tree. + + With ``lenient`` set, list lengths come from what is actually there + (each item is recognised by its object header) rather than from the + stored count, so files whose counts were left stale can still be read + and repaired; the stored counts are kept in the report for checking. + """ + + def __init__(self, data, lenient): + self.d = bytes(data) + self.pos = 0 + self.lenient = lenient + self.next_index = 1 + self.kinds = {} # index -> ("class" | "obj", class name) + self.schemas = {} + self.r = WalkReport() + + # primitives + + def _need(self, n, what): + if n < 0 or self.pos + n > len(self.d): + raise WalkError(f"file ends inside {what} at 0x{self.pos:x}") + + def take(self, n, what="data"): + self._need(n, what) + b = self.d[self.pos:self.pos + n] + self.pos += n + return b + + def u8(self, what="byte"): + return self.take(1, what)[0] + + def u16(self, what="word"): + return struct.unpack(" len(self.d): + return None + return struct.unpack_from(" len(self.d): + return None + n = self._w(pos + 4) + raw = self.d[pos + 6:pos + 6 + n] + if not 1 <= n <= 64 or len(raw) != n or raw[:1] != b"C": + return None + if not raw.replace(b"_", b"").isalnum(): + return None + return raw.decode("ascii") + + def _tag_at(self, pos): + # Only the high bit is checked: a stale tag can hold any index, even + # one past the current map size after objects were removed. + w = self._w(pos) + return (w is not None and bool(w & CLASS_TAG) and + w not in (NEW_CLASS_TAG, BIG_OBJECT_TAG)) + + def _object_at(self, pos, classes): + name = self._class_at(pos) + if name is not None: + return name in classes + return bool(self._tag_at(pos)) + + def _printable_cstring_at(self, pos, max_len=64): + if pos >= len(self.d): + return False + n = self.d[pos] + raw = self.d[pos + 1:pos + 1 + n] + return n <= max_len and len(raw) == n and all( + 32 <= c < 127 for c in raw) + + # objects + + def _index(self, kind, name): + self.kinds[self.next_index] = (kind, name) + self.next_index += 1 + + def header(self, expect): + """Read an object header; return the class name (None for NULL). + + A tag is recorded together with the class the layout puts at this + spot, so a stale tag value cannot send the walk the wrong way. + """ + start = self.pos + w = self.u16("object header") + if w == NULL_TAG: + return None + if w == NEW_CLASS_TAG: + schema = self.u16("class schema") + n = self.u16("class name length") + raw = self.take(n, "class name") + name = raw.decode("ascii", "replace") + if self._class_at(start) is None: + raise WalkError(f"bad class header at 0x{start:x}") + if name in self.r.class_index: + raise WalkError(f"class {name} defined twice (0x{start:x})") + if expect is not None and name not in expect: + raise WalkError( + f"expected {' or '.join(sorted(expect))} at 0x{start:x}," + f" found new class {name}") + self.schemas[name] = schema + self.r.class_index[name] = self.next_index + self.r.class_order.append(name) + self._index("class", name) + self._index("obj", name) + return name + if w == BIG_OBJECT_TAG or not w & CLASS_TAG: + raise WalkError( + f"unexpected word 0x{w:04x} at 0x{start:x} where an object " + f"header was expected") + if expect is not None and len(expect) == 1: + name = next(iter(expect)) + else: + kind = self.kinds.get(w & ~CLASS_TAG) + if not kind or kind[0] != "class" or ( + expect is not None and kind[1] not in expect): + raise WalkError( + f"cannot tell which class the tag 0x{w:04x} at " + f"0x{start:x} names") + name = kind[1] + if name not in self.r.class_index: + raise WalkError( + f"tag at 0x{start:x} refers to {name}, which is not defined " + f"before it") + self.r.tags.append(TagSite(start, name, w & ~CLASS_TAG)) + self._index("obj", name) + return name + + def counted(self, name, more, read_item): + """Read a WORD-counted list; ``more()`` says whether another item + starts at the cursor (used when lenient).""" + site = self.pos + stored = self.u16(f"{name} count") + lst = ObjList(name) + if self.lenient: + while more(): + if len(lst.items) >= MAX_ITEMS: + raise WalkError(f"runaway {name} list at 0x{site:x}") + lst.items.append(read_item()) + else: + for _ in range(stored): + lst.items.append(read_item()) + self.r.counts.append(CountSite(site, name, stored, len(lst.items))) + return lst + + # document + + def document(self): + if self.header({"CPersonality"}) != "CPersonality": + raise WalkError("file does not start with CPersonality") + start = self.pos + kv = self.u8("personality header") + self.take(kv + 4, "personality header") + for _ in range(6): + self.cstring("personality string") + n_types = self.u16("radio type list") + self.take(2 * n_types, "radio type list") + parts = [self.d[start:self.pos]] + + parts.append(self.counted("systems", self._system_follows, + self.system)) + parts.append(self.set_list("trunk sets")) + parts.append(self.take(6, "fields after trunk sets")) + parts.append(self.set_list("conv sets")) + parts.append(self.counted("options", self._option_follows, + self.option)) + start = self.pos + self.cstring("personality name") + self.take(2, "personality fields") + self.cstring("user name") + self.take(2 + 32 + 2, "band limits") + parts.append(self.d[start:self.pos]) + parts.append(self.set_list("group sets")) + parts.append(self.set_list("P25 conv sets")) + site = self.pos + if self.u16("list after P25 conv sets"): + raise WalkError( + f"unknown non-empty list after the P25 conv sets at " + f"0x{site:x}") + parts.append(ObjList("unknown list")) + parts.append(self.set_list("IDEN sets")) + self.r.tail_offset = self.pos + self._check_tail() + parts.append(self.d[self.pos:]) + self.r.entries = self.next_index - 1 + return Document(Obj("CPersonality", parts), dict(self.schemas)) + + def _check_tail(self): + """Only plain fields may follow the IDEN sets; an object there would + be one this walker does not know, whose tags it could not fix.""" + pos = self.pos + while True: + pos = self.d.find(b"\xff\xff", pos) + if pos < 0: + return + name = self._class_at(pos) + if name is not None and len(name) >= 4: + raise WalkError( + f"unknown object {name} after the IDEN sets at 0x{pos:x}") + pos += 1 + + # systems + + def _system_follows(self): + name = self._class_at(self.pos) + if name is not None: + return name in SYSTEM_CLASSES + if not self._tag_at(self.pos): + return False + p = self.pos + 2 + if not self._printable_cstring_at(p): + return False + p += 1 + self.d[p] + return (p + 3 <= len(self.d) and self.d[p] in SYSTEM_TYPE_CLASSES + and self.d[p + 1:p + 3] == b"\xff\xff") + + def system(self): + start = self.pos + if self._w(self.pos) == NEW_CLASS_TAG: + cls = self.header(SYSTEM_CLASSES) + data_start = self.pos + self.cstring("system name") + stype = self.u8("system type") + if SYSTEM_TYPE_CLASSES.get(stype) != cls: + raise WalkError( + f"system at 0x{start:x}: class {cls} with type byte " + f"0x{stype:02x}") + else: + # A tag only says "a system"; the type byte after the name says + # which class, so a stale tag value cannot mislead the walk. + w = self.u16("system header") + if not w & CLASS_TAG or w in (NEW_CLASS_TAG, BIG_OBJECT_TAG): + raise WalkError(f"expected a system object at 0x{start:x}") + data_start = self.pos + self.cstring("system name") + stype = self.u8("system type") + cls = SYSTEM_TYPE_CLASSES.get(stype) + if cls is None: + raise WalkError( + f"unknown system type 0x{stype:02x} at 0x{start:x}") + if cls not in self.r.class_index: + raise WalkError( + f"system at 0x{start:x} is tagged, but no {cls} is " + f"defined before it") + self.r.tags.append(TagSite(start, cls, w & ~CLASS_TAG)) + self._index("obj", cls) + if self.u16("system config marker") != 0xFFFF: + raise WalkError(f"system at 0x{start:x}: config lacks FFFF") + self.take(42, "system config prefix") + self.cstring("system long name") + if cls == "CP25TrkSystem": + self.take(15, "system flags") + self.cstring("trunk set name") + self.cstring("group set name") + self.take(12 + 4 + 12 + 6 + 2 + 4, "system ids") + self.cstring("WAN name") + self.take(44, "WAN config") + self.cstring("WAN name") + self.take(13 + 4 + 4, "unit ids and band limits") + if self.u8("ECC marker") != 0x06: + raise WalkError(f"system at 0x{start:x}: ECC marker missing") + head = self.d[data_start:self.pos] + ecc = self.counted( + "ECC entries", + lambda: self._object_at(self.pos, + {"CPreferredSystemTableEntry"}), + lambda: self.fixed("CPreferredSystemTableEntry", 13)) + rest = self.pos + self.take(4, "fields after ECC list") + self.cstring("IDEN set name") + self.take(63, "system tail") + return Obj(cls, [head, ecc, self.d[rest:self.pos]]) + if cls == "CConvSystem": + self.take(12, "conv system fields") + self.cstring("conv set name") + self.take(3 + 4, "conv system fields") + else: + self.take(5 + 4, "P25 conv system fields") + self.cstring("P25 conv set name") + self.take(27 + 6 + 2 + 26, "P25 conv system fields") + return Obj(cls, [self.d[data_start:self.pos]]) + + def fixed(self, cls, size): + name = self.header({cls}) + if name is None: + return None + return Obj(cls, [self.take(size, cls)]) + + # sets + + def set_list(self, name): + set_cls, item_cls, _ = SET_LISTS[name] + return self.counted(name, lambda: self._set_follows(name), + lambda: self.set_object(name)) + + def _set_follows(self, name): + set_cls, item_cls, _ = SET_LISTS[name] + cname = self._class_at(self.pos) + if cname is not None: + return cname == set_cls + if not self._tag_at(self.pos): + return False + n = self._w(self.pos + 2) + if n is None or n > MAX_ITEMS: + return False + return n == 0 or self._object_at(self.pos + 4, {item_cls}) + + def set_object(self, name): + set_cls, item_cls, size = SET_LISTS[name] + self.header({set_cls}) + items = self.counted( + "items", lambda: self._object_at(self.pos, {item_cls}), + lambda: self.fixed(item_cls, size) if size else + self.variable_item(item_cls)) + meta_start = self.pos + getattr(self, "_meta_" + set_cls)() + return Obj(set_cls, [items, self.d[meta_start:self.pos]]) + + def variable_item(self, cls): + if self.header({cls}) is None: + return None + start = self.pos + if cls == "CConvChannel": + self.cstring("short name") + self.take(16, "frequencies") + self.cstring("tx tone") + self.cstring("rx tone") + self.take(4 + 48 + 10, "channel fields") + self.cstring("long name") + self.take(7, "channel trailer") + elif cls == "CP25Group": + self.cstring("group name") + self.take(2 + 12 + 7, "group fields") + self.cstring("group long name") + self.take(4, "group tail") + else: # CP25ConvChannel + self.cstring("short name") + self.take(16, "frequencies") + self.cstring("tx tone") + self.cstring("rx tone") + self.take(8 + 22, "channel fields") + self.cstring("long name") + self.take(20, "channel trailer") + return Obj(cls, [self.d[start:self.pos]]) + + def _meta_CTrunkSet(self): + self.cstring("trunk set name") + self.take(2 + 32 + 13, "trunk set fields") + + def _meta_CConvSet(self): + self.cstring("conv set name") + self.take(CONV_SET_META_SIZE, "conv set fields") + if self._after_conv_set(): + return + # Issue #1: some RPM files carry a few more bytes here. Find where + # the next set (or the options list) starts and keep the bytes. + base = self.pos + for k in range(1, MAX_SET_PADDING + 1): + self.pos = base + k + if self.pos + 2 <= len(self.d) and self._after_conv_set(): + self.r.padding.append((base, self.d[base:self.pos])) + return + self.pos = base + raise WalkError(f"cannot find the end of the conv set at 0x{base:x}") + + def _after_conv_set(self): + """True when the next conv set or the options list starts here.""" + if self._set_follows("conv sets"): + return True + n = self._w(self.pos) # the options list count + if n is None or n > 200: + return False + if self._class_at(self.pos + 2) is not None: + return True # first option (count may be stale) + return n == 0 and self._doc_fields_at(self.pos + 2) + + def _doc_fields_at(self, pos): + """Personality name, 2 bytes, user name, then 0E 00 (no options).""" + if not self._printable_cstring_at(pos, 255): + return False + pos += 1 + self.d[pos] + 2 + if not self._printable_cstring_at(pos, 255): + return False + pos += 1 + self.d[pos] + return self.d[pos:pos + 2] == b"\x0e\x00" + + def _meta_CP25GroupSet(self): + self.cstring("group set name") + self.take(16, "group set fields") + + def _meta_CP25ConvSet(self): + self.cstring("P25 conv set name") + self.take(2 + 32, "P25 conv set fields") + self.cstring("P25 conv group reference") + self.take(13, "P25 conv set fields") + + def _meta_CIdenDataSet(self): + self.cstring("IDEN set name") + self.take(2, "IDEN set fields") + + # options + + def _option_follows(self): + name = self._class_at(self.pos) + if name is not None: + return name not in SYSTEM_CLASSES + # The options are followed by the personality name (a CString of + # ASCII), which can never look like a tag. + return self._tag_at(self.pos) + + def option(self): + start = self.pos + cls = self.header(None) + if cls is None: + return None + if cls == "CP25tWanOpts": + return Obj(cls, [self.counted( + "WAN entries", + lambda: self._object_at(self.pos, {"CP25TrkWan"}), + self._wan_entry)]) + if cls == "CPrgrmICall": + return Obj(cls, [self.counted( + "individual calls", + lambda: self._object_at(self.pos, {"CICall"}), + lambda: self.fixed("CICall", 22))]) + if cls == "CPrgrmPhoneCall": + return Obj(cls, [self.counted( + "phone calls", + lambda: self._object_at(self.pos, {"CPhoneCall"}), + lambda: self.fixed("CPhoneCall", 8))]) + if cls == "CType99Opts": + head = self.take(4, "Type 99 options") + tones = ObjList("Type 99 tones", counted=False) + for _ in range(3): + tones.items.append(self.fixed("CT99", 33)) + return Obj(cls, [head, tones]) + if cls in OPTION_DATA_SIZES: + return Obj(cls, [self.take(OPTION_DATA_SIZES[cls], cls)]) + raise WalkError(f"option {cls} at 0x{start:x} has no known size") + + def _wan_entry(self): + if self.header({"CP25TrkWan"}) is None: + return None + start = self.pos + self.cstring("WAN name") + self.take(6, "WAN entry") + return Obj("CP25TrkWan", [self.d[start:self.pos]]) + + +# ── writer ──────────────────────────────────────────────────────────── + +class _Writer: + def __init__(self, schemas): + self.out = bytearray() + self.schemas = schemas + self.class_index = {} + self.next_index = 1 + + def obj(self, o): + if o is None: + self.out += struct.pack("= BIG_OBJECT_TAG: + raise ValueError("archive too large for 16-bit class tags") + self.out += struct.pack(" 0xFFFE: + raise ValueError(f"too many items in {lst.name}") + self.out += struct.pack("= 13: + tail = trailing[:13] # parsed last set: its own 13 bytes come first + else: + tail = bytes(tset.gap_bytes or b"")[:12].ljust(12, b"\x00") + b"\x01" + return Obj("CTrunkSet", [ObjList("items", channels), + tset.metadata_to_bytes() + tail]) + + +def _conv_set_obj(cset): + channels = [Obj("CConvChannel", [ch.to_bytes()]) for ch in cset.channels] + meta = cset.metadata_to_bytes() + bytes(getattr(cset, "padding", b"")) + return Obj("CConvSet", [ObjList("items", channels), meta]) + + +def _group_set_obj(gset): + groups = [Obj("CP25Group", [g.to_bytes()]) for g in gset.groups] + return Obj("CP25GroupSet", [ObjList("items", groups), + gset.metadata_to_bytes()]) + + +def _iden_set_obj(iset): + elements = list(iset.elements[:IdenDataSet.SLOTS]) + while len(elements) < IdenDataSet.SLOTS: + elements.append(IdenElement()) + items = [Obj("CDefaultIdenElem", [e.to_bytes()]) for e in elements] + meta = write_lps(iset.name) + bytes(iset.metadata)[:2].ljust(2, b"\x00") + return Obj("CIdenDataSet", [ObjList("items", items), meta]) + + +def _p25_conv_set_obj(pset): + channels = [Obj("CP25ConvChannel", [ch.to_bytes()]) + for ch in pset.channels] + # The old parser's 17-byte "trailing" ends with the next two list + # counts; only the first 13 bytes belong to the set. + meta = (write_lps(pset.name) + write_uint8(pset.scan_list_size) + + write_uint8(pset.config_byte2) + write_double_le(pset.tx_min) + + write_double_le(pset.rx_min) + write_double_le(pset.tx_max) + + write_double_le(pset.rx_max) + write_lps(pset.group_set_ref) + + bytes(pset.trailing)[:13].ljust(13, b"\x00")) + return Obj("CP25ConvSet", [ObjList("items", channels), meta]) + + +_SET_OBJ_BUILDERS = { + "trunk sets": _trunk_set_obj, + "conv sets": _conv_set_obj, + "group sets": _group_set_obj, + "IDEN sets": _iden_set_obj, + "P25 conv sets": _p25_conv_set_obj, +} + + +def _write_set_list(prs, list_name, sets): + """Replace one whole set list (may be empty) and rewrite the file.""" + doc = archive.document_from_prs(prs) + build = _SET_OBJ_BUILDERS[list_name] + doc.list(list_name).items = [build(s) for s in sets] + archive.write_document(prs, doc) + + +def _system_obj_names(obj): + """(short name, long name) of a system object in an archive.Document.""" + data = obj.parts[0] + short, pos = archive.read_cstring(data, 0) + pos += 1 + 2 + 42 # type byte, FFFF, config prefix + long_name, _ = archive.read_cstring(data, pos) + return short, long_name + + +def _append_system(prs, obj): + doc = archive.document_from_prs(prs) + doc.list("systems").items.append(obj) + archive.write_document(prs, doc) + + # ─── Trunk Set Operations ──────────────────────────────────────────── def add_trunk_set(prs, trunk_set): @@ -142,22 +230,13 @@ def add_trunk_channels(prs, set_name, channels): set_byte1, set_byte2) -def _replace_trunk_sections(prs, sets, byte1, byte2, set_byte1, set_byte2): - """Replace CTrunkChannel and CTrunkSet sections with rebuilt data.""" +def _replace_trunk_sections(prs, sets, byte1=None, byte2=None, + set_byte1=None, set_byte2=None): + """Replace all trunk sets. The header-byte arguments are ignored (kept + for callers); schemas come from the file or RPM's defaults.""" if not sets: raise ValueError("No trunk sets to write") - new_ch_raw = _build_trunk_channel_raw(sets, byte1, byte2) - new_set_raw = _rebuild_set_section("CTrunkSet", len(sets[0].channels), - set_byte1, set_byte2) - - ch_idx = _find_section_index(prs, "CTrunkChannel") - set_idx = _find_section_index(prs, "CTrunkSet") - if ch_idx < 0 or set_idx < 0: - raise ValueError("CTrunkChannel or CTrunkSet section not found") - prs.sections[ch_idx] = Section(offset=0, raw=new_ch_raw, - class_name="CTrunkChannel") - prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, - class_name="CTrunkSet") + _write_set_list(prs, "trunk sets", sets) def _build_trunk_channel_raw(sets, byte1, byte2): @@ -257,23 +336,12 @@ def add_talkgroups(prs, set_name, groups): set_byte1, set_byte2) -def _replace_group_sections(prs, sets, byte1, byte2, set_byte1, set_byte2): - """Replace CP25Group and CP25GroupSet sections with rebuilt data.""" +def _replace_group_sections(prs, sets, byte1=None, byte2=None, + set_byte1=None, set_byte2=None): + """Replace all talkgroup sets (header-byte arguments are ignored).""" if not sets: raise ValueError("No group sets to write") - new_grp_raw = _build_group_raw(sets, byte1, byte2) - new_set_raw = _rebuild_set_section("CP25GroupSet", - len(sets[0].groups), - set_byte1, set_byte2) - - grp_idx = _find_section_index(prs, "CP25Group") - set_idx = _find_section_index(prs, "CP25GroupSet") - if grp_idx < 0 or set_idx < 0: - raise ValueError("CP25Group or CP25GroupSet section not found") - prs.sections[grp_idx] = Section(offset=0, raw=new_grp_raw, - class_name="CP25Group") - prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, - class_name="CP25GroupSet") + _write_set_list(prs, "group sets", sets) def _build_group_raw(sets, byte1, byte2): @@ -324,27 +392,25 @@ def add_iden_set(prs, iden_set): set_byte1, set_byte2 = _get_header_bytes(set_sec) first_count = _get_first_count(prs, "CIdenDataSet") - # Extract trailing data BEFORE rebuilding (platformConfig XML, passwords, etc.) - trailing = extract_iden_trailing_data(elem_sec.raw, first_count) - existing_sets = _parse_section_data(elem_sec, parse_iden_section, first_count) existing_sets.append(iden_set) + # The document keeps everything after the IDEN sets (platformConfig XML, + # passwords, GUID) on its own, so no trailing data needs carrying here. + _replace_iden_sections(prs, existing_sets) - # Rebuild with trailing data preserved - new_elem_raw = _build_iden_raw(existing_sets, byte1, byte2, - trailing_data=trailing) - new_set_raw = _rebuild_set_section("CIdenDataSet", - len(existing_sets[0].elements), - set_byte1, set_byte2) - elem_idx = _find_section_index(prs, "CDefaultIdenElem") - set_idx = _find_section_index(prs, "CIdenDataSet") - if elem_idx < 0 or set_idx < 0: - raise ValueError("CDefaultIdenElem or CIdenDataSet section not found") - prs.sections[elem_idx] = Section(offset=0, raw=new_elem_raw, - class_name="CDefaultIdenElem") - prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, - class_name="CIdenDataSet") +def _replace_iden_sections(prs, sets, *_args, **_kwargs): + """Replace all IDEN sets (extra arguments are ignored).""" + if not sets: + raise ValueError("No IDEN sets to write") + _write_set_list(prs, "IDEN sets", sets) + + +def _replace_p25_conv_sections(prs, sets, *_args, **_kwargs): + """Replace all P25 conventional sets (extra arguments are ignored).""" + if not sets: + raise ValueError("No P25 conv sets to write") + _write_set_list(prs, "P25 conv sets", sets) def _build_iden_raw(sets, byte1, byte2, trailing_data=None): @@ -397,28 +463,15 @@ def add_p25_trunked_system(prs, config, trunk_set=None, group_set=None, group_set: optional P25GroupSet to inject iden_set: optional IdenDataSet to inject """ - # Build the system config data section - data_raw = config.build_data_section() - data_section = Section(offset=0, raw=data_raw, class_name="") - - # Check if a CP25TrkSystem header already exists - header_idx = _find_section_index(prs, "CP25TrkSystem") - - if header_idx < 0: - # No existing header — create one and insert before the data sets - header_raw = config.build_header_section() - header_section = Section(offset=0, raw=header_raw, - class_name="CP25TrkSystem") - - # Find insertion point: just before the first C*Set section - insert_idx = _find_set_insertion_point(prs) - prs.sections.insert(insert_idx, data_section) - prs.sections.insert(insert_idx, header_section) - else: - # Header exists — insert data section after the last system config - # data section that follows the header - insert_idx = _find_system_data_end(prs, header_idx) - prs.sections.insert(insert_idx, data_section) + # The system goes at the end of the systems list; its ECC entries are + # CPreferredSystemTableEntry objects inside it. + head, ecc, rest = config.object_parts() + _append_system(prs, Obj("CP25TrkSystem", [ + head, + ObjList("ECC entries", + [Obj("CPreferredSystemTableEntry", [e]) for e in ecc]), + rest, + ])) # Inject associated data sets if trunk_set: @@ -450,41 +503,37 @@ def _update_wan_sections(prs, config): wan_name = wan_name + ' ' * (8 - len(wan_name)) wan_name = wan_name[:8] - # Parse existing WAN entries - wan_idx = _find_section_index(prs, "CP25TrkWan") - if wan_idx < 0: - return # No WAN section to update - - wan_sec = prs.sections[wan_idx] - try: - existing_entries = parse_wan_section(wan_sec.raw) - except Exception: - existing_entries = [] - - # Check for duplicate by wan_name (stripped for comparison) - for entry in existing_entries: + doc = archive.document_from_prs(prs) + wan_list = _wan_list(doc, create=True) + for item in wan_list.items: + if item is None: + continue + entry, _ = P25TrkWanEntry.parse(item.parts[0], 0) if entry.wan_name.strip() == wan_name.strip(): - return # Already exists, skip + return # already there - # Create new entry new_entry = P25TrkWanEntry( wan_name=wan_name, wacn=config.wacn, system_id=config.system_id, ) - existing_entries.append(new_entry) + wan_list.items.append(Obj("CP25TrkWan", [new_entry.to_bytes()])) + archive.write_document(prs, doc) + - # Rebuild CP25TrkWan section - new_wan_raw = build_wan_section(existing_entries) - prs.sections[wan_idx] = Section( - offset=0, raw=new_wan_raw, class_name="CP25TrkWan") +def _wan_list(doc, create=False): + """The WAN entry list inside the CP25tWanOpts option (None if absent). - # Update CP25tWanOpts count - opts_idx = _find_section_index(prs, "CP25tWanOpts") - if opts_idx >= 0: - new_opts_raw = build_wan_opts_section(len(existing_entries)) - prs.sections[opts_idx] = Section( - offset=0, raw=new_opts_raw, class_name="CP25tWanOpts") + With ``create``, adds an empty CP25tWanOpts option when the + personality has none, so P25 systems always get their WAN entry. + """ + opts = doc.option("CP25tWanOpts") + if opts is None: + if not create: + return None + opts = Obj("CP25tWanOpts", [ObjList("WAN entries")]) + doc.list("options").items.insert(0, opts) + return opts.lists()[0] def add_preferred_entries(prs, new_entries): @@ -497,16 +546,14 @@ def add_preferred_entries(prs, new_entries): prs: PRSFile object new_entries: list of PreferredSystemEntry to add """ - from .record_types import ( - parse_preferred_section, build_preferred_section, - ) - - pref_idx = _find_section_index(prs, "CPreferredSystemTableEntry") - if pref_idx < 0 or not new_entries: + if not new_entries: return - - sec = prs.sections[pref_idx] - entries, iden, tail, chain, ctype = parse_preferred_section(sec.raw) + doc = archive.document_from_prs(prs) + system = _first_ecc_system(doc) + if system is None: + return + ecc = system.lists()[0] + entries = _preferred_entries_of(system) # Compute next sequence index max_f2 = max((e.field2 for e in entries), default=0) @@ -514,13 +561,29 @@ def add_preferred_entries(prs, new_entries): if entry.field2 == 0: entry.field2 = max_f2 + 1 + i - entries.extend(new_entries) + for entry in new_entries: + ecc.items.append(Obj("CPreferredSystemTableEntry", + [entry.to_bytes()[:13]])) + archive.write_document(prs, doc) - # Rebuild section preserving tail - new_raw = build_preferred_section(entries, tail_bytes=tail) - prs.sections[pref_idx] = Section( - offset=0, raw=new_raw, - class_name="CPreferredSystemTableEntry") + +def _first_ecc_system(doc): + """The first P25 trunked system: the "preferred system table" is its + ECC list (the CPreferredSystemTableEntry objects inside it).""" + for obj in doc.list("systems").items: + if obj is not None and obj.cls == "CP25TrkSystem": + return obj + return None + + +def _preferred_entries_of(system): + from .record_types import PreferredSystemEntry + entries = [] + for item in system.lists()[0].items: + if item is not None: + entries.append(PreferredSystemEntry.from_bytes( + item.parts[0] + b"\x00\x00", 0)) + return entries def get_preferred_entries(prs): @@ -529,15 +592,26 @@ def get_preferred_entries(prs): Returns: (entries, iden_name, chain_name) or ([], None, None) """ - from .record_types import parse_preferred_section - - pref_idx = _find_section_index(prs, "CPreferredSystemTableEntry") - if pref_idx < 0: + try: + doc = archive.document_from_prs(prs) + except archive.WalkError: + doc = None + system = _first_ecc_system(doc) if doc else None + if system is None: return [], None, None - - sec = prs.sections[pref_idx] - entries, iden, tail, chain, ctype = parse_preferred_section(sec.raw) - return entries, iden, chain + entries = _preferred_entries_of(system) + rest = system.parts[2] + iden, _ = archive.read_cstring(rest, 4) + # the next system in the list, which the old section layout called + # the "chain" + # The next system in the list is the "chain" when it is another P25 + # trunked system (what the old section parser reported). + systems = [o for o in doc.list("systems").items if o is not None] + pos = systems.index(system) + chain = None + if pos + 1 < len(systems) and systems[pos + 1].cls == "CP25TrkSystem": + chain = _system_obj_names(systems[pos + 1])[0] + return entries, iden or None, chain def _find_set_insertion_point(prs): @@ -610,42 +684,18 @@ def _safe_add_iden_set(prs, iden_set): def _create_trunk_sections(prs, sets): - """Create CTrunkSet + CTrunkChannel sections from scratch.""" - set_raw = build_class_header('CTrunkSet', 0x64, 0x00) + \ - write_uint16_le(len(sets[0].channels)) - ch_raw = _build_trunk_channel_raw(sets, 0x64, 0x00) - - insert_idx = _find_data_set_insert_point(prs) - prs.sections.insert(insert_idx, Section( - offset=0, raw=ch_raw, class_name="CTrunkChannel")) - prs.sections.insert(insert_idx, Section( - offset=0, raw=set_raw, class_name="CTrunkSet")) + """Write the first trunk sets of a personality that had none.""" + _write_set_list(prs, "trunk sets", sets) def _create_group_sections(prs, sets): - """Create CP25GroupSet + CP25Group sections from scratch.""" - set_raw = build_class_header('CP25GroupSet', 0x6a, 0x00) + \ - write_uint16_le(len(sets[0].groups)) - grp_raw = _build_group_raw(sets, 0x6a, 0x00) - - insert_idx = _find_data_set_insert_point(prs) - prs.sections.insert(insert_idx, Section( - offset=0, raw=grp_raw, class_name="CP25Group")) - prs.sections.insert(insert_idx, Section( - offset=0, raw=set_raw, class_name="CP25GroupSet")) + """Write the first talkgroup sets of a personality that had none.""" + _write_set_list(prs, "group sets", sets) def _create_iden_sections(prs, sets): - """Create CIdenDataSet + CDefaultIdenElem sections from scratch.""" - set_raw = build_class_header('CIdenDataSet', 0x66, 0x00) + \ - write_uint16_le(len(sets[0].elements)) - elem_raw = _build_iden_raw(sets, 0x66, 0x00) - - insert_idx = _find_data_set_insert_point(prs) - prs.sections.insert(insert_idx, Section( - offset=0, raw=elem_raw, class_name="CDefaultIdenElem")) - prs.sections.insert(insert_idx, Section( - offset=0, raw=set_raw, class_name="CIdenDataSet")) + """Write the first IDEN sets of a personality that had none.""" + _write_set_list(prs, "IDEN sets", sets) def _find_data_set_insert_point(prs): @@ -685,22 +735,12 @@ def add_conv_set(prs, conv_set): set_byte1, set_byte2) -def _replace_conv_sections(prs, sets, byte1, byte2, set_byte1, set_byte2): - """Replace CConvChannel and CConvSet sections with rebuilt data.""" +def _replace_conv_sections(prs, sets, byte1=None, byte2=None, + set_byte1=None, set_byte2=None): + """Replace all conventional sets (header-byte arguments are ignored).""" if not sets: raise ValueError("No conv sets to write") - new_ch_raw = _build_conv_channel_raw(sets, byte1, byte2) - new_set_raw = _rebuild_set_section("CConvSet", len(sets[0].channels), - set_byte1, set_byte2) - - ch_idx = _find_section_index(prs, "CConvChannel") - set_idx = _find_section_index(prs, "CConvSet") - if ch_idx < 0 or set_idx < 0: - raise ValueError("CConvChannel or CConvSet section not found") - prs.sections[ch_idx] = Section(offset=0, raw=new_ch_raw, - class_name="CConvChannel") - prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, - class_name="CConvSet") + _write_set_list(prs, "conv sets", sets) def _build_conv_channel_raw(sets, byte1, byte2): @@ -739,16 +779,8 @@ def _safe_add_conv_set(prs, conv_set): def _create_conv_sections(prs, sets): - """Create CConvSet + CConvChannel sections from scratch.""" - set_raw = build_class_header('CConvSet', 0x65, 0x00) + \ - write_uint16_le(len(sets[0].channels)) - ch_raw = _build_conv_channel_raw(sets, 0x6a, 0x00) - - insert_idx = _find_data_set_insert_point(prs) - prs.sections.insert(insert_idx, Section( - offset=0, raw=ch_raw, class_name="CConvChannel")) - prs.sections.insert(insert_idx, Section( - offset=0, raw=set_raw, class_name="CConvSet")) + """Write the first conventional sets of a personality that had none.""" + _write_set_list(prs, "conv sets", sets) # ─── Conventional System Creation ────────────────────────────────── @@ -764,21 +796,7 @@ def add_conv_system(prs, config, conv_set=None): config: ConvSystemConfig with system parameters conv_set: optional ConvSet to inject """ - data_raw = config.build_data_section() - data_section = Section(offset=0, raw=data_raw, class_name="") - - header_idx = _find_section_index(prs, "CConvSystem") - - if header_idx < 0: - header_raw = config.build_header_section() - header_section = Section(offset=0, raw=header_raw, - class_name="CConvSystem") - insert_idx = _find_set_insertion_point(prs) - prs.sections.insert(insert_idx, data_section) - prs.sections.insert(insert_idx, header_section) - else: - insert_idx = _find_system_data_end(prs, header_idx) - prs.sections.insert(insert_idx, data_section) + _append_system(prs, Obj("CConvSystem", [config.object_data()])) if conv_set: _safe_add_conv_set(prs, conv_set) @@ -795,20 +813,7 @@ def add_p25_conv_system(prs, config): prs: PRSFile object config: P25ConvSystemConfig with system parameters """ - header_raw = config.build_header_section() - data_raw = config.build_data_section() - trailing_raw = config.build_trailing_section() - - header_section = Section(offset=0, raw=header_raw, - class_name="CP25ConvSystem") - data_section = Section(offset=0, raw=data_raw, class_name="") - trailing_section = Section(offset=0, raw=trailing_raw, class_name="") - - # Insert before data sets - insert_idx = _find_set_insertion_point(prs) - prs.sections.insert(insert_idx, trailing_section) - prs.sections.insert(insert_idx, data_section) - prs.sections.insert(insert_idx, header_section) + _append_system(prs, Obj("CP25ConvSystem", [config.object_data()])) # ─── Set Removal ─────────────────────────────────────────────────── @@ -841,18 +846,8 @@ def remove_trunk_set(prs, set_name): if len(remaining) == len(existing_sets): return False # not found - if not remaining: - # Last set removed — drop both sections - ch_idx = _find_section_index(prs, "CTrunkChannel") - set_idx = _find_section_index(prs, "CTrunkSet") - # Remove in reverse order to preserve indices - for idx in sorted([ch_idx, set_idx], reverse=True): - if idx >= 0: - prs.sections.pop(idx) - else: - _replace_trunk_sections(prs, remaining, byte1, byte2, - set_byte1, set_byte2) - + # An empty list is fine: the archive then holds a count of 0. + _write_set_list(prs, "trunk sets", remaining) return True @@ -884,16 +879,7 @@ def remove_group_set(prs, set_name): if len(remaining) == len(existing_sets): return False # not found - if not remaining: - grp_idx = _find_section_index(prs, "CP25Group") - set_idx = _find_section_index(prs, "CP25GroupSet") - for idx in sorted([grp_idx, set_idx], reverse=True): - if idx >= 0: - prs.sections.pop(idx) - else: - _replace_group_sections(prs, remaining, byte1, byte2, - set_byte1, set_byte2) - + _write_set_list(prs, "group sets", remaining) return True @@ -925,16 +911,7 @@ def remove_conv_set(prs, set_name): if len(remaining) == len(existing_sets): return False # not found - if not remaining: - ch_idx = _find_section_index(prs, "CConvChannel") - set_idx = _find_section_index(prs, "CConvSet") - for idx in sorted([ch_idx, set_idx], reverse=True): - if idx >= 0: - prs.sections.pop(idx) - else: - _replace_conv_sections(prs, remaining, byte1, byte2, - set_byte1, set_byte2) - + _write_set_list(prs, "conv sets", remaining) return True @@ -1256,158 +1233,76 @@ def remove_wan_entry(prs, wan_name): Returns: True if entry was removed, False if not found. """ - wan_idx = _find_section_index(prs, "CP25TrkWan") - if wan_idx < 0: + doc = archive.document_from_prs(prs) + wan_list = _wan_list(doc) + if wan_list is None: return False - wan_sec = prs.sections[wan_idx] - try: - entries = parse_wan_section(wan_sec.raw) - except Exception: - return False + def _name(item): + return P25TrkWanEntry.parse(item.parts[0], 0)[0].wan_name.strip() - remaining = [e for e in entries - if e.wan_name.strip() != wan_name.strip()] - if len(remaining) == len(entries): + remaining = [i for i in wan_list.items + if i is None or _name(i) != wan_name.strip()] + if len(remaining) == len(wan_list.items): return False # not found - if not remaining: - # Remove WAN section entirely - prs.sections.pop(wan_idx) - opts_idx = _find_section_index(prs, "CP25tWanOpts") - if opts_idx >= 0: - prs.sections.pop(opts_idx) - else: - new_wan_raw = build_wan_section(remaining) - prs.sections[wan_idx] = Section( - offset=0, raw=new_wan_raw, class_name="CP25TrkWan") - opts_idx = _find_section_index(prs, "CP25tWanOpts") - if opts_idx >= 0: - new_opts_raw = build_wan_opts_section(len(remaining)) - prs.sections[opts_idx] = Section( - offset=0, raw=new_opts_raw, class_name="CP25tWanOpts") - + # An emptied WAN list stays as CP25tWanOpts with a count of 0. + wan_list.items = remaining + archive.write_document(prs, doc) return True # ─── System Removal ───────────────────────────────────────────────── def remove_system_config(prs, long_name): - """Remove a system config data section by its long display name. - - Finds and removes the unnamed data section whose long name matches. - If this was the only config section after a system header, the - header is also removed. + """Remove the system whose long display name is ``long_name``. Args: prs: PRSFile object long_name: the system's long display name (e.g., "PSERN SEATTLE") Returns: - True if a section was removed, False if not found. + True if a system was removed, False if not found. """ - from .record_types import parse_system_long_name, is_system_config_data - - target_idx = None - for i, sec in enumerate(prs.sections): - if not sec.class_name and is_system_config_data(sec.raw): - name = parse_system_long_name(sec.raw) - if name == long_name: - target_idx = i - break - - if target_idx is None: - return False - - # Remove the config data section - prs.sections.pop(target_idx) - - # Check if the preceding header now has no config data sections - _cleanup_orphan_headers(prs) - - return True + doc = archive.document_from_prs(prs) + systems = doc.list("systems") + for i, obj in enumerate(systems.items): + if obj is not None and _system_obj_names(obj)[1] == long_name: + del systems.items[i] + archive.write_document(prs, doc) + return True + return False def remove_system_by_class(prs, class_name, system_name=None): - """Remove all sections for a system type (or a specific named system). - - Removes the class header section and all following data sections that - belong to it (system config data, continuation data, etc.). + """Remove the systems of one class, or one of them by short name. Args: prs: PRSFile object class_name: "CP25TrkSystem", "CConvSystem", or "CP25ConvSystem" - system_name: optional short name to target a specific header. - If None, removes ALL sections of this class type. + system_name: optional short name to target a specific system. + If None, removes ALL systems of this class. Returns: - Number of sections removed. + Number of systems removed. """ - from .record_types import ( - parse_system_short_name, is_system_config_data, - ) - + doc = archive.document_from_prs(prs) + systems = doc.list("systems") + keep = [] removed = 0 - i = 0 - while i < len(prs.sections): - sec = prs.sections[i] - if sec.class_name != class_name: - i += 1 - continue - - # Check system_name filter - if system_name: - short = parse_system_short_name(sec.raw) - if short != system_name: - i += 1 - continue - - # Remove this header - prs.sections.pop(i) - removed += 1 - - # Remove all following data sections until the next class header - while i < len(prs.sections): - next_sec = prs.sections[i] - if next_sec.class_name: - break # hit the next class header, stop - prs.sections.pop(i) + for obj in systems.items: + if (obj is not None and obj.cls == class_name and + (system_name is None or + _system_obj_names(obj)[0] == system_name)): removed += 1 - + else: + keep.append(obj) + if removed: + systems.items = keep + archive.write_document(prs, doc) return removed -def _cleanup_orphan_headers(prs): - """Remove system headers that have no config data sections following them.""" - from .record_types import is_system_config_data - - system_classes = {'CP25TrkSystem', 'CConvSystem', 'CP25ConvSystem'} - to_remove = [] - - for i, sec in enumerate(prs.sections): - if sec.class_name not in system_classes: - continue - - # Check if the next section is a config data section - has_config = False - j = i + 1 - while j < len(prs.sections): - next_sec = prs.sections[j] - if next_sec.class_name: - break # hit another class header - if is_system_config_data(next_sec.raw): - has_config = True - break - j += 1 - - if not has_config: - to_remove.append(i) - - # Remove in reverse order to preserve indices - for idx in reversed(to_remove): - prs.sections.pop(idx) - - # ─── Bulk Edit Operations ──────────────────────────────────────────── def bulk_edit_talkgroups(prs, set_name, enable_scan=None, enable_tx=None, @@ -1670,19 +1565,7 @@ def set_p25_conv_nac(prs, set_name, channel_index, nac_tx=None, nac_rx=None): raise ValueError(f"NAC RX {nac_rx:#x} out of range (0-FFF)") ch.nac_rx = nac_rx - # Rebuild sections - new_ch_raw = build_p25_conv_channel_section(existing_sets, byte1, byte2) - new_set_raw = build_p25_conv_set_section( - len(existing_sets[0].channels), set_byte1, set_byte2) - - ch_idx = _find_section_index(prs, "CP25ConvChannel") - set_idx = _find_section_index(prs, "CP25ConvSet") - if ch_idx < 0 or set_idx < 0: - raise ValueError("CP25ConvChannel or CP25ConvSet section not found") - prs.sections[ch_idx] = Section(offset=0, raw=new_ch_raw, - class_name="CP25ConvChannel") - prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, - class_name="CP25ConvSet") + _replace_p25_conv_sections(prs, existing_sets) logger.info("Set NAC on channel %d in '%s' (tx=%s, rx=%s)", channel_index, set_name, @@ -1706,25 +1589,17 @@ def reorder_preferred_entries(prs, new_order): Raises: ValueError: if new_order doesn't match existing entries. """ - from .record_types import ( - parse_preferred_section, build_preferred_section, - ) - - pref_idx = _find_section_index(prs, "CPreferredSystemTableEntry") - if pref_idx < 0: + doc = archive.document_from_prs(prs) + system = _first_ecc_system(doc) + if system is None: return False - - sec = prs.sections[pref_idx] - entries, iden, tail, chain, ctype = parse_preferred_section(sec.raw) + entries = _preferred_entries_of(system) if len(new_order) != len(entries): raise ValueError( f"new_order has {len(new_order)} items but there are " f"{len(entries)} entries") - # Preserve the last_sep from the original last entry - original_last_sep = entries[-1].last_sep - # Build a map of system_id -> entry entry_map = {} for e in entries: @@ -1742,14 +1617,10 @@ def reorder_preferred_entries(prs, new_order): entry.field2 = i reordered.append(entry) - # Transfer the original last_sep to the new last entry - reordered[-1].last_sep = original_last_sep - - # Rebuild section preserving tail - new_raw = build_preferred_section(reordered, tail_bytes=tail) - prs.sections[pref_idx] = Section( - offset=0, raw=new_raw, - class_name="CPreferredSystemTableEntry") + system.lists()[0].items = [ + Obj("CPreferredSystemTableEntry", [e.to_bytes()[:13]]) + for e in reordered] + archive.write_document(prs, doc) logger.info("Reordered %d preferred entries", len(reordered)) return True @@ -2520,55 +2391,25 @@ def clone_system(target, source, system_long_name): return result -def _find_system_type(prs, data_sec): - """Determine the system class type that owns a data section. - - Walks the section list to find the nearest preceding class header - (CP25TrkSystem, CConvSystem, CP25ConvSystem) before the data section. - """ - target_idx = None - for i, sec in enumerate(prs.sections): - if sec is data_sec: - target_idx = i - break - - if target_idx is None: - return None - - # Walk backwards to find the owning header - for i in range(target_idx - 1, -1, -1): - sec = prs.sections[i] - if sec.class_name in ('CP25TrkSystem', 'CConvSystem', - 'CP25ConvSystem'): - return sec.class_name - # If we hit a different class header, stop - if sec.class_name and sec.class_name not in ( - 'CP25TrkSystem', 'CConvSystem', 'CP25ConvSystem'): - break - +def _system_ref_for(prs, data_sec): + from .record_types import list_system_configs + for ref in list_system_configs(prs): + if ref.section is data_sec: + return ref return None -def _find_system_short_name(prs, data_sec): - """Find the short name of the system header that owns a data section.""" - target_idx = None - for i, sec in enumerate(prs.sections): - if sec is data_sec: - target_idx = i - break - - if target_idx is None: - return None +def _find_system_type(prs, data_sec): + """The system class (CP25TrkSystem, CConvSystem, CP25ConvSystem) that + owns a config data section, from the type byte in front of it.""" + ref = _system_ref_for(prs, data_sec) + return ref.class_name if ref else None - for i in range(target_idx - 1, -1, -1): - sec = prs.sections[i] - if sec.class_name in ('CP25TrkSystem', 'CConvSystem', - 'CP25ConvSystem'): - return parse_system_short_name(sec.raw) - if sec.class_name: - break - return None +def _find_system_short_name(prs, data_sec): + """The short name of the system that owns a config data section.""" + ref = _system_ref_for(prs, data_sec) + return ref.short_name if ref else None # ─── Channel Numbering & Auto-Naming ───────────────────────────────── diff --git a/quickprs/json_io.py b/quickprs/json_io.py index a2eb7cd..27d3e75 100644 --- a/quickprs/json_io.py +++ b/quickprs/json_io.py @@ -24,7 +24,7 @@ parse_system_short_name, parse_system_long_name, parse_system_wan_name, parse_system_set_refs, is_system_config_data, parse_ecc_entries, - parse_sets_from_sections, + parse_sets_from_sections, list_system_configs, ) from .option_maps import extract_platform_config @@ -214,33 +214,11 @@ def _collect_systems(prs): 'CConvSystem': 'Conventional', 'CP25ConvSystem': 'P25Conv', } - - current_type = None - current_name = None - - for sec in prs.sections: - if sec.class_name in system_class_map: - current_type = system_class_map[sec.class_name] - current_name = parse_system_short_name(sec.raw) or "" - elif (not sec.class_name and is_system_config_data(sec.raw) - and current_type is not None): - sys_dict = _config_to_sys_dict(sec.raw, current_type) - # Use the header short name for the first config after a header - if current_name is not None: - sys_dict["name"] = current_name - current_name = None # consumed - else: - # Chained inline system — derive name from long_name - ln = sys_dict.get("long_name", "") - sys_dict["name"] = ln[:8] if ln else "" - systems.append(sys_dict) - elif sec.class_name and sec.class_name not in ( - 'CPreferredSystemTableEntry', - ): - # Non-config named section breaks the chain - current_type = None - current_name = None - + for ref in list_system_configs(prs): + sys_dict = _config_to_sys_dict(ref.section.raw, + system_class_map[ref.class_name]) + sys_dict["name"] = ref.short_name + systems.append(sys_dict) return systems diff --git a/quickprs/prs_parser.py b/quickprs/prs_parser.py index f0d2131..9ed15d1 100644 --- a/quickprs/prs_parser.py +++ b/quickprs/prs_parser.py @@ -7,6 +7,7 @@ from dataclasses import dataclass, field from pathlib import Path +import struct from .binary_io import find_all_ffff, try_read_class_name @@ -21,10 +22,16 @@ class Section: @dataclass class PRSFile: - """Parsed .PRS file — ordered list of sections.""" + """Parsed .PRS file — ordered list of sections. + + ``archive_ok`` records whether the bytes followed RPM's archive layout + when they were loaded (see archive.py); write_prs uses it to refuse an + edit that broke a readable file. + """ sections: list = field(default_factory=list) filepath: str = "" file_size: int = 0 + archive_ok: object = None def get_sections_by_class(self, class_name): """Get all sections with a given class name.""" @@ -52,6 +59,30 @@ def summary(self): return "\n".join(lines) +# Classes whose objects hold user values (talkgroup and key IDs, unit IDs, +# frequencies) that can contain the bytes FF FF. The splitter would start +# a new section there; such pieces belong to the section before them. +_JOIN_CONTINUATIONS = frozenset({ + "CTrunkChannel", "CConvChannel", "CP25Group", "CP25ConvChannel", + "CDefaultIdenElem", "CICall", "CPhoneCall", "CP25TrkWan", +}) + + +def _join_continuations(sections): + joined = [] + for sec in sections: + if (joined and not sec.class_name and + joined[-1].class_name in _JOIN_CONTINUATIONS and + sec.raw != b'\xff\xff' and + not sec.raw.startswith(b'\xff\xff\x00\x01')): + prev = joined[-1] + joined[-1] = Section(offset=prev.offset, raw=prev.raw + sec.raw, + class_name=prev.class_name) + else: + joined.append(sec) + return joined + + def parse_prs(filepath): """Parse a .PRS file into an ordered list of sections. @@ -86,17 +117,29 @@ def parse_prs(filepath): )) prs = PRSFile( - sections=sections, + sections=_join_continuations(sections), filepath=str(path), file_size=len(data), + archive_ok=_archive_readable(data), ) return prs -def parse_prs_bytes(data): +def _archive_readable(data): + from .archive import read_document, WalkError + try: + read_document(data, lenient=True) + return True + except (WalkError, IndexError, UnicodeDecodeError, struct.error): + return False + + +def parse_prs_bytes(data, verify=True): """Parse PRS data from raw bytes (no file I/O). Used for undo/restore operations where we have the bytes in memory. + ``verify=False`` skips the archive check (for callers that only want + the sections of bytes they just serialized). """ markers = find_all_ffff(data) @@ -120,7 +163,8 @@ def parse_prs_bytes(data): )) return PRSFile( - sections=sections, + sections=_join_continuations(sections), filepath="(from bytes)", file_size=len(data), + archive_ok=_archive_readable(data) if verify else None, ) diff --git a/quickprs/prs_writer.py b/quickprs/prs_writer.py index b9292d9..85cd541 100644 --- a/quickprs/prs_writer.py +++ b/quickprs/prs_writer.py @@ -1,16 +1,52 @@ """PRS file writer — reassembles sections back to binary. -For Sprint 1, this is trivial: concatenate all section raw bytes. -Guaranteed byte-identical roundtrip because we preserve raw bytes. +Before writing, the archive is walked (see archive.py): every MFC class tag +and list count is set to what RPM expects, so a personality edited by any +code path still opens in RPM. An edit that leaves a previously readable +file in a state the walker cannot follow is refused instead of written. """ import logging from pathlib import Path import shutil +from . import archive + logger = logging.getLogger("quickprs") +class UnsafeWriteError(ValueError): + """The personality would not open in RPM, so it was not written.""" + + +def prepare_for_write(prs_file): + """Fix class tags and list counts in place; return the bytes to write. + + Raises UnsafeWriteError when the file was readable when it was loaded + (or built) but no longer is. Files QuickPRS could never follow (an + unknown RPM layout) are passed through unchanged with a warning, as + before. + """ + data = prs_file.to_bytes() + try: + fixed = archive.repair_bytes(data) + except archive.WalkError as e: + if getattr(prs_file, "archive_ok", None): + raise UnsafeWriteError( + f"not written: after this edit the personality no longer " + f"follows RPM's file structure ({e})") from e + logger.warning("Archive structure not verified (%s); writing the " + "file unchanged", e) + return data + if fixed != data: + from .prs_parser import parse_prs_bytes + logger.info("Rewrote archive class tags and list counts") + prs_file.sections = parse_prs_bytes(fixed, verify=False).sections + prs_file.file_size = len(fixed) + prs_file.archive_ok = True + return fixed + + def write_prs(prs_file, filepath, backup=True): """Write a PRSFile back to disk. @@ -19,8 +55,13 @@ def write_prs(prs_file, filepath, backup=True): filepath: output path backup: if True and file exists, create .bak backup first Also creates a timestamped backup via the backup module. + + Raises: + UnsafeWriteError: the edit broke the file's structure; nothing was + written. """ path = Path(filepath) + data = prepare_for_write(prs_file) if backup and path.exists(): bak = path.with_suffix(path.suffix + '.bak') @@ -33,6 +74,5 @@ def write_prs(prs_file, filepath, backup=True): except Exception as e: logger.debug("Auto-backup skipped: %s", e) - data = prs_file.to_bytes() path.write_bytes(data) return len(data) diff --git a/quickprs/record_types.py b/quickprs/record_types.py index d15e567..4b660c7 100644 --- a/quickprs/record_types.py +++ b/quickprs/record_types.py @@ -42,6 +42,19 @@ _MARKER_BYTE2_VALUES = frozenset({0x80, 0x81, 0x82, 0x83}) +def is_class_tag(word_bytes): + """True for a 2-byte MFC class tag (0x8000 | class index). + + The index depends on how many objects precede the class in the file + (see archive.py), so parsers must not compare against fixed values such + as the ones observed in PAWSOVERMAWS.PRS. + """ + if len(word_bytes) < 2: + return False + w = word_bytes[0] | (word_bytes[1] << 8) + return bool(w & 0x8000) and w not in (0xFFFF, 0x7FFF) + + def _is_record_marker(data, pos): """Check if data[pos:pos+2] looks like a valid record/set marker. @@ -51,12 +64,17 @@ def _is_record_marker(data, pos): """ if pos + 6 > len(data): return False - if data[pos + 1] not in _MARKER_BYTE2_VALUES: + # Class indices past 1023 put 0x84 and up in the second byte, so any + # tag value is accepted (large personalities used to stop parsing + # here). The set class is always defined before its item class, so + # the set tag is the smaller one, and the item count is bounded. + if not (is_class_tag(data[pos:pos + 2]) and + is_class_tag(data[pos + 4:pos + 6])): return False - # Also verify the separator 2 bytes after the count - if data[pos + 5] not in _MARKER_BYTE2_VALUES: - return False - return True + set_tag = data[pos] | (data[pos + 1] << 8) + count = data[pos + 2] | (data[pos + 3] << 8) + item_tag = data[pos + 4] | (data[pos + 5] << 8) + return set_tag < item_tag and count <= 2048 # Class header byte1 values (record type IDs) @@ -1509,7 +1527,8 @@ def to_bytes(self): @classmethod def from_bytes(cls, data, offset=0): """Parse from 15 bytes at the given offset.""" - if data[offset:offset + 2] != ECC_MARKER: + if offset + ECC_ENTRY_SIZE > len(data) or \ + not is_class_tag(data[offset:offset + 2]): return None entry_type = data[offset + 2] system_id = struct.unpack_from(' len(raw_section): continue - if raw_section[ecc_start:ecc_start + 2] != ECC_MARKER: + tag = raw_section[ecc_start:ecc_start + 2] + if not is_class_tag(tag): continue # Verify all entries fit @@ -1558,11 +1578,13 @@ def parse_ecc_entries(raw_section): if ecc_end > len(raw_section): continue - # Parse entries — all must have valid 09 80 marker + # Parse entries — all are objects of one class, so they share a tag entries = [] for i in range(count): - entry = EnhancedCCEntry.from_bytes( - raw_section, ecc_start + i * ECC_ENTRY_SIZE) + at = ecc_start + i * ECC_ENTRY_SIZE + if raw_section[at:at + 2] != tag: + break + entry = EnhancedCCEntry.from_bytes(raw_section, at) if entry: entries.append(entry) else: @@ -1663,9 +1685,11 @@ def parse_preferred_section(raw): # Parse class header to find data start _, _, _, data_start = parse_class_header(raw, 0) - # Parse entries until we hit a non-09-80 separator or end + # Parse entries; each later entry starts with the class tag of + # CPreferredSystemTableEntry, whatever its index is in this file. entries = [] pos = data_start + entry_tag = None while pos + PREF_ENTRY_SIZE <= len(raw): entry = PreferredSystemEntry.from_bytes(raw, pos) if entry is None: @@ -1674,7 +1698,9 @@ def parse_preferred_section(raw): # Check separator (last 2 bytes of this 15-byte entry) sep = raw[pos + 13:pos + 15] pos += PREF_ENTRY_SIZE - if sep != PREF_SEP: + if entry_tag is None and is_class_tag(sep): + entry_tag = sep + if sep != entry_tag: break # last entry # Everything after entries is the tail @@ -1688,21 +1714,12 @@ def parse_preferred_section(raw): tail_pos = pos + 2 # skip 2-byte gap if tail_pos < len(raw): iden_name, tail_pos = read_lps(raw, tail_pos) - # Look for chain marker at the end: 07 80 + LPS + type - # The 63-byte post-ECC tail sits between IDEN and chain - for scan in range(len(raw) - 4, pos, -1): - if raw[scan:scan + 2] == b'\x07\x80': - name_len = raw[scan + 2] - if (0 < name_len <= 8 and - scan + 3 + name_len < len(raw)): - try: - chain_name = raw[ - scan + 3:scan + 3 + name_len - ].decode('ascii') - chain_type = raw[scan + 3 + name_len] - except (UnicodeDecodeError, IndexError): - pass - break + # The next system's header can follow the 63-byte post-ECC tail: + # class tag + LPS(name) + type byte, at the very end of the section. + # Only a following P25 trunked system counts as the chain. + owner = system_header_at_end(raw) + if owner and owner[0] == 0x05 and owner[2] >= pos + 2: + chain_type, chain_name = owner[0], owner[1] except (IndexError, ValueError): pass @@ -1884,6 +1901,33 @@ def build_data_section(self): return b''.join(parts) + def object_parts(self): + """The system's archive data as ``(head, ecc_payloads, rest)``. + + ``head`` runs from the short name to the ECC list marker, the ECC + payloads are each entry's 13 data bytes, and ``rest`` holds the + fields after the list. Tags and counts are left to the archive + writer (see archive.py), so ``ecc_count_override`` and the chain + fields do not apply here. + """ + saved = (self.ecc_entries, self.ecc_count_override, + self.iden_set_name, self.next_system_name) + try: + self.ecc_entries = [] + self.ecc_count_override = None + self.iden_set_name = "" + self.next_system_name = "" + config = self.build_data_section() + finally: + (self.ecc_entries, self.ecc_count_override, + self.iden_set_name, self.next_system_name) = saved + # build_data_section ends with 0x06 + uint16(count); drop the count + head = write_lps(self.system_name) + b'\x05' + config[:-2] + ecc = [e.to_bytes()[2:] for e in self.ecc_entries] + rest = (b'\x00' * 4 + write_lps(self.iden_set_name[:8]) + + _build_post_ecc_tail(self.post_ecc_float)) + return head, ecc, rest + @dataclass class ConvSystemConfig: @@ -1938,6 +1982,17 @@ def build_data_section(self): parts.append(struct.pack('B', self.next_system_type)) return b''.join(parts) + def object_data(self): + """The system's archive data (short name to last field), without + the next system's header (the archive writer adds that).""" + saved = self.next_system_name + try: + self.next_system_name = "" + config = self.build_data_section() + finally: + self.next_system_name = saved + return write_lps(self.system_name) + b'\x01' + config + # CP25ConvSystem trailing section template (28 bytes after ffff marker) _P25CONV_TRAILING = ( @@ -1987,6 +2042,14 @@ def build_trailing_section(self): """Build the second data section that follows CP25ConvSystem config.""" return SECTION_MARKER + _P25CONV_TRAILING + def object_data(self): + """The system's archive data. The last two bytes of the old + trailing section are the next list's count, not part of the + system, so they are left out.""" + return (write_lps(self.system_name) + b'\x03' + + self.build_data_section() + + SECTION_MARKER + _P25CONV_TRAILING[:-2]) + def parse_system_long_name(raw): """Extract the long display name from a system config data section. @@ -2086,6 +2149,70 @@ def parse_system_short_name(raw): return None +def system_header_at_end(raw): + """Find a system object's opening bytes at the end of ``raw``. + + A system's config block (FF FF + prefix) is preceded by its short name + and a type byte (0x01 conventional, 0x03 P25 conventional, 0x05 P25 + trunked), so a section split at that FF FF ends with LPS(name) + type. + Returns ``(type_byte, name, offset_of_name_length)`` or None. + """ + if not raw or raw[-1] not in (0x01, 0x03, 0x05): + return None + # A length byte below 32 cannot be a name character, so the smallest + # matching length is the real one. + for n in range(0, min(32, len(raw) - 1)): + at = len(raw) - 2 - n + if at < 0: + break + if raw[at] == n and all(32 <= c < 127 for c in raw[at + 1:-1]): + return raw[-1], raw[at + 1:-1].decode('ascii'), at + return None + + +SYSTEM_TYPE_CLASS_NAMES = { + 0x01: 'CConvSystem', + 0x03: 'CP25ConvSystem', + 0x05: 'CP25TrkSystem', +} + + +@dataclass +class SystemConfigRef: + """One system in file order (see list_system_configs).""" + class_name: str # CConvSystem / CP25TrkSystem / CP25ConvSystem + short_name: str + index: int # index of the config data section in prs.sections + section: object # that Section (raw = FF FF + config ...) + + @property + def long_name(self): + return parse_system_long_name(self.section.raw) or "" + + +def list_system_configs(prs): + """Every system's config data section, in file order, with its class. + + Only the first system of each class is written with a class header; + later ones start with a 2-byte tag (see archive.py), so "the last class + header seen" does not tell a system's type. The bytes just before each + config block do: the short name and a type byte. + """ + refs = [] + for i in range(1, len(prs.sections)): + sec = prs.sections[i] + if sec.class_name or not sec.raw.startswith(b'\xff\xff'): + continue + owner = system_header_at_end(prs.sections[i - 1].raw) + if owner is None or len(sec.raw) < 44: + continue + if not is_system_config_data(sec.raw) and sec.raw[2:4] != b'\x01\x01': + continue + refs.append(SystemConfigRef(SYSTEM_TYPE_CLASS_NAMES[owner[0]], + owner[1], i, sec)) + return refs + + def is_system_config_data(raw): """Check if a data section is a system config (P25 trunk/conv/P25conv). @@ -2518,9 +2645,9 @@ def parse_wan_section(raw): entry, pos = P25TrkWanEntry.parse(raw, pos) entries.append(entry) - # Check for separator (31 82) - if pos + 2 <= len(raw) and raw[pos:pos + 2] == WAN_ENTRY_SEP: - pos += 2 # skip separator + # Later entries start with the CP25TrkWan class tag + if pos + 2 <= len(raw) and is_class_tag(raw[pos:pos + 2]): + pos += 2 # skip tag else: break # last entry or end of data diff --git a/quickprs/repair.py b/quickprs/repair.py index 993c183..a7e3bea 100644 --- a/quickprs/repair.py +++ b/quickprs/repair.py @@ -86,9 +86,32 @@ def repair_prs(prs, issues=None): Returns: (repaired_prs, list_of_repairs_made) + + A file whose archive structure can be followed (see archive.py) only + gets its class tags and list counts rewritten; the section surgery + below is for files that cannot be followed at all. """ + from . import archive + repairs = [] + try: + problems = archive.check(prs) + except archive.WalkError: + problems = None + if problems is not None: + if problems: + tags = sum(1 for p in problems if "tag" in p.message) + counts = len(problems) - tags + archive.repair(prs) + repairs.append( + f"Rewrote {tags} class tag(s) and {counts} list count(s) " + f"so RPM can load the file") + # The walk treats the fields after the IDEN sets as opaque, so a + # cut-off terminator there is still worth completing. + _fix_terminator(prs, repairs) + return prs, repairs + # 1. Fix missing CPersonality personality = prs.get_section_by_class("CPersonality") if not personality: @@ -131,21 +154,14 @@ def repair_prs(prs, issues=None): parts = [f"{name} (x{count})" for name, count in counts.items()] repairs.append(f"Removed duplicate sections: {', '.join(parts)}") - # 4. Remove orphan system config data sections - header_types = {"CP25TrkSystem", "CConvSystem", "CP25ConvSystem"} + # 4. Remove orphan system config data sections: every real config block + # is preceded by its system's short name and type byte. + from .record_types import system_header_at_end to_remove = [] for i, sec in enumerate(prs.sections): if not sec.class_name and is_system_config_data(sec.raw): - found_header = False - for j in range(i - 1, -1, -1): - if prs.sections[j].class_name in header_types: - found_header = True - break - if prs.sections[j].class_name == "CPreferredSystemTableEntry": - continue - if not prs.sections[j].class_name: - continue - break + found_header = (i > 0 and system_header_at_end( + prs.sections[i - 1].raw) is not None) if not found_header: long = parse_system_long_name(sec.raw) or "(unknown)" to_remove.append(i) @@ -190,6 +206,17 @@ def repair_prs(prs, issues=None): if prs.sections: _fix_terminator(prs, repairs) + # If the surgery left a structure the archive walker can follow, set + # its tags and counts the way RPM expects. + try: + if archive.check(prs): + archive.repair(prs) + repairs.append("Rewrote class tags and list counts so RPM can " + "load the file") + except archive.WalkError: + repairs.append("File structure still not recognized; RPM may not " + "open it") + # Recalculate offsets offset = 0 for sec in prs.sections: diff --git a/quickprs/reports.py b/quickprs/reports.py index ea6109b..4278da7 100644 --- a/quickprs/reports.py +++ b/quickprs/reports.py @@ -265,36 +265,23 @@ def _add_systems(parts, prs): parts.append("NameType" "Long NameSize") - for cls, label in system_types: - secs = prs.get_sections_by_class(cls) - if not secs: - continue - for sec in secs: - short = parse_system_short_name(sec.raw) or "(unnamed)" - parts.append(f"{_esc(short)}{_esc(label)}" - f"{len(sec.raw):,} bytes") - - # Config data sections - current_type = None - for sec_obj in prs.sections: - if sec_obj.class_name == cls: - current_type = cls - continue - if (not sec_obj.class_name and current_type == cls - and is_system_config_data(sec_obj.raw)): - long_name = parse_system_long_name(sec_obj.raw) or "" - wan_name = "" - try: - wan_name = parse_system_wan_name(sec_obj.raw) or "" - except Exception: - pass - detail = long_name - if wan_name: - detail += f" (WACN: {wan_name})" - parts.append( - f"{_esc(label)} Config" - f"{_esc(detail)}" - f"{len(sec_obj.raw):,} bytes") + from .record_types import list_system_configs + labels = dict(system_types) + # One row per system, in file order (the order the radio shows them). + for ref in list_system_configs(prs): + label = labels.get(ref.class_name, ref.class_name) + wan_name = "" + try: + wan_name = parse_system_wan_name(ref.section.raw) or "" + except Exception: + pass + detail = ref.long_name + if wan_name and ref.class_name == 'CP25TrkSystem': + detail += f" (WAN: {wan_name})" + parts.append( + f"{_esc(ref.short_name or '(unnamed)')}" + f"{_esc(label)}{_esc(detail)}" + f"{len(ref.section.raw):,} bytes") parts.append("") diff --git a/quickprs/validation.py b/quickprs/validation.py index 10c228a..107bf1c 100644 --- a/quickprs/validation.py +++ b/quickprs/validation.py @@ -1198,6 +1198,20 @@ def validate_structure(prs): issues = [] + # 0. MFC archive structure: the one thing RPM itself checks on load. + from . import archive + archive_readable = False + try: + for problem in archive.check(prs): + issues.append((ERROR, + f"RPM will not open this file: {problem.message} " + f"(offset 0x{problem.offset:x}). Run 'quickprs repair " + f"' or save it again with this version to fix it.")) + archive_readable = True + except archive.WalkError as e: + issues.append((ERROR, + f"File structure not recognized ({e}). RPM may not open it.")) + # 1. CPersonality must be present and first personality = prs.get_section_by_class("CPersonality") if not personality: @@ -1209,32 +1223,23 @@ def validate_structure(prs): "CPersonality is not the first section " f"(found at index {next(i for i, s in enumerate(prs.sections) if s.class_name == 'CPersonality')})")) - # 2. At least one system + # 2. At least one system. RPM itself saves personalities without any + # (a new radio file), so this is a warning, not an error. system_classes = ['CP25TrkSystem', 'CConvSystem', 'CP25ConvSystem'] total_systems = sum(len(prs.get_sections_by_class(c)) for c in system_classes) if total_systems == 0: - issues.append((ERROR, - "No system sections found — file must contain at least one " - "CConvSystem, CP25TrkSystem, or CP25ConvSystem")) + issues.append((WARNING, + "No systems defined: the radio will have no channels or " + "talkgroups to select")) - # 3. System config data sections must follow a system header - header_types = {'CP25TrkSystem', 'CConvSystem', 'CP25ConvSystem'} + # 3. Every system config block is preceded by its system's short name + # and type byte (whether the system opens with a class header or a + # tag), so a config without them is an orphan. + from .record_types import system_header_at_end for i, sec in enumerate(prs.sections): if not sec.class_name and is_system_config_data(sec.raw): - # Walk backward to find the nearest system header - found_header = False - for j in range(i - 1, -1, -1): - if prs.sections[j].class_name in header_types: - found_header = True - break - # CPreferredSystemTableEntry can appear between header and data - if prs.sections[j].class_name == 'CPreferredSystemTableEntry': - continue - # Other unnamed data sections (small continuations) are OK - if not prs.sections[j].class_name: - continue - # Hit a different class section — no header found - break + found_header = (i > 0 and system_header_at_end( + prs.sections[i - 1].raw) is not None) if not found_header: long = parse_system_long_name(sec.raw) or "(unknown)" issues.append((ERROR, @@ -1246,13 +1251,15 @@ def validate_structure(prs): if not sec.class_name and is_system_config_data(sec.raw): actual_prefix = sec.raw[2:44] if actual_prefix != SYSTEM_CONFIG_PREFIX: + # These bytes hold system options QuickPRS has not decoded, + # so a difference means "not RPM's defaults", not damage. long = parse_system_long_name(sec.raw) or "(unknown)" diffs = [j for j in range(len(SYSTEM_CONFIG_PREFIX)) if j < len(actual_prefix) and actual_prefix[j] != SYSTEM_CONFIG_PREFIX[j]] - issues.append((ERROR, - f"System config '{long}' at index {i} has " - f"corrupted prefix (differs at {len(diffs)} byte positions)")) + issues.append((INFO, + f"System config '{long}' at index {i} differs from " + f"RPM's default option bytes at {len(diffs)} positions")) # 5. Cross-reference: system config set names must resolve _validate_set_crossrefs(prs, issues, parse_system_set_refs, parse_system_long_name) @@ -1290,8 +1297,10 @@ def validate_structure(prs): except Exception as e: logger.debug("ConvSet metadata check failed: %s", e) - # 8. Required companion sections - _validate_companion_sections(prs, issues) + # 8. Required companion sections (the archive walk above already + # proves the structure when it succeeds) + if not archive_readable: + _validate_companion_sections(prs, issues) return issues diff --git a/tests/test_archive.py b/tests/test_archive.py new file mode 100644 index 0000000..a448642 --- /dev/null +++ b/tests/test_archive.py @@ -0,0 +1,232 @@ +"""Tests for the MFC CArchive layer (quickprs/archive.py). + +RPM loads a personality with CArchive, which rejects a class tag that does +not name the class it expects and reads every list by its WORD count. These +tests check that every file QuickPRS writes keeps both right, and that the +reader follows RPM-saved files exactly. +""" + +import struct +from pathlib import Path + +import pytest + +from quickprs import archive, injector +from quickprs.archive import Obj, ObjList +from quickprs.builder import create_blank_prs +from quickprs.prs_parser import parse_prs, parse_prs_bytes +from quickprs.record_types import ( + P25TrkSystemConfig, ConvSystemConfig, P25ConvSystemConfig, + list_system_configs, +) + +TESTDATA = Path(__file__).parent / "testdata" +PAWS = TESTDATA / "PAWSOVERMAWS.PRS" +CLAUDE = TESTDATA / "claude test.PRS" +RPM_FILES = sorted([p for p in (PAWS, CLAUDE) if p.exists()] + + list((TESTDATA / "every option").glob("*.PRS"))) + + +def _sets(n_groups=2, name="G"): + return injector.make_group_set( + name, [(100 + i, f"TG{i}", f"TALKGROUP {i}") for i in range(n_groups)]) + + +# ─── Reading RPM-saved files ───────────────────────────────────────── + +@pytest.mark.skipif(not RPM_FILES, reason="RPM test files not available") +@pytest.mark.parametrize("path", RPM_FILES, ids=lambda p: p.name[:40]) +def test_rpm_file_round_trips_through_tree(path): + """Reading an RPM file into the tree and writing it back regenerates + every header, tag and count byte for byte.""" + data = path.read_bytes() + for lenient in (False, True): + doc, _ = archive.read_document(data, lenient=lenient) + assert archive.serialize(doc) == data + + +@pytest.mark.skipif(not RPM_FILES, reason="RPM test files not available") +@pytest.mark.parametrize("path", RPM_FILES, ids=lambda p: p.name[:40]) +def test_rpm_file_is_consistent(path): + assert archive.check_bytes(path.read_bytes()) == [] + + +@pytest.mark.skipif(not PAWS.exists(), reason="PAWSOVERMAWS.PRS not available") +def test_paws_class_indices(): + """The indices RPM used (seen in the file's tags) are the ones the map + counting gives: one index per class and per object.""" + _, rep = archive.read_document(PAWS.read_bytes()) + idx = rep.class_index + assert idx["CTrunkSet"] == 104 + assert idx["CTrunkChannel"] == 106 + assert idx["CConvSet"] == 403 # 106 + 290 channels + 6 sets + 1 + assert idx["CConvChannel"] == 405 + assert idx["CP25GroupSet"] == 655 + assert idx["CP25Group"] == 657 + assert idx["CIdenDataSet"] == 905 # 657 + 241 groups + 6 sets + 1 + assert idx["CDefaultIdenElem"] == 907 + assert len(rep.tags) == 859 + + +@pytest.mark.skipif(not PAWS.exists(), reason="PAWSOVERMAWS.PRS not available") +def test_paws_list_counts(): + doc = archive.document_from_prs(parse_prs(PAWS)) + counts = {name: len(doc.list(name).items) for name in ( + "systems", "trunk sets", "conv sets", "options", "group sets", + "P25 conv sets", "IDEN sets")} + assert counts == {"systems": 13, "trunk sets": 7, "conv sets": 3, + "options": 33, "group sets": 7, "P25 conv sets": 0, + "IDEN sets": 3} + + +def test_serializer_tags_and_counts(): + """First object of a class gets a header, later ones a tag naming the + class index; lists carry their count.""" + root = Obj("CPersonality", [ + b"\x00" * 0, + ObjList("things", [Obj("CTrunkSet", [b"A"]), + Obj("CTrunkSet", [b"B"]), + None]), + ]) + out = archive.serialize(archive.Document(root)) + hdr = struct.pack("= 2, f"Expected at least 2 sections removed, got {removed}" - assert len(prs.sections) == original_count - removed + assert removed == 1, f"Expected 1 system removed, got {removed}" + assert len(prs.sections) < original_count - # CConvSystem header should be gone + # CConvSystem header should be gone, the other systems kept assert prs.get_section_by_class("CConvSystem") is None + after = [r.short_name for r in list_system_configs(prs)] + assert after == [n for n in before if n != "convent"] + assert archive.check(prs) == [] # Double roundtrip tmp = TESTDATA / "remove_class_test.tmp" @@ -1177,80 +1184,78 @@ def test_add_conv_set_no_existing_raises(): # ─── Create-from-scratch tests (via add_p25_trunked_system) ───────── +def _claude_without(list_name): + """claude test.PRS with one set list emptied the way RPM would store it + (a count of 0), not by deleting the sections holding it.""" + from quickprs import archive + prs = cached_parse_prs(TESTDATA / "claude test.PRS") + doc = archive.document_from_prs(prs) + doc.list(list_name).items = [] + archive.write_document(prs, doc) + return prs + + +def _new_p25_config(**kw): + return P25TrkSystemConfig(system_name="NEW", long_name="NEW SYSTEM", + trunk_set_name="NEW", group_set_name="NEW", + wan_name="NEW", **kw) + + @pytest.mark.skipif(not CLAUDE.exists(), reason="Test PRS data not available") def test_create_trunk_from_scratch(): - """Injecting a system with trunk set into a file without trunk sections - should create them from scratch via _safe_add_trunk_set.""" - prs = cached_parse_prs(TESTDATA / "claude test.PRS") - # Remove trunk sections - prs.sections = [s for s in prs.sections - if s.class_name not in ("CTrunkChannel", "CTrunkSet")] + """Injecting a system with a trunk set into a personality without trunk + sets creates the first one (class header, count and tags right).""" + from quickprs import archive + prs = _claude_without("trunk sets") assert prs.get_section_by_class("CTrunkChannel") is None ts = make_trunk_set("NEW", [(851.0125, 851.0125), (851.5125, 851.5125)]) - config = P25TrkSystemConfig( - system_name="NEW", - long_name="NEW SYSTEM", - trunk_set_name="NEW", - group_set_name="NEW", - wan_name="NEW", - ) - add_p25_trunked_system(prs, config, trunk_set=ts) + add_p25_trunked_system(prs, _new_p25_config(), trunk_set=ts) - # Should now have trunk sections assert prs.get_section_by_class("CTrunkChannel") is not None assert prs.get_section_by_class("CTrunkSet") is not None + assert archive.check(prs) == [] + doc = archive.document_from_prs(prs) + assert len(doc.list("trunk sets").items) == 1 @pytest.mark.skipif(not CLAUDE.exists(), reason="Test PRS data not available") def test_create_group_from_scratch(): - """Injecting a system with group set into a file without group sections - should create them from scratch.""" - prs = cached_parse_prs(TESTDATA / "claude test.PRS") - prs.sections = [s for s in prs.sections - if s.class_name not in ("CP25Group", "CP25GroupSet")] + """Injecting a system with a group set into a personality without group + sets creates the first one.""" + from quickprs import archive + prs = _claude_without("group sets") assert prs.get_section_by_class("CP25Group") is None gs = make_group_set("NEW", [(100, "TEST", "TEST TG"), (200, "TEST2", "TEST TG 2")]) - config = P25TrkSystemConfig( - system_name="NEW", - long_name="NEW SYSTEM", - trunk_set_name="NEW", - group_set_name="NEW", - wan_name="NEW", - ) - add_p25_trunked_system(prs, config, group_set=gs) + add_p25_trunked_system(prs, _new_p25_config(), group_set=gs) assert prs.get_section_by_class("CP25Group") is not None assert prs.get_section_by_class("CP25GroupSet") is not None + assert archive.check(prs) == [] @pytest.mark.skipif(not CLAUDE.exists(), reason="Test PRS data not available") def test_create_iden_from_scratch(): - """Injecting a system with IDEN set into a file without IDEN sections - should create them from scratch.""" - prs = cached_parse_prs(TESTDATA / "claude test.PRS") - prs.sections = [s for s in prs.sections - if s.class_name not in ("CDefaultIdenElem", "CIdenDataSet")] + """Injecting a system with an IDEN set into a personality without IDEN + sets creates the first one and keeps the fields after the list.""" + from quickprs import archive + prs = _claude_without("IDEN sets") + tail = archive.document_from_prs(prs).root.parts[-1] assert prs.get_section_by_class("CDefaultIdenElem") is None iset = make_iden_set("NEW", [ {"base_freq_hz": 851012500, "chan_spacing_hz": 12500, "bandwidth_hz": 12500, "tx_offset_mhz": -45.0, "iden_type": 0}, ]) - config = P25TrkSystemConfig( - system_name="NEW", - long_name="NEW SYSTEM", - trunk_set_name="NEW", - group_set_name="NEW", - wan_name="NEW", - iden_set_name="NEW", - ) - add_p25_trunked_system(prs, config, iden_set=iset) + add_p25_trunked_system(prs, _new_p25_config(iden_set_name="NEW"), + iden_set=iset) assert prs.get_section_by_class("CDefaultIdenElem") is not None assert prs.get_section_by_class("CIdenDataSet") is not None + assert archive.check(prs) == [] + assert archive.document_from_prs(prs).root.parts[-1] == tail # ─── WAN Auto-Update Tests ────────────────────────────────────────────── diff --git a/tests/test_prs_writer.py b/tests/test_prs_writer.py index 26783dc..1c642a4 100644 --- a/tests/test_prs_writer.py +++ b/tests/test_prs_writer.py @@ -110,18 +110,20 @@ def test_overwrite_preserves_content(): """Overwriting with modified PRS should update file content.""" if not CLAUDE.exists(): pytest.skip("test file not found") - prs = cached_parse_prs(CLAUDE) + prs = parse_prs(CLAUDE) # edited below, so not the shared cached copy with tempfile.TemporaryDirectory() as d: out = Path(d) / "out.PRS" write_prs(prs, out) - # Modify a section to make the output different + # Make a real edit so the output differs + from quickprs.injector import edit_personality original_raw = prs.sections[0].raw - prs.sections[0].raw = b'\xff\xff' + b'\x00' * 10 + edit_personality(prs, saved_by="TESTER") write_prs(prs, out) written = out.read_bytes() assert written != CLAUDE.read_bytes() + assert b"TESTER" in written # Backup should have the original content bak = out.with_suffix(".PRS.bak") @@ -129,3 +131,43 @@ def test_overwrite_preserves_content(): # Restore prs.sections[0].raw = original_raw + + +def test_refuses_to_write_broken_structure(): + """An edit that leaves a readable personality unreadable is not + written, and the existing file is left alone.""" + if not CLAUDE.exists(): + pytest.skip("test file not found") + from quickprs.prs_parser import parse_prs + from quickprs.prs_writer import UnsafeWriteError + prs = parse_prs(CLAUDE) + with tempfile.TemporaryDirectory() as d: + out = Path(d) / "out.PRS" + write_prs(prs, out) + before = out.read_bytes() + prs.sections[0].raw = b'\xff\xff' + b'\x00' * 10 + with pytest.raises(UnsafeWriteError): + write_prs(prs, out) + assert out.read_bytes() == before + + +def test_write_fixes_stale_tags(): + """write_prs rewrites stale class tags (left by older QuickPRS versions) + so RPM can open the file.""" + if not PAWS.exists(): + pytest.skip("test file not found") + import struct + from quickprs import archive + from quickprs.prs_parser import parse_prs, parse_prs_bytes + data = bytearray(PAWS.read_bytes()) + # Corrupt the first CDefaultIdenElem tag the way an old edit would + _, rep = archive.read_document(bytes(data)) + site = next(t for t in rep.tags if t.class_name == "CDefaultIdenElem") + struct.pack_into(" Date: Tue, 27 Oct 2026 20:37:57 -0700 Subject: [PATCH 03/14] Fix conventional sets after padded gaps; P25 conventional CSV (#1) Some RPM files carry a few bytes between a conventional set's 60-byte block and the next set's marker (13 and 12 bytes in the reported file). The parser stopped at the first set, so later sets were missing from the GUI, from CONV_SET.csv and from any rebuild. - The conventional set parser looks past such bytes for the next set (matching the channels' class tag) and keeps them as ConvSet.padding; rebuilds take each set's extra bytes from the archive walk, so they are written back unchanged. - P25 conventional sets export to P25_CONV_SET.csv (NACs in hex, TX/RX/ Scan, long name) and import from it; the NAC columns are checked before the analog conventional columns, which a P25 file also has. - injector.add_p25_conv_set / make_p25_conv_set / get_p25_conv_sets create P25 conventional sets, including the first one; new channels use the flag and trailer bytes RPM writes. - New `quickprs import-csv FILE.PRS CSV...` detects each file's type, so export-csv output imports directly. The GUI CSV import handles P25 conventional files, works on a blank personality and rolls back on failure. - CLI writes now back up an existing output file, not only the input. - Two watcher tests no longer depend on the clock's mtime granularity. Fixes #1 --- quickprs/cli.py | 125 +++++++++++++++++++++---- quickprs/csv_export.py | 22 +++++ quickprs/csv_import.py | 83 ++++++++++++++++- quickprs/gui/app.py | 33 ++++++- quickprs/injector.py | 98 ++++++++++++++++++- quickprs/record_types.py | 23 ++++- tests/test_issue1_conv_sets.py | 155 +++++++++++++++++++++++++++++++ tests/test_watcher_cheatsheet.py | 8 +- 8 files changed, 513 insertions(+), 34 deletions(-) create mode 100644 tests/test_issue1_conv_sets.py diff --git a/quickprs/cli.py b/quickprs/cli.py index 168e536..3cc3962 100644 --- a/quickprs/cli.py +++ b/quickprs/cli.py @@ -774,6 +774,68 @@ def cmd_freq_map(filepath, band=None): return 0 +def cmd_import_csv(filepath, csv_files, output=None): + """Import CSV files (the export-csv format, or RPM-style columns) into + a PRS file. Each file's type is detected from its header: + GROUP_SET (talkgroups), TRK_SET (trunk frequencies), CONV_SET (analog + conventional) or P25_CONV_SET (P25 conventional, with NACs). + + Returns: + 0 on success, 1 on error. + """ + from .csv_import import import_csv + from .injector import ( + _safe_add_group_set, _safe_add_trunk_set, _safe_add_conv_set, + add_p25_conv_set, + ) + from .prs_writer import write_prs + + adders = { + "groups": (_safe_add_group_set, "talkgroup set", "groups"), + "trunk": (_safe_add_trunk_set, "trunk set", "channels"), + "conv": (_safe_add_conv_set, "conv set", "channels"), + "p25conv": (add_p25_conv_set, "P25 conv set", "channels"), + } + prs = parse_prs(filepath) + added = [] + for csv_path in csv_files: + try: + kind, sets = import_csv(csv_path) + except ValueError as e: + print(f"Error: {e}", file=sys.stderr) + return 1 + if kind == "unknown" or not sets: + print(f"Error: {csv_path}: no talkgroup, trunk, conventional or " + f"P25 conventional columns found", file=sys.stderr) + return 1 + add, label, attr = adders[kind] + for obj in sets: + try: + add(prs, obj) + except ValueError as e: + print(f"Error: {csv_path}: {label} '{obj.name}': {e}", + file=sys.stderr) + return 1 + added.append(f"{label} '{obj.name}' " + f"({len(getattr(obj, attr))} {attr})") + + issues = validate_prs(prs) + errors = [m for sev, m in issues if sev == ERROR] + if errors: + print(f"Not written: {len(errors)} validation error(s)", + file=sys.stderr) + for msg in errors: + print(f" [ERROR] {msg}", file=sys.stderr) + return 1 + + out_path = output or filepath + write_prs(prs, out_path, backup=True) + for line in added: + print(f"Imported {line}") + print(f"Saved {out_path}") + return 0 + + def cmd_export_csv(filepath, output_dir): """Export personality data to CSV files.""" prs = parse_prs(filepath) @@ -793,6 +855,12 @@ def cmd_export_csv(filepath, output_dir): if sets: exported.append(export_conv_sets(out / "CONV_SET.csv", sets)) + from .csv_export import export_p25_conv_sets + from .injector import get_p25_conv_sets + sets = get_p25_conv_sets(prs) + if sets: + exported.append(export_p25_conv_sets(out / "P25_CONV_SET.csv", sets)) + sets = _parse_iden_sets(prs) if sets: exported.append(export_iden_sets(out / "IDEN_SET.csv", sets)) @@ -1264,7 +1332,7 @@ def cmd_inject_p25(filepath, name, sysid, long_name=None, wacn=0, errors = [(s, m) for s, m in issues if s == ERROR] out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Injected P25 system '{name}' (SysID {sysid}) into {out_path}") if errors: @@ -1342,7 +1410,7 @@ def cmd_inject_conv(filepath, name, channels_csv=None, template=None, errors = [(s, m) for s, m in issues if s == ERROR] out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) source = f"template '{template}'" if template else channels_csv print(f"Injected conv system '{name}' ({len(channels_data)} channels " @@ -1422,7 +1490,7 @@ def cmd_import_scanner(filepath, csv_file, scanner_fmt='auto', errors = [(s, m) for s, m in issues if s == ERROR] out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Imported {len(channels)} channels from {csv_file} " f"(format: {fmt}) as conv system '{name}' into {out_path}") @@ -1470,7 +1538,7 @@ def cmd_inject_talkgroups(filepath, set_name, tgs_csv, output=None): errors = [(s, m) for s, m in issues if s == ERROR] out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Added {len(tgs)} talkgroups to set '{set_name}' in {out_path}") if errors: @@ -1714,7 +1782,7 @@ def cmd_renumber(filepath, set_name=None, start=1, set_type="conv", return 1 out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) target = f"set '{set_name}'" if set_name else "all sets" print(f"Renumbered {count} channels in {target} " f"(starting at {start}) in {out_path}") @@ -1744,7 +1812,7 @@ def cmd_auto_name(filepath, set_name, style="compact", output=None): return 1 out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Auto-named {count} talkgroups in set '{set_name}' " f"(style: {style}) in {out_path}") return 0 @@ -2209,7 +2277,7 @@ def cmd_remove(filepath, remove_type, name, output=None): errors = [(s, m) for s, m in issues if s == ERROR] out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Removed {label} from {out_path}") if errors: @@ -2287,7 +2355,7 @@ def cmd_edit(filepath, name=None, author=None, errors = [(s, m) for s, m in issues if s == ERROR] out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Edited {out_path}: {', '.join(changes)}") if errors: @@ -2380,7 +2448,7 @@ def cmd_set_option(filepath, option_path=None, value=None, list_opts=False, return 1 out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Set {section}.{attr} = {value} in {out_path}") return 0 @@ -2533,7 +2601,7 @@ def cmd_import_rr(filepath, sid=None, url=None, username=None, apikey=None, errors = [(s, m) for s, m in issues if s == ERROR] out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) # Print summary n_tgs = len(data['talkgroups']) @@ -2682,7 +2750,7 @@ def cmd_import_paste(filepath, name, sysid, wacn=0, long_name=None, errors = [(s, m) for s, m in issues if s == ERROR] out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Injected P25 system '{name}' (SysID {sysid}) into {out_path}") print(f" Talkgroups: {tg_count} Frequencies: {freq_count}") @@ -2804,7 +2872,7 @@ def cmd_repair(filepath, output=None, salvage=False): print("\nStructural validation: PASS") out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"\nRepaired file written to: {out_path}") return 0 @@ -3037,7 +3105,7 @@ def cmd_bulk_edit_talkgroups(filepath, set_name, enable_scan=None, return 1 out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Bulk-edited {count} talkgroups in set '{set_name}' " f"-> {out_path}") @@ -3079,7 +3147,7 @@ def cmd_bulk_edit_channels(filepath, set_name, set_tone=None, return 1 out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Bulk-edited {count} channels in set '{set_name}' " f"-> {out_path}") @@ -3127,7 +3195,7 @@ def cmd_encrypt(filepath, set_name, tg_id=None, encrypt_all=False, return 1 out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) action = "Encrypted" if encrypted else "Decrypted" target = f"TG {tg_id}" if tg_id else f"{count} TGs" @@ -3183,7 +3251,7 @@ def cmd_set_nac(filepath, set_name, channel=0, nac="293", nac_rx=None, return 1 out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Set NAC on channel {channel} in '{set_name}' " f"(TX:{nac_tx_val:03X} RX:{nac_rx_val:03X}) -> {out_path}") @@ -3228,7 +3296,7 @@ def cmd_rename(filepath, set_name, pattern, replace, return 0 out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Renamed {count} items in set '{set_name}' -> {out_path}") @@ -3270,7 +3338,7 @@ def cmd_sort(filepath, set_name, key="frequency", set_type="conv", return 1 out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) order = "descending" if reverse else "ascending" print(f"Sorted set '{set_name}' by {sort_by} ({order}) -> {out_path}") @@ -3445,7 +3513,7 @@ def cmd_auto_setup(filepath, sid=None, url=None, username=None, apikey=None, selected_tags) out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) # Print summary print(f"Auto-setup complete: '{summary['full_name']}' (SID {sid})") @@ -3622,7 +3690,7 @@ def cmd_systems(subcmd, query=None, filepath=None, system_name=None, errors = [(s, m) for s, m in issues if s == ERROR] out_path = output or filepath - write_prs(prs, out_path, backup=(out_path == filepath)) + write_prs(prs, out_path, backup=True) print(f"Added P25 system '{name}' (SysID {sys_obj.system_id}, " f"WACN {sys_obj.wacn}) to {out_path}") @@ -4243,6 +4311,20 @@ def run_cli(args=None): help="Output file (default: overwrite input)") # export-csv + p_icsv = sub.add_parser( + "import-csv", + help="Import CSV files (talkgroups, trunk, conv, P25 conv)", + formatter_class=fmt, + epilog="The type of each file is read from its header, so the\n" + "files written by export-csv import directly.\n" + "Example:\n" + " quickprs import-csv radio.PRS GROUP_SET.csv " + "P25_CONV_SET.csv") + p_icsv.add_argument("file", help="PRS file path") + p_icsv.add_argument("csv_files", nargs="+", help="CSV file(s)") + p_icsv.add_argument("-o", "--output", default=None, + help="Output file (default: modify in place)") + p_csv = sub.add_parser("export-csv", help="Export to CSV files", formatter_class=fmt, epilog="Example:\n" @@ -5454,6 +5536,9 @@ def run_cli(args=None): list_opts=parsed.list_opts, output=parsed.output, ) + elif parsed.command == "import-csv": + return cmd_import_csv(parsed.file, parsed.csv_files, + output=parsed.output) elif parsed.command == "export-csv": return cmd_export_csv(parsed.file, parsed.output_dir) elif parsed.command == "export-json": diff --git a/quickprs/csv_export.py b/quickprs/csv_export.py index f07a2c6..6e2f3dc 100644 --- a/quickprs/csv_export.py +++ b/quickprs/csv_export.py @@ -68,6 +68,28 @@ def export_conv_sets(path, sets): return f"CONV_SET.csv ({total} channels)" +def export_p25_conv_sets(path, sets): + """Write P25_CONV_SET.csv from a list of P25ConvSet objects. + + NACs are written as 3-digit hex (the way RPM and radios show them). + """ + with open(path, 'w', newline='', encoding='utf-8') as f: + w = csv.writer(f) + w.writerow(["Set", "ShortName", "TxFreq", "RxFreq", "TxNAC", + "RxNAC", "TX", "RX", "Scan", "LongName"]) + for pset in sets: + for ch in pset.channels: + w.writerow([pset.name, ch.short_name, + f"{ch.tx_freq:.5f}", f"{ch.rx_freq:.5f}", + f"{ch.nac_tx:03X}", f"{ch.nac_rx:03X}", + "Y" if ch.tx else "N", + "Y" if ch.rx else "N", + "Y" if ch.scan else "N", + ch.long_name]) + total = sum(len(s.channels) for s in sets) + return f"P25_CONV_SET.csv ({total} channels)" + + def export_iden_sets(path, sets): """Write IDEN_SET.csv from a list of IdenDataSet objects.""" with open(path, 'w', newline='', encoding='utf-8') as f: diff --git a/quickprs/csv_import.py b/quickprs/csv_import.py index 8ec4c6a..09ca3c2 100644 --- a/quickprs/csv_import.py +++ b/quickprs/csv_import.py @@ -4,6 +4,7 @@ - GROUP_SET.csv → P25GroupSet objects - TRK_SET.csv → TrunkSet objects - CONV_SET.csv → ConvSet objects + - P25_CONV_SET.csv → P25ConvSet objects (NACs, TX/RX/scan) - Generic CSV with flexible column matching RPM CSV format uses header rows with known column names. This module @@ -24,8 +25,8 @@ def import_csv(filepath): Returns: tuple of (data_type, objects) where: - data_type: "groups" | "trunk" | "conv" | "unknown" - objects: list of P25GroupSet | TrunkSet | ConvSet + data_type: "groups" | "trunk" | "conv" | "p25conv" | "unknown" + objects: list of P25GroupSet | TrunkSet | ConvSet | P25ConvSet """ filepath = Path(filepath) try: @@ -42,6 +43,10 @@ def import_csv(filepath): if _is_group_csv(header_lower): return "groups", import_group_csv(filepath) + elif _is_p25_conv_csv(header_lower): + # Before the analog check: a P25 conventional CSV also has + # ShortName, TxFreq and RxFreq columns. + return "p25conv", import_p25_conv_csv(filepath) elif _is_conv_csv(header_lower): return "conv", import_conv_csv(filepath) elif _is_trunk_csv(header_lower): @@ -63,6 +68,12 @@ def _is_trunk_csv(header): 'groupid' not in header and 'talkgroup' not in header) +def _is_p25_conv_csv(header): + """Check if header matches P25_CONV_SET format (has NAC columns).""" + cols = {h.replace(' ', '_') for h in header} + return bool(cols & {'txnac', 'rxnac', 'tx_nac', 'rx_nac', 'nac'}) + + def _is_conv_csv(header): """Check if header matches CONV_SET format.""" return ('shortname' in header or 'short_name' in header or @@ -252,6 +263,74 @@ def import_conv_csv(filepath): for name, channels in sets_dict.items()] +def _parse_nac(val, default=0x293): + """A NAC as hex ("293", "0x293", "$293"); blank gives the default.""" + val = (val or '').strip().lstrip('$') + if not val: + return default + nac = int(val, 16) + if not 0 <= nac <= 0xFFF: + raise ValueError(f"NAC {val} out of range (000-FFF)") + return nac + + +def import_p25_conv_csv(filepath): + """Import P25_CONV_SET.csv → list of P25ConvSet. + + Expected columns (flexible matching): + Set, ShortName, TxFreq, RxFreq, TxNAC, RxNAC, TX, RX, Scan, LongName + NACs are hex. Rows with a bad frequency or NAC are skipped. + """ + from .injector import make_p25_conv_set + + filepath = Path(filepath) + rows = _read_csv(filepath) + if not rows: + return [] + + col_map = _map_columns(rows[0], { + 'set': ['set', 'setname', 'set_name', 'zone'], + 'short_name': ['shortname', 'short_name', 'name', 'channel', 'short'], + 'tx_freq': ['txfreq', 'tx_freq', 'frequency', 'freq'], + 'rx_freq': ['rxfreq', 'rx_freq'], + 'nac_tx': ['txnac', 'tx_nac', 'nac'], + 'nac_rx': ['rxnac', 'rx_nac'], + 'tx': ['tx', 'transmit'], + 'rx': ['rx', 'receive'], + 'scan': ['scan'], + 'long_name': ['longname', 'long_name', 'long', 'description'], + }) + + sets_dict = {} + default_set = filepath.stem[:8].upper() + for row in rows[1:]: + if not row or row[0].lstrip().startswith('#'): + continue + short = _get_field(row, col_map, 'short_name', '')[:8] + if not short: + continue + try: + tx = float(_get_field(row, col_map, 'tx_freq', '')) + rx = float(_get_field(row, col_map, 'rx_freq', str(tx))) + nac_tx = _parse_nac(_get_field(row, col_map, 'nac_tx', '')) + nac_rx = _parse_nac(_get_field(row, col_map, 'nac_rx', ''), + default=nac_tx) + except ValueError: + continue + set_name = _get_field(row, col_map, 'set', default_set)[:8] + sets_dict.setdefault(set_name, []).append({ + 'short_name': short, 'tx_freq': tx, 'rx_freq': rx, + 'nac_tx': nac_tx, 'nac_rx': nac_rx, + 'tx': _parse_bool(_get_field(row, col_map, 'tx', 'Y')), + 'rx': _parse_bool(_get_field(row, col_map, 'rx', 'Y')), + 'scan': _parse_bool(_get_field(row, col_map, 'scan', 'Y')), + 'long_name': _get_field(row, col_map, 'long_name', short)[:16], + }) + + return [make_p25_conv_set(name, data) + for name, data in sets_dict.items()] + + # ─── Helpers ──────────────────────────────────────────────────────── def _read_csv(filepath): diff --git a/quickprs/gui/app.py b/quickprs/gui/app.py index a004490..81fb427 100644 --- a/quickprs/gui/app.py +++ b/quickprs/gui/app.py @@ -1282,6 +1282,16 @@ def export_csv(self): except Exception as e: log_error("export_csv", f"{filename}: {e}") + try: + from ..csv_export import export_p25_conv_sets + from ..injector import get_p25_conv_sets + p25_sets = get_p25_conv_sets(self.prs) + if p25_sets: + exported.append(export_p25_conv_sets( + out_dir / "P25_CONV_SET.csv", p25_sets)) + except Exception as e: + log_error("export_csv", f"P25_CONV_SET.csv: {e}") + # Options and systems from PRS directly try: result = export_options(out_dir / "OPTIONS.csv", self.prs) @@ -1546,7 +1556,11 @@ def import_csv(self): return from ..csv_import import import_csv as do_import - from ..injector import add_group_set, add_trunk_set, add_conv_set + from ..injector import ( + _safe_add_group_set, _safe_add_trunk_set, _safe_add_conv_set, + add_p25_conv_set, + ) + from ..prs_parser import parse_prs_bytes try: data_type, objects = do_import(path) @@ -1561,7 +1575,8 @@ def import_csv(self): "Expected columns:\n" " Groups: GroupID, ShortName, LongName, TX, Scan\n" " Trunk: TxFreq, RxFreq\n" - " Conv: ShortName, TxFreq, RxFreq, TxTone, RxTone") + " Conv: ShortName, TxFreq, RxFreq, TxTone, RxTone\n" + " P25 conv: ShortName, TxFreq, RxFreq, TxNAC, RxNAC") return # Show what was found and confirm @@ -1576,6 +1591,9 @@ def import_csv(self): elif data_type == "conv": summaries.append(f"Conv Set '{obj.name}': " f"{len(obj.channels)} channels") + elif data_type == "p25conv": + summaries.append(f"P25 Conv Set '{obj.name}': " + f"{len(obj.channels)} channels") if not messagebox.askyesno( "Confirm Import", @@ -1585,15 +1603,18 @@ def import_csv(self): return self.save_undo_snapshot(f"Import CSV ({data_type})") + before = self.prs.to_bytes() try: for obj in objects: if data_type == "groups": - add_group_set(self.prs, obj) + _safe_add_group_set(self.prs, obj) elif data_type == "trunk": - add_trunk_set(self.prs, obj) + _safe_add_trunk_set(self.prs, obj) elif data_type == "conv": - add_conv_set(self.prs, obj) + _safe_add_conv_set(self.prs, obj) + elif data_type == "p25conv": + add_p25_conv_set(self.prs, obj) self.mark_modified() self.personality_view.refresh() @@ -1602,6 +1623,8 @@ def import_csv(self): log_action("csv_import", file=path, type=data_type, sets=len(objects)) except Exception as e: + # Leave the personality as it was rather than half-imported + self.prs.sections = parse_prs_bytes(before, verify=False).sections log_error("csv_import", str(e), file=path) messagebox.showerror("Error", f"Import failed:\n{e}") diff --git a/quickprs/injector.py b/quickprs/injector.py index 5fbd0c8..5cd1cfd 100644 --- a/quickprs/injector.py +++ b/quickprs/injector.py @@ -103,9 +103,17 @@ def _trunk_set_obj(tset): tset.metadata_to_bytes() + tail]) -def _conv_set_obj(cset): +def _conv_set_obj(cset, old=None): channels = [Obj("CConvChannel", [ch.to_bytes()]) for ch in cset.channels] - meta = cset.metadata_to_bytes() + bytes(getattr(cset, "padding", b"")) + meta = write_lps(cset.name) + cset.metadata + if old is not None: + # The walker knows where the set really ends; bytes after the + # 60-byte block (issue #1) are kept from there, not guessed. + old_meta = old.parts[1] + _, at = archive.read_cstring(old_meta, 0) + meta += old_meta[at + ConvSet.METADATA_SIZE:] + else: + meta += bytes(getattr(cset, "padding", b"")) return Obj("CConvSet", [ObjList("items", channels), meta]) @@ -146,11 +154,27 @@ def _p25_conv_set_obj(pset): } +def _set_obj_name(obj): + return archive.read_cstring(obj.parts[1], 0)[0] + + def _write_set_list(prs, list_name, sets): """Replace one whole set list (may be empty) and rewrite the file.""" doc = archive.document_from_prs(prs) + lst = doc.list(list_name) build = _SET_OBJ_BUILDERS[list_name] - doc.list(list_name).items = [build(s) for s in sets] + if list_name == "conv sets": + # Match the file's own set objects by name (or by position when a + # rename kept the list the same length) to keep their extra bytes. + old_items = [o for o in lst.items if o is not None] + by_name = {_set_obj_name(o): o for o in old_items} + same_len = len(old_items) == len(sets) + lst.items = [ + build(s, by_name.get(s.name, + old_items[i] if same_len else None)) + for i, s in enumerate(sets)] + else: + lst.items = [build(s) for s in sets] archive.write_document(prs, doc) @@ -413,6 +437,25 @@ def _replace_p25_conv_sections(prs, sets, *_args, **_kwargs): _write_set_list(prs, "P25 conv sets", sets) +def get_p25_conv_sets(prs): + """The personality's P25 conventional sets ([] when there are none).""" + from .record_types import parse_p25_conv_channel_section + ch_sec = prs.get_section_by_class("CP25ConvChannel") + set_sec = prs.get_section_by_class("CP25ConvSet") + if not ch_sec or not set_sec: + return [] + return parse_sets_from_sections(set_sec.raw, ch_sec.raw, + parse_p25_conv_channel_section) + + +def add_p25_conv_set(prs, p25_conv_set): + """Add a P25 conventional set, creating the first one if needed.""" + existing = get_p25_conv_sets(prs) + if any(s.name == p25_conv_set.name for s in existing): + raise ValueError(f"P25 conv set '{p25_conv_set.name}' already exists") + _write_set_list(prs, "P25 conv sets", existing + [p25_conv_set]) + + def _build_iden_raw(sets, byte1, byte2, trailing_data=None): """Build complete CDefaultIdenElem section from list of IdenDataSets. @@ -1727,6 +1770,55 @@ def make_conv_channel(short_name, tx_freq, rx_freq=None, ) +# Flag and trailer bytes of a P25 conventional channel as RPM 14 creates +# it (taken from an RPM-saved personality): RX, call and alert tones, scan +# list member, scan, backlight and TX on; tone mode and narrowband set. +_RPM_P25_CONV_FLAGS = bytes.fromhex( + "00010101010001000000010100010100000000010001") +_RPM_P25_CONV_TRAILER = bytes.fromhex( + "0000000000010001000000000000000000000000") + + +def make_p25_conv_channel(short_name, tx_freq, rx_freq=None, nac_tx=0x293, + nac_rx=None, long_name="", tx=True, rx=True, + scan=True): + """Create a P25 conventional channel with RPM's default flags. + + NACs are 12-bit (0x000-0xFFF); 0x293 is the P25 default. + """ + from .record_types import P25ConvChannel + if rx_freq is None: + rx_freq = tx_freq + if nac_rx is None: + nac_rx = nac_tx + for label, nac in (("TX", nac_tx), ("RX", nac_rx)): + if not 0 <= nac <= 0xFFF: + raise ValueError(f"{label} NAC {nac:#x} out of range (0-FFF)") + ch = P25ConvChannel(short_name=short_name[:8], tx_freq=tx_freq, + rx_freq=rx_freq, nac_tx=nac_tx, nac_rx=nac_rx, + long_name=(long_name or short_name)[:16], + trailer=_RPM_P25_CONV_TRAILER) + ch.flags = _RPM_P25_CONV_FLAGS + ch.tx = ch.tx_enable = tx + ch.rx = rx + ch.scan = scan + return ch + + +def make_p25_conv_set(name, channels_data, group_set_ref=""): + """Create a P25ConvSet from dicts with short_name, tx_freq, rx_freq, + nac_tx, nac_rx, long_name, tx, rx and scan keys.""" + from .record_types import P25ConvSet + channels = [make_p25_conv_channel( + short_name=d['short_name'], tx_freq=d['tx_freq'], + rx_freq=d.get('rx_freq'), nac_tx=d.get('nac_tx', 0x293), + nac_rx=d.get('nac_rx'), long_name=d.get('long_name', ''), + tx=d.get('tx', True), rx=d.get('rx', True), scan=d.get('scan', True)) + for d in channels_data] + return P25ConvSet(name=name[:8], channels=channels, + group_set_ref=group_set_ref[:8]) + + def make_conv_set(name, channels_data): """Create a ConvSet from channel data. diff --git a/quickprs/record_types.py b/quickprs/record_types.py index 4b660c7..746c6f4 100644 --- a/quickprs/record_types.py +++ b/quickprs/record_types.py @@ -353,8 +353,12 @@ class ConvSet: separator: bytes = b'\x95\x81' # inter-channel separator (file-specific) set_marker: bytes = b'\x93\x81' # inter-set marker (file-specific) trailing_uint16: int = 0 # trailing 2 bytes at end of section (last set only) + # Bytes some RPM files carry between the 60-byte block and the next + # set (GitHub issue #1); kept so they are written back unchanged. + padding: bytes = b'' METADATA_SIZE = 60 + MAX_PADDING = 64 @property def metadata(self): @@ -391,8 +395,8 @@ def channels_to_bytes(self): return b''.join(parts) def metadata_to_bytes(self): - """Serialize set name + metadata.""" - return write_lps(self.name) + self.metadata + """Serialize set name + metadata (+ any padding the file had).""" + return write_lps(self.name) + self.metadata + self.padding # ─── CP25ConvChannel ───────────────────────────────────────────────── @@ -1086,6 +1090,21 @@ def parse_conv_channel_section(data, offset, end, first_count): cset.metadata = meta sets.append(cset) + # Some files hold a few more bytes before the next set's marker + # (GitHub issue #1). Look ahead for a marker whose channel tag is + # the one this set's channels use. + if not (pos < end - 6 and _is_record_marker(data, pos)): + for k in range(1, ConvSet.MAX_PADDING + 1): + at = pos + k + if at >= end - 6: + break + if (_is_record_marker(data, at) and + (observed_sep is None or + bytes(data[at + 4:at + 6]) == observed_sep)): + cset.padding = bytes(data[pos:at]) + pos = at + break + # Inter-set gap: set_marker(2) + uint16(count) + separator(2) # Detect by checking both marker and separator have valid byte2 if pos < end - 6 and _is_record_marker(data, pos): diff --git a/tests/test_issue1_conv_sets.py b/tests/test_issue1_conv_sets.py new file mode 100644 index 0000000..9ca8762 --- /dev/null +++ b/tests/test_issue1_conv_sets.py @@ -0,0 +1,155 @@ +"""GitHub issue #1: conventional sets after padded gaps, and P25 +conventional sets in CSV export/import. + +Some RPM files hold a few extra bytes between a conventional set's 60-byte +block and the next set (13 and 12 bytes in the reported file). The +parser used to stop after the first set, so later sets vanished from the +GUI and from CONV_SET.csv. +""" + +import csv + +import pytest + +from quickprs import archive, injector +from quickprs.builder import create_blank_prs +from quickprs.csv_export import export_conv_sets, export_p25_conv_sets +from quickprs.csv_import import import_csv +from quickprs.prs_parser import parse_prs_bytes +from quickprs.record_types import ( + parse_sets_from_sections, parse_conv_channel_section, +) + +PAD_A = bytes.fromhex("0c") + b"EXTRA FIELD1" # 13 bytes, string-like +PAD_B = bytes(12) # 12 zero bytes + + +def _conv_sets(prs): + return parse_sets_from_sections( + prs.get_section_by_class("CConvSet").raw, + prs.get_section_by_class("CConvChannel").raw, + parse_conv_channel_section) + + +def _channels(prefix, n, base): + return [{"short_name": f"{prefix}{i}", "tx_freq": base + i * 0.0125, + "long_name": f"{prefix} CHAN {i}"} for i in range(n)] + + +@pytest.fixture +def padded(): + """A personality with three conventional sets where the first two are + followed by extra bytes, the way the reported RPM file was.""" + prs = create_blank_prs() + injector.add_conv_set(prs, injector.make_conv_set( + "SET_A", _channels("A", 4, 151.0))) + injector.add_conv_set(prs, injector.make_conv_set( + "SET_B", _channels("B", 3, 152.0))) + doc = archive.document_from_prs(prs) + sets = doc.list("conv sets").items + sets[0].parts[1] += PAD_A # after "Conv 1" + sets[1].parts[1] += PAD_B # after SET_A + return parse_prs_bytes(archive.serialize(doc)) + + +def test_all_padded_sets_parse(padded): + sets = _conv_sets(padded) + assert [s.name for s in sets] == ["Conv 1", "SET_A", "SET_B"] + assert [len(s.channels) for s in sets] == [1, 4, 3] + assert sets[0].padding == PAD_A + assert sets[1].padding == PAD_B + assert sets[2].padding == b"" + + +def test_padded_file_is_consistent_and_round_trips(padded): + data = padded.to_bytes() + assert archive.check_bytes(data) == [] + doc, rep = archive.read_document(data, lenient=False) + assert archive.serialize(doc) == data + assert [pad for _, pad in rep.padding] == [PAD_A, PAD_B] + + +def test_csv_export_has_every_set(padded, tmp_path): + out = tmp_path / "CONV_SET.csv" + export_conv_sets(out, _conv_sets(padded)) + with open(out, newline="") as f: + rows = list(csv.DictReader(f)) + assert {r["Set"] for r in rows} == {"Conv 1", "SET_A", "SET_B"} + assert len(rows) == 8 + + +def test_edits_keep_the_padding(padded): + injector.add_conv_set(padded, injector.make_conv_set( + "SET_C", _channels("C", 2, 153.0))) + injector.rename_conv_set(padded, "SET_A", "SET_AA") + assert archive.check(padded) == [] + data = padded.to_bytes() + assert PAD_A in data and data.count(bytes(12)) >= 1 + sets = _conv_sets(padded) + assert [s.name for s in sets] == ["Conv 1", "SET_AA", "SET_B", "SET_C"] + assert sets[0].padding == PAD_A and sets[1].padding == PAD_B + + +# ─── P25 conventional CSV ──────────────────────────────────────────── + +@pytest.fixture +def p25conv(): + prs = create_blank_prs() + injector.add_p25_conv_set(prs, injector.make_p25_conv_set("DIG", [ + {"short_name": "DIG 1", "tx_freq": 155.1, "nac_tx": 0x293, + "long_name": "DIGITAL ONE"}, + {"short_name": "DIG 2", "tx_freq": 155.2, "rx_freq": 155.25, + "nac_tx": 0x123, "nac_rx": 0xF7E, "tx": False, "scan": False}, + ])) + assert archive.check(prs) == [] + return prs + + +def test_p25_conv_csv_round_trip(p25conv, tmp_path): + out = tmp_path / "P25_CONV_SET.csv" + export_p25_conv_sets(out, injector.get_p25_conv_sets(p25conv)) + kind, sets = import_csv(out) + assert kind == "p25conv" + (pset,) = sets + assert pset.name == "DIG" + got = [(c.short_name, round(c.tx_freq, 5), round(c.rx_freq, 5), + c.nac_tx, c.nac_rx, c.tx, c.rx, c.scan, c.long_name) + for c in pset.channels] + assert got == [ + ("DIG 1", 155.1, 155.1, 0x293, 0x293, True, True, True, + "DIGITAL ONE"), + ("DIG 2", 155.2, 155.25, 0x123, 0xF7E, False, True, False, "DIG 2"), + ] + + +def test_p25_conv_csv_not_taken_for_analog(tmp_path): + """A P25 conventional CSV also has ShortName/TxFreq/RxFreq, so the NAC + columns must decide before the analog check does.""" + out = tmp_path / "x.csv" + out.write_text("Set,ShortName,TxFreq,RxFreq,TxNAC,RxNAC\n" + "D,CH1,155.1,155.1,293,293\n") + assert import_csv(out)[0] == "p25conv" + + +def test_analog_conv_csv_still_analog(tmp_path): + out = tmp_path / "x.csv" + out.write_text("Set,ShortName,TxFreq,RxFreq,TxTone,RxTone,LongName\n" + "A,CH1,151.82,151.82,,,MURS 1\n") + assert import_csv(out)[0] == "conv" + + +def test_import_p25_conv_into_blank(p25conv, tmp_path): + """Importing P25 conventional sets creates the first set list.""" + out = tmp_path / "P25_CONV_SET.csv" + export_p25_conv_sets(out, injector.get_p25_conv_sets(p25conv)) + _, sets = import_csv(out) + prs = create_blank_prs() + for s in sets: + injector.add_p25_conv_set(prs, s) + assert archive.check(prs) == [] + assert [s.name for s in injector.get_p25_conv_sets(prs)] == ["DIG"] + + +def test_bad_nac_rejected(): + with pytest.raises(ValueError): + injector.make_p25_conv_channel("X", 155.0, nac_tx=0x1000) diff --git a/tests/test_watcher_cheatsheet.py b/tests/test_watcher_cheatsheet.py index 91387b4..57fc646 100644 --- a/tests/test_watcher_cheatsheet.py +++ b/tests/test_watcher_cheatsheet.py @@ -330,7 +330,8 @@ def fake_sleep(seconds): if call_count[0] == 1: # Simulate file change by bumping mtime import os - os.utime(str(test_file), None) + st = test_file.stat() + os.utime(str(test_file), (st.st_atime, st.st_mtime + 10)) elif call_count[0] >= 2: raise KeyboardInterrupt @@ -359,7 +360,10 @@ def fake_sleep(seconds): call_count[0] += 1 if call_count[0] == 1: import os - os.utime(str(test_file), None) + # An explicit later mtime: "now" can equal the copy's mtime + # within the clock's granularity, which made this flaky. + st = test_file.stat() + os.utime(str(test_file), (st.st_atime, st.st_mtime + 10)) elif call_count[0] >= 2: raise KeyboardInterrupt From d3e04c8d92012999e0429969493a3d3176d802b9 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 20:54:17 -0700 Subject: [PATCH 04/14] GUI fixes and validated radio options GUI: - Import Wizard built ConvSystemConfig/P25TrkSystemConfig with fields that do not exist (short_name, sys_id, flags) and passed an IDEN template object as entries, so every non-talkgroup import failed; clipboard channels were read with dict access on objects. - System Wizard: log_action was called with a positional message after the system was added, so "Finish" reported failure and a retry added the system twice. Talkgroup IDs are checked (1-65535) before anything is changed, and a failed add is rolled back. - Opening another file kept the undo history, so Undo could put the previous file's bytes into the new one; opening from Recent Files did not ask about unsaved changes; a failed "save first" still went on to close or replace the document. One _confirm_discard/_set_document path now serves open, drop, new, build, import JSON and close. - Delete, Insert, F2, Ctrl+Z/Y no longer act on the tree while a text field has focus. - Multi-select edits act on the exact (set, talkgroup) pairs selected, not on every selected ID in every selected set. - Add-set dialogs work on a blank personality; Health Check no longer raises (current_path); keyboard-shortcut window unbinds its mouse wheel handler; dropped file paths are read as Unicode; the packaged exe launches the wizard; run.py routes any non-file argument to the CLI instead of keeping a list of commands. Radio options (platformConfig): - set_platform_option refuses misspelt attributes and values a field does not allow, and addresses nested elements such as audioConfig/microphone[micType=INTERNAL] instead of writing on the parent. - The fallback XML is now RPM's own new-radio options (the old one had invented attributes and an invalid batteryType), and it is placed where RPM keeps it instead of shifting the fields after it. - Presets and profiles no longer set attributes the XG-100P XML does not have (misc.ledEnabled, gps.reportInterval). --- quickprs/__main__.py | 9 +- quickprs/completions.py | 27 ++- quickprs/favorites.py | 8 +- quickprs/gui/app.py | 324 ++++++++++++++++--------------- quickprs/gui/import_wizard.py | 58 +++--- quickprs/gui/personality_view.py | 51 ++--- quickprs/gui/system_wizard.py | 48 +++-- quickprs/option_maps.py | 275 ++++++++++++++++---------- quickprs/profile_templates.py | 8 +- run.py | 61 +++--- tests/test_favorites.py | 20 +- tests/test_fleet_check.py | 15 +- tests/test_gui_smoke.py | 137 +++++++++++++ tests/test_platform_options.py | 73 +++++++ 14 files changed, 713 insertions(+), 401 deletions(-) create mode 100644 tests/test_gui_smoke.py create mode 100644 tests/test_platform_options.py diff --git a/quickprs/__main__.py b/quickprs/__main__.py index 398a2d2..86b2183 100644 --- a/quickprs/__main__.py +++ b/quickprs/__main__.py @@ -18,8 +18,11 @@ try: from .gui.app import main main() -except Exception: - # GUI unavailable (no display, no tkinter, etc.) — offer wizard - print("GUI not available. Use 'quickprs wizard' for interactive mode,") +except Exception as exc: + # GUI unavailable (no display, no tkinter, etc.) — offer wizard. The + # error itself is shown too: a bare message once hid a startup crash. + print(f"GUI not available ({type(exc).__name__}: {exc}).", + file=sys.stderr) + print("Use 'quickprs wizard' for interactive mode,") print("or run 'quickprs --help' for CLI commands.") sys.exit(1) diff --git a/quickprs/completions.py b/quickprs/completions.py index 5d82978..1e63d0e 100644 --- a/quickprs/completions.py +++ b/quickprs/completions.py @@ -53,22 +53,17 @@ "accessory", "mandown", "display"] # Common option paths for set-option -OPTION_PATHS = [ - "gps.gpsMode", "gps.type", "gps.operationMode", "gps.mapDatum", - "gps.positionFormat", "gps.elevationUnits", "gps.northingType", - "gps.gridDigits", "gps.angularUnits", "gps.reportInterval", - "audio.speakerMode", "audio.pttMode", "audio.noiseCancellation", - "audio.tones", "audio.cctTimer", - "bluetooth.friendlyName", "bluetooth.btMode", "bluetooth.btAdminMode", - "misc.password", "misc.maintenancePassword", "misc.topFpMode", - "misc.topFpOrient", "misc.topFpIntensity", "misc.topFpTimeout", - "misc.topFpLedColor", "misc.dateFormat", "misc.p25Optimize", - "misc.batteryType", "misc.autoRSSIThreshold", "misc.ledEnabled", - "timedate.time", "timedate.zone", "timedate.date", - "accessory.noiseCancellation", "accessory.micSelectMode", - "accessory.pttMode", - "mandown.inactivityTime", "mandown.warningTime", -] +def _option_paths(): + """section.attribute for every top-level option RPM's XML has.""" + from .option_maps import XML_FIELD_INDEX, SECTION_MAP + friendly = {} + for name, element in SECTION_MAP.items(): + friendly.setdefault(element, name) + return sorted(f"{friendly[el]}.{attr}" + for el, attr in XML_FIELD_INDEX if el in friendly) + + +OPTION_PATHS = _option_paths() # Flags per subcommand _SUBCOMMAND_FLAGS = { diff --git a/quickprs/favorites.py b/quickprs/favorites.py index 1277eef..8521f84 100644 --- a/quickprs/favorites.py +++ b/quickprs/favorites.py @@ -162,10 +162,9 @@ def clear_favorites(category=None): PRESETS = { 'field_ops': { - 'description': 'Field operations (GPS on, high power, long timeout)', + 'description': 'Field operations (GPS on, long display timeout)', 'options': { 'gps.gpsMode': 'ON', - 'gps.reportInterval': '30', 'misc.topFpTimeout': '60', }, }, @@ -173,7 +172,7 @@ def clear_favorites(category=None): 'description': 'Covert operations (no GPS, no LED, short timeout)', 'options': { 'gps.gpsMode': 'OFF', - 'misc.ledEnabled': 'false', + 'misc.enableTriColorLed': 'OFF', 'misc.topFpTimeout': '5', 'misc.topFpIntensity': '1', }, @@ -185,10 +184,9 @@ def clear_favorites(category=None): }, }, 'gps_on': { - 'description': 'Enable GPS with 5-second reporting', + 'description': 'Enable GPS', 'options': { 'gps.gpsMode': 'ON', - 'gps.reportInterval': '5', }, }, 'gps_off': { diff --git a/quickprs/gui/app.py b/quickprs/gui/app.py index 81fb427..11215d5 100644 --- a/quickprs/gui/app.py +++ b/quickprs/gui/app.py @@ -90,29 +90,47 @@ def __init__(self, root): self.root.bind('', lambda e: self.open_file()) self.root.bind('', lambda e: self.save_file()) self.root.bind('', lambda e: self.save_as()) - self.root.bind('', lambda e: self.undo_injection()) - self.root.bind('', lambda e: self.redo()) - self.root.bind('', lambda e: self.redo()) + # Keys that also edit text do nothing app-wide while a text field + # has focus (Delete in the search box used to offer to delete the + # selected talkgroup). + self.root.bind('', + self._unless_typing(self.undo_injection)) + self.root.bind('', self._unless_typing(self.redo)) + self.root.bind('', self._unless_typing(self.redo)) self.root.bind('', lambda e: self.compare_files()) self.root.bind('', lambda e: self.export_json()) self.root.bind('', lambda e: self._show_import_wizard()) self.root.bind('', lambda e: self.merge_prs()) self.root.bind('', lambda e: self.add_template_channels()) self.root.bind('', lambda e: self.generate_report()) - self.root.bind('', lambda e: self._delete_selected()) - self.root.bind('', lambda e: self._rename_selected()) + self.root.bind('', self._unless_typing(self._delete_selected)) + self.root.bind('', self._unless_typing(self._rename_selected)) self.root.bind('', lambda e: self.validate()) self.root.bind('', lambda e: self._capacity_report()) - self.root.bind('', lambda e: self._insert_context_aware()) + self.root.bind('', + self._unless_typing(self._insert_context_aware)) self.root.bind('', lambda e: self.show_shortcuts()) # Drag-and-drop file opening (Windows) if HAS_WINDND: - windnd.hook_dropfiles(self.root, func=self._on_file_drop) + windnd.hook_dropfiles(self.root, func=self._on_file_drop, + force_unicode=True) self._update_title() self._restore_geometry() + _TEXT_WIDGETS = (tk.Entry, tk.Text, tk.Spinbox, ttk.Entry, ttk.Combobox, + ttk.Spinbox) + + def _unless_typing(self, handler): + """Wrap a key handler so it is skipped while a text field has focus.""" + def _on_key(event): + if isinstance(event.widget, self._TEXT_WIDGETS): + return None + handler() + return "break" + return _on_key + # ─── Menu bar ──────────────────────────────────────────────────── def _build_menu(self): @@ -436,12 +454,16 @@ def _launch_wizard(self): import subprocess import shutil - # Find the Python executable - python = sys.executable or shutil.which("python") or "python" + if getattr(sys, "frozen", False): + # The packaged QuickPRS.exe takes the command directly + command = [sys.executable, "wizard"] + else: + python = sys.executable or shutil.which("python") or "python" + command = [python, "-m", "quickprs", "wizard"] try: subprocess.Popen( - [python, "-m", "quickprs", "wizard"], + command, creationflags=subprocess.CREATE_NEW_CONSOLE, ) self.status_set("Launched wizard in new console window") @@ -687,32 +709,71 @@ def _build_status_bar(self): def _on_file_drop(self, files): """Handle file(s) dropped onto the window from the OS.""" for raw in files: - path = raw.decode('utf-8') if isinstance(raw, bytes) else str(raw) + path = self._dropped_path(raw) if path.lower().endswith('.prs'): - if self.modified: - result = messagebox.askyesnocancel( - "Unsaved Changes", - "You have unsaved changes. Save before opening?") - if result is None: - return - if result: - self.save_file() self._open_path(path) return # No .PRS file found in drop - names = [Path(f.decode('utf-8') if isinstance(f, bytes) else str(f)).name - for f in files] + names = [Path(self._dropped_path(f)).name for f in files] self.status_set(f"Not a PRS file: {', '.join(names)}", color="orange") + @staticmethod + def _dropped_path(raw): + """windnd hands over ANSI bytes unless asked for Unicode.""" + if isinstance(raw, bytes): + try: + return raw.decode('mbcs') + except (LookupError, UnicodeDecodeError): + return raw.decode('utf-8', errors='replace') + return str(raw) + + def _confirm_discard(self, action="continue"): + """Ask about unsaved changes. True means go ahead: nothing to save, + the user chose not to, or the save worked.""" + if not self.modified: + return True + result = messagebox.askyesnocancel( + "Unsaved Changes", + f"You have unsaved changes. Save before you {action}?") + if result is None: + return False + if result: + return self.save_file() + return True + + def _set_document(self, prs, path): + """Make ``prs`` the open personality. Undo history and the saved + baseline belong to one file, so both start fresh.""" + self.prs = prs + self.prs_path = Path(path) if path else None + self._undo_stack = UndoStack(max_levels=20) + self._update_undo_menu() + self._last_saved_bytes = prs.to_bytes() + self.modified = False + self._hide_welcome() + self._update_title() + fg = "#e0e0e0" if self.dark_mode else "black" + self.file_label.config( + text=self.prs_path.name if self.prs_path else "", foreground=fg) + self.size_label.config(text=f"{len(self._last_saved_bytes):,} bytes") + self._status_modified.config(text="") + self.personality_view.refresh() + self._update_stats() + self._update_capacity_label() + + def _remember_path(self, path): + """Recent files and last folder; a settings write failure must not + break opening or saving.""" + self.settings["last_open_dir"] = str(Path(path).parent) + add_recent_file(self.settings, str(path)) + try: + self._refresh_recent_menu() + except Exception as e: + log_error("recent_files", str(e)) + def open_file(self): - if self.modified: - result = messagebox.askyesnocancel( - "Unsaved Changes", - "You have unsaved changes. Save before opening a new file?") - if result is None: # Cancel - return - if result: # Yes - self.save_file() + if not self._confirm_discard("open another file"): + return initial_dir = self.settings.get("last_open_dir", "") path = filedialog.askopenfilename( @@ -722,54 +783,41 @@ def open_file(self): ) if not path: return - self._open_path(path) + self._open_path(path, confirmed=True) - def _open_path(self, path): + def _open_path(self, path, confirmed=False): """Load a PRS file from a path string.""" path = str(path) - # Remember directory and add to recent files - self.settings["last_open_dir"] = str(Path(path).parent) - add_recent_file(self.settings, path) - self._refresh_recent_menu() - + if not confirmed and not self._confirm_discard("open another file"): + return try: - self.prs = parse_prs(Path(path)) - self.prs_path = Path(path) - self.modified = False - self._last_saved_bytes = self.prs.to_bytes() - self._hide_welcome() - self._update_title() - fg = "#e0e0e0" if self.dark_mode else "black" - self.file_label.config( - text=str(self.prs_path.name), foreground=fg) - self.status_set( - f"Loaded {self.prs_path.name} " - f"({self.prs.file_size:,} bytes, " - f"{len(self.prs.sections)} sections)") - self.size_label.config( - text=f"{self.prs.file_size:,} bytes") - self.personality_view.refresh() - self._update_stats() - self._update_capacity_label() - self._status_modified.config(text="") - log_action("file_open", - path=str(path), - size=self.prs.file_size, - sections=len(self.prs.sections)) + prs = parse_prs(Path(path)) except Exception as e: log_error("file_open", str(e), path=str(path)) messagebox.showerror("Error", f"Failed to open file:\n{e}") + return + + self._set_document(prs, path) + self._remember_path(path) + self.status_set( + f"Loaded {self.prs_path.name} " + f"({self.prs.file_size:,} bytes, " + f"{len(self.prs.sections)} sections)") + log_action("file_open", + path=str(path), + size=self.prs.file_size, + sections=len(self.prs.sections)) def save_file(self): + """Save to the current path; True when the file was written.""" if not self.prs or not self.prs_path: - self.save_as() - return - self._do_save(self.prs_path) + return self.save_as() + return self._do_save(self.prs_path) def save_as(self): if not self.prs: messagebox.showwarning("Warning", "No file loaded.") - return + return False initial_dir = self.settings.get("last_open_dir", "") path = filedialog.asksaveasfilename( @@ -780,34 +828,41 @@ def save_as(self): initialdir=initial_dir or None, ) if not path: - return - self._do_save(Path(path)) + return False + return self._do_save(Path(path)) def _do_save(self, path): + """Write the personality; True on success. Callers that were about + to close or replace the document must stop when this is False.""" + path = Path(path) try: - # Check if we have a previous state to diff against has_changes = (self._last_saved_bytes is not None and self.prs.to_bytes() != self._last_saved_bytes) - write_prs(self.prs, path, backup=True) - self.prs_path = path - self.modified = False - self._update_title() - self._status_modified.config(text="Saved", foreground="green") - self.status_set(f"Saved to {path.name}") - log_action("file_save", - path=str(path), - size=len(self.prs.to_bytes())) - - # Offer to view change report if there were modifications - if has_changes: - self._offer_change_report() - - # Update saved bytes snapshot - self._last_saved_bytes = self.prs.to_bytes() except Exception as e: log_error("file_save", str(e), path=str(path)) messagebox.showerror("Error", f"Failed to save:\n{e}") + return False + + self.prs_path = path + self.modified = False + self._update_title() + fg = "#e0e0e0" if self.dark_mode else "black" + self.file_label.config(text=path.name, foreground=fg) + saved = self.prs.to_bytes() + self.size_label.config(text=f"{len(saved):,} bytes") + self._status_modified.config(text="Saved", foreground="green") + self.status_set(f"Saved to {path.name}") + self._remember_path(path) + log_action("file_save", path=str(path), size=len(saved)) + + # Offer to view change report if there were modifications + if has_changes: + self._offer_change_report() + + # Update saved bytes snapshot + self._last_saved_bytes = saved + return True def _offer_change_report(self): """Ask if the user wants to view a change report after save.""" @@ -1085,7 +1140,7 @@ def _show_health_check(self): results = run_health_check(self.prs) health_lines = format_health_report(results) - filepath = self.current_path or "file.PRS" + filepath = str(self.prs_path) if self.prs_path else "file.PRS" suggestions = suggest_improvements(self.prs, filepath=filepath) suggest_lines = format_suggestions(suggestions, filepath=filepath) @@ -1705,14 +1760,8 @@ def import_scanner_csv(self): def new_blank(self): """Create a new blank personality file.""" - if self.modified: - result = messagebox.askyesnocancel( - "Unsaved Changes", - "You have unsaved changes. Save before creating a new file?") - if result is None: - return - if result: - self.save_file() + if not self._confirm_discard("create a new file"): + return path = filedialog.asksaveasfilename( title="Create New Blank Personality", @@ -1726,18 +1775,9 @@ def new_blank(self): try: from ..builder import create_blank_prs name = Path(path).name - self.prs = create_blank_prs(filename=name) - self.prs_path = Path(path) - self._do_save(self.prs_path) - self.modified = False - self._hide_welcome() - self._update_title() - fg = "#e0e0e0" if self.dark_mode else "black" - self.file_label.config(text=name, foreground=fg) - self.personality_view.refresh() - self._update_stats() - self.size_label.config( - text=f"{len(self.prs.to_bytes()):,} bytes") + self._set_document(create_blank_prs(filename=name), path) + if not self._do_save(self.prs_path): + return self.status_set("Created new blank personality") log_action("new_blank", path=str(path)) except Exception as e: @@ -1747,14 +1787,8 @@ def new_blank(self): def build_from_config(self): """Build a PRS personality from an INI config file.""" - if self.modified: - result = messagebox.askyesnocancel( - "Unsaved Changes", - "You have unsaved changes. Save before building?") - if result is None: - return - if result: - self.save_file() + if not self._confirm_discard("build a new personality"): + return config_path = filedialog.askopenfilename( title="Select Config File", @@ -1783,19 +1817,9 @@ def build_from_config(self): return try: - self.prs = prs - self.prs_path = Path(save_path) - self._do_save(self.prs_path) - self.modified = False - self._hide_welcome() - self._update_title() - fg = "#e0e0e0" if self.dark_mode else "black" - self.file_label.config( - text=self.prs_path.name, foreground=fg) - self.personality_view.refresh() - self._update_stats() - self.size_label.config( - text=f"{len(self.prs.to_bytes()):,} bytes") + self._set_document(prs, save_path) + if not self._do_save(self.prs_path): + return self.status_set( f"Built personality from {Path(config_path).name}") log_action("build_from_config", config=config_path, @@ -1863,14 +1887,8 @@ def export_config(self): def import_json(self): """Import a PRS personality from a JSON file.""" - if self.modified: - result = messagebox.askyesnocancel( - "Unsaved Changes", - "You have unsaved changes. Save before importing?") - if result is None: - return - if result: - self.save_file() + if not self._confirm_discard("import a new personality"): + return json_path = filedialog.askopenfilename( title="Import JSON", @@ -1902,19 +1920,9 @@ def import_json(self): return try: - self.prs = prs - self.prs_path = Path(save_path) - self._do_save(self.prs_path) - self.modified = False - self._hide_welcome() - self._update_title() - fg = "#e0e0e0" if self.dark_mode else "black" - self.file_label.config( - text=self.prs_path.name, foreground=fg) - self.personality_view.refresh() - self._update_stats() - self.size_label.config( - text=f"{len(self.prs.to_bytes()):,} bytes") + self._set_document(prs, save_path) + if not self._do_save(self.prs_path): + return self.status_set( f"Imported from {Path(json_path).name}") log_action("import_json", json_path=json_path, @@ -2166,10 +2174,10 @@ def on_apply(): for (element, attr), (entry_widget, orig_val) in entries.items(): new_val = entry_widget.get().strip() if new_val != orig_val: - # Resolve the section name for set_platform_option - section = element.split('/')[0] if '/' in element else element + # The full path, so a nested element such as + # audioConfig/microphone[micType=INTERNAL] is the one set try: - set_platform_option(self.prs, section, attr, new_val) + set_platform_option(self.prs, element, attr, new_val) changed += 1 except Exception as e: errors.append(f"{element}.{attr}: {e}") @@ -2769,7 +2777,10 @@ def show_shortcuts(self): font=("Consolas", 10)).pack(side=tk.LEFT) ttk.Label(row, text=desc).pack(side=tk.LEFT, padx=4) - btn = ttk.Button(frame, text="Close", command=win.destroy, width=10) + # Close through _on_close so the global mouse-wheel binding goes + # with the window + btn = ttk.Button(frame, text="Close", command=lambda: _on_close(), + width=10) btn.pack(pady=(12, 0)) frame.update_idletasks() @@ -3296,15 +3307,12 @@ def _save_geometry(self): save_settings(self.settings) def _on_close(self): - if self.modified: - result = messagebox.askyesnocancel( - "Unsaved Changes", - "You have unsaved changes. Save before closing?") - if result is None: # Cancel - return - if result: # Yes - self.save_file() - self._save_geometry() + if not self._confirm_discard("close"): + return + try: + self._save_geometry() + except Exception as e: + log_error("save_geometry", str(e)) self.root.destroy() diff --git a/quickprs/gui/import_wizard.py b/quickprs/gui/import_wizard.py index 8a099f4..29bfe5b 100644 --- a/quickprs/gui/import_wizard.py +++ b/quickprs/gui/import_wizard.py @@ -616,29 +616,34 @@ def _import_from_database(self): get_template, get_default_name, find_matching_iden_set, ) + # Auto-select IDEN template + iden_key = get_iden_template_key(sys) + existing_iden = find_matching_iden_set(self.app.prs, iden_key) + iden_set = None + iden_name = existing_iden or "" + if not existing_iden: + template = get_template(iden_key) + if template: + iden_name = get_default_name(iden_key) + iden_set = make_iden_set(iden_name, template.entries) + # Create an empty P25 system with the database info config = P25TrkSystemConfig( - short_name=sys.name[:8], + system_name=sys.name[:8], long_name=sys.long_name[:16], - sys_id=sys.system_id, + trunk_set_name=sys.name[:8], + group_set_name=sys.name[:8], + wan_name=sys.name[:8], + system_id=sys.system_id, wacn=sys.wacn, - flags=build_sys_flags(), + sys_flags=build_sys_flags(self.app.settings), + iden_set_name=iden_name, ) # Add empty group and trunk sets group_set = make_group_set(sys.name[:8], []) trunk_set = make_trunk_set(sys.name[:8], []) - # Auto-select IDEN template - iden_key = get_iden_template_key(sys) - existing_iden = find_matching_iden_set(self.app.prs, iden_key) - iden_set = None - if not existing_iden: - template = get_template(iden_key) - if template: - iden_name = get_default_name(iden_key) - iden_set = make_iden_set(iden_name, template) - add_p25_trunked_system( self.app.prs, config, trunk_set=trunk_set, @@ -793,9 +798,7 @@ def _preview_clipboard(self): lines.append(f"Detected: {len(channels)} conventional channels") lines.append("") for i, ch in enumerate(channels[:30]): - name = ch.get('short_name', ch.get('name', '')) - freq = ch.get('tx_freq', ch.get('freq', 0)) - lines.append(f" {i+1}. {name} - {freq:.4f} MHz") + lines.append(f" {i+1}. {ch.name} - {ch.freq:.5f} MHz") if len(channels) > 30: lines.append(f"... and {len(channels) - 30} more") @@ -863,15 +866,19 @@ def _import_clipboard(self): self._inject_channels(set_name, channels_data) elif self._clip_data_type == 'channels': + # parse_pasted_conv_channels returns ConvChannelData + # objects: freq is the receive frequency, tx_freq 0 means + # simplex. channels_data = [] for ch in self._clip_data: + rx = ch.freq channels_data.append({ - 'short_name': ch.get('short_name', ch.get('name', ''))[:8], - 'tx_freq': ch.get('tx_freq', ch.get('freq', 0)), - 'rx_freq': ch.get('rx_freq', ch.get('freq', 0)), - 'tx_tone': ch.get('tx_tone', ''), - 'rx_tone': ch.get('rx_tone', ''), - 'long_name': ch.get('long_name', '')[:16], + 'short_name': (ch.name or f"{rx:.4f}")[:8], + 'tx_freq': ch.tx_freq or rx, + 'rx_freq': rx, + 'tx_tone': ch.tx_tone or ch.tone, + 'rx_tone': ch.tone, + 'long_name': (ch.description or ch.name)[:16], }) self._inject_channels(set_name, channels_data) @@ -891,12 +898,15 @@ def _inject_channels(self, set_name, channels_data): from ..record_types import ConvSystemConfig conv_set = make_conv_set(set_name, channels_data) - config = ConvSystemConfig(short_name=set_name[:8]) + config = ConvSystemConfig(system_name=set_name[:8], + long_name=set_name[:16], + conv_set_name=set_name[:8]) add_conv_system(self.app.prs, config, conv_set=conv_set) def _inject_talkgroups(self, set_name, tgs_data): """Inject a list of talkgroup dicts as a new group set.""" - from ..injector import make_group_set, add_group_set + from ..injector import make_group_set + from ..injector import _safe_add_group_set as add_group_set tg_tuples = [] for tg in tgs_data: diff --git a/quickprs/gui/personality_view.py b/quickprs/gui/personality_view.py index 1635109..2824812 100644 --- a/quickprs/gui/personality_view.py +++ b/quickprs/gui/personality_view.py @@ -2351,7 +2351,7 @@ def _add_to_favorites(self, category, name): self.app.status_set( f"'{name}' is already in favorites") except Exception as e: - log_error(f"Failed to add favorite: {e}") + log_error("add_favorite", str(e)) messagebox.showerror("Error", f"Could not add favorite: {e}") def _remove_from_favorites(self, category, name): @@ -2366,7 +2366,7 @@ def _remove_from_favorites(self, category, name): else: self.app.status_set(f"'{name}' not found in favorites") except Exception as e: - log_error(f"Failed to remove favorite: {e}") + log_error("remove_favorite", str(e)) messagebox.showerror("Error", f"Could not remove favorite: {e}") @@ -3003,7 +3003,9 @@ def _add_group_set_dialog(self): set_name = set_name[:8] try: - from ..injector import add_group_set, make_group_set + # _safe_ variants also create the first set of a blank file + from ..injector import _safe_add_group_set as add_group_set + from ..injector import make_group_set group_set = make_group_set(set_name, [ (1, "TG 1", "TALKGROUP 1"), ]) @@ -3037,7 +3039,8 @@ def _add_trunk_set_dialog(self): set_name = set_name[:8] try: - from ..injector import add_trunk_set, make_trunk_set + from ..injector import _safe_add_trunk_set as add_trunk_set + from ..injector import make_trunk_set trunk_set = make_trunk_set(set_name, [ (851.0125, 806.0125), ]) @@ -3071,7 +3074,8 @@ def _add_conv_set_dialog(self): set_name = set_name[:8] try: - from ..injector import add_conv_set, make_conv_set + from ..injector import _safe_add_conv_set as add_conv_set + from ..injector import make_conv_set conv_set = make_conv_set(set_name, [ {"short_name": "CH 1", "tx_freq": 462.5625}, ]) @@ -3406,6 +3410,19 @@ def _batch_group_set(self, set_name, field, value): except Exception as e: messagebox.showerror("Error", f"Batch operation failed:\n{e}") + def _selected_tg_pairs(self, tg_items): + """(set name, talkgroup ID) of each selected row. Matching on the + pair matters: the same ID can sit in several sets, and selecting it + in one set must not change it in the others.""" + pairs = set() + for iid, meta in tg_items: + gid = meta.get("group_id") + parent_meta = self._item_meta.get(self.tree.parent(iid), {}) + set_name = parent_meta.get("name", "") + if gid is not None and set_name: + pairs.add((set_name, gid)) + return pairs + def _batch_selected_tgs(self, tg_items, set_names, field, value): """Batch-modify a field on specifically selected talkgroups.""" prs = self.app.prs @@ -3428,11 +3445,7 @@ def _batch_selected_tgs(self, tg_items, set_names, field, value): grp_sec, parse_group_section, first_count) # Build set of selected group IDs - selected_ids = set() - for _, meta in tg_items: - gid = meta.get("group_id") - if gid is not None: - selected_ids.add(gid) + selected_ids = self._selected_tg_pairs(tg_items) label = "TX" if field == "tx" else "Scan" action = "Enable" if value else "Disable" @@ -3449,7 +3462,7 @@ def _batch_selected_tgs(self, tg_items, set_names, field, value): if gs.name not in set_names: continue for g in gs.groups: - if g.group_id in selected_ids: + if (gs.name, g.group_id) in selected_ids: setattr(g, field, value) changed += 1 @@ -3492,11 +3505,7 @@ def _batch_delete_selected_tgs(self, tg_items, set_names): existing_sets = _parse_section_data( grp_sec, parse_group_section, first_count) - selected_ids = set() - for _, meta in tg_items: - gid = meta.get("group_id") - if gid is not None: - selected_ids.add(gid) + selected_ids = self._selected_tg_pairs(tg_items) self.app.save_undo_snapshot("Delete selected TGs") removed = 0 @@ -3505,7 +3514,7 @@ def _batch_delete_selected_tgs(self, tg_items, set_names): continue orig = len(gs.groups) gs.groups = [g for g in gs.groups - if g.group_id not in selected_ids] + if (gs.name, g.group_id) not in selected_ids] removed += orig - len(gs.groups) _replace_group_sections(prs, existing_sets, byte1, byte2, @@ -3542,11 +3551,7 @@ def _batch_edit_selected_tgs(self, tg_items, set_names): messagebox.showerror("Error", f"Failed to parse groups:\n{e}") return - selected_ids = set() - for _, meta in tg_items: - gid = meta.get("group_id") - if gid is not None: - selected_ids.add(gid) + selected_ids = self._selected_tg_pairs(tg_items) count = len(selected_ids) @@ -3627,7 +3632,7 @@ def _apply(): if gs.name not in set_names: continue for g in gs.groups: - if g.group_id in selected_ids: + if (gs.name, g.group_id) in selected_ids: if tx_choice == "enable": g.tx = True elif tx_choice == "disable": diff --git a/quickprs/gui/system_wizard.py b/quickprs/gui/system_wizard.py index 702783f..35ce33a 100644 --- a/quickprs/gui/system_wizard.py +++ b/quickprs/gui/system_wizard.py @@ -565,6 +565,10 @@ def _parse_talkgroups(self): continue return tgs + def _bad_talkgroup_ids(self, tgs): + """IDs outside 1-65535, which a talkgroup cannot hold.""" + return [gid for gid, _, _ in tgs if not 1 <= gid <= 65535] + def _finish(self): """Add the system to the personality and close.""" if not self.app.prs: @@ -573,21 +577,36 @@ def _finish(self): name = self.sys_name.get().strip()[:8] long_name = self.sys_long_name.get().strip()[:16] or name - sys_id = int(self.sys_id.get().strip()) - wacn = int(self.sys_wacn.get().strip()) + try: + sys_id = int(self.sys_id.get().strip()) + wacn = int(self.sys_wacn.get().strip()) + except ValueError: + messagebox.showerror("Invalid Input", + "System ID and WACN must be numbers.", + parent=self) + return band = self.sys_band.get() sys_type = self.sys_type.get() + # Check everything before touching the personality + freqs = self._parse_freqs() + tgs = self._parse_talkgroups() + bad = self._bad_talkgroup_ids(tgs) + if bad: + messagebox.showerror( + "Invalid Talkgroups", + "Talkgroup IDs must be 1-65535. Out of range: " + + ", ".join(str(b) for b in bad[:10]), + parent=self) + return + # Save undo state self.app.save_undo_snapshot("Add P25 System via Wizard") + before = self.app.prs.to_bytes() try: prs = self.app.prs - # Parse data - freqs = self._parse_freqs() - tgs = self._parse_talkgroups() - # Build sets trunk_set = make_trunk_set(name, freqs) if freqs else None group_set = None @@ -639,15 +658,13 @@ def _finish(self): issues = validate_prs(prs) errors = [(s, m) for s, m in issues if s == ERROR] - self.app.modified = True - self.app._update_title() + self.app.mark_modified() self.app.personality_view.refresh() freq_str = f"{len(freqs)} freqs" if freqs else "no freqs" tg_str = f"{len(tgs)} TGs" if tgs else "no TGs" - log_action("wizard_add", - f"Added P25 system '{name}' " - f"(SysID {sys_id}, {freq_str}, {tg_str})") + log_action("wizard_add", system=name, sysid=sys_id, + freqs=freq_str, talkgroups=tg_str) if errors: messagebox.showwarning( @@ -667,6 +684,12 @@ def _finish(self): self.destroy() except Exception as e: + # Put the personality back the way it was, so a failed add + # cannot leave half a system behind + from ..prs_parser import parse_prs_bytes + self.app.prs.sections = parse_prs_bytes( + before, verify=False).sections + self.app.personality_view.refresh() log_error("wizard_add", str(e)) messagebox.showerror( "Error", @@ -826,8 +849,7 @@ def _add_system(self): self.app.modified = True self.app._update_title() self.app.personality_view.refresh() - log_action("db_add", - f"Added '{sys.name}' from system database") + log_action("db_add", system=sys.name) messagebox.showinfo( "System Added", f"P25 system '{sys.name}' added.\n" diff --git a/quickprs/option_maps.py b/quickprs/option_maps.py index 10c7ef1..87bb942 100644 --- a/quickprs/option_maps.py +++ b/quickprs/option_maps.py @@ -18,6 +18,7 @@ """ import logging +import re import struct import xml.etree.ElementTree as ET from dataclasses import dataclass, field @@ -177,26 +178,74 @@ def _dict_to_element(d, tag): } +# platformConfig of a new XG-100P personality exactly as RPM 14 +# writes it (every attribute at RPM's default), used when a +# personality has no radio options block yet. _DEFAULT_PLATFORM_XML = ( '' - '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + 'linearUnits="STATUTE" angularUnits="CARDINAL" ' + 'elevationBasis="SEA_LEVEL" gridDigits="10" northing="TRUE" />' '' - '' - '' + 'tones="OFF" cctTimer="120" minVol="0" pttAudio="RADIO_ACCESSORY">' + '' + '' + '' + '' + '' '' - '' - '' '' ) @@ -206,123 +255,145 @@ def _create_default_platform_xml(): return _DEFAULT_PLATFORM_XML +def _cstring(text): + """Encode an MFC CString (1-byte length, or 0xFF + 16-bit length).""" + raw = text.encode("ascii") + if len(raw) < 0xFF: + return struct.pack("= {field.min_val}") + if field.max_val is not None and num > field.max_val: + raise ValueError(f"{field.attribute} must be <= {field.max_val}") + - Finds the XML in the PRS data, modifies the specified attribute, - and rebuilds the section with the updated XML (including the - uint16 length prefix). +def set_platform_option(prs, section_name, attr_name, value, + create=False): + """Modify a platformConfig XML attribute in the PRS file. Args: prs: parsed PRSFile object - section_name: friendly section name (e.g. 'gps', 'audio') - or XML element name (e.g. 'gpsConfig', 'audioConfig') + section_name: friendly section name ('gps', 'audio'), XML element + name ('gpsConfig') or a nested path such as + 'audioConfig/microphone[micType=INTERNAL]' attr_name: XML attribute name (e.g. 'gpsMode', 'speakerMode') value: new value as string + create: allow adding an attribute QuickPRS does not know about Returns: - True if the attribute was modified, False on error. + True when the attribute was set. Raises: - ValueError: if no platformConfig found, section unknown, - or attribute not found in the XML. + ValueError: no platformConfig and none could be added, unknown + element or attribute, or a value the field does not allow. """ xml_str = extract_platform_xml(prs) if xml_str is None: - # Create a default platformConfig XML and inject it - xml_str = _create_default_platform_xml() - if not _inject_platform_xml(prs, xml_str): + # Start from the options RPM writes for a new radio + if not _inject_platform_xml(prs, _create_default_platform_xml()): raise ValueError( "No platformConfig XML found and unable to create one") + xml_str = extract_platform_xml(prs) - # Resolve friendly section name to XML element name - xml_element = SECTION_MAP.get(section_name, section_name) - - # Parse the XML root = ET.fromstring(xml_str) - - # Find the target element - target = root.find(xml_element) + target = _find_option_element(root, section_name) if target is None: - valid = [child.tag for child in root] + valid = sorted({child.tag for child in root}) raise ValueError( - f"Section '{xml_element}' not found in platformConfig. " - f"Available: {', '.join(sorted(set(valid)))}") + f"Section '{section_name}' not found in platformConfig. " + f"Available: {', '.join(valid)}") - # Check if attribute exists (warn but still set it) - old_val = target.get(attr_name) - if old_val is None: - # Attribute doesn't exist — could be new. Set it anyway but log. - logger.info("Attribute '%s' not found in <%s>, creating it", - attr_name, xml_element) + field = _field_def(section_name, attr_name) + if target.get(attr_name) is None and field is None and not create: + known = sorted(target.attrib) + raise ValueError( + f"<{target.tag}> has no attribute '{attr_name}'. " + f"Attributes: {', '.join(known) or '(none)'}") + _check_option_value(field, value) - # Set the attribute target.set(attr_name, str(value)) # Rebuild XML and write back diff --git a/quickprs/profile_templates.py b/quickprs/profile_templates.py index c486eff..9fd8fea 100644 --- a/quickprs/profile_templates.py +++ b/quickprs/profile_templates.py @@ -31,7 +31,7 @@ 'description': 'Public safety interoperability setup', 'templates': ['interop', 'public_safety'], 'custom_channels': [], - 'options': {'gps.gpsMode': 'ON', 'gps.reportInterval': '30'}, + 'options': {'gps.gpsMode': 'ON'}, }, 'ham_portable': { 'description': 'Amateur radio operator portable setup', @@ -69,7 +69,7 @@ {'short_name': 'HAZCHEM', 'tx_freq': 155.175, 'long_name': 'HazMat/Chemical'}, ], - 'options': {'gps.gpsMode': 'ON', 'gps.reportInterval': '30'}, + 'options': {'gps.gpsMode': 'ON'}, }, 'law_enforcement': { 'description': 'Law enforcement base configuration', @@ -97,7 +97,7 @@ {'short_name': 'CLEMARS', 'tx_freq': 155.205, 'long_name': 'CLEMARS'}, ], - 'options': {'gps.gpsMode': 'ON', 'gps.reportInterval': '15'}, + 'options': {'gps.gpsMode': 'ON'}, }, 'search_rescue': { 'description': 'Search and Rescue configuration', @@ -108,7 +108,7 @@ {'short_name': 'SAR CMD', 'tx_freq': 155.205, 'long_name': 'SAR Command'}, ], - 'options': {'gps.gpsMode': 'ON', 'gps.reportInterval': '60'}, + 'options': {'gps.gpsMode': 'ON'}, }, } diff --git a/run.py b/run.py index c7e107d..6849440 100644 --- a/run.py +++ b/run.py @@ -11,49 +11,36 @@ """ import sys +from pathlib import Path + + +def _gui_target(argv): + """(True, file or None) when the arguments ask for the GUI. + + No arguments, or a personality file, opens the GUI; anything else is a + CLI command (argparse reports unknown ones), so new commands never + need to be listed here. + """ + if len(argv) < 2: + return True, None + arg = argv[1] + if arg.startswith("-"): + return False, None + path = Path(arg) + if path.suffix.lower() == ".prs" or path.is_file(): + return True, arg + return False, None def main(): - # Check if any CLI subcommand is being used - cli_commands = { - # Create & Build - "create", "build", "profiles", "wizard", "fleet", - # Modify - "inject", "remove", "edit", "merge", "clone", "clone-personality", - "rename", "sort", "renumber", "auto-name", "bulk-edit", - # Import - "import-rr", "import-paste", "import-scanner", "import-json", - "auto-setup", "systems", "template-csv", - # Export - "export", "export-csv", "export-json", "export-config", - "report", "card", - # Inspect & Validate - "info", "validate", "compare", "diff-report", "diff-options", - "stats", "capacity", "list", "dump", - # Radio Options - "set-option", "encrypt", "set-nac", - # Planning & Tools - "zones", "freq-tools", "iden-templates", - # Maintenance - "repair", "cleanup", "search", "backup", - } - cli_flags = {"--version", "-V", "--completion"} - - has_cli = (len(sys.argv) > 1 and - (sys.argv[1] in cli_commands or sys.argv[1] in cli_flags)) - - if has_cli: + gui, filepath = _gui_target(sys.argv) + if not gui: from quickprs.cli import run_cli result = run_cli() sys.exit(result if result is not None else 0) - else: - # GUI mode — pass first arg as filepath if it looks like a file - filepath = None - if len(sys.argv) > 1 and not sys.argv[1].startswith('-'): - filepath = sys.argv[1] - - from quickprs.gui.app import main as gui_main - gui_main(filepath=filepath) + + from quickprs.gui.app import main as gui_main + gui_main(filepath=filepath) if __name__ == "__main__": diff --git a/tests/test_favorites.py b/tests/test_favorites.py index b863b04..059b8eb 100644 --- a/tests/test_favorites.py +++ b/tests/test_favorites.py @@ -371,10 +371,10 @@ def test_field_ops_preset(self): assert preset['options']['gps.gpsMode'] == 'ON' def test_covert_preset(self): - """Covert preset disables GPS and LEDs.""" + """Covert preset disables GPS and the tri-color LED.""" preset = PRESETS['covert'] assert preset['options']['gps.gpsMode'] == 'OFF' - assert preset['options']['misc.ledEnabled'] == 'false' + assert preset['options']['misc.enableTriColorLed'] == 'OFF' def test_training_preset(self): """Training preset enables GPS.""" @@ -382,10 +382,20 @@ def test_training_preset(self): assert preset['options']['gps.gpsMode'] == 'ON' def test_gps_on_preset(self): - """GPS on preset enables GPS with interval.""" + """GPS on preset enables GPS (the XG-100P options have no + reporting-interval attribute).""" preset = PRESETS['gps_on'] - assert preset['options']['gps.gpsMode'] == 'ON' - assert 'gps.reportInterval' in preset['options'] + assert preset['options'] == {'gps.gpsMode': 'ON'} + + def test_every_preset_applies_to_a_blank(self): + """Every preset key is a real attribute with an allowed value.""" + from quickprs.builder import create_blank_prs + from quickprs.option_maps import set_platform_option + for name, preset in PRESETS.items(): + prs = create_blank_prs() + for key, value in preset['options'].items(): + section, attr = key.split('.', 1) + set_platform_option(prs, section, attr, value) def test_gps_off_preset(self): """GPS off preset disables GPS.""" diff --git a/tests/test_fleet_check.py b/tests/test_fleet_check.py index 3e6e9ea..a1c4ec9 100644 --- a/tests/test_fleet_check.py +++ b/tests/test_fleet_check.py @@ -365,17 +365,10 @@ def test_search_rescue_has_marine(self): profile = get_profile_template('search_rescue') assert 'marine' in profile['templates'] - def test_fire_has_gps_30s(self): - profile = get_profile_template('fire_department') - assert profile['options']['gps.reportInterval'] == '30' - - def test_ems_has_gps_15s(self): - profile = get_profile_template('ems') - assert profile['options']['gps.reportInterval'] == '15' - - def test_search_rescue_has_gps_60s(self): - profile = get_profile_template('search_rescue') - assert profile['options']['gps.reportInterval'] == '60' + def test_profiles_turn_gps_on(self): + for name in ('fire_department', 'ems', 'search_rescue'): + profile = get_profile_template(name) + assert profile['options'] == {'gps.gpsMode': 'ON'}, name def test_all_profiles_listed(self): names = [name for name, _ in list_profile_templates()] diff --git a/tests/test_gui_smoke.py b/tests/test_gui_smoke.py new file mode 100644 index 0000000..3c42950 --- /dev/null +++ b/tests/test_gui_smoke.py @@ -0,0 +1,137 @@ +"""Smoke tests that build the real GUI on a hidden Tk window. + +Nothing here opens a visible window or runs the event loop; message boxes +are patched. These tests exist because the app once crashed on start +(a missing argument in the welcome screen) and no test constructed it. +""" + +import shutil +from pathlib import Path +from unittest import mock + +import pytest + +tk = pytest.importorskip("tkinter") + +TESTDATA = Path(__file__).parent / "testdata" +PAWS = TESTDATA / "PAWSOVERMAWS.PRS" + + +@pytest.fixture(scope="module") +def tk_root(): + """One Tk interpreter for the module: creating many in one process + fails now and then on Windows ("Tcl wasn't installed properly").""" + try: + root = tk.Tk() + except tk.TclError as e: + pytest.skip(f"no Tk display: {e}") + root.withdraw() + yield root + root.destroy() + + +@pytest.fixture +def app(tk_root, tmp_path, monkeypatch): + """A QuickPRSApp on a hidden window, with settings in tmp_path.""" + from quickprs.gui import settings as gui_settings + monkeypatch.setattr(gui_settings, "SETTINGS_DIR", tmp_path / "cfg") + monkeypatch.setattr(gui_settings, "SETTINGS_FILE", + tmp_path / "cfg" / "settings.json") + top = tk.Toplevel(tk_root) + top.withdraw() + from quickprs.gui.app import QuickPRSApp + with mock.patch("quickprs.gui.app.messagebox"): + application = QuickPRSApp(top) + yield application + top.destroy() + + +def test_app_starts(app): + assert app.prs is None + assert "QuickPRS" in app.root.title() + + +def test_open_resets_undo_history(app, tmp_path): + from quickprs.builder import create_blank_prs + from quickprs.prs_writer import write_prs + a, b = tmp_path / "a.PRS", tmp_path / "b.PRS" + write_prs(create_blank_prs("a.PRS"), a) + write_prs(create_blank_prs("b.PRS"), b) + + app._open_path(a, confirmed=True) + app.save_undo_snapshot("edit A") + assert app._undo_stack.can_undo() + app._open_path(b, confirmed=True) + # Undo history belonged to A; undoing must not put A's bytes into B + assert not app._undo_stack.can_undo() + assert app.prs_path == b + assert app.modified is False + + +def test_failed_save_stops_close(app, tmp_path): + from quickprs.builder import create_blank_prs + app._set_document(create_blank_prs("x.PRS"), tmp_path / "x.PRS") + app.modified = True + with mock.patch("quickprs.gui.app.messagebox") as mb, \ + mock.patch("quickprs.gui.app.write_prs", + side_effect=PermissionError("locked")): + mb.askyesnocancel.return_value = True # "Save first" + assert app._confirm_discard("close") is False + mb.showerror.assert_called() + + +def test_keys_ignored_in_text_fields(app): + calls = [] + handler = app._unless_typing(lambda: calls.append(1)) + entry = tk.Entry(app.root) + tree_event = mock.Mock(widget=app.root) + entry_event = mock.Mock(widget=entry) + assert handler(entry_event) is None and calls == [] + assert handler(tree_event) == "break" and calls == [1] + + +def test_selected_pairs_are_exact(app): + """Selecting TG 100 in set A must not select TG 100 in set B.""" + pv = app.personality_view + tree = pv.tree + a = tree.insert("", "end", text="A") + b = tree.insert("", "end", text="B") + pv._item_meta[a] = {"name": "SET A"} + pv._item_meta[b] = {"name": "SET B"} + t1 = tree.insert(a, "end", text="100") + t2 = tree.insert(b, "end", text="200") + pairs = pv._selected_tg_pairs([(t1, {"group_id": 100}), + (t2, {"group_id": 200})]) + assert pairs == {("SET A", 100), ("SET B", 200)} + + +@pytest.mark.skipif(not PAWS.exists(), reason="PAWSOVERMAWS.PRS not available") +def test_open_real_file_and_refresh(app, tmp_path): + copy = tmp_path / "p.PRS" + shutil.copy(PAWS, copy) + app._open_path(copy, confirmed=True) + assert app.prs is not None + assert app.personality_view.tree.get_children() + + +def test_wizard_rejects_out_of_range_talkgroups(): + from quickprs.gui.system_wizard import SystemWizard + bad = SystemWizard._bad_talkgroup_ids(None, [(70000, "X", "X"), + (5, "Y", "Y"), + (0, "Z", "Z")]) + assert bad == [70000, 0] + + +def test_import_wizard_injects_into_blank(app): + """The import wizard's helpers used config fields that do not exist + and the non-creating group adder, so every import failed.""" + from quickprs import archive + from quickprs.builder import create_blank_prs + from quickprs.gui.import_wizard import ImportWizard + app.prs = create_blank_prs() + fake = mock.Mock(app=app) + ImportWizard._inject_channels(fake, "MURS", [ + {"short_name": "MURS1", "tx_freq": 151.82}]) + ImportWizard._inject_talkgroups(fake, "TGS", [ + {"group_id": 100, "short_name": "TG100", "long_name": "TG 100"}]) + assert archive.check(app.prs) == [] diff --git a/tests/test_platform_options.py b/tests/test_platform_options.py new file mode 100644 index 0000000..e8e8c31 --- /dev/null +++ b/tests/test_platform_options.py @@ -0,0 +1,73 @@ +"""platformConfig (radio options) editing: real attributes only, values +checked, nested elements addressed exactly, and the XML placed where RPM +keeps it.""" + +import re + +import pytest + +from quickprs import archive +from quickprs.builder import create_blank_prs +from quickprs.option_maps import ( + set_platform_option, extract_platform_xml, list_platform_options, + _DEFAULT_PLATFORM_XML, +) + + +@pytest.fixture +def blank(): + return create_blank_prs() + + +def test_default_xml_is_rpm_new_radio(): + assert _DEFAULT_PLATFORM_XML.startswith(" 12 + ("nosuchsection", "x", "1"), +]) +def test_bad_options_rejected(blank, section, attr, value): + with pytest.raises(ValueError): + set_platform_option(blank, section, attr, value) + + +def test_known_attribute_can_be_created(blank): + set_platform_option(blank, "misc", "password", "1234") + assert 'password="1234"' in extract_platform_xml(blank) + + +def test_nested_element_is_the_one_changed(blank): + set_platform_option(blank, "audioConfig/microphone[micType=INTERNAL]", + "alc", "ON") + mics = re.findall(r"]*>", extract_platform_xml(blank)) + assert 'micType="INTERNAL" alc="ON"' in mics[0] + assert 'micType="EXTERNAL" alc="OFF"' in mics[1] + assert " Date: Tue, 27 Oct 2026 21:07:12 -0700 Subject: [PATCH 05/14] Fix RadioReference login, repeater offsets and TX/RX order - import-rr and auto-setup passed the API key as the account password (RadioReferenceAPI(username, apikey, apikey)), so the documented commands could not log in. They take --password (or QUICKPRS_RR_USER / _PASSWORD / _APIKEY, and ask for the password when a terminal is attached, keeping it out of shell history). - 2 m repeater offsets were reversed: per the ARRL band plan 146.61- 146.97 MHz outputs take -600 kHz and 147.00-147.39 MHz take +600 kHz (freq-tools offset 146.94 printed input 147.54; it is 146.34). - RPM stores a trunk channel's TX on the site uplink (806 MHz) and RX on the downlink (851 MHz), but the README, example INIs and CSV templates showed 851,806 under a tx,rx header, which builds a radio listening on the uplink. Examples are corrected, the README INI block now parses (key = value lines), and validation warns when a trunk set's TX and RX look swapped. - import-paste paired every pasted frequency with itself; it now pairs each listed downlink with its band's uplink, as the GUI already did. --- README.md | 30 ++++++----- quickprs/cli.py | 87 ++++++++++++++++++++++++------ quickprs/config_builder.py | 4 +- quickprs/freq_tools.py | 6 ++- quickprs/validation.py | 15 ++++++ tests/test_cli.py | 3 +- tests/test_cli_import.py | 40 +++++++------- tests/test_config_builder.py | 9 ++-- tests/test_freq_tools.py | 27 +++++----- tests/test_property_based.py | 4 +- tests/test_validation.py | 11 +++- tests/testdata/example_patrol.ini | 12 ++--- tests/testdata/example_scanner.ini | 14 ++--- 13 files changed, 175 insertions(+), 87 deletions(-) diff --git a/README.md b/README.md index 27f24b8..57becd7 100644 --- a/README.md +++ b/README.md @@ -210,21 +210,24 @@ INI-style config files let you define an entire radio personality in one place: name = PATROL.PRS author = Dispatch -[system.PSERN] +; Example values: use your system's real IDs and frequencies. +[system.COUNTY] type = p25_trunked -long_name = PSERN SEATTLE -system_id = 892 +long_name = COUNTY P25 +system_id = 100 wacn = 781824 -[system.PSERN.frequencies] -851.0125,806.0125 -851.5125,806.5125 -852.0125,807.0125 +[system.COUNTY.frequencies] +; tx_freq (radio transmit = site uplink), rx_freq (site downlink) +1 = 806.0125,851.0125 +2 = 806.5125,851.5125 +3 = 807.0125,852.0125 -[system.PSERN.talkgroups] -1000,PD DISP,Police Dispatch -1001,PD TAC1,Police Tactical 1 -2000,FD DISP,Fire Dispatch +[system.COUNTY.talkgroups] +; id, short_name, long_name +1 = 1000,PD DISP,Police Dispatch +2 = 1001,PD TAC1,Police Tactical 1 +3 = 2000,FD DISP,Fire Dispatch [channels.MURS] template = murs @@ -237,9 +240,8 @@ template = interop [channels.LOCAL] ; short_name, tx_freq, rx_freq, tx_tone, rx_tone, long_name -RPT IN,147.000,147.600,100.0,100.0,Repeater Input -RPT OUT,147.600,147.600,,,Repeater Output -SIMPLEX,146.520,146.520,,,2m Calling +1 = RPT 147,147.600,147.000,100.0,100.0,147.00+ Repeater +2 = SIMPLEX,146.520,146.520,,,2m Calling [options] gps.gpsMode = ON diff --git a/quickprs/cli.py b/quickprs/cli.py index 3cc3962..fc4bcfc 100644 --- a/quickprs/cli.py +++ b/quickprs/cli.py @@ -2454,8 +2454,35 @@ def cmd_set_option(filepath, option_path=None, value=None, list_opts=False, return 0 +def _rr_credentials(username, apikey, password): + """RadioReference login: username, password and app key. + + Each comes from its option, else QUICKPRS_RR_USER / + QUICKPRS_RR_PASSWORD / QUICKPRS_RR_APIKEY, and the password is asked + for (hidden) when a terminal is attached, so it need not appear in + shell history. Returns None (after printing why) when one is missing. + """ + import os + username = username or os.environ.get("QUICKPRS_RR_USER") + apikey = apikey or os.environ.get("QUICKPRS_RR_APIKEY") + password = password or os.environ.get("QUICKPRS_RR_PASSWORD") + if not password and username and sys.stdin.isatty(): + import getpass + password = getpass.getpass(f"RadioReference password for " + f"{username}: ") + missing = [name for name, val in (("--username", username), + ("--password", password), + ("--apikey", apikey)) if not val] + if missing: + print(f"Error: RadioReference login needs {', '.join(missing)} " + f"(or the QUICKPRS_RR_* environment variables)", + file=sys.stderr) + return None + return username, password, apikey + + def cmd_import_rr(filepath, sid=None, url=None, username=None, apikey=None, - categories=None, tags=None, output=None): + categories=None, tags=None, output=None, password=None): """Import a P25 trunked system from RadioReference and inject into PRS. Args: @@ -2500,10 +2527,14 @@ def cmd_import_rr(filepath, sid=None, url=None, username=None, apikey=None, print("Error: --sid or --url is required", file=sys.stderr) return 1 + creds = _rr_credentials(username, apikey, password) + if creds is None: + return 1 + # Fetch system from API print(f"Fetching system {sid} from RadioReference...") try: - api = RadioReferenceAPI(username, apikey, apikey) + api = RadioReferenceAPI(*creds) rr_system = api.get_system(sid) except (ImportError, ConnectionError) as e: print(f"Error: {e}", file=sys.stderr) @@ -2709,6 +2740,10 @@ def cmd_import_paste(filepath, name, sysid, wacn=0, long_name=None, print("Error: no frequencies found in pasted text", file=sys.stderr) return 1 + # RadioReference lists the sites' downlink (receive) frequencies; + # the radio transmits on the band's paired uplink. + from .iden_library import calculate_tx_freq + freqs = [(calculate_tx_freq(rx), rx) for _, rx in freqs] trunk_set = make_trunk_set(name, freqs) freq_count = len(freqs) @@ -3436,7 +3471,7 @@ def cmd_freq_tools(subcmd, freq=None, freq_list=None): def cmd_auto_setup(filepath, sid=None, url=None, username=None, apikey=None, - categories=None, tags=None, output=None): + categories=None, tags=None, output=None, password=None): """One-click RadioReference system setup with ECC and IDEN. Like import-rr but also auto-configures ECC entries and IDEN @@ -3476,10 +3511,14 @@ def cmd_auto_setup(filepath, sid=None, url=None, username=None, apikey=None, print("Error: --sid or --url is required", file=sys.stderr) return 1 + creds = _rr_credentials(username, apikey, password) + if creds is None: + return 1 + # Fetch system from API print(f"Fetching system {sid} from RadioReference...") try: - api = RadioReferenceAPI(username, apikey, apikey) + api = RadioReferenceAPI(*creds) rr_system = api.get_system(sid) except (ImportError, ConnectionError) as e: print(f"Error: {e}", file=sys.stderr) @@ -3844,8 +3883,9 @@ def cmd_template_csv(template_type, output=None): 'default_name': 'freqs.csv', 'content': ( "tx_freq,rx_freq\n" - "# Example: 851.0125,806.0125\n" - "# One frequency pair per line\n" + "# Example: 806.0125,851.0125\n" + "# TX is the radio's transmit (site uplink), RX the site\n" + "# downlink RadioReference lists. One pair per line.\n" ), }, 'talkgroups': { @@ -3889,8 +3929,9 @@ def cmd_template_csv(template_type, output=None): "#wacn = 0\n" "\n" "#[system.MYSYS.frequencies]\n" - "#1 = 851.0125,806.0125\n" - "#2 = 851.0375,806.0375\n" + "# tx_freq (site uplink),rx_freq (site downlink)\n" + "#1 = 806.0125,851.0125\n" + "#2 = 806.0375,851.0375\n" "\n" "#[system.MYSYS.talkgroups]\n" "#1 = 1,DISP,Dispatch\n" @@ -4554,10 +4595,16 @@ def run_cli(args=None): help="RadioReference system ID (from URL: /db/sid/XXXX)") p_rr.add_argument("--url", default=None, help="RadioReference system URL (alternative to --sid)") - p_rr.add_argument("--username", required=True, - help="RadioReference username") - p_rr.add_argument("--apikey", required=True, - help="RadioReference API key") + p_rr.add_argument("--username", default=None, + help="RadioReference username " + "(or QUICKPRS_RR_USER)") + p_rr.add_argument("--password", default=None, + help="RadioReference password (or " + "QUICKPRS_RR_PASSWORD; asked for " + "when omitted)") + p_rr.add_argument("--apikey", default=None, + help="RadioReference API (app) key " + "(or QUICKPRS_RR_APIKEY)") p_rr.add_argument("--categories", default=None, help="Comma-separated category IDs to include " "(default: all)") @@ -5021,10 +5068,16 @@ def run_cli(args=None): p_auto.add_argument("--url", default=None, help="RadioReference system URL (alternative " "to --sid)") - p_auto.add_argument("--username", required=True, - help="RadioReference username") - p_auto.add_argument("--apikey", required=True, - help="RadioReference API key") + p_auto.add_argument("--username", default=None, + help="RadioReference username " + "(or QUICKPRS_RR_USER)") + p_auto.add_argument("--password", default=None, + help="RadioReference password (or " + "QUICKPRS_RR_PASSWORD; asked for " + "when omitted)") + p_auto.add_argument("--apikey", default=None, + help="RadioReference API (app) key " + "(or QUICKPRS_RR_APIKEY)") p_auto.add_argument("--categories", default=None, help="Comma-separated category IDs to include") p_auto.add_argument("--tags", default=None, @@ -5604,6 +5657,7 @@ def run_cli(args=None): url=parsed.url, username=parsed.username, apikey=parsed.apikey, + password=parsed.password, categories=parsed.categories, tags=parsed.tags, output=parsed.output, @@ -5783,6 +5837,7 @@ def run_cli(args=None): url=parsed.url, username=parsed.username, apikey=parsed.apikey, + password=parsed.password, categories=parsed.categories, tags=parsed.tags, output=parsed.output, diff --git a/quickprs/config_builder.py b/quickprs/config_builder.py index 8084e23..21aa8f7 100644 --- a/quickprs/config_builder.py +++ b/quickprs/config_builder.py @@ -147,8 +147,8 @@ def _parse_freq_lines(cfg, section_name): for key, value in cfg.items(section_name): # The key might be a number or 'freq1', etc. Use the value. # But configparser stores "key = value", so if the user writes - # "851.0125,806.0125" it becomes key="851.0125,806.0125" value="" - # or the user can write "1 = 851.0125,806.0125" + # "806.0125,851.0125" it becomes key="806.0125,851.0125" value="" + # or the user can write "1 = 806.0125,851.0125" line = value if value else key parts = line.split(',') try: diff --git a/quickprs/freq_tools.py b/quickprs/freq_tools.py index 90fe436..2e2fd50 100644 --- a/quickprs/freq_tools.py +++ b/quickprs/freq_tools.py @@ -91,7 +91,9 @@ def calculate_repeater_offset(freq_mhz): Returns (offset_mhz, direction) tuple where direction is '+' or '-'. Standard offsets: - - 2m (144-148 MHz): +/- 0.6 MHz (output below 147 = +, above = -) + - 2m (144-148 MHz): 0.6 MHz; ARRL band plan: outputs 147.00-147.39 + take a + offset, the other repeater outputs (145.1-145.5, + 146.61-146.97, 147.6-148.0) take a - offset - 220 (222-225 MHz): -1.6 MHz - 70cm (420-450 MHz): +/- 5.0 MHz (output below 445 = +, above = -) - 900 (902-928 MHz): -12.0 MHz (input higher than output) @@ -99,7 +101,7 @@ def calculate_repeater_offset(freq_mhz): Returns None if frequency is not in a standard repeater band. """ if 144.0 <= freq_mhz <= 148.0: - direction = "+" if freq_mhz < 147.0 else "-" + direction = "+" if 147.0 <= freq_mhz < 147.4 else "-" return (0.6, direction) elif 222.0 <= freq_mhz <= 225.0: return (1.6, "-") diff --git a/quickprs/validation.py b/quickprs/validation.py index 107bf1c..58cd380 100644 --- a/quickprs/validation.py +++ b/quickprs/validation.py @@ -291,6 +291,21 @@ def validate_trunk_set(trunk_set): f"Remove this frequency or correct it to a valid " f"XG-100P band.")) + # TX and RX the wrong way round: TX on a site downlink frequency and + # RX on that downlink's uplink. The radio would then listen where the + # site never transmits. + from .iden_library import calculate_tx_freq + swapped = [ch for ch in trunk_set.channels + if abs(ch.tx_freq - ch.rx_freq) > 0.001 and + abs(calculate_tx_freq(ch.tx_freq) - ch.rx_freq) < 0.0001] + if swapped: + ch = swapped[0] + issues.append((WARNING, + f"Trunk set '{name}': {len(swapped)} channel(s) have TX and RX " + f"swapped (e.g. TX {ch.tx_freq:.5f} is a site downlink, RX " + f"{ch.rx_freq:.5f} its uplink). TX should be the uplink " + f"{ch.rx_freq:.5f}, RX the downlink {ch.tx_freq:.5f}.")) + return issues diff --git a/tests/test_cli.py b/tests/test_cli.py index 65b520b..486d46b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -934,7 +934,8 @@ def test_freq_tools_offset_2m(self, capsys): assert result == 0 out = capsys.readouterr().out assert "146.9400" in out - assert "+0.6" in out + assert "-0.6" in out + assert "146.3400" in out def test_freq_tools_offset_70cm(self, capsys): """freq-tools offset for 70cm should show 5 MHz offset.""" diff --git a/tests/test_cli_import.py b/tests/test_cli_import.py index 0108a59..28fbe03 100644 --- a/tests/test_cli_import.py +++ b/tests/test_cli_import.py @@ -141,9 +141,13 @@ def test_import_rr_basic(self, mock_api_cls, capsys, tmp_path): prs_file = _create_blank(tmp_path) result = cmd_import_rr( prs_file, sid=8155, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", ) assert result == 0 + # RadioReferenceAPI(username, password, app_key): the account + # password, not the API key a second time + mock_api_cls.assert_called_once_with("testuser", "testpass", + "testkey") out = capsys.readouterr().out assert "Test County Public Safety" in out assert "SID 8155" in out @@ -160,7 +164,7 @@ def test_import_rr_creates_sets(self, mock_api_cls, capsys, tmp_path): prs_file = _create_blank(tmp_path) cmd_import_rr( prs_file, sid=8155, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", ) prs = parse_prs(prs_file) trunk_sets = _count_trunk_sets(prs) @@ -178,7 +182,7 @@ def test_import_rr_validates_clean(self, mock_api_cls, capsys, tmp_path): prs_file = _create_blank(tmp_path) cmd_import_rr( prs_file, sid=8155, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", ) prs = parse_prs(prs_file) issues = validate_prs(prs) @@ -195,7 +199,7 @@ def test_import_rr_roundtrip(self, mock_api_cls, capsys, tmp_path): prs_file = _create_blank(tmp_path) cmd_import_rr( prs_file, sid=8155, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", ) raw1 = Path(prs_file).read_bytes() prs = parse_prs(prs_file) @@ -213,7 +217,7 @@ def test_import_rr_url_flag(self, mock_api_cls, capsys, tmp_path): result = cmd_import_rr( prs_file, url="https://www.radioreference.com/db/sid/8155", - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", ) assert result == 0 mock_api.get_system.assert_called_once_with(8155) @@ -229,7 +233,7 @@ def test_import_rr_output_flag(self, mock_api_cls, capsys, tmp_path): out_file = str(tmp_path / "output.PRS") result = cmd_import_rr( prs_file, sid=8155, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", output=out_file, ) assert result == 0 @@ -245,7 +249,7 @@ def test_import_rr_category_filter(self, mock_api_cls, capsys, tmp_path): prs_file = _create_blank(tmp_path) result = cmd_import_rr( prs_file, sid=8155, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", categories="1", # Law Enforcement only ) assert result == 0 @@ -263,7 +267,7 @@ def test_import_rr_tag_filter(self, mock_api_cls, capsys, tmp_path): prs_file = _create_blank(tmp_path) result = cmd_import_rr( prs_file, sid=8155, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", tags="Law Dispatch,Law Tac", ) assert result == 0 @@ -285,7 +289,7 @@ def test_import_rr_into_paws(self, mock_api_cls, capsys, tmp_path): result = cmd_import_rr( prs_file, sid=8155, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", ) assert result == 0 @@ -307,7 +311,7 @@ def test_import_rr_no_sid_no_url(self, capsys, tmp_path): """Missing both --sid and --url should return 1.""" prs_file = _create_blank(tmp_path) result = cmd_import_rr( - prs_file, username="testuser", apikey="testkey", + prs_file, username="testuser", apikey="testkey", password="testpass", ) assert result == 1 err = capsys.readouterr().err @@ -318,7 +322,7 @@ def test_import_rr_bad_url(self, capsys, tmp_path): prs_file = _create_blank(tmp_path) result = cmd_import_rr( prs_file, url="https://google.com", - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", ) assert result == 1 err = capsys.readouterr().err @@ -330,7 +334,7 @@ def test_import_rr_no_zeep(self, capsys, tmp_path): prs_file = _create_blank(tmp_path) result = cmd_import_rr( prs_file, sid=8155, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", ) assert result == 1 err = capsys.readouterr().err @@ -347,7 +351,7 @@ def test_import_rr_api_connection_error(self, mock_api_cls, capsys, prs_file = _create_blank(tmp_path) result = cmd_import_rr( prs_file, sid=8155, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", ) assert result == 1 err = capsys.readouterr().err @@ -363,7 +367,7 @@ def test_import_rr_empty_system(self, mock_api_cls, capsys, tmp_path): prs_file = _create_blank(tmp_path) result = cmd_import_rr( prs_file, sid=9999, - username="testuser", apikey="testkey", + username="testuser", apikey="testkey", password="testpass", ) assert result == 1 err = capsys.readouterr().err @@ -375,7 +379,7 @@ def test_import_rr_missing_prs(self, capsys, tmp_path): "import-rr", "nonexistent.PRS", "--sid", "8155", "--username", "testuser", - "--apikey", "testkey", + "--apikey", "testkey", "--password", "testpass", ]) assert result == 1 @@ -667,7 +671,7 @@ def test_import_rr_via_cli_sid(self, mock_api_cls, capsys, tmp_path): "import-rr", prs_file, "--sid", "8155", "--username", "testuser", - "--apikey", "testkey", + "--apikey", "testkey", "--password", "testpass", ]) assert result == 0 out = capsys.readouterr().out @@ -685,7 +689,7 @@ def test_import_rr_via_cli_url(self, mock_api_cls, capsys, tmp_path): "import-rr", prs_file, "--url", "https://www.radioreference.com/db/sid/8155", "--username", "testuser", - "--apikey", "testkey", + "--apikey", "testkey", "--password", "testpass", ]) assert result == 0 @@ -703,7 +707,7 @@ def test_import_rr_via_cli_all_flags(self, mock_api_cls, capsys, "import-rr", prs_file, "--sid", "8155", "--username", "testuser", - "--apikey", "testkey", + "--apikey", "testkey", "--password", "testpass", "--categories", "1,2", "--tags", "Law Dispatch", "-o", out_file, diff --git a/tests/test_config_builder.py b/tests/test_config_builder.py index 49177b8..62c4b10 100644 --- a/tests/test_config_builder.py +++ b/tests/test_config_builder.py @@ -123,8 +123,9 @@ def test_patrol_trunk_freq_values(self): tsets = _prs_trunk_sets(prs) psern = [t for t in tsets if t['name'].strip() == 'PSERN'][0] ch0 = psern['channels'][0] - assert abs(ch0['tx_freq'] - 851.0125) < 0.001 - assert abs(ch0['rx_freq'] - 806.0125) < 0.001 + # TX is the radio's transmit (site uplink), RX the site downlink + assert abs(ch0['tx_freq'] - 806.0125) < 0.001 + assert abs(ch0['rx_freq'] - 851.0125) < 0.001 def test_patrol_talkgroups(self): prs = build_from_config(str(PATROL_INI)) @@ -952,8 +953,8 @@ def test_patrol_json_trunk_freqs(self): tsets = d['trunk_sets'] psern = [t for t in tsets if t['name'].strip() == 'PSERN'][0] # Verify first and last freq - assert abs(psern['channels'][0]['tx_freq'] - 851.0125) < 0.001 - assert abs(psern['channels'][4]['tx_freq'] - 851.1125) < 0.001 + assert abs(psern['channels'][0]['tx_freq'] - 806.0125) < 0.001 + assert abs(psern['channels'][4]['tx_freq'] - 806.1125) < 0.001 def test_patrol_json_talkgroup_ids(self): prs = build_from_config(str(PATROL_INI)) diff --git a/tests/test_freq_tools.py b/tests/test_freq_tools.py index 12529b0..83bff5f 100644 --- a/tests/test_freq_tools.py +++ b/tests/test_freq_tools.py @@ -70,28 +70,28 @@ def test_common_dcs_codes_present(self): class TestRepeaterOffset: """Test repeater offset calculations.""" - def test_2m_low_positive(self): - """2m output below 147 MHz has + offset.""" + def test_2m_146_outputs_negative(self): + """ARRL plan: 146.61-146.97 MHz outputs listen 600 kHz below + (146.94 output, 146.34 input).""" result = calculate_repeater_offset(146.940) assert result is not None offset, direction = result assert offset == 0.6 - assert direction == "+" + assert direction == "-" - def test_2m_high_negative(self): - """2m output at/above 147 MHz has - offset.""" + def test_2m_147_low_outputs_positive(self): + """147.00-147.39 MHz outputs listen 600 kHz above.""" result = calculate_repeater_offset(147.060) assert result is not None offset, direction = result assert offset == 0.6 - assert direction == "-" + assert direction == "+" - def test_2m_boundary(self): - """Exactly 147.0 should give - offset.""" - result = calculate_repeater_offset(147.0) - assert result is not None - _, direction = result - assert direction == "-" + def test_2m_boundaries(self): + assert calculate_repeater_offset(147.0)[1] == "+" + assert calculate_repeater_offset(147.39)[1] == "+" + assert calculate_repeater_offset(147.6)[1] == "-" + assert calculate_repeater_offset(145.29)[1] == "-" def test_220_band(self): """220 MHz band always has -1.6 MHz offset.""" @@ -386,7 +386,8 @@ def test_repeater_offset_format(self): lines = format_repeater_offset(146.940) text = "\n".join(lines) assert "146.9400" in text - assert "+0.6" in text + assert "-0.6" in text + assert "146.3400" in text # the input, 600 kHz below assert "2m" in text def test_repeater_offset_out_of_band(self): diff --git a/tests/test_property_based.py b/tests/test_property_based.py index 151ba46..0f651a2 100644 --- a/tests/test_property_based.py +++ b/tests/test_property_based.py @@ -199,8 +199,8 @@ def test_freq_to_channel_unknown(freq): @pytest.mark.parametrize("freq,expected_offset,expected_dir", [ - (146.52, 0.6, "+"), - (147.36, 0.6, "-"), + (146.94, 0.6, "-"), + (147.36, 0.6, "+"), (223.5, 1.6, "-"), (440.0, 5.0, "+"), (449.0, 5.0, "-"), diff --git a/tests/test_validation.py b/tests/test_validation.py index e3f2d40..83d5e27 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -143,13 +143,20 @@ def test_validate_group_set_name_too_long(): def test_validate_trunk_set_clean(): """A valid trunk set produces no issues.""" ts = make_trunk_set("TEST", [ - (851.0125, 806.0125), - (852.0125, 807.0125), + (806.0125, 851.0125), + (807.0125, 852.0125), ]) issues = validate_trunk_set(ts) assert len(issues) == 0 +def test_validate_trunk_set_swapped_tx_rx(): + """TX on the site downlink and RX on its uplink is flagged.""" + ts = make_trunk_set("TEST", [(851.0125, 806.0125)]) + issues = validate_trunk_set(ts) + assert any("swapped" in m for s, m in issues if s == WARNING) + + def test_validate_trunk_set_duplicate_freq(): """Duplicate frequencies produce warnings.""" ts = make_trunk_set("DUP", [ diff --git a/tests/testdata/example_patrol.ini b/tests/testdata/example_patrol.ini index 0a1c44e..27a283b 100644 --- a/tests/testdata/example_patrol.ini +++ b/tests/testdata/example_patrol.ini @@ -15,12 +15,12 @@ iden_base = 851012500 iden_spacing = 12500 [system.PSERN.frequencies] -# tx_freq,rx_freq -1 = 851.0125,806.0125 -2 = 851.0375,806.0375 -3 = 851.0625,806.0625 -4 = 851.0875,806.0875 -5 = 851.1125,806.1125 +# tx_freq (radio TX = site uplink),rx_freq (site downlink) +1 = 806.0125,851.0125 +2 = 806.0375,851.0375 +3 = 806.0625,851.0625 +4 = 806.0875,851.0875 +5 = 806.1125,851.1125 [system.PSERN.talkgroups] # id,short_name,long_name diff --git a/tests/testdata/example_scanner.ini b/tests/testdata/example_scanner.ini index 515add6..86fe331 100644 --- a/tests/testdata/example_scanner.ini +++ b/tests/testdata/example_scanner.ini @@ -14,9 +14,9 @@ iden_base = 851012500 iden_spacing = 12500 [system.KCSO.frequencies] -1 = 851.2125,806.2125 -2 = 851.2375,806.2375 -3 = 851.2625,806.2625 +1 = 806.2125,851.2125 +2 = 806.2375,851.2375 +3 = 806.2625,851.2625 [system.KCSO.talkgroups] 1 = 100,KCSO DP,KCSO Dispatch @@ -32,10 +32,10 @@ iden_base = 851012500 iden_spacing = 12500 [system.SPD.frequencies] -1 = 851.0125,806.0125 -2 = 851.0375,806.0375 -3 = 851.0625,806.0625 -4 = 851.0875,806.0875 +1 = 806.0125,851.0125 +2 = 806.0375,851.0375 +3 = 806.0625,851.0625 +4 = 806.0875,851.0875 [system.SPD.talkgroups] 1 = 1,SPD DSP,SPD Dispatch From eed9a014925d70f39fcb4a02701d861cb63a0f85 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:24:20 -0700 Subject: [PATCH 06/14] Generate 800 MHz IDEN tables that reach every channel The 800 MHz tables used base 851.00625 MHz with 12.5 kHz steps, which lands on 851.01875, 851.03125 ... and never on an 800 MHz channel centre (851.0125 is half a step away), so channel numbers mapped to the wrong frequencies and ECC channel references rounded to the wrong channel. Phase II tables used 6.25 kHz spacing and bandwidth, unlike every TDMA entry in the RPM-saved test personality. - 800 MHz tables (FDMA and TDMA) start at 851.0125 MHz with 12500 in both the spacing and bandwidth fields: the entries RPM-saved files hold, and whole steps to every channel whichever field is the spacing. A frequency list on a 6.25 kHz offset still gets 6.25 kHz steps from 851.00625. - TDMA templates use 12.5 kHz like the real TDMA entries; the Mixed template no longer claims to copy a table it did not match. --- quickprs/iden_library.py | 52 ++++++++++++++++--------- quickprs/injector.py | 12 +++++- tests/test_auto_iden_freq_validation.py | 2 +- tests/test_iden_library.py | 38 ++++++++++++------ tests/test_radioreference.py | 10 ++--- 5 files changed, 77 insertions(+), 37 deletions(-) diff --git a/quickprs/iden_library.py b/quickprs/iden_library.py index 7c4ba3d..12d69d8 100644 --- a/quickprs/iden_library.py +++ b/quickprs/iden_library.py @@ -64,9 +64,12 @@ def build_standard_iden_entries(frequencies, system_type=""): if not frequencies: return [] + # Phase II carriers are 12.5 kHz wide like Phase I (two TDMA slots + # each); every TDMA IDEN entry in RPM-saved personalities uses 12.5 kHz + # spacing and bandwidth. is_tdma = "Phase II" in system_type - spacing = 6250 if is_tdma else 12500 - bw = 6250 if is_tdma else 12500 + spacing = 12500 + bw = 12500 iden_type = 1 if is_tdma else 0 # Find the band from the first frequency @@ -81,7 +84,9 @@ def build_standard_iden_entries(frequencies, system_type=""): tx_offset_mhz = tx_offset if band_name == '800': - return _standard_800_iden(spacing, bw, tx_offset_mhz, iden_type) + return _standard_800_iden(spacing, bw, tx_offset_mhz, iden_type, + base_hz=_TDMA_800_BASE_HZ if is_tdma + else _FDMA_800_BASE_HZ) elif band_name in ('700', '700_upper'): return _standard_700_iden(spacing, bw, tx_offset_mhz, iden_type) elif band_name == '900': @@ -91,16 +96,25 @@ def build_standard_iden_entries(frequencies, system_type=""): frequencies, spacing, bw, tx_offset_mhz, iden_type) -def _standard_800_iden(spacing, bw, tx_offset_mhz, iden_type): +# 851.0125 MHz with 12.5 kHz steps lands on every 800 MHz channel centre +# whichever of the element's two 12500 fields is the spacing, and is the +# FDMA and TDMA entry RPM-saved personalities hold (e.g. IDEN set 92738). +# The old 851.00625 base needs 6.25 kHz steps to reach 851.0125. +_FDMA_800_BASE_HZ = 851012500 +_TDMA_800_BASE_HZ = 851012500 + + +def _standard_800_iden(spacing, bw, tx_offset_mhz, iden_type, + base_hz=_FDMA_800_BASE_HZ): """Standard 800 MHz rebanded IDEN table (16 entries). - Covers 851.00625 - 867.88125 MHz in 1.125 MHz blocks. - This is the standard table used by PSERN, BEE00, and all - standard 800 MHz rebanded P25 systems. + Covers the 851-869 MHz downlink in 1.125 MHz blocks starting at + ``base_hz``. Systems publish their own IDEN tables; check them + against what the system broadcasts. """ return [ { - 'base_freq_hz': 851006250 + i * 1125000, + 'base_freq_hz': base_hz + i * 1125000, 'chan_spacing_hz': spacing, 'bandwidth_hz': bw, 'tx_offset_mhz': tx_offset_mhz, @@ -224,16 +238,18 @@ def _build_templates(): key="800-TDMA", label="800 MHz TDMA (Phase II)", band="800", mode="TDMA", - description="Standard 800 MHz rebanded, 6.25 kHz TDMA. " - "16 entries covering 851-868 MHz.", - entries=_standard_800_iden(6250, 6250, -45.0, 1), + description="Standard 800 MHz rebanded, 12.5 kHz TDMA carriers " + "(two slots each). 16 entries covering 851-868 MHz.", + entries=_standard_800_iden(12500, 12500, -45.0, 1, + base_hz=_TDMA_800_BASE_HZ), ) templates[t.key] = t - # 800 MHz Mixed (FDMA slots 0-1 + TDMA slots 2-15) - # Like BEE00 in PAWSOVERMAWS — systems with both Phase I and Phase II + # 800 MHz Mixed (FDMA slots 0-1 + TDMA slots 2-15), for systems + # carrying both Phase I and Phase II traffic fdma_entries = _standard_800_iden(12500, 12500, -45.0, 0) - tdma_entries = _standard_800_iden(6250, 6250, -45.0, 1) + tdma_entries = _standard_800_iden(12500, 12500, -45.0, 1, + base_hz=_TDMA_800_BASE_HZ) mixed_entries = fdma_entries[:2] + tdma_entries[2:] t = IdenTemplate( key="800-Mixed", @@ -261,9 +277,9 @@ def _build_templates(): key="700-TDMA", label="700 MHz TDMA (Phase II)", band="700", mode="TDMA", - description="Standard 700 MHz, 6.25 kHz TDMA. " + description="Standard 700 MHz, 12.5 kHz TDMA carriers. " "16 entries covering 764-776 MHz, TX +30 MHz.", - entries=_standard_700_iden(6250, 6250, 30.0, 1), + entries=_standard_700_iden(12500, 12500, 30.0, 1), ) templates[t.key] = t @@ -283,9 +299,9 @@ def _build_templates(): key="900-TDMA", label="900 MHz TDMA (Phase II)", band="900", mode="TDMA", - description="Standard 900 MHz, 6.25 kHz TDMA. " + description="Standard 900 MHz, 12.5 kHz TDMA carriers. " "8 active entries (935-939 MHz), TX -39 MHz.", - entries=_standard_900_iden(6250, 6250, -39.0, 1), + entries=_standard_900_iden(12500, 12500, -39.0, 1), ) templates[t.key] = t diff --git a/quickprs/injector.py b/quickprs/injector.py index 5cd1cfd..d1d6382 100644 --- a/quickprs/injector.py +++ b/quickprs/injector.py @@ -1953,13 +1953,23 @@ def _has_tdma_spacing(freqs): is_tdma = _has_tdma_spacing(freqs) spacing = 6250 if is_tdma else 12500 bw = 6250 if is_tdma else 12500 + base_kw = {} + if band_name == '800': + # The table must reach every listed frequency in whole steps: + # 12.5 kHz from 851.0125 covers the 800 MHz channel centres, + # anything on a 6.25 kHz offset needs 6.25 kHz from 851.00625. + if is_tdma: + spacing = bw = 6250 + base_kw = {'base_hz': 851006250} + else: + spacing = bw = 12500 iden_type = 1 if is_tdma else 0 mode_str = "TDMA" if is_tdma else "FDMA" gen_fn, tx_offset, max_entries = band_config[band_name] if gen_fn is not None: - entries = gen_fn(spacing, bw, tx_offset, iden_type) + entries = gen_fn(spacing, bw, tx_offset, iden_type, **base_kw) else: # VHF/UHF — derive from actual frequencies entries = _derive_iden_from_freqs( diff --git a/tests/test_auto_iden_freq_validation.py b/tests/test_auto_iden_freq_validation.py index 0afb93f..cafdbff 100644 --- a/tests/test_auto_iden_freq_validation.py +++ b/tests/test_auto_iden_freq_validation.py @@ -71,7 +71,7 @@ def test_auto_iden_800_only(): active = [e for e in iden_set.elements if e.base_freq_hz > 0] assert len(active) == 16 # Standard 800 MHz table - assert active[0].base_freq_hz == 851006250 + assert active[0].base_freq_hz == 851012500 def test_auto_iden_800_fdma(): diff --git a/tests/test_iden_library.py b/tests/test_iden_library.py index 36720b7..5fcbee9 100644 --- a/tests/test_iden_library.py +++ b/tests/test_iden_library.py @@ -107,7 +107,7 @@ def test_800_fdma_template(): assert len(t.entries) == 16 for i, e in enumerate(t.entries): - assert e['base_freq_hz'] == 851006250 + i * 1125000 + assert e['base_freq_hz'] == 851012500 + i * 1125000 assert e['chan_spacing_hz'] == 12500 assert e['bandwidth_hz'] == 12500 assert e['tx_offset_mhz'] == -45.0 @@ -126,14 +126,28 @@ def test_800_tdma_template(): t = get_template("800-TDMA") assert len(t.entries) == 16 - for e in t.entries: - assert e['chan_spacing_hz'] == 6250 - assert e['bandwidth_hz'] == 6250 + # The TDMA entries RPM-saved personalities hold (BEE00 and 92738 + # slot 2): base 851.0125 MHz, 12500 / 12500 + for i, e in enumerate(t.entries): + assert e['base_freq_hz'] == 851012500 + i * 1125000 + assert e['chan_spacing_hz'] == 12500 + assert e['bandwidth_hz'] == 12500 assert e['iden_type'] == 1 # TDMA assert e['tx_offset_mhz'] == -45.0 print(" PASS: 800 MHz TDMA template") +def test_800_templates_reach_every_channel(): + """Every 800 MHz channel centre (851.0125 MHz + n x 12.5 kHz) is a + whole number of steps from the first entry's base.""" + for key in ("800-FDMA", "800-TDMA", "800-Mixed"): + e = get_template(key).entries[0] + for n in range(0, 80): + f_hz = 851012500 + n * 12500 + steps = (f_hz - e['base_freq_hz']) / e['chan_spacing_hz'] + assert steps == int(steps), (key, f_hz) + + def test_800_mixed_template(): """800 MHz Mixed template: slots 0-1 FDMA, slots 2-15 TDMA.""" t = get_template("800-Mixed") @@ -150,13 +164,13 @@ def test_800_mixed_template(): # Slots 2-15: TDMA for i in range(2, 16): e = t.entries[i] - assert e['chan_spacing_hz'] == 6250, f"Slot {i} spacing wrong" - assert e['bandwidth_hz'] == 6250, f"Slot {i} BW wrong" + assert e['chan_spacing_hz'] == 12500, f"Slot {i} spacing wrong" + assert e['bandwidth_hz'] == 12500, f"Slot {i} BW wrong" assert e['iden_type'] == 1, f"Slot {i} should be TDMA" # All entries have same base freq pattern and TX offset for i, e in enumerate(t.entries): - assert e['base_freq_hz'] == 851006250 + i * 1125000 + assert e['base_freq_hz'] == 851012500 + i * 1125000 assert e['tx_offset_mhz'] == -45.0 print(" PASS: 800 MHz Mixed template") @@ -182,7 +196,7 @@ def test_700_tdma_template(): assert len(t.entries) == 16 for e in t.entries: - assert e['chan_spacing_hz'] == 6250 + assert e['chan_spacing_hz'] == 12500 assert e['iden_type'] == 1 assert e['tx_offset_mhz'] == 30.0 print(" PASS: 700 MHz TDMA template") @@ -214,7 +228,7 @@ def test_900_tdma_template(): assert len(active) == 8 for e in active: - assert e['chan_spacing_hz'] == 6250 + assert e['chan_spacing_hz'] == 12500 assert e['iden_type'] == 1 assert e['tx_offset_mhz'] == -39.0 print(" PASS: 900 MHz TDMA template") @@ -312,8 +326,8 @@ def test_build_entries_800_phase2(): entries = build_standard_iden_entries( [851.0125, 851.2625], "Project 25 Phase II") assert len(entries) == 16 - assert entries[0]['base_freq_hz'] == 851006250 - assert entries[0]['chan_spacing_hz'] == 6250 + assert entries[0]['base_freq_hz'] == 851012500 + assert entries[0]['chan_spacing_hz'] == 12500 assert entries[0]['iden_type'] == 1 print(" PASS: build_entries 800 Phase II") @@ -392,7 +406,7 @@ def test_cli_iden_templates_detail(): rc = cmd_iden_templates(detail=True) assert rc == 0 output = buf.getvalue() - assert "851.00625" in output # 800 MHz first entry + assert "851.01250" in output # 800 MHz first entry assert "TDMA" in output assert "FDMA" in output print(" PASS: CLI iden-templates detail") diff --git a/tests/test_radioreference.py b/tests/test_radioreference.py index 18079b2..4743a38 100644 --- a/tests/test_radioreference.py +++ b/tests/test_radioreference.py @@ -163,17 +163,17 @@ def test_iden_table_800mhz(): assert len(entries) == 16 # First entry should be standard 800 MHz base - assert entries[0]['base_freq_hz'] == 851006250 - assert entries[0]['chan_spacing_hz'] == 6250 # TDMA - assert entries[0]['bandwidth_hz'] == 6250 + assert entries[0]['base_freq_hz'] == 851012500 + assert entries[0]['chan_spacing_hz'] == 12500 # as RPM files hold + assert entries[0]['bandwidth_hz'] == 12500 assert entries[0]['tx_offset_mhz'] == -45.0 # -45 MHz assert entries[0]['iden_type'] == 1 # TDMA # Second entry should be 1.125 MHz higher - assert entries[1]['base_freq_hz'] == 852131250 + assert entries[1]['base_freq_hz'] == 852137500 # Last entry - assert entries[15]['base_freq_hz'] == 851006250 + 15 * 1125000 + assert entries[15]['base_freq_hz'] == 851012500 + 15 * 1125000 print(" PASS: 800 MHz IDEN table") From 8838bba0fe5fce58ff638a366b7938aacde5677b Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:37:24 -0700 Subject: [PATCH 07/14] Add `quickprs radio`; flag unverified system IDs quickprs radio (new): - The XG-100P's Bluetooth is Bluetooth Classic, and RPM's own help ("Setting Up A Bluetooth Connection") documents programming it over the serial port profile, i.e. the Bluetooth COM port. The protocol is not published, so these commands help learn it from RPM without sending anything of their own to the radio: - radio scan: paired Bluetooth serial ports with the device names (outgoing vs incoming port), optional BLE scan. - radio probe: connect and listen, never transmit; hex dump, guess at what arrives (NMEA, PPP, AT, text), optional capture file. - radio relay: sit between RPM (on a virtual null-modem pair) and the radio, forward both ways, log every byte and modem-line change. - radio analyze: per-direction statistics, chunk openers, text, and any .PRS archive in the radio's replies (--extract writes it). - Capture files are JSON Lines, written line by line so a crash keeps what was read. System database: - The built-in list's System IDs and WACNs were never verified (the header claimed the FCC publishes them; it does not), and several are wrong. PSERN is corrected to 939 from an RPM-saved personality and marked verified; every other entry is marked unverified and the CLI and GUI warn before one is added to a personality. --- quickprs/cli.py | 87 ++++++++++++++- quickprs/gui/import_wizard.py | 9 +- quickprs/gui/system_wizard.py | 7 ++ quickprs/radio/__init__.py | 21 ++++ quickprs/radio/analyze.py | 137 +++++++++++++++++++++++ quickprs/radio/bluetooth.py | 138 +++++++++++++++++++++++ quickprs/radio/capture.py | 127 +++++++++++++++++++++ quickprs/radio/commands.py | 166 +++++++++++++++++++++++++++ quickprs/radio/link.py | 40 +++++++ quickprs/radio/probe.py | 50 +++++++++ quickprs/radio/relay.py | 81 ++++++++++++++ quickprs/system_database.py | 34 ++++-- tests/test_import_wizard.py | 2 +- tests/test_radio.py | 204 ++++++++++++++++++++++++++++++++++ tests/test_system_database.py | 22 +++- 15 files changed, 1105 insertions(+), 20 deletions(-) create mode 100644 quickprs/radio/__init__.py create mode 100644 quickprs/radio/analyze.py create mode 100644 quickprs/radio/bluetooth.py create mode 100644 quickprs/radio/capture.py create mode 100644 quickprs/radio/commands.py create mode 100644 quickprs/radio/link.py create mode 100644 quickprs/radio/probe.py create mode 100644 quickprs/radio/relay.py create mode 100644 tests/test_radio.py diff --git a/quickprs/cli.py b/quickprs/cli.py index fc4bcfc..7c0b317 100644 --- a/quickprs/cli.py +++ b/quickprs/cli.py @@ -3592,7 +3592,7 @@ def cmd_systems(subcmd, query=None, filepath=None, system_name=None, """ from .system_database import ( list_all_systems, search_systems, get_system_by_name, - get_iden_template_key, get_default_iden_name, + get_iden_template_key, get_default_iden_name, unverified_warning, ) if subcmd == "list": @@ -3605,8 +3605,10 @@ def cmd_systems(subcmd, query=None, filepath=None, system_name=None, print("-" * 75) for s in systems: print(f"{s.name:<10} {s.location:<25} {s.band:<10} " - f"{s.system_type:<10} {s.system_id:>6} {s.wacn:>8}") - print(f"\n{len(systems)} systems in database") + f"{s.system_type:<10} {s.system_id:>6} {s.wacn:>8}" + f"{'' if s.verified else ' (unverified)'}") + print(f"\n{len(systems)} systems in database. IDs marked " + f"unverified are examples: confirm them on RadioReference.") return 0 elif subcmd == "search": @@ -3652,6 +3654,8 @@ def cmd_systems(subcmd, query=None, filepath=None, system_name=None, print(f"State: {sys_obj.state}") print(f"System ID: {sys_obj.system_id}") print(f"WACN: {sys_obj.wacn}") + if not sys_obj.verified: + print(f"Warning: {unverified_warning(sys_obj)}") print(f"Band: {sys_obj.band}") print(f"Type: {sys_obj.system_type}") print(f"IDEN Key: {iden_key}") @@ -3689,6 +3693,10 @@ def cmd_systems(subcmd, query=None, filepath=None, system_name=None, from .record_types import P25TrkSystemConfig from .iden_library import get_template + warning = unverified_warning(sys_obj) + if warning: + print(f"Warning: {warning}", file=sys.stderr) + prs = parse_prs(filepath) name = sys_obj.name[:8] @@ -4163,6 +4171,9 @@ def run_cli(args=None): " fleet-check Compare fleet for consistency\n" " snapshot Save/compare configuration snapshots\n" "\n" + "Radio link (Bluetooth / serial):\n" + " radio scan, probe, relay (log RPM), analyze\n" + "\n" "Modify:\n" " inject Add systems/channels/talkgroups\n" " remove Remove systems or sets\n" @@ -4352,6 +4363,58 @@ def run_cli(args=None): help="Output file (default: overwrite input)") # export-csv + # 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", + 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" + "Examples:\n" + " quickprs radio scan\n" + " quickprs radio probe --port COM6 --seconds 15 " + "--log first.jsonl\n" + " quickprs radio relay --pc-port COM21 --radio-port COM6 " + "--log read.jsonl\n" + " quickprs radio analyze read.jsonl --extract radio.PRS") + radio_sub = p_radio.add_subparsers(dest="radio_cmd") + p_rscan = radio_sub.add_parser( + "scan", help="List paired Bluetooth serial ports (radios)") + p_rscan.add_argument("--ble", action="store_true", + help="Also list advertising BLE devices") + p_rscan.add_argument("--ble-seconds", type=float, default=5.0) + p_rprobe = radio_sub.add_parser( + "probe", help="Connect and listen without sending anything") + p_rprobe.add_argument("--port", default=None, + help="COM port (default: the one paired radio)") + p_rprobe.add_argument("--seconds", type=float, default=10.0) + p_rprobe.add_argument("--log", default=None, + help="Save the received bytes to a capture file") + p_rprobe.add_argument("--dtr", action="store_true", + help="Assert DTR when connecting") + p_rprobe.add_argument("--quiet", action="store_true", + help="Do not hex-dump as data arrives") + p_rrelay = radio_sub.add_parser( + "relay", help="Pass bytes between RPM and the radio, logging both") + p_rrelay.add_argument("--pc-port", required=True, + help="Your end of a virtual null-modem pair " + "(RPM opens the other end)") + p_rrelay.add_argument("--radio-port", default=None, + help="The radio's port (default: the one paired " + "radio)") + p_rrelay.add_argument("--log", default="session.jsonl") + p_rrelay.add_argument("--note", default="", + help="What this session is, e.g. 'RPM extract'") + 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("--extract", default=None, + help="Write a personality archive found in the " + "radio's replies to this .PRS path") + p_icsv = sub.add_parser( "import-csv", help="Import CSV files (talkgroups, trunk, conv, P25 conv)", @@ -5589,6 +5652,24 @@ def run_cli(args=None): list_opts=parsed.list_opts, output=parsed.output, ) + elif parsed.command == "radio": + from .radio import commands as radio_commands + if parsed.radio_cmd == "scan": + return radio_commands.cmd_radio_scan( + ble=parsed.ble, ble_seconds=parsed.ble_seconds) + if parsed.radio_cmd == "probe": + return radio_commands.cmd_radio_probe( + port=parsed.port, seconds=parsed.seconds, + log=parsed.log, dtr=parsed.dtr, quiet=parsed.quiet) + if parsed.radio_cmd == "relay": + return radio_commands.cmd_radio_relay( + parsed.pc_port, radio_port=parsed.radio_port, + log=parsed.log, note=parsed.note) + if parsed.radio_cmd == "analyze": + return radio_commands.cmd_radio_analyze( + parsed.capture, extract=parsed.extract) + p_radio.print_help() + return 1 elif parsed.command == "import-csv": return cmd_import_csv(parsed.file, parsed.csv_files, output=parsed.output) diff --git a/quickprs/gui/import_wizard.py b/quickprs/gui/import_wizard.py index 29bfe5b..60207a0 100644 --- a/quickprs/gui/import_wizard.py +++ b/quickprs/gui/import_wizard.py @@ -599,10 +599,17 @@ def _import_from_database(self): return name = selection[0] - from ..system_database import get_system_by_name, get_iden_template_key + from ..system_database import ( + get_system_by_name, get_iden_template_key, unverified_warning, + ) sys = get_system_by_name(name) if not sys: return + warning = unverified_warning(sys) + if warning and not messagebox.askyesno( + "Unverified IDs", warning + "\n\nAdd it anyway?", + icon=messagebox.WARNING, parent=self): + return self.app.save_undo_snapshot(f"Add system {sys.name}") diff --git a/quickprs/gui/system_wizard.py b/quickprs/gui/system_wizard.py index 35ce33a..11d743c 100644 --- a/quickprs/gui/system_wizard.py +++ b/quickprs/gui/system_wizard.py @@ -842,6 +842,13 @@ def _add_system(self): parent=self): return + from ..system_database import unverified_warning + warning = unverified_warning(sys) + if warning and not messagebox.askyesno( + "Unverified IDs", warning + "\n\nAdd it anyway?", + icon=messagebox.WARNING, parent=self): + return + self.app.save_undo_snapshot("Add System from Database") try: diff --git a/quickprs/radio/__init__.py b/quickprs/radio/__init__.py new file mode 100644 index 0000000..f009b29 --- /dev/null +++ b/quickprs/radio/__init__.py @@ -0,0 +1,21 @@ +"""Talking to the radio itself (as opposed to editing .PRS files). + +The XG-100P's Bluetooth is Bluetooth Classic (2.x pairing, not BLE). A +paired radio offers a Serial Port Profile service, which Windows exposes as +a COM port, and RPM's help ("Setting Up A Bluetooth Connection") says RPM +programs the radio over that link just as it does over the USB cable: the +Unity Product Management window extracts (reads), writes, activates and +removes mission plans. + +The programming protocol is not published, so this package does what is +needed to learn it from RPM, without guessing at commands: + +* ``bluetooth`` find paired radios and their SPP COM ports (and scan BLE) +* ``link`` serial links (a Bluetooth COM port or a USB serial port) +* ``capture`` a timestamped, direction-tagged log of every byte +* ``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 + +Nothing here sends a byte of its own to the radio. +""" diff --git a/quickprs/radio/analyze.py b/quickprs/radio/analyze.py new file mode 100644 index 0000000..f547513 --- /dev/null +++ b/quickprs/radio/analyze.py @@ -0,0 +1,137 @@ +"""Summarise a capture and look for personality data inside it. + +Without the protocol, the useful questions about a capture of RPM reading +a radio are: how much went each way, how the bytes are chunked, which +byte patterns open messages, what text is in it, and whether the +personality crosses the link in the same MFC archive form a .PRS file +uses (class headers ``FF FF`` + schema + name, see archive.py). If it +does, the archive can be cut out and saved as a .PRS file. +""" + +from collections import Counter +from dataclasses import dataclass, field +import re +import struct + +from .capture import DIRECTIONS + +_CLASS_NAME = re.compile(rb"C[A-Za-z0-9_]{2,47}") + + +@dataclass +class ClassHeader: + offset: int + schema: int + name: str + + +@dataclass +class DirectionSummary: + direction: str + total_bytes: int = 0 + chunks: int = 0 + chunk_sizes: Counter = field(default_factory=Counter) + first_bytes: Counter = field(default_factory=Counter) # chunk openers + strings: list = field(default_factory=list) + class_headers: list = field(default_factory=list) + + +def find_class_headers(data): + """Every MFC new-class header in ``data``: FF FF, schema, name length, + and a class name that looks like RPM's (C + letters/digits).""" + hits = [] + pos = data.find(b"\xff\xff") + while pos >= 0: + if pos + 6 <= len(data): + schema, n = struct.unpack_from(" 0 else "")) + else: + lines.append(" no PRS archive class headers (the data is in " + "another form, or compressed/encrypted)") + if s.strings: + shown = "; ".join(f"0x{o:x} {t!r}" for o, t in s.strings[:top]) + lines.append(f" text: {shown}") + return lines diff --git a/quickprs/radio/bluetooth.py b/quickprs/radio/bluetooth.py new file mode 100644 index 0000000..31cd359 --- /dev/null +++ b/quickprs/radio/bluetooth.py @@ -0,0 +1,138 @@ +"""Find paired radios and the COM ports their Bluetooth serial service uses. + +Windows gives every Bluetooth Serial Port Profile (SPP) service of a paired +device a "Standard Serial over Bluetooth link" COM port. Its hardware ID +holds the service UUID and the device address, e.g.:: + + BTHENUM\\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0002\\ + 7&1A2B3C4D&0&000268123456_C00000000 + +An address of all zeros marks the *incoming* port (for devices that connect +to the PC); the outgoing port carries the device's address and is the one +to open. Device names come from the Bluetooth stack's registry entries. +""" + +from dataclasses import dataclass +import re +import sys + +SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB" + +_BTHENUM = re.compile( + r"BTHENUM\\\{(?P[0-9A-F-]{36})\}[^\\]*\\[^&\\]*&[^&\\]*&[^&\\]*&" + r"(?P[0-9A-F]{12})_", re.IGNORECASE) + + +@dataclass +class BluetoothPort: + """A COM port backed by a Bluetooth Classic serial service.""" + port: str # e.g. "COM6" + address: str # "00:02:68:12:34:56", or "" for an incoming port + service_uuid: str + name: str = "" # paired device name, e.g. "MY RADIO" + description: str = "" + + @property + def outgoing(self): + """True for the port that connects out to the device.""" + return bool(self.address) + + +def format_address(raw12): + """'000268123456' -> '00:02:68:12:34:56' ('' for all zeros).""" + raw12 = raw12.upper() + if set(raw12) == {"0"}: + return "" + return ":".join(raw12[i:i + 2] for i in range(0, 12, 2)) + + +def parse_hwid(hwid): + """(service UUID, address) from a BTHENUM hardware ID, or None.""" + m = _BTHENUM.search(hwid or "") + if not m: + return None + return m.group("uuid").upper(), format_address(m.group("addr")) + + +def paired_device_names(): + """{address: name} for paired Bluetooth devices (Windows only).""" + if sys.platform != "win32": + return {} + import winreg + names = {} + key_path = r"SYSTEM\CurrentControlSet\Services\BTHPORT\Parameters\Devices" + try: + root = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, key_path) + except OSError: + return names + i = 0 + while True: + try: + sub = winreg.EnumKey(root, i) + except OSError: + break + i += 1 + try: + raw, _ = winreg.QueryValueEx(winreg.OpenKey(root, sub), "Name") + except OSError: + continue + name = bytes(raw).split(b"\x00")[0].decode("utf-8", "replace") + names[format_address(sub)] = name + return names + + +def bluetooth_serial_ports(comports=None, names=None): + """Every COM port backed by a Bluetooth serial service. + + ``comports`` and ``names`` default to the live system (pyserial's port + list and the paired-device registry); tests pass their own. + """ + if comports is None: + from serial.tools import list_ports + comports = list_ports.comports() + if names is None: + names = paired_device_names() + found = [] + for p in comports: + parsed = parse_hwid(getattr(p, "hwid", "")) + if not parsed: + continue + uuid, address = parsed + found.append(BluetoothPort( + port=p.device, address=address, service_uuid=uuid, + name=names.get(address, ""), + description=getattr(p, "description", "") or "")) + return found + + +def radio_ports(ports=None): + """Outgoing SPP ports: the ones a paired radio can be reached on.""" + if ports is None: + ports = bluetooth_serial_ports() + return [p for p in ports if p.outgoing and p.service_uuid == SPP_UUID] + + +def scan_ble(seconds=5.0): + """Advertising BLE devices as (address, name, rssi), strongest first. + + Needs the optional ``bleak`` package. An XG-100P does not show up + here: its Bluetooth is Classic, which BLE scanning does not see. + """ + import asyncio + try: + from bleak import BleakScanner + except ImportError as e: + raise RuntimeError( + "BLE scanning needs the 'bleak' package " + "(pip install quickprs[radio])") from e + + async def _scan(): + found = await BleakScanner.discover(timeout=seconds, + return_adv=True) + rows = [] + for device, adv in found.values(): + rows.append((device.address, device.name or adv.local_name or "", + adv.rssi)) + return sorted(rows, key=lambda r: -r[2]) + + return asyncio.run(_scan()) diff --git a/quickprs/radio/capture.py b/quickprs/radio/capture.py new file mode 100644 index 0000000..7a5d810 --- /dev/null +++ b/quickprs/radio/capture.py @@ -0,0 +1,127 @@ +"""Session capture: every byte that crossed a link, in order. + +A capture is a JSON Lines file. The first line describes the session; each +later line is one chunk as it was read, or an event such as a modem-line +change:: + + {"capture": "quickprs", "version": 1, "started": "...", "note": "..."} + {"t": 0.0123, "dir": "pc>radio", "hex": "a5 01 ..."} + {"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 +radio's side of the conversation: ``pc>radio`` is what RPM (or the PC) +sent, ``radio>pc`` what the radio answered. +""" + +from dataclasses import dataclass, field +from datetime import datetime, timezone +import json +import threading +import time + +PC_TO_RADIO = "pc>radio" +RADIO_TO_PC = "radio>pc" +DIRECTIONS = (PC_TO_RADIO, RADIO_TO_PC) + + +@dataclass +class Chunk: + t: float + direction: str + data: bytes + + +@dataclass +class Capture: + chunks: list = field(default_factory=list) + events: list = field(default_factory=list) # (t, text) + header: dict = field(default_factory=dict) + + def stream(self, direction): + """All bytes sent one way, joined.""" + return b"".join(c.data for c in self.chunks + if c.direction == direction) + + def total(self, direction=None): + return sum(len(c.data) for c in self.chunks + if direction is None or c.direction == direction) + + +class CaptureWriter: + """Append chunks to a 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 + directions of a relay) write at the same time. + """ + + def __init__(self, path, note=""): + self._f = open(path, "w", encoding="utf-8", newline="\n") + self._t0 = time.monotonic() + self._lock = threading.Lock() + header = {"capture": "quickprs", "version": 1, + "started": datetime.now(timezone.utc).isoformat( + timespec="seconds")} + if note: + header["note"] = note + self._write(header) + + def _write(self, obj): + with self._lock: + self._f.write(json.dumps(obj) + "\n") + self._f.flush() + + def _now(self): + return round(time.monotonic() - self._t0, 6) + + def add(self, direction, data): + if direction not in DIRECTIONS: + raise ValueError(f"unknown direction {direction!r}") + if data: + self._write({"t": self._now(), "dir": direction, + "hex": data.hex(" ")}) + + def event(self, text): + self._write({"t": self._now(), "event": str(text)}) + + def close(self): + self._f.close() + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.close() + + +def read_capture(path): + """Load a capture file written by :class:`CaptureWriter`.""" + cap = Capture() + with open(path, encoding="utf-8") as f: + for n, line in enumerate(f, 1): + line = line.strip() + if not line: + continue + obj = json.loads(line) + if "capture" in obj: + cap.header = obj + elif "event" in obj: + cap.events.append((float(obj.get("t", 0)), obj["event"])) + elif obj.get("dir") in DIRECTIONS: + cap.chunks.append(Chunk(float(obj["t"]), obj["dir"], + bytes.fromhex(obj["hex"]))) + else: + raise ValueError(f"{path}:{n}: not a capture line") + return cap + + +def hexdump(data, width=16, offset=0): + """Classic offset / hex / ASCII lines.""" + lines = [] + for i in range(0, len(data), width): + row = data[i:i + width] + hexpart = " ".join(f"{b:02x}" for b in row) + text = "".join(chr(b) if 32 <= b < 127 else "." for b in row) + lines.append(f"{offset + i:08x} {hexpart:<{width * 3}} {text}") + return lines diff --git a/quickprs/radio/commands.py b/quickprs/radio/commands.py new file mode 100644 index 0000000..fac9eee --- /dev/null +++ b/quickprs/radio/commands.py @@ -0,0 +1,166 @@ +"""`quickprs radio ...` commands (see quickprs.radio for the background).""" + +import sys +from pathlib import Path + +from .analyze import extract_personality, report +from .bluetooth import ( + SPP_UUID, bluetooth_serial_ports, radio_ports, scan_ble, +) +from .capture import CaptureWriter, RADIO_TO_PC, hexdump, read_capture +from .link import LinkError, open_serial +from .probe import classify, listen + +PAIRING_HELP = ( + "Pair the radio first. On the radio: SETTINGS > BLUETOOTH, set " + "ENABLED to YES, then PAIRING MGNT > ADD NEW and pick this PC; accept " + "the pass key on both. (Bluetooth must be enabled in the radio's " + "personality: Options > Bluetooth Settings.)") + + +def _pick_port(port): + if port: + return port + radios = radio_ports() + if len(radios) == 1: + return radios[0].port + if not radios: + print("Error: no paired Bluetooth serial device found. " + + PAIRING_HELP, file=sys.stderr) + else: + listed = ", ".join(f"{r.port} ({r.name or r.address})" + for r in radios) + print(f"Error: several Bluetooth serial ports ({listed}); " + f"choose one with --port", file=sys.stderr) + return None + + +def cmd_radio_scan(ble=False, ble_seconds=5.0): + ports = bluetooth_serial_ports() + if ports: + print("Bluetooth serial ports:") + for p in ports: + kind = "SPP" if p.service_uuid == SPP_UUID else p.service_uuid + who = p.name or "(unnamed)" + addr = p.address or "incoming (for devices that call the PC)" + print(f" {p.port:7s} {who:20s} {addr:20s} {kind}") + radios = radio_ports(ports) + if radios: + print() + for r in radios: + print(f"Use --port {r.port} for {r.name or r.address}.") + else: + print("No outgoing Bluetooth serial port. " + PAIRING_HELP) + + if ble: + print() + print(f"BLE devices advertising nearby ({ble_seconds:g} s scan):") + try: + rows = scan_ble(ble_seconds) + except RuntimeError as e: + print(f" {e}", file=sys.stderr) + return 1 + for address, name, rssi in rows: + print(f" {address:20s} {rssi:4d} dBm {name}") + if not rows: + print(" none") + print(" (An XG-100P is Bluetooth Classic and does not appear in a " + "BLE scan.)") + return 0 + + +def cmd_radio_probe(port=None, seconds=10.0, log=None, dtr=False, + quiet=False): + port = _pick_port(port) + if port is None: + return 1 + print(f"Opening {port}. For a Bluetooth port this connects to the radio " + f"and can take several seconds...") + try: + link = open_serial(port, dtr=dtr) + except LinkError as e: + print(f"Error: {e}", file=sys.stderr) + return 1 + print(f"Connected. Listening for {seconds:g} s; nothing is sent.") + writer = CaptureWriter(log, note=f"probe {port}") if log else None + offset = [0] + + def show(data): + if not quiet: + for line in hexdump(data, offset=offset[0]): + print(line) + offset[0] += len(data) + + try: + data = listen(link, seconds, writer=writer, on_chunk=show) + except KeyboardInterrupt: + data = b"" + finally: + link.close() + if writer is not None: + writer.close() + print(f"Received {offset[0]} bytes: {classify(data)}.") + if log: + print(f"Capture saved to {log}") + return 0 + + +def cmd_radio_relay(pc_port, radio_port=None, log="session.jsonl", + note=""): + from .relay import run_relay + radio_port = _pick_port(radio_port) + if radio_port is None: + return 1 + try: + radio = open_serial(radio_port) + except LinkError as e: + print(f"Error: {e}", file=sys.stderr) + return 1 + try: + pc = open_serial(pc_port) + except LinkError as e: + radio.close() + print(f"Error: {e}", file=sys.stderr) + return 1 + + counts = {"pc>radio": 0, "radio>pc": 0} + + 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: + try: + errors = run_relay(pc, radio, writer=writer, on_chunk=tally) + finally: + pc.close() + radio.close() + print(f"Stopped. RPM to radio: {counts['pc>radio']:,} bytes; radio to " + 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}") + return 0 + + +def cmd_radio_analyze(capture_path, extract=None): + try: + cap = read_capture(capture_path) + except (OSError, ValueError) as e: + print(f"Error: {e}", file=sys.stderr) + return 1 + for line in report(cap): + print(line) + if extract: + data = extract_personality(cap.stream(RADIO_TO_PC)) + if data is None: + print("\nNo .PRS archive the walker could follow in the radio's " + "replies.", file=sys.stderr) + return 1 + Path(extract).write_bytes(data) + print(f"\nWrote {len(data):,} bytes of archive to {extract} " + f"(compare with a .PRS RPM saved before trusting it).") + return 0 diff --git a/quickprs/radio/link.py b/quickprs/radio/link.py new file mode 100644 index 0000000..8c49eb6 --- /dev/null +++ b/quickprs/radio/link.py @@ -0,0 +1,40 @@ +"""Serial links: a paired radio's Bluetooth COM port, or a USB serial port. + +Opening a Bluetooth SPP COM port is what makes Windows connect to the +radio, so ``open_serial`` can take several seconds and fails when the radio +is off, out of range or has Bluetooth disabled. +""" + + +class LinkError(RuntimeError): + """The port could not be opened or used.""" + + +def open_serial(port, baudrate=115200, timeout=0.2, dtr=False, rts=False): + """Open ``port`` with the modem lines set before the port opens. + + For a Bluetooth SPP port the baud rate means nothing (RFCOMM carries + bytes, not a line rate); it matters only for a real serial cable. + DTR and RTS default to off, the quietest way to connect: over + Bluetooth they travel to the radio as RFCOMM modem status. + """ + try: + import serial + except ImportError as e: + raise LinkError("serial ports need the 'pyserial' package " + "(pip install quickprs[radio])") from e + ser = serial.Serial() + ser.port = port + ser.baudrate = baudrate + ser.timeout = timeout + ser.write_timeout = 5 + ser.dtr = dtr + ser.rts = rts + try: + ser.open() + except (serial.SerialException, OSError) as e: + raise LinkError( + f"could not open {port}: {e}. For a Bluetooth port, check the " + f"radio is on, in range and has Bluetooth enabled " + f"(SETTINGS > BLUETOOTH > ENABLED).") from e + return ser diff --git a/quickprs/radio/probe.py b/quickprs/radio/probe.py new file mode 100644 index 0000000..06cdeae --- /dev/null +++ b/quickprs/radio/probe.py @@ -0,0 +1,50 @@ +"""Listen on a radio's port without sending anything. + +Useful first contact: it shows whether the radio's Bluetooth serial service +connects at all and whether the radio says anything unprompted (NMEA from +GPS, PPP frames for data, a text banner ...). It never writes a byte. +""" + +import re +import time + +from .capture import RADIO_TO_PC + +_NMEA = re.compile(rb"\$(G[PNLA]|P[A-Z]{3})[A-Z]{3},[^\r\n*]*\*[0-9A-F]{2}") + + +def classify(data): + """Best guess at what a received byte stream is, as a short phrase.""" + if not data: + return "nothing received" + if _NMEA.search(data): + return "NMEA sentences (GPS position output)" + if data.count(b"\x7e") >= 2 and (b"\xff\x03" in data or + b"\xff\x7d\x23" in data): + return "PPP frames (HDLC framing, 0x7E flags)" + text = data.strip(b"\r\n\x00") + if re.search(rb"(^|\r|\n)(OK|ERROR|CONNECT|RING|AT[A-Z])", data): + return "AT/modem text" + printable = sum(32 <= b < 127 or b in (9, 10, 13) for b in text) + if text and printable / len(text) > 0.9: + return "plain text" + return "binary" + + +def listen(link, seconds, writer=None, on_chunk=None, clock=time.monotonic): + """Read from ``link`` for ``seconds``; return everything received. + + ``link`` needs ``read(n)`` and ``in_waiting``; nothing is written to + it. Each chunk goes to ``writer`` (a CaptureWriter) and ``on_chunk``. + """ + received = bytearray() + end = clock() + seconds + while clock() < end: + data = link.read(max(1, getattr(link, "in_waiting", 0) or 1)) + if data: + received += data + if writer is not None: + writer.add(RADIO_TO_PC, data) + if on_chunk is not None: + on_chunk(data) + return bytes(received) diff --git a/quickprs/radio/relay.py b/quickprs/radio/relay.py new file mode 100644 index 0000000..05c7d94 --- /dev/null +++ b/quickprs/radio/relay.py @@ -0,0 +1,81 @@ +"""Relay between RPM and the radio, logging both directions. + +RPM talks to the radio through a COM port. Give it a virtual one instead: +with a null-modem pair (for example com0com's COM20 <-> COM21), RPM opens +COM20, this relay opens COM21 and the radio's real port (the Bluetooth SPP +port, or the radio's serial port), and passes every byte across while +writing it to a capture file. RPM stays in charge of the conversation; the +relay only forwards what each side sends. + +com0com maps each side's DTR/RTS to the other side's DSR/CTS, so the relay +also copies RPM's modem lines to the radio's port. +""" + +import threading +import time + +from .capture import PC_TO_RADIO, RADIO_TO_PC + + +def _pump(src, dst, direction, writer, stop, on_chunk, errors): + try: + while not stop.is_set(): + data = src.read(max(1, getattr(src, "in_waiting", 0) or 1)) + if not data: + continue + dst.write(data) + if writer is not None: + writer.add(direction, data) + if on_chunk is not None: + on_chunk(direction, data) + except Exception as e: # a closed port ends the session + errors.append((direction, e)) + stop.set() + + +def _mirror_lines(pc, radio, writer, stop, poll): + """Copy RPM's DTR/RTS (seen as DSR/CTS on the virtual pair) across.""" + last = None + while not stop.is_set(): + try: + state = (bool(pc.dsr), bool(pc.cts)) + if state != last: + radio.dtr, radio.rts = state + if writer is not None: + writer.event(f"pc dtr={int(state[0])} rts={int(state[1])}") + last = state + except Exception: + return + time.sleep(poll) + + +def run_relay(pc_link, radio_link, writer=None, stop=None, on_chunk=None, + mirror_lines=True, poll=0.05): + """Forward bytes both ways until ``stop`` is set or a port closes. + + Returns the list of (direction, exception) that ended it, if any. + """ + stop = stop or threading.Event() + errors = [] + threads = [ + threading.Thread(target=_pump, daemon=True, args=( + pc_link, radio_link, PC_TO_RADIO, writer, stop, on_chunk, + errors)), + threading.Thread(target=_pump, daemon=True, args=( + radio_link, pc_link, RADIO_TO_PC, writer, stop, on_chunk, + errors)), + ] + if mirror_lines: + threads.append(threading.Thread( + target=_mirror_lines, daemon=True, + args=(pc_link, radio_link, writer, stop, poll))) + for t in threads: + t.start() + try: + while not stop.is_set(): + time.sleep(poll) + except KeyboardInterrupt: + stop.set() + for t in threads: + t.join(timeout=2) + return errors diff --git a/quickprs/system_database.py b/quickprs/system_database.py index 41ef237..9a4cf15 100644 --- a/quickprs/system_database.py +++ b/quickprs/system_database.py @@ -1,12 +1,14 @@ -"""Built-in database of common US P25 trunked radio systems. - -Provides a searchable catalog of well-known P25 systems with their -basic parameters (System ID, WACN, band, type). Users can select -from the database instead of looking up info on RadioReference. - -Data sourced from public FCC/NTIA records and RadioReference wiki. -System IDs and WACNs are public information published by the FCC -Universal Licensing System and NTIA spectrum management databases. +"""Built-in list of common US P25 trunked radio systems. + +A searchable starting point (name, area, band, phase) for setting up a +system. The System IDs and WACNs here are NOT verified: they do not come +from any authoritative source (the FCC's licensing database does not +publish P25 System IDs or WACNs) and several are known to be wrong. +Only entries marked ``verified`` were checked, against a personality +saved by RPM for a radio on that system. Confirm every ID on +RadioReference (or with the system's administrator) before a radio is +programmed with it: a wrong System ID or WACN keeps the radio off the +system. """ from dataclasses import dataclass @@ -25,6 +27,16 @@ class P25System: band: str # frequency band ("700", "800", "700/800", "900") system_type: str # "Phase I" or "Phase II" description: str = "" # brief description of coverage/purpose + verified: bool = False # IDs checked against an RPM-saved personality + + +def unverified_warning(system): + """Warning text for an entry whose IDs nobody checked, else ''.""" + if system.verified: + return "" + return (f"System ID {system.system_id} and WACN {system.wacn:#x} for " + f"{system.name} are unverified; confirm both on RadioReference " + f"before programming a radio.") # ─── System Database ───────────────────────────────────────────────── @@ -38,8 +50,10 @@ class P25System: long_name="Puget Sound Emergency Radio Network", location="Seattle Metro, WA", state="WA", - system_id=892, + # 939 (0x3AB) / WACN BEE00 as RPM saved them for a radio on PSERN + system_id=939, wacn=781824, + verified=True, band="800", system_type="Phase II", description="King County regional public safety, replaces KCERS", diff --git a/tests/test_import_wizard.py b/tests/test_import_wizard.py index f237b5b..eea36d9 100644 --- a/tests/test_import_wizard.py +++ b/tests/test_import_wizard.py @@ -192,7 +192,7 @@ def test_search_by_state(self): assert len(wa_systems) >= 1 def test_search_by_id(self): - results = search_systems("892") + results = search_systems("939") # PSERN assert len(results) >= 1 def test_search_empty_returns_all(self): diff --git a/tests/test_radio.py b/tests/test_radio.py new file mode 100644 index 0000000..5f86033 --- /dev/null +++ b/tests/test_radio.py @@ -0,0 +1,204 @@ +"""quickprs.radio: Bluetooth port discovery, capture files, the listen-only +probe, the RPM relay and capture analysis. No radio or Bluetooth adapter +is needed: ports and links are stand-ins.""" + +import threading +import time +from types import SimpleNamespace + +import pytest + +from quickprs.radio import analyze, bluetooth, capture, probe, relay +from quickprs.radio.capture import PC_TO_RADIO, RADIO_TO_PC + +# Hardware IDs in the form Windows reports for a paired XG-100P +# (example address) +OUT_HWID = (r"BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0002" + r"\7&1A2B3C4D&0&000268123456_C00000000") +IN_HWID = (r"BTHENUM\{00001101-0000-1000-8000-00805F9B34FB}_LOCALMFG&0000" + r"\7&1A2B3C4D&0&000000000000_00000025") + + +def _port(device, hwid, description=""): + return SimpleNamespace(device=device, hwid=hwid, description=description) + + +# ─── discovery ─────────────────────────────────────────────────────── + +def test_parse_hwid(): + assert bluetooth.parse_hwid(OUT_HWID) == (bluetooth.SPP_UUID, + "00:02:68:12:34:56") + assert bluetooth.parse_hwid(IN_HWID) == (bluetooth.SPP_UUID, "") + assert bluetooth.parse_hwid(r"USB\VID_303A&PID_1001&MI_00\6&1") is None + + +def test_radio_ports_pick_the_outgoing_spp_port(): + ports = bluetooth.bluetooth_serial_ports( + comports=[_port("COM3", IN_HWID), _port("COM6", OUT_HWID), + _port("COM8", r"USB\VID_303A&PID_1001")], + names={"00:02:68:12:34:56": "MY RADIO"}) + assert [(p.port, p.name, p.outgoing) for p in ports] == [ + ("COM3", "", False), ("COM6", "MY RADIO", True)] + assert [p.port for p in bluetooth.radio_ports(ports)] == ["COM6"] + + +# ─── capture files ─────────────────────────────────────────────────── + +def test_capture_round_trip(tmp_path): + path = tmp_path / "s.jsonl" + with capture.CaptureWriter(path, note="unit test") as w: + w.add(PC_TO_RADIO, b"\x01\x02") + w.event("pc dtr=1 rts=0") + w.add(RADIO_TO_PC, b"\xa5\x5a\x00") + w.add(RADIO_TO_PC, b"") # empty reads are not logged + cap = capture.read_capture(path) + assert cap.header["note"] == "unit test" + assert [(c.direction, c.data) for c in cap.chunks] == [ + (PC_TO_RADIO, b"\x01\x02"), (RADIO_TO_PC, b"\xa5\x5a\x00")] + assert cap.events[0][1] == "pc dtr=1 rts=0" + assert cap.stream(RADIO_TO_PC) == b"\xa5\x5a\x00" + + +def test_capture_lines_stay_whole_across_threads(tmp_path): + path = tmp_path / "t.jsonl" + w = capture.CaptureWriter(path) + + def spam(direction): + for i in range(300): + w.add(direction, bytes([i % 256]) * 40) + + threads = [threading.Thread(target=spam, args=(d,)) + for d in (PC_TO_RADIO, RADIO_TO_PC)] + for t in threads: + t.start() + for t in threads: + t.join() + w.close() + cap = capture.read_capture(path) + assert len(cap.chunks) == 600 + assert all(len(c.data) == 40 for c in cap.chunks) + + +def test_hexdump(): + assert capture.hexdump(b"AB\x00", offset=16) == [ + "00000010 41 42 00" + " " * 40 + " AB."] # hex column is 48 wide + + +# ─── probe ─────────────────────────────────────────────────────────── + +class FakeLink: + """read() hands out queued chunks; write() must never be called by + the probe.""" + + def __init__(self, chunks=()): + self.chunks = list(chunks) + self.written = bytearray() + self.lock = threading.Lock() + self.dsr = self.cts = False + self.dtr = self.rts = False + + @property + def in_waiting(self): + return len(self.chunks[0]) if self.chunks else 0 + + def read(self, n): + with self.lock: + if self.chunks: + return self.chunks.pop(0) + time.sleep(0.001) + return b"" + + def write(self, data): + with self.lock: + self.written += data + + +@pytest.mark.parametrize("data,kind", [ + (b"$GPGGA,123519,4807.038,N,01131.000,E,1,08,0.9,545.4,M,46.9,M,,*47" + b"\r\n", "NMEA"), + (b"\x7e\xff\x03\xc0\x21\x01\x01\x00\x0e\x7e", "PPP"), + (b"\r\nOK\r\n", "AT/modem"), + (b"XG-100P READY\r\n", "plain text"), + (b"\xa5\x01\x9c\x00\x13", "binary"), + (b"", "nothing"), +]) +def test_classify(data, kind): + assert probe.classify(data).startswith(kind) + + +def test_listen_never_writes(tmp_path): + link = FakeLink([b"\x01\x02", b"\x03"]) + ticks = iter(i * 0.1 for i in range(1000)) + with capture.CaptureWriter(tmp_path / "p.jsonl") as w: + got = probe.listen(link, 0.5, writer=w, clock=lambda: next(ticks)) + assert got == b"\x01\x02\x03" + assert link.written == b"" + cap = capture.read_capture(tmp_path / "p.jsonl") + assert cap.stream(RADIO_TO_PC) == b"\x01\x02\x03" + + +# ─── relay ─────────────────────────────────────────────────────────── + +def test_relay_forwards_and_logs_both_ways(tmp_path): + pc = FakeLink([b"\x10\x11", b"\x12"]) # what RPM sends + radio = FakeLink([b"\x20", b"\x21\x22\x23"]) # what the radio answers + pc.dsr = True # RPM raised DTR + stop = threading.Event() + threading.Timer(0.3, stop.set).start() + with capture.CaptureWriter(tmp_path / "r.jsonl") as w: + errors = relay.run_relay(pc, radio, writer=w, stop=stop, poll=0.01) + assert errors == [] + assert bytes(radio.written) == b"\x10\x11\x12" + assert bytes(pc.written) == b"\x20\x21\x22\x23" + assert radio.dtr is True and radio.rts is False + cap = capture.read_capture(tmp_path / "r.jsonl") + assert cap.stream(PC_TO_RADIO) == b"\x10\x11\x12" + assert cap.stream(RADIO_TO_PC) == b"\x20\x21\x22\x23" + assert any("dtr=1" in text for _, text in cap.events) + + +# ─── analysis ──────────────────────────────────────────────────────── + +def _blank_bytes(): + from quickprs.builder import create_blank_prs + return create_blank_prs("RADIO.PRS").to_bytes() + + +def test_find_class_headers_in_a_stream(): + prs = _blank_bytes() + stream = b"\xa5\x5a\x00\x10junk" + prs + names = [h.name for h in analyze.find_class_headers(stream)] + assert names[0] == "CPersonality" + assert "CConvSystem" in names and "CConvChannel" in names + + +def test_extract_personality_from_framed_replies(): + prs = _blank_bytes() + stream = b"\x02\x00\x41HEADER" + prs + assert analyze.extract_personality(stream) == prs + assert analyze.extract_personality(b"\x00" * 64) is None + + +def test_report_mentions_archive_and_text(tmp_path): + prs = _blank_bytes() + path = tmp_path / "a.jsonl" + with capture.CaptureWriter(path, note="RPM extract") as w: + w.add(PC_TO_RADIO, b"\x01READ PERSONALITY") + for i in range(0, len(prs), 64): + w.add(RADIO_TO_PC, prs[i:i + 64]) + text = "\n".join(analyze.report(capture.read_capture(path))) + assert "RPM extract" in text + assert "CPersonality@0x0" in text + assert "'READ PERSONALITY'" in text + + +def test_cli_analyze_extracts(tmp_path, capsys): + from quickprs.cli import run_cli + prs = _blank_bytes() + path = tmp_path / "a.jsonl" + with capture.CaptureWriter(path) as w: + w.add(RADIO_TO_PC, b"\xff\x00" + prs) + out_prs = tmp_path / "radio.PRS" + assert run_cli(["radio", "analyze", str(path), "--extract", + str(out_prs)]) == 0 + assert out_prs.read_bytes() == prs diff --git a/tests/test_system_database.py b/tests/test_system_database.py index 96cfdee..96a46da 100644 --- a/tests/test_system_database.py +++ b/tests/test_system_database.py @@ -92,7 +92,7 @@ def test_search_by_state(self): assert len(results) >= 2 # PSERN, KCERS, WSP def test_search_by_system_id(self): - results = search_systems("892") + results = search_systems("939") assert any(s.name == "PSERN" for s in results) def test_search_by_description(self): @@ -118,7 +118,9 @@ class TestGetSystemByName: def test_exact_name(self): s = get_system_by_name("PSERN") assert s is not None - assert s.system_id == 892 + # 939 as RPM saved it for a radio on PSERN (the old 892 was wrong) + assert s.system_id == 939 + assert s.verified is True def test_case_insensitive(self): s = get_system_by_name("psern") @@ -138,7 +140,7 @@ class TestGetSystemById: """Test get_system_by_id lookup.""" def test_existing_id(self): - results = get_system_by_id(892) + results = get_system_by_id(939) assert len(results) >= 1 assert results[0].name == "PSERN" @@ -246,8 +248,18 @@ def test_systems_info(self, capsys): result = run_cli(["systems", "info", "PSERN"]) assert result == 0 out = capsys.readouterr().out - assert "892" in out + assert "939" in out assert "Puget Sound" in out + assert "unverified" not in out + + def test_systems_info_warns_unverified(self, capsys): + assert run_cli(["systems", "info", "NYPD"]) == 0 + assert "unverified" in capsys.readouterr().out + + def test_only_checked_entries_are_verified(self): + from quickprs.system_database import SYSTEMS, unverified_warning + assert [s.name for s in SYSTEMS if s.verified] == ["PSERN"] + assert all(unverified_warning(s) for s in SYSTEMS if not s.verified) def test_systems_info_not_found(self, capsys): result = run_cli(["systems", "info", "NONEXISTENT"]) @@ -267,7 +279,7 @@ def test_systems_add_to_prs(self, capsys): out = capsys.readouterr().out assert "Added P25 system" in out assert "PSERN" in out - assert "892" in out + assert "939" in out @pytest.mark.skipif(not PAWS.exists(), reason="Test PRS data not available") def test_systems_add_to_prs_output_flag(self, capsys): From 11286e59d2122c7c326c6f3377a5710970f4998e Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:47:23 -0700 Subject: [PATCH 08/14] Correct the national interoperability channels The interop template had VTAC11-14 at 155.7675-156.0375 MHz (they are 151.1375, 154.4525, 158.7375 and 159.4725), a UTAC44 that does not exist, the 800 MHz channels at their pre-rebanding 866-868 MHz, the UHF and 800 MHz channels as simplex on the output only, and the P25 700 MHz channels as analog FM. Values now follow the NIFOG as RadioReference's National Interoperability page lists it: VCALL10/VTAC11-14 simplex; UCALL40 and UTAC41-43 as repeater pairs (+5 MHz) plus direct channels; 8CALL90 and 8TAC91-94 at 851.0125-853.0125 MHz as repeater pairs (-45 MHz) plus direct channels; narrowband where the plan says FMN. The 700 MHz channels are left to a P25 conventional set. The health check's interop list uses the same frequencies, and make_conv_channel / make_conv_set accept a narrowband flag. --- quickprs/health_check.py | 13 +++-- quickprs/injector.py | 6 +- quickprs/templates.py | 121 +++++++++++++++------------------------ tests/test_templates.py | 62 +++++++++++--------- 4 files changed, 93 insertions(+), 109 deletions(-) diff --git a/quickprs/health_check.py b/quickprs/health_check.py index 1422179..4f28d21 100644 --- a/quickprs/health_check.py +++ b/quickprs/health_check.py @@ -32,16 +32,17 @@ # NOAA Weather Radio frequencies (MHz) _NOAA_FREQS = {162.400, 162.425, 162.450, 162.475, 162.500, 162.525, 162.550} -# National interop frequencies (NPSPAC, MHz) +# National interop frequencies (MHz, as the NIFOG lists them; outputs) _INTEROP_FREQS = { # VHF - 155.7525, 156.7625, 158.7375, 159.4725, + 155.7525, 151.1375, 154.4525, 158.7375, 159.4725, # UHF 453.2125, 453.4625, 453.7125, 453.8625, - # 800 MHz - 866.0125, 866.5125, 867.0125, 867.5125, - # 700 MHz - 769.24375, 769.74375, 770.24375, 770.74375, + # 800 MHz (rebanded) + 851.0125, 851.5125, 852.0125, 852.5125, 853.0125, + # 700 MHz (P25) + 769.24375, 769.14375, 769.64375, 770.14375, 770.64375, 769.74375, + 770.24375, } # Emergency talkgroup IDs (common P25 emergency TG ranges) diff --git a/quickprs/injector.py b/quickprs/injector.py index d1d6382..13aab11 100644 --- a/quickprs/injector.py +++ b/quickprs/injector.py @@ -1741,7 +1741,7 @@ def make_group_set(name, talkgroups, tx_default=False, scan_default=True): def make_conv_channel(short_name, tx_freq, rx_freq=None, tx_tone="", rx_tone="", long_name="", - tx=True, scan=True): + tx=True, scan=True, narrowband=False): """Create a ConvChannel with default flags. Args: @@ -1753,6 +1753,7 @@ def make_conv_channel(short_name, tx_freq, rx_freq=None, long_name: 16-char max long name (defaults to short_name) tx: transmit enable (False for receive-only channels like NOAA) scan: scan enable + narrowband: 12.5 kHz channel (False = 25 kHz wideband) """ if rx_freq is None: rx_freq = tx_freq @@ -1766,7 +1767,7 @@ def make_conv_channel(short_name, tx_freq, rx_freq=None, return ConvChannel( short_name=short_name, tx_freq=tx_freq, rx_freq=rx_freq, tx_tone=tx_tone, rx_tone=rx_tone, long_name=long_name, - tx=tx, scan=scan, + tx=tx, scan=scan, narrowband=narrowband, ) @@ -1839,6 +1840,7 @@ def make_conv_set(name, channels_data): long_name=ch.get('long_name', ''), tx=ch.get('tx', True), scan=ch.get('scan', True), + narrowband=ch.get('narrowband', False), )) return ConvSet(name=name[:8], channels=channels) diff --git a/quickprs/templates.py b/quickprs/templates.py index 8f5cb8d..8eab137 100644 --- a/quickprs/templates.py +++ b/quickprs/templates.py @@ -241,82 +241,55 @@ def get_noaa_channels(): @_register('interop') def get_interop_channels(): - """Return National Public Safety Interoperability channels. - - Standard NPSPAC/interop channels used across all US agencies: - - VCALL10 (155.7525 MHz, VHF calling channel) - - VTAC11-14 (155.7675-156.0375 MHz, VHF tactical) - - UCALL40 (453.2125 MHz, UHF calling) - - UTAC41-44 (453.4625-453.8875 MHz, UHF tactical) - - 8CALL90 (866.0125 MHz, 800 MHz calling) - - 8TAC91-94 (866.5125-868.0125 MHz, 800 MHz tactical) - - 7CALL50 (769.24375 MHz, 700 MHz calling) - - 7TAC51-54 (769.74375-771.24375 MHz, 700 MHz tactical) - - VHF/UHF/800 channels use 156.7 Hz PL tone (NPSPAC standard). - 700 MHz channels are P25 digital (no PL tone). + """Return the national public safety interoperability channels. + + Values as the NIFOG publishes them (checked against RadioReference's + National Interoperability page; the current NIFOG from CISA wins any + disagreement). All use 156.7 Hz CTCSS and narrowband FM unless noted: + + - VHF, simplex: VCALL10 155.7525, VTAC11 151.1375, VTAC12 154.4525, + VTAC13 158.7375, VTAC14 159.4725 MHz + - UHF repeater pairs (radio transmits 5 MHz up) and their direct + ("D") simplex channels: UCALL40 453.2125, UTAC41 453.4625, + UTAC42 453.7125, UTAC43 453.8625 MHz + - 800 MHz repeater pairs (radio transmits 45 MHz down; wide FM) and + direct channels: 8CALL90 851.0125, 8TAC91-94 851.5125-853.0125 MHz + (the rebanded frequencies; 866-868 MHz is the pre-rebanding plan) + + The 700 MHz channels (7CALL50, 7TAC51-56) are P25 digital (NAC 293), + which an analog conventional set cannot carry; add them as a P25 + conventional set (P25_CONV_SET.csv import) instead. """ - return [ - # VHF Interop (NPSPAC) - {'short_name': 'VCALL10', 'tx_freq': 155.7525, - 'long_name': 'VHF Call', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': 'VTAC11', 'tx_freq': 155.7675, - 'long_name': 'VHF Tactical 1', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': 'VTAC12', 'tx_freq': 155.7825, - 'long_name': 'VHF Tactical 2', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': 'VTAC13', 'tx_freq': 155.7975, - 'long_name': 'VHF Tactical 3', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': 'VTAC14', 'tx_freq': 156.0375, - 'long_name': 'VHF Tactical 4', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - # UHF Interop - {'short_name': 'UCALL40', 'tx_freq': 453.2125, - 'long_name': 'UHF Call', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': 'UTAC41', 'tx_freq': 453.4625, - 'long_name': 'UHF Tactical 1', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': 'UTAC42', 'tx_freq': 453.7125, - 'long_name': 'UHF Tactical 2', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': 'UTAC43', 'tx_freq': 453.8625, - 'long_name': 'UHF Tactical 3', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': 'UTAC44', 'tx_freq': 453.8875, - 'long_name': 'UHF Tactical 4', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - # 800 MHz Interop - {'short_name': '8CALL90', 'tx_freq': 866.0125, - 'long_name': '800 Call', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': '8TAC91', 'tx_freq': 866.5125, - 'long_name': '800 Tactical 1', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': '8TAC92', 'tx_freq': 867.0125, - 'long_name': '800 Tactical 2', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': '8TAC93', 'tx_freq': 867.5125, - 'long_name': '800 Tactical 3', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - {'short_name': '8TAC94', 'tx_freq': 868.0125, - 'long_name': '800 Tactical 4', - 'tx_tone': '156.7', 'rx_tone': '156.7'}, - # 700 MHz Interop - {'short_name': '7CALL50', 'tx_freq': 769.24375, - 'long_name': '700 Call'}, - {'short_name': '7TAC51', 'tx_freq': 769.74375, - 'long_name': '700 Tactical 1'}, - {'short_name': '7TAC52', 'tx_freq': 770.24375, - 'long_name': '700 Tactical 2'}, - {'short_name': '7TAC53', 'tx_freq': 770.74375, - 'long_name': '700 Tactical 3'}, - {'short_name': '7TAC54', 'tx_freq': 771.24375, - 'long_name': '700 Tactical 4'}, + def ch(name, rx, tx=None, long_name="", narrowband=True): + return {'short_name': name, 'tx_freq': tx if tx else rx, + 'rx_freq': rx, 'long_name': long_name, + 'tx_tone': '156.7', 'rx_tone': '156.7', + 'narrowband': narrowband} + + channels = [ + ch('VCALL10', 155.7525, long_name='VHF Call'), + ch('VTAC11', 151.1375, long_name='VHF Tactical 11'), + ch('VTAC12', 154.4525, long_name='VHF Tactical 12'), + ch('VTAC13', 158.7375, long_name='VHF Tactical 13'), + ch('VTAC14', 159.4725, long_name='VHF Tactical 14'), ] + for name, out, label in (('UCALL40', 453.2125, 'UHF Call'), + ('UTAC41', 453.4625, 'UHF Tactical 41'), + ('UTAC42', 453.7125, 'UHF Tactical 42'), + ('UTAC43', 453.8625, 'UHF Tactical 43')): + channels.append(ch(name, out, tx=round(out + 5.0, 4), + long_name=f'{name} Repeater')) + channels.append(ch(name + 'D', out, long_name=f'{name} Direct')) + for name, out, label in (('8CALL90', 851.0125, '800 Call'), + ('8TAC91', 851.5125, '800 Tactical 91'), + ('8TAC92', 852.0125, '800 Tactical 92'), + ('8TAC93', 852.5125, '800 Tactical 93'), + ('8TAC94', 853.0125, '800 Tactical 94')): + channels.append(ch(name, out, tx=round(out - 45.0, 4), + long_name=f'{name} Repeater', + narrowband=False)) + channels.append(ch(name + 'D', out, long_name=f'{name} Direct')) + return channels @_register('public_safety') diff --git a/tests/test_templates.py b/tests/test_templates.py index 6973a71..13bea76 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -302,9 +302,10 @@ class TestInteropTemplate: """Test National Interoperability channel data.""" def test_interop_count(self): - """Interop has exactly 20 channels (5 VHF + 5 UHF + 5 800 + 5 700).""" + """5 VHF simplex + 4 UHF and 5 800 MHz channels, each as a + repeater pair and a direct channel (700 MHz is P25, not here).""" channels = get_interop_channels() - assert len(channels) == 20 + assert len(channels) == 5 + 4 * 2 + 5 * 2 def test_interop_short_names_length(self): """All interop short names are 8 chars or less.""" @@ -330,21 +331,35 @@ def test_interop_ucall40_present(self): channels = get_interop_channels() ucall = [ch for ch in channels if ch['short_name'] == 'UCALL40'] assert len(ucall) == 1 - assert ucall[0]['tx_freq'] == 453.2125 + # repeater: the radio listens on 453.2125 and transmits 5 MHz up + assert ucall[0]['rx_freq'] == 453.2125 + assert ucall[0]['tx_freq'] == 458.2125 + direct = [ch for ch in channels if ch['short_name'] == 'UCALL40D'] + assert direct[0]['tx_freq'] == direct[0]['rx_freq'] == 453.2125 def test_interop_8call90_present(self): - """8CALL90 (800 MHz calling) must be present at 866.0125 MHz.""" + """8CALL90 is 851.0125 MHz since 800 MHz rebanding (input + 806.0125); 866.0125 was the old plan.""" channels = get_interop_channels() call800 = [ch for ch in channels if ch['short_name'] == '8CALL90'] assert len(call800) == 1 - assert call800[0]['tx_freq'] == 866.0125 - - def test_interop_7call50_present(self): - """7CALL50 (700 MHz calling) must be present at 769.24375 MHz.""" - channels = get_interop_channels() - call700 = [ch for ch in channels if ch['short_name'] == '7CALL50'] - assert len(call700) == 1 - assert call700[0]['tx_freq'] == 769.24375 + assert call800[0]['rx_freq'] == 851.0125 + assert call800[0]['tx_freq'] == 806.0125 + + def test_interop_vtac_frequencies(self): + """VTAC11-14 as the NIFOG lists them.""" + got = {ch['short_name']: ch['tx_freq'] + for ch in get_interop_channels() + if ch['short_name'].startswith('VTAC')} + assert got == {'VTAC11': 151.1375, 'VTAC12': 154.4525, + 'VTAC13': 158.7375, 'VTAC14': 159.4725} + + def test_interop_no_700_or_utac44(self): + """700 MHz interop is P25 (not an analog channel) and there is no + UTAC44.""" + names = {ch['short_name'] for ch in get_interop_channels()} + assert not any(n.startswith('7') for n in names) + assert 'UTAC44' not in names def test_interop_vhf_channels(self): """Interop has 5 VHF channels (VCALL10 + VTAC11-14).""" @@ -358,21 +373,14 @@ def test_interop_uhf_channels(self): channels = get_interop_channels() uhf = [ch for ch in channels if ch['short_name'].startswith('U')] - assert len(uhf) == 5 + assert len(uhf) == 8 def test_interop_800_channels(self): - """Interop has 5 800 MHz channels (8CALL90 + 8TAC91-94).""" + """8CALL90 + 8TAC91-94, repeater and direct.""" channels = get_interop_channels() ch800 = [ch for ch in channels if ch['short_name'].startswith('8')] - assert len(ch800) == 5 - - def test_interop_700_channels(self): - """Interop has 5 700 MHz channels (7CALL50 + 7TAC51-54).""" - channels = get_interop_channels() - ch700 = [ch for ch in channels - if ch['short_name'].startswith('7')] - assert len(ch700) == 5 + assert len(ch800) == 10 def test_interop_vhf_tones(self): """VHF interop channels use 156.7 Hz CTCSS tone.""" @@ -390,11 +398,11 @@ def test_interop_uhf_tones(self): assert ch.get('tx_tone') == '156.7' assert ch.get('rx_tone') == '156.7' - def test_interop_no_duplicate_freqs(self): - """No duplicate frequencies in interop template.""" + def test_interop_no_duplicate_channels(self): + """No two channels share both frequencies.""" channels = get_interop_channels() - freqs = [ch['tx_freq'] for ch in channels] - assert len(freqs) == len(set(freqs)) + pairs = [(ch['tx_freq'], ch['rx_freq']) for ch in channels] + assert len(pairs) == len(set(pairs)) def test_interop_has_required_keys(self): """Each interop channel has required keys.""" @@ -406,7 +414,7 @@ def test_interop_has_required_keys(self): def test_interop_lookup_by_name(self): """get_template_channels('interop') returns data.""" channels = get_template_channels('interop') - assert len(channels) == 20 + assert len(channels) == len(get_interop_channels()) # ─── Public Safety template ────────────────────────────────────────── From 3c1b0794039441a6be929b7027b6a64b3e023780 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:56:41 -0700 Subject: [PATCH 09/14] Stop silent overwrites; fix cleanup, backups, fleet names, search - create refused nothing: `quickprs create radio.PRS` on an existing personality wiped it. It now stops unless --force (which keeps a .bak). import-json's default output is the .PRS the JSON was exported from, so it now stops instead of overwriting it. Both write through write_prs. - cleanup reported every trunk and talkgroup set as unused because it never read the set names systems refer to; it now uses them (13 sets wrongly reported on the PAWSOVERMAWS sample, 1 truly unused now). - Backups of "radio_v2.PRS" were listed, restored and pruned as backups of "radio.PRS", and ordering by file time put a restored copy last; backups are now matched by exact name and ordered by their timestamp. - fleet: unit names cannot place output files outside the output folder, duplicate names are reported instead of overwriting, short CSV rows no longer crash, and unit IDs must fit 24 bits. - search reports files it cannot read (exit 1 when none were readable); list output prints 6.25 kHz channels with 5 decimals; the summary card escapes tone names like the full report. --- quickprs/backup.py | 33 ++++++++++++++++++++++----------- quickprs/cleanup.py | 5 +++++ quickprs/cli.py | 41 +++++++++++++++++++++++++++++++++-------- quickprs/fleet.py | 30 +++++++++++++++++++----------- quickprs/injector.py | 35 +++++++++++++++++++++++++++++++++++ quickprs/reports.py | 2 +- tests/test_cli.py | 14 +++++++++++--- 7 files changed, 126 insertions(+), 34 deletions(-) diff --git a/quickprs/backup.py b/quickprs/backup.py index 4e5b47c..baa2d6c 100644 --- a/quickprs/backup.py +++ b/quickprs/backup.py @@ -13,6 +13,25 @@ MAX_BACKUPS = 10 +def _backups_of(src, backup_dir): + """Backups of ``src`` in ``backup_dir``, newest first. + + Matched on the exact name pattern create_backup writes, so the + backups of "radio_v2.PRS" are not taken for those of "radio.PRS", and + ordered by the timestamp in the name (a restored copy keeps its old + file time). + """ + import re + pattern = re.compile(re.escape(src.stem) + r"_(\d{8}_\d{6}(?:_\d{6})?)" + + re.escape(src.suffix) + "$", re.IGNORECASE) + found = [] + for p in Path(backup_dir).iterdir(): + m = pattern.match(p.name) + if m: + found.append((m.group(1), p)) + return [p for _, p in sorted(found, reverse=True)] + + def create_backup(filepath, backup_dir=None): """Create a timestamped backup of a PRS file. @@ -37,12 +56,8 @@ def create_backup(filepath, backup_dir=None): shutil.copy2(str(src), str(backup_path)) - # Prune old backups for this specific file (by stem prefix) - backups = sorted( - backup_dir.glob(f"{src.stem}_*{src.suffix}"), - key=lambda p: p.stat().st_mtime, - reverse=True, - ) + # Prune old backups for this specific file + backups = _backups_of(src, backup_dir) for old in backups[MAX_BACKUPS:]: old.unlink() @@ -61,11 +76,7 @@ def list_backups(filepath): if not backup_dir.exists(): return [] - backups = sorted( - backup_dir.glob(f"{src.stem}_*{src.suffix}"), - key=lambda p: p.stat().st_mtime, - reverse=True, - ) + backups = _backups_of(src, backup_dir) result = [] for i, bp in enumerate(backups, 1): diff --git a/quickprs/cleanup.py b/quickprs/cleanup.py index b8cf5b1..a4be0f6 100644 --- a/quickprs/cleanup.py +++ b/quickprs/cleanup.py @@ -72,6 +72,11 @@ def _get_system_config_refs(prs): if sn: refs.add(sn.strip().lower()) + # The sets each system actually names (trunk, talkgroup, conventional, + # P25 conventional and IDEN sets) + from .injector import system_set_references + refs |= {name.strip().lower() for name in system_set_references(prs)} + return refs diff --git a/quickprs/cli.py b/quickprs/cli.py index 7c0b317..fdfd751 100644 --- a/quickprs/cli.py +++ b/quickprs/cli.py @@ -1895,11 +1895,17 @@ def cmd_import_json(filepath, output=None): if output is None: output = Path(filepath).with_suffix('.PRS') + if output.exists(): + print(f"Error: {output} already exists (probably the " + f"personality this JSON came from); choose the output " + f"with -o", file=sys.stderr) + return 1 + from .prs_writer import write_prs out = Path(output) out.parent.mkdir(parents=True, exist_ok=True) + write_prs(prs, out, backup=True) raw = prs.to_bytes() - out.write_bytes(raw) print(f"Created: {out}") print(f" Size: {len(raw):,} bytes") @@ -2202,26 +2208,32 @@ def cmd_snapshot(filepath, output=None, compare=None): return 0 -def cmd_create(output_path, name=None, author=""): +def cmd_create(output_path, name=None, author="", force=False): """Create a new blank PRS file. Args: output_path: path for the output .PRS file name: personality name (defaults to output filename) author: saved-by field (default empty) + force: replace an existing file (a .bak copy is kept) Returns: 0 on success, 1 on error. """ from .builder import create_blank_prs + from .prs_writer import write_prs out = Path(output_path) + if out.exists() and not force: + print(f"Error: {out} already exists; use --force to replace it " + f"(a .bak copy is kept)", file=sys.stderr) + return 1 filename = name if name else out.name prs = create_blank_prs(filename=filename, saved_by=author) - raw = prs.to_bytes() out.parent.mkdir(parents=True, exist_ok=True) - out.write_bytes(raw) + write_prs(prs, out, backup=True) + raw = prs.to_bytes() print(f"Created: {out}") print(f"Size: {len(raw):,} bytes") @@ -3068,13 +3080,13 @@ def cmd_list(filepath, list_type): if ch.tx_tone: tone = f"tone={ch.tx_tone}" print(f"{cs.name}\t{ch.short_name}\t" - f"{ch.tx_freq:.4f}\t{ch.rx_freq:.4f}\t{tone}") + f"{ch.tx_freq:.5f}\t{ch.rx_freq:.5f}\t{tone}") elif list_type == "frequencies": sets = _parse_trunk_sets(prs) for ts in sets: for ch in ts.channels: - print(f"{ts.name}\t{ch.tx_freq:.4f}\t{ch.rx_freq:.4f}") + print(f"{ts.name}\t{ch.tx_freq:.5f}\t{ch.rx_freq:.5f}") elif list_type == "sets": for kind, parser_fn in [("group", _parse_group_sets), @@ -3845,7 +3857,18 @@ def cmd_search(filepaths, freq=None, tg=None, name=None): print("No PRS files found.", file=sys.stderr) return 1 - print(f"Searching {len(prs_files)} file(s)...") + unreadable = [] + for f in prs_files: + try: + parse_prs(f) + except Exception as e: + unreadable.append((f, e)) + for f, e in unreadable: + print(f"Warning: cannot read {f}: {e}", file=sys.stderr) + if len(unreadable) == len(prs_files): + return 1 + + print(f"Searching {len(prs_files) - len(unreadable)} file(s)...") print() from .search import ( @@ -4515,6 +4538,8 @@ def run_cli(args=None): help="Personality name (default: output filename)") p_create.add_argument("--author", default="", help="Saved-by field") + p_create.add_argument("--force", action="store_true", + help="Replace an existing file (keeps a .bak)") # build p_build = sub.add_parser("build", @@ -5691,7 +5716,7 @@ def run_cli(args=None): raw=parsed.raw) elif parsed.command == "create": return cmd_create(parsed.output, name=parsed.name, - author=parsed.author) + author=parsed.author, force=parsed.force) elif parsed.command == "build": return cmd_build(parsed.config, output=parsed.output) elif parsed.command == "export-config": diff --git a/quickprs/fleet.py b/quickprs/fleet.py index 5347c37..894d626 100644 --- a/quickprs/fleet.py +++ b/quickprs/fleet.py @@ -61,18 +61,21 @@ def build_fleet(config_path, units_csv_path, output_dir): output_dir.mkdir(parents=True, exist_ok=True) results = [] + written = set() for unit in units: unit_id = unit['unit_id'] - name = unit.get('name', '').strip() - password = unit.get('password', '').strip() - - # Determine output filename - if name: - filename = f"{name}.PRS" - else: - filename = f"unit_{unit_id}.PRS" + name = (unit.get('name') or '').strip() + password = (unit.get('password') or '').strip() + # Determine output filename: a plain name inside output_dir only + safe = "".join(c for c in name if c not in '\\/:*?"<>|').strip(". ") + filename = f"{safe}.PRS" if safe else f"unit_{unit_id}.PRS" out_path = output_dir / filename + if out_path in written: + results.append((str(out_path), unit_id, False, + f"duplicate output name {filename}")) + continue + written.add(out_path) try: prs = _build_unit_prs(config_path, unit_id, name, password) @@ -118,7 +121,7 @@ def _parse_units_csv(csv_path): pw_col = normalized.get('password') for row_num, row in enumerate(reader, start=2): - uid_str = row.get(uid_col, '').strip() + uid_str = (row.get(uid_col) or '').strip() if not uid_str: continue # skip blank rows @@ -128,13 +131,18 @@ def _parse_units_csv(csv_path): raise ValueError( f"Units CSV row {row_num}: invalid unit_id '{uid_str}'") + if not 1 <= uid <= 0xFFFFFF: + raise ValueError( + f"Units CSV row {row_num}: unit_id {uid} is outside " + f"the 24-bit P25 range (1-16777215)") + entry = {'unit_id': uid} if name_col is not None: - entry['name'] = row.get(name_col, '').strip() + entry['name'] = (row.get(name_col) or '').strip() else: entry['name'] = '' if pw_col is not None: - entry['password'] = row.get(pw_col, '').strip() + entry['password'] = (row.get(pw_col) or '').strip() else: entry['password'] = '' diff --git a/quickprs/injector.py b/quickprs/injector.py index 13aab11..ded22d8 100644 --- a/quickprs/injector.py +++ b/quickprs/injector.py @@ -187,6 +187,41 @@ def _system_obj_names(obj): return short, long_name +def system_set_references(prs): + """Every set name the personality's systems refer to. + + P25 trunked systems name a trunk set, a talkgroup set and an IDEN set; + conventional and P25 conventional systems name their channel set. + Returns an empty set when the archive cannot be read. + """ + try: + doc = archive.document_from_prs(prs) + except archive.WalkError: + return set() + refs = set() + for obj in doc.list("systems").items: + if obj is None: + continue + data = obj.parts[0] + _, pos = archive.read_cstring(data, 0) + pos += 1 + 2 + 42 # type byte, FFFF, prefix + _, pos = archive.read_cstring(data, pos) # long name + if obj.cls == "CP25TrkSystem": + pos += 15 + trunk, pos = archive.read_cstring(data, pos) + group, pos = archive.read_cstring(data, pos) + iden, _ = archive.read_cstring(obj.parts[2], 4) + refs.update((trunk, group, iden)) + elif obj.cls == "CConvSystem": + conv, _ = archive.read_cstring(data, pos + 12) + refs.add(conv) + elif obj.cls == "CP25ConvSystem": + conv, _ = archive.read_cstring(data, pos + 5 + 4) + refs.add(conv) + refs.discard("") + return refs + + def _append_system(prs, obj): doc = archive.document_from_prs(prs) doc.list("systems").items.append(obj) diff --git a/quickprs/reports.py b/quickprs/reports.py index 4278da7..c757163 100644 --- a/quickprs/reports.py +++ b/quickprs/reports.py @@ -780,7 +780,7 @@ def _card_add_summary_stats(parts, prs): tones = stats.get('ctcss_tones', {}) if tones: - tone_strs = [f"{t} ({c})" for t, c + tone_strs = [f"{_esc(t)} ({c})" for t, c in sorted(tones.items(), key=lambda x: -x[1])] parts.append(f"

" f"Tones:" diff --git a/tests/test_cli.py b/tests/test_cli.py index 486d46b..ed23734 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -880,15 +880,23 @@ def test_create_default_name_is_filename(self, capsys, tmp_path): p = parse_personality_section(sec.raw) assert p.filename == "MyPersonality.PRS" - def test_create_overwrites_existing(self, capsys, tmp_path): - """Create should silently overwrite an existing file.""" + def test_create_refuses_existing(self, capsys, tmp_path): + """Create must not wipe an existing personality by accident.""" out_file = tmp_path / "existing.PRS" out_file.write_bytes(b"old data") result = cmd_create(str(out_file)) + assert result == 1 + assert out_file.read_bytes() == b"old data" + assert "already exists" in capsys.readouterr().err + + def test_create_force_replaces_and_keeps_bak(self, capsys, tmp_path): + out_file = tmp_path / "existing.PRS" + out_file.write_bytes(b"old data") + result = cmd_create(str(out_file), force=True) assert result == 0 content = out_file.read_bytes() - assert content != b"old data" assert content[:2] == b'\xff\xff' # valid PRS header + assert (tmp_path / "existing.PRS.bak").read_bytes() == b"old data" def test_create_section_count(self, capsys, tmp_path): """Output should report section count.""" From d588d4b923244f34f2132385ad608d1da45ba62e Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:04:33 -0700 Subject: [PATCH 10/14] Apply INI [options]; set clone name and unit ID where they live - build ignored the [options] section (the README's example included) because a new personality has no platformConfig XML. It now starts from RPM's new-radio options and applies the lines. - clone-personality --name and --unit-id wrote invented attributes into the options XML and changed nothing the radio uses. The name goes in the CPersonality header and the Home Unit ID into every P25 trunked system, the same way fleet sets it. --- quickprs/cloner.py | 24 ++++++++++-------------- quickprs/config_builder.py | 11 +++++++---- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/quickprs/cloner.py b/quickprs/cloner.py index 9bf6b7b..8a2a867 100644 --- a/quickprs/cloner.py +++ b/quickprs/cloner.py @@ -101,13 +101,11 @@ def clone_personality(source_prs, modifications=None): if 'name' in mods: _set_personality_name(clone, mods['name']) - # 8. Set unit ID via option_maps + # 8. Set the Home Unit ID in every P25 trunked system (where the + # radio keeps it; the options XML has no unit ID attribute) if 'unit_id' in mods: - try: - set_platform_option(clone, 'misc', 'homeUnitID', - str(mods['unit_id'])) - except (ValueError, KeyError) as e: - logger.warning("Could not set unit_id: %s", e) + from .fleet import set_home_unit_id + set_home_unit_id(clone, int(mods['unit_id'])) # 9. Set password via option_maps if 'password' in mods: @@ -200,11 +198,9 @@ def _set_tx_on_set(prs, set_name, enable=True): def _set_personality_name(prs, name): - """Set the personality file name stored in the PRS header.""" - # The personality name is stored in the first section's raw bytes. - # Try setting it via option maps first. - try: - set_platform_option(prs, 'misc', 'personalityName', name) - except (ValueError, KeyError, TypeError): - # Not all files have this option — log and continue - logger.debug("Could not set personality name via option_maps") + """Set the personality name stored in the CPersonality header (the + options XML has no name attribute).""" + from .injector import edit_personality + if not name.upper().endswith(".PRS"): + name = f"{name}.PRS" + edit_personality(prs, filename=name) diff --git a/quickprs/config_builder.py b/quickprs/config_builder.py index 21aa8f7..dfcab8d 100644 --- a/quickprs/config_builder.py +++ b/quickprs/config_builder.py @@ -407,14 +407,17 @@ def _apply_options(cfg, prs): from .option_maps import ( extract_platform_config, config_to_xml, write_platform_config, + _inject_platform_xml, _create_default_platform_xml, ) - # Get current platform config (may not exist in blank PRS) + # Get current platform config. A new personality has none yet: start + # it from RPM's new-radio options, then apply the [options] lines. config = extract_platform_config(prs) if config is None: - # Blank PRS has no platformConfig — nothing to modify - logger.debug("No platformConfig found, skipping options") - return + if not _inject_platform_xml(prs, _create_default_platform_xml()): + raise ConfigError( + "[options]: this personality cannot take radio options") + config = extract_platform_config(prs) # Apply each option for key, value in options: From c51a0b0376fd94dbc776108a5b7cb365338d4a77 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:18:32 -0700 Subject: [PATCH 11/14] Wide 800 MHz interop direct channels; PSERN examples use 939 - The 800 MHz interop direct channels (8CALL90D, 8TAC91D-94D) were narrowband while their repeater pairs were wide. 806-809/851-854 MHz has a 20 kHz authorized bandwidth (47 CFR 90.209), direct channels included, so all ten are wide. (RadioReference lists 8TAC91D-94D as FMN but 8CALL90D as FM.) New test covers it. - Help text and examples paired PSERN with System ID 892; the RPM-saved value is 939. - The training preset claimed "low power" but only turns GPS on. --- quickprs/cli.py | 12 ++++++------ quickprs/favorites.py | 2 +- quickprs/record_types.py | 2 +- quickprs/templates.py | 26 +++++++++++++------------- tests/test_templates.py | 10 +++++++++- 5 files changed, 30 insertions(+), 22 deletions(-) diff --git a/quickprs/cli.py b/quickprs/cli.py index fdfd751..b91d864 100644 --- a/quickprs/cli.py +++ b/quickprs/cli.py @@ -6,14 +6,14 @@ quickprs export-csv file.PRS output_dir/ quickprs compare file_a.PRS file_b.PRS [--detail] quickprs dump file.PRS [-s N] [-x BYTES] - quickprs inject file.PRS p25 --name PSERN --sysid 892 ... + quickprs inject file.PRS p25 --name PSERN --sysid 939 ... quickprs inject file.PRS conv --name MURS --channels-csv ch.csv quickprs inject file.PRS conv --name MURS --template murs quickprs inject file.PRS talkgroups --set "PSERN PD" --tgs-csv tgs.csv quickprs merge target.PRS source.PRS [--systems] [--channels] [--all] quickprs clone target.PRS source.PRS "PSERN SEATTLE" [-o output.PRS] quickprs import-rr file.PRS --sid 8155 --username USER --apikey KEY - quickprs import-paste file.PRS --name PSERN --sysid 892 --tgs-file tgs.txt + quickprs import-paste file.PRS --name PSERN --sysid 939 --tgs-file tgs.txt quickprs export-json file.PRS [-o output.json] quickprs import-json file.json [-o output.PRS] quickprs remove file.PRS system "PSERN SEATTLE" @@ -4709,7 +4709,7 @@ def run_cli(args=None): formatter_class=fmt, epilog="Example:\n" " quickprs import-paste radio.PRS --name PSERN " - "--sysid 892 --wacn 781824 " + "--sysid 939 --wacn 781824 " "--tgs-file tgs.txt --freqs-file freqs.txt") p_paste.add_argument("file", help="PRS file to inject into") p_paste.add_argument("--name", required=True, @@ -4877,7 +4877,7 @@ def run_cli(args=None): epilog="Subcommands: p25, conv, talkgroups\n\n" "Examples:\n" " quickprs inject radio.PRS p25 --name PSERN " - "--sysid 892 --freqs-csv freqs.csv --tgs-csv tgs.csv\n" + "--sysid 939 --freqs-csv freqs.csv --tgs-csv tgs.csv\n" " quickprs inject radio.PRS conv --template murs\n" " quickprs inject radio.PRS talkgroups " "--set \"PSERN PD\" --tgs-csv more_tgs.csv") @@ -4890,7 +4890,7 @@ def run_cli(args=None): formatter_class=fmt, epilog="Example:\n" " quickprs inject radio.PRS p25 --name PSERN " - "--sysid 892 --wacn 781824 " + "--sysid 939 --wacn 781824 " "--freqs-csv freqs.csv --tgs-csv tgs.csv") p_inj_p25.add_argument("--name", required=True, help="System short name (8 chars max)") @@ -5463,7 +5463,7 @@ def run_cli(args=None): epilog="Examples:\n" " quickprs favorites list\n" " quickprs favorites list systems\n" - " quickprs favorites add system PSERN --sysid 892\n" + " quickprs favorites add system PSERN --sysid 939\n" " quickprs favorites add template murs\n" " quickprs favorites remove system PSERN\n" " quickprs favorites clear") diff --git a/quickprs/favorites.py b/quickprs/favorites.py index 8521f84..d49c2c9 100644 --- a/quickprs/favorites.py +++ b/quickprs/favorites.py @@ -178,7 +178,7 @@ def clear_favorites(category=None): }, }, 'training': { - 'description': 'Training mode (GPS on, low power)', + 'description': 'Training mode (GPS on)', 'options': { 'gps.gpsMode': 'ON', }, diff --git a/quickprs/record_types.py b/quickprs/record_types.py index 746c6f4..c8f8cb9 100644 --- a/quickprs/record_types.py +++ b/quickprs/record_types.py @@ -1804,7 +1804,7 @@ class P25TrkSystemConfig: group_set_name: str = "" # reference to CP25GroupSet (e.g., "PSERN PD") wan_name: str = "" # WAN name, 8-char padded (e.g., "PSERN ") home_unit_id: int = 0 # radio's unit ID on this system - system_id: int = 0 # P25 System ID (decimal, e.g., 892 for PSERN) + system_id: int = 0 # P25 System ID (decimal, e.g., 939 for PSERN) wacn: int = 0 # Wide Area Communication Network ID (for WAN section) sys_flags: bytes = P25_TRUNK_DEFAULT_FLAGS # 15 bytes diff --git a/quickprs/templates.py b/quickprs/templates.py index 8eab137..6fb6a9b 100644 --- a/quickprs/templates.py +++ b/quickprs/templates.py @@ -252,9 +252,12 @@ def get_interop_channels(): - UHF repeater pairs (radio transmits 5 MHz up) and their direct ("D") simplex channels: UCALL40 453.2125, UTAC41 453.4625, UTAC42 453.7125, UTAC43 453.8625 MHz - - 800 MHz repeater pairs (radio transmits 45 MHz down; wide FM) and - direct channels: 8CALL90 851.0125, 8TAC91-94 851.5125-853.0125 MHz - (the rebanded frequencies; 866-868 MHz is the pre-rebanding plan) + - 800 MHz repeater pairs (radio transmits 45 MHz down) and direct + channels: 8CALL90 851.0125, 8TAC91-94 851.5125-853.0125 MHz (the + rebanded frequencies; 866-868 MHz is the pre-rebanding plan). All + wide FM: 806-809/851-854 MHz has a 20 kHz authorized bandwidth + (47 CFR 90.209), direct channels included, although RadioReference + lists 8TAC91D-94D as FMN The 700 MHz channels (7CALL50, 7TAC51-56) are P25 digital (NAC 293), which an analog conventional set cannot carry; add them as a P25 @@ -273,22 +276,19 @@ def ch(name, rx, tx=None, long_name="", narrowband=True): ch('VTAC13', 158.7375, long_name='VHF Tactical 13'), ch('VTAC14', 159.4725, long_name='VHF Tactical 14'), ] - for name, out, label in (('UCALL40', 453.2125, 'UHF Call'), - ('UTAC41', 453.4625, 'UHF Tactical 41'), - ('UTAC42', 453.7125, 'UHF Tactical 42'), - ('UTAC43', 453.8625, 'UHF Tactical 43')): + for name, out in (('UCALL40', 453.2125), ('UTAC41', 453.4625), + ('UTAC42', 453.7125), ('UTAC43', 453.8625)): channels.append(ch(name, out, tx=round(out + 5.0, 4), long_name=f'{name} Repeater')) channels.append(ch(name + 'D', out, long_name=f'{name} Direct')) - for name, out, label in (('8CALL90', 851.0125, '800 Call'), - ('8TAC91', 851.5125, '800 Tactical 91'), - ('8TAC92', 852.0125, '800 Tactical 92'), - ('8TAC93', 852.5125, '800 Tactical 93'), - ('8TAC94', 853.0125, '800 Tactical 94')): + for name, out in (('8CALL90', 851.0125), ('8TAC91', 851.5125), + ('8TAC92', 852.0125), ('8TAC93', 852.5125), + ('8TAC94', 853.0125)): channels.append(ch(name, out, tx=round(out - 45.0, 4), long_name=f'{name} Repeater', narrowband=False)) - channels.append(ch(name + 'D', out, long_name=f'{name} Direct')) + channels.append(ch(name + 'D', out, long_name=f'{name} Direct', + narrowband=False)) return channels diff --git a/tests/test_templates.py b/tests/test_templates.py index 13bea76..7e55d86 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -369,7 +369,8 @@ def test_interop_vhf_channels(self): assert len(vhf) == 5 def test_interop_uhf_channels(self): - """Interop has 5 UHF channels (UCALL40 + UTAC41-44).""" + """UCALL40 + UTAC41-43, each as a repeater pair and a direct + channel.""" channels = get_interop_channels() uhf = [ch for ch in channels if ch['short_name'].startswith('U')] @@ -382,6 +383,13 @@ def test_interop_800_channels(self): if ch['short_name'].startswith('8')] assert len(ch800) == 10 + def test_interop_bandwidth(self): + """VHF and UHF interop is narrowband; 800 MHz (NPSPAC) is wide on + the repeater pair and the direct channel alike.""" + for ch in get_interop_channels(): + wide = ch['short_name'].startswith('8') + assert ch['narrowband'] is (not wide), ch['short_name'] + def test_interop_vhf_tones(self): """VHF interop channels use 156.7 Hz CTCSS tone.""" channels = get_interop_channels() From 83068072ad5d65d973e98dcb7455b80f57aa7fdf Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:36:44 -0700 Subject: [PATCH 12/14] Check build options; keep exported option lists; wizard time zone Since build started applying [options] to new personalities, it wrote each line into a dict of the options XML: a friendly name such as gps.gpsMode added an invented element beside the real gpsConfig, misc.password never reached miscConfig, any value was accepted, and the lists export-config writes for repeated elements (programmable buttons, accessory buttons, short menu, microphones) replaced those elements with an attribute holding the list text. - apply_platform_options applies every line the way set-option does (section names mapped, attributes and values checked) on one parsed copy of the XML and writes once, so a bad line changes nothing. List values update the existing elements in order; the count must match and each value is checked. The PAWSOVERMAWS options now come back identical through export-config and build. - The wizard saved the time zone as display.timeZone, which the radio does not have; it sets TimeDateCfg zone and asks again for a zone RPM does not list (and for a GPS answer other than ON/OFF). - The bad-option test passed on the old code for the wrong reason (every case failed earlier, on the missing options XML); each case now checks its own message. --- quickprs/config_builder.py | 39 +++------- quickprs/option_maps.py | 138 ++++++++++++++++++++++++++------- quickprs/wizard.py | 22 +++++- tests/test_config_builder.py | 91 ++++++++++++++++++++++ tests/test_platform_options.py | 17 ++-- tests/test_wizard.py | 30 +++++++ 6 files changed, 268 insertions(+), 69 deletions(-) diff --git a/quickprs/config_builder.py b/quickprs/config_builder.py index dfcab8d..9ddeee3 100644 --- a/quickprs/config_builder.py +++ b/quickprs/config_builder.py @@ -405,36 +405,15 @@ def _apply_options(cfg, prs): f"[options]: key '{key}' must be dot-separated " f"(e.g., gps.gpsMode)") - from .option_maps import ( - extract_platform_config, config_to_xml, write_platform_config, - _inject_platform_xml, _create_default_platform_xml, - ) - - # Get current platform config. A new personality has none yet: start - # it from RPM's new-radio options, then apply the [options] lines. - config = extract_platform_config(prs) - if config is None: - if not _inject_platform_xml(prs, _create_default_platform_xml()): - raise ConfigError( - "[options]: this personality cannot take radio options") - config = extract_platform_config(prs) - - # Apply each option - for key, value in options: - parts = key.split('.') - - # Navigate into the config dict - target = config - for part in parts[:-1]: - if part not in target: - target[part] = {} - target = target[part] - - target[parts[-1]] = value - - # Write back - xml_str = config_to_xml(config) - write_platform_config(prs, xml_str) + # Checked like `quickprs set-option`, against the options RPM writes + # for a new radio when the personality has none yet. Unknown + # attributes and disallowed values are errors: written into the XML + # they would add elements the radio does not have. + from .option_maps import apply_platform_options + try: + apply_platform_options(prs, options) + except ValueError as e: + raise ConfigError(f"[options] {e}") from e # ─── Export: PRS → INI config ────────────────────────────────────── diff --git a/quickprs/option_maps.py b/quickprs/option_maps.py index 87bb942..5bd4ac2 100644 --- a/quickprs/option_maps.py +++ b/quickprs/option_maps.py @@ -350,35 +350,24 @@ def _check_option_value(field, value): raise ValueError(f"{field.attribute} must be <= {field.max_val}") -def set_platform_option(prs, section_name, attr_name, value, - create=False): - """Modify a platformConfig XML attribute in the PRS file. - - Args: - prs: parsed PRSFile object - section_name: friendly section name ('gps', 'audio'), XML element - name ('gpsConfig') or a nested path such as - 'audioConfig/microphone[micType=INTERNAL]' - attr_name: XML attribute name (e.g. 'gpsMode', 'speakerMode') - value: new value as string - create: allow adding an attribute QuickPRS does not know about - - Returns: - True when the attribute was set. - - Raises: - ValueError: no platformConfig and none could be added, unknown - element or attribute, or a value the field does not allow. - """ +def _platform_root(prs): + """The personality's platformConfig as an element tree, adding RPM's + new-radio options first when it has none.""" xml_str = extract_platform_xml(prs) if xml_str is None: - # Start from the options RPM writes for a new radio if not _inject_platform_xml(prs, _create_default_platform_xml()): raise ValueError( "No platformConfig XML found and unable to create one") xml_str = extract_platform_xml(prs) + return ET.fromstring(xml_str) - root = ET.fromstring(xml_str) + +def _write_platform_root(prs, root): + if not write_platform_config(prs, ET.tostring(root, encoding='unicode')): + raise ValueError("Failed to write updated XML back to PRS file") + + +def _set_option_in_tree(root, section_name, attr_name, value, create=False): target = _find_option_element(root, section_name) if target is None: valid = sorted({child.tag for child in root}) @@ -393,17 +382,112 @@ def set_platform_option(prs, section_name, attr_name, value, f"<{target.tag}> has no attribute '{attr_name}'. " f"Attributes: {', '.join(known) or '(none)'}") _check_option_value(field, value) - target.set(attr_name, str(value)) - # Rebuild XML and write back - new_xml_str = ET.tostring(root, encoding='unicode') - if not write_platform_config(prs, new_xml_str): - raise ValueError("Failed to write updated XML back to PRS file") +def _child_field(parent_path, child, attr_name): + """Field definition for an attribute of a repeated element such as + (indexed by micType) or (by tag alone).""" + for key, val in child.attrib.items(): + field = _field_def(f"{parent_path}/{child.tag}[{key}={val}]", + attr_name) + if field is not None: + return field + return XML_FIELD_INDEX.get((child.tag, attr_name)) + + +def _set_children_in_tree(root, parent_path, tag, entries): + """Update the elements under ``parent_path`` from ``entries``, + one attribute dict per element in order (the form export-config + writes). The radio has a fixed set of these, so the count must match + and only attributes the elements have can be set.""" + parent = _find_option_element(root, parent_path) + if parent is None: + raise ValueError(f"Section '{parent_path}' not found in " + f"platformConfig") + children = [c for c in parent if c.tag == tag] + if not children: + raise ValueError(f"<{parent.tag}> has no <{tag}> elements") + if (not isinstance(entries, list) or + not all(isinstance(e, dict) for e in entries)): + raise ValueError(f"<{tag}> entries must be a list of attribute " + f"sets") + if len(entries) != len(children): + raise ValueError(f"<{parent.tag}> has {len(children)} <{tag}> " + f"elements, got {len(entries)}") + full_path = "/".join(SECTION_MAP.get(p, p) if i == 0 else p + for i, p in enumerate(parent_path.split("/"))) + for child, attrs in zip(children, entries): + for attr_name, value in attrs.items(): + field = _child_field(full_path, child, attr_name) + if child.get(attr_name) is None and field is None: + raise ValueError(f"<{tag}> has no attribute '{attr_name}'") + _check_option_value(field, value) + for attr_name, value in attrs.items(): + child.set(attr_name, str(value)) + + +def set_platform_option(prs, section_name, attr_name, value, + create=False): + """Modify a platformConfig XML attribute in the PRS file. + + Args: + prs: parsed PRSFile object + section_name: friendly section name ('gps', 'audio'), XML element + name ('gpsConfig') or a nested path such as + 'audioConfig/microphone[micType=INTERNAL]' + attr_name: XML attribute name (e.g. 'gpsMode', 'speakerMode') + value: new value as string + create: allow adding an attribute QuickPRS does not know about + + Returns: + True when the attribute was set. + + Raises: + ValueError: no platformConfig and none could be added, unknown + element or attribute, or a value the field does not allow. + """ + root = _platform_root(prs) + _set_option_in_tree(root, section_name, attr_name, value, create) + _write_platform_root(prs, root) return True +def apply_platform_options(prs, options): + """Apply ``(key, value)`` option lines, all or none. + + Keys are dotted paths ending in an attribute: ``gps.gpsMode``, + ``gpsConfig.gpsMode`` or ``accessoryConfig.accessoryButtons.x``. A + value that is a list of attribute dicts updates repeated elements + (``progButtons.progButton = [{...}, ...]``), as export-config writes + them. Every line is checked like set_platform_option before anything + is written. + + Raises: + ValueError: naming the first line that cannot be applied. + """ + import ast + root = _platform_root(prs) + for key, value in options: + section, _, attr_name = key.rpartition('.') + if not section or not attr_name: + raise ValueError(f"{key}: expected section.attribute") + path = section.replace('.', '/') + text = str(value).strip() + try: + if text.startswith('['): + try: + entries = ast.literal_eval(text) + except (ValueError, SyntaxError) as e: + raise ValueError(f"not a list of elements ({e})") + _set_children_in_tree(root, path, attr_name, entries) + else: + _set_option_in_tree(root, path, attr_name, value) + except ValueError as e: + raise ValueError(f"{key}: {e}") from e + _write_platform_root(prs, root) + + def list_platform_options(prs): """List all platformConfig options with their current values. diff --git a/quickprs/wizard.py b/quickprs/wizard.py index 41e6525..a1620af 100644 --- a/quickprs/wizard.py +++ b/quickprs/wizard.py @@ -38,6 +38,15 @@ def _input(prompt, default=None): return value if value else (default if default is not None else "") +def _input_choice(prompt, choices): + """Ask until the answer is blank (skip) or one of ``choices``.""" + while True: + value = _input(prompt, "").upper() + if not value or value in choices: + return value + print(f" Choose one of: {', '.join(choices)}") + + def _input_yn(prompt, default=False): """Yes/no prompt. @@ -283,17 +292,22 @@ def run_wizard(modify_file=None): print("--- Step 4: Radio Options ---") options = {} - gps = _input("Set GPS mode? [ON/off]", "") + from .option_maps import XML_FIELD_INDEX + + gps = _input_choice("Set GPS mode? [ON/off]", ("ON", "OFF")) if gps: - options['gps.gpsMode'] = gps.upper() + options['gps.gpsMode'] = gps password = _input("Set radio password (blank to skip)", "") if password: options['misc.password'] = password - timezone = _input("Set timezone (e.g., PST, EST, UTC, blank to skip)", "") + # The radio's time zone is TimeDateCfg zone, one of RPM's abbreviations + zones = XML_FIELD_INDEX[("TimeDateCfg", "zone")].enum_values + timezone = _input_choice( + "Set time zone (e.g., PST, EST, GMT, blank to skip)", zones) if timezone: - options['display.timeZone'] = timezone.upper() + options['timedate.zone'] = timezone print() # --- Build --- diff --git a/tests/test_config_builder.py b/tests/test_config_builder.py index 62c4b10..1cd698d 100644 --- a/tests/test_config_builder.py +++ b/tests/test_config_builder.py @@ -1206,3 +1206,94 @@ def test_parse_inline_skips_template_key(self): } channels = _parse_inline_channels(section) assert len(channels) == 1 # template key skipped + + +class TestOptionsOnNewPersonality: + """[options] applies to a personality built from scratch (it used to + be skipped because a new personality has no options XML yet).""" + + def test_options_are_applied(self, tmp_path): + import xml.etree.ElementTree as ET + from quickprs.option_maps import ( + extract_platform_xml, _DEFAULT_PLATFORM_XML, + ) + ini = tmp_path / "opts.ini" + ini.write_text("[personality]\nname = OPTS.PRS\n\n" + "[channels.MURS]\ntemplate = murs\n\n" + "[options]\ngps.gpsMode = OFF\n" + "misc.password = 1234\n", encoding="utf-8") + xml = extract_platform_xml(build_from_config(str(ini))) + assert xml is not None + root = ET.fromstring(xml) + assert root.find("gpsConfig").get("gpsMode") == "OFF" + assert root.find("miscConfig").get("password") == "1234" + # set on RPM's elements, with nothing added beside them + assert ([c.tag for c in root] == + [c.tag for c in ET.fromstring(_DEFAULT_PLATFORM_XML)]) + + def test_bad_option_is_an_error(self, tmp_path): + ini = tmp_path / "bad.ini" + ini.write_text("[personality]\nname = BAD.PRS\n\n" + "[channels.MURS]\ntemplate = murs\n\n" + "[options]\ngps.gpsMode = BANANA\n", + encoding="utf-8") + with pytest.raises(ConfigError, match="gpsMode"): + build_from_config(str(ini)) + + +class TestOptionsRoundTrip: + """export-config writes repeated option elements (programmable + buttons, microphones, short menu) as lists; build must put them back + as elements, not as an attribute holding the list text.""" + + BUTTONS = ("[{'buttonName': 'TOP_SIDE', 'function': 'TALKAROUND_DIRECT'," + " 'delay': '0.0', 'extraData': ''}," + " {'buttonName': 'MID_SIDE', 'function': 'ZONE_UP'," + " 'delay': '0.0', 'extraData': ''}," + " {'buttonName': 'BOT_SIDE', 'function': 'ZONE_DOWN'," + " 'delay': '0.0', 'extraData': ''}," + " {'buttonName': 'EMERGENCY', 'function': 'EMERGENCY_CALL'," + " 'delay': '', 'extraData': ''}]") + + def _build(self, tmp_path, lines): + ini = tmp_path / "rt.ini" + ini.write_text("[personality]\nname = RT.PRS\n\n" + "[channels.MURS]\ntemplate = murs\n\n" + "[options]\n" + lines, encoding="utf-8") + return build_from_config(str(ini)) + + def test_list_updates_elements(self, tmp_path): + import re + from quickprs.option_maps import extract_platform_xml + prs = self._build(tmp_path, + f"progButtons.progButton = {self.BUTTONS}\n") + xml = extract_platform_xml(prs) + assert "[{" not in xml + buttons = re.findall(r"]*>", xml) + assert len(buttons) == 4 + assert 'buttonName="TOP_SIDE" function="TALKAROUND_DIRECT"' \ + in buttons[0] + + def test_list_with_wrong_count_is_an_error(self, tmp_path): + two = "[{'buttonName': 'TOP_SIDE'}, {'buttonName': 'MID_SIDE'}]" + with pytest.raises(ConfigError, match="4 "): + self._build(tmp_path, f"progButtons.progButton = {two}\n") + + def test_list_value_is_checked(self, tmp_path): + mics = ("[{'micType': 'INTERNAL', 'alc': 'OFF', 'gain': '99'}," + " {'micType': 'EXTERNAL', 'alc': 'OFF', 'gain': '0'}]") + with pytest.raises(ConfigError, match="gain must be <= 12"): + self._build(tmp_path, f"audioConfig.microphone = {mics}\n") + + @pytest.mark.skipif(not (TESTDATA / "PAWSOVERMAWS.PRS").exists(), + reason="Test PRS data not available") + def test_rpm_options_survive_export_and_build(self, tmp_path): + from quickprs.prs_parser import parse_prs + from quickprs.config_builder import export_config + from quickprs.option_maps import extract_platform_config + source = parse_prs(str(TESTDATA / "PAWSOVERMAWS.PRS")) + ini = tmp_path / "paws.ini" + export_config(source, str(ini)) + built = build_from_config(str(ini)) + assert (extract_platform_config(built) == + extract_platform_config(source)) diff --git a/tests/test_platform_options.py b/tests/test_platform_options.py index e8e8c31..4d6e39c 100644 --- a/tests/test_platform_options.py +++ b/tests/test_platform_options.py @@ -38,15 +38,16 @@ def test_first_option_adds_xml_in_place(blank): assert 'gpsMode="OFF"' in extract_platform_xml(blank) -@pytest.mark.parametrize("section,attr,value", [ - ("gps", "gpsModee", "ON"), # misspelt attribute - ("gps", "gpsMode", "BANANA"), # not ON/OFF - ("misc", "batteryType", "STANDARD"), # not in the enum - ("audioConfig/microphone[micType=INTERNAL]", "gain", "99"), # > 12 - ("nosuchsection", "x", "1"), +@pytest.mark.parametrize("section,attr,value,why", [ + ("gps", "gpsModee", "ON", "no attribute 'gpsModee'"), + ("gps", "gpsMode", "BANANA", "must be ON or OFF"), + ("misc", "batteryType", "STANDARD", "must be one of"), + ("audioConfig/microphone[micType=INTERNAL]", "gain", "99", + "must be <= 12"), + ("nosuchsection", "x", "1", "'nosuchsection' not found"), ]) -def test_bad_options_rejected(blank, section, attr, value): - with pytest.raises(ValueError): +def test_bad_options_rejected(blank, section, attr, value, why): + with pytest.raises(ValueError, match=re.escape(why)): set_platform_option(blank, section, attr, value) diff --git a/tests/test_wizard.py b/tests/test_wizard.py index 0836129..77227ca 100644 --- a/tests/test_wizard.py +++ b/tests/test_wizard.py @@ -807,3 +807,33 @@ def test_wizard_roundtrips(self, tmp_path): raw1 = prs.to_bytes() raw2 = parse_prs_bytes(raw1).to_bytes() assert raw1 == raw2 + + +class TestWizardOptionsReachTheRadio: + """The wizard's GPS, password and time zone answers end up in the + radio's options (the time zone used to go to an attribute the radio + does not have).""" + + def _run(self, tmp_path, answers): + from quickprs.prs_parser import parse_prs + from quickprs.option_maps import extract_platform_xml + out = str(tmp_path / "OPTS.PRS") + inputs = ["OPTS.PRS", out, "n", "murs"] + answers + with patch('builtins.input', side_effect=inputs): + assert run_wizard() == 0 + return extract_platform_xml(parse_prs(out)) + + def test_answers_are_set(self, tmp_path): + import xml.etree.ElementTree as ET + from quickprs.option_maps import _DEFAULT_PLATFORM_XML + root = ET.fromstring(self._run(tmp_path, ["off", "1234", "pst"])) + assert root.find("TimeDateCfg").get("zone") == "PST" + assert root.find("gpsConfig").get("gpsMode") == "OFF" + assert root.find("miscConfig").get("password") == "1234" + assert ([c.tag for c in root] == + [c.tag for c in ET.fromstring(_DEFAULT_PLATFORM_XML)]) + + def test_unknown_zone_is_asked_again(self, tmp_path, capsys): + xml = self._run(tmp_path, ["", "", "UTC", "GMT"]) + assert "Choose one of" in capsys.readouterr().out + assert 'zone="GMT"' in xml From 9d09cee1abe1c05147bdd48eff4abe43a1dc017a Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:36:44 -0700 Subject: [PATCH 13/14] Regression tests for the overwrite, cleanup, backup, fleet and clone fixes Commits 38694cf and 14b5c6f fixed these without tests. Each new test fails with its fix undone: - import-json leaves the .PRS its JSON came from alone - cleanup counts the sets RPM-saved systems name as used - backups: exact file name, newest by the name's timestamp - fleet: names stay in the output folder, duplicates reported, short rows read, unit IDs limited to 24 bits - search reports unreadable files and fails when none can be read - list prints 6.25 kHz channels with five decimals - the summary card escapes tone names - clone-personality puts the name in the header and the unit ID in every P25 trunked system --- quickprs/cloner.py | 5 +++-- tests/test_backup.py | 25 ++++++++++++++++++++++++ tests/test_cleanup.py | 28 +++++++++++++++++++++++++++ tests/test_cli.py | 29 ++++++++++++++++++++++++++++ tests/test_cli_list_bulk.py | 21 ++++++++++++++++++++ tests/test_cloner_renumber.py | 24 +++++++++++++++++++++++ tests/test_fleet.py | 33 ++++++++++++++++++++++++++++++++ tests/test_reports.py | 24 +++++++++++++++++++++++ tests/test_search.py | 36 +++++++++++++++++++++++++++++++++++ 9 files changed, 223 insertions(+), 2 deletions(-) diff --git a/quickprs/cloner.py b/quickprs/cloner.py index 8a2a867..6b50be0 100644 --- a/quickprs/cloner.py +++ b/quickprs/cloner.py @@ -37,14 +37,15 @@ def clone_personality(source_prs, modifications=None): Args: source_prs: PRSFile to clone modifications: dict with optional keys: - 'name': new personality name (stored in options) + 'name': new personality name (in the CPersonality header; + '.PRS' is added when missing) 'remove_sets': list of set names to remove (trunk/group/conv) 'remove_systems': list of system long names to remove 'add_talkgroups': {set_name: [(id, short_name, long_name), ...]} 'remove_talkgroups': {set_name: [group_id, ...]} 'enable_tx_sets': [set_names where TX should be enabled] 'disable_tx_sets': [set_names where TX should be disabled] - 'unit_id': int for HomeUnitID + 'unit_id': Home Unit ID for every P25 trunked system 'password': str for radio password Returns: diff --git a/tests/test_backup.py b/tests/test_backup.py index de95b52..07c3e73 100644 --- a/tests/test_backup.py +++ b/tests/test_backup.py @@ -393,3 +393,28 @@ def test_cli_backup_restore_no_backups(self, capsys): assert rc == 1 err = capsys.readouterr().err assert "No backups" in err + + +class TestBackupsOfExactFile: + """Backups are matched on the exact file name and ordered by the + timestamp create_backup puts in the name.""" + + def test_similar_name_is_not_listed(self, tmp_path): + radio = _make_test_prs(tmp_path, "radio.PRS", b"A") + other = _make_test_prs(tmp_path, "radio_v2.PRS", b"B") + create_backup(radio) + create_backup(other) + listed = [Path(p).name for _, p, _ in list_backups(radio)] + assert len(listed) == 1 + assert listed[0].startswith("radio_2") + + def test_newest_by_name_not_file_time(self, tmp_path): + radio = _make_test_prs(tmp_path, "radio.PRS", b"A") + first = Path(create_backup(radio)) + time.sleep(0.01) + second = Path(create_backup(radio)) + # a restored or copied backup can carry a newer file time + later = second.stat().st_mtime + 100 + os.utime(first, (later, later)) + listed = [Path(p) for _, p, _ in list_backups(radio)] + assert listed == [second, first] diff --git a/tests/test_cleanup.py b/tests/test_cleanup.py index 278cbbc..d60666c 100644 --- a/tests/test_cleanup.py +++ b/tests/test_cleanup.py @@ -343,3 +343,31 @@ def test_cleanup_report_both_files(self): prs = parse_prs(fp) lines = cleanup_report(prs) assert len(lines) > 0 + + +class TestUnusedSetsSeeSystemReferences: + """A set a system names is in use (cleanup used to report every + trunk and talkgroup set of an RPM-saved file as unused).""" + + @pytest.mark.skipif(not PAWS.exists(), + reason="Test PRS data not available") + def test_rpm_saved_system_sets_are_used(self): + unused = find_unused_sets(cached_parse_prs(PAWS)) + assert unused["trunk_sets"] == [] + assert unused["group_sets"] == [] + # WA and NV both use FURRY NB; nothing names WA WIDE + assert unused["conv_sets"] == ["WA WIDE"] + + def test_built_system_sets_are_used(self): + from quickprs.config_builder import build_from_config + prs = build_from_config(str(TESTDATA / "example_patrol.ini")) + unused = find_unused_sets(prs) + assert unused["trunk_sets"] == [] + assert unused["group_sets"] == [] + + def test_unreferenced_set_is_still_reported(self): + from quickprs.config_builder import build_from_config + from quickprs.injector import make_group_set, add_group_set + prs = build_from_config(str(TESTDATA / "example_patrol.ini")) + add_group_set(prs, make_group_set("SPARE", [(77, "SPARE", "Spare")])) + assert find_unused_sets(prs)["group_sets"] == ["SPARE"] diff --git a/tests/test_cli.py b/tests/test_cli.py index ed23734..f9c2dad 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -986,3 +986,32 @@ def test_freq_tools_no_subcommand(self, capsys): """freq-tools without subcommand should show help.""" result = run_cli(["freq-tools"]) assert result == 1 + + +class TestImportJsonKeepsSource: + """import-json's default output is the .PRS the JSON was exported + from, so it must not overwrite it silently.""" + + def _export(self, tmp_path): + from quickprs.cli import cmd_create, cmd_export_json + prs_path = tmp_path / "radio.PRS" + assert cmd_create(str(prs_path), name="RADIO") == 0 + json_path = tmp_path / "radio.json" + assert cmd_export_json(str(prs_path), str(json_path)) == 0 + return prs_path, json_path + + def test_default_output_is_not_overwritten(self, tmp_path, capsys): + from quickprs.cli import cmd_import_json + prs_path, json_path = self._export(tmp_path) + before = prs_path.read_bytes() + prs_path.write_bytes(before + b"edited since export") + assert cmd_import_json(str(json_path)) == 1 + assert prs_path.read_bytes() == before + b"edited since export" + assert "already exists" in capsys.readouterr().err + + def test_explicit_output_is_written(self, tmp_path): + from quickprs.cli import cmd_import_json + _, json_path = self._export(tmp_path) + out = tmp_path / "copy.PRS" + assert cmd_import_json(str(json_path), str(out)) == 0 + assert out.exists() diff --git a/tests/test_cli_list_bulk.py b/tests/test_cli_list_bulk.py index 55854a2..193cf8b 100644 --- a/tests/test_cli_list_bulk.py +++ b/tests/test_cli_list_bulk.py @@ -374,3 +374,24 @@ def test_gui_app_has_main(self): """gui.app should have a main() function.""" from quickprs.gui.app import main assert callable(main) + + +def _personality_with_channel(path, short_name="ODD", freq=851.00625, + tx_tone=""): + from quickprs.builder import create_blank_prs + from quickprs.injector import make_conv_set, _safe_add_conv_set + from quickprs.prs_writer import write_prs + prs = create_blank_prs() + _safe_add_conv_set(prs, make_conv_set("ODD", [ + {"short_name": short_name, "tx_freq": freq, "rx_freq": freq, + "tx_tone": tx_tone, "rx_tone": tx_tone}])) + write_prs(prs, str(path), backup=False) + return prs + + +def test_list_channels_keeps_6_25_khz_digits(tmp_path, capsys): + """6.25 kHz channels need five decimals (851.00625, not 851.0063).""" + path = tmp_path / "odd.PRS" + _personality_with_channel(path) + assert cmd_list(str(path), "channels") == 0 + assert "851.00625\t851.00625" in capsys.readouterr().out diff --git a/tests/test_cloner_renumber.py b/tests/test_cloner_renumber.py index a560df5..71ab3a3 100644 --- a/tests/test_cloner_renumber.py +++ b/tests/test_cloner_renumber.py @@ -785,3 +785,27 @@ def test_auto_named_department_validates(self): issues = validate_prs(prs) errors = [(s, m) for s, m in issues if s == ERROR] assert len(errors) == 0 + + +class TestCloneNameAndUnitId: + """clone-personality --name sets the name in the CPersonality header + and --unit-id the Home Unit ID of every P25 trunked system.""" + + def _patrol(self): + from quickprs.config_builder import build_from_config + return build_from_config(str(TESTDATA / "example_patrol.ini")) + + def test_name_goes_in_header(self): + from quickprs.record_types import parse_personality_section + clone = clone_personality(self._patrol(), {"name": "CLONED"}) + header = parse_personality_section( + clone.get_section_by_class("CPersonality").raw) + assert header.filename == "CLONED.PRS" + + def test_unit_id_in_every_trunked_system(self): + from test_fleet import _read_home_unit_ids + clone = clone_personality(self._patrol(), {"unit_id": 4242}) + systems = _read_home_unit_ids(clone) + assert systems + for _, uids in systems: + assert uids == [4242, 4242, 4242] diff --git a/tests/test_fleet.py b/tests/test_fleet.py index efddea5..0b6dce4 100644 --- a/tests/test_fleet.py +++ b/tests/test_fleet.py @@ -612,3 +612,36 @@ def test_mixed_p25_and_conv(self, tmp_path): uids = _read_home_unit_ids(prs) assert len(uids) == 1 # only the P25 system assert uids[0][1] == [3001, 3001, 3001] + + +class TestFleetOutputNames: + """Unit names stay inside the output folder, duplicates are reported, + short rows are read, and unit IDs fit 24 bits.""" + + def test_name_cannot_leave_output_dir(self, tmp_path): + units = _write_csv(tmp_path, "unit_id,name\n1001,../escape\n") + out = tmp_path / "out" + results = build_fleet(str(PATROL_INI), units, str(out)) + assert results[0][2], results + assert not (tmp_path / "escape.PRS").exists() + assert (out / "escape.PRS").exists() + + def test_duplicate_names_are_reported(self, tmp_path): + units = _write_csv(tmp_path, + "unit_id,name\n1001,CAR\n1002,CAR\n") + out = tmp_path / "out" + results = build_fleet(str(PATROL_INI), units, str(out)) + assert results[0][2] + assert not results[1][2] + assert "duplicate" in results[1][3] + + def test_short_row_is_read(self, tmp_path): + units = _write_csv(tmp_path, "unit_id,name,password\n1001\n") + parsed = _parse_units_csv(units) + assert parsed[0]["unit_id"] == 1001 + assert parsed[0].get("name", "") == "" + + def test_unit_id_over_24_bits_rejected(self, tmp_path): + units = _write_csv(tmp_path, "unit_id\n16777216\n") + with pytest.raises(ValueError, match="24-bit"): + _parse_units_csv(units) diff --git a/tests/test_reports.py b/tests/test_reports.py index af14f9b..1fd761a 100644 --- a/tests/test_reports.py +++ b/tests/test_reports.py @@ -217,3 +217,27 @@ def test_cli_report_nonexistent_file(self): from quickprs.cli import run_cli result = run_cli(["report", "nonexistent.PRS"]) assert result == 1 + + +def _personality_with_channel(path, short_name="ODD", freq=851.00625, + tx_tone=""): + from quickprs.builder import create_blank_prs + from quickprs.injector import make_conv_set, _safe_add_conv_set + from quickprs.prs_writer import write_prs + prs = create_blank_prs() + _safe_add_conv_set(prs, make_conv_set("ODD", [ + {"short_name": short_name, "tx_freq": freq, "rx_freq": freq, + "tx_tone": tx_tone, "rx_tone": tx_tone}])) + write_prs(prs, str(path), backup=False) + return prs + + +def test_summary_card_escapes_tone_names(tmp_path): + """Tone names come from the file, so the card escapes them like the + full report does.""" + from quickprs.reports import generate_summary_card + prs = _personality_with_channel(tmp_path / "t.PRS", + tx_tone="x") + html = generate_summary_card(prs) + assert "x" not in html + assert "<b>x</b>" in html diff --git a/tests/test_search.py b/tests/test_search.py index 143120b..bec3dde 100644 --- a/tests/test_search.py +++ b/tests/test_search.py @@ -338,3 +338,39 @@ def test_format_count_header(self): ] lines = format_search_results(results, 'freq') assert any("2 match" in line for line in lines) + + +def _personality_with_channel(path, short_name="ODD", freq=851.00625, + tx_tone=""): + from quickprs.builder import create_blank_prs + from quickprs.injector import make_conv_set, _safe_add_conv_set + from quickprs.prs_writer import write_prs + prs = create_blank_prs() + _safe_add_conv_set(prs, make_conv_set("ODD", [ + {"short_name": short_name, "tx_freq": freq, "rx_freq": freq, + "tx_tone": tx_tone, "rx_tone": tx_tone}])) + write_prs(prs, str(path), backup=False) + return prs + + +class TestCmdSearchUnreadable: + """search says which files it could not read, and fails when it + could read none.""" + + def test_unreadable_file_is_reported(self, tmp_path, capsys): + from quickprs.cli import cmd_search + good = tmp_path / "good.PRS" + _personality_with_channel(good) + bad = tmp_path / "bad.PRS" + bad.write_bytes(b"not a personality") + cmd_search([str(good), str(bad)], name="ODD") + captured = capsys.readouterr() + assert "cannot read" in captured.err + assert "bad.PRS" in captured.err + assert "good.PRS" in captured.out + + def test_nothing_readable_fails(self, tmp_path): + from quickprs.cli import cmd_search + bad = tmp_path / "bad.PRS" + bad.write_bytes(b"not a personality") + assert cmd_search([str(bad)], name="ODD") == 1 From 57e97e8cbdd26538d0d1a14a8adecfbdeaf7c274 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Tue, 27 Oct 2026 22:36:44 -0700 Subject: [PATCH 14/14] 1.1.0: docs, changelog and packaging - README: Bluetooth groundwork, accurate feature list (no "100% decoded" claim; the system list is unverified), the RadioReference password, import-paste with its real flags, every CLI command, the corrected interop template. - docs/prs-format.md (the MFC archive rules, with diagrams) and docs/bluetooth.md (finding the radio and recording RPM's sessions). - CHANGELOG 1.1.0; the never-released 1.0.3 notes ship in it. - Version 1.1.0; optional `radio` dependencies (pyserial, bleak); pyserial in requirements.txt. - build.py collects every quickprs module instead of a hand-kept list, bundles pyserial, and leaves out bleak and httpx, which brought the WinRT runtime and rich, pygments, Pillow and numpy into the EXE. - Missing-package messages name the package to install (QuickPRS is not on PyPI, so `pip install quickprs[radio]` could not work). --- CHANGELOG.md | 41 +++++++++++++++- CONTRIBUTING.md | 8 +++- README.md | 39 ++++++++++------ build.py | 60 ++++-------------------- docs/bluetooth.md | 93 +++++++++++++++++++++++++++++++++++++ docs/prs-format.md | 89 +++++++++++++++++++++++++++++++++++ pyproject.toml | 3 +- quickprs/__init__.py | 2 +- quickprs/radio/bluetooth.py | 2 +- quickprs/radio/link.py | 2 +- requirements.txt | 1 + 11 files changed, 269 insertions(+), 71 deletions(-) create mode 100644 docs/bluetooth.md create mode 100644 docs/prs-format.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d2eab0..fe92088 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,13 +2,50 @@ All notable changes to QuickPRS will be documented in this file. -## [1.0.3] - 2026-03-16 +## [1.1.0] - 2026-10-27 + +### Fixed +- **Edits broke the file structure RPM reads.** A .PRS file is an MFC archive: every class and object is numbered as it is written, and every list starts with its count. Adding or removing a talkgroup, channel, set or system left every later class tag and the list counts stale, and MFC's loader, which RPM uses, rejects tags that name the wrong class. QuickPRS now reads a personality into a tree that keeps every byte and writes it back with tags and counts recomputed. All 36 RPM-saved test files re-serialize byte for byte. See [docs/prs-format.md](docs/prs-format.md). +- Saving refuses an edit that breaks a file's archive structure, and `validate` reports stale tags and counts; `repair` fixes files saved by QuickPRS 1.0.x +- `create` built a file whose system count, list counts and WAN object did not match its contents +- Conventional sets after a padded gap were missing from the GUI, CSV export and rebuilds (#1) +- A talkgroup ID of 65535 cut its talkgroup list short +- 800 MHz IDEN tables started at 851.00625 MHz in 12.5 kHz steps, which never lands on an 800 MHz channel; they now start at 851.0125 MHz, and TDMA templates use 12.5 kHz as RPM-saved files do +- Trunk channel TX and RX were reversed in the README, example INIs and CSV templates (RPM stores TX on the uplink, 806 MHz, and RX on the downlink, 851 MHz); validation now warns when a trunk set looks swapped +- `import-paste` paired every pasted frequency with itself +- `import-rr` and `auto-setup` sent the API key as the account password, so they could not log in +- 2 m repeater offsets were reversed (146.61-146.97 MHz outputs take -600 kHz, 147.00-147.39 MHz take +600 kHz) +- Interop template: VTAC11-14 were on the wrong frequencies, UTAC44 does not exist, the 800 MHz channels were on their pre-rebanding frequencies, repeater channels were simplex, and the 700 MHz P25 channels were analog. It now follows the NIFOG: 23 channels with repeater pairs and direct channels, all 800 MHz channels wide (20 kHz, 47 CFR 90.209), 700 MHz left to a P25 conventional set +- The built-in P25 system list's IDs were never verified (the FCC does not publish System IDs or WACNs). PSERN is corrected to 939 and marked verified; the CLI and GUI warn before an unverified system is added +- `create` silently replaced an existing file (it now needs `--force` and keeps a `.bak`), and `import-json` overwrote the .PRS its JSON came from +- `cleanup` reported every trunk and talkgroup set as unused +- Backups of `radio_v2.PRS` were listed, restored and pruned as backups of `radio.PRS` +- `fleet`: unit names could write outside the output folder, duplicate names overwrote each other, short CSV rows crashed, and unit IDs were not checked against 24 bits +- `build` ignored the `[options]` section. Options are now checked like `set-option` (an unknown attribute or a value the radio does not allow is an error), and the lists `export-config` writes for programmable buttons, microphones and the short menu build back into those elements +- The wizard saved the time zone to an attribute the radio does not have; it now sets the radio's time zone and asks again for one RPM does not list +- `clone-personality --name/--unit-id` changed nothing the radio uses +- `set-option` accepted misspelt attributes and values a field does not allow, and wrote nested settings on the parent element; the default options XML is now RPM's own; presets and profiles no longer set attributes the XG-100P does not have +- GUI: crashed on start; the Import Wizard failed every non-talkgroup import; the System Wizard reported failure on success and could add a system twice; undo history carried over to the next file; opening a recent file did not ask about unsaved changes; Delete, F2 and undo acted on the tree while typing; multi-select edits touched talkgroups that were not selected; Health Check crashed; dropped paths were not read as Unicode +- `search` skipped unreadable files without saying so; listings print 6.25 kHz channels with 5 decimals ### Added +- `quickprs radio`: groundwork for reading the radio over Bluetooth. The XG-100P uses Bluetooth Classic (serial port profile), which RPM programs over like the USB cable. `scan` finds paired radios and their COM ports, `probe` listens, `relay` sits between RPM and the radio and logs both directions, and `analyze` summarises a capture and extracts any personality in it. None of them sends bytes of its own to the radio. See [docs/bluetooth.md](docs/bluetooth.md). +- P25 conventional sets: CSV export, CSV import and creation +- `quickprs import-csv`, which detects each CSV's type, so `export-csv` output imports directly +- RadioReference login from `--password` or the `QUICKPRS_RR_*` environment variables, with a hidden password prompt +- `radio` optional dependencies (pyserial, bleak); the standalone EXE includes pyserial + +### Changed +- CLI writes back up an existing output file, not only the input +- The EXE build collects every quickprs module instead of a hand-kept list + +### Also in this release (prepared as 1.0.3, never released) + +#### Added - README: Dedicated RadioReference integration section with auto-setup, paste import, and GUI wizard documentation - README: Updated Quick Start to lead with RadioReference one-command workflow -### Fixed +#### Fixed - Section replacement functions now validate section indices before writing, preventing silent data corruption if expected sections are missing - Added empty set guards to prevent IndexError when trunk, group, or conv sets are unexpectedly empty - NOAA weather channels now correctly set as receive-only (TX disabled) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 28b5d2d..1e33260 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,7 +30,10 @@ Note: Test PRS data files are not included in this repository (gitignored). Test ## Project Structure - `quickprs/` -- Main package (parser, writer, CLI, GUI, validation, etc.) -- `tests/` -- Test suite (26 test files, 3,265+ tests) + - `archive.py` -- The .PRS document model: reads the MFC archive, checks it, and writes it back with class tags and list counts recomputed ([format notes](docs/prs-format.md)) + - `radio/` -- Bluetooth and serial tools for talking to the radio ([notes](docs/bluetooth.md)) +- `docs/` -- Format and Bluetooth notes +- `tests/` -- Test suite (pytest) - `dist/` -- Built executable (gitignored) - `local/` -- Developer scratch files (gitignored) @@ -51,5 +54,6 @@ Note: Test PRS data files are not included in this repository (gitignored). Test ## Code Style - Follow existing code conventions (PEP 8, type hints where practical) -- Add tests for new features +- Add tests for new features, and check that a new test fails when the fix it covers is undone +- Change personalities through `archive.Document` (or the injector helpers built on it) rather than by splicing bytes, so class tags and list counts stay right - Keep CLI help text clear and include usage examples diff --git a/README.md b/README.md index 57becd7..328f103 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). QuickPRS replaces the personality *creation and editing* workflow, not the radio flashing process. +> **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)). ## RadioReference Integration @@ -23,6 +23,8 @@ quickprs auto-setup radio.PRS --sid 8155 --username YOUR_USER --apikey YOUR_KEY quickprs validate radio.PRS ``` +`auto-setup` and `import-rr` log in with your RadioReference username and password plus the API key. The password is asked for when you run them (or comes from `--password` or `QUICKPRS_RR_PASSWORD`; `QUICKPRS_RR_USER` and `QUICKPRS_RR_APIKEY` work for the other two). + This single `auto-setup` command: 1. Fetches the full system from RadioReference (talkgroups, sites, frequencies) 2. Creates the trunk frequency set with all site frequencies @@ -37,11 +39,9 @@ This single `auto-setup` command: No API key? Just copy talkgroup/frequency tables from RadioReference and paste them in: ```bash -# Paste talkgroup data from the website -quickprs import-paste radio.PRS --name PSERN --sysid 892 --tgs-file tgs.txt - -# Or import site/frequency data -quickprs import-paste radio.PRS --name PSERN --sites-file sites.txt +# Paste the talkgroup table, the site/frequency table, or both +quickprs import-paste radio.PRS --name PSERN --sysid 939 --wacn 781824 \ + --tgs-file tgs.txt --freqs-file freqs.txt ``` ### GUI Import Wizard @@ -60,14 +60,17 @@ The GUI includes a dedicated RadioReference import wizard (File > Import Wizard) ## Features -- 100% binary format decoded (49 section types, 27 option sections, 514+ fields) +- Writes personalities the way RPM does: the .PRS is an MFC archive, and every save rebuilds its class tags and list counts ([format notes](docs/prs-format.md)) +- Refuses to save an edit that breaks the archive structure; `repair` fixes files saved by QuickPRS 1.0.x - Create PRS files from scratch or INI config files - **RadioReference integration** — auto-setup P25 systems via SOAP API, web scraping, or paste - Import from scanner formats (CHIRP, Uniden Sentinel, SDRTrunk) -- 45+ CLI commands for scripting and batch processing +- P25 conventional channel sets (CSV export and import) +- 60+ CLI commands for scripting and batch processing - 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 P25 system database (30 major US systems) +- 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`) - JSON export/import for human-editable radio configs - Export to CHIRP CSV, Uniden CSV, SDRTrunk, DSD+, Markdown, INI - Merge, clone, and compare PRS files @@ -84,7 +87,7 @@ The GUI includes a dedicated RadioReference import wizard (File > Import Wizard) - Comprehensive validation against XG-100P hardware limits - File repair and data salvage for damaged PRS files - Lossless binary roundtrip (parse and rewrite produces byte-identical output) -- 5,300+ automated tests +- 5,400+ automated tests ## Quick Start @@ -109,7 +112,7 @@ quickprs validate radio.PRS ```bash quickprs create radio.PRS --name "PATROL" -quickprs inject radio.PRS p25 --name PSERN --sysid 892 --freqs-csv freqs.csv --tgs-csv tgs.csv +quickprs inject radio.PRS p25 --name PSERN --sysid 939 --wacn 781824 --freqs-csv freqs.csv --tgs-csv tgs.csv quickprs inject radio.PRS conv --template murs quickprs inject radio.PRS conv --template noaa quickprs inject radio.PRS conv --template interop @@ -138,6 +141,8 @@ Or use the standalone EXE from [Releases](../../releases) (no Python required). - `darkdetect` — Auto dark mode detection - `windnd` — Drag-and-drop file support (Windows) - `zeep` — RadioReference SOAP API access (requires premium subscription) +- `pyserial` — serial and Bluetooth ports for `quickprs radio` +- `bleak` — BLE device scan (`quickprs radio scan --ble`) ## CLI Commands @@ -168,6 +173,10 @@ Or use the standalone EXE from [Releases](../../releases) (no Python required). | `import-paste` | Import from pasted RadioReference text | | `import-scanner` | Import from CHIRP, Uniden, or SDRTrunk CSV | | `import-json` | Create a PRS from a JSON file | +| `import-csv` | Import talkgroup, trunk, conventional and P25 conventional sets from CSV (the `export-csv` format) | +| `convert` | Convert between PRS, JSON, INI, CSV, CHIRP and Markdown | +| `preset` | Apply named option presets (GPS, covert, quiet, etc.) | +| `favorites` | Bookmark systems, talkgroups, channels and templates | | `systems` | Browse/search/add from built-in P25 system database | | `template-csv` | Generate blank CSV/INI templates for data entry | | `validate` | Validate PRS file against XG-100P hardware limits | @@ -200,6 +209,10 @@ Or use the standalone EXE from [Releases](../../releases) (no Python required). | `export-config` | Export PRS to editable INI config file | | `watch` | File watcher with auto-validation on change | | `cheat-sheet` | Quick reference of common CLI workflows | +| `radio` | Find a paired radio, listen to it, or log RPM talking to it ([docs](docs/bluetooth.md)) | +| `tutorial` | Interactive step-by-step CLI tutorial | +| `demo` | Build an example patrol radio from scratch, non-interactively | +| `about` | Project info and statistics | ## Config File Format @@ -260,7 +273,7 @@ Build with: `quickprs build patrol.ini -o patrol.PRS` | `frs` | 22 | Family Radio Service (462-467 MHz) | | `marine` | 15 | Marine VHF (156-157 MHz) | | `noaa` / `weather` | 7 | NOAA Weather Radio (162 MHz) | -| `interop` | 20 | National Interoperability (NPSPAC) | +| `interop` | 23 | National interoperability (NIFOG): VHF, UHF and 800 MHz calling and tactical channels | | `public_safety` | 10 | Public Safety simplex frequencies | Usage: `quickprs inject file.PRS conv --template murs` @@ -282,7 +295,7 @@ Note: Test PRS data files are not included in this repository. Tests that requir - This tool is an independent project and is NOT affiliated with, endorsed by, or supported by L3Harris Technologies, Harris Corporation, or any radio manufacturer - XG-100P, RPM, and related trademarks belong to their respective owners - Users are responsible for ensuring their radio configurations comply with all applicable FCC regulations and local laws -- The P25 system database contains publicly available information from FCC records +- The built-in P25 system list is a starting point only: its System IDs and WACNs are unverified unless marked, and a wrong one keeps a radio off the system ## License diff --git a/build.py b/build.py index ca275c6..2a114f1 100644 --- a/build.py +++ b/build.py @@ -39,56 +39,16 @@ def build(): "--windowed", "--name", "QuickPRS", "--add-data", f"{ROOT / 'quickprs'}{sep}quickprs", - "--hidden-import", "quickprs", - "--hidden-import", "quickprs.gui", - "--hidden-import", "quickprs.gui.app", - "--hidden-import", "quickprs.gui.personality_view", - "--hidden-import", "quickprs.gui.import_panel", - "--hidden-import", "quickprs.gui.settings", - "--hidden-import", "quickprs.gui.button_config", - "--hidden-import", "quickprs.gui.diff_viewer", - "--hidden-import", "quickprs.gui.hex_viewer", - "--hidden-import", "quickprs.gui.system_wizard", - "--hidden-import", "quickprs.prs_parser", - "--hidden-import", "quickprs.prs_writer", - "--hidden-import", "quickprs.record_types", - "--hidden-import", "quickprs.binary_io", - "--hidden-import", "quickprs.injector", - "--hidden-import", "quickprs.radioreference", - "--hidden-import", "quickprs.validation", - "--hidden-import", "quickprs.comparison", - "--hidden-import", "quickprs.cli", - "--hidden-import", "quickprs.csv_import", - "--hidden-import", "quickprs.csv_export", - "--hidden-import", "quickprs.logger", - "--hidden-import", "quickprs.cache", - "--hidden-import", "quickprs.builder", - "--hidden-import", "quickprs.json_io", - "--hidden-import", "quickprs.templates", - "--hidden-import", "quickprs.config_builder", - "--hidden-import", "quickprs.iden_library", - "--hidden-import", "quickprs.option_maps", - "--hidden-import", "quickprs.option_differ", - "--hidden-import", "quickprs.main", - "--hidden-import", "quickprs.fleet", - "--hidden-import", "quickprs.repair", - "--hidden-import", "quickprs.undo", - "--hidden-import", "quickprs.scanner_import", - "--hidden-import", "quickprs.freq_tools", - "--hidden-import", "quickprs.auto_setup", - "--hidden-import", "quickprs.completions", - "--hidden-import", "quickprs.system_database", - "--hidden-import", "quickprs.zones", - "--hidden-import", "quickprs.export_formats", - "--hidden-import", "quickprs.reports", - "--hidden-import", "quickprs.backup", - "--hidden-import", "quickprs.cleanup", - "--hidden-import", "quickprs.cloner", - "--hidden-import", "quickprs.diff_report", - "--hidden-import", "quickprs.profile_templates", - "--hidden-import", "quickprs.search", - "--hidden-import", "quickprs.wizard", - "--hidden-import", "quickprs.gui.import_wizard", + # Every quickprs module, so new ones need no list to keep + "--collect-submodules", "quickprs", + # pyserial for `quickprs radio` + "--hidden-import", "serial", + "--hidden-import", "serial.tools.list_ports", + # Optional packages that would otherwise come along when installed: + # bleak (BLE scans) brings the WinRT runtime, and httpx (zeep's + # async transport, unused) brings rich, pygments, Pillow and numpy + "--exclude-module", "bleak", + "--exclude-module", "httpx", "--hidden-import", "windnd", "--hidden-import", "sv_ttk", "--hidden-import", "darkdetect", diff --git a/docs/bluetooth.md b/docs/bluetooth.md new file mode 100644 index 0000000..32c150a --- /dev/null +++ b/docs/bluetooth.md @@ -0,0 +1,93 @@ +# Talking to the radio over Bluetooth + +QuickPRS cannot read or program a radio by itself yet. The `quickprs radio` +commands are the groundwork: they find the radio, listen to it, and record +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. + +## Bluetooth Classic, not BLE + +The XG-100P's Bluetooth is Bluetooth Classic with the Serial Port Profile +(SPP). Windows gives a paired radio an outgoing COM port, and RPM's help +("Setting Up A Bluetooth Connection") describes programming the radio over +that port just as over the USB cable: extract (read), write, activate and +remove mission plans. + +## Setup + +1. Install pyserial (the standalone EXE already includes it): + ```bash + pip install pyserial + ``` +2. Pair the radio. On the radio: SETTINGS > BLUETOOTH, set ENABLED to YES, + then PAIRING MGNT > ADD NEW and pick the PC; accept the pass key on both. + Bluetooth must be enabled in the radio's personality + (Options > Bluetooth Settings). +3. Find its COM port: + ```bash + quickprs radio scan # --ble also lists nearby BLE devices (needs bleak) + ``` + +## Listen + +```bash +quickprs radio probe --port COM6 --seconds 15 --log first.jsonl +``` + +Opens the port and prints anything the radio sends. A radio that is off, +out of range or not paired shows up here as a connection timeout. + +## Record an RPM session + +RPM has to talk to the radio through QuickPRS, so give it a virtual port. A +virtual null-modem pair such as com0com (free, open source; installs a +driver) links two COM ports, for example COM20 and COM21. RPM opens one end, +the relay opens the other and the radio's port, and every byte is passed +across and logged: + +```mermaid +flowchart LR + RPM["Harris RPM"] -->|"COM20"| NM["virtual null-modem pair
(com0com)"] + NM -->|"COM21"| RL["quickprs radio relay"] + RL -->|"COM6, Bluetooth SPP"| R["XG-100P"] + RL --> LOG[("read.jsonl")] +``` + +```bash +quickprs radio relay --pc-port COM21 --radio-port COM6 --log read.jsonl --note "RPM extract" +``` + +Then point RPM's connection at COM20 and extract the radio's personality as +usual. The relay also copies RPM's DTR/RTS lines to the radio's port. + +## Look at a capture + +```bash +quickprs radio analyze read.jsonl +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 +file, so treat it as something to compare with the .PRS RPM saved for the +same session, not as a finished file. + +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. + +## 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"] +``` + +Writing comes last and only after reading works and the write session is +understood byte for byte: a bad write can leave a radio unusable. diff --git a/docs/prs-format.md b/docs/prs-format.md new file mode 100644 index 0000000..1c242ef --- /dev/null +++ b/docs/prs-format.md @@ -0,0 +1,89 @@ +# The .PRS file format + +A .PRS personality is the saved state of RPM's document, written with +Microsoft MFC's `CArchive` serialization (RPM's `persdata.dll` links +`mfc100.dll`). QuickPRS reads a file into a tree that keeps every byte +(`quickprs/archive.py`), edits the tree, and writes it back with the +archive's bookkeeping recomputed, so edits keep the structure RPM reads. + +## Two rules every edit has to keep + +**Class and object numbering.** The archive numbers every class and every +object as it writes them, starting at 1 (0 is the null object). The first +object of a class is written as `FF FF`, the class schema (2 bytes), the +name length (2 bytes) and the name. Every later object of that class is the +2-byte tag `0x8000 | class index`. + +**List counts.** A list is a 2-byte count followed by its objects. + +So adding one talkgroup changes the index of every class first written +after it, and with it every later tag, and the count in front of its list. +RPM's loader (`CArchive::ReadObject`) rejects a tag that does not name the +class it expects (`badIndex`, `badClass`) and a class written with another +schema (`badSchema`). + +```mermaid +flowchart LR + A["FF FF, schema, name
first CP25Group
(class gets index n)"] --> B["object data"] + B --> C["0x8000 #124; n
next CP25Group"] + C --> D["object data"] + D --> E["..."] + X["a class or object
inserted earlier"] -.->|"shifts n and every later tag"| C +``` + +QuickPRS 1.0.x copied these tags from the source file, which is right only +while nothing in front of them changes. Since 1.1 it rebuilds them on every +save. + +## Document order + +RPM writes the parts of a personality in this order: + +```mermaid +flowchart TD + P["CPersonality header
fields, radio type list"] --> S["systems list
CConvSystem · CP25TrkSystem · CP25ConvSystem
(P25 trunked systems hold their ECC list)"] + S --> T["trunk sets
CTrunkSet → CTrunkChannel"] + T --> B6["6 bytes"] + B6 --> C["conventional sets
CConvSet → CConvChannel"] + C --> O["options list
CGenRadioOpts, CP25tWanOpts, CPrgrmICall,
CPrgrmPhoneCall, CType99Opts, …"] + O --> F["personality name, user,
band limits, radio type"] + F --> G["group sets
CP25GroupSet → CP25Group"] + G --> PC["P25 conventional sets
CP25ConvSet → CP25ConvChannel"] + PC --> U["a list that is empty in every file seen so far"] + U --> I["IDEN sets
CIdenDataSet → CDefaultIdenElem"] + I --> X["tail: radio options XML, terminator"] +``` + +Trunk channels are stored as RPM shows them: transmit is the site's uplink +(806 MHz on an 800 MHz system) and receive the downlink (851 MHz). + +## What happens on save + +```mermaid +flowchart LR + E["edit"] --> W["walk the archive"] + W -->|"follows"| R["recompute tags and counts"] + R --> OK["write"] + W -->|"no longer follows, but did when loaded"| NO["refuse to write
(UnsafeWriteError)"] + W -->|"never followed (unknown RPM layout)"| PASS["write unchanged,
with a warning"] +``` + +`quickprs repair` rewrites the stale tags and counts in a file saved by +QuickPRS 1.0.x. + +## Not yet confirmed + +These fields are read and written as they are, but their meaning has not +been checked against RPM: + +- **IDEN elements:** QuickPRS reads the first two fields (4 bytes, then 2) + as channel spacing and bandwidth. One RPM-saved table has an element with + base 851.00625 MHz holding 12500 in the first and 6250 in the second; that + base reaches the system's channels (851.0125 MHz and up) only in 6.25 kHz + steps, so the two may be the other way round. One RPM save with a single + IDEN value changed would settle it. +- **Enhanced control channel (ECC) entries:** four numbers per entry; how + they map to RFSS, site and channel has not been confirmed. + +A good way to settle either: change one value in RPM, save, and compare the +two files with `quickprs compare --detail` or `quickprs dump`. diff --git a/pyproject.toml b/pyproject.toml index 3b29462..2d02026 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "quickprs" -version = "1.0.2" +version = "1.1.0" description = "Generate Harris XG-100P personality files without Harris RPM" requires-python = ">=3.8" dependencies = [ @@ -12,6 +12,7 @@ dependencies = [ [project.optional-dependencies] gui = ["sv-ttk>=2.5", "darkdetect>=0.8", "windnd>=1.0.7"] build = ["pyinstaller>=6.0"] +radio = ["pyserial>=3.5", "bleak>=0.22"] [project.scripts] quickprs = "quickprs.cli:run_cli" diff --git a/quickprs/__init__.py b/quickprs/__init__.py index da70d26..3447224 100644 --- a/quickprs/__init__.py +++ b/quickprs/__init__.py @@ -1,3 +1,3 @@ """QuickPRS - Harris RPM Personality File Tool""" -__version__ = "1.0.3" +__version__ = "1.1.0" diff --git a/quickprs/radio/bluetooth.py b/quickprs/radio/bluetooth.py index 31cd359..51f23fc 100644 --- a/quickprs/radio/bluetooth.py +++ b/quickprs/radio/bluetooth.py @@ -124,7 +124,7 @@ def scan_ble(seconds=5.0): except ImportError as e: raise RuntimeError( "BLE scanning needs the 'bleak' package " - "(pip install quickprs[radio])") from e + "(pip install bleak)") from e async def _scan(): found = await BleakScanner.discover(timeout=seconds, diff --git a/quickprs/radio/link.py b/quickprs/radio/link.py index 8c49eb6..41b7f55 100644 --- a/quickprs/radio/link.py +++ b/quickprs/radio/link.py @@ -22,7 +22,7 @@ def open_serial(port, baudrate=115200, timeout=0.2, dtr=False, rts=False): import serial except ImportError as e: raise LinkError("serial ports need the 'pyserial' package " - "(pip install quickprs[radio])") from e + "(pip install pyserial)") from e ser = serial.Serial() ser.port = port ser.baudrate = baudrate diff --git a/requirements.txt b/requirements.txt index bbb5122..37122a0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,4 @@ sv-ttk>=2.5 darkdetect>=0.8 windnd>=1.0.7 pyinstaller>=6.0 +pyserial>=3.5