From 7d79163c2bd9ad4deddb7ae1e8418f07649bf3ad Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:20:25 -0700 Subject: [PATCH 01/22] Templates: narrowband where the FCC requires it; drop marine channel 70 FRS (all channels, 47 CFR 95.573), GMRS 8-14 (the 467 MHz interstitials, 95.1773), MURS 1-3 (11.25 kHz, 95.2773) and the public safety simplex channels (Part 90 VHF/UHF since 2013, 90.209(b)(5)) were programmed as 25 kHz channels. Marine channel 70 carries DSC only, and voice is not allowed on it. The GMRS docstring called channels 8-14 repeater inputs. --- quickprs/templates.py | 45 +++++++++++++++---------- tests/test_templates.py | 75 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+), 17 deletions(-) diff --git a/quickprs/templates.py b/quickprs/templates.py index 6fb6a9b..fdfa24c 100644 --- a/quickprs/templates.py +++ b/quickprs/templates.py @@ -48,17 +48,17 @@ def get_template_channels(name): def get_murs_channels(): """Return MURS (Multi-Use Radio Service) channel data. - 5 channels, license-free, 2W max. Channels 1-3 are 11.25 kHz - bandwidth, channels 4-5 are 20 kHz bandwidth. + 5 channels, license-free, 2W max. Channels 1-3 are limited to + 11.25 kHz (narrowband), channels 4-5 to 20 kHz (47 CFR 95.2773). FCC Part 95 Subpart J. """ return [ {'short_name': 'MURS 1', 'tx_freq': 151.820, - 'long_name': 'MURS Channel 1'}, + 'long_name': 'MURS Channel 1', 'narrowband': True}, {'short_name': 'MURS 2', 'tx_freq': 151.880, - 'long_name': 'MURS Channel 2'}, + 'long_name': 'MURS Channel 2', 'narrowband': True}, {'short_name': 'MURS 3', 'tx_freq': 151.940, - 'long_name': 'MURS Channel 3'}, + 'long_name': 'MURS Channel 3', 'narrowband': True}, {'short_name': 'MURS 4', 'tx_freq': 154.570, 'long_name': 'MURS Channel 4'}, {'short_name': 'MURS 5', 'tx_freq': 154.600, @@ -70,11 +70,12 @@ def get_murs_channels(): def get_gmrs_channels(): """Return GMRS (General Mobile Radio Service) channel data. - 22 channels per FCC Part 95 Subpart E. - Channels 1-7: 462 MHz simplex (shared with FRS, 5W GMRS / 2W FRS) - Channels 8-14: 467 MHz repeater inputs (0.5W) - Channels 15-22: 462 MHz simplex (GMRS only, 50W) - Repeater outputs for channels 15R-22R on 462 MHz. + 22 simplex channels per FCC Part 95 Subpart E (repeater pairs are + not included): + Channels 1-7: 462 MHz interstitial (shared with FRS, 5W), 20 kHz + Channels 8-14: 467 MHz interstitial (0.5W), 12.5 kHz (narrowband) + Channels 15-22: 462 MHz main channels (50W), 20 kHz + Bandwidths per 47 CFR 95.1773. """ channels = [] @@ -90,7 +91,7 @@ def get_gmrs_channels(): 'long_name': f'GMRS Channel {i}', }) - # Channels 8-14: 467 MHz (FRS/GMRS interstitial, 0.5W) + # Channels 8-14: 467 MHz (FRS/GMRS interstitial, 0.5W, 12.5 kHz) ch8_14_freqs = [ 467.5625, 467.5875, 467.6125, 467.6375, 467.6625, 467.6875, 467.7125, @@ -100,6 +101,7 @@ def get_gmrs_channels(): 'short_name': f'GMRS {i:2d}', 'tx_freq': freq, 'long_name': f'GMRS Channel {i}', + 'narrowband': True, }) # Channels 15-22: 462 MHz (GMRS only, higher power) @@ -125,7 +127,8 @@ def get_frs_channels(): Channels 1-7: 462 MHz (shared with GMRS, 2W) Channels 8-14: 467 MHz (shared with GMRS, 0.5W) Channels 15-22: 462 MHz (2W, shared with GMRS) - All simplex, license-free. + All simplex, license-free, and 12.5 kHz (narrowband) on every + channel (47 CFR 95.573). """ channels = [] @@ -139,6 +142,7 @@ def get_frs_channels(): 'short_name': f'FRS {i:2d}', 'tx_freq': freq, 'long_name': f'FRS Channel {i}', + 'narrowband': True, }) # Channels 8-14: 467 MHz @@ -151,6 +155,7 @@ def get_frs_channels(): 'short_name': f'FRS {i:2d}', 'tx_freq': freq, 'long_name': f'FRS Channel {i}', + 'narrowband': True, }) # Channels 15-22: 462 MHz @@ -163,6 +168,7 @@ def get_frs_channels(): 'short_name': f'FRS {i:2d}', 'tx_freq': freq, 'long_name': f'FRS Channel {i}', + 'narrowband': True, }) return channels @@ -174,7 +180,9 @@ def get_marine_channels(): Common marine channels per ITU-R M.1084 / FCC Part 80. Includes calling/distress (16), secondary calling (9), - and common recreational/commercial channels. + and common recreational/commercial channels. Channel 70 + (156.525 MHz) is left out: it carries digital selective calling + (DSC) only, and voice is not allowed on it. Simplex channels use the same TX/RX frequency. Duplex channels have a 4.6 MHz offset (ship TX on low, coast RX on high). """ @@ -209,8 +217,6 @@ def get_marine_channels(): 'long_name': 'Vessel Traffic'}, {'short_name': 'MAR 14', 'tx_freq': 156.700, 'long_name': 'Vessel Traffic'}, - {'short_name': 'MAR 70', 'tx_freq': 156.525, - 'long_name': 'DSC Calling'}, # Coast Guard {'short_name': 'MAR 22', 'tx_freq': 157.100, 'long_name': 'USCG Liaison'}, @@ -297,9 +303,11 @@ def get_public_safety_channels(): """Return common public safety simplex frequencies. Standard VHF/UHF simplex frequencies used by fire, EMS, - and law enforcement for on-scene operations. All simplex. + and law enforcement for on-scene operations. All simplex and + narrowband: Part 90 stations at 150-174 and 421-512 MHz must use + 12.5 kHz channels since 2013 (47 CFR 90.209(b)(5)). """ - return [ + channels = [ # VHF public safety {'short_name': 'PS VHF1', 'tx_freq': 155.3400, 'long_name': 'PS Simplex 1'}, @@ -323,3 +331,6 @@ def get_public_safety_channels(): {'short_name': 'PS UHF3', 'tx_freq': 453.1375, 'long_name': 'PS UHF Simplex3'}, ] + for ch in channels: + ch['narrowband'] = True + return channels diff --git a/tests/test_templates.py b/tests/test_templates.py index 7e55d86..617a16e 100644 --- a/tests/test_templates.py +++ b/tests/test_templates.py @@ -483,3 +483,78 @@ def test_public_safety_lookup_by_name(self): """get_template_channels('public_safety') returns data.""" channels = get_template_channels('public_safety') assert len(channels) == 10 + + +# ─── Bandwidth the FCC requires ───────────────────────────────────── + + +def _template_channels_in_file(tmp_path, template): + """Inject a template into a blank personality and read its channels + back from the written file.""" + from quickprs.builder import create_blank_prs + from quickprs.cli import cmd_inject_conv + from quickprs.prs_parser import parse_prs + from quickprs.record_types import ( + parse_sets_from_sections, parse_conv_channel_section, + ) + path = tmp_path / "radio.PRS" + path.write_bytes(create_blank_prs().to_bytes()) + assert cmd_inject_conv(str(path), None, template=template) == 0 + prs = parse_prs(str(path)) + sets = parse_sets_from_sections( + prs.get_section_by_class("CConvSet").raw, + prs.get_section_by_class("CConvChannel").raw, + parse_conv_channel_section) + return [s for s in sets if s.name == template.upper()[:8]][0].channels + + +class TestServiceBandwidths: + """Templates mark a channel narrowband where the service's rules cap + it at 12.5 kHz or less.""" + + def test_frs_is_narrowband_on_every_channel(self): + """47 CFR 95.573: FRS occupied bandwidth may not exceed 12.5 kHz.""" + for ch in get_frs_channels(): + assert ch.get('narrowband') is True, ch['short_name'] + + def test_gmrs_467_interstitials_are_narrowband(self): + """47 CFR 95.1773: 12.5 kHz on the 467 MHz interstitial channels + (8-14), 20 kHz on the 462 MHz channels.""" + for ch in get_gmrs_channels(): + interstitial_467 = 467.5625 <= ch['tx_freq'] <= 467.7125 + assert bool(ch.get('narrowband')) is interstitial_467, \ + ch['short_name'] + + def test_murs_151_channels_are_narrowband(self): + """47 CFR 95.2773: 11.25 kHz on 151.820/151.880/151.940 MHz, + 20 kHz on 154.570/154.600 MHz.""" + for ch in get_murs_channels(): + assert bool(ch.get('narrowband')) is (ch['tx_freq'] < 152.0), \ + ch['short_name'] + + def test_public_safety_simplex_is_narrowband(self): + """47 CFR 90.209(b)(5): Part 90 stations at 150-174 and + 421-512 MHz use 12.5 kHz channels since 2013.""" + for ch in get_public_safety_channels(): + assert ch.get('narrowband') is True, ch['short_name'] + + def test_marine_and_noaa_stay_wide(self): + """Marine VHF and NOAA weather use 25 kHz channels.""" + for ch in get_marine_channels() + get_noaa_channels(): + assert not ch.get('narrowband'), ch['short_name'] + + def test_marine_leaves_out_dsc_channel_70(self): + """Channel 70 (156.525 MHz) carries DSC only; voice is not allowed.""" + freqs = {ch['tx_freq'] for ch in get_marine_channels()} + assert 156.525 not in freqs + assert not any(ch['short_name'] == 'MAR 70' + for ch in get_marine_channels()) + + @pytest.mark.parametrize("template, expected", [ + ("frs", [True] * 22), + ("murs", [True, True, True, False, False]), + ]) + def test_bandwidth_reaches_the_written_channels(self, tmp_path, + template, expected): + channels = _template_channels_in_file(tmp_path, template) + assert [ch.narrowband for ch in channels] == expected From 4c63623c617ad8d193a1fc170d983175e04932ec Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:24:22 -0700 Subject: [PATCH 02/22] CHIRP: keep both tones, narrowband, skip and TX off; Uniden takes the RX tone CHIRP's TSQL mode sends and expects cToneFreq, so a channel whose TX and RX tones differ lost its TX tone; an RX-only tone came out as TX and RX, and DCS ignored the RX side. Export now uses Cross mode (CrossMode, RxDtcsCode) for any pair TSQL or DTCS cannot hold, and import reads it. Narrowband channels export as NFM (always FM before), scan off as Skip S and TX off as Duplex off, and import reads all three back. A scanner listens on the receive frequency, so the Uniden export now uses the tone the radio expects there instead of the one it sends. --- quickprs/export_formats.py | 101 +++++++++++++++++++++------------- quickprs/scanner_import.py | 63 ++++++++++++++------- tests/test_export_formats.py | 104 ++++++++++++++++++++++++++++++++++- 3 files changed, 208 insertions(+), 60 deletions(-) diff --git a/quickprs/export_formats.py b/quickprs/export_formats.py index e77849d..f45774a 100644 --- a/quickprs/export_formats.py +++ b/quickprs/export_formats.py @@ -69,34 +69,59 @@ def _filter_sets(sets, names): _CHIRP_COLUMNS = [ "Location", "Name", "Frequency", "Duplex", "Offset", "Tone", - "rToneFreq", "cToneFreq", "DtcsCode", "DtcsPolarity", "Mode", - "TStep", "Skip", "Comment", "URCALL", "RPT1CALL", "RPT2CALL", + "rToneFreq", "cToneFreq", "DtcsCode", "DtcsPolarity", "RxDtcsCode", + "CrossMode", "Mode", "TStep", "Skip", "Comment", "URCALL", + "RPT1CALL", "RPT2CALL", ] -def _tone_to_chirp(tx_tone, rx_tone): - """Convert PRS tone strings to CHIRP Tone/rToneFreq/cToneFreq/DtcsCode. - - Returns: (tone_mode, rtonefreq, ctonefreq, dtcscode) - """ - if not tx_tone and not rx_tone: - return ("", "88.5", "88.5", "023") - - # DCS tones start with "D" - if tx_tone and tx_tone.startswith("D"): - code = tx_tone[1:] - return ("DTCS", "88.5", "88.5", code) +def dcs_parts(tone): + """(code, polarity) of a DCS tone string such as 'D023', 'D023N' or + 'D023I' (inverted): ('023', 'N') or ('023', 'R'). None if not DCS.""" + if not tone or not tone.upper().startswith("D"): + return None + body = tone[1:].upper() + polarity = "N" + if body[-1:] in ("N", "I", "R"): + polarity = "N" if body[-1] == "N" else "R" + body = body[:-1] + if not body.isdigit(): + return None + return body.zfill(3), polarity - if tx_tone and rx_tone: - # Both set = TSQL (carrier squelch with tone) - return ("TSQL", tx_tone, rx_tone, "023") - if tx_tone: - # TX only = Tone (encode only) - return ("Tone", tx_tone, "88.5", "023") +def _tone_to_chirp(tx_tone, rx_tone): + """CHIRP's tone columns for a channel's TX and RX tones. - # RX only (uncommon but possible) - return ("TSQL", rx_tone, rx_tone, "023") + CHIRP's TSQL mode sends and expects cToneFreq, and its DTCS mode uses + DtcsCode both ways, so they only fit a channel whose two tones are + the same. Anything else is Cross mode: CrossMode names the TX and RX + halves, TX uses rToneFreq or DtcsCode, RX cToneFreq or RxDtcsCode. + """ + tx_dcs, rx_dcs = dcs_parts(tx_tone), dcs_parts(rx_tone) + tx_kind = "DTCS" if tx_dcs else ("Tone" if tx_tone else "") + rx_kind = "DTCS" if rx_dcs else ("Tone" if rx_tone else "") + fields = { + "rToneFreq": tx_tone if tx_kind == "Tone" else "88.5", + "cToneFreq": rx_tone if rx_kind == "Tone" else "88.5", + "DtcsCode": tx_dcs[0] if tx_dcs else "023", + "RxDtcsCode": rx_dcs[0] if rx_dcs else "023", + "DtcsPolarity": ((tx_dcs[1] if tx_dcs else "N") + + (rx_dcs[1] if rx_dcs else "N")), + "CrossMode": "Tone->Tone", + } + if not tx_kind and not rx_kind: + fields["Tone"] = "" + elif tx_kind == "Tone" and not rx_kind: + fields["Tone"] = "Tone" + elif tx_kind == rx_kind == "Tone" and tx_tone == rx_tone: + fields["Tone"] = "TSQL" + elif tx_kind == rx_kind == "DTCS" and tx_dcs[0] == rx_dcs[0]: + fields["Tone"] = "DTCS" + else: + fields["Tone"] = "Cross" + fields["CrossMode"] = f"{tx_kind}->{rx_kind}" + return fields def export_chirp_csv(prs, filepath, sets=None): @@ -128,7 +153,10 @@ def export_chirp_csv(prs, filepath, sets=None): rx = ch.rx_freq diff = round(tx - rx, 6) - if abs(diff) < 0.0001: + if not ch.tx: + duplex = "off" # CHIRP: transmit inhibited + offset = "0.000000" + elif abs(diff) < 0.0001: duplex = "" offset = "0.000000" elif diff > 0: @@ -138,23 +166,16 @@ def export_chirp_csv(prs, filepath, sets=None): duplex = "-" offset = f"{abs(diff):.6f}" - tone_mode, rtone, ctone, dtcs = _tone_to_chirp( - ch.tx_tone, ch.rx_tone) - rows.append({ "Location": str(location), "Name": ch.short_name, "Frequency": f"{rx:.6f}", "Duplex": duplex, "Offset": offset, - "Tone": tone_mode, - "rToneFreq": rtone, - "cToneFreq": ctone, - "DtcsCode": dtcs, - "DtcsPolarity": "NN", - "Mode": "FM", + **_tone_to_chirp(ch.tx_tone, ch.rx_tone), + "Mode": "NFM" if ch.narrowband else "FM", "TStep": "5.00", - "Skip": "", + "Skip": "" if ch.scan else "S", "Comment": ch.long_name or f"{cset.name} {ch.short_name}", "URCALL": "", "RPT1CALL": "", @@ -200,20 +221,22 @@ def export_uniden_csv(prs, filepath, sets=None): for cset in conv_sets: for ch in cset.channels: + # The scanner listens on the receive frequency, so it takes the + # tone the radio expects there, not the one it transmits tone_str = "" code_str = "" - if ch.tx_tone: - if ch.tx_tone.startswith("D"): - code_str = ch.tx_tone[1:] - else: - tone_str = ch.tx_tone + dcs = dcs_parts(ch.rx_tone) + if dcs: + code_str = dcs[0] + elif ch.rx_tone: + tone_str = ch.rx_tone rows.append({ "System": cset.name, "Department": cset.name, "Channel": ch.short_name, "Frequency": f"{ch.rx_freq:.4f}", - "Modulation": "NFM", + "Modulation": "NFM" if ch.narrowband else "FM", "Tone": tone_str, "Code": code_str, "Lockout": "Unlocked", diff --git a/quickprs/scanner_import.py b/quickprs/scanner_import.py index f017c43..98ed15a 100644 --- a/quickprs/scanner_import.py +++ b/quickprs/scanner_import.py @@ -133,8 +133,10 @@ def import_chirp_csv(filepath): Location,Name,Frequency,Duplex,Offset,Tone,rToneFreq,cToneFreq, DtcsCode,DtcsPolarity,Mode,TStep,Skip,Comment,... - Duplex: '', '+', '-', 'split', 'off' - Tone: '', 'Tone', 'TSQL', 'DTCS', 'Cross' + Duplex: '', '+', '-', 'split', 'off' (transmit inhibited) + Tone: '', 'Tone', 'TSQL', 'DTCS', 'Cross' (CrossMode, e.g. + 'Tone->DTCS', names the TX and RX halves) + Mode: 'NFM' is a narrowband channel; Skip: 'S' leaves it out of scan Returns list of dicts compatible with make_conv_channel(). """ @@ -179,24 +181,7 @@ def import_chirp_csv(filepath): else: tx_freq = freq # simplex - # Tone handling - tone_mode = row_lower.get('tone', '') - tx_tone = '' - rx_tone = '' - - if tone_mode in ('Tone', 'TSQL'): - rtone = row_lower.get('rtonefreq', '') - ctone = row_lower.get('ctonefreq', '') - if tone_mode == 'Tone': - tx_tone = rtone - elif tone_mode == 'TSQL': - tx_tone = ctone - rx_tone = ctone - elif tone_mode == 'DTCS': - dtcs = row_lower.get('dtcscode', '') - if dtcs: - tx_tone = f"D{dtcs}" - rx_tone = f"D{dtcs}" + tx_tone, rx_tone = _chirp_tones(row_lower) # Comment as long name comment = row_lower.get('comment', '') @@ -210,11 +195,49 @@ def import_chirp_csv(filepath): 'rx_tone': rx_tone, 'long_name': long_name[:16].upper(), 'system_name': '', + 'tx': duplex.lower() != 'off', + 'scan': row_lower.get('skip', '').upper() != 'S', + 'narrowband': row_lower.get('mode', '').upper() == 'NFM', }) return channels +def _chirp_dcs(code, polarity): + """QuickPRS DCS tone string for a CHIRP code and polarity ('N'/'R').""" + code = code.strip() + if not code.isdigit(): + return '' + return f"D{code.zfill(3)}" + ("I" if polarity == "R" else "") + + +def _chirp_tones(row): + """(tx_tone, rx_tone) from a CHIRP row (keys lowercased). + + TSQL uses cToneFreq both ways and DTCS uses DtcsCode both ways; in + Cross mode TX takes rToneFreq or DtcsCode, RX cToneFreq or RxDtcsCode. + """ + mode = row.get('tone', '') + rtone = row.get('rtonefreq', '') + ctone = row.get('ctonefreq', '') + dtcs = row.get('dtcscode', '') + rx_dtcs = row.get('rxdtcscode', '') or dtcs + pol = (row.get('dtcspolarity', '') or 'NN').upper().ljust(2, 'N') + if mode == 'Tone': + return rtone, '' + if mode == 'TSQL': + return ctone, ctone + if mode == 'DTCS': + return _chirp_dcs(dtcs, pol[0]), _chirp_dcs(dtcs, pol[1]) + if mode == 'Cross': + tx_part, _, rx_part = (row.get('crossmode', '') + or 'Tone->Tone').partition('->') + tx = {'Tone': rtone, 'DTCS': _chirp_dcs(dtcs, pol[0])} + rx = {'Tone': ctone, 'DTCS': _chirp_dcs(rx_dtcs, pol[1])} + return tx.get(tx_part, ''), rx.get(rx_part, '') + return '', '' + + def import_sdrtrunk_csv(filepath): """Import channels from SDRTrunk CSV export. diff --git a/tests/test_export_formats.py b/tests/test_export_formats.py index 06e4d2d..beb91c4 100644 --- a/tests/test_export_formats.py +++ b/tests/test_export_formats.py @@ -281,6 +281,9 @@ def test_uniden_export_frequency(self, tmp_path): assert abs(float(noaa['Frequency']) - 162.55) < 0.001 def test_uniden_export_tone(self, tmp_path): + """A scanner listens on the receive frequency, so it gets the tone + the radio expects there: none for RPT IN (it only sends 100.0 to + the repeater), 100.0 for SIMPLEX.""" prs_file = _create_prs_with_conv(tmp_path) prs = parse_prs(prs_file) out = tmp_path / "uniden.csv" @@ -290,7 +293,9 @@ def test_uniden_export_tone(self, tmp_path): reader = csv.DictReader(f) rows = list(reader) rpt = [r for r in rows if r['Channel'] == 'RPT IN'][0] - assert rpt['Tone'] == '100.0' + assert rpt['Tone'] == '' + simplex = [r for r in rows if r['Channel'] == 'SIMPLEX'][0] + assert simplex['Tone'] == '100.0' def test_uniden_export_dcs_code(self, tmp_path): """DCS tone should go in Code column, not Tone.""" @@ -995,3 +1000,100 @@ def test_dsd_export_paws(self, tmp_path): out = tmp_path / "freqs.txt" count = export_dsd_freqs(prs, out) assert count >= 0 + + +# ─── CHIRP tones, mode, skip and TX off ────────────────────────────── + +_TONE_CASES = [ + # (tx_tone, rx_tone, CHIRP Tone, CrossMode or None, {column: value}) + ("", "", "", None, {}), + ("100.0", "", "Tone", None, {"rToneFreq": "100.0"}), + ("100.0", "100.0", "TSQL", None, {"cToneFreq": "100.0"}), + ("100.0", "123.0", "Cross", "Tone->Tone", + {"rToneFreq": "100.0", "cToneFreq": "123.0"}), + ("", "123.0", "Cross", "->Tone", {"cToneFreq": "123.0"}), + ("D023", "D023", "DTCS", None, {"DtcsCode": "023"}), + ("D023", "", "Cross", "DTCS->", {"DtcsCode": "023"}), + ("", "D754", "Cross", "->DTCS", {"RxDtcsCode": "754"}), + ("D023", "D754", "Cross", "DTCS->DTCS", + {"DtcsCode": "023", "RxDtcsCode": "754"}), + ("100.0", "D754", "Cross", "Tone->DTCS", + {"rToneFreq": "100.0", "RxDtcsCode": "754"}), + ("D023", "123.0", "Cross", "DTCS->Tone", + {"DtcsCode": "023", "cToneFreq": "123.0"}), + ("D023I", "D023", "DTCS", None, {"DtcsCode": "023", + "DtcsPolarity": "RN"}), +] + + +def _chirp_rows(tmp_path, channels): + """Write channels to a personality, export CHIRP, return the rows and + the CSV path.""" + from quickprs.builder import create_blank_prs + from quickprs.injector import add_conv_set, make_conv_set + prs = create_blank_prs() + add_conv_set(prs, make_conv_set("CHIRP", channels)) + out = tmp_path / "chirp.csv" + export_chirp_csv(prs, out, sets=["CHIRP"]) + with open(out, newline="") as f: + return list(csv.DictReader(f)), out + + +def _tone_channels(): + return [{"short_name": f"T{i}", "tx_freq": 146.52, "rx_freq": 146.52, + "tx_tone": tx, "rx_tone": rx} + for i, (tx, rx, *_ ) in enumerate(_TONE_CASES)] + + +class TestChirpTones: + """CHIRP's TSQL and DTCS modes use one tone both ways; a channel whose + TX and RX tones differ needs Cross mode, or its TX tone is lost.""" + + @pytest.mark.parametrize("i", range(len(_TONE_CASES))) + def test_export_columns(self, tmp_path, i): + rows, _ = _chirp_rows(tmp_path, _tone_channels()) + tx, rx, mode, cross, columns = _TONE_CASES[i] + row = rows[i] + assert row["Tone"] == mode, (tx, rx) + if cross: + assert row["CrossMode"] == cross + for column, value in columns.items(): + assert row[column] == value, (tx, rx, column) + + def test_tones_survive_export_and_import(self, tmp_path): + _, out = _chirp_rows(tmp_path, _tone_channels()) + back = import_chirp_csv(out) + assert [(c["tx_tone"], c["rx_tone"]) for c in back] == [(tx, rx) for tx, rx, *_ in _TONE_CASES] + + +class TestChirpChannelFlags: + """Narrowband, scan and TX-off reach CHIRP's Mode, Skip and Duplex + columns and come back on import.""" + + CHANNELS = [ + {"short_name": "WIDE", "tx_freq": 146.52, "narrowband": False}, + {"short_name": "NARROW", "tx_freq": 151.82, "narrowband": True}, + {"short_name": "NOSCAN", "tx_freq": 151.88, "scan": False}, + {"short_name": "RXONLY", "tx_freq": 162.55, "tx": False}, + ] + + def test_export(self, tmp_path): + rows, _ = _chirp_rows(tmp_path, self.CHANNELS) + by_name = {r["Name"]: r for r in rows} + assert by_name["WIDE"]["Mode"] == "FM" + assert by_name["NARROW"]["Mode"] == "NFM" + assert by_name["NOSCAN"]["Skip"] == "S" + assert by_name["WIDE"]["Skip"] == "" + assert by_name["RXONLY"]["Duplex"] == "off" + assert by_name["WIDE"]["Duplex"] == "" + + def test_round_trip(self, tmp_path): + _, out = _chirp_rows(tmp_path, self.CHANNELS) + back = {c["short_name"]: c for c in import_chirp_csv(out)} + assert back["NARROW"]["narrowband"] is True + assert back["WIDE"]["narrowband"] is False + assert back["NOSCAN"]["scan"] is False + assert back["WIDE"]["scan"] is True + assert back["RXONLY"]["tx"] is False + assert back["WIDE"]["tx"] is True + From 8ae949c196c10242a444aaa48a2097c70979d6a2 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:29:30 -0700 Subject: [PATCH 03/22] RadioReference conventional channels: read DPL and NAC, honor the mode The Tone column parser read '754 DPL' as tone 754 and a P25 NAC ('293 NAC') as tone 293, and every channel went into an analog set as wide FM whatever its mode. Now DPL codes become DCS tones, NACs are kept, FMN channels are narrowband, P25 channels go to a P25 conventional set with their NACs, and modes neither set carries (DMR, NXDN, AM...) are left out and counted. Both GUI importers use one injection path. --- quickprs/gui/import_panel.py | 25 +++--- quickprs/gui/import_wizard.py | 25 +++--- quickprs/radioreference.py | 158 +++++++++++++++++++++++++++------- tests/test_radioreference.py | 93 ++++++++++++++++++++ 4 files changed, 240 insertions(+), 61 deletions(-) diff --git a/quickprs/gui/import_panel.py b/quickprs/gui/import_panel.py index f7e8a84..7e12b98 100644 --- a/quickprs/gui/import_panel.py +++ b/quickprs/gui/import_panel.py @@ -23,7 +23,7 @@ parse_rr_url, build_injection_data, parse_pasted_talkgroups, parse_pasted_frequencies, parse_full_page, parse_pasted_conv_channels, - conv_channels_to_set_data, + add_rr_conv_channels, make_short_name, make_long_name, make_set_name, calculate_tx_freq, build_standard_iden_entries, build_ecc_from_sites, @@ -1851,20 +1851,13 @@ def _paste_inject(self): ) # Inject conventional system if we have conv channels - conv_count = 0 + conv_count = p25_conv_count = 0 + skipped_conv = [] if selected_conv: - conv_data = conv_channels_to_set_data(selected_conv) - conv_set = make_conv_set(set_name, conv_data) - conv_long = (self.paste_system.name or set_name)[:16] - conv_config = ConvSystemConfig( - system_name=set_name, - long_name=conv_long.upper(), - conv_set_name=set_name, - ) - add_conv_system( - self.app.prs, conv_config, - conv_set=conv_set) - conv_count = len(conv_data) + conv_count, p25_conv_count, skipped_conv = ( + add_rr_conv_channels( + self.app.prs, set_name, + self.paste_system.name or set_name, selected_conv)) self.app.mark_modified() self.app.personality_view.refresh() @@ -1884,6 +1877,10 @@ def _paste_inject(self): parts.append(f"{ecc_count} ECC") if conv_count: parts.append(f"{conv_count} conv ch") + if p25_conv_count: + parts.append(f"{p25_conv_count} P25 conv ch") + if skipped_conv: + parts.append(f"{len(skipped_conv)} skipped (mode)") summary = f"Injected '{set_name}': " + ", ".join(parts) self.app.status_set(summary) diff --git a/quickprs/gui/import_wizard.py b/quickprs/gui/import_wizard.py index 60207a0..558a632 100644 --- a/quickprs/gui/import_wizard.py +++ b/quickprs/gui/import_wizard.py @@ -873,21 +873,16 @@ 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.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) + # parse_pasted_conv_channels returns ConvChannelData; + # P25 channels go to a P25 conventional set, and modes + # neither set carries (DMR, NXDN, AM...) are left out + from ..radioreference import add_rr_conv_channels + _, _, skipped = add_rr_conv_channels( + self.app.prs, set_name, set_name, self._clip_data) + if skipped: + messagebox.showinfo( + "Import", f"{len(skipped)} channel(s) left out: " + "their mode is not analog FM or P25.", parent=self) self.app.personality_view.refresh() self.app.mark_modified() diff --git a/quickprs/radioreference.py b/quickprs/radioreference.py index c3da9d6..d7827e0 100644 --- a/quickprs/radioreference.py +++ b/quickprs/radioreference.py @@ -1201,6 +1201,31 @@ class ConvChannelData: description: str = "" # description/notes tx_freq: float = 0.0 # TX freq (0 = same as freq / simplex) tx_tone: str = "" # TX tone + nac: int = -1 # P25 network access code (-1 = none given) + + +def parse_rr_tone(text): + """Read RadioReference's Tone column. + + Returns ('ctcss', '136.5'), ('dcs', 'D023'), ('nac', 0x293) or + (None, '') for '136.5 PL', '023 DPL' or 'D023 N', '293 NAC' or + 'NAC 293', and 'CSQ' (carrier squelch) or anything unreadable. + """ + from .freq_tools import validate_ctcss_tone + t = text.strip().upper() + m = re.search(r'NAC\s*\$?([0-9A-F]{1,3})\b|\$?\b([0-9A-F]{1,3})\s*NAC\b', + t) + if m: + return 'nac', int(m.group(1) or m.group(2), 16) + m = re.search(r'\bD?(\d{3})\s*(?:DPL|DCS)\b|\bDCS\s*(\d{3})\b' + r'|\bD(\d{3})(?:\s*([NI]))?\b', t) + if m: + code = m.group(1) or m.group(2) or m.group(3) + return 'dcs', f"D{code}" + ("I" if m.group(4) == "I" else "") + m = re.search(r'\b(\d{2,3}\.\d)\b', t) + if m and validate_ctcss_tone(m.group(1)): + return 'ctcss', m.group(1) + return None, '' def parse_pasted_conv_channels(text): @@ -1316,11 +1341,11 @@ def _parse_conv_line(line, col_map): elif col == 'description': ch.description = val elif col == 'tone': - # Parse tone: "136.5 PL" -> "136.5", "D023 N" -> "D023" - tone_match = re.match( - r'([\d.]+)\s*(?:PL)?|(D\d{3})\s*(?:N)?', val) - if tone_match: - ch.tone = tone_match.group(1) or tone_match.group(2) + kind, tone = parse_rr_tone(val) + if kind == 'nac': + ch.nac = tone + elif kind: + ch.tone = tone elif col == 'mode': ch.mode = val elif col == 'input': @@ -1346,10 +1371,11 @@ def _parse_conv_line(line, col_map): # Try to extract tone from second part if len(parts) >= 2: - tone_match = re.match( - r'^([\d.]+)\s*(?:PL)?$|^(D\d{3})\s*(?:N)?$', parts[1]) - if tone_match: - ch.tone = tone_match.group(1) or tone_match.group(2) + kind, tone = parse_rr_tone(parts[1]) + if kind == 'nac': + ch.nac = tone + elif kind: + ch.tone = tone else: ch.name = parts[1] @@ -1362,44 +1388,112 @@ def _parse_conv_line(line, col_map): return ch +# RadioReference modes an analog conventional channel can carry; a +# channel with no mode given is taken as analog unless it has a NAC +ANALOG_MODES = {"", "FM", "FMN", "NFM"} +NARROW_MODES = {"FMN", "NFM"} + + +def conv_channel_kind(ch): + """'analog', 'p25' or None (a mode the XG-100P's conventional sets do + not carry: DMR, NXDN, AM, telemetry and the like).""" + mode = (ch.mode or "").strip().upper() + if mode.startswith("P25") or (not mode and ch.nac >= 0): + return "p25" + if mode in ANALOG_MODES: + return "analog" + return None + + +def _conv_names(ch): + """(short_name, long_name) from a channel's name, description or + frequency.""" + short = ch.name[:8].upper() if ch.name else f"{ch.freq:.4f}"[:8] + if ch.description: + long = ch.description[:16].upper() + elif ch.name: + long = ch.name[:16].upper() + else: + long = short + return short, long + + def conv_channels_to_set_data(channels): - """Convert ConvChannelData list to dicts for make_conv_set(). + """Convert the analog channels of a ConvChannelData list to dicts for + make_conv_set(); P25 and other digital channels are left out (see + p25_conv_channels_to_set_data and conv_channel_kind). Generates short_name (8-char) and long_name (16-char) from the channel data. If no name is available, generates from frequency. - Args: - channels: list of ConvChannelData objects - Returns: list of dicts with keys: short_name, tx_freq, rx_freq, tx_tone, - rx_tone, long_name + rx_tone, long_name, narrowband """ result = [] for ch in channels: - # Generate names from available data - if ch.name: - short = ch.name[:8].upper() - else: - # Format freq as name: "155.7600" or "462.562" - short = f"{ch.freq:.4f}"[:8] - - if ch.description: - long = ch.description[:16].upper() - elif ch.name: - long = ch.name[:16].upper() - else: - long = short + if conv_channel_kind(ch) != "analog": + continue + short, long = _conv_names(ch) + result.append({ + 'short_name': short, + # TX freq: explicit input frequency, else simplex + 'tx_freq': ch.tx_freq if ch.tx_freq > 0 else ch.freq, + 'rx_freq': ch.freq, + 'tx_tone': ch.tx_tone or ch.tone, + 'rx_tone': ch.tone, + 'long_name': long, + 'narrowband': (ch.mode or "").strip().upper() in NARROW_MODES, + }) + return result - # TX freq: use explicit tx_freq if set, else same as RX (simplex) - tx_freq = ch.tx_freq if ch.tx_freq > 0 else ch.freq +def p25_conv_channels_to_set_data(channels): + """Dicts for make_p25_conv_set() from the P25 channels of a + ConvChannelData list (NAC 293, the P25 default, when none is given).""" + result = [] + for ch in channels: + if conv_channel_kind(ch) != "p25": + continue + short, long = _conv_names(ch) + nac = ch.nac if ch.nac >= 0 else 0x293 result.append({ 'short_name': short, - 'tx_freq': tx_freq, + 'tx_freq': ch.tx_freq if ch.tx_freq > 0 else ch.freq, 'rx_freq': ch.freq, - 'tx_tone': ch.tone, - 'rx_tone': ch.tone, # same tone for TX and RX by default + 'nac_tx': nac, + 'nac_rx': nac, 'long_name': long, }) return result + + +def add_rr_conv_channels(prs, set_name, long_name, channels): + """Add pasted RadioReference conventional channels to a personality: + analog ones as a conventional system and set named set_name, P25 ones + as a P25 conventional system and set (set_name with P25 at the end). + + Returns (analog_count, p25_count, skipped) where skipped lists the + channels whose mode neither can carry. + """ + from .injector import (add_conv_system, add_p25_conv_set, + add_p25_conv_system, make_conv_set, + make_p25_conv_set) + from .record_types import ConvSystemConfig, P25ConvSystemConfig + analog = conv_channels_to_set_data(channels) + p25 = p25_conv_channels_to_set_data(channels) + skipped = [ch for ch in channels if conv_channel_kind(ch) is None] + set_name = set_name[:8] + long_name = long_name[:16].upper() + if analog: + add_conv_system(prs, ConvSystemConfig( + system_name=set_name, long_name=long_name, + conv_set_name=set_name), + conv_set=make_conv_set(set_name, analog)) + if p25: + p25_name = f"{set_name[:5]}P25" + add_p25_conv_set(prs, make_p25_conv_set(p25_name, p25)) + add_p25_conv_system(prs, P25ConvSystemConfig( + system_name=p25_name, long_name=long_name, + conv_set_name=p25_name)) + return len(analog), len(p25), skipped diff --git a/tests/test_radioreference.py b/tests/test_radioreference.py index 4743a38..daab60a 100644 --- a/tests/test_radioreference.py +++ b/tests/test_radioreference.py @@ -1603,3 +1603,96 @@ def main(): if __name__ == "__main__": sys.exit(main()) + + +# ─── Tone column formats and channel modes ─────────────────────────── + +import pytest # noqa: E402 + +from quickprs.radioreference import ( # noqa: E402 + parse_rr_tone, p25_conv_channels_to_set_data, add_rr_conv_channels, + conv_channel_kind, +) + + +@pytest.mark.parametrize("text, expected", [ + ("136.5 PL", ("ctcss", "136.5")), + ("67.0", ("ctcss", "67.0")), + ("023 DPL", ("dcs", "D023")), + ("754 DPL", ("dcs", "D754")), + ("D023 N", ("dcs", "D023")), + ("D023 I", ("dcs", "D023I")), + ("293 NAC", ("nac", 0x293)), + ("NAC 3AB", ("nac", 0x3AB)), + ("CSQ", (None, "")), + ("", (None, "")), + ("999.9 PL", (None, "")), # not a CTCSS tone +]) +def test_parse_rr_tone(text, expected): + """A DPL code or a P25 NAC is not a CTCSS tone (754 DPL used to come + out as tone '754', 293 NAC as tone '293').""" + assert parse_rr_tone(text) == expected + + +_MIXED = """Frequency License Type Tone Alpha Tag Description Mode Tag +155.76000 KQD949 BM 136.5 PL LE D1 Law Dispatch FMN Law Dispatch +155.01000 KQD949 BM 754 DPL FIRE D1 Fire Dispatch FM Fire Dispatch +154.43000 KQD949 BM 293 NAC PD TAC Police Tac P25 Law Tac +154.83000 KQD949 BM CC 1 PW OPS Public Works DMR Public Works +151.07000 KQD949 BM F7E NAC SO ENC Sheriff Secure P25E Law Tac +""" + + +class TestConvChannelModes: + """RR's Mode column decides which set a channel can go in: analog FM + (FMN is narrowband), P25 conventional, or neither.""" + + def test_tones_and_nacs(self): + chans = parse_pasted_conv_channels(_MIXED) + assert [c.tone for c in chans] == ["136.5", "D754", "", "", ""] + assert [c.nac for c in chans] == [-1, -1, 0x293, -1, 0xF7E] + + def test_kinds(self): + chans = parse_pasted_conv_channels(_MIXED) + assert [conv_channel_kind(c) for c in chans] == \ + ["analog", "analog", "p25", None, "p25"] + + def test_analog_set_data(self): + data = conv_channels_to_set_data(parse_pasted_conv_channels(_MIXED)) + assert [d['short_name'] for d in data] == ["LE D1", "FIRE D1"] + assert [d['narrowband'] for d in data] == [True, False] + assert data[1]['tx_tone'] == data[1]['rx_tone'] == "D754" + + def test_p25_set_data(self): + data = p25_conv_channels_to_set_data( + parse_pasted_conv_channels(_MIXED)) + assert [(d['short_name'], d['nac_tx'], d['nac_rx']) for d in data] \ + == [("PD TAC", 0x293, 0x293), ("SO ENC", 0xF7E, 0xF7E)] + + def test_nac_without_mode_is_p25(self): + ch = ConvChannelData(freq=155.0, nac=0x293) + assert conv_channel_kind(ch) == "p25" + + def test_added_to_a_personality(self): + from quickprs import archive, injector + from quickprs.builder import create_blank_prs + from quickprs.prs_parser import parse_prs_bytes + prs = create_blank_prs() + analog, p25, skipped = add_rr_conv_channels( + prs, "COUNTY", "County Conv", parse_pasted_conv_channels(_MIXED)) + assert (analog, p25) == (2, 2) + assert [c.name for c in skipped] == ["PW OPS"] + back = parse_prs_bytes(prs.to_bytes()) + from quickprs.record_types import ( + parse_sets_from_sections, parse_conv_channel_section) + conv = {s.name: s for s in parse_sets_from_sections( + back.get_section_by_class("CConvSet").raw, + back.get_section_by_class("CConvChannel").raw, + parse_conv_channel_section)} + assert [c.short_name for c in conv["COUNTY"].channels] == \ + ["LE D1", "FIRE D1"] + p25_sets = {s.name: s for s in injector.get_p25_conv_sets(back)} + assert [(c.short_name, c.nac_tx) for c in + p25_sets["COUNTP25"].channels] == \ + [("PD TAC", 0x293), ("SO ENC", 0xF7E)] + assert archive.check(back) == [] From 16253564ef9e0627fc05cfd2db3d4ad887ad7606 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 09:34:14 -0700 Subject: [PATCH 04/22] compare: report changes inside sets, systems and options compare matched conventional sets by channel count, talkgroups by ID and trunk channels by receive frequency only, and never looked at P25 conventional sets, system settings or radio options, so a changed frequency, tone, name, flag, NAC or system ID came out as 'Files are identical' with exit code 0. Items are now matched by key and compared field by field (the change line names the item and the fields), P25 conventional sets are compared, and the two archive trees (data without tags or counts) are compared so anything else that differs is reported. --- quickprs/comparison.py | 241 +++++++++++++++++++++++++++++----- tests/test_compare_changes.py | 103 +++++++++++++++ 2 files changed, 309 insertions(+), 35 deletions(-) create mode 100644 tests/test_compare_changes.py diff --git a/quickprs/comparison.py b/quickprs/comparison.py index b339e6d..0dc9489 100644 --- a/quickprs/comparison.py +++ b/quickprs/comparison.py @@ -1,9 +1,13 @@ """PRS file comparison — diff two personality files at a semantic level. -Compares systems, group sets, trunk sets, IDEN sets, and conv sets between -two parsed PRS files. Produces a structured list of differences. +Compares systems, group sets, trunk sets, IDEN sets, conv sets and P25 +conv sets between two parsed PRS files, item by item, then compares the +two archive trees so that a difference in anything else (system settings, +radio options, personality fields) is reported too. Produces a +structured list of differences. """ +import dataclasses import logging from .prs_parser import parse_prs @@ -13,6 +17,7 @@ from .record_types import ( parse_group_section, parse_trunk_channel_section, parse_conv_channel_section, parse_iden_section, + parse_p25_conv_channel_section, parse_system_short_name, parse_system_long_name, parse_system_set_refs, is_system_config_data, @@ -37,8 +42,10 @@ def compare_prs(prs_a, prs_b): diffs.extend(_compare_group_sets(prs_a, prs_b)) diffs.extend(_compare_trunk_sets(prs_a, prs_b)) diffs.extend(_compare_conv_sets(prs_a, prs_b)) + diffs.extend(_compare_p25_conv_sets(prs_a, prs_b)) diffs.extend(_compare_iden_sets(prs_a, prs_b)) diffs.extend(_compare_sections(prs_a, prs_b)) + diffs.extend(_compare_documents(prs_a, prs_b, diffs)) diffs.extend(_compare_size(prs_a, prs_b)) return diffs @@ -185,45 +192,115 @@ def _compare_set_type(prs_a, prs_b, label, data_cls, set_cls, return diffs -def _diff_groups(gs_a, gs_b): - """Detail diff for group sets — compares talkgroup IDs.""" - ids_a = {g.group_id for g in gs_a.groups} - ids_b = {g.group_id for g in gs_b.groups} - added, removed = ids_b - ids_a, ids_a - ids_b - if added or removed: - parts = [] - if added: - parts.append(f"+{len(added)} TGs") - if removed: - parts.append(f"-{len(removed)} TGs") - return (f"{len(gs_a.groups)}->{len(gs_b.groups)} " - f"({', '.join(parts)})") - return None - - -def _diff_trunks(ts_a, ts_b): - """Detail diff for trunk sets — compares frequencies.""" - freqs_a = {(round(c.rx_freq, 5),) for c in ts_a.channels} - freqs_b = {(round(c.rx_freq, 5),) for c in ts_b.channels} - added, removed = freqs_b - freqs_a, freqs_a - freqs_b - if added or removed: +# Set fields that hold archive bookkeeping (class tags, and bytes that +# belong to the section rather than to the set), not settings +_BOOKKEEPING = frozenset({"separator", "set_marker", "trailing_bytes", + "trailing_uint16", "gap_bytes"}) + +# How many names a change line lists before "and N more" +_SHOW = 3 + + +def _changed_fields(a, b, skip=frozenset()): + """Names of the dataclass fields that differ between a and b; private + fields (undecoded flag bytes) are reported as "other flags".""" + names = [f.name for f in dataclasses.fields(a) + if f.name not in skip and getattr(a, f.name) != getattr(b, f.name)] + shown = [n for n in names if not n.startswith("_")] + if len(shown) < len(names): + shown.append("other flags") + return shown + + +def _listed(names): + names = list(names) + text = ", ".join(names[:_SHOW]) + if len(names) > _SHOW: + text += f" and {len(names) - _SHOW} more" + return text + + +def _diff_items(items_a, items_b, key, label, noun): + """Describe how two item lists differ, or None when they are equal. + + Items are matched by key (a talkgroup ID, a channel name ...); a + matched item whose fields differ is a change, listed with the fields + that changed. + """ + if items_a == items_b: + return None + map_a, map_b = {}, {} + for item in items_a: + map_a.setdefault(key(item), item) + for item in items_b: + map_b.setdefault(key(item), item) + added = [label(map_b[k]) for k in map_b if k not in map_a] + removed = [label(map_a[k]) for k in map_a if k not in map_b] + changed = [f"{label(map_b[k])} ({', '.join(_changed_fields(map_a[k], map_b[k]))})" + for k in map_a if k in map_b and map_a[k] != map_b[k]] + parts = [] + if len(items_a) != len(items_b): + parts.append(f"{len(items_a)}->{len(items_b)} {noun}") + if added: + parts.append(f"+{len(added)}: {_listed(added)}") + if removed: + parts.append(f"-{len(removed)}: {_listed(removed)}") + if changed: + parts.append(f"changed {len(changed)}: {_listed(changed)}") + if not parts: + parts.append(f"{noun} reordered" if len(map_a) == len(items_a) + else f"{noun} changed") + return "; ".join(parts) + + +def _diff_sets(items_attr, key, label, noun): + """A diff_fn for _compare_set_type: the set's own fields, then its + items.""" + def diff(set_a, set_b): parts = [] - if added: - parts.append(f"+{len(added)} freqs") - if removed: - parts.append(f"-{len(removed)} freqs") - return (f"{len(ts_a.channels)}->{len(ts_b.channels)} " - f"({', '.join(parts)})") - return None + fields = _changed_fields(set_a, set_b, + skip=_BOOKKEEPING | {items_attr}) + if fields: + parts.append("set fields: " + ", ".join(fields)) + items = _diff_items(getattr(set_a, items_attr), + getattr(set_b, items_attr), key, label, noun) + if items: + parts.append(items) + return "; ".join(parts) or None + return diff + + +_diff_groups = _diff_sets( + "groups", lambda g: g.group_id, + lambda g: f"{g.group_id} {g.group_name.strip()}", "talkgroups") + +_diff_trunks = _diff_sets( + "channels", lambda c: (round(c.tx_freq, 5), round(c.rx_freq, 5)), + lambda c: f"{c.tx_freq:.5f}/{c.rx_freq:.5f}", "freqs") + +_diff_convs = _diff_sets( + "channels", lambda c: c.short_name, + lambda c: c.short_name.strip() or "(unnamed)", "channels") def _diff_idens(is_a, is_b): - """Detail diff for IDEN sets — compares active element counts.""" + """Detail diff for IDEN sets — elements compared slot by slot.""" + parts = [] + fields = _changed_fields(is_a, is_b, skip=_BOOKKEEPING | {"elements"}) + if fields: + parts.append("set fields: " + ", ".join(fields)) active_a = sum(1 for e in is_a.elements if not e.is_empty()) active_b = sum(1 for e in is_b.elements if not e.is_empty()) if active_a != active_b: - return f"{active_a}->{active_b} active elements" - return None + parts.append(f"{active_a}->{active_b} active elements") + changed = [f"#{i} ({', '.join(_changed_fields(a, b))})" + for i, (a, b) in enumerate(zip(is_a.elements, is_b.elements)) + if a != b] + if changed: + parts.append(f"changed {len(changed)}: {_listed(changed)}") + elif len(is_a.elements) != len(is_b.elements): + parts.append(f"{len(is_a.elements)}->{len(is_b.elements)} elements") + return "; ".join(parts) or None def _compare_group_sets(prs_a, prs_b): @@ -246,7 +323,16 @@ def _compare_conv_sets(prs_a, prs_b): return _compare_set_type(prs_a, prs_b, "Conv Set", "CConvChannel", "CConvSet", parse_conv_channel_section, - lambda s: len(s.channels), "channels") + lambda s: len(s.channels), "channels", + _diff_convs) + + +def _compare_p25_conv_sets(prs_a, prs_b): + return _compare_set_type(prs_a, prs_b, "P25 Conv Set", + "CP25ConvChannel", "CP25ConvSet", + parse_p25_conv_channel_section, + lambda s: len(s.channels), "channels", + _diff_convs) def _compare_iden_sets(prs_a, prs_b): @@ -258,6 +344,91 @@ def _compare_iden_sets(prs_a, prs_b): "active elements", _diff_idens) +# Parts of the archive's root object, in order (see archive.Document), and +# the category a difference in each is reported under. Lists compared item +# by item above only get a line here when that comparison found nothing. +_ROOT_PARTS = [ + ("Personality", "header fields"), + ("System", None), + ("Trunk Set", "set data"), + ("Personality", "fields after the trunk sets"), + ("Conv Set", "set data"), + ("Options", None), + ("Personality", "name, user and band limits"), + ("Group Set", "set data"), + ("P25 Conv Set", "set data"), + ("Personality", "list after the P25 conv sets"), + ("IDEN Set", "set data"), + ("Radio Options", "options XML and file tail"), +] + + +def _system_name(obj): + """A system object's short name (its data starts with it).""" + data = obj.data() + return data[1:1 + data[0]].decode("latin-1") if data else "?" + + +def _compare_documents(prs_a, prs_b, found): + """Differences the item comparisons above did not report. + + The archive tree holds every object's data without class tags or + list counts, so two files whose trees are equal hold the same + personality; anything else that differs is reported here. + """ + from . import archive + reported = {cat for kind, cat, _, _ in found if kind != SAME} + try: + doc_a = archive.document_from_prs(prs_a) + doc_b = archive.document_from_prs(prs_b) + except archive.WalkError: + if prs_a.to_bytes() != prs_b.to_bytes() and not reported: + return [(CHANGED, "File", "Content", + "the files differ (layout QuickPRS cannot itemize)")] + return [] + + parts_a, parts_b = doc_a.root.parts, doc_b.root.parts + if len(parts_a) != len(parts_b) or len(parts_a) != len(_ROOT_PARTS): + return ([] if parts_a == parts_b else + [(CHANGED, "File", "Content", "the files differ")]) + diffs = [] + for (cat, what), a, b in zip(_ROOT_PARTS, parts_a, parts_b): + if a == b: + continue + if cat == "System": + diffs.extend(_compare_system_objects(a.items, b.items)) + elif cat == "Options": + # options only one file has are reported as sections + for cls in sorted({o.cls for o in a.items if o} & + {o.cls for o in b.items if o}): + oa = [o for o in a.items if o and o.cls == cls] + ob = [o for o in b.items if o and o.cls == cls] + if oa != ob: + diffs.append((CHANGED, "Options", cls, "settings differ")) + elif cat in ("Personality", "Radio Options") or cat not in reported: + diffs.append((CHANGED, cat, what, "differs")) + return diffs + + +def _compare_system_objects(items_a, items_b): + """Systems present in both files whose settings differ (systems added + or removed are reported by _compare_systems).""" + by_name_a, by_name_b = {}, {} + for o in items_a: + by_name_a.setdefault((o.cls, _system_name(o)), o) + for o in items_b: + by_name_b.setdefault((o.cls, _system_name(o)), o) + labels = {"CP25TrkSystem": "P25 Trunked", "CConvSystem": "Conventional", + "CP25ConvSystem": "P25 Conv"} + diffs = [(CHANGED, labels.get(cls, cls), name, "system settings differ") + for (cls, name), o in by_name_a.items() + if (cls, name) in by_name_b and by_name_b[(cls, name)] != o] + if not diffs and [o for o in items_a] != [o for o in items_b] and \ + set(by_name_a) == set(by_name_b): + diffs.append((CHANGED, "System", "order", "systems reordered")) + return diffs + + def format_comparison(diffs, filepath_a="", filepath_b=""): """Format comparison results as human-readable text. diff --git a/tests/test_compare_changes.py b/tests/test_compare_changes.py new file mode 100644 index 0000000..19fdfe1 --- /dev/null +++ b/tests/test_compare_changes.py @@ -0,0 +1,103 @@ +"""compare reports changes inside sets and systems, not only sets added or +removed: a changed frequency, tone, talkgroup name, NAC or system setting +used to come out as "Files are identical" with exit code 0.""" + +import pytest + +from quickprs import injector +from quickprs.builder import create_blank_prs +from quickprs.cli import cmd_compare +from quickprs.comparison import compare_prs, format_comparison, SAME +from quickprs.prs_parser import parse_prs_bytes +from quickprs.record_types import P25TrkSystemConfig + + +def _personality(conv_rx=155.76, conv_tone="136.5", conv_narrow=False, + tg_name="PD DISP", tg_scan=True, trunk_tx=806.0125, + iden_base=851_012_500, nac=0x293, system_id=939, + gps=None): + """The same small personality every time, with one value changed.""" + prs = create_blank_prs() + injector.add_conv_set(prs, injector.make_conv_set("CONV", [ + {"short_name": "LE D1", "tx_freq": 155.76, "rx_freq": conv_rx, + "tx_tone": conv_tone, "rx_tone": conv_tone, + "narrowband": conv_narrow}, + {"short_name": "FIRE D1", "tx_freq": 154.28}, + ])) + injector.add_p25_conv_set(prs, injector.make_p25_conv_set("P25C", [ + {"short_name": "TAC 1", "tx_freq": 154.43, "nac_tx": nac}])) + gset = injector.make_group_set("CITY", [ + (100, tg_name, "PD DISPATCH"), (200, "FIRE", "FIRE DISPATCH")]) + gset.groups[0].scan = tg_scan + injector.add_p25_trunked_system( + prs, + P25TrkSystemConfig(system_name="CITY", long_name="CITY P25", + trunk_set_name="CITY", group_set_name="CITY", + wan_name="CITY", system_id=system_id), + trunk_set=injector.make_trunk_set( + "CITY", [(trunk_tx, 851.0125), (806.5125, 851.5125)]), + group_set=gset, + iden_set=injector.make_iden_set("CITY", [ + {"base_freq_hz": iden_base, "tx_offset_mhz": -45.0}])) + if gps: + from quickprs.option_maps import set_platform_option + set_platform_option(prs, "gps", "gpsMode", gps) + return parse_prs_bytes(prs.to_bytes()) + + +def _changes(**changed): + return [d for d in compare_prs(_personality(), _personality(**changed)) + if d[0] != SAME] + + +def test_same_personality_is_identical(): + assert _changes() == [] + + +@pytest.mark.parametrize("changed, category, name, words", [ + ({"conv_rx": 155.775}, "Conv Set", "CONV", ["LE D1", "rx_freq"]), + ({"conv_tone": "141.3"}, "Conv Set", "CONV", ["tx_tone", "rx_tone"]), + ({"conv_narrow": True}, "Conv Set", "CONV", ["narrowband"]), + ({"tg_name": "PD MAIN"}, "Group Set", "CITY", ["100 PD MAIN", + "group_name"]), + ({"tg_scan": False}, "Group Set", "CITY", ["100 PD DISP", "scan"]), + ({"trunk_tx": 806.0250}, "Trunk Set", "CITY", + ["+1: 806.02500/851.01250", "-1: 806.01250/851.01250"]), + ({"iden_base": 851_006_250}, "IDEN Set", "CITY", ["#0", "base_freq_hz"]), + ({"nac": 0x3AB}, "P25 Conv Set", "P25C", ["TAC 1", "nac_tx"]), + ({"system_id": 940}, "P25 Trunked", "CITY", ["system settings differ"]), + ({"gps": "OFF"}, "Radio Options", None, ["differs"]), +]) +def test_change_is_reported(changed, category, name, words): + hits = [d for d in _changes(**changed) if d[1] == category + and (name is None or d[2] == name)] + assert hits, _changes(**changed) + text = " ".join(d[3] for d in hits) + for word in words: + assert word in text + + +def test_compare_exits_1_on_a_changed_channel(tmp_path, capsys): + a, b = tmp_path / "a.PRS", tmp_path / "b.PRS" + a.write_bytes(_personality().to_bytes()) + b.write_bytes(_personality(conv_rx=155.775).to_bytes()) + assert cmd_compare(str(a), str(b)) == 1 + out = capsys.readouterr().out + assert "identical" not in out.lower() + assert "LE D1 (rx_freq)" in out + + +def test_identical_files_exit_0(tmp_path, capsys): + a, b = tmp_path / "a.PRS", tmp_path / "b.PRS" + a.write_bytes(_personality().to_bytes()) + b.write_bytes(_personality().to_bytes()) + assert cmd_compare(str(a), str(b)) == 0 + assert "identical" in capsys.readouterr().out.lower() + + +def test_long_change_lists_are_shortened(): + """A change line names three items, then counts the rest.""" + from quickprs.comparison import _listed + assert _listed(["a", "b", "c", "d", "e"]) == "a, b, c and 2 more" + lines = format_comparison(_changes(conv_rx=155.775)) + assert any("LE D1" in line for line in lines) From 475568e7e3196a5ce4e9fc3dbdf843b391b0d59b Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:00:36 -0700 Subject: [PATCH 05/22] JSON: export everything, import the same personality back Import rebuilt a personality from the readable fields on top of a blank one: it duplicated the blank's conventional set, never imported P25 conventional sets or systems or the radio options, packed IDEN elements into the first slots (the control channel names an IDEN by its slot), set system IDs to 0 unless a WAN entry gave one, and dropped every channel and talkgroup field without a readable key (power, squelch, audio profile, flags). Each channel, talkgroup and set now carries all of its fields after the readable ones (bytes as hex), IDEN elements carry their slot, and an 'archive' block carries everything else (systems, option objects, personality fields, options XML). An unedited export imports to the same bytes: all 36 RPM-saved test files do. Edits to sets, channels and talkgroups apply. A JSON without the archive block is built from a blank whose set lists and systems it replaces, with P25 conventional systems, system IDs, home unit IDs and the options XML. --- quickprs/json_io.py | 527 ++++++++++++++++++++++++++++++------------ tests/test_json_io.py | 136 +++++++++++ 2 files changed, 517 insertions(+), 146 deletions(-) diff --git a/quickprs/json_io.py b/quickprs/json_io.py index 27d3e75..690eafb 100644 --- a/quickprs/json_io.py +++ b/quickprs/json_io.py @@ -4,14 +4,22 @@ decoded data (personality, systems, trunk/group/conv/IDEN sets, WAN entries, platform config). -Import: reads a JSON document and creates a valid PRS file from its contents, -using the injector pipeline to build the binary structure. +Every channel, talkgroup and set carries all of its fields (bytes as hex) +after the readable ones, and an "archive" block carries the rest of the +file (systems, option objects, personality fields, options XML) as data, +so importing an unedited export gives back the same personality. + +Import: reads a JSON document and creates a valid PRS file from its +contents (see dict_to_prs). """ +import dataclasses import json import logging from pathlib import Path +from . import archive + from .prs_parser import parse_prs from .record_types import ( parse_personality_section, @@ -26,13 +34,39 @@ is_system_config_data, parse_ecc_entries, parse_sets_from_sections, list_system_configs, ) -from .option_maps import extract_platform_config +from .option_maps import extract_platform_config, extract_platform_xml logger = logging.getLogger("quickprs") # ─── Export: PRS → dict → JSON ────────────────────────────────────── +# Each channel, talkgroup and set is exported with its readable keys and, +# after them, every other field of its record (bytes as hex), so an import +# rebuilds it exactly. Class tags are left out: they are recomputed on +# every save. +_TAGS = ("separator", "set_marker") + +_CONV_HIDDEN = ("_flags_reserved", "pre_long_name", "trailer") +_P25_CONV_HIDDEN = ("_flags_reserved", "trailer") +_GROUP_HIDDEN = ("_middle_reserved_9_10", "audio_profile", "key_id") +_GROUP_RENAME = {"id": "group_id", "short_name": "group_name"} + + +def _hidden(obj, shown): + """The fields of a record not among its readable keys, bytes as hex.""" + out = {} + for f in dataclasses.fields(obj): + if f.name in shown or f.name in _TAGS: + continue + value = getattr(obj, f.name) + if isinstance(value, list): + continue + if isinstance(value, (bytes, bytearray)): + value = bytes(value).hex() + out[f.name] = value + return out + def _parse_sets(prs, data_cls, set_cls, parser_func): """Parse a set type from PRS sections. Returns list or [].""" @@ -47,11 +81,10 @@ def _trunk_set_to_dict(tset): """Convert a TrunkSet to a JSON-friendly dict.""" channels = [] for ch in tset.channels: - channels.append({ - "tx_freq": round(ch.tx_freq, 6), - "rx_freq": round(ch.rx_freq, 6), - }) - return { + d = {"tx_freq": ch.tx_freq, "rx_freq": ch.rx_freq} + d.update(_hidden(ch, d)) + channels.append(d) + result = { "name": tset.name, "channels": channels, "tx_min": tset.tx_min, @@ -59,36 +92,44 @@ def _trunk_set_to_dict(tset): "rx_min": tset.rx_min, "rx_max": tset.rx_max, } + result.update(_hidden(tset, result)) + return result def _group_set_to_dict(gset): """Convert a P25GroupSet to a JSON-friendly dict.""" groups = [] for g in gset.groups: - groups.append({ + d = { "id": g.group_id, "short_name": g.group_name, "long_name": g.long_name, "tx": g.tx, "scan": g.scan, "rx": g.rx, - }) - return { + } + d.update(_hidden(g, {_GROUP_RENAME.get(k, k) for k in d})) + groups.append(d) + result = { "name": gset.name, "scan_list_size": gset.scan_list_size, "system_id": gset.system_id, "groups": groups, } + result.update(_hidden(gset, result)) + return result def _conv_set_to_dict(cset): """Convert a ConvSet to a JSON-friendly dict.""" channels = [] + readable = ("short_name", "tx_freq", "rx_freq", "long_name", "tx", "rx", + "scan", "tx_tone", "rx_tone", "narrowband") for ch in cset.channels: d = { "short_name": ch.short_name, - "tx_freq": round(ch.tx_freq, 6), - "rx_freq": round(ch.rx_freq, 6), + "tx_freq": ch.tx_freq, + "rx_freq": ch.rx_freq, "long_name": ch.long_name, "tx": ch.tx, "rx": ch.rx, @@ -100,16 +141,17 @@ def _conv_set_to_dict(cset): d["rx_tone"] = ch.rx_tone if ch.narrowband: d["narrowband"] = True + d.update(_hidden(ch, readable)) channels.append(d) result = { "name": cset.name, "channels": channels, + "tx_min": cset.tx_min, + "tx_max": cset.tx_max, + "rx_min": cset.rx_min, + "rx_max": cset.rx_max, } - if cset.tx_min != 0.0: - result["tx_min"] = cset.tx_min - result["tx_max"] = cset.tx_max - result["rx_min"] = cset.rx_min - result["rx_max"] = cset.rx_max + result.update(_hidden(cset, result)) return result @@ -119,19 +161,18 @@ def _p25_conv_set_to_dict(cset): for ch in cset.channels: d = { "short_name": ch.short_name, - "tx_freq": round(ch.tx_freq, 6), - "rx_freq": round(ch.rx_freq, 6), + "tx_freq": ch.tx_freq, + "rx_freq": ch.rx_freq, "long_name": ch.long_name, "tx": ch.tx, "rx": ch.rx, "scan": ch.scan, + "nac_tx": ch.nac_tx, + "nac_rx": ch.nac_rx, } - if ch.nac_tx: - d["nac_tx"] = ch.nac_tx - if ch.nac_rx: - d["nac_rx"] = ch.nac_rx + d.update(_hidden(ch, d)) channels.append(d) - return { + result = { "name": cset.name, "channels": channels, "tx_min": cset.tx_min, @@ -140,25 +181,37 @@ def _p25_conv_set_to_dict(cset): "rx_max": cset.rx_max, "group_set_ref": cset.group_set_ref, } + result.update(_hidden(cset, result)) + return result def _iden_set_to_dict(iset): - """Convert an IdenDataSet to a JSON-friendly dict.""" + """Convert an IdenDataSet to a JSON-friendly dict. + + Only elements that are set are listed, each with its slot ("index", + 0-15): the control channel names an IDEN by its slot, so slots must + not move.""" + from .record_types import IdenElement elements = [] - for elem in iset.elements: - if elem.is_empty(): + for index, elem in enumerate(iset.elements): + if elem == IdenElement(): continue - elements.append({ + d = { + "index": index, "chan_spacing_hz": elem.chan_spacing_hz, "bandwidth_hz": elem.bandwidth_hz, "base_freq_hz": elem.base_freq_hz, "tx_offset_mhz": round(elem.tx_offset_mhz, 1), "iden_type": "TDMA" if elem.iden_type else "FDMA", - }) - return { + } + d.update(_hidden(elem, set(d) | {"iden_type"})) + elements.append(d) + result = { "name": iset.name, "elements": elements, } + result.update(_hidden(iset, result)) + return result def _wan_entry_to_dict(entry): @@ -200,6 +253,31 @@ def _config_to_sys_dict(cfg_raw, sys_type): return sys_dict +def _system_extras(obj): + """Set references and IDs read from a system object of an + archive.Document (the readable systems list shows them).""" + 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 + _, pos = archive.read_cstring(data, pos) # trunk set + _, pos = archive.read_cstring(data, pos) # group set + pos += 12 + home = int.from_bytes(data[pos:pos + 4], "little") + pos += 4 + 12 + 6 + 2 + sysid = int.from_bytes(data[pos:pos + 4], "little") + iden, _ = archive.read_cstring(obj.parts[2], 4) + extras = {"system_id": sysid, "home_unit_id": home} + if iden: + extras["iden_set"] = iden + return extras + if obj.cls == "CConvSystem": + return {"conv_set": archive.read_cstring(data, pos + 12)[0]} + return {"conv_set": archive.read_cstring(data, pos + 5 + 4)[0]} + + def _collect_systems(prs): """Collect all system information into a list of dicts. @@ -219,6 +297,17 @@ def _collect_systems(prs): system_class_map[ref.class_name]) sys_dict["name"] = ref.short_name systems.append(sys_dict) + try: + objs = [o for o in archive.document_from_prs(prs).list( + "systems").items if o is not None] + except archive.WalkError: + objs = [] + if len(objs) == len(systems): + for sys_dict, obj in zip(systems, objs): + try: + sys_dict.update(_system_extras(obj)) + except (IndexError, ValueError): + pass return systems @@ -297,14 +386,51 @@ def prs_to_dict(prs): _wan_entry_to_dict(e) for e in entries ] - # Platform config (XML options) + # Platform config (XML options): readable, and the XML itself, which + # an import without the archive block applies config = extract_platform_config(prs) if config: - result["options"] = {"platform_config": config} + result["options"] = {"platform_config": config, + "platform_xml": extract_platform_xml(prs)} + + # Everything that is not a set (systems, option objects, personality + # fields, the options XML) as archive data; dict_to_prs rebuilds the + # personality from it and the readable sets + try: + doc = archive.document_from_prs(prs) + except archive.WalkError: + doc = None + if doc is not None: + result["archive"] = { + "schemas": dict(doc.schemas), + "root": _obj_to_json(doc.root, skip=_SET_LIST_NAMES), + } return result +# The archive's set lists: exported as readable sets, not as data +_SET_LIST_NAMES = ("trunk sets", "conv sets", "group sets", "P25 conv sets", + "IDEN sets") + + +def _obj_to_json(obj, skip=()): + """An archive object as JSON: its class and its parts (bytes as hex, + nested lists as {list, counted, items}); lists named in ``skip`` are + written empty.""" + if obj is None: + return None + parts = [] + for p in obj.parts: + if isinstance(p, (bytes, bytearray)): + parts.append(bytes(p).hex()) + else: + parts.append({"list": p.name, "counted": p.counted, + "items": [] if p.name in skip else + [_obj_to_json(i) for i in p.items]}) + return {"class": obj.cls, "parts": parts} + + def dict_to_json(d, compact=False): """Serialize a dict to a formatted JSON string. @@ -355,11 +481,168 @@ def json_to_dict(filepath): return json.loads(text) +def _is_bytes_field(f): + return isinstance(f.default, (bytes, bytearray)) or f.type in ( + bytes, 'bytes') + + +def _from_fields(cls, d, rename=None, **fixed): + """Build a dataclass from exported keys: readable keys (renamed via + ``rename``, JSON key -> field) and hidden ones, hex strings back to + bytes. Keys the class does not have are ignored; fields the dict + leaves out keep their defaults.""" + rename = rename or {} + data = {rename.get(k, k): v for k, v in d.items()} + kwargs = {} + for f in dataclasses.fields(cls): + if f.name in fixed: + kwargs[f.name] = fixed[f.name] + elif f.name in data and not isinstance(data[f.name], (list, dict)): + value = data[f.name] + if _is_bytes_field(f) and isinstance(value, str): + value = bytes.fromhex(value) + kwargs[f.name] = value + return cls(**kwargs) + + +def _trunk_set_from_dict(ts_d): + from .record_types import TrunkChannel, TrunkSet + channels = [_from_fields(TrunkChannel, ch) + for ch in ts_d.get("channels", [])] + return _from_fields(TrunkSet, ts_d, channels=channels, + name=ts_d["name"][:8]) + + +def _group_set_from_dict(gs_d): + from .injector import make_p25_group + from .record_types import P25Group, P25GroupSet + groups = [] + for g in gs_d.get("groups", []): + if any(k in g for k in _GROUP_HIDDEN): + groups.append(_from_fields(P25Group, g, _GROUP_RENAME)) + else: + # hand-written: the injector's defaults for a new talkgroup + grp = make_p25_group(g["id"], + g.get("short_name", f"TG{g['id']}")[:8], + g.get("long_name", "")[:16], + tx=g.get("tx", False), + scan=g.get("scan", True)) + if "rx" in g: + grp.rx = g["rx"] + groups.append(grp) + return _from_fields(P25GroupSet, gs_d, groups=groups, + name=gs_d["name"][:8]) + + +def _conv_set_from_dict(cs_d): + from .injector import make_conv_channel + from .record_types import ConvChannel, ConvSet + channels = [] + for ch in cs_d.get("channels", []): + if any(k in ch for k in _CONV_HIDDEN): + channels.append(_from_fields(ConvChannel, ch)) + else: + channels.append(make_conv_channel( + ch.get("short_name", "CH")[:8], ch["tx_freq"], + ch.get("rx_freq", ch["tx_freq"]), + tx_tone=ch.get("tx_tone", ""), rx_tone=ch.get("rx_tone", ""), + long_name=ch.get("long_name", "")[:16], + tx=ch.get("tx", True), scan=ch.get("scan", True), + narrowband=ch.get("narrowband", False))) + if "rx" in ch: + channels[-1].rx = ch["rx"] + return _from_fields(ConvSet, cs_d, channels=channels, + name=cs_d["name"][:8]) + + +def _p25_conv_set_from_dict(cs_d): + from .injector import make_p25_conv_channel + from .record_types import P25ConvChannel, P25ConvSet + channels = [] + for ch in cs_d.get("channels", []): + if any(k in ch for k in _P25_CONV_HIDDEN): + channels.append(_from_fields(P25ConvChannel, ch)) + else: + channels.append(make_p25_conv_channel( + ch.get("short_name", "CH")[:8], ch["tx_freq"], + ch.get("rx_freq", ch["tx_freq"]), + nac_tx=ch.get("nac_tx", 0x293), nac_rx=ch.get("nac_rx"), + long_name=ch.get("long_name", "")[:16], + tx=ch.get("tx", True), rx=ch.get("rx", True), + scan=ch.get("scan", True))) + return _from_fields(P25ConvSet, cs_d, channels=channels, + name=cs_d["name"][:8]) + + +def _iden_set_from_dict(is_d): + from .record_types import IdenElement, IdenDataSet + elements = [IdenElement() for _ in range(IdenDataSet.SLOTS)] + for pos, e in enumerate(is_d.get("elements", [])): + index = e.get("index", pos) + fields = dict(e) + kind = fields.pop("iden_type", 0) + elem = _from_fields(IdenElement, fields) + elem.iden_type = 1 if kind in ("TDMA", 1) else 0 + raw = fields.get("tx_offset") + mhz = fields.get("tx_offset_mhz") + if mhz is not None and (raw is None or round(elem.tx_offset_mhz, 1) + != round(mhz, 1)): + elem.tx_offset_mhz = mhz # edited (or hand-written) + if not 0 <= index < IdenDataSet.SLOTS: + raise ValueError(f"IDEN set {is_d['name']}: element index " + f"{index} is not 0-{IdenDataSet.SLOTS - 1}") + elements[index] = elem + return _from_fields(IdenDataSet, is_d, elements=elements, + name=is_d["name"][:8]) + + +# (JSON key, archive list, set reader) +_SET_LISTS = [ + ("trunk_sets", "trunk sets", _trunk_set_from_dict), + ("conv_sets", "conv sets", _conv_set_from_dict), + ("group_sets", "group sets", _group_set_from_dict), + ("p25_conv_sets", "P25 conv sets", _p25_conv_set_from_dict), + ("iden_sets", "IDEN sets", _iden_set_from_dict), +] + + +def _obj_from_json(j): + from .archive import Obj, ObjList + if j is None: + return None + parts = [] + for p in j["parts"]: + if isinstance(p, str): + parts.append(bytes.fromhex(p)) + else: + parts.append(ObjList(p["list"], + [_obj_from_json(i) for i in p.get("items", [])], + p.get("counted", True))) + return Obj(j["class"], parts) + + +def _set_objects(list_name, sets): + from .injector import _SET_OBJ_BUILDERS + build = _SET_OBJ_BUILDERS[list_name] + if list_name == "conv sets": + return [build(s, None) for s in sets] + return [build(s) for s in sets] + + def dict_to_prs(d): """Convert a JSON-derived dict into a PRSFile. - Creates a blank PRS and injects systems, sets, and WAN entries - from the dict structure. + A dict from prs_to_dict carries an "archive" block (systems, option + objects, personality fields and the options XML, as data) next to the + readable sets: the personality is rebuilt from both, so an unedited + export imports to the same personality, and edits to the sets, their + channels and talkgroups are applied. Systems and options come from + the archive block; to rebuild them from the readable "systems" list + instead, delete the "archive" key. + + Without an archive block (a hand-written file, or one from QuickPRS + 1.1 or older) the personality is built from a blank one: each set list + and the systems list the dict has replaces the blank's. Args: d: dict (from json_to_dict or prs_to_dict) @@ -367,106 +650,48 @@ def dict_to_prs(d): Returns: PRSFile object """ + from .prs_parser import parse_prs_bytes + from . import archive + + if "archive" in d: + arch = d["archive"] + doc = archive.Document(_obj_from_json(arch["root"]), + dict(arch.get("schemas", {}))) + for key, list_name, read in _SET_LISTS: + doc.list(list_name).items = _set_objects( + list_name, [read(x) for x in d.get(key, [])]) + return parse_prs_bytes(archive.serialize(doc)) + + return _dict_to_prs_readable(d) + + +def _dict_to_prs_readable(d): from .builder import create_blank_prs - from .injector import ( - add_p25_trunked_system, add_conv_system, - make_trunk_set, make_group_set, make_p25_group, - make_trunk_channel, make_conv_set, make_conv_channel, - make_iden_set, - ) - from .record_types import ( - P25TrkSystemConfig, ConvSystemConfig, - TrunkChannel, TrunkSet, P25Group, P25GroupSet, - ConvChannel, ConvSet, IdenElement, IdenDataSet, - P25TrkWanEntry, EnhancedCCEntry, - ) + from . import archive + from .injector import (add_p25_trunked_system, add_conv_system, + add_p25_conv_system) + from .record_types import (P25TrkSystemConfig, ConvSystemConfig, + P25ConvSystemConfig) + from .prs_parser import parse_prs_bytes - # Personality metadata pers = d.get("personality", {}) - filename = pers.get("filename", "Imported.PRS") - saved_by = pers.get("saved_by", "") - - prs = create_blank_prs(filename=filename, saved_by=saved_by) - - # Track what sets need to be created - trunk_sets_data = d.get("trunk_sets", []) - group_sets_data = d.get("group_sets", []) - conv_sets_data = d.get("conv_sets", []) - iden_sets_data = d.get("iden_sets", []) - wan_entries_data = d.get("wan_entries", []) - systems_data = d.get("systems", []) - - # Create trunk sets - for ts_d in trunk_sets_data: - channels = ts_d.get("channels", []) - freqs = [(ch["tx_freq"], ch["rx_freq"]) for ch in channels] - tset = make_trunk_set( - ts_d["name"], freqs, - tx_min=ts_d.get("tx_min", 136.0), - tx_max=ts_d.get("tx_max", 870.0), - rx_min=ts_d.get("rx_min", 136.0), - rx_max=ts_d.get("rx_max", 870.0), - ) - from .injector import _safe_add_trunk_set - _safe_add_trunk_set(prs, tset) - - # Create group sets - for gs_d in group_sets_data: - groups_data = gs_d.get("groups", []) - groups = [] - for g in groups_data: - groups.append(make_p25_group( - g["id"], - g.get("short_name", f"TG{g['id']}")[:8], - g.get("long_name", "")[:16], - tx=g.get("tx", False), - scan=g.get("scan", True), - )) - from .record_types import P25GroupSet - gset = P25GroupSet(name=gs_d["name"][:8], groups=groups) - from .injector import _safe_add_group_set - _safe_add_group_set(prs, gset) - - # Create IDEN sets - for is_d in iden_sets_data: - elements_data = is_d.get("elements", []) - entries = [] - for elem in elements_data: - iden_type = 1 if elem.get("iden_type", "FDMA") == "TDMA" else 0 - entries.append({ - "chan_spacing_hz": elem.get("chan_spacing_hz", 12500), - "bandwidth_hz": elem.get("bandwidth_hz", 6250), - "base_freq_hz": elem.get("base_freq_hz", 0), - "tx_offset_mhz": elem.get("tx_offset_mhz", 0.0), - "iden_type": iden_type, - }) - iset = make_iden_set(is_d["name"], entries) - from .injector import _safe_add_iden_set - _safe_add_iden_set(prs, iset) - - # Create conventional sets - for cs_d in conv_sets_data: - channels_data = cs_d.get("channels", []) - ch_list = [] - for ch in channels_data: - ch_list.append({ - "short_name": ch.get("short_name", "CH")[:8], - "tx_freq": ch["tx_freq"], - "rx_freq": ch.get("rx_freq", ch["tx_freq"]), - "tx_tone": ch.get("tx_tone", ""), - "rx_tone": ch.get("rx_tone", ""), - "long_name": ch.get("long_name", "")[:16], - }) - cset = make_conv_set(cs_d["name"], ch_list) - from .injector import _safe_add_conv_set - _safe_add_conv_set(prs, cset) - - # Create systems - for sys_d in systems_data: + prs = create_blank_prs(filename=pers.get("filename", "Imported.PRS"), + saved_by=pers.get("saved_by", "")) + + doc = archive.document_from_prs(prs) + for key, list_name, read in _SET_LISTS: + if key in d: + doc.list(list_name).items = _set_objects( + list_name, [read(x) for x in d[key]]) + if "systems" in d: + doc.list("systems").items = [] + prs = parse_prs_bytes(archive.serialize(doc)) + + wan_entries = d.get("wan_entries", []) + for sys_d in d.get("systems", []): sys_type = sys_d.get("type", "") sys_name = sys_d.get("name", "SYS")[:8] long_name = sys_d.get("long_name", sys_name)[:16] - if sys_type == "P25Trunked": config = P25TrkSystemConfig( system_name=sys_name, @@ -475,26 +700,36 @@ def dict_to_prs(d): group_set_name=sys_d.get("group_set", sys_name)[:8], wan_name=sys_d.get("wan_name", sys_name)[:8], system_id=sys_d.get("system_id", 0), + home_unit_id=sys_d.get("home_unit_id", 0), + iden_set_name=sys_d.get("iden_set", "")[:8], ) - # Look up WACN from wan_entries if available - wan_name_stripped = config.wan_name.strip() - for we in wan_entries_data: - if we.get("wan_name", "").strip() == wan_name_stripped: + for we in wan_entries: + if we.get("wan_name", "").strip() == config.wan_name.strip(): config.wacn = we.get("wacn", 0) - config.system_id = we.get("system_id", - config.system_id) + config.system_id = we.get("system_id", config.system_id) break add_p25_trunked_system(prs, config) - elif sys_type == "Conventional": - config = ConvSystemConfig( - system_name=sys_name, - long_name=long_name, - conv_set_name=sys_d.get("group_set", - sys_d.get("conv_set", sys_name))[:8], - ) - add_conv_system(prs, config) - + add_conv_system(prs, ConvSystemConfig( + system_name=sys_name, long_name=long_name, + conv_set_name=sys_d.get("conv_set", sys_name)[:8])) + elif sys_type == "P25Conv": + add_p25_conv_system(prs, P25ConvSystemConfig( + system_name=sys_name, long_name=long_name, + conv_set_name=sys_d.get("conv_set", sys_name)[:8])) + + xml = d.get("options", {}).get("platform_xml") + if xml: + from .option_maps import (extract_platform_xml, write_platform_config, + _inject_platform_xml) + if extract_platform_xml(prs) is None: + written = _inject_platform_xml(prs, xml) + else: + written = write_platform_config(prs, xml) + if not written: + logger.warning("The JSON's radio options could not be written") + elif d.get("options", {}).get("platform_config"): + logger.warning("JSON options without platform_xml are not imported") return prs @@ -508,12 +743,12 @@ def import_json(filepath, output_path=None): Returns: (PRSFile, str): the PRS object and the output path written to """ + from .prs_writer import write_prs d = json_to_dict(filepath) prs = dict_to_prs(d) if output_path is None: output_path = Path(filepath).with_suffix('.PRS') - raw = prs.to_bytes() - Path(output_path).write_bytes(raw) + write_prs(prs, output_path, backup=True) return prs, str(output_path) diff --git a/tests/test_json_io.py b/tests/test_json_io.py index cae0ef4..5aeb554 100644 --- a/tests/test_json_io.py +++ b/tests/test_json_io.py @@ -806,3 +806,139 @@ def test_frequencies_preserved(self): ts = next(ts for ts in d2["trunk_sets"] if ts["name"] == "FREQ") assert abs(ts["channels"][0]["tx_freq"] - 851.0125) < 0.0001 assert abs(ts["channels"][1]["tx_freq"] - 851.5125) < 0.0001 + + +# ─── Lossless round trip ───────────────────────────────────────────── + + +def _built(): + """A personality with every set type, a P25 system with IDs, an IDEN + table with a gap between its slots, and a changed radio option.""" + from quickprs import injector + from quickprs.option_maps import set_platform_option + from quickprs.prs_parser import parse_prs_bytes + from quickprs.record_types import P25TrkSystemConfig, P25ConvSystemConfig + prs = create_blank_prs("built.PRS", "tester") + injector.add_conv_set(prs, injector.make_conv_set("CONV", [ + {"short_name": "LE D1", "tx_freq": 155.76, "tx_tone": "136.5", + "rx_tone": "136.5", "narrowband": True}, + {"short_name": "FIRE D1", "tx_freq": 154.28, "scan": False}])) + injector.add_p25_conv_set(prs, injector.make_p25_conv_set("P25C", [ + {"short_name": "TAC 1", "tx_freq": 154.43, "nac_tx": 0x3AB}])) + injector.add_p25_conv_system(prs, P25ConvSystemConfig( + system_name="P25C", long_name="P25 CONV", conv_set_name="P25C")) + iden = injector.make_iden_set("CITY", [ + {"base_freq_hz": 851_012_500, "tx_offset_mhz": -45.0}]) + iden.elements[3] = injector.make_iden_set("X", [ + {"base_freq_hz": 762_006_250, "tx_offset_mhz": 30.0, + "iden_type": 1, "chan_spacing_hz": 12500}]).elements[0] + gset = injector.make_group_set("CITY", [ + (100, "PD DISP", "PD DISPATCH"), (200, "FIRE", "FIRE DISPATCH")]) + injector.add_p25_trunked_system( + prs, + P25TrkSystemConfig(system_name="CITY", long_name="CITY P25", + trunk_set_name="CITY", group_set_name="CITY", + wan_name="CITY", system_id=939, + home_unit_id=1234567, iden_set_name="CITY"), + trunk_set=injector.make_trunk_set( + "CITY", [(806.0125, 851.0125), (806.5125, 851.5125)]), + group_set=gset, iden_set=iden) + set_platform_option(prs, "gps", "gpsMode", "OFF") + return parse_prs_bytes(prs.to_bytes()) + + +def _through_json(d): + return json.loads(json.dumps(d)) + + +class TestLosslessRoundTrip: + """An unedited export imports to the same personality. Import used to + drop P25 conventional sets and systems and the radio options, compact + IDEN tables, lose system IDs and duplicate the blank's default set.""" + + def test_blank_is_identical(self): + prs = create_blank_prs("roundtrip.PRS", "tester") + back = dict_to_prs(_through_json(prs_to_dict(prs))) + assert back.to_bytes() == prs.to_bytes() + + def test_built_personality_is_identical(self): + prs = _built() + back = dict_to_prs(_through_json(prs_to_dict(prs))) + assert back.to_bytes() == prs.to_bytes() + + @pytest.mark.skipif(not TESTDATA.exists(), reason="no test data") + def test_rpm_files_are_identical(self): + files = sorted(TESTDATA.rglob("*.PRS")) + if not files: + pytest.skip("Test PRS data not available") + for f in files: + prs = parse_prs(f) + back = dict_to_prs(_through_json(prs_to_dict(prs))) + assert back.to_bytes() == f.read_bytes(), f.name + + def test_edits_apply_and_nothing_else_changes(self): + from quickprs.comparison import compare_prs, SAME + prs = _built() + d = _through_json(prs_to_dict(prs)) + city = next(g for g in d["group_sets"] if g["name"] == "CITY") + city["groups"][0]["short_name"] = "PD MAIN" + conv = next(c for c in d["conv_sets"] if c["name"] == "CONV") + conv["channels"][0]["rx_freq"] = 155.775 + diffs = [x for x in compare_prs(prs, dict_to_prs(d)) if x[0] != SAME] + assert sorted((x[1], x[2]) for x in diffs) == [ + ("Conv Set", "CONV"), ("Group Set", "CITY")], diffs + + def test_iden_slots_are_kept(self): + d = _through_json(prs_to_dict(_built())) + city = next(i for i in d["iden_sets"] if i["name"] == "CITY") + assert [e["index"] for e in city["elements"]] == [0, 3] + assert city["elements"][1]["iden_type"] == "TDMA" + + +class TestImportWithoutArchive: + """A JSON without the archive block (hand-written, or from 1.1.0 or + older) is built from a blank personality.""" + + @staticmethod + def _readable(prs): + d = _through_json(prs_to_dict(prs)) + del d["archive"] + return d + + def test_default_set_is_not_duplicated(self): + from quickprs.injector import get_p25_conv_sets # noqa: F401 + back = prs_to_dict(dict_to_prs(self._readable( + create_blank_prs("blank.PRS")))) + assert [c["name"] for c in back["conv_sets"]] == ["Conv 1"] + assert [s["name"] for s in back["systems"]] == ["Conv 1"] + + def test_sets_systems_ids_and_options_survive(self): + from quickprs.option_maps import extract_platform_config + back_prs = dict_to_prs(self._readable(_built())) + back = prs_to_dict(back_prs) + assert [c["name"] for c in back["p25_conv_sets"]] == ["P25C"] + assert back["p25_conv_sets"][0]["channels"][0]["nac_tx"] == 0x3AB + systems = {s["name"]: s for s in back["systems"]} + assert systems["P25C"]["type"] == "P25Conv" + assert systems["P25C"]["conv_set"] == "P25C" + assert systems["CITY"]["system_id"] == 939 + assert systems["CITY"]["home_unit_id"] == 1234567 + assert systems["CITY"]["iden_set"] == "CITY" + city = next(i for i in back["iden_sets"] if i["name"] == "CITY") + assert [e["index"] for e in city["elements"]] == [0, 3] + gps = extract_platform_config(back_prs)["gpsConfig"] + assert gps["gpsMode"] == "OFF" + + def test_hidden_fields_are_kept(self): + """Channel and talkgroup fields that have no readable key (power, + squelch, audio profile...) come through the hidden fields.""" + prs = _built() + d = self._readable(prs) + conv = next(c for c in d["conv_sets"] if c["name"] == "CONV") + conv["channels"][0]["pre_long_name"] = "00010c0000000000" "0101" + back = prs_to_dict(dict_to_prs(d)) + ch = next(c for c in back["conv_sets"] + if c["name"] == "CONV")["channels"][0] + assert ch["pre_long_name"] == "00010c00000000000101" + assert ch["narrowband"] is True + assert ch["tx_tone"] == "136.5" From a7809b11a64d1380e23644dfb0f0f5776c3d253c Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:00:37 -0700 Subject: [PATCH 06/22] compare: name the personality fields that differ Two blanks saved under different names came out as 'header fields differs'; compare now lists the file name, saved-by, save time, personality name and user name that changed. --- quickprs/comparison.py | 48 ++++++++++++++++++++++++++++++++++++++++++ tests/test_stress.py | 15 ++++++++----- 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/quickprs/comparison.py b/quickprs/comparison.py index 0dc9489..5242cbe 100644 --- a/quickprs/comparison.py +++ b/quickprs/comparison.py @@ -405,11 +405,59 @@ def _compare_documents(prs_a, prs_b, found): ob = [o for o in b.items if o and o.cls == cls] if oa != ob: diffs.append((CHANGED, "Options", cls, "settings differ")) + elif what == "header fields": + diffs.extend(_compare_personality_headers(prs_a, prs_b)) + elif what == "name, user and band limits": + diffs.extend(_compare_doc_fields(a, b)) elif cat in ("Personality", "Radio Options") or cat not in reported: diffs.append((CHANGED, cat, what, "differs")) return diffs +def _compare_personality_headers(prs_a, prs_b): + """The CPersonality fields that differ (file name, saved by, save + time ...).""" + from .record_types import parse_personality_section + try: + pa = parse_personality_section( + prs_a.get_section_by_class("CPersonality").raw) + pb = parse_personality_section( + prs_b.get_section_by_class("CPersonality").raw) + except Exception: + return [(CHANGED, "Personality", "header fields", "differs")] + diffs = [(CHANGED, "Personality", f.name, + f"{getattr(pa, f.name)!r} -> {getattr(pb, f.name)!r}") + for f in dataclasses.fields(pa) + if getattr(pa, f.name) != getattr(pb, f.name)] + return diffs or [(CHANGED, "Personality", "header fields", "differ")] + + +def _compare_doc_fields(a, b): + """Personality name, user name and band limits (the document fields + after the options list).""" + from . import archive + try: + name_a, pos_a = archive.read_cstring(a, 0) + name_b, pos_b = archive.read_cstring(b, 0) + user_a, end_a = archive.read_cstring(a, pos_a + 2) + user_b, end_b = archive.read_cstring(b, pos_b + 2) + except (IndexError, ValueError): + return [(CHANGED, "Personality", "name, user and band limits", + "differ")] + diffs = [] + if name_a != name_b: + diffs.append((CHANGED, "Personality", "personality name", + f"{name_a!r} -> {name_b!r}")) + if user_a != user_b: + diffs.append((CHANGED, "Personality", "user name", + f"{user_a!r} -> {user_b!r}")) + if (a[pos_a:pos_a + 2] != b[pos_b:pos_b + 2] + or a[end_a:] != b[end_b:]): + diffs.append((CHANGED, "Personality", "band limits and flags", + "differ")) + return diffs + + def _compare_system_objects(items_a, items_b): """Systems present in both files whose settings differ (systems added or removed are reported by _compare_systems).""" diff --git a/tests/test_stress.py b/tests/test_stress.py index 175b5e4..79fd1b1 100644 --- a/tests/test_stress.py +++ b/tests/test_stress.py @@ -1461,11 +1461,16 @@ def test_export_csv_via_cli(self, tmp_path, capsys): assert rc == 0 def test_compare_via_cli(self, tmp_path, capsys): - """compare via run_cli.""" - a = _make_blank(tmp_path, "a.PRS") - b = _make_blank(tmp_path, "b.PRS") - rc = run_cli(["compare", a, b]) - assert rc == 0 + """compare via run_cli: the same personality is identical, another + name is a difference.""" + (tmp_path / "x").mkdir() + (tmp_path / "y").mkdir() + a = _make_blank(tmp_path / "x") + b = _make_blank(tmp_path / "y") + assert run_cli(["compare", a, b]) == 0 + c = _make_blank(tmp_path, "c.PRS") + assert run_cli(["compare", a, c]) == 1 + assert "'blank.PRS' -> 'c.PRS'" in capsys.readouterr().out def test_diff_options_via_cli(self, tmp_path, capsys): """diff-options via run_cli.""" From 528b35ba549f98d88ef0d27e55a4c1e01718dea0 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:00:37 -0700 Subject: [PATCH 07/22] Refuse duplicate set names; merge copies systems exactly Systems find their sets by name, but adding a set under a name already in use went through silently (validation then warned that RPM may confuse the two). The add functions now refuse it. That showed merge creating such duplicates. It also walked systems the 1.0 way, one class header and every config block after it, so every system was named after the first of its class; it rebuilt P25 systems from defaults (system ID 0 unless a WAN entry gave one, no home unit ID, flags or ECC entries, an IDEN set guessed from the name) and left P25 conventional systems out. merge now copies each system object and the sets it names from the archive tree as they are, with its WAN entry, and skips (and reports) a system whose set name the target holds with other contents. Tests that meant to add a talkgroup or frequency to an existing set added a second set with the same name; they now add to the set. --- quickprs/cli.py | 8 +- quickprs/gui/app.py | 5 +- quickprs/injector.py | 337 ++++++++++++--------------------- tests/test_clone_and_detail.py | 12 +- tests/test_comparison.py | 12 +- tests/test_injection.py | 39 ++++ tests/test_merge.py | 121 ++++++++++++ 7 files changed, 301 insertions(+), 233 deletions(-) diff --git a/quickprs/cli.py b/quickprs/cli.py index a9915ab..70d5668 100644 --- a/quickprs/cli.py +++ b/quickprs/cli.py @@ -1557,8 +1557,10 @@ def cmd_merge(target_path, source_path, include_systems=True, """Merge systems and channels from source PRS into target PRS. Copies P25 trunked systems (with their trunk sets, group sets, IDEN sets) - and conventional systems (with their conv sets) from source into target. - Skips systems that already exist in target (by short name). + and conventional and P25 conventional systems (with their channel + sets) from source into target, as the source has them. Skips systems + that already exist in target (by short name) and systems naming a set + the target holds with other contents. Args: target_path: target PRS file path @@ -1600,6 +1602,8 @@ def cmd_merge(target_path, source_path, include_systems=True, f"{stats['conv_skipped']} skipped") if total_added == 0 and total_skipped == 0: print(" No systems found in source to merge.") + for line in stats['conflicts']: + print(f" Not merged: {line}") if errors: print(f" Validation: {len(errors)} errors", file=sys.stderr) diff --git a/quickprs/gui/app.py b/quickprs/gui/app.py index 3f1c2db..368f611 100644 --- a/quickprs/gui/app.py +++ b/quickprs/gui/app.py @@ -1966,8 +1966,11 @@ def merge_prs(self): msg = f"Merged {total_added} systems from {Path(source_path).name}" if total_skipped: - msg += f" ({total_skipped} skipped as duplicates)" + msg += f" ({total_skipped} skipped)" self.status_set(msg) + if stats['conflicts']: + messagebox.showinfo( + "Merge", "Not merged:\n" + "\n".join(stats['conflicts'])) log_action("merge_prs", source=source_path, p25_added=stats['p25_added'], conv_added=stats['conv_added'], diff --git a/quickprs/injector.py b/quickprs/injector.py index ded22d8..9f92b55 100644 --- a/quickprs/injector.py +++ b/quickprs/injector.py @@ -187,6 +187,39 @@ def _system_obj_names(obj): return short, long_name +def _system_obj_refs(obj): + """The sets a system object of an archive.Document names, as + (archive list name, set name) pairs: trunk, talkgroup and IDEN sets + for a P25 trunked system, the channel set for the others.""" + 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, _ = archive.read_cstring(data, pos) + iden, _ = archive.read_cstring(obj.parts[2], 4) + return [("trunk sets", trunk), ("group sets", group), + ("IDEN sets", iden)] + if obj.cls == "CConvSystem": + return [("conv sets", archive.read_cstring(data, pos + 12)[0])] + return [("P25 conv sets", archive.read_cstring(data, pos + 5 + 4)[0])] + + +def _system_obj_wan_name(obj): + """The WAN name a P25 trunked system object names.""" + data = obj.parts[0] + _, pos = archive.read_cstring(data, 0) + pos += 1 + 2 + 42 + _, pos = archive.read_cstring(data, pos) # long name + pos += 15 + _, pos = archive.read_cstring(data, pos) # trunk set + _, pos = archive.read_cstring(data, pos) # group set + pos += 12 + 4 + 12 + 6 + 2 + 4 # ... home unit ID, system ID + return archive.read_cstring(data, pos)[0] + + def system_set_references(prs): """Every set name the personality's systems refer to. @@ -200,24 +233,8 @@ def system_set_references(prs): 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) + if obj is not None: + refs.update(name for _, name in _system_obj_refs(obj)) refs.discard("") return refs @@ -230,6 +247,13 @@ def _append_system(prs, obj): # ─── Trunk Set Operations ──────────────────────────────────────────── +def _refuse_duplicate(existing_sets, new_set, label): + """Systems refer to sets by name, so two sets of one type may not + share a name (validation warns that RPM may confuse them).""" + if any(s.name == new_set.name for s in existing_sets): + raise ValueError(f"{label} '{new_set.name}' already exists") + + def add_trunk_set(prs, trunk_set): """Add a new TrunkSet to the personality. @@ -251,6 +275,7 @@ def add_trunk_set(prs, trunk_set): existing_sets = _parse_section_data(ch_sec, parse_trunk_channel_section, first_count) + _refuse_duplicate(existing_sets, trunk_set, "Trunk set") existing_sets.append(trunk_set) _replace_trunk_sections(prs, existing_sets, byte1, byte2, @@ -358,6 +383,7 @@ def add_group_set(prs, group_set): first_count = _get_first_count(prs, "CP25GroupSet") existing_sets = _parse_section_data(grp_sec, parse_group_section, first_count) + _refuse_duplicate(existing_sets, group_set, "Group set") existing_sets.append(group_set) _replace_group_sections(prs, existing_sets, byte1, byte2, @@ -452,6 +478,7 @@ def add_iden_set(prs, iden_set): first_count = _get_first_count(prs, "CIdenDataSet") existing_sets = _parse_section_data(elem_sec, parse_iden_section, first_count) + _refuse_duplicate(existing_sets, iden_set, "IDEN set") 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. @@ -486,8 +513,7 @@ def get_p25_conv_sets(prs): 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") + _refuse_duplicate(existing, p25_conv_set, "P25 conv set") _write_set_list(prs, "P25 conv sets", existing + [p25_conv_set]) @@ -807,6 +833,7 @@ def add_conv_set(prs, conv_set): existing_sets = _parse_section_data(ch_sec, parse_conv_channel_section, first_count) + _refuse_duplicate(existing_sets, conv_set, "Conv set") existing_sets.append(conv_set) _replace_conv_sections(prs, existing_sets, byte1, byte2, @@ -2072,236 +2099,110 @@ def _has_tdma_spacing(freqs): def merge_prs(target, source, include_systems=True, include_channels=True): """Merge data from source PRS into target PRS. - Copies P25 trunked systems (with their trunk sets, group sets, IDEN sets) - and conventional systems (with their conv sets) from source to target. - Skips systems that already exist in target (by short name). + Copies P25 trunked systems (with their trunk, talkgroup and IDEN sets + and their WAN entry) and conventional and P25 conventional systems + (with their channel sets) from source to target, exactly as the + source has them. Skips systems whose short name the target already + has, and systems naming a set that the target holds with other + contents under the same name (systems find their sets by name, so the + merged system would get the target's set). Args: target: PRSFile object (modified in-place) source: PRSFile object (read-only) include_systems: if True, merge P25 trunked systems - include_channels: if True, merge conventional systems + include_channels: if True, merge conventional and P25 + conventional systems Returns: dict with merge statistics: p25_added: number of P25 systems added - p25_skipped: number of P25 systems skipped (duplicates) + p25_skipped: number of P25 systems skipped conv_added: number of conventional systems added - conv_skipped: number of conventional systems skipped (duplicates) + conv_skipped: number of conventional systems skipped + conflicts: one line per system skipped over a set name clash """ stats = { 'p25_added': 0, 'p25_skipped': 0, 'conv_added': 0, 'conv_skipped': 0, + 'conflicts': [], } + t_doc = archive.document_from_prs(target) + s_doc = archive.document_from_prs(source) + t_systems = t_doc.list("systems").items + t_names = {_system_obj_names(o)[0] for o in t_systems if o is not None} - # Collect existing system short names in target - target_system_names = _collect_system_names(target) - - if include_systems: - _merge_p25_systems(target, source, target_system_names, stats) - - if include_channels: - _merge_conv_systems(target, source, target_system_names, stats) - - return stats - - -def _collect_system_names(prs): - """Collect all system short names from a PRS file. - - Checks both system header sections (CP25TrkSystem, CConvSystem, etc.) - and system config data sections (unnamed sections with the universal - prefix). This catches systems where multiple configs share one header. - The config data sections contain the long name; we extract and store - both the long name and any conv set reference name, since the source - system's short name may match any of these. - """ - names = set() - for sec in prs.sections: - if sec.class_name in ('CP25TrkSystem', 'CConvSystem', - 'CP25ConvSystem'): - name = parse_system_short_name(sec.raw) - if name: - names.add(name) - elif not sec.class_name and is_system_config_data(sec.raw): - long_name = parse_system_long_name(sec.raw) - if long_name: - names.add(long_name) - # For P25 trunked systems, also extract set references - trunk_ref, group_ref = parse_system_set_refs(sec.raw) - if trunk_ref: - names.add(trunk_ref) - return names - - -def _get_source_system_configs(prs, class_name): - """Extract system header + config data section groups from a PRS. - - For each system header of the given class_name, returns a list of - (header_section, [data_sections]) tuples. - """ - systems = [] - i = 0 - while i < len(prs.sections): - sec = prs.sections[i] - if sec.class_name != class_name: - i += 1 + for obj in s_doc.list("systems").items: + if obj is None: continue - - header = sec - data_sections = [] - j = i + 1 - while j < len(prs.sections): - next_sec = prs.sections[j] - if next_sec.class_name: - break # hit another class header - data_sections.append(next_sec) - j += 1 - - systems.append((header, data_sections)) - i = j - - return systems - - -def _merge_p25_systems(target, source, target_names, stats): - """Merge P25 trunked systems from source into target.""" - from .record_types import P25TrkSystemConfig - - # Parse source data sets - src_trunk_sets = _parse_source_sets( - source, "CTrunkChannel", "CTrunkSet", parse_trunk_channel_section) - src_group_sets = _parse_source_sets( - source, "CP25Group", "CP25GroupSet", parse_group_section) - src_iden_sets = _parse_source_sets( - source, "CDefaultIdenElem", "CIdenDataSet", parse_iden_section) - - systems = _get_source_system_configs(source, "CP25TrkSystem") - - for header, data_secs in systems: - short_name = parse_system_short_name(header.raw) - if not short_name: + p25 = obj.cls == "CP25TrkSystem" + if not (include_systems if p25 else include_channels): continue - - if short_name in target_names: - logger.debug("Skipping P25 system '%s' (already in target)", - short_name) - stats['p25_skipped'] += 1 + kind = 'p25' if p25 else 'conv' + name = _system_obj_names(obj)[0] + if name in t_names: + logger.debug("Skipping system '%s' (already in target)", name) + stats[f'{kind}_skipped'] += 1 continue - # For each data section (there may be multiple configs per header), - # extract references and inject - for data_sec in data_secs: - if not is_system_config_data(data_sec.raw): + copies, clashes = [], [] + for list_name, set_name in _system_obj_refs(obj): + if not set_name: continue + src = _find_set_obj(s_doc, list_name, set_name) + have = _find_set_obj(t_doc, list_name, set_name) + if have is None: + if src is not None: + copies.append((list_name, src)) + elif src is not None and have != src: + clashes.append(set_name) + if clashes: + stats['conflicts'].append( + f"{name}: the target has other sets named " + f"{', '.join(repr(c) for c in clashes)}") + stats[f'{kind}_skipped'] += 1 + continue - long_name = parse_system_long_name(data_sec.raw) - trunk_ref, group_ref = parse_system_set_refs(data_sec.raw) + for list_name, src in copies: + t_doc.list(list_name).items.append(src) + if p25: + _merge_wan_entry(t_doc, s_doc, _system_obj_wan_name(obj)) + t_systems.append(obj) + t_names.add(name) + stats[f'{kind}_added'] += 1 - # Find matching trunk set in source - trunk_set = None - if trunk_ref: - for ts in src_trunk_sets: - if ts.name == trunk_ref: - trunk_set = ts - break + archive.write_document(target, t_doc) + return stats - # Find matching group set in source - group_set = None - if group_ref: - for gs in src_group_sets: - if gs.name == group_ref: - group_set = gs - break - # Find matching IDEN set — use the short name prefix - iden_set = None - for iset in src_iden_sets: - # IDEN sets are often named with a prefix of the system name - if iset.name.strip(): - iden_set = iset - # Prefer an IDEN set whose name relates to this system - if short_name[:5].upper() in iset.name.upper(): - break - - # Build config from the raw data section's fields - config = P25TrkSystemConfig( - system_name=short_name, - long_name=long_name or short_name, - trunk_set_name=trunk_ref or "", - group_set_name=group_ref or "", - wan_name=short_name, - system_id=0, # will be read from WAN if available - wacn=0, - ) - - # Try to get system_id and wacn from source WAN entries - _populate_wan_from_source(source, config, short_name) - - # Build IDEN set name - if iden_set: - config.iden_set_name = iden_set.name - - add_p25_trunked_system( - target, config, - trunk_set=trunk_set, - group_set=group_set, - iden_set=iden_set, - ) - - target_names.add(short_name) - stats['p25_added'] += 1 - - -def _merge_conv_systems(target, source, target_names, stats): - """Merge conventional systems from source into target.""" - from .record_types import ConvSystemConfig - - src_conv_sets = _parse_source_sets( - source, "CConvChannel", "CConvSet", parse_conv_channel_section) - - systems = _get_source_system_configs(source, "CConvSystem") - - for header, data_secs in systems: - short_name = parse_system_short_name(header.raw) - if not short_name: - continue +def _find_set_obj(doc, list_name, set_name): + for o in doc.list(list_name).items: + if o is not None and _set_obj_name(o) == set_name: + return o + return None - if short_name in target_names: - logger.debug("Skipping conv system '%s' (already in target)", - short_name) - stats['conv_skipped'] += 1 - continue - for data_sec in data_secs: - if not is_system_config_data(data_sec.raw): - continue +def _merge_wan_entry(t_doc, s_doc, wan_name): + """Copy the source's WAN entry for wan_name unless the target has one.""" + def entries(doc): + opts = doc.option("CP25tWanOpts") + return opts.parts[0].items if opts is not None else None - long_name = parse_system_long_name(data_sec.raw) + src, dst = entries(s_doc), entries(t_doc) + if src is None or dst is None: + return - # Extract conv set reference from data section - # Layout: PREFIX(44) + LPS(long_name) + 12 zeros + LPS(conv_set) - conv_ref = _parse_conv_set_ref(data_sec.raw) + def wan(o): + return archive.read_cstring(o.parts[0], 0)[0].strip() - conv_set = None - if conv_ref: - for cs in src_conv_sets: - if cs.name == conv_ref: - conv_set = cs - break - - config = ConvSystemConfig( - system_name=short_name, - long_name=long_name or short_name, - conv_set_name=conv_ref or "", - ) - - add_conv_system(target, config, conv_set=conv_set) - - target_names.add(short_name) - stats['conv_added'] += 1 + if any(o is not None and wan(o) == wan_name.strip() for o in dst): + return + for o in src: + if o is not None and wan(o) == wan_name.strip(): + dst.append(o) + return def _parse_source_sets(prs, data_cls, set_cls, parser_func): diff --git a/tests/test_clone_and_detail.py b/tests/test_clone_and_detail.py index 0ceee7f..7f27607 100644 --- a/tests/test_clone_and_detail.py +++ b/tests/test_clone_and_detail.py @@ -441,10 +441,9 @@ def test_talkgroup_diffs_after_add(self): prs_b = deepcopy(prs_a) # Add a talkgroup to an existing group set - new_gset = make_group_set("PSERN PD", [ - (9999, "EXTRA", "EXTRA TALKGROUP"), - ]) - add_group_set(prs_b, new_gset) + from quickprs.injector import add_talkgroups, make_p25_group + add_talkgroups(prs_b, "PSERN PD", + [make_p25_group(9999, "EXTRA", "EXTRA TALKGROUP")]) detail = detailed_comparison(prs_a, prs_b) @@ -461,8 +460,9 @@ def test_freq_diffs_after_add(self): prs_a = cached_parse_prs(PAWS) prs_b = deepcopy(prs_a) - new_tset = make_trunk_set("PSERN", [(999.0125, 999.0125)]) - add_trunk_set(prs_b, new_tset) + from quickprs.injector import add_trunk_channels, make_trunk_channel + add_trunk_channels(prs_b, "PSERN", + [make_trunk_channel(806.0125, 851.0125)]) detail = detailed_comparison(prs_a, prs_b) diff --git a/tests/test_comparison.py b/tests/test_comparison.py index 0e8180e..21162c9 100644 --- a/tests/test_comparison.py +++ b/tests/test_comparison.py @@ -171,10 +171,9 @@ def test_compare_group_set_content_change(self): prs_a = cached_parse_prs(PAWS) prs_b = deepcopy(prs_a) # Add a talkgroup to an existing set - new_gset = make_group_set("PSERN PD", [ - (9999, "EXTRA", "EXTRA TALKGROUP"), - ]) - add_group_set(prs_b, new_gset) + from quickprs.injector import add_talkgroups, make_p25_group + add_talkgroups(prs_b, "PSERN PD", + [make_p25_group(9999, "EXTRA", "EXTRA TALKGROUP")]) diffs = compare_prs(prs_a, prs_b) group_diffs = [d for d in diffs if d[1] == "Group Set" and d[2] == "PSERN PD"] @@ -186,8 +185,9 @@ def test_compare_trunk_set_content_change(self): from copy import deepcopy prs_a = cached_parse_prs(PAWS) prs_b = deepcopy(prs_a) - new_tset = make_trunk_set("PSERN", [(999.0125, 999.0125)]) - add_trunk_set(prs_b, new_tset) + from quickprs.injector import add_trunk_channels, make_trunk_channel + add_trunk_channels(prs_b, "PSERN", + [make_trunk_channel(806.0125, 851.0125)]) diffs = compare_prs(prs_a, prs_b) trunk_diffs = [d for d in diffs if d[1] == "Trunk Set" and d[2] == "PSERN"] diff --git a/tests/test_injection.py b/tests/test_injection.py index df6b79f..011beb2 100644 --- a/tests/test_injection.py +++ b/tests/test_injection.py @@ -1495,3 +1495,42 @@ def main(): if __name__ == "__main__": sys.exit(main()) + + +# ─── Set names are unique per set type ─────────────────────────────── + + +def _one_of_each(name): + """A small set of every type, all called ``name``.""" + import quickprs.injector as inj + return { + "conv": inj.make_conv_set(name, [ + {"short_name": "A", "tx_freq": 151.625}]), + "trunk": inj.make_trunk_set(name, [(806.0125, 851.0125)]), + "group": inj.make_group_set(name, [(1, "TG", "TG")]), + "iden": inj.make_iden_set(name, [{"base_freq_hz": 851_012_500}]), + "p25conv": inj.make_p25_conv_set(name, [ + {"short_name": "P", "tx_freq": 154.43}]), + } + + +@pytest.mark.parametrize("kind", ["conv", "trunk", "group", "iden", + "p25conv"]) +def test_adding_a_set_name_twice_is_refused(kind): + """Systems find their sets by name; a second set under the same name + used to be added silently (validation then warned that RPM may confuse + the two).""" + import quickprs.injector as inj + from quickprs.builder import create_blank_prs + first = {"conv": inj._safe_add_conv_set, "trunk": inj._safe_add_trunk_set, + "group": inj._safe_add_group_set, "iden": inj._safe_add_iden_set, + "p25conv": inj.add_p25_conv_set}[kind] + again = {"conv": inj.add_conv_set, "trunk": inj.add_trunk_set, + "group": inj.add_group_set, "iden": inj.add_iden_set, + "p25conv": inj.add_p25_conv_set}[kind] + prs = create_blank_prs() + first(prs, _one_of_each("SAME")[kind]) + before = prs.to_bytes() + with pytest.raises(ValueError, match="already exists"): + again(prs, _one_of_each("SAME")[kind]) + assert prs.to_bytes() == before diff --git a/tests/test_merge.py b/tests/test_merge.py index 6fa8eb1..771f141 100644 --- a/tests/test_merge.py +++ b/tests/test_merge.py @@ -555,3 +555,124 @@ def test_multiple_templates_same_file(self, capsys, tmp_path): raw1 = Path(prs_file).read_bytes() raw2 = prs.to_bytes() assert raw1 == raw2 + + +# ─── Systems come across exactly ───────────────────────────────────── + + +def _systems(prs): + from quickprs import archive + return [o for o in archive.document_from_prs(prs).list("systems").items + if o is not None] + + +def _system_names(prs): + from quickprs.injector import _system_obj_names + return [_system_obj_names(o)[0] for o in _systems(prs)] + + +def _source(): + """Two P25 systems sharing an IDEN set, a conventional system and a P25 + conventional one, with IDs a rebuild from defaults would lose.""" + from quickprs import injector + from quickprs.builder import create_blank_prs + from quickprs.prs_parser import parse_prs_bytes + from quickprs.record_types import ( + P25TrkSystemConfig, ConvSystemConfig, P25ConvSystemConfig) + prs = create_blank_prs("source.PRS") + iden = injector.make_iden_set("SHARED", [ + {"base_freq_hz": 851_012_500, "tx_offset_mhz": -45.0}]) + for i, name in enumerate(("CITY", "COUNTY")): + injector.add_p25_trunked_system( + prs, + P25TrkSystemConfig( + system_name=name, long_name=f"{name} P25", + trunk_set_name=name, group_set_name=name, wan_name=name, + system_id=900 + i, home_unit_id=1234500 + i, + iden_set_name="SHARED"), + trunk_set=injector.make_trunk_set( + name, [(806.0125 + i, 851.0125 + i)]), + group_set=injector.make_group_set( + name, [(100 + i, f"TG {i}", f"TALKGROUP {i}")]), + iden_set=iden if i == 0 else None) + injector.add_conv_system(prs, ConvSystemConfig( + system_name="SIMPLEX", long_name="SIMPLEX", conv_set_name="SIMPLEX"), + conv_set=injector.make_conv_set("SIMPLEX", [ + {"short_name": "S1", "tx_freq": 155.16}])) + injector.add_p25_conv_set(prs, injector.make_p25_conv_set("P25C", [ + {"short_name": "TAC", "tx_freq": 154.43, "nac_tx": 0x3AB}])) + injector.add_p25_conv_system(prs, P25ConvSystemConfig( + system_name="P25C", long_name="P25 CONV", conv_set_name="P25C")) + return parse_prs_bytes(prs.to_bytes()) + + +class TestMergeKeepsSystems: + """merge used to name every system after the first one of its class, + rebuild P25 systems from defaults (system ID 0 unless a WAN entry gave + one, no home unit ID, a guessed IDEN set) and leave P25 conventional + systems out.""" + + def test_names_and_settings_are_the_sources(self): + from quickprs.builder import create_blank_prs + from quickprs.prs_parser import parse_prs_bytes + source = _source() + target = parse_prs_bytes(create_blank_prs("target.PRS").to_bytes()) + stats = merge_prs(target, source) + # both blanks have "Conv 1", so that one is skipped + assert (stats["p25_added"], stats["conv_added"], + stats["conv_skipped"]) == (2, 2, 1) + merged = {s.cls + ":" + s.parts[0][1:1 + s.parts[0][0]].decode(): + s for s in _systems(target)} + for obj in _systems(source): + key = obj.cls + ":" + obj.parts[0][1:1 + obj.parts[0][0]].decode() + assert merged[key] == obj, key + + def test_merged_file_is_complete(self): + from quickprs import archive + from quickprs.builder import create_blank_prs + from quickprs.json_io import prs_to_dict + from quickprs.prs_parser import parse_prs_bytes + target = parse_prs_bytes(create_blank_prs("target.PRS").to_bytes()) + merge_prs(target, _source()) + d = prs_to_dict(parse_prs_bytes(target.to_bytes())) + assert [s["name"] for s in d["iden_sets"]] == ["SHARED"] + assert [s["name"] for s in d["p25_conv_sets"]] == ["P25C"] + assert {w["wan_name"] for w in d["wan_entries"]} == {"CITY", + "COUNTY"} + systems = {s["name"]: s for s in d["systems"]} + assert systems["COUNTY"]["system_id"] == 901 + assert systems["COUNTY"]["home_unit_id"] == 1234501 + assert systems["COUNTY"]["iden_set"] == "SHARED" + assert archive.check(target) == [] + + def test_merging_twice_adds_nothing(self): + from quickprs.builder import create_blank_prs + from quickprs.prs_parser import parse_prs_bytes + target = parse_prs_bytes(create_blank_prs("target.PRS").to_bytes()) + merge_prs(target, _source()) + before = target.to_bytes() + stats = merge_prs(target, _source()) + assert stats["p25_added"] == stats["conv_added"] == 0 + assert target.to_bytes() == before + + def test_a_different_set_under_the_same_name_is_a_conflict(self): + from quickprs import injector + from quickprs.builder import create_blank_prs + from quickprs.prs_parser import parse_prs_bytes + target = create_blank_prs("target.PRS") + injector.add_conv_set(target, injector.make_conv_set("SIMPLEX", [ + {"short_name": "OTHER", "tx_freq": 151.625}])) + target = parse_prs_bytes(target.to_bytes()) + stats = merge_prs(target, _source()) + assert "SIMPLEX" not in _system_names(target) + assert stats["conflicts"] == [ + "SIMPLEX: the target has other sets named 'SIMPLEX'"] + + @pytest.mark.skipif(not PAWS.exists(), reason="Test PRS data not available") + def test_rpm_file_into_blank(self): + from quickprs.builder import create_blank_prs + from quickprs.prs_parser import parse_prs_bytes + source = cached_parse_prs(PAWS) + target = parse_prs_bytes(create_blank_prs("target.PRS").to_bytes()) + merge_prs(target, source) + assert _system_names(target) == ["Conv 1"] + _system_names(source) From 3800f34230f2c4511673b8d9ed87a93cc60d7b40 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:00:37 -0700 Subject: [PATCH 08/22] wizard --modify adds to the file; ask before replacing an output wizard --modify FILE printed 'Modifying: FILE', then built a new personality and wrote it to the output name without reading FILE. It now adds the systems, channels and options it collects to FILE and saves it in place by default. The wizard also wrote over an existing output file without asking and without a backup, bypassing the save checks; it now asks, and writes through write_prs (backup, structure check). --- quickprs/config_builder.py | 10 ++-- quickprs/wizard.py | 52 +++++++++++++----- tests/test_wizard.py | 109 ++++++++++++++++++++++++++++++++----- 3 files changed, 139 insertions(+), 32 deletions(-) diff --git a/quickprs/config_builder.py b/quickprs/config_builder.py index 9ddeee3..c69a16a 100644 --- a/quickprs/config_builder.py +++ b/quickprs/config_builder.py @@ -34,14 +34,16 @@ class ConfigError(Exception): pass -def build_from_config(config_path): +def build_from_config(config_path, base=None): """Build a complete PRS file from a config file. - Parses the INI file, creates a blank PRS, then injects systems, - channels, and options as specified. + Parses the INI file, creates a blank PRS (or takes ``base``), then + injects systems, channels, and options as specified. Args: config_path: path to the .ini config file + base: optional PRSFile to add to instead of a blank personality + (its [personality] name and author are then left as they are) Returns: PRSFile object @@ -66,7 +68,7 @@ def build_from_config(config_path): cfg.read(str(path), encoding='utf-8') # Build the PRS - prs = _build_personality(cfg) + prs = base if base is not None else _build_personality(cfg) _inject_systems(cfg, prs) _inject_channels(cfg, prs) _apply_options(cfg, prs) diff --git a/quickprs/wizard.py b/quickprs/wizard.py index a1620af..e40268e 100644 --- a/quickprs/wizard.py +++ b/quickprs/wizard.py @@ -240,9 +240,10 @@ def run_wizard(modify_file=None): """Run the interactive wizard. Args: - modify_file: if provided, path to existing PRS to modify. - Currently only new-file creation is supported; - modify_file is reserved for future use. + modify_file: if provided, path to an existing PRS: the systems, + channels and options the wizard collects are added + to it, and it is saved in place unless another + output file is given (a backup is kept). Returns: 0 on success, 1 on error. @@ -252,18 +253,36 @@ def run_wizard(modify_file=None): print("=" * 40) print() + base = None if modify_file: + from .prs_parser import parse_prs + try: + base = parse_prs(modify_file) + except (OSError, ValueError) as e: + print(f"Error: cannot read {modify_file}: {e}", file=sys.stderr) + return 1 print(f"Modifying: {modify_file}") - print("Note: modify mode re-builds from scratch on top of " - "the existing file.") + print("The systems, channels and options you add go into this " + "file.") print() # --- Step 1: Personality --- print("--- Step 1: Personality ---") - name = _input("Personality name", "New Radio.PRS") - if not name.upper().endswith('.PRS'): - name += '.PRS' - output_file = _input("Output file", name) + if base is not None: + name = Path(modify_file).name + output_file = _input("Output file", modify_file) + else: + name = _input("Personality name", "New Radio.PRS") + if not name.upper().endswith('.PRS'): + name += '.PRS' + output_file = _input("Output file", name) + out_path = Path(output_file) + replacing_other = out_path.exists() and not ( + modify_file and out_path.resolve() == Path(modify_file).resolve()) + if replacing_other and not _input_yn( + f"{out_path} exists. Replace it (a .bak copy is kept)?", False): + print("Cancelled.") + return 1 print() # --- Step 2: P25 Systems --- @@ -326,8 +345,9 @@ def run_wizard(modify_file=None): f.write(ini_content) tmp_ini = f.name - prs = build_from_config(tmp_ini) - except ConfigError as e: + prs = build_from_config(tmp_ini, base=base) + except (ConfigError, ValueError) as e: + # ValueError: a name the file already uses, for one print(f"Error building personality: {e}", file=sys.stderr) return 1 finally: @@ -336,11 +356,15 @@ def run_wizard(modify_file=None): except OSError: pass - # Write output - out_path = Path(output_file) + # Write output (a .bak copy of a replaced file is kept) + from .prs_writer import write_prs, UnsafeWriteError out_path.parent.mkdir(parents=True, exist_ok=True) + try: + write_prs(prs, out_path, backup=True) + except UnsafeWriteError as e: + print(f"Error: {e}", file=sys.stderr) + return 1 raw = prs.to_bytes() - out_path.write_bytes(raw) # Validate from .validation import validate_prs, ERROR, WARNING diff --git a/tests/test_wizard.py b/tests/test_wizard.py index 77227ca..bd4adfd 100644 --- a/tests/test_wizard.py +++ b/tests/test_wizard.py @@ -711,21 +711,102 @@ def test_cli_wizard_dispatch(self, tmp_path, capsys): result = run_cli(["wizard"]) assert result == 0 - def test_cli_wizard_modify_flag(self, tmp_path, capsys): - """--modify flag is accepted.""" - out = str(tmp_path / "MOD.PRS") - inputs = [ - "MOD.PRS", - out, - "n", - "", - "", - "", - "", - ] + def test_cli_wizard_modify_missing_file(self, tmp_path, capsys): + """--modify needs a file it can read (it used to build a new + personality and report success).""" + missing = str(tmp_path / "missing.PRS") + with patch('builtins.input', side_effect=AssertionError("asked")): + result = run_cli(["wizard", "--modify", missing]) + assert result == 1 + assert "cannot read" in capsys.readouterr().err + + +class TestWizardModify: + """wizard --modify FILE adds to FILE; it used to ignore FILE and write + a new personality to the output name.""" + + def _radio(self, tmp_path): + from quickprs.builder import create_blank_prs + from quickprs.injector import add_conv_set, make_conv_set + prs = create_blank_prs(filename="MINE.PRS") + add_conv_set(prs, make_conv_set("KEEP", [ + {"short_name": "KEEP 1", "tx_freq": 151.625}])) + path = tmp_path / "radio.PRS" + path.write_bytes(prs.to_bytes()) + return path + + @staticmethod + def _conv_set_names(path): + from quickprs.prs_parser import parse_prs + from quickprs.record_types import ( + parse_sets_from_sections, parse_conv_channel_section) + prs = parse_prs(str(path)) + return [s.name for s in parse_sets_from_sections( + prs.get_section_by_class("CConvSet").raw, + prs.get_section_by_class("CConvChannel").raw, + parse_conv_channel_section)] + + def test_adds_to_the_file_in_place(self, tmp_path): + path = self._radio(tmp_path) + before = path.read_bytes() + # output (default: the file itself), no P25 system, MURS, no options + inputs = ["", "n", "murs", "", "", ""] with patch('builtins.input', side_effect=inputs): - result = run_cli(["wizard", "--modify", "dummy.PRS"]) - assert result == 0 + assert run_cli(["wizard", "--modify", str(path)]) == 0 + assert self._conv_set_names(path) == ["Conv 1", "KEEP", "MURS"] + assert Path(str(path) + ".bak").read_bytes() == before + assert not (tmp_path / "New Radio.PRS").exists() + + def test_keeps_the_personality_name(self, tmp_path): + from quickprs.prs_parser import parse_prs + from quickprs.record_types import parse_personality_section + path = self._radio(tmp_path) + with patch('builtins.input', side_effect=["", "n", "murs", "", "", + ""]): + assert run_cli(["wizard", "--modify", str(path)]) == 0 + prs = parse_prs(str(path)) + info = parse_personality_section( + prs.get_section_by_class("CPersonality").raw) + assert "MINE" in str(info) + + def test_name_clash_is_an_error(self, tmp_path, capsys): + path = self._radio(tmp_path) + before = path.read_bytes() + from quickprs.injector import add_conv_set, make_conv_set + from quickprs.prs_parser import parse_prs + prs = parse_prs(str(path)) + add_conv_set(prs, make_conv_set("MURS", [ + {"short_name": "M1", "tx_freq": 151.82}])) + path.write_bytes(prs.to_bytes()) + before = path.read_bytes() + with patch('builtins.input', side_effect=["", "n", "murs", "", "", + ""]): + assert run_cli(["wizard", "--modify", str(path)]) == 1 + assert "Error building personality" in capsys.readouterr().err + assert path.read_bytes() == before + + +class TestWizardOutputExists: + """The wizard wrote over an existing output file without asking.""" + + def test_declining_keeps_the_file(self, tmp_path): + out = tmp_path / "taken.PRS" + out.write_bytes(b"precious") + with patch('builtins.input', side_effect=["NEW.PRS", str(out), + "n"]): + assert run_cli(["wizard"]) == 1 + assert out.read_bytes() == b"precious" + + def test_replacing_keeps_a_backup(self, tmp_path): + from quickprs.builder import create_blank_prs + out = tmp_path / "taken.PRS" + old = create_blank_prs(filename="OLD.PRS").to_bytes() + out.write_bytes(old) + inputs = ["NEW.PRS", str(out), "y", "n", "", "", "", ""] + with patch('builtins.input', side_effect=inputs): + assert run_cli(["wizard"]) == 0 + assert Path(str(out) + ".bak").read_bytes() == old + assert out.read_bytes() != old # ─── Wizard validates output ────────────────────────────────────────── From 3fbc26f64cf75f20e0bbd006ac2b8dc888bf8f64 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:01:38 -0700 Subject: [PATCH 09/22] Wizard test: check the replace question was asked --- tests/test_wizard.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/tests/test_wizard.py b/tests/test_wizard.py index bd4adfd..3d6c75a 100644 --- a/tests/test_wizard.py +++ b/tests/test_wizard.py @@ -789,12 +789,20 @@ def test_name_clash_is_an_error(self, tmp_path, capsys): class TestWizardOutputExists: """The wizard wrote over an existing output file without asking.""" - def test_declining_keeps_the_file(self, tmp_path): + def test_declining_keeps_the_file(self, tmp_path, capsys): out = tmp_path / "taken.PRS" out.write_bytes(b"precious") - with patch('builtins.input', side_effect=["NEW.PRS", str(out), - "n"]): + asked = [] + answers = iter(["NEW.PRS", str(out), "n"]) + + def answer(prompt): + asked.append(prompt) + return next(answers) + + with patch('builtins.input', side_effect=answer): assert run_cli(["wizard"]) == 1 + assert "exists. Replace it" in asked[-1] + assert "Cancelled." in capsys.readouterr().out assert out.read_bytes() == b"precious" def test_replacing_keeps_a_backup(self, tmp_path): From e9d3f897b14e451744e2618ab52ae710bc9ef3b0 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:02:11 -0700 Subject: [PATCH 10/22] Changelog: unreleased fixes --- CHANGELOG.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5389ce4..c63c585 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,22 @@ All notable changes to QuickPRS will be documented in this file. +## [Unreleased] + +### Fixed +- Templates: FRS, GMRS 8-14, MURS 1-3 and the public safety simplex channels were 25 kHz channels where the FCC allows 12.5 kHz or less (47 CFR 95.573, 95.1773, 95.2773, 90.209(b)(5)); they are narrowband now. Marine channel 70 carries DSC only (no voice) and is no longer in the marine template +- CHIRP export lost the TX tone of a channel whose TX and RX tones differ, turned an RX-only tone into TX and RX, ignored the RX side of DCS, always wrote FM and dropped scan-off and TX-off. It now uses CHIRP's Cross mode, NFM, Skip and Duplex off, and CHIRP import reads them all back +- The Uniden export gave the scanner the tone the radio transmits; it now gives the one the radio expects on the receive frequency +- RadioReference conventional channels: DPL codes and P25 NACs were read as CTCSS tones, and every channel went into an analog set as wide FM. FMN channels are now narrowband, P25 channels go to a P25 conventional set with their NAC, and DMR, NXDN, AM and other modes are left out and counted +- `compare` said "Files are identical" (exit code 0) when a channel's frequency, tone, name or flags, a talkgroup, a trunk TX frequency, an IDEN element, a P25 conventional channel, a system setting or a radio option had changed. It now names the changed items and their fields, and reports anything else that differs +- JSON import duplicated the default conventional set, lost P25 conventional sets and systems, the radio options, system IDs and every field without a readable key, and moved IDEN elements to other slots. An unedited export now imports to the same bytes (all 36 RPM-saved test files do) +- `merge` named every system after the first one of its class, rebuilt P25 systems from defaults (system ID 0, no home unit ID, a guessed IDEN set), left P25 conventional systems out and could add a second set under a name already in use. It now copies systems and the sets they use exactly and reports name clashes +- Adding a set under a name already used by a set of the same type is refused: systems find their sets by name +- `wizard --modify FILE` ignored FILE and built a new personality; it now adds to FILE. The wizard replaced an existing output file without asking or keeping a backup + +### Changed +- JSON exports carry every field of each set, channel and talkgroup (bytes as hex) and an `archive` block with the rest of the file; IDEN elements carry their slot (`index`) + ## [1.1.0] - 2026-10-28 ### Fixed From de8ba4fb68f342daca6ab9e606d910530b6482d5 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:03:21 -0700 Subject: [PATCH 11/22] RadioReference cache: keep conventional channels, categories, color codes The cache saved a hand-picked list of fields, so a system loaded from it had no conventional channels and no categories (the GUI's category filter came up empty) and its frequencies lost their color codes. Save and load every field of the data classes instead. --- quickprs/cache.py | 121 ++++++++++---------------------------------- tests/test_cache.py | 32 ++++++++++++ 2 files changed, 58 insertions(+), 95 deletions(-) diff --git a/quickprs/cache.py b/quickprs/cache.py index d45b5f7..667a859 100644 --- a/quickprs/cache.py +++ b/quickprs/cache.py @@ -6,6 +6,7 @@ local user data only. """ +import dataclasses import json import logging from pathlib import Path @@ -13,7 +14,8 @@ logger = logging.getLogger("quickprs") -from .radioreference import RRSystem, RRTalkgroup, RRSite, RRSiteFreq +from .radioreference import (RRSystem, RRTalkgroup, RRSite, RRSiteFreq, + ConvChannelData) CACHE_DIR = Path.home() / '.quickprs' / 'cache' @@ -40,52 +42,10 @@ def save_system(system, source="paste"): filename = f"{safe_name}.json" filepath = cache_dir / filename - data = { - 'cached_at': datetime.now().isoformat(), - 'source': source, - 'sid': system.sid, - 'name': system.name, - 'system_type': system.system_type, - 'sysid': system.sysid, - 'wacn': system.wacn, - 'nac': system.nac, - 'voice': system.voice, - 'city': system.city, - 'state': system.state, - 'county': system.county, - 'talkgroups': [ - { - 'dec_id': tg.dec_id, - 'hex_id': tg.hex_id, - 'alpha_tag': tg.alpha_tag, - 'description': tg.description, - 'mode': tg.mode, - 'encrypted': tg.encrypted, - 'tag': tg.tag, - 'category': tg.category, - 'category_id': tg.category_id, - } - for tg in system.talkgroups - ], - 'sites': [ - { - 'site_id': site.site_id, - 'site_number': site.site_number, - 'name': site.name, - 'rfss': site.rfss, - 'nac': site.nac, - 'county': getattr(site, 'county', ''), - 'lat': getattr(site, 'lat', 0.0), - 'lon': getattr(site, 'lon', 0.0), - 'range_miles': getattr(site, 'range_miles', 0.0), - 'freqs': [ - {'freq': sf.freq, 'lcn': sf.lcn, 'use': sf.use} - for sf in site.freqs - ], - } - for site in system.sites - ], - } + # Every field of the system and the records in it (talkgroups, sites + # and their frequencies, conventional channels, categories) + data = {'cached_at': datetime.now().isoformat(), 'source': source} + data.update(dataclasses.asdict(system)) with open(filepath, 'w', encoding='utf-8') as f: json.dump(data, f, indent=2) @@ -98,60 +58,31 @@ def load_system(filepath): with open(filepath, 'r', encoding='utf-8') as f: data = json.load(f) - system = RRSystem( - sid=data.get('sid', 0), - name=data.get('name', ''), - system_type=data.get('system_type', ''), - sysid=data.get('sysid', ''), - wacn=data.get('wacn', ''), - nac=data.get('nac', ''), - voice=data.get('voice', ''), - city=data.get('city', ''), - state=data.get('state', ''), - county=data.get('county', ''), - ) - - system.talkgroups = [ - RRTalkgroup( - dec_id=tg['dec_id'], - hex_id=tg.get('hex_id', ''), - alpha_tag=tg.get('alpha_tag', ''), - description=tg.get('description', ''), - mode=tg.get('mode', ''), - encrypted=tg.get('encrypted', 0), - tag=tg.get('tag', ''), - category=tg.get('category', ''), - category_id=tg.get('category_id', 0), - ) - for tg in data.get('talkgroups', []) - ] - + system = _record(RRSystem, data, sid=data.get('sid', 0)) + system.categories = {int(k): v + for k, v in data.get('categories', {}).items()} + system.talkgroups = [_record(RRTalkgroup, tg) + for tg in data.get('talkgroups', [])] system.sites = [ - RRSite( - site_id=site['site_id'], - site_number=site.get('site_number', ''), - name=site.get('name', ''), - rfss=site.get('rfss', 0), - nac=site.get('nac', ''), - county=site.get('county', ''), - lat=float(site.get('lat', 0.0)), - lon=float(site.get('lon', 0.0)), - range_miles=float(site.get('range_miles', 0.0)), - freqs=[ - RRSiteFreq( - freq=sf['freq'], - lcn=sf.get('lcn', 0), - use=sf.get('use', ''), - ) - for sf in site.get('freqs', []) - ], - ) + _record(RRSite, site, freqs=[_record(RRSiteFreq, sf) + for sf in site.get('freqs', [])]) for site in data.get('sites', []) ] - + system.conv_channels = [_record(ConvChannelData, ch) + for ch in data.get('conv_channels', [])] return system +def _record(cls, d, **fixed): + """A data class from a cached dict: its own keys (others ignored, + missing ones default) plus ``fixed``.""" + names = {f.name for f in dataclasses.fields(cls)} + kwargs = {k: v for k, v in d.items() + if k in names and not isinstance(v, (list, dict))} + kwargs.update(fixed) + return cls(**kwargs) + + def list_cached_systems(): """List all cached systems. diff --git a/tests/test_cache.py b/tests/test_cache.py index 8b76b75..c54f50f 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -268,3 +268,35 @@ def test_overwrite_same_name(self, tmp_cache): assert path1 == path2 loaded = load_system(path2) assert len(loaded.talkgroups) == 3 + + +class TestEverythingIsCached: + """The cache dropped the conventional channels, the categories (the + GUI's category filter) and each frequency's color code.""" + + def test_round_trip_keeps_every_field(self, tmp_cache): + from quickprs.radioreference import ( + RRSystem, RRTalkgroup, RRSite, RRSiteFreq, ConvChannelData) + system = RRSystem( + sid=11628, name="PSERN", system_type="Project 25 Phase II", + sysid="3AB", wacn="BEE00", nac="3A1", voice="Analog and Digital", + city="Seattle", state="WA", county="King", + categories={7: "Seattle Police", 9: "King County Fire"}, + talkgroups=[RRTalkgroup(dec_id=1001, hex_id="3e9", + alpha_tag="SPD N", description="North", + mode="DE", encrypted=2, + tag="Law Dispatch", + category="Seattle Police", + category_id=7)], + sites=[RRSite(site_id=1, site_number="001", name="Capitol Hill", + rfss=1, nac="3A1", lat=47.6, lon=-122.3, + range_miles=12.0, county="King", + freqs=[RRSiteFreq(freq=851.0125, lcn=1, use="c", + color_code=3)])], + conv_channels=[ConvChannelData( + freq=155.76, name="LE D1", tone="136.5", mode="FMN", + description="Law Dispatch", tx_freq=150.76, tx_tone="136.5", + nac=0x293)], + ) + back = load_system(save_system(system)) + assert back == system From ecda307f3db2bd2c99bcf4ff54052be41c52f600 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:05:34 -0700 Subject: [PATCH 12/22] Set the personality name and user in both places they are stored The personality name and user name are stored in the CPersonality header and again among the document fields after the options; RPM writes the same values in both (all 36 test files). edit --name/--author, fleet unit names and clone-personality --name changed only the header. A name too long for the header's one-byte-length block is now a clear error instead of struct.error. --- quickprs/archive.py | 10 ++++ quickprs/cloner.py | 5 +- quickprs/injector.py | 26 +++++++++- tests/test_personality_names.py | 84 +++++++++++++++++++++++++++++++++ 4 files changed, 122 insertions(+), 3 deletions(-) create mode 100644 tests/test_personality_names.py diff --git a/quickprs/archive.py b/quickprs/archive.py index a93a8e7..c648624 100644 --- a/quickprs/archive.py +++ b/quickprs/archive.py @@ -784,6 +784,16 @@ def read_cstring(data, pos): return body.decode("latin-1"), w.pos +def write_cstring(text): + """Encode an MFC CString (1-byte length, or 0xFF + 16-bit length).""" + raw = text.encode("latin-1", errors="replace") + if len(raw) < 0xFF: + return struct.pack(" Date: Wed, 28 Oct 2026 10:07:50 -0700 Subject: [PATCH 13/22] CSV templates: readers skip the templates' comment lines template-csv writes '#' comment lines under each header, and inject and fleet read them as data: frequencies and units failed ('could not convert string to float: # Example: 806.0125') and the comment became a channel. The readers for these files now skip '#' lines and blank lines (exported CSVs, whose names may start with '#', are read as before). The channels example now says which frequency is the repeater input. --- quickprs/cli.py | 9 +++++--- quickprs/csv_import.py | 11 +++++++++ quickprs/fleet.py | 3 ++- tests/test_csv_templates.py | 46 +++++++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 4 deletions(-) create mode 100644 tests/test_csv_templates.py diff --git a/quickprs/cli.py b/quickprs/cli.py index 70d5668..e0579ae 100644 --- a/quickprs/cli.py +++ b/quickprs/cli.py @@ -1117,8 +1117,9 @@ def _read_csv_file(filepath): path = Path(filepath) if not path.exists(): raise FileNotFoundError(f"CSV file not found: {filepath}") + from .csv_import import data_lines with open(path, 'r', encoding='utf-8-sig') as f: - reader = csv.DictReader(f) + reader = csv.DictReader(data_lines(f)) return list(reader) @@ -3934,8 +3935,10 @@ def cmd_template_csv(template_type, output=None): 'default_name': 'channels.csv', 'content': ( "short_name,tx_freq,rx_freq,tx_tone,rx_tone,long_name\n" - "# Example: RPT IN,147.000,147.600,100.0,100.0," - "Repeater Input\n" + "# Example: RPT 147,147.600,147.000,100.0,100.0," + "Repeater 147.00\n" + "# The radio transmits on the repeater's input (tx_freq)\n" + "# and receives its output (rx_freq).\n" ), }, 'units': { diff --git a/quickprs/csv_import.py b/quickprs/csv_import.py index 09ca3c2..1df86d6 100644 --- a/quickprs/csv_import.py +++ b/quickprs/csv_import.py @@ -333,6 +333,17 @@ def import_p25_conv_csv(filepath): # ─── Helpers ──────────────────────────────────────────────────────── +def data_lines(f): + """The lines of a CSV file that hold data: blank lines and lines + starting with '#' (the comments `template-csv` writes) left out. + Used for the files `template-csv` makes, not for exported CSVs, + whose names may start with '#'.""" + for line in f: + stripped = line.strip() + if stripped and not stripped.startswith('#'): + yield line + + def _read_csv(filepath): """Read CSV file, return list of rows (each a list of strings).""" with open(filepath, 'r', encoding='utf-8-sig') as f: diff --git a/quickprs/fleet.py b/quickprs/fleet.py index 894d626..310f87f 100644 --- a/quickprs/fleet.py +++ b/quickprs/fleet.py @@ -102,9 +102,10 @@ def _parse_units_csv(csv_path): Returns: list of dicts with keys: unit_id (int), name (str), password (str) """ + from .csv_import import data_lines units = [] with open(csv_path, 'r', encoding='utf-8-sig') as f: - reader = csv.DictReader(f) + reader = csv.DictReader(data_lines(f)) if reader.fieldnames is None: raise ValueError("Units CSV is empty (no header row)") diff --git a/tests/test_csv_templates.py b/tests/test_csv_templates.py new file mode 100644 index 0000000..0c04463 --- /dev/null +++ b/tests/test_csv_templates.py @@ -0,0 +1,46 @@ +"""The CSV files `template-csv` writes are read by inject and fleet. + +The templates put '#' comment lines under the header, which the readers +took as data: the frequencies and units readers failed on them ("could +not convert string to float: '# Example: 806.0125'") and the channels +reader imported the comment as a channel. +""" + +from quickprs.cli import ( + cmd_template_csv, _parse_freq_csv, _parse_tgs_csv, _parse_conv_csv, +) +from quickprs.fleet import _parse_units_csv + + +def _template(tmp_path, kind, rows): + path = tmp_path / f"{kind}.csv" + assert cmd_template_csv(kind, str(path)) == 0 + with open(path, "a", encoding="utf-8") as f: + f.writelines(row + "\n" for row in rows) + return path + + +def test_frequencies(tmp_path): + path = _template(tmp_path, "frequencies", + ["806.0125,851.0125", "", "806.5125,851.5125"]) + assert _parse_freq_csv(path) == [(806.0125, 851.0125), + (806.5125, 851.5125)] + + +def test_talkgroups(tmp_path): + path = _template(tmp_path, "talkgroups", + ["1000,PD DISP,Police Dispatch,false,true"]) + assert _parse_tgs_csv(path) == [ + (1000, "PD DISP", "Police Dispatch", False, True)] + + +def test_channels(tmp_path): + path = _template(tmp_path, "channels", + ["SIMPLEX,146.520,146.520,,,Simplex"]) + assert [c["short_name"] for c in _parse_conv_csv(path)] == ["SIMPLEX"] + + +def test_units(tmp_path): + path = _template(tmp_path, "units", ["1001,UNIT-1001,1234"]) + assert _parse_units_csv(path) == [ + {"unit_id": 1001, "name": "UNIT-1001", "password": "1234"}] From 4217432f8d1dce6b03023958084a5b9128884ec2 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:10:37 -0700 Subject: [PATCH 14/22] Validation: check frequencies against the XG-100P's bands Frequencies were checked against 30-960 MHz, so a channel at 220, 300 or 900 MHz passed although the radio tunes only 136-174, 380-520 and 762-870 MHz; the band edges were in the limits table but unused, and the error message called 30-960 MHz the XG-100P's range. --- quickprs/validation.py | 41 +++++++++++++++++++++++++-------------- tests/test_integration.py | 41 ++++++++++++++++++--------------------- tests/test_validation.py | 22 ++++++++++++++++++++- 3 files changed, 66 insertions(+), 38 deletions(-) diff --git a/quickprs/validation.py b/quickprs/validation.py index 58cd380..60ed6a0 100644 --- a/quickprs/validation.py +++ b/quickprs/validation.py @@ -55,11 +55,12 @@ 'long_name_max': 16, 'talkgroup_id_max': 65535, # uint16 - # XG-100P frequency range - 'freq_min_mhz': 30.0, - 'freq_max_mhz': 960.0, + # Lowest and highest frequency of any band below + 'freq_min_mhz': 136.0, + 'freq_max_mhz': 870.0, - # XG-100P band edges (VHF, UHF, 700/800) + # XG-100P bands (VHF, UHF, 700/800); the radio tunes nothing between + # them (L3Harris lists the same bands for the XG-100M mobile) 'vhf_min': 136.0, 'vhf_max': 174.0, 'uhf_min': 380.0, 'uhf_max': 520.0, 'band_700_min': 762.0, 'band_800_max': 870.0, @@ -69,6 +70,19 @@ } +RADIO_BANDS = ( + (LIMITS['vhf_min'], LIMITS['vhf_max']), + (LIMITS['uhf_min'], LIMITS['uhf_max']), + (LIMITS['band_700_min'], LIMITS['band_800_max']), +) +BANDS_TEXT = ", ".join(f"{lo:g}-{hi:g}" for lo, hi in RADIO_BANDS) + " MHz" + + +def in_radio_bands(freq_mhz): + """True when the XG-100P can tune the frequency.""" + return any(lo <= freq_mhz <= hi for lo, hi in RADIO_BANDS) + + # Severity levels ERROR = 'ERROR' # will cause malfunction WARNING = 'WARNING' # may cause issues @@ -280,16 +294,14 @@ def validate_trunk_set(trunk_set): f"{trunk_set.rx_max:.1f}. Verify the frequency is correct " f"or update the IDEN band limits.")) - # Check absolute frequency range + # Check the radio's bands for ch in trunk_set.channels: for freq in (ch.tx_freq, ch.rx_freq): - if freq < LIMITS['freq_min_mhz'] or freq > LIMITS['freq_max_mhz']: + if not in_radio_bands(freq): issues.append((ERROR, - f"Trunk set '{name}' freq {freq:.5f} MHz outside " - f"XG-100P range ({LIMITS['freq_min_mhz']}-" - f"{LIMITS['freq_max_mhz']} MHz). " - f"Remove this frequency or correct it to a valid " - f"XG-100P band.")) + f"Trunk set '{name}' freq {freq:.5f} MHz is outside " + f"the XG-100P's bands ({BANDS_TEXT}). " + f"Remove this frequency or correct it.")) # 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 @@ -337,13 +349,12 @@ def validate_conv_set(conv_set): issues.extend(_validate_name_lengths( ch.short_name, ch.long_name, f"channel '{ch.short_name}'")) - # Check frequency range + # Check the radio's bands for freq in (ch.tx_freq, ch.rx_freq): - if freq < LIMITS['freq_min_mhz'] or freq > LIMITS['freq_max_mhz']: + if not in_radio_bands(freq): issues.append((ERROR, f"Conv channel '{ch.short_name}' freq {freq:.5f} MHz " - f"outside XG-100P range ({LIMITS['freq_min_mhz']}-" - f"{LIMITS['freq_max_mhz']} MHz). " + f"is outside the XG-100P's bands ({BANDS_TEXT}). " f"Correct the frequency or remove this channel.")) # Check tone format diff --git a/tests/test_integration.py b/tests/test_integration.py index f34da55..3db6659 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -1226,26 +1226,23 @@ def test_unicode_names(self): pass def test_frequency_boundaries(self): - """Test channels at 30 MHz (min) and 960 MHz (max XG-100P range).""" - from quickprs.validation import validate_trunk_set, validate_conv_set, LIMITS - - # Exactly at boundaries — should pass - tset_ok = make_trunk_set("BOUNDOK", [ - (LIMITS['freq_min_mhz'], LIMITS['freq_min_mhz']), - (LIMITS['freq_max_mhz'], LIMITS['freq_max_mhz']), - ]) - issues = validate_trunk_set(tset_ok) - freq_errors = [i for i in issues if i[0] == ERROR and "range" in i[1].lower()] - assert len(freq_errors) == 0, f"Boundary freqs should be valid: {freq_errors}" - - # Just outside boundaries — should fail - tset_bad = make_trunk_set("BOUNDBAD", [ - (29.999, 29.999), - (960.001, 960.001), - ]) - issues = validate_trunk_set(tset_bad) - freq_errors = [i for i in issues if i[0] == ERROR and "range" in i[1].lower()] - assert len(freq_errors) >= 2, "Freqs outside 30-960 MHz should error" + """Band edges (136-174, 380-520, 762-870 MHz) pass; just outside + each edge fails.""" + from quickprs.validation import validate_trunk_set, RADIO_BANDS + + edges = [f for band in RADIO_BANDS for f in band] + issues = validate_trunk_set(make_trunk_set( + "BOUNDOK", [(f, f) for f in edges])) + freq_errors = [i for i in issues if i[0] == ERROR and "bands" in i[1]] + assert freq_errors == [], f"Band edges should be valid: {freq_errors}" + + outside = ([lo - 0.001 for lo, _ in RADIO_BANDS] + + [hi + 0.001 for _, hi in RADIO_BANDS]) + issues = validate_trunk_set(make_trunk_set( + "BOUNDBAD", [(f, f) for f in outside])) + freq_errors = [i for i in issues if i[0] == ERROR and "bands" in i[1]] + # each channel's TX and RX + assert len(freq_errors) == 2 * len(outside) def test_zero_frequency(self): """Inject a channel with 0.0 MHz, check validation catches it.""" @@ -1253,8 +1250,8 @@ def test_zero_frequency(self): tset = make_trunk_set("ZEROF", [(0.0, 0.0)]) issues = validate_trunk_set(tset) - freq_errors = [i for i in issues if i[0] == ERROR and "range" in i[1].lower()] - assert len(freq_errors) >= 1, "0.0 MHz should be caught as out-of-range" + freq_errors = [i for i in issues if i[0] == ERROR and "bands" in i[1]] + assert len(freq_errors) >= 1, "0.0 MHz should be caught as out-of-band" @pytest.mark.skipif(not CLAUDE.exists(), reason="Test PRS data not available") def test_duplicate_talkgroup_ids_different_sets(self): diff --git a/tests/test_validation.py b/tests/test_validation.py index 83d5e27..87a982b 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -175,7 +175,27 @@ def test_validate_trunk_set_out_of_band(): ], tx_min=10.0, tx_max=10.0, rx_min=10.0, rx_max=10.0) issues = validate_trunk_set(ts) errors = [msg for sev, msg in issues if sev == ERROR] - assert any("outside XG-100P range" in e for e in errors) + assert any("outside the XG-100P's bands" in e for e in errors) + + +@pytest.mark.parametrize("freq", [100.0, 220.0, 300.0, 600.0, 900.0]) +def test_between_the_radios_bands_is_an_error(freq): + """The check was 30-960 MHz, so 220 or 900 MHz passed although the + XG-100P tunes only 136-174, 380-520 and 762-870 MHz.""" + from quickprs.injector import make_conv_set + issues = validate_conv_set(make_conv_set("OOB", [ + {"short_name": "X", "tx_freq": freq}])) + assert any(sev == ERROR and "XG-100P's bands" in msg + for sev, msg in issues) + + +@pytest.mark.parametrize("freq", [136.0, 155.76, 174.0, 380.0, 453.2125, + 520.0, 762.0, 806.0125, 851.0125, 870.0]) +def test_inside_the_radios_bands_is_fine(freq): + from quickprs.injector import make_conv_set + issues = validate_conv_set(make_conv_set("IN", [ + {"short_name": "X", "tx_freq": freq}])) + assert not any("bands" in msg for _, msg in issues) # ─── validate_conv_set ─────────────────────────────────────────────── From 5b67e69c6e3dc13e1625276c1eefeb095f36bdeb Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:17:30 -0700 Subject: [PATCH 15/22] Test: the channels template's example text changed --- tests/test_wizard.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_wizard.py b/tests/test_wizard.py index 3d6c75a..9418a96 100644 --- a/tests/test_wizard.py +++ b/tests/test_wizard.py @@ -102,7 +102,7 @@ def test_has_example(self, tmp_path): out = str(tmp_path / "channels.csv") cmd_template_csv("channels", output=out) content = Path(out).read_text(encoding='utf-8') - assert "RPT IN" in content + assert "# Example: RPT 147" in content class TestTemplateCsvUnits: From 511fb5cd2da99aa849d24cf388dd0c3323198bed Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:17:30 -0700 Subject: [PATCH 16/22] INI export: keep channel flags; templates only when they match exactly export-config wrote inline channels without narrowband, TX-off or scan-off, so PAWSOVERMAWS's FURRY NB set came back from build as 25 kHz channels, and it wrote 'template = X' for any set with a template's frequencies, so a MURS set programmed wide (WA WIDE) would build narrowband with the template's names. Inline channel lines take an optional seventh field of flags (nb, rxonly, noscan), and a set is written as a template only when the template builds it back exactly. --- quickprs/config_builder.py | 77 ++++++++++++++++++++++++------- tests/test_export_config.py | 90 ++++++++++++++++++++++++++++--------- 2 files changed, 132 insertions(+), 35 deletions(-) diff --git a/quickprs/config_builder.py b/quickprs/config_builder.py index c69a16a..2d99def 100644 --- a/quickprs/config_builder.py +++ b/quickprs/config_builder.py @@ -306,11 +306,34 @@ def _get_channel_sections(cfg): return channels +# Channel flags an inline channel line may end with (space-separated), +# and the channel field each sets +_CHANNEL_FLAGS = { + 'nb': ('narrowband', True), # 12.5 kHz channel + 'rxonly': ('tx', False), # transmit off + 'noscan': ('scan', False), # left out of scan +} + + +def _channel_flags(ch): + """The flag words for a channel dict (empty when all are default).""" + words = [] + if ch.get('narrowband'): + words.append('nb') + if ch.get('tx', True) is False: + words.append('rxonly') + if ch.get('scan', True) is False: + words.append('noscan') + return " ".join(words) + + def _parse_inline_channels(section_dict): """Parse inline channel definitions from a channels section. Lines that look like channel data (contain a frequency) are parsed. - Format: short_name,tx_freq,rx_freq,tx_tone,rx_tone,long_name + Format: short_name,tx_freq,rx_freq,tx_tone,rx_tone,long_name[,flags] + where flags is any of "nb" (narrowband), "rxonly" and "noscan", + separated by spaces. Returns list of channel dicts. """ @@ -331,14 +354,22 @@ def _parse_inline_channels(section_dict): tx_tone = parts[3] if len(parts) > 3 else '' rx_tone = parts[4] if len(parts) > 4 else '' long_name = parts[5][:16] if len(parts) > 5 else short - channels.append({ + channel = { 'short_name': short, 'tx_freq': tx, 'rx_freq': rx, 'tx_tone': tx_tone, 'rx_tone': rx_tone, 'long_name': long_name, - }) + } + for word in (parts[6].lower().split() if len(parts) > 6 else []): + if word not in _CHANNEL_FLAGS: + raise ConfigError( + f"channel '{short}': unknown flag '{word}' " + f"(use {', '.join(_CHANNEL_FLAGS)})") + field, value = _CHANNEL_FLAGS[word] + channel[field] = value + channels.append(channel) except (ValueError, IndexError): continue return channels @@ -567,8 +598,11 @@ def export_config(prs, filepath, source_path=None): tx_tone = ch.get("tx_tone", "") rx_tone = ch.get("rx_tone", "") long_n = ch.get("long_name", short).strip() - lines.append( - f"{i} = {short},{tx},{rx},{tx_tone},{rx_tone},{long_n}") + line = f"{i} = {short},{tx},{rx},{tx_tone},{rx_tone},{long_n}" + flags = _channel_flags(ch) + if flags: + line += f",{flags}" + lines.append(line) lines.append("") # Options from platformConfig @@ -598,27 +632,40 @@ def _build_template_cache(): cache = {} for name in get_template_names(): try: - channels = get_template_channels(name) - freqs = sorted(round(ch["tx_freq"], 6) for ch in channels) - cache[name] = freqs + from .injector import make_conv_set + from .json_io import _conv_set_to_dict + built = make_conv_set(name, get_template_channels(name)) + cache[name] = _template_key( + _conv_set_to_dict(built)["channels"]) except Exception: continue return cache +def _template_key(channels): + """What a 'template = X' line rebuilds of each channel: names, + frequencies, tones and flags.""" + return sorted( + (ch.get("short_name", "").strip(), ch.get("long_name", "").strip(), + round(ch["tx_freq"], 6), round(ch.get("rx_freq", ch["tx_freq"]), 6), + ch.get("tx_tone", ""), ch.get("rx_tone", ""), + bool(ch.get("narrowband")), ch.get("tx", True), ch.get("scan", True)) + for ch in channels) + + def _detect_template(channels, template_cache): - """Check if a set of channels matches a built-in template. + """Check if a set of channels is exactly a built-in template. - Compares the sorted TX frequencies of the channel set against - each template. Returns the template name if matched, else None. + Only then can the export say 'template = X': building from the + template gives back the same names, frequencies, tones and flags. + Returns the template name if matched, else None. """ if not channels: return None - ch_freqs = sorted(round(ch["tx_freq"], 6) for ch in channels) - - for name, template_freqs in template_cache.items(): - if ch_freqs == template_freqs: + key = _template_key(channels) + for name, template_key in template_cache.items(): + if key == template_key: return name return None diff --git a/tests/test_export_config.py b/tests/test_export_config.py index cf4436c..5467a97 100644 --- a/tests/test_export_config.py +++ b/tests/test_export_config.py @@ -391,38 +391,50 @@ def test_build_template_cache(self): assert 'noaa' in cache assert 'gmrs' in cache + @staticmethod + def _exported(name): + """A template's channels as export_config sees them.""" + from quickprs.injector import make_conv_set + from quickprs.json_io import _conv_set_to_dict + from quickprs.templates import get_template_channels + return _conv_set_to_dict( + make_conv_set(name, get_template_channels(name)))["channels"] + def test_detect_murs(self): """MURS channels are detected as murs template.""" - from quickprs.templates import get_template_channels - channels = get_template_channels('murs') - cache = _build_template_cache() - ch_dicts = [{'tx_freq': ch['tx_freq']} for ch in channels] - result = _detect_template(ch_dicts, cache) - assert result == 'murs' + assert _detect_template(self._exported('murs'), + _build_template_cache()) == 'murs' def test_detect_noaa(self): """NOAA channels are detected as noaa or weather template.""" - from quickprs.templates import get_template_channels - channels = get_template_channels('noaa') - cache = _build_template_cache() - ch_dicts = [{'tx_freq': ch['tx_freq']} for ch in channels] - result = _detect_template(ch_dicts, cache) + result = _detect_template(self._exported('noaa'), + _build_template_cache()) assert result in ('noaa', 'weather') - def test_detect_gmrs_or_frs(self): - """GMRS channels match gmrs or frs (identical frequencies).""" - from quickprs.templates import get_template_channels - channels = get_template_channels('gmrs') + def test_detect_gmrs(self): + """GMRS and FRS share frequencies but not names or bandwidths.""" cache = _build_template_cache() - ch_dicts = [{'tx_freq': ch['tx_freq']} for ch in channels] - result = _detect_template(ch_dicts, cache) - # GMRS and FRS have identical frequencies, either match is valid - assert result in ('gmrs', 'frs') + assert _detect_template(self._exported('gmrs'), cache) == 'gmrs' + assert _detect_template(self._exported('frs'), cache) == 'frs' + + def test_same_frequencies_other_flags_is_not_the_template(self): + """A MURS set programmed wide (as PAWSOVERMAWS's WA WIDE is) used + to export as 'template = murs', which builds MURS 1-3 narrowband.""" + channels = self._exported('murs') + for ch in channels: + ch.pop('narrowband', None) + assert _detect_template(channels, _build_template_cache()) is None + + def test_same_frequencies_other_names_is_not_the_template(self): + channels = self._exported('murs') + channels[0]['long_name'] = 'MY MURS' + assert _detect_template(channels, _build_template_cache()) is None def test_detect_custom_no_match(self): """Custom channels do not match any template.""" cache = _build_template_cache() - custom = [{'tx_freq': 462.123}, {'tx_freq': 462.456}] + custom = [{'short_name': 'A', 'tx_freq': 462.123}, + {'short_name': 'B', 'tx_freq': 462.456}] result = _detect_template(custom, cache) assert result is None @@ -804,3 +816,41 @@ def test_blank_no_systems(self, tmp_path): export_config(prs, str(out)) content = out.read_text(encoding='utf-8') assert "[system." not in content + + +class TestInlineChannelFlags: + """Inline channels lost narrowband, TX off and scan off: PAWSOVERMAWS's + FURRY NB set came back wideband from export-config + build.""" + + def test_flags_round_trip(self, tmp_path): + from quickprs.builder import create_blank_prs + from quickprs.config_builder import build_from_config, export_config + from quickprs.injector import add_conv_set, make_conv_set + from quickprs.json_io import prs_to_dict + prs = create_blank_prs("flags.PRS") + add_conv_set(prs, make_conv_set("MIXED", [ + {"short_name": "NB", "tx_freq": 151.625, "narrowband": True}, + {"short_name": "RX", "tx_freq": 162.55, "tx": False}, + {"short_name": "NOSCAN", "tx_freq": 154.57, "scan": False}, + {"short_name": "PLAIN", "tx_freq": 146.52}, + ])) + ini = tmp_path / "flags.ini" + export_config(prs, ini) + assert "1 = NB,151.625,151.625,,,NB,nb" in ini.read_text() + back = prs_to_dict(build_from_config(ini)) + chans = {c["short_name"]: c for c in next( + s for s in back["conv_sets"] if s["name"] == "MIXED")["channels"]} + assert chans["NB"].get("narrowband") is True + assert chans["RX"]["tx"] is False + assert chans["NOSCAN"]["scan"] is False + assert (chans["PLAIN"].get("narrowband"), chans["PLAIN"]["tx"], + chans["PLAIN"]["scan"]) == (None, True, True) + + def test_unknown_flag_is_an_error(self, tmp_path): + from quickprs.config_builder import build_from_config, ConfigError + ini = tmp_path / "bad.ini" + ini.write_text("[channels.X]\n1 = A,146.52,146.52,,,A,wide\n", + encoding="utf-8") + with pytest.raises(ConfigError, match="unknown flag 'wide'"): + build_from_config(ini) + From 2a28428a85248f7932d3cf35bf84847c2c5225cf Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:17:31 -0700 Subject: [PATCH 17/22] New analog channels get the values RPM gives every channel RPM writes 85 in both tone address fields and sets the flag QuickPRS calls tone mode in every analog channel it creates, with or without tones (280 of the 285 channels in the test files; the other five are a set QuickPRS 1.0 made). QuickPRS wrote 0, 0 and off. What the fields mean is not known, so new channels now match RPM's. --- quickprs/record_types.py | 9 ++++++--- tests/test_record_types.py | 29 +++++++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/quickprs/record_types.py b/quickprs/record_types.py index c8f8cb9..d97fe18 100644 --- a/quickprs/record_types.py +++ b/quickprs/record_types.py @@ -230,8 +230,11 @@ class ConvChannel: rx_freq: float # MHz tx_tone: str = "" # CTCSS/DCS tone string (e.g., "250.3", "" for none) rx_tone: str = "" - tx_addr: int = 0 # uint16, tone address code - rx_addr: int = 0 # uint16 + # tx_addr, rx_addr and tone_mode: RPM writes 85, 85 and 1 in every + # analog channel it creates, with or without tones (their meaning + # is not known); new channels get the same + tx_addr: int = 85 # uint16 + rx_addr: int = 85 # uint16 # Decoded flag fields (from 48-byte flags block) flag0: bool = False # byte 0: 1 for MURS/VHF channels @@ -239,7 +242,7 @@ class ConvChannel: calls: bool = True # byte 2: call alert enable alert: bool = True # byte 3: alert tone enable scan_list_member: bool = True # byte 4: scan list membership - tone_mode: bool = False # byte 22: 1 when CTCSS/DCS active + tone_mode: bool = True # byte 22: set by RPM on every channel narrowband: bool = False # byte 27: 1=12.5kHz, 0=25kHz scan: bool = True # byte 29: scan enable tx: bool = True # byte 46: transmit enable diff --git a/tests/test_record_types.py b/tests/test_record_types.py index 1b6afd3..7c412ba 100644 --- a/tests/test_record_types.py +++ b/tests/test_record_types.py @@ -1275,13 +1275,15 @@ def test_default_flags_pattern(self): f = ch.flags assert len(f) == 48 # Defaults: rx=True, calls=True, alert=True, slm=True, scan=True, tx=True - # flag0=False, tone_mode=False, narrowband=False + # flag0=False, narrowband=False; tone_mode=True and both addresses + # 85, as RPM writes in every analog channel it creates assert f[0] == 0 # flag0 assert f[1] == 1 # rx assert f[2] == 1 # calls assert f[3] == 1 # alert assert f[4] == 1 # scan_list_member - assert f[22] == 0 # tone_mode + assert f[22] == 1 # tone_mode + assert (ch.tx_addr, ch.rx_addr) == (85, 85) assert f[27] == 0 # narrowband assert f[29] == 1 # scan assert f[46] == 1 # tx @@ -2398,3 +2400,26 @@ def main(): if __name__ == "__main__": sys.exit(main()) + + +def test_new_channels_match_rpms(): + """RPM writes tx_addr 85, rx_addr 85 and the tone mode flag in every + analog channel it creates, with or without tones; QuickPRS wrote 0, 0 + and off.""" + from conftest import cached_parse_prs + from quickprs.injector import make_conv_channel + paws = Path(__file__).parent / "testdata" / "PAWSOVERMAWS.PRS" + if not paws.exists(): + pytest.skip("Test PRS data not available") + prs = cached_parse_prs(paws) + rpm_made = [ch for s in parse_sets_from_sections( + prs.get_section_by_class("CConvSet").raw, + prs.get_section_by_class("CConvChannel").raw, + parse_conv_channel_section) + if s.name in ("FURRY NB", "FURRY WB") for ch in s.channels] + assert rpm_made + ours = [make_conv_channel("A", 151.625), + make_conv_channel("B", 462.5625, tx_tone="250.3", + rx_tone="250.3", narrowband=True)] + for ch in rpm_made + ours: + assert (ch.tx_addr, ch.rx_addr, ch.tone_mode) == (85, 85, True) From ce51e3df6c2fa257b6185aec0fb86fcced409b51 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:20:29 -0700 Subject: [PATCH 18/22] Validation: no warnings for what RPM itself writes; docs Validation warned about a trunk set and a talkgroup set sharing a name, which is how RPM names them (four such pairs in PAWSOVERMAWS), and about PTCT, RPM's default 2-position switch function (33 of the 36 test files). Duplicate names are now reported within one set type only, and PTCT is a known switch function. README: the inline channel flags, and what a config file keeps compared with JSON. Format notes: the analog channel fields RPM always sets. --- README.md | 12 ++++++++- docs/prs-format.md | 6 +++++ quickprs/option_maps.py | 1 + quickprs/validation.py | 19 +++++++------ tests/test_validation.py | 58 +++++++++++++++++++++++++--------------- 5 files changed, 65 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 4312772..06826f2 100644 --- a/README.md +++ b/README.md @@ -252,9 +252,12 @@ template = noaa template = interop [channels.LOCAL] -; short_name, tx_freq, rx_freq, tx_tone, rx_tone, long_name +; short_name, tx_freq, rx_freq, tx_tone, rx_tone, long_name[, flags] +; flags: any of nb (narrowband), rxonly, noscan 1 = RPT 147,147.600,147.000,100.0,100.0,147.00+ Repeater 2 = SIMPLEX,146.520,146.520,,,2m Calling +3 = MURS 1,151.820,151.820,,,MURS 1,nb +4 = NOAA WX,162.550,162.550,,,NOAA Seattle,rxonly noscan [options] gps.gpsMode = ON @@ -264,6 +267,13 @@ misc.password = 1234 Build with: `quickprs build patrol.ini -o patrol.PRS` +A config file is a recipe, not a copy: `export-config` writes what `build` +can make (systems with their IDs, frequencies and talkgroups, channels with +their tones and flags, radio options). `build` makes IDEN tables from the +frequencies and gives each system its own sets, and other settings take +their defaults. For a complete copy that imports back byte for byte, use +`export-json` and `import-json`. + ## Built-in Templates | Template | Channels | Description | diff --git a/docs/prs-format.md b/docs/prs-format.md index 1c242ef..bf9dbdb 100644 --- a/docs/prs-format.md +++ b/docs/prs-format.md @@ -84,6 +84,12 @@ been checked against RPM: 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. +- **Analog channel fields RPM always sets:** every analog channel RPM + creates, with or without tones, holds 85 in both 2-byte fields after the + tone strings (QuickPRS calls them `tx_addr` and `rx_addr`) and 1 in flag + byte 22 (`tone_mode`). QuickPRS 1.2 and later write the same in new + channels; earlier versions wrote 0, 0 and 0, and what difference that + makes on the radio is not known. 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/quickprs/option_maps.py b/quickprs/option_maps.py index 5bd4ac2..00e6d2e 100644 --- a/quickprs/option_maps.py +++ b/quickprs/option_maps.py @@ -3700,6 +3700,7 @@ class XmlFieldDef: "CHAN_BANK": "Channel Bank", "ZONE": "Zone", "TALKAROUND": "Talkaround", + "PTCT": "PTCT", # RPM's default for the 2-position switch } diff --git a/quickprs/validation.py b/quickprs/validation.py index 60ed6a0..b370f1d 100644 --- a/quickprs/validation.py +++ b/quickprs/validation.py @@ -962,7 +962,9 @@ def _validate_system_counts(prs): def _check_duplicate_set_names(prs, issues): - """Detect duplicate set names across all set types.""" + """Detect two sets of one type with the same name. Systems name their + trunk, talkgroup and IDEN sets separately, so a trunk set and a + talkgroup set may share a name (RPM names them that way).""" set_names = {} # name -> list of type labels for cls, label, parser_fn in [ @@ -986,13 +988,14 @@ def _check_duplicate_set_names(prs, issues): set_names.setdefault(s.name, []).append(label) for name, types in set_names.items(): - if len(types) > 1: - labels = ", ".join(types) - issues.append((WARNING, - f"Duplicate set name '{name}' used by: {labels}. " - "RPM may confuse references. Rename one of the sets " - "with 'quickprs edit --rename-set " - f"\"{name}\" '.")) + for label in sorted(set(types)): + count = types.count(label) + if count > 1: + issues.append((WARNING, + f"Duplicate set name '{name}': {count} {label} sets. " + "RPM may confuse references. Rename one of the sets " + "with 'quickprs edit --rename-set " + f"\"{name}\" '.")) diff --git a/tests/test_validation.py b/tests/test_validation.py index 87a982b..72c3b32 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -430,30 +430,44 @@ def test_validate_combined_channel_limit(): assert len(combined_issues) == 0 -def test_validate_duplicate_set_names(): - """Duplicate set names across types produce warnings.""" - if not CLAUDE_PRS.exists(): - pytest.skip("test file not found") - from quickprs.injector import add_p25_trunked_system, make_group_set, make_trunk_set +def test_trunk_and_group_sets_may_share_a_name(): + """Systems name their trunk and talkgroup sets separately, and RPM + gives them one name (PAWSOVERMAWS: WASP, NNSS, SNACC, NSRS); this used + to be reported as a duplicate.""" + from quickprs.builder import create_blank_prs + from quickprs.injector import (add_p25_trunked_system, make_group_set, + make_trunk_set) from quickprs.record_types import P25TrkSystemConfig - prs = cached_parse_prs(CLAUDE_PRS) - # Inject a system where trunk and group sets share the name "DUPE" + prs = create_blank_prs() config = P25TrkSystemConfig( - system_name="DUPE", - long_name="DUPE TEST", - trunk_set_name="DUPE", - group_set_name="DUPE", - wan_name="DUPEWAN", - home_unit_id=100, - system_id=555, - ) - gs = make_group_set("DUPE", [(100, "TG1", "TEST TG")]) - ts = make_trunk_set("DUPE", [(851.0125, 806.0125)]) - add_p25_trunked_system(prs, config, group_set=gs, trunk_set=ts) - issues = validate_prs(prs) - dup_issues = [m for _, m in issues if "Duplicate set name" in m] - assert len(dup_issues) >= 1 - assert "DUPE" in dup_issues[0] + system_name="SAME", long_name="SAME TEST", trunk_set_name="SAME", + group_set_name="SAME", wan_name="SAME", system_id=555) + add_p25_trunked_system( + prs, config, group_set=make_group_set("SAME", [(100, "TG1", "TG")]), + trunk_set=make_trunk_set("SAME", [(806.0125, 851.0125)])) + assert not [m for _, m in validate_prs(prs) if "Duplicate set" in m] + + +def test_two_sets_of_one_type_with_one_name_warn(): + from quickprs.builder import create_blank_prs + from quickprs.injector import _write_set_list, make_conv_set + prs = create_blank_prs() + _write_set_list(prs, "conv sets", [ + make_conv_set("DUPE", [{"short_name": "A", "tx_freq": 151.625}]), + make_conv_set("DUPE", [{"short_name": "B", "tx_freq": 154.57}])]) + dups = [m for _, m in validate_prs(prs) if "Duplicate set" in m] + assert dups == [dups[0]] and "'DUPE': 2 conv sets" in dups[0] + + +def test_rpm_file_has_no_false_warnings(): + """Neither the shared set names nor RPM's default 2-position switch + function (PTCT) is a problem.""" + paws = Path(__file__).parent / "testdata" / "PAWSOVERMAWS.PRS" + if not paws.exists(): + pytest.skip("test file not found") + messages = [m for _, m in validate_prs(cached_parse_prs(paws))] + assert not [m for m in messages if "Duplicate set" in m] + assert not [m for m in messages if "not a known switch" in m] def test_validate_zone_advisory_large_group_set(): From acc8f2ac36b7be1812ca6711f9bf0498f650b43e Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:25:38 -0700 Subject: [PATCH 19/22] GUI: trunk channel edits find the channel by its index, not its row With the search in filter mode, rows that do not match are detached, so a trunk channel row's place among its visible siblings is not the channel's place in its set. Inline frequency edits, Move Up/Down and the context menu used that place, so they changed or moved another channel (the first one, when the row was not found). Trunk channel rows now carry their channel index, as conventional channel rows already did. --- quickprs/gui/personality_view.py | 20 +++++++--------- tests/test_gui_smoke.py | 41 ++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 11 deletions(-) diff --git a/quickprs/gui/personality_view.py b/quickprs/gui/personality_view.py index 2824812..48ca615 100644 --- a/quickprs/gui/personality_view.py +++ b/quickprs/gui/personality_view.py @@ -657,21 +657,24 @@ def _add_trunk_sets(self, parent, prs): meta={"type": "trunk_set", "name": tset.name, "set_data": tset}) - for ch in tset.channels: + # ch_idx: the channel's place in its set (a row's place among + # its visible siblings differs while the search filters rows) + for ch_idx, ch in enumerate(tset.channels): if ch.tx_freq == ch.rx_freq: self._insert( set_node, tk.END, text=f"{ch.tx_freq:.5f} MHz", values=("simplex",), meta={"type": "trunk_channel", - "freq": ch.tx_freq}) + "freq": ch.tx_freq, "ch_idx": ch_idx}) else: self._insert( set_node, tk.END, text=f"TX:{ch.tx_freq:.5f}", values=(f"RX:{ch.rx_freq:.5f} MHz",), meta={"type": "trunk_channel", - "tx": ch.tx_freq, "rx": ch.rx_freq}) + "tx": ch.tx_freq, "rx": ch.rx_freq, + "ch_idx": ch_idx}) def _add_group_sets(self, parent, prs): """Add group set nodes with talkgroups.""" @@ -2223,8 +2226,7 @@ def _on_right_click(self, event): parent_iid = self.tree.parent(iid) parent_meta = self._item_meta.get(parent_iid, {}) set_name = parent_meta.get("name", "") - siblings = list(self.tree.get_children(parent_iid)) - ch_idx = siblings.index(iid) if iid in siblings else 0 + ch_idx = meta.get("ch_idx", 0) freq = meta.get("freq") or meta.get("tx", "") self.ctx_menu.add_command( label="Move Up", @@ -3909,9 +3911,7 @@ def _move_selected(self, direction): parent_iid = self.tree.parent(iid) parent_meta = self._item_meta.get(parent_iid, {}) set_name = parent_meta.get("name", "") - # Get index from tree position - siblings = list(self.tree.get_children(parent_iid)) - ch_idx = siblings.index(iid) if iid in siblings else None + ch_idx = meta.get("ch_idx") if set_name and ch_idx is not None: self._move_trunk_channel(set_name, ch_idx, direction) elif item_type == "group_set": @@ -4726,9 +4726,7 @@ def _commit_inline_edit(self, iid, meta, new_val, max_len): self._inline_edit_conv_channel( prs, set_name, meta.get("ch_idx"), new_val, max_len) elif item_type == "trunk_channel": - # Get channel index from tree position - siblings = list(self.tree.get_children(parent_iid)) - ch_idx = siblings.index(iid) if iid in siblings else None + ch_idx = meta.get("ch_idx") if ch_idx is not None: self._inline_edit_trunk_freq( prs, set_name, ch_idx, new_val) diff --git a/tests/test_gui_smoke.py b/tests/test_gui_smoke.py index 3c42950..da2b1f5 100644 --- a/tests/test_gui_smoke.py +++ b/tests/test_gui_smoke.py @@ -135,3 +135,44 @@ def test_import_wizard_injects_into_blank(app): ImportWizard._inject_talkgroups(fake, "TGS", [ {"group_id": 100, "short_name": "TG100", "long_name": "TG 100"}]) assert archive.check(app.prs) == [] + + +def test_trunk_edit_while_filtered_hits_the_right_channel(app, tmp_path): + """The search's filter mode detaches rows that do not match, so a + row's place among its visible siblings is not its channel's place in + the set: editing the second channel while the first was hidden changed + the first.""" + from quickprs import injector + from quickprs.builder import create_blank_prs + from quickprs.prs_writer import write_prs + from quickprs.record_types import P25TrkSystemConfig + prs = create_blank_prs("trunk.PRS") + injector.add_p25_trunked_system( + prs, P25TrkSystemConfig(system_name="CITY", long_name="CITY", + trunk_set_name="CITY", group_set_name="CITY", + wan_name="CITY"), + trunk_set=injector.make_trunk_set("CITY", [ + (806.0125, 851.0125), (806.5125, 851.5125), + (807.0125, 852.0125)]), + group_set=injector.make_group_set("CITY", [(1, "TG", "TG")])) + path = tmp_path / "trunk.PRS" + write_prs(prs, path) + app._open_path(path, confirmed=True) + + pv = app.personality_view + pv._filter_mode.set(True) + pv.search_var.set("851.5125") # only the second channel shows + iid, meta = next((i, m) for i, m in pv._item_meta.items() + if m.get("type") == "trunk_channel" + and m.get("rx") == 851.5125) + assert pv.tree.index(iid) == 0 # first among visible rows + with mock.patch("quickprs.gui.personality_view.messagebox"): + pv._commit_inline_edit(iid, meta, "806.525", 16) + + from quickprs.record_types import parse_trunk_channel_section + channels = next(s for s in injector._parse_section_data( + app.prs.get_section_by_class("CTrunkChannel"), + parse_trunk_channel_section, + injector._get_first_count(app.prs, "CTrunkSet")) + if s.name == "CITY").channels + assert [c.tx_freq for c in channels] == [806.0125, 806.525, 807.0125] From 00c9b44579ee4f7d4614f6e7c3c5d5f05daf1876 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:30:59 -0700 Subject: [PATCH 20/22] Renaming a set renames its references; GUI P25 and IDEN fixes Systems find their trunk, talkgroup, IDEN and channel sets by name, and a P25 conventional set may name a talkgroup set. The rename functions changed only the set, so edit --rename-set (which validation suggests for duplicate names) and the GUI's rename left the system naming a set that no longer existed. One rename on the archive tree now changes the set and every reference, refuses a name already in use, and covers IDEN and P25 conventional sets too (edit --rename-set iden|p25conv). GUI: Export to CSV on a P25 conventional set wrote an empty file; it writes P25_CONV_SET.csv. The NAC editor and IDEN set delete spliced raw sections the 1.0 way; they use the archive helpers. Deleting a set now names the systems that use it before asking. --- quickprs/cli.py | 33 ++-- quickprs/gui/personality_view.py | 306 +++++-------------------------- quickprs/injector.py | 236 ++++++++++++------------ tests/test_gui_smoke.py | 51 ++++++ tests/test_rename_references.py | 126 +++++++++++++ 5 files changed, 365 insertions(+), 387 deletions(-) create mode 100644 tests/test_rename_references.py diff --git a/quickprs/cli.py b/quickprs/cli.py index e0579ae..1724051 100644 --- a/quickprs/cli.py +++ b/quickprs/cli.py @@ -2317,7 +2317,8 @@ def cmd_edit(filepath, name=None, author=None, filepath: input PRS file name: new personality filename (None = don't change) author: new saved-by field (None = don't change) - rename_set_type: set type to rename ("trunk", "group", "conv") + rename_set_type: set type to rename ("trunk", "group", "conv", + "iden", "p25conv"); systems naming the set follow the rename rename_old: current set name rename_new: new set name output: output file path (default: overwrite input) @@ -2325,9 +2326,7 @@ def cmd_edit(filepath, name=None, author=None, Returns: 0 on success, 1 on error. """ - from .injector import ( - edit_personality, rename_trunk_set, rename_group_set, rename_conv_set, - ) + from .injector import edit_personality from .prs_writer import write_prs prs = parse_prs(filepath) @@ -2342,18 +2341,19 @@ def cmd_edit(filepath, name=None, author=None, if author is not None: changes.append(f"author='{author}'") - # Rename set + # Rename set (and the systems' references to it) if rename_set_type and rename_old and rename_new: + from .injector import rename_set, _SET_LISTS rename_new = rename_new[:8] - if rename_set_type == "trunk": - renamed = rename_trunk_set(prs, rename_old, rename_new) - elif rename_set_type == "group": - renamed = rename_group_set(prs, rename_old, rename_new) - elif rename_set_type == "conv": - renamed = rename_conv_set(prs, rename_old, rename_new) - else: - print(f"Error: unknown set type '{rename_set_type}'", - file=sys.stderr) + if rename_set_type not in _SET_LISTS: + print(f"Error: unknown set type '{rename_set_type}' (use " + f"{', '.join(_SET_LISTS)})", file=sys.stderr) + return 1 + try: + renamed = rename_set(prs, rename_set_type, rename_old, + rename_new) + except ValueError as e: + print(f"Error: {e}", file=sys.stderr) return 1 if not renamed: @@ -4658,8 +4658,9 @@ def run_cli(args=None): help="New saved-by field") p_edit.add_argument("--rename-set", nargs=3, metavar=("TYPE", "OLD", "NEW"), - help="Rename a set: TYPE OLD NEW " - "(TYPE: trunk, group, conv)") + help="Rename a set and the references to it: " + "TYPE OLD NEW (TYPE: trunk, group, conv, " + "iden, p25conv)") p_edit.add_argument("-o", "--output", default=None, help="Output file (default: overwrite input)") diff --git a/quickprs/gui/personality_view.py b/quickprs/gui/personality_view.py index 48ca615..c9c13ee 100644 --- a/quickprs/gui/personality_view.py +++ b/quickprs/gui/personality_view.py @@ -2555,14 +2555,24 @@ def _delete_set(self, item_type, set_name): } label = type_labels.get(item_type, item_type) + prs = self.app.prs + if not prs: + return + + users = [] + if item_type in self._RENAMEABLE_SETS: + from ..injector import systems_using_set + users = systems_using_set( + prs, self._RENAMEABLE_SETS[item_type][0], set_name) + warning = "" + if users: + warning = (f"\n\nUsed by {', '.join(users)}: " + f"{'it' if len(users) == 1 else 'they'} would name " + f"a set that no longer exists.") if not messagebox.askyesno( "Confirm Delete", f"Delete {label} set '{set_name}'?\n\n" - "All data in this set will be removed."): - return - - prs = self.app.prs - if not prs: + f"All data in this set will be removed.{warning}"): return self.app.save_undo_snapshot("Delete set") @@ -2649,41 +2659,20 @@ def _delete_conv_set(self, prs, set_name): set_byte1, set_byte2) def _delete_iden_set(self, prs, set_name): - from ..injector import (_parse_section_data, - _get_header_bytes, _get_first_count) - from ..record_types import (parse_iden_section, - build_iden_section, - extract_iden_trailing_data) + from ..injector import (_parse_section_data, _get_first_count, + _replace_iden_sections) + from ..record_types import parse_iden_section elem_sec = prs.get_section_by_class("CDefaultIdenElem") - set_sec = prs.get_section_by_class("CIdenDataSet") - if not elem_sec or not set_sec: + if not elem_sec or not prs.get_section_by_class("CIdenDataSet"): raise ValueError("No IDEN sections found") - byte1, byte2 = _get_header_bytes(elem_sec) - set_byte1, set_byte2 = _get_header_bytes(set_sec) - first_count = _get_first_count(prs, "CIdenDataSet") - trailing = extract_iden_trailing_data(elem_sec.raw, first_count) existing = _parse_section_data( - elem_sec, parse_iden_section, first_count) + elem_sec, parse_iden_section, _get_first_count(prs, "CIdenDataSet")) remaining = [i for i in existing if i.name != set_name] if len(remaining) == len(existing): raise ValueError(f"Set '{set_name}' not found") if not remaining: raise ValueError("Cannot delete the last IDEN set") - # Rebuild using build_iden_section (preserving trailing data) - new_raw = build_iden_section(remaining, byte1, byte2, - trailing_data=trailing) - from ..prs_parser import Section - from ..injector import _find_section_index, _rebuild_set_section - from ..binary_io import write_uint16_le - elem_idx = _find_section_index(prs, "CDefaultIdenElem") - set_idx = _find_section_index(prs, "CIdenDataSet") - prs.sections[elem_idx] = Section(offset=0, raw=new_raw, - class_name="CDefaultIdenElem") - new_set_raw = _rebuild_set_section("CIdenDataSet", - len(remaining[0].elements), - set_byte1, set_byte2) - prs.sections[set_idx] = Section(offset=0, raw=new_set_raw, - class_name="CIdenDataSet") + _replace_iden_sections(prs, remaining) # ─── Add standard IDEN set ──────────────────────────────────────── @@ -3300,6 +3289,12 @@ def _export_set_csv(self, item_type, name, set_data): return try: + if item_type == "p25_conv_set": + from ..csv_export import export_p25_conv_sets + export_p25_conv_sets(path, [set_data]) + self.app.status_set(f"Exported '{name}' to {Path(path).name}") + return + with open(path, 'w', newline='', encoding='utf-8') as f: w = csv.writer(f) @@ -4227,216 +4222,37 @@ def _rename_system(self, class_name, old_name): messagebox.showwarning("Warning", f"System '{old_name}' not found.") - def _rename_set(self, set_type, old_name): - """Dispatch rename to the appropriate handler.""" - if set_type == "group_set": - self._rename_group_set(old_name) - elif set_type == "trunk_set": - self._rename_trunk_set(old_name) - elif set_type == "conv_set": - self._rename_conv_set(old_name) - elif set_type == "iden_set": - self._rename_iden_set(old_name) - - def _rename_group_set(self, old_name): - """Rename a group set (change name in parsed data, rebuild).""" - prs = self.app.prs - if not prs: - return - - new_name = self._prompt_new_name( - "Rename Group Set", f"New name for '{old_name}':", old_name) - if not new_name: - return - - grp_sec = prs.get_section_by_class("CP25Group") - set_sec = prs.get_section_by_class("CP25GroupSet") - if not grp_sec or not set_sec: - return - - from ..injector import _parse_section_data, _replace_group_sections - from ..injector import _get_header_bytes, _get_first_count - - try: - byte1, byte2 = _get_header_bytes(grp_sec) - set_byte1, set_byte2 = _get_header_bytes(set_sec) - first_count = _get_first_count(prs, "CP25GroupSet") - existing_sets = _parse_section_data( - grp_sec, parse_group_section, first_count) - - found = False - for gs in existing_sets: - if gs.name == old_name: - gs.name = new_name - found = True - break - - if not found: - messagebox.showwarning("Warning", - f"Group set '{old_name}' not found.") - return - - self.app.save_undo_snapshot("Rename group set") - _replace_group_sections(prs, existing_sets, byte1, byte2, - set_byte1, set_byte2) - self.app.mark_modified() - self.refresh() - self.app.status_set( - f"Renamed group set '{old_name}' to '{new_name}'") - - except Exception as e: - messagebox.showerror("Error", f"Rename failed:\n{e}") - - def _rename_trunk_set(self, old_name): - """Rename a trunk set.""" - prs = self.app.prs - if not prs: - return - - new_name = self._prompt_new_name( - "Rename Trunk Set", f"New name for '{old_name}':", old_name) - if not new_name: - return - - ch_sec = prs.get_section_by_class("CTrunkChannel") - set_sec = prs.get_section_by_class("CTrunkSet") - if not ch_sec or not set_sec: - return - - from ..injector import _parse_section_data, _replace_trunk_sections - from ..injector import _get_header_bytes, _get_first_count - - try: - byte1, byte2 = _get_header_bytes(ch_sec) - set_byte1, set_byte2 = _get_header_bytes(set_sec) - first_count = _get_first_count(prs, "CTrunkSet") - existing_sets = _parse_section_data( - ch_sec, parse_trunk_channel_section, first_count) - - found = False - for ts in existing_sets: - if ts.name == old_name: - ts.name = new_name - found = True - break - - if not found: - messagebox.showwarning("Warning", - f"Trunk set '{old_name}' not found.") - return - - self.app.save_undo_snapshot("Rename trunk set") - _replace_trunk_sections(prs, existing_sets, byte1, byte2, - set_byte1, set_byte2) - self.app.mark_modified() - self.refresh() - self.app.status_set( - f"Renamed trunk set '{old_name}' to '{new_name}'") - - except Exception as e: - messagebox.showerror("Error", f"Rename failed:\n{e}") - - def _rename_conv_set(self, old_name): - """Rename a conv set.""" + # tree item type -> (injector set type, label) + _RENAMEABLE_SETS = { + "group_set": ("group", "Group Set"), + "trunk_set": ("trunk", "Trunk Set"), + "conv_set": ("conv", "Conv Set"), + "iden_set": ("iden", "IDEN Set"), + "p25_conv_set": ("p25conv", "P25 Conv Set"), + } + + def _rename_set(self, item_type, old_name): + """Rename a set; the systems that use it follow (rename_set).""" prs = self.app.prs - if not prs: + if not prs or item_type not in self._RENAMEABLE_SETS: return - + set_type, label = self._RENAMEABLE_SETS[item_type] new_name = self._prompt_new_name( - "Rename Conv Set", f"New name for '{old_name}':", old_name) + f"Rename {label}", f"New name for '{old_name}':", old_name) if not new_name: return - conv_sec = prs.get_section_by_class("CConvChannel") - set_sec = prs.get_section_by_class("CConvSet") - if not conv_sec or not set_sec: - return - - from ..injector import _parse_section_data, _replace_conv_sections - from ..injector import _get_header_bytes, _get_first_count - + from ..injector import rename_set try: - byte1, byte2 = _get_header_bytes(conv_sec) - set_byte1, set_byte2 = _get_header_bytes(set_sec) - first_count = _get_first_count(prs, "CConvSet") - existing_sets = _parse_section_data( - conv_sec, parse_conv_channel_section, first_count) - - found = False - for cs in existing_sets: - if cs.name == old_name: - cs.name = new_name - found = True - break - - if not found: + self.app.save_undo_snapshot(f"Rename {label.lower()}") + if not rename_set(prs, set_type, old_name, new_name): messagebox.showwarning("Warning", - f"Conv set '{old_name}' not found.") + f"{label} '{old_name}' not found.") return - - self.app.save_undo_snapshot("Rename conv set") - _replace_conv_sections(prs, existing_sets, byte1, byte2, - set_byte1, set_byte2) self.app.mark_modified() self.refresh() self.app.status_set( - f"Renamed conv set '{old_name}' to '{new_name}'") - - except Exception as e: - messagebox.showerror("Error", f"Rename failed:\n{e}") - - def _rename_iden_set(self, old_name): - """Rename an IDEN set.""" - prs = self.app.prs - if not prs: - return - - new_name = self._prompt_new_name( - "Rename IDEN Set", f"New name for '{old_name}':", old_name) - if not new_name: - return - - elem_sec = prs.get_section_by_class("CDefaultIdenElem") - set_sec = prs.get_section_by_class("CIdenDataSet") - if not elem_sec or not set_sec: - return - - from ..injector import _parse_section_data, _get_header_bytes - from ..injector import _get_first_count, _find_section_index - from ..record_types import (parse_iden_section, build_iden_section, - extract_iden_trailing_data) - - try: - byte1, byte2 = _get_header_bytes(elem_sec) - first_count = _get_first_count(prs, "CIdenDataSet") - trailing = extract_iden_trailing_data(elem_sec.raw, first_count) - existing_sets = _parse_section_data( - elem_sec, parse_iden_section, first_count) - - found = False - for iset in existing_sets: - if iset.name == old_name: - iset.name = new_name - found = True - break - - if not found: - messagebox.showwarning("Warning", - f"IDEN set '{old_name}' not found.") - return - - self.app.save_undo_snapshot("Rename IDEN set") - new_raw = build_iden_section(existing_sets, byte1, byte2, - trailing_data=trailing) - from ..prs_parser import Section - elem_idx = _find_section_index(prs, "CDefaultIdenElem") - prs.sections[elem_idx] = Section( - offset=0, raw=new_raw, class_name="CDefaultIdenElem") - self.app.mark_modified() - self.refresh() - self.app.status_set( - f"Renamed IDEN set '{old_name}' to '{new_name}'") - + f"Renamed {label.lower()} '{old_name}' to '{new_name[:8]}'") except Exception as e: messagebox.showerror("Error", f"Rename failed:\n{e}") @@ -5698,15 +5514,8 @@ def _edit_nac_dialog(self, set_name, ch_idx): if not prs: return - from ..record_types import ( - parse_p25_conv_channel_section, - build_p25_conv_channel_section, - build_p25_conv_set_section, - ) - from ..injector import ( - _get_header_bytes, _get_first_count, _parse_section_data, - _find_section_index, - ) + from ..record_types import parse_p25_conv_channel_section + from ..injector import _get_first_count, _parse_section_data ch_sec = prs.get_section_by_class("CP25ConvChannel") set_sec = prs.get_section_by_class("CP25ConvSet") @@ -5714,8 +5523,6 @@ def _edit_nac_dialog(self, set_name, ch_idx): return try: - byte1, byte2 = _get_header_bytes(ch_sec) - set_byte1, set_byte2 = _get_header_bytes(set_sec) first_count = _get_first_count(prs, "CP25ConvSet") existing_sets = _parse_section_data( ch_sec, parse_p25_conv_channel_section, first_count) @@ -5828,22 +5635,9 @@ def _save(): if result[0]: try: - from ..prs_parser import Section + from ..injector import _replace_p25_conv_sections self.app.save_undo_snapshot("Edit NAC") - 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_sec = _find_section_index(prs, "CP25ConvChannel") - set_idx = _find_section_index(prs, "CP25ConvSet") - prs.sections[ch_idx_sec] = 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) self.app.mark_modified() self.refresh() self.app.status_set( diff --git a/quickprs/injector.py b/quickprs/injector.py index 744be3e..b4ab5f5 100644 --- a/quickprs/injector.py +++ b/quickprs/injector.py @@ -187,24 +187,120 @@ def _system_obj_names(obj): return short, long_name -def _system_obj_refs(obj): - """The sets a system object of an archive.Document names, as - (archive list name, set name) pairs: trunk, talkgroup and IDEN sets - for a P25 trunked system, the channel set for the others.""" +def _system_ref_sites(obj): + """Where a system object of an archive.Document names its sets: + (archive list name, part index, start, end) of each name's CString, + trunk, talkgroup and IDEN sets for a P25 trunked system, the channel + set for the others.""" 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, _ = archive.read_cstring(data, pos) - iden, _ = archive.read_cstring(obj.parts[2], 4) - return [("trunk sets", trunk), ("group sets", group), - ("IDEN sets", iden)] - if obj.cls == "CConvSystem": - return [("conv sets", archive.read_cstring(data, pos + 12)[0])] - return [("P25 conv sets", archive.read_cstring(data, pos + 5 + 4)[0])] + _, trunk_end = archive.read_cstring(data, pos) + _, group_end = archive.read_cstring(data, trunk_end) + _, iden_end = archive.read_cstring(obj.parts[2], 4) + return [("trunk sets", 0, pos, trunk_end), + ("group sets", 0, trunk_end, group_end), + ("IDEN sets", 2, 4, iden_end)] + start = pos + (12 if obj.cls == "CConvSystem" else 5 + 4) + _, end = archive.read_cstring(data, start) + return [("conv sets" if obj.cls == "CConvSystem" else "P25 conv sets", + 0, start, end)] + + +def _system_obj_refs(obj): + """The sets a system object names, as (archive list name, set name).""" + return [(list_name, + archive.read_cstring(obj.parts[part], start)[0]) + for list_name, part, start, _ in _system_ref_sites(obj)] + + +def _replace_cstring(data, start, end, text): + return data[:start] + archive.write_cstring(text) + data[end:] + + +# The archive set list each rename_* function works on, and its label +_SET_LISTS = { + "trunk": ("trunk sets", "Trunk set"), + "group": ("group sets", "Group set"), + "conv": ("conv sets", "Conv set"), + "iden": ("IDEN sets", "IDEN set"), + "p25conv": ("P25 conv sets", "P25 conv set"), +} + + +def systems_using_set(prs, set_type, name): + """Short names of the systems that name this set (set_type as for + rename_set). Empty when the archive cannot be read.""" + list_name = _SET_LISTS[set_type][0] + try: + doc = archive.document_from_prs(prs) + except archive.WalkError: + return [] + return [_system_obj_names(o)[0] for o in doc.list("systems").items + if o is not None and (list_name, name) in _system_obj_refs(o)] + + +def rename_set(prs, set_type, old_name, new_name): + """Rename a set and every reference to it. + + Systems find their sets by name, and a P25 conventional set may name a + talkgroup set, so those names change with it. + + Args: + set_type: "trunk", "group", "conv", "iden" or "p25conv" + new_name: 8 characters at most (longer is cut) + + Returns: + True if renamed, False if no set of that type has old_name. + + Raises: + ValueError: another set of that type already has new_name. + """ + list_name, label = _SET_LISTS[set_type] + new_name = new_name[:8] + if not prs.sections: + return False + doc = archive.document_from_prs(prs) + sets = [o for o in doc.list(list_name).items if o is not None] + target = next((o for o in sets if _set_obj_name(o) == old_name), None) + if target is None: + return False + if new_name == old_name: + return True + if any(_set_obj_name(o) == new_name for o in sets): + raise ValueError(f"{label} '{new_name}' already exists") + + meta = target.parts[1] + _, end = archive.read_cstring(meta, 0) + target.parts[1] = _replace_cstring(meta, 0, end, new_name) + + for obj in doc.list("systems").items: + if obj is None: + continue + # back to front, so earlier positions stay valid + for site_list, part, start, end in reversed(_system_ref_sites(obj)): + if (site_list == list_name and + archive.read_cstring(obj.parts[part], start)[0] + == old_name): + obj.parts[part] = _replace_cstring( + obj.parts[part], start, end, new_name) + + if list_name == "group sets": + for obj in doc.list("P25 conv sets").items: + if obj is None: + continue + meta = obj.parts[1] + _, pos = archive.read_cstring(meta, 0) # set name + pos += 1 + 1 + 32 # sizes, band limits + ref, end = archive.read_cstring(meta, pos) + if ref == old_name: + obj.parts[1] = _replace_cstring(meta, pos, end, new_name) + + archive.write_document(prs, doc) + return True def _system_obj_wan_name(obj): @@ -1021,120 +1117,30 @@ def remove_conv_set(prs, set_name): def rename_trunk_set(prs, old_name, new_name): - """Rename a trunk set. Rebuilds CTrunkChannel section with updated name. - - Args: - prs: PRSFile object - old_name: current set name - new_name: new set name (8 chars max) - - Returns: - True if renamed, False if not found. - """ - ch_sec = prs.get_section_by_class("CTrunkChannel") - set_sec = prs.get_section_by_class("CTrunkSet") - if not ch_sec or not set_sec: - return False - - byte1, byte2 = _get_header_bytes(ch_sec) - set_byte1, set_byte2 = _get_header_bytes(set_sec) - first_count = _get_first_count(prs, "CTrunkSet") - - existing_sets = _parse_section_data(ch_sec, parse_trunk_channel_section, - first_count) - - found = False - for s in existing_sets: - if s.name == old_name: - s.name = new_name[:8] - found = True - break - - if not found: - return False - - _replace_trunk_sections(prs, existing_sets, byte1, byte2, - set_byte1, set_byte2) - return True + """Rename a trunk set and the references to it (see rename_set).""" + return rename_set(prs, "trunk", old_name, new_name) def rename_group_set(prs, old_name, new_name): - """Rename a group set. Rebuilds CP25Group section with updated name. - - Args: - prs: PRSFile object - old_name: current set name - new_name: new set name (8 chars max) - - Returns: - True if renamed, False if not found. - """ - grp_sec = prs.get_section_by_class("CP25Group") - set_sec = prs.get_section_by_class("CP25GroupSet") - if not grp_sec or not set_sec: - return False - - byte1, byte2 = _get_header_bytes(grp_sec) - set_byte1, set_byte2 = _get_header_bytes(set_sec) - first_count = _get_first_count(prs, "CP25GroupSet") + """Rename a group set and the references to it (see rename_set).""" + return rename_set(prs, "group", old_name, new_name) - existing_sets = _parse_section_data(grp_sec, parse_group_section, - first_count) - found = False - for s in existing_sets: - if s.name == old_name: - s.name = new_name[:8] - found = True - break +def rename_iden_set(prs, old_name, new_name): + """Rename an IDEN set and the references to it (see rename_set).""" + return rename_set(prs, "iden", old_name, new_name) - if not found: - return False - _replace_group_sections(prs, existing_sets, byte1, byte2, - set_byte1, set_byte2) - return True +def rename_p25_conv_set(prs, old_name, new_name): + """Rename a P25 conventional set and the references to it (see + rename_set).""" + return rename_set(prs, "p25conv", old_name, new_name) def rename_conv_set(prs, old_name, new_name): - """Rename a conv set. Rebuilds CConvChannel section with updated name. - - Args: - prs: PRSFile object - old_name: current set name - new_name: new set name (8 chars max) - - Returns: - True if renamed, False if not found. - """ - ch_sec = prs.get_section_by_class("CConvChannel") - set_sec = prs.get_section_by_class("CConvSet") - if not ch_sec or not set_sec: - return False - - byte1, byte2 = _get_header_bytes(ch_sec) - set_byte1, set_byte2 = _get_header_bytes(set_sec) - first_count = _get_first_count(prs, "CConvSet") - - existing_sets = _parse_section_data(ch_sec, parse_conv_channel_section, - first_count) - - found = False - for s in existing_sets: - if s.name == old_name: - s.name = new_name[:8] - found = True - break - - if not found: - return False - - _replace_conv_sections(prs, existing_sets, byte1, byte2, - set_byte1, set_byte2) - return True - + """Rename a conventional set and the references to it (see rename_set).""" + return rename_set(prs, "conv", old_name, new_name) -# ─── Reorder Operations ────────────────────────────────────────────── def reorder_talkgroup(prs, set_name, old_index, new_index): """Move a talkgroup to a new position within its group set. diff --git a/tests/test_gui_smoke.py b/tests/test_gui_smoke.py index da2b1f5..0f837e4 100644 --- a/tests/test_gui_smoke.py +++ b/tests/test_gui_smoke.py @@ -176,3 +176,54 @@ def test_trunk_edit_while_filtered_hits_the_right_channel(app, tmp_path): injector._get_first_count(app.prs, "CTrunkSet")) if s.name == "CITY").channels assert [c.tx_freq for c in channels] == [806.0125, 806.525, 807.0125] + + +def _p25_conv_personality(tmp_path): + from quickprs import injector + from quickprs.builder import create_blank_prs + from quickprs.prs_writer import write_prs + from quickprs.record_types import P25ConvSystemConfig + prs = create_blank_prs("p25c.PRS") + injector.add_p25_conv_set(prs, injector.make_p25_conv_set("P25C", [ + {"short_name": "TAC 1", "tx_freq": 154.43, "nac_tx": 0x3AB}])) + injector.add_p25_conv_system(prs, P25ConvSystemConfig( + system_name="P25C", long_name="P25 CONV", conv_set_name="P25C")) + injector._safe_add_iden_set(prs, injector.make_iden_set( + "SPARE", [{"base_freq_hz": 851_012_500}])) + injector._safe_add_iden_set(prs, injector.make_iden_set( + "KEEP", [{"base_freq_hz": 762_006_250}])) + path = tmp_path / "p25c.PRS" + write_prs(prs, path) + return path + + +def test_p25_conv_set_csv_export(app, tmp_path): + """The P25 conv set menu offered Export to CSV, and the file came out + empty; it is now P25_CONV_SET.csv, which import-csv reads.""" + from quickprs.csv_import import import_csv + app._open_path(_p25_conv_personality(tmp_path), confirmed=True) + pv = app.personality_view + meta = next(m for m in pv._item_meta.values() + if m.get("type") == "p25_conv_set") + out = tmp_path / "out.csv" + with mock.patch("quickprs.gui.personality_view.filedialog") as fd, \ + mock.patch("quickprs.gui.personality_view.messagebox"): + fd.asksaveasfilename.return_value = str(out) + pv._export_set_csv("p25_conv_set", "P25C", meta["set_data"]) + kind, sets = import_csv(out) + assert kind == "p25conv" + assert [(c.short_name, c.nac_tx) for c in sets[0].channels] == [ + ("TAC 1", 0x3AB)] + + +def test_delete_iden_set_keeps_the_file_readable(app, tmp_path): + from quickprs import archive + from quickprs.prs_parser import parse_prs_bytes + app._open_path(_p25_conv_personality(tmp_path), confirmed=True) + pv = app.personality_view + pv._delete_iden_set(app.prs, "SPARE") + back = parse_prs_bytes(app.prs.to_bytes()) + assert archive.check(back) == [] + names = [archive.read_cstring(o.parts[1], 0)[0] for o in + archive.document_from_prs(back).list("IDEN sets").items] + assert names == ["KEEP"] diff --git a/tests/test_rename_references.py b/tests/test_rename_references.py new file mode 100644 index 0000000..2160ffe --- /dev/null +++ b/tests/test_rename_references.py @@ -0,0 +1,126 @@ +"""Renaming a set renames the references to it. + +Systems find their trunk, talkgroup, IDEN and channel sets by name, and a +P25 conventional set may name a talkgroup set. rename_trunk_set, +rename_group_set and rename_conv_set changed only the set, so `edit +--rename-set` left the system naming a set that no longer existed. +""" + +import pytest + +from quickprs import archive, injector +from quickprs.builder import create_blank_prs +from quickprs.prs_parser import parse_prs_bytes +from quickprs.record_types import ( + P25TrkSystemConfig, ConvSystemConfig, P25ConvSystemConfig, +) +from quickprs.validation import validate_prs, ERROR + + +def _personality(): + prs = create_blank_prs("refs.PRS") + injector.add_p25_trunked_system( + prs, + P25TrkSystemConfig(system_name="CITY", long_name="CITY P25", + trunk_set_name="CITY T", group_set_name="CITY G", + wan_name="CITY", iden_set_name="CITY I"), + trunk_set=injector.make_trunk_set( + "CITY T", [(806.0125, 851.0125)]), + group_set=injector.make_group_set("CITY G", [(1, "TG", "TG")]), + iden_set=injector.make_iden_set( + "CITY I", [{"base_freq_hz": 851_012_500}])) + injector.add_conv_system(prs, ConvSystemConfig( + system_name="LOCAL", long_name="LOCAL", conv_set_name="LOCAL C"), + conv_set=injector.make_conv_set("LOCAL C", [ + {"short_name": "A", "tx_freq": 151.625}])) + injector.add_p25_conv_set(prs, injector.make_p25_conv_set( + "P25 C", [{"short_name": "P", "tx_freq": 154.43}], + group_set_ref="CITY G")) + injector.add_p25_conv_system(prs, P25ConvSystemConfig( + system_name="P25", long_name="P25", conv_set_name="P25 C")) + return parse_prs_bytes(prs.to_bytes()) + + +def _refs(prs): + doc = archive.document_from_prs(prs) + return {injector._system_obj_names(o)[0]: injector._system_obj_refs(o) + for o in doc.list("systems").items if o is not None} + + +def _no_dangling(prs): + back = parse_prs_bytes(prs.to_bytes()) + assert archive.check(back) == [] + errors = [m for s, m in validate_prs(back) if s == ERROR] + assert not [m for m in errors if "references" in m], errors + + +@pytest.mark.parametrize("set_type, old, new, system, list_name", [ + ("trunk", "CITY T", "METRO T", "CITY", "trunk sets"), + ("group", "CITY G", "METRO G", "CITY", "group sets"), + ("iden", "CITY I", "METRO I", "CITY", "IDEN sets"), + ("conv", "LOCAL C", "TOWN C", "LOCAL", "conv sets"), + ("p25conv", "P25 C", "DIG C", "P25", "P25 conv sets"), +]) +def test_system_follows_the_rename(set_type, old, new, system, list_name): + prs = _personality() + assert injector.rename_set(prs, set_type, old, new) is True + refs = dict(_refs(prs)[system]) + assert refs[list_name] == new + _no_dangling(prs) + + +def test_p25_conv_set_follows_a_talkgroup_set_rename(): + prs = _personality() + injector.rename_group_set(prs, "CITY G", "METRO G") + p25 = injector.get_p25_conv_sets(parse_prs_bytes(prs.to_bytes())) + assert [s.group_set_ref for s in p25] == ["METRO G"] + + +def test_wrappers_follow_too(): + prs = _personality() + assert injector.rename_trunk_set(prs, "CITY T", "X1") + assert injector.rename_group_set(prs, "CITY G", "X2") + assert injector.rename_conv_set(prs, "LOCAL C", "X3") + assert injector.rename_iden_set(prs, "CITY I", "X4") + assert injector.rename_p25_conv_set(prs, "P25 C", "X5") + refs = _refs(prs) + assert dict(refs["CITY"]) == {"trunk sets": "X1", "group sets": "X2", + "IDEN sets": "X4"} + assert dict(refs["LOCAL"]) == {"conv sets": "X3"} + assert dict(refs["P25"]) == {"P25 conv sets": "X5"} + _no_dangling(prs) + + +def test_a_taken_name_is_refused(): + prs = _personality() + injector.add_conv_set(prs, injector.make_conv_set("TAKEN", [ + {"short_name": "B", "tx_freq": 154.57}])) + before = prs.to_bytes() + with pytest.raises(ValueError, match="already exists"): + injector.rename_set(prs, "conv", "LOCAL C", "TAKEN") + assert prs.to_bytes() == before + + +def test_unknown_set_is_false(): + assert injector.rename_set(_personality(), "trunk", "NOPE", "X") is False + + +def test_systems_using_set(): + prs = _personality() + assert injector.systems_using_set(prs, "group", "CITY G") == ["CITY"] + assert injector.systems_using_set(prs, "conv", "LOCAL C") == ["LOCAL"] + assert injector.systems_using_set(prs, "trunk", "NOPE") == [] + + +def test_cli_renames_iden_and_p25conv(tmp_path): + from quickprs.cli import run_cli + path = tmp_path / "refs.PRS" + path.write_bytes(_personality().to_bytes()) + assert run_cli(["edit", str(path), "--rename-set", "iden", "CITY I", + "NEW I"]) == 0 + assert run_cli(["edit", str(path), "--rename-set", "p25conv", "P25 C", + "NEW C"]) == 0 + from quickprs.prs_parser import parse_prs + refs = _refs(parse_prs(path)) + assert dict(refs["CITY"])["IDEN sets"] == "NEW I" + assert dict(refs["P25"])["P25 conv sets"] == "NEW C" From 32845193e91ad40ca2b240ac568edddb5cfa78d2 Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:35:15 -0700 Subject: [PATCH 21/22] GUI: the RadioReference fetch thread no longer calls Tk The API fetch ran in a worker thread that scheduled its result with winfo_toplevel().after(), a Tk call from outside the main thread, which Tk does not allow. The worker now leaves its result in a queue that the main thread polls. --- quickprs/gui/import_panel.py | 21 +++++++++++++----- tests/test_gui_smoke.py | 42 ++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 5 deletions(-) diff --git a/quickprs/gui/import_panel.py b/quickprs/gui/import_panel.py index 7e12b98..c0fd29c 100644 --- a/quickprs/gui/import_panel.py +++ b/quickprs/gui/import_panel.py @@ -16,6 +16,7 @@ import tkinter as tk from tkinter import ttk, messagebox, filedialog +import queue import threading from ..radioreference import ( @@ -2168,17 +2169,27 @@ def _fetch(self): foreground="blue") self.fetch_btn.config(state=tk.DISABLED) + # Tk may only be called from this (the main) thread: the worker + # leaves its result in a queue and the main thread polls for it + results = queue.Queue() + def _do_fetch(): try: api = RadioReferenceAPI(username, password, app_key) - system = api.get_system(sid) - self.winfo_toplevel().after( - 0, self._on_fetch_complete, system, None) + results.put((api.get_system(sid), None)) except Exception as e: - self.winfo_toplevel().after( - 0, self._on_fetch_complete, None, str(e)) + results.put((None, str(e))) + + def _poll(): + try: + system, error = results.get_nowait() + except queue.Empty: + self.after(100, _poll) + return + self._on_fetch_complete(system, error) threading.Thread(target=_do_fetch, daemon=True).start() + self.after(100, _poll) def _on_fetch_complete(self, system, error): self.fetch_btn.config(state=tk.NORMAL) diff --git a/tests/test_gui_smoke.py b/tests/test_gui_smoke.py index 0f837e4..d9cffbe 100644 --- a/tests/test_gui_smoke.py +++ b/tests/test_gui_smoke.py @@ -227,3 +227,45 @@ def test_delete_iden_set_keeps_the_file_readable(app, tmp_path): names = [archive.read_cstring(o.parts[1], 0)[0] for o in archive.document_from_prs(back).list("IDEN sets").items] assert names == ["KEEP"] + + +def test_api_fetch_result_is_handled_on_the_main_thread(app): + """The fetch thread called Tk (winfo_toplevel().after) itself; Tk may + only be called from the main thread. The result now comes back + through a queue the main thread polls.""" + import threading + import time + from quickprs.gui import import_panel as ip + from quickprs.radioreference import RRSystem + + panel = app.import_panel + seen = {} + + class FakeAPI: + def __init__(self, *args): + seen["api_thread"] = threading.current_thread() + + def get_system(self, sid): + return RRSystem(sid=sid, name="FAKE") + + def complete(system, error): + seen["thread"] = threading.current_thread() + seen["result"] = (system.name if system else None, error) + + panel.url_var.set("https://www.radioreference.com/db/sid/11628") + panel.user_var.set("u") + panel.pass_var.set("p") + panel.key_var.set("k") + with mock.patch.object(ip, "RadioReferenceAPI", FakeAPI), \ + mock.patch.object(ip, "HAS_ZEEP", True), \ + mock.patch.object(panel, "_on_fetch_complete", complete), \ + mock.patch.object(panel, "winfo_toplevel", + side_effect=AssertionError("Tk call")): + panel._fetch() + deadline = time.time() + 5 + while "result" not in seen and time.time() < deadline: + app.root.update() + time.sleep(0.02) + assert seen["result"] == ("FAKE", None) + assert seen["thread"] is threading.main_thread() + assert seen["api_thread"] is not threading.main_thread() From 0c549338c40c651a21026c627399dfdcac36498a Mon Sep 17 00:00:00 2001 From: TheAbider <51920546+TheAbider@users.noreply.github.com> Date: Wed, 28 Oct 2026 10:38:45 -0700 Subject: [PATCH 22/22] QuickPRS 1.2.0 --- CHANGELOG.md | 16 +++++++++++++++- README.md | 2 +- pyproject.toml | 2 +- quickprs/__init__.py | 2 +- 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c63c585..358a163 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ All notable changes to QuickPRS will be documented in this file. -## [Unreleased] +## [1.2.0] - 2026-10-28 ### Fixed - Templates: FRS, GMRS 8-14, MURS 1-3 and the public safety simplex channels were 25 kHz channels where the FCC allows 12.5 kHz or less (47 CFR 95.573, 95.1773, 95.2773, 90.209(b)(5)); they are narrowband now. Marine channel 70 carries DSC only (no voice) and is no longer in the marine template @@ -14,9 +14,23 @@ All notable changes to QuickPRS will be documented in this file. - `merge` named every system after the first one of its class, rebuilt P25 systems from defaults (system ID 0, no home unit ID, a guessed IDEN set), left P25 conventional systems out and could add a second set under a name already in use. It now copies systems and the sets they use exactly and reports name clashes - Adding a set under a name already used by a set of the same type is refused: systems find their sets by name - `wizard --modify FILE` ignored FILE and built a new personality; it now adds to FILE. The wizard replaced an existing output file without asking or keeping a backup +- Renaming a set (`edit --rename-set`, the GUI) left the systems that use it naming a set that no longer existed; their references now follow the rename, as does a P25 conventional set's talkgroup set reference. A name already in use is refused +- The personality name and user name are stored twice in a file (RPM writes both copies the same); `edit --name/--author`, `fleet` and `clone-personality --name` changed only one +- `export-config` dropped narrowband, TX-off and scan-off from conventional channels (PAWSOVERMAWS's FURRY NB set came back from `build` as 25 kHz channels) and wrote `template = X` for any set with a template's frequencies, so a MURS set programmed wide would build narrowband +- The CSV files `template-csv` writes did not work: inject and fleet read their `#` comment lines as data +- The RadioReference cache dropped conventional channels, categories (the GUI's category filter) and color codes +- Validation checked frequencies against 30-960 MHz, so 220 or 900 MHz passed; it now checks the XG-100P's bands (136-174, 380-520, 762-870 MHz). It no longer warns about a trunk set and talkgroup set sharing a name, or about PTCT, RPM's default 2-position switch function: RPM writes both +- New analog channels get the values RPM writes in every channel it creates (85 in both tone address fields, the tone mode flag set); QuickPRS wrote 0, 0 and off +- GUI: with the search filtering rows, editing or moving a trunk channel changed another channel; Export to CSV on a P25 conventional set wrote an empty file; the NAC editor and IDEN set delete spliced raw sections (IDEN delete left a stale count); the RadioReference fetch thread called Tk; deleting a set now names the systems that use it + +### Added +- `edit --rename-set` takes `iden` and `p25conv` sets +- Config file channel lines take an optional seventh field of flags: `nb`, `rxonly`, `noscan` +- `merge` merges P25 conventional systems ### Changed - JSON exports carry every field of each set, channel and talkgroup (bytes as hex) and an `archive` block with the rest of the file; IDEN elements carry their slot (`index`) +- `compare` matches items by key and names the fields that changed ## [1.1.0] - 2026-10-28 diff --git a/README.md b/README.md index 06826f2..01c6a96 100644 --- a/README.md +++ b/README.md @@ -87,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,400+ automated tests +- 5,600+ automated tests ## Quick Start diff --git a/pyproject.toml b/pyproject.toml index 2d02026..e372330 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "quickprs" -version = "1.1.0" +version = "1.2.0" description = "Generate Harris XG-100P personality files without Harris RPM" requires-python = ">=3.8" dependencies = [ diff --git a/quickprs/__init__.py b/quickprs/__init__.py index 3447224..fd8fbd6 100644 --- a/quickprs/__init__.py +++ b/quickprs/__init__.py @@ -1,3 +1,3 @@ """QuickPRS - Harris RPM Personality File Tool""" -__version__ = "1.1.0" +__version__ = "1.2.0"