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 +1597,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 +1704,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 +1717,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 +1733,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
@@ -1768,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
@@ -1884,6 +1920,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 +2001,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 +2061,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 +2168,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 +2664,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..c757163 100644
--- a/quickprs/reports.py
+++ b/quickprs/reports.py
@@ -265,36 +265,23 @@ def _add_systems(parts, prs):
parts.append("| Name | Type | "
"Long Name | Size |
")
- 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("")
@@ -793,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/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/quickprs/templates.py b/quickprs/templates.py
index 12f808b..6fb6a9b 100644
--- a/quickprs/templates.py
+++ b/quickprs/templates.py
@@ -234,87 +234,62 @@ def get_noaa_channels():
'short_name': f'WX {i}',
'tx_freq': freq,
'long_name': f'NOAA Weather {i}',
+ 'tx': False,
})
return 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.8625 MHz, UHF tactical)
- - 8CALL90 (866.0125 MHz, 800 MHz calling)
- - 8TAC91-94 (866.5125-867.5125 MHz, 800 MHz tactical)
- - 7CALL50 (769.24375 MHz, 700 MHz calling)
- - 7TAC51-54 (769.74375-770.74375 MHz, 700 MHz tactical)
-
- All simplex, no CTCSS/DCS tones (interop standard).
+ """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) 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
+ 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 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 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',
+ narrowband=False))
+ return channels
@_register('public_safety')
diff --git a/quickprs/validation.py b/quickprs/validation.py
index 10c228a..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
@@ -1198,6 +1213,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 +1238,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 +1266,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 +1312,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/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/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
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_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(" 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_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_builder.py b/tests/test_builder.py
index a915b6f..f6bf8b2 100644
--- a/tests/test_builder.py
+++ b/tests/test_builder.py
@@ -131,10 +131,24 @@ def test_blank_prs_has_wan_opts():
assert prs.get_section_by_class("CP25tWanOpts") is not None
-def test_blank_prs_has_wan():
- """Blank PRS contains CP25TrkWan section."""
+def test_blank_prs_has_empty_wan_list():
+ """Blank PRS holds CP25tWanOpts with an empty WAN list and no
+ CP25TrkWan object (an object of that class needs entry data)."""
+ from quickprs import archive
prs = create_blank_prs()
- assert prs.get_section_by_class("CP25TrkWan") is not None
+ doc = archive.document_from_prs(prs)
+ wan_opts = doc.option("CP25tWanOpts")
+ assert wan_opts is not None
+ assert wan_opts.lists()[0].items == []
+ assert prs.get_section_by_class("CP25TrkWan") is None
+
+
+def test_blank_prs_archive_consistent():
+ """Every tag and list count in a blank PRS is what RPM expects."""
+ from quickprs import archive
+ prs = create_blank_prs()
+ assert prs.archive_ok is True
+ assert archive.check(prs) == []
def test_blank_prs_has_type99_opts():
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 65b520b..f9c2dad 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."""
@@ -934,7 +942,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."""
@@ -977,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_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_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_config_builder.py b/tests/test_config_builder.py
index 49177b8..1cd698d 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))
@@ -1205,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_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.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_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_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_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_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_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_injection.py b/tests/test_injection.py
index 324b780..df6b79f 100644
--- a/tests/test_injection.py
+++ b/tests/test_injection.py
@@ -840,13 +840,20 @@ def test_remove_system_by_class():
prs = cached_parse_prs(TESTDATA / "claude test.PRS")
original_count = len(prs.sections)
- # Remove CConvSystem
+ from quickprs import archive
+ from quickprs.record_types import list_system_configs
+ before = [r.short_name for r in list_system_configs(prs)]
+
+ # Remove CConvSystem: one system object, the header and config with it
removed = remove_system_by_class(prs, "CConvSystem")
- assert removed >= 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_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_platform_options.py b/tests/test_platform_options.py
new file mode 100644
index 0000000..4d6e39c
--- /dev/null
+++ b/tests/test_platform_options.py
@@ -0,0 +1,74 @@
+"""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("]*>", extract_platform_xml(blank))
+ assert 'micType="INTERNAL" alc="ON"' in mics[0]
+ assert 'micType="EXTERNAL" alc="OFF"' in mics[1]
+ assert "x