radtel_rt950pro (v0.1.8)

CHIRP driver for the Radtel RT-950 Pro.

This single-file driver lets CHIRP read and write the Radtel RT-950 Pro handheld over its USB programming cable. It targets firmware with 990 channels in 10 zones of 99 channels (vendor CPS v1.2.1 and later, firmware 0.24 and later).

Memory layout (confirmed on hardware):

0x0000-0x7BBF  990 channels x 32 bytes = 10 zones x 99 channels
0x7BC0-0x7FFF  unused; kept verbatim in the image, never written to the radio
0x8000         VFO A/B/C            (0x100 bytes, 96 used)
0x9000         function settings    (0x100 bytes, 96 used)
0xA000         DTMF settings        (0x200 bytes, 384 used)
0xB000         modulation params    (0x200 bytes, 256 used)
0xC000-0xC09F  10 zone names x 16 bytes (read as 0xC000-0xC0FF)
0xD000         modulation names     (0x300 bytes)
APRS           separate space: read command 0x54, write command 0x58

Zone z, channel k (both 1-based) is 1-based slot (z - 1) * 99 + k, i.e. RadioImage.channels[(z - 1) * 99 + k - 1] at byte address ((z - 1) * 99 + k - 1) * 32.

The vendor CPS setting Channel Divide (function byte 0x9026, measured on hardware: 0 = Zone CH Mode, 1 = All CH Mode) only changes how the radio presents these slots: in Zone CH Mode as 10 zones of 99 channels, in All CH Mode as one list of channels 1-990 in which channel n is slot n (the zones placed one after the other; empty channels stay empty and are not moved up). The channel memory is the same in both modes. The driver follows the setting: CHIRP shows ten zone tabs in Zone CH Mode and a single memory list 1-990 in All CH Mode.

The module is organised in layers, from raw bytes up to CHIRP:

  1. Channel records: ToneSetting, ChannelRecord and the BCD/GB2312 codecs for the 32-byte channel structure.
  2. Settings sections: dataclasses plus parse_*/encode_* functions for the VFO, function, DTMF, modulation and APRS blocks.
  3. Settings API: validated getters and setters (get_*/set_*).
  4. Image: RadioImage, the parsed form of a complete clone image.
  5. Transport: CloneSerialTransport, the serial clone protocol (PROGRAMBT9000U handshake and XOR-obfuscated 0x80-byte blocks).
  6. CHIRP integration: RT950ProRadio and one RT950ProZoneRadio sub-device per zone.

Unedited channel records, VFO entries and settings blocks are written back byte-identical. Settings encoders work read-modify-write on the stored bytes and only rewrite a field whose value was edited; a field byte holding 0xFF is treated as 0 before an edited field is merged into it. Settings applied in CHIRP only touch the settings that were changed. An edited channel record is rebuilt from its fields, keeping the unknown high nibbles of bytes 12-13 (see ChannelRecord.to_bytes()).

The module needs CHIRP to work with a radio. Without CHIRP it still imports (stand-ins for the CHIRP names, for documentation builds), but HAVE_CHIRP is False; get_features, get_settings, get_memory and set_memory then raise RadioError, other methods may fail with AttributeError.

See docs/memory-map.md and docs/protocol.md in the repository for the byte-level reference.

Warning:

Experimental. Always download from the radio and keep the .img as a backup before uploading.

   1# Radtel RT-950 Pro driver for CHIRP
   2#
   3# Copyright (c) 2025 Nathan G. Barguss - 2E0NBS   (original driver)
   4# Copyright (c) 2026 PE1HVH                         (zones, zone names, 990
   5#                                                   channels, APRS write, fixes)
   6#
   7# Version 0.1.8 (see CHANGELOG.md)
   8#
   9# Licensed under the MIT License; see the LICENSE file for the full text.
  10#
  11# EXPERIMENTAL. Use at your own risk: a driver bug can mis-program your radio.
  12# Always keep a backup of your radio (CPS .dat and a CHIRP .img) before
  13# writing. Tested on hardware: see README.md.
  14
  15"""CHIRP driver for the Radtel RT-950 Pro.
  16
  17This single-file driver lets CHIRP read and write the Radtel RT-950 Pro
  18handheld over its USB programming cable. It targets firmware with
  19990 channels in 10 zones of 99 channels (vendor CPS v1.2.1 and later,
  20firmware 0.24 and later).
  21
  22Memory layout (confirmed on hardware):
  23
  24    0x0000-0x7BBF  990 channels x 32 bytes = 10 zones x 99 channels
  25    0x7BC0-0x7FFF  unused; kept verbatim in the image, never written to the radio
  26    0x8000         VFO A/B/C            (0x100 bytes, 96 used)
  27    0x9000         function settings    (0x100 bytes, 96 used)
  28    0xA000         DTMF settings        (0x200 bytes, 384 used)
  29    0xB000         modulation params    (0x200 bytes, 256 used)
  30    0xC000-0xC09F  10 zone names x 16 bytes (read as 0xC000-0xC0FF)
  31    0xD000         modulation names     (0x300 bytes)
  32    APRS           separate space: read command 0x54, write command 0x58
  33
  34Zone *z*, channel *k* (both 1-based) is 1-based slot ``(z - 1) * 99 + k``,
  35i.e. ``RadioImage.channels[(z - 1) * 99 + k - 1]`` at byte address
  36``((z - 1) * 99 + k - 1) * 32``.
  37
  38The vendor CPS setting *Channel Divide* (function byte 0x9026, measured on
  39hardware: 0 = *Zone CH Mode*, 1 = *All CH Mode*) only changes how the
  40radio presents these slots: in Zone CH Mode as 10 zones of 99 channels,
  41in All CH Mode as one list of channels 1-990 in which channel *n* is slot
  42*n* (the zones placed one after the other; empty channels stay empty and
  43are not moved up). The channel memory is the same in both modes. The
  44driver follows the setting: CHIRP shows ten zone tabs in Zone CH Mode
  45and a single memory list 1-990 in All CH Mode.
  46
  47The module is organised in layers, from raw bytes up to CHIRP:
  48
  491. Channel records: :class:`ToneSetting`, :class:`ChannelRecord` and the
  50   BCD/GB2312 codecs for the 32-byte channel structure.
  512. Settings sections: dataclasses plus ``parse_*``/``encode_*`` functions
  52   for the VFO, function, DTMF, modulation and APRS blocks.
  533. Settings API: validated getters and setters (``get_*``/``set_*``).
  544. Image: :class:`RadioImage`, the parsed form of a complete clone image.
  555. Transport: :class:`CloneSerialTransport`, the serial clone protocol
  56   (``PROGRAMBT9000U`` handshake and XOR-obfuscated 0x80-byte blocks).
  576. CHIRP integration: :class:`RT950ProRadio` and one
  58   :class:`RT950ProZoneRadio` sub-device per zone.
  59
  60Unedited channel records, VFO entries and settings blocks are written back
  61byte-identical. Settings encoders work read-modify-write on the stored
  62bytes and only rewrite a field whose value was edited; a field byte holding
  630xFF is treated as 0 before an edited field is merged into it. Settings
  64applied in CHIRP only touch the settings that were changed. An edited
  65channel record is rebuilt from its fields, keeping the unknown high nibbles
  66of bytes 12-13 (see :meth:`ChannelRecord.to_bytes`).
  67
  68The module needs CHIRP to work with a radio. Without CHIRP it still
  69imports (stand-ins for the CHIRP names, for documentation builds), but
  70:data:`HAVE_CHIRP` is ``False``; ``get_features``, ``get_settings``,
  71``get_memory`` and ``set_memory`` then raise ``RadioError``, other methods
  72may fail with ``AttributeError``.
  73
  74See ``docs/memory-map.md`` and ``docs/protocol.md`` in the repository for
  75the byte-level reference.
  76
  77Warning:
  78    Experimental. Always download from the radio and keep the ``.img``
  79    as a backup before uploading.
  80"""
  81
  82# Design-size checks are disabled module-wide on purpose: the dataclasses
  83# mirror fixed radio structures field by field, and the settings builders
  84# mirror the vendor CPS screens. Splitting them would hide the 1:1 mapping
  85# with the memory map. The dataclasses in this module share their private
  86# change-tracking state (_raw_bytes, _original_state, _state_tuple) by design.
  87# pylint: disable=too-many-lines,too-many-instance-attributes
  88# pylint: disable=too-few-public-methods,too-many-arguments
  89# pylint: disable=too-many-positional-arguments,too-many-locals
  90# pylint: disable=too-many-statements,too-many-branches,protected-access
  91
  92from __future__ import annotations
  93
  94import logging
  95import random
  96import time
  97import unicodedata
  98from dataclasses import dataclass, field
  99from enum import Enum
 100from pathlib import Path
 101from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple
 102
 103try:
 104    import serial
 105except ImportError:  # pragma: no cover - pydoc/doc builds without pyserial
 106    serial = None  # pylint: disable=invalid-name
 107
 108__version__ = "0.1.8"
 109"""Driver version (semantic versioning); equal to the latest entry in
 110``CHANGELOG.md`` and to the release tag ``v<version>`` on GitHub.
 111
 112Shown after the module name in the heading of the documentation page
 113(``docs/build.py``)."""
 114
 115__all__ = [
 116    # Channel records
 117    "ToneMode",
 118    "ToneSetting",
 119    "PowerLevel",
 120    "Bandwidth",
 121    "Modulation",
 122    "ChannelRecord",
 123    # Settings sections
 124    "VFOSettings",
 125    "FunctionSettings",
 126    "DTMFSettings",
 127    "ModulationChannelEntry",
 128    "ModulationSettings",
 129    "APRSSettings",
 130    "parse_vfo_section",
 131    "parse_function_section",
 132    "parse_dtmf_section",
 133    "parse_modulation_sections",
 134    "parse_aprs_section",
 135    "encode_vfo_section",
 136    "encode_function_section",
 137    "encode_dtmf_section",
 138    "encode_modulation_sections",
 139    "encode_aprs_section",
 140    # Settings API
 141    "SettingsError",
 142    "SettingSpec",
 143    "CHANNEL_DIVIDE_ZONE",
 144    "CHANNEL_DIVIDE_ALL",
 145    "function_keys",
 146    "get_function_value",
 147    "set_function_value",
 148    "aprs_keys",
 149    "get_aprs_value",
 150    "set_aprs_value",
 151    "get_dtmf_current_id",
 152    "set_dtmf_current_id",
 153    "get_dtmf_ptt_mode",
 154    "set_dtmf_ptt_mode",
 155    "get_dtmf_code_group",
 156    "set_dtmf_code_group",
 157    # Image
 158    "ZONE_COUNT",
 159    "ZONE_SIZE",
 160    "CHANNEL_COUNT",
 161    "CHANNEL_SIZE",
 162    "CHANNEL_SECTION_BYTES",
 163    "parse_zone_names",
 164    "encode_zone_names",
 165    "RadioImage",
 166    # Transport
 167    "CloneSegment",
 168    "CloneTransportError",
 169    "CloneSerialConfig",
 170    "CloneSerialTransport",
 171    "DEFAULT_SEGMENTS",
 172    # CHIRP integration
 173    "MEM_FORMAT",
 174    "HAVE_CHIRP",
 175    "VALID_BANDS",
 176    "RT950ProRadio",
 177    "RT950ProZoneRadio",
 178    "RT950ProDriver",
 179]
 180
 181# ===========================================================================
 182# 1. Channel records
 183# ===========================================================================
 184
 185LOG = logging.getLogger(__name__ + ".channel")
 186"""Module logger.
 187
 188Note: ``LOG`` is rebound to ``logging.getLogger(__name__)`` in section 6.
 189Functions look ``LOG`` up at call time, so code that uses ``LOG`` directly
 190logs through that final driver logger. Code that takes a ``logger``
 191argument uses the logger passed in (``RadioImage`` defaults to
 192``CHANNEL_LOG``, the transport to ``__name__ + ".transport"``).
 193"""
 194
 195_DCS_CODES = [
 196    "D023N",
 197    "D025N",
 198    "D026N",
 199    "D031N",
 200    "D032N",
 201    "D036N",
 202    "D043N",
 203    "D047N",
 204    "D051N",
 205    "D053N",
 206    "D054N",
 207    "D065N",
 208    "D071N",
 209    "D072N",
 210    "D073N",
 211    "D074N",
 212    "D114N",
 213    "D115N",
 214    "D116N",
 215    "D122N",
 216    "D125N",
 217    "D131N",
 218    "D132N",
 219    "D134N",
 220    "D143N",
 221    "D145N",
 222    "D152N",
 223    "D155N",
 224    "D156N",
 225    "D162N",
 226    "D165N",
 227    "D172N",
 228    "D174N",
 229    "D205N",
 230    "D212N",
 231    "D223N",
 232    "D225N",
 233    "D226N",
 234    "D243N",
 235    "D244N",
 236    "D245N",
 237    "D246N",
 238    "D251N",
 239    "D252N",
 240    "D255N",
 241    "D261N",
 242    "D263N",
 243    "D265N",
 244    "D266N",
 245    "D271N",
 246    "D274N",
 247    "D306N",
 248    "D311N",
 249    "D315N",
 250    "D325N",
 251    "D331N",
 252    "D332N",
 253    "D343N",
 254    "D346N",
 255    "D351N",
 256    "D356N",
 257    "D364N",
 258    "D365N",
 259    "D371N",
 260    "D411N",
 261    "D412N",
 262    "D413N",
 263    "D423N",
 264    "D431N",
 265    "D432N",
 266    "D445N",
 267    "D446N",
 268    "D452N",
 269    "D454N",
 270    "D455N",
 271    "D462N",
 272    "D464N",
 273    "D465N",
 274    "D466N",
 275    "D503N",
 276    "D506N",
 277    "D516N",
 278    "D523N",
 279    "D526N",
 280    "D532N",
 281    "D546N",
 282    "D565N",
 283    "D606N",
 284    "D612N",
 285    "D624N",
 286    "D627N",
 287    "D631N",
 288    "D632N",
 289    "D645N",
 290    "D654N",
 291    "D662N",
 292    "D664N",
 293    "D703N",
 294    "D712N",
 295    "D723N",
 296    "D731N",
 297    "D732N",
 298    "D734N",
 299    "D743N",
 300    "D754N",
 301    "D023I",
 302    "D025I",
 303    "D026I",
 304    "D031I",
 305    "D032I",
 306    "D036I",
 307    "D043I",
 308    "D047I",
 309    "D051I",
 310    "D053I",
 311    "D054I",
 312    "D065I",
 313    "D071I",
 314    "D072I",
 315    "D073I",
 316    "D074I",
 317    "D114I",
 318    "D115I",
 319    "D116I",
 320    "D122I",
 321    "D125I",
 322    "D131I",
 323    "D132I",
 324    "D134I",
 325    "D143I",
 326    "D145I",
 327    "D152I",
 328    "D155I",
 329    "D156I",
 330    "D162I",
 331    "D165I",
 332    "D172I",
 333    "D174I",
 334    "D205I",
 335    "D212I",
 336    "D223I",
 337    "D225I",
 338    "D226I",
 339    "D243I",
 340    "D244I",
 341    "D245I",
 342    "D246I",
 343    "D251I",
 344    "D252I",
 345    "D255I",
 346    "D261I",
 347    "D263I",
 348    "D265I",
 349    "D266I",
 350    "D271I",
 351    "D274I",
 352    "D306I",
 353    "D311I",
 354    "D315I",
 355    "D325I",
 356    "D331I",
 357    "D332I",
 358    "D343I",
 359    "D346I",
 360    "D351I",
 361    "D356I",
 362    "D364I",
 363    "D365I",
 364    "D371I",
 365    "D411I",
 366    "D412I",
 367    "D413I",
 368    "D423I",
 369    "D431I",
 370    "D432I",
 371    "D445I",
 372    "D446I",
 373    "D452I",
 374    "D454I",
 375    "D455I",
 376    "D462I",
 377    "D464I",
 378    "D465I",
 379    "D466I",
 380    "D503I",
 381    "D506I",
 382    "D516I",
 383    "D523I",
 384    "D526I",
 385    "D532I",
 386    "D546I",
 387    "D565I",
 388    "D606I",
 389    "D612I",
 390    "D624I",
 391    "D627I",
 392    "D631I",
 393    "D632I",
 394    "D645I",
 395    "D654I",
 396    "D662I",
 397    "D664I",
 398    "D703I",
 399    "D712I",
 400    "D723I",
 401    "D731I",
 402    "D732I",
 403    "D734I",
 404    "D743I",
 405    "D754I",
 406]
 407"""DCS codes in radio order.
 408
 409A tone field with second byte 0x00 stores a DCS code as a 1-based index
 410into this list: indexes 1-105 are normal polarity (``N``) and 106-210 are
 411inverted (``I``).
 412"""
 413
 414
 415class ToneMode(Enum):
 416    """Kind of sub-audio tone used by a channel for transmit or receive."""
 417
 418    OFF = "off"
 419    """No tone; carrier squelch."""
 420    CTCSS = "ctcss"
 421    """Analog sub-audio tone (``ctcss_hz``)."""
 422    DCS = "dcs"
 423    """Digital coded squelch (``dcs_code`` and ``dcs_polarity``)."""
 424
 425
 426@dataclass(slots=True)
 427class ToneSetting:
 428    """Transmit or receive tone of one channel or VFO.
 429
 430    The radio stores a tone in two bytes:
 431
 432    * ``00 00`` (or ``FF FF``): no tone.
 433    * ``nn 00``: DCS, ``nn`` is a 1-based index into ``_DCS_CODES``.
 434    * otherwise: CTCSS in tenths of a hertz, little-endian.
 435
 436    An instance remembers the bytes it was decoded from. As long as the
 437    tone is not changed, :meth:`to_bytes` returns those original bytes, so
 438    unknown encodings survive a read/write cycle unchanged.
 439    """
 440
 441    mode: ToneMode
 442    """Tone kind."""
 443    ctcss_hz: Optional[float] = None
 444    """CTCSS frequency in Hz when ``mode`` is CTCSS."""
 445    dcs_code: Optional[int] = None
 446    """DCS code as an octal-looking integer (e.g. ``23`` for D023) when
 447    ``mode`` is DCS.
 448    """
 449    dcs_polarity: Optional[str] = None
 450    """``"N"`` (normal) or ``"I"`` (inverted) for DCS."""
 451    _raw_bytes: bytes = field(default=b"", repr=False, compare=False)
 452    """The two bytes this tone was decoded from (empty for a new tone).
 453    Returned unchanged by :meth:`to_bytes` while the tone is not edited.
 454    """
 455    _original_state: Optional[tuple] = field(
 456        default=None, repr=False, compare=False)
 457    """``(mode, ctcss_hz, dcs_code, dcs_polarity)`` when the tone was
 458    created or last encoded; compared with the current state to detect an
 459    edit.
 460    """
 461
 462    def __post_init__(self) -> None:
 463        """Snapshot the initial state for change tracking."""
 464        if self._original_state is None:
 465            object.__setattr__(self, "_original_state", self._state_tuple())
 466
 467    def _state_tuple(self) -> tuple:
 468        """Return the user-visible fields as a tuple for change detection.
 469
 470        Returns:
 471            tuple: ``(mode, ctcss_hz, dcs_code, dcs_polarity)``.
 472        """
 473        return (
 474            self.mode,
 475            self.ctcss_hz,
 476            self.dcs_code,
 477            self.dcs_polarity,
 478        )
 479
 480    @property
 481    def is_off(self) -> bool:
 482        """Whether no tone is set (``mode`` is OFF)."""
 483        return self.mode is ToneMode.OFF
 484
 485    @classmethod
 486    def off(cls) -> "ToneSetting":
 487        """Create a tone setting without a tone.
 488
 489        Returns:
 490            ToneSetting: A setting with ``mode`` OFF.
 491        """
 492        return cls(ToneMode.OFF)
 493
 494    @classmethod
 495    def ctcss(cls, hz: float) -> "ToneSetting":
 496        """Create a CTCSS tone setting.
 497
 498        Args:
 499            hz: CTCSS frequency in hertz, e.g. ``88.5``.
 500
 501        Returns:
 502            ToneSetting: A setting with ``mode`` CTCSS.
 503        """
 504        return cls(ToneMode.CTCSS, ctcss_hz=hz)
 505
 506    @classmethod
 507    def dcs(cls, code: int, polarity: str) -> "ToneSetting":
 508        """Create a DCS tone setting.
 509
 510        Args:
 511            code: DCS code as written, e.g. ``23`` for D023.
 512            polarity: ``"N"`` or ``"I"`` (case-insensitive).
 513
 514        Returns:
 515            ToneSetting: A setting with ``mode`` DCS.
 516        """
 517        return cls(ToneMode.DCS, dcs_code=code, dcs_polarity=polarity.upper())
 518
 519    def to_display(self) -> str:
 520        """Format the tone the way the CPS shows it.
 521
 522        Returns:
 523            str: ``"OFF"``, a CTCSS value such as ``"88.5"`` or a DCS code
 524            such as ``"D023N"``.
 525        """
 526        if self.mode is ToneMode.OFF:
 527            return "OFF"
 528        if self.mode is ToneMode.CTCSS and self.ctcss_hz is not None:
 529            return f"{self.ctcss_hz:.1f}"
 530        if (self.mode is ToneMode.DCS and self.dcs_code is not None
 531                and self.dcs_polarity):
 532            return f"D{self.dcs_code:03}{self.dcs_polarity.upper()}"
 533        return "OFF"
 534
 535    def to_bytes(self) -> bytes:
 536        """Encode the tone into the radio's two-byte format.
 537
 538        Unchanged tones return the bytes they were decoded from. A DCS or
 539        CTCSS tone without a code, polarity or frequency encodes as ``00 00``
 540        (no tone). After encoding, the new bytes become the reference for
 541        the next change check.
 542
 543        Returns:
 544            bytes: Two bytes as stored in a channel or VFO record.
 545
 546        Raises:
 547            ValueError: If the DCS code is not in ``_DCS_CODES`` or the
 548                CTCSS value is not within 0.1-6553.5 Hz.
 549        """
 550        current_state = self._state_tuple()
 551        if (
 552            self._original_state is not None
 553            and current_state == self._original_state
 554            and self._raw_bytes
 555        ):
 556            return self._raw_bytes
 557
 558        if self.mode is ToneMode.OFF:
 559            result = b"\x00\x00"
 560        elif self.mode is ToneMode.DCS and self.dcs_code is not None and self.dcs_polarity:
 561            token = f"D{self.dcs_code:03}{self.dcs_polarity.upper()}"
 562            try:
 563                index = _DCS_CODES.index(token)
 564            except ValueError as exc:
 565                raise ValueError(f"Unsupported DCS code {token}") from exc
 566            result = bytes((index + 1, 0x00))
 567        elif self.mode is ToneMode.CTCSS and self.ctcss_hz is not None:
 568            value = int(round(self.ctcss_hz * 10))
 569            if value <= 0 or value > 0xFFFF:
 570                raise ValueError(f"CTCSS value out of range: {self.ctcss_hz}")
 571            result = bytes((value & 0xFF, (value >> 8) & 0xFF))
 572        else:
 573            result = b"\x00\x00"
 574
 575        object.__setattr__(self, "_raw_bytes", result)
 576        object.__setattr__(self, "_original_state", current_state)
 577        return result
 578
 579    @staticmethod
 580    def from_bytes(raw: bytes) -> "ToneSetting":
 581        """Decode a two-byte tone field.
 582
 583        Unknown DCS indexes are logged and decoded as OFF; the original bytes
 584        are kept, so they are written back unchanged unless the tone is edited.
 585
 586        Args:
 587            raw: The two tone bytes from a channel or VFO record.
 588
 589        Returns:
 590            ToneSetting: The decoded tone, remembering ``raw``.
 591
 592        Raises:
 593            ValueError: If ``raw`` is not exactly two bytes long.
 594        """
 595        if len(raw) != 2:
 596            raise ValueError("Tone bytes must be length 2")
 597        first, second = raw
 598        if first == 0 and second == 0:
 599            setting = ToneSetting.off()
 600        elif second == 0:
 601            index = first
 602            if 1 <= index <= len(_DCS_CODES):
 603                token = _DCS_CODES[index - 1]
 604                code = int(token[1:4])
 605                polarity = token[4]
 606                setting = ToneSetting.dcs(code, polarity)
 607            else:
 608                LOG.warning("Unknown DCS index %s", index)
 609                setting = ToneSetting.off()
 610        else:
 611            value = (second << 8) | first
 612            if value == 0xFFFF:
 613                setting = ToneSetting.off()
 614            else:
 615                hz = value / 10.0
 616                setting = ToneSetting.ctcss(hz)
 617
 618        object.__setattr__(setting, "_raw_bytes", bytes(raw))
 619        object.__setattr__(setting, "_original_state", setting._state_tuple())
 620        return setting
 621
 622class PowerLevel(Enum):
 623    """Transmit power as stored in the low nibble of channel byte 14."""
 624
 625    HIGH = 0
 626    """High power (stored value 0)."""
 627    MEDIUM = 1
 628    """Medium power (stored value 1)."""
 629    LOW = 2
 630    """Low power (stored value 2)."""
 631
 632class Bandwidth(Enum):
 633    """FM channel bandwidth (bit 6 of the channel flags byte).
 634
 635    Note:
 636        The enum values do not equal the stored bit; the codecs translate.
 637    """
 638
 639    NARROW = 0
 640    """Narrow FM, 12.5 kHz; stored as bit 6 = 1."""
 641    WIDE = 1
 642    """Wide FM, 25 kHz; stored as bit 6 = 0."""
 643
 644class Modulation(Enum):
 645    """Receive modulation (bit 0 of the channel flags byte)."""
 646
 647    FM = 0
 648    """Frequency modulation; stored as bit 0 = 0."""
 649    AM = 1
 650    """Amplitude modulation, e.g. airband; stored as bit 0 = 1."""
 651
 652@dataclass(slots=True)
 653class ChannelRecord:
 654    """One 32-byte memory channel.
 655
 656    Byte layout:
 657
 658        0-3    RX frequency, packed BCD, 10 Hz units, little-endian
 659        4-7    TX frequency, same format
 660        8-9    RX tone (see ToneSetting)
 661        10-11  TX tone
 662        12     signalling group (low nibble); high nibble unknown, kept
 663        13     PTT ID (low nibble); high nibble unknown, kept
 664        14     scrambler (high nibble) | power (low nibble)
 665        15     flags: b7 learn FHSS, b6 narrow, b5-4 encryption,
 666               b3 busy lockout, b2 scan add, b1 TX enabled, b0 AM
 667        16-19  FHSS code (byte 3 == 0xA0 when set)
 668        20-31  name, GB2312, padded with 0xFF
 669
 670    An unchanged record serialises to exactly the bytes it was read from.
 671    """
 672
 673    rx_hz: Optional[int]
 674    """Receive frequency in Hz, or ``None`` for an empty slot."""
 675    tx_hz: Optional[int]
 676    """Transmit frequency in Hz, or ``None``."""
 677    rx_tone: ToneSetting
 678    """Receive (decode) tone."""
 679    tx_tone: ToneSetting
 680    """Transmit (encode) tone."""
 681    signalling_group: int
 682    """DTMF signalling group, 0-15."""
 683    ptt_id: int
 684    """PTT ID mode, 0-15."""
 685    power: PowerLevel
 686    """Transmit power."""
 687    scrambler: int
 688    """Scrambler code, 0-15 (0 = off)."""
 689    learn_fhss: bool
 690    """Learn-FHSS flag."""
 691    bandwidth: Bandwidth
 692    """FM bandwidth."""
 693    encryption: int
 694    """Encryption mode, 0-3 (0 = off)."""
 695    busy_lockout: bool
 696    """Busy-channel lockout."""
 697    scan_add: bool
 698    """``True`` if the channel is included in scanning."""
 699    tx_enabled: bool
 700    """TX-enable flag as stored by the radio."""
 701    rx_modulation: Modulation
 702    """Receive modulation."""
 703    fhss_code: Optional[str]
 704    """Six hex digits, or ``None``."""
 705    name: str
 706    """Channel name, up to 12 bytes in GB2312."""
 707    _raw_bytes: bytes = field(default=b"", repr=False, compare=False)
 708    """The 32 bytes this record was decoded from (empty for a new record).
 709    Returned unchanged by :meth:`to_bytes` while the record is not edited,
 710    so unknown bits survive a read/write cycle.
 711    """
 712    _original_state: Optional[tuple] = field(default=None, repr=False, compare=False)
 713    """Result of ``_state_tuple()`` when the record was decoded or last
 714    encoded, or ``None`` for a new record; used to detect an edit.
 715    """
 716
 717    @classmethod
 718    def from_bytes(cls, data: bytes, *, logger: Optional[logging.Logger] = None) -> "ChannelRecord":
 719        """Parse a raw 32-byte channel record.
 720
 721        A power nibble above 2 is decoded as LOW; the raw bytes are kept, so
 722        they are written back unchanged unless the record is edited.
 723
 724        Args:
 725            data: Exactly 32 bytes from the channel area.
 726            logger: Logger for name-decoding warnings; defaults to ``LOG``.
 727
 728        Returns:
 729            ChannelRecord: The decoded record, remembering ``data``.
 730
 731        Raises:
 732            ValueError: If ``data`` is not 32 bytes or holds invalid BCD.
 733        """
 734        if len(data) != 32:
 735            raise ValueError("Channel record must be exactly 32 bytes")
 736        logger = logger or LOG
 737        rx_hz = _decode_frequency(data[0:4])
 738        tx_hz = _decode_frequency(data[4:8])
 739        rx_tone = ToneSetting.from_bytes(data[8:10])
 740        tx_tone = ToneSetting.from_bytes(data[10:12])
 741        signalling_group = data[12] & 0x0F
 742        ptt_id = data[13] & 0x0F
 743        power = PowerLevel(min(data[14] & 0x0F, 2))
 744        scrambler = (data[14] >> 4) & 0x0F
 745        flags = data[15]
 746        learn_fhss = bool(flags & 0x80)
 747        # Radio uses bit6: 1 = NARROW, 0 = WIDE
 748        bandwidth = Bandwidth.NARROW if ((flags >> 6) & 0x01) else Bandwidth.WIDE
 749        encryption = (flags >> 4) & 0x03
 750        busy_lockout = bool(flags & 0x08)
 751        scan_add = bool(flags & 0x04)
 752        tx_enabled = bool(flags & 0x02)
 753        rx_modulation = Modulation(flags & 0x01)
 754        fhss_code = _decode_fhss_code(data[16:20])
 755        name = _decode_name(data[20:32], logger)
 756        record = cls(
 757            rx_hz=rx_hz,
 758            tx_hz=tx_hz,
 759            rx_tone=rx_tone,
 760            tx_tone=tx_tone,
 761            signalling_group=signalling_group,
 762            ptt_id=ptt_id,
 763            power=power,
 764            scrambler=scrambler,
 765            learn_fhss=learn_fhss,
 766            bandwidth=bandwidth,
 767            encryption=encryption,
 768            busy_lockout=busy_lockout,
 769            scan_add=scan_add,
 770            tx_enabled=tx_enabled,
 771            rx_modulation=rx_modulation,
 772            fhss_code=fhss_code,
 773            name=name,
 774        )
 775        record._raw_bytes = bytes(data)
 776        record._original_state = record._state_tuple()
 777        return record
 778
 779    def to_bytes(self, *, logger: Optional[logging.Logger] = None) -> bytes:
 780        """Serialise the record into the radio's 32-byte format.
 781
 782        An unchanged record returns its original bytes. A changed record is
 783        rebuilt from scratch; the new bytes then become the reference for the
 784        next change check. Rebuilding writes the known fields; the high
 785        nibbles of bytes 12 and 13 (meaning unknown) are taken from the
 786        original bytes (0 if that byte was 0xFF), the FHSS field becomes
 787        0xFF x 4 when no code is set, and the name is padded with 0xFF.
 788
 789        Args:
 790            logger: Logger for name-encoding warnings; defaults to ``LOG``.
 791
 792        Returns:
 793            bytes: 32 bytes ready to be written to the channel area.
 794
 795        Raises:
 796            ValueError: If a frequency, tone or FHSS code cannot be encoded.
 797        """
 798        logger = logger or LOG
 799
 800        current_state = self._state_tuple()
 801        if self._original_state is not None and current_state == self._original_state:
 802            if self._raw_bytes:
 803                return self._raw_bytes
 804
 805        buf = bytearray(b"\xFF" * 32)
 806        buf[0:4] = _encode_frequency(self.rx_hz)
 807        buf[4:8] = _encode_frequency(self.tx_hz)
 808        buf[8:10] = self.rx_tone.to_bytes()
 809        buf[10:12] = self.tx_tone.to_bytes()
 810        # Keep the high nibbles of bytes 12-13 (meaning unknown) from the
 811        # bytes this record was decoded from; 0xFF counts as 0.
 812        old = self._raw_bytes if len(self._raw_bytes) == 32 else b""
 813        high12 = old[12] & 0xF0 if old and old[12] != 0xFF else 0
 814        high13 = old[13] & 0xF0 if old and old[13] != 0xFF else 0
 815        buf[12] = high12 | (self.signalling_group & 0x0F)
 816        buf[13] = high13 | (self.ptt_id & 0x0F)
 817        scram = self.scrambler & 0x0F
 818        power_value = self.power.value & 0x0F
 819        buf[14] = (scram << 4) | power_value
 820        flags = 0
 821        if self.learn_fhss:
 822            flags |= 0x80
 823        # Radio uses bit6: 1 = NARROW, 0 = WIDE
 824        if self.bandwidth is Bandwidth.NARROW:
 825            flags |= 0x40
 826        flags |= (self.encryption & 0x03) << 4
 827        if self.busy_lockout:
 828            flags |= 0x08
 829        if self.scan_add:
 830            flags |= 0x04
 831        if self.tx_enabled:
 832            flags |= 0x02
 833        if self.rx_modulation is Modulation.AM:
 834            flags |= 0x01
 835        buf[15] = flags
 836        buf[16:20] = _encode_fhss_code(self.fhss_code)
 837        buf[20:32] = _encode_name(self.name, logger)
 838        result = bytes(buf)
 839        self._raw_bytes = result
 840        self._original_state = current_state
 841        return result
 842
 843    def _state_tuple(self) -> tuple:
 844        """Return all user-visible fields as a tuple for change detection.
 845
 846        Returns:
 847            tuple: The field values, with tones reduced to their own state
 848            tuples.
 849        """
 850        return (
 851            self.rx_hz,
 852            self.tx_hz,
 853            self.rx_tone._state_tuple(),
 854            self.tx_tone._state_tuple(),
 855            self.signalling_group,
 856            self.ptt_id,
 857            self.power,
 858            self.scrambler,
 859            self.learn_fhss,
 860            self.bandwidth,
 861            self.encryption,
 862            self.busy_lockout,
 863            self.scan_add,
 864            self.tx_enabled,
 865            self.rx_modulation,
 866            self.fhss_code,
 867            self.name,
 868        )
 869
 870def _decode_frequency(raw: bytes) -> Optional[int]:
 871    """Decode a channel frequency field.
 872
 873    The four bytes are packed BCD, least significant byte first, in units
 874    of 10 Hz (``50 12 52 14`` is 145.21250 MHz).
 875
 876    Args:
 877        raw: Four frequency bytes.
 878
 879    Returns:
 880        int | None: Frequency in Hz, or ``None`` if all bytes are 0x00/0xFF.
 881
 882    Raises:
 883        ValueError: If ``raw`` is not four bytes or contains a non-BCD nibble.
 884    """
 885    if len(raw) != 4:
 886        raise ValueError("Frequency field must be 4 bytes")
 887    if all(b in (0x00, 0xFF) for b in raw):
 888        return None
 889    digits = []
 890    for byte in raw:
 891        high = (byte >> 4) & 0x0F
 892        low = byte & 0x0F
 893        if high > 9 or low > 9:
 894            raise ValueError(f"Invalid BCD digit in frequency byte {byte:02X}")
 895        digits.append(high * 10 + low)
 896    value = 0
 897    for chunk in reversed(digits):
 898        value = value * 100 + chunk
 899    return value * 10
 900
 901def _encode_frequency(hz: Optional[int]) -> bytes:
 902    """Encode a frequency into the four-byte channel format.
 903
 904    Args:
 905        hz: Frequency in Hz; ``None`` or 0 gives an empty field (0xFF x 4).
 906
 907    Returns:
 908        bytes: Four bytes, packed BCD, 10 Hz units, least significant first.
 909
 910    Raises:
 911        ValueError: If ``hz`` is not a multiple of 10 or exceeds 8 digits.
 912    """
 913    if hz is None or hz == 0:
 914        return b"\xFF" * 4
 915    if hz % 10 != 0:
 916        raise ValueError("Frequency must align to 10 Hz steps")
 917    value = hz // 10
 918    digits = []
 919    for _ in range(4):
 920        digits.append(value % 100)
 921        value //= 100
 922    if value:
 923        raise ValueError("Frequency value exceeds 32-bit packed BCD range")
 924    out = bytearray()
 925    for chunk in digits:
 926        high = chunk // 10
 927        low = chunk % 10
 928        out.append((high << 4) | low)
 929    return bytes(out)
 930
 931def _decode_fhss_code(raw: bytes) -> Optional[str]:
 932    """Decode the FHSS code field.
 933
 934    Byte 3 is 0xA0 when a code is set; bytes 2, 1, 0 hold its six hex
 935    digits from most to least significant.
 936
 937    Args:
 938        raw: Four FHSS bytes.
 939
 940    Returns:
 941        str | None: Six upper-case hex digits, or ``None`` if not set.
 942
 943    Raises:
 944        ValueError: If ``raw`` is not four bytes.
 945    """
 946    if len(raw) != 4:
 947        raise ValueError("FHSS field must be 4 bytes")
 948    if raw[3] != 0xA0:
 949        return None
 950    digits = "0123456789ABCDEF"
 951    parts = []
 952    for byte in reversed(raw[:3]):
 953        parts.append(digits[(byte >> 4) & 0x0F])
 954        parts.append(digits[byte & 0x0F])
 955    return "".join(parts)
 956
 957def _encode_fhss_code(code: Optional[str]) -> bytes:
 958    """Encode an FHSS code into its four-byte field.
 959
 960    Args:
 961        code: Six hex digits, or empty/``None`` for no code.
 962
 963    Returns:
 964        bytes: Four bytes; 0xFF x 4 when no code is given.
 965
 966    Raises:
 967        ValueError: If ``code`` is not six hex characters.
 968    """
 969    buf = bytearray(b"\xFF\xFF\xFF\xFF")
 970    if not code:
 971        return bytes(buf)
 972    token = code.strip().upper()
 973    if len(token) != 6 or any(c not in "0123456789ABCDEF" for c in token):
 974        raise ValueError(f"FHSS code must be 6 hex characters: {code}")
 975    buf[3] = 0xA0
 976    digits = "0123456789ABCDEF"
 977    buf[2] = (digits.index(token[0]) << 4) | digits.index(token[1])
 978    buf[1] = (digits.index(token[2]) << 4) | digits.index(token[3])
 979    buf[0] = (digits.index(token[4]) << 4) | digits.index(token[5])
 980    return bytes(buf)
 981
 982def _decode_name(raw: bytes, logger: logging.Logger) -> str:
 983    """Decode a channel name.
 984
 985    Decoding stops at the first 0x00 or 0xFF byte. Invalid GB2312 bytes
 986    are replaced and logged.
 987
 988    Args:
 989        raw: The 12-byte name field.
 990        logger: Logger for decoding warnings.
 991
 992    Returns:
 993        str: The name, or ``""`` if empty.
 994    """
 995    data = bytearray()
 996    for byte in raw:
 997        if byte in (0xFF, 0x00):
 998            break
 999        data.append(byte)
1000    if not data:
1001        return ""
1002    try:
1003        return data.decode("gb2312")
1004    except UnicodeDecodeError:
1005        name = data.decode("gb2312", errors="replace")
1006        logger.warning("Channel name contained invalid GB2312 bytes: %s", data.hex())
1007        return name
1008
1009def _encode_name(name: str, logger: logging.Logger) -> bytes:
1010    """Encode a channel name into the 12-byte GB2312 field.
1011
1012    If the name cannot be encoded as GB2312, the whole name is
1013    NFKD-normalised and reduced to its ASCII characters (all non-ASCII
1014    characters, including valid GB2312 ones, are dropped); if nothing ASCII
1015    remains, the GB2312-encodable characters are kept instead. Characters
1016    that still cannot be encoded are dropped, and the result is truncated to
1017    12 bytes without splitting a character. Every change is logged.
1018
1019    Args:
1020        name: Channel name.
1021        logger: Logger for warnings about altered names.
1022
1023    Returns:
1024        bytes: 12 bytes, padded with 0xFF.
1025    """
1026    if not name:
1027        return b"\xFF" * 12
1028    working = name
1029    try:
1030        working.encode("gb2312")
1031    except UnicodeEncodeError:
1032        normalised = unicodedata.normalize("NFKD", working)
1033        ascii_only = normalised.encode("ascii", errors="ignore").decode("ascii")
1034        if not ascii_only:
1035            ascii_only = normalised.encode("gb2312", errors="ignore").decode(
1036                "gb2312", errors="ignore"
1037            )
1038        logger.warning(
1039            "Channel name '%s' contains non-GB2312 characters; stored as '%s'",
1040            name,
1041            ascii_only,
1042        )
1043        working = ascii_only
1044    encoded = bytearray()
1045    for char in working:
1046        try:
1047            char_bytes = char.encode("gb2312")
1048        except UnicodeEncodeError:
1049            logger.warning(
1050                "Dropping character '%s' from channel name '%s' during encoding",
1051                char,
1052                name,
1053            )
1054            continue
1055        if len(encoded) + len(char_bytes) > 12:
1056            logger.warning("Channel name '%s' truncated to 12 bytes", name)
1057            break
1058        encoded.extend(char_bytes)
1059    while len(encoded) < 12:
1060        encoded.append(0xFF)
1061    return bytes(encoded[:12])
1062
1063
1064# ===========================================================================
1065# 2. Settings sections: data structures and codecs
1066# ===========================================================================
1067
1068_DTMF_DIGITS = "0123456789ABCD*#"
1069"""DTMF symbols in radio order; a stored byte is an index into this string.
1070
10710xFF terminates a sequence.
1072"""
1073
1074@dataclass(slots=True)
1075class VFOSettings:
1076    """One 32-byte VFO entry (VFO A, B or C) from the block at 0x8000.
1077
1078    Byte layout:
1079
1080        0-7    RX frequency, one decimal digit per byte, 10 Hz units
1081        8-9    RX tone
1082        10-11  TX tone
1083        13     b0 busy lockout
1084        14     b5-4 offset direction | b3-0 signalling group
1085        16     scrambler (high nibble) | power (low nibble)
1086        17     b7 learn FHSS, b6 narrow, b5-4 encryption, b0 AM
1087        18     frequency band (low nibble)
1088        19     step index (low nibble)
1089        20-26  offset, one decimal digit per byte, 100 Hz units
1090
1091    Bits and bytes not listed are preserved when encoding, except that a
1092    listed byte holding 0xFF is treated as 0 before its fields are written.
1093    """
1094
1095    rx_hz: Optional[int]
1096    """Receive frequency in Hz, or ``None``."""
1097    offset_hz: Optional[int]
1098    """Repeater offset in Hz, or ``None``."""
1099    rx_tone: ToneSetting
1100    """Receive tone."""
1101    tx_tone: ToneSetting
1102    """Transmit tone."""
1103    busy_lockout: bool
1104    """Busy-channel lockout."""
1105    offset_direction: int
1106    """0 none, 1 plus, 2 minus (CPS *Offset Dir*). 3 (split) is not offered
1107    by the CPS or in CHIRP; a stored 3 is kept."""
1108    signalling_group: int
1109    """DTMF signalling group as stored, 0-14; the CPS shows it plus one
1110    (1-15)."""
1111    tx_power: PowerLevel
1112    """Transmit power: stored 0 High, 1 Middle (``MEDIUM``), 2 Low."""
1113    scrambler: int
1114    """Scrambler code, 0 (off) to 8; the nibble can hold up to 15."""
1115    learn_fhss: bool
1116    """Learn-FHSS flag; not shown in the CPS *VFO Mode* screen or in CHIRP,
1117    kept as stored."""
1118    bandwidth: Bandwidth
1119    """FM bandwidth."""
1120    encryption: int
1121    """Encryption mode, 0-3."""
1122    rx_modulation: Modulation
1123    """Receive modulation."""
1124    freq_band: int
1125    """Frequency band, 0 VHF or 1 UHF (see ``_VFO_BAND_CHOICES``)."""
1126    step_freq_index: int
1127    """Step index 0-9, 2.5 kHz to 100 kHz (see ``_VFO_STEP_CHOICES``)."""
1128    _raw_bytes: bytes = field(default=b"", repr=False, compare=False)
1129    """The 32-byte VFO entry this object was decoded from (empty when new).
1130    Written back unchanged by :func:`encode_vfo_section` while the entry
1131    is not edited.
1132    """
1133    _original_state: Optional[tuple] = field(default=None, repr=False, compare=False)
1134    """Result of ``_state_tuple()`` when the entry was decoded or last
1135    encoded, or ``None`` when new; used to detect an edit.
1136    """
1137
1138    def _state_tuple(self) -> tuple:
1139        """Return all user-visible fields as a tuple for change detection.
1140
1141        Returns:
1142            tuple: The field values, with tones reduced to their own state
1143            tuples.
1144        """
1145        return (
1146            self.rx_hz,
1147            self.offset_hz,
1148            self.rx_tone._state_tuple(),
1149            self.tx_tone._state_tuple(),
1150            self.busy_lockout,
1151            self.offset_direction,
1152            self.signalling_group,
1153            self.tx_power,
1154            self.scrambler,
1155            self.learn_fhss,
1156            self.bandwidth,
1157            self.encryption,
1158            self.rx_modulation,
1159            self.freq_band,
1160            self.step_freq_index,
1161        )
1162
1163@dataclass(slots=True)
1164class FunctionSettings:
1165    """Function settings from the 96-byte block at 0x9000.
1166
1167    Values are kept in a flat dictionary keyed by the names used in
1168    ``_FUNCTION_SPECS`` (e.g. ``"sql"``, ``"tot"``, ``"key1_long"``).
1169    """
1170
1171    values: Dict[str, Optional[int]] = field(default_factory=dict)
1172    """Setting name to raw integer value; ``None`` means the byte was 0xFF (not
1173    set).
1174    """
1175
1176@dataclass(slots=True)
1177class DTMFSettings:
1178    """DTMF settings from the 384-byte block at 0xA000.
1179
1180    Layout: a 32-byte info part followed by 22 code groups of 16 bytes.
1181    """
1182
1183    current_id: str
1184    """Own DTMF ID, up to 5 symbols."""
1185    ptt_id_mode: Optional[int]
1186    """PTT ID mode 0-3 (off, BOT, EOT, both), or ``None``."""
1187    last_time_send: Optional[int]
1188    """Raw "last time send" value, or ``None``."""
1189    last_time_stop: Optional[int]
1190    """Raw "last time stop" value, or ``None``."""
1191    code_groups: List[str]
1192    """The 22 code groups, up to 6 symbols each."""
1193
1194@dataclass(slots=True)
1195class ModulationChannelEntry:
1196    """One of the 16 broadcast/SSB memory entries of the modulation screen.
1197
1198    Each entry holds an FM, an AM and an SSB memory side by side.
1199    """
1200
1201    fm_frequency: Optional[int]
1202    """FM broadcast frequency in Hz (stored in 10 kHz units), or ``None``."""
1203    fm_name: str
1204    """FM memory name."""
1205    am_frequency: Optional[int]
1206    """AM broadcast frequency in Hz (stored in 10 kHz units), or ``None``."""
1207    am_name: str
1208    """AM memory name."""
1209    ssb_frequency: Optional[int]
1210    """SSB frequency in Hz (stored in 10 kHz units), or ``None``."""
1211    ssb_bandwidth: Optional[int]
1212    """Raw SSB bandwidth index, or ``None``."""
1213    ssb_beat_offset: Optional[int]
1214    """SSB BFO offset (signed), or ``None``."""
1215    ssb_name: str
1216    """SSB memory name."""
1217
1218@dataclass(slots=True)
1219class ModulationSettings:
1220    """Contents of the modulation blocks (parameters at 0xB000, names at 0xD000)."""
1221
1222    fm_current_channel: Optional[int]
1223    """Selected FM memory, 0-14, or ``None``."""
1224    am_current_channel: Optional[int]
1225    """Selected AM memory, 0-14, or ``None``."""
1226    ssb_current_channel: Optional[int]
1227    """Selected SSB memory, 0-14, or ``None``."""
1228    work_mode: Optional[int]
1229    """Work mode, 0-1, or ``None``."""
1230    modulation_mode: Optional[int]
1231    """Modulation mode, 0-4, or ``None``."""
1232    am_step_index: Optional[int]
1233    """AM step index, 0-3, or ``None``."""
1234    am_rx_gain: Optional[int]
1235    """AM RX gain, 0-36, or ``None``."""
1236    ssb_step_index: Optional[int]
1237    """SSB step index, 0-5, or ``None``."""
1238    ssb_rx_gain: Optional[int]
1239    """SSB RX gain, 0-36, or ``None``."""
1240    channels: List[ModulationChannelEntry]
1241    """The 16 :class:`ModulationChannelEntry` items."""
1242
1243@dataclass(slots=True)
1244class APRSSettings:
1245    """APRS settings from the separate 128-byte APRS space.
1246
1247    Values are kept in a flat dictionary keyed by the names used in
1248    ``_APRS_SPECS`` (e.g. ``"call_sign"``, ``"ssid"``, ``"altitude"``).
1249    """
1250
1251    fields: Dict[str, Optional[object]] = field(default_factory=dict)
1252    """Setting name to value (int or str); ``None`` means not set."""
1253
1254def parse_vfo_section(section: bytes) -> List[VFOSettings]:
1255    """Decode the VFO block into VFO entries.
1256
1257    Args:
1258        section: The used part of the VFO block (normally 96 bytes, three
1259            32-byte entries).
1260
1261    Returns:
1262        list[VFOSettings]: One entry per 32 bytes, in order A, B, C. Each
1263        entry remembers its raw bytes.
1264
1265    Raises:
1266        ValueError: If the length is not a multiple of 32.
1267
1268    Note:
1269        The power nibble (byte 16) holds 0 High, 1 Middle, 2 Low; a higher
1270        value is decoded as Low, as for channels, and written back as 2 only
1271        if that VFO entry is re-encoded because another field changed.
1272    """
1273    if len(section) % 32 != 0:
1274        raise ValueError("VFO section must be a multiple of 32 bytes")
1275    entries: List[VFOSettings] = []
1276    for offset in range(0, len(section), 32):
1277        chunk = section[offset : offset + 32]
1278        rx_hz = _decode_vfo_frequency(chunk[0:8])
1279        rx_tone = ToneSetting.from_bytes(bytes(chunk[8:10]))
1280        tx_tone = ToneSetting.from_bytes(bytes(chunk[10:12]))
1281        busy_lockout = bool(chunk[13] & 0x01)
1282        offset_dir = (chunk[14] >> 4) & 0x03
1283        signalling_group = chunk[14] & 0x0F
1284        tx_power_raw = chunk[16] & 0x0F
1285        tx_power = PowerLevel(min(tx_power_raw, PowerLevel.LOW.value))
1286        scrambler = (chunk[16] >> 4) & 0x0F
1287        learn_fhss = bool((chunk[17] >> 7) & 0x01)
1288        # Radio uses bit6: 1 = NARROW, 0 = WIDE
1289        bandwidth = Bandwidth.NARROW if ((chunk[17] >> 6) & 0x01) else Bandwidth.WIDE
1290        encryption = (chunk[17] >> 4) & 0x03
1291        rx_modulation = Modulation.AM if (chunk[17] & 0x01) else Modulation.FM
1292        freq_band = chunk[18] & 0x0F
1293        step_freq = chunk[19] & 0x0F
1294        offset_hz = _decode_offset_frequency(chunk[20:27])
1295        entry = VFOSettings(
1296            rx_hz=rx_hz,
1297            offset_hz=offset_hz,
1298            rx_tone=rx_tone,
1299            tx_tone=tx_tone,
1300            busy_lockout=busy_lockout,
1301            offset_direction=offset_dir,
1302            signalling_group=signalling_group,
1303            tx_power=tx_power,
1304            scrambler=scrambler,
1305            learn_fhss=learn_fhss,
1306            bandwidth=bandwidth,
1307            encryption=encryption,
1308            rx_modulation=rx_modulation,
1309            freq_band=freq_band,
1310            step_freq_index=step_freq,
1311        )
1312        entry._raw_bytes = bytes(chunk)
1313        entry._original_state = entry._state_tuple()
1314        entries.append(entry)
1315    return entries
1316
1317def parse_function_section(section: bytes) -> FunctionSettings:
1318    """Decode the 96-byte function block.
1319
1320    The block is read as three 32-byte parts; each known byte is mapped to
1321    a named setting (see the ``_set`` calls for the offsets). Each value is
1322    the low nibble of its byte (5 bits for ``key*_long``); byte 26 holds
1323    ``work_mode_a/b/c`` in bits 1-0, 3-2 and 5-4.
1324
1325    Args:
1326        section: Exactly 96 bytes.
1327
1328    Returns:
1329        FunctionSettings: All known settings; 0xFF bytes become ``None``.
1330
1331    Raises:
1332        ValueError: If ``section`` is not 96 bytes.
1333    """
1334    if len(section) != 96:
1335        raise ValueError("Function config section must be 96 bytes")
1336    part1 = section[0:32]
1337    part2 = section[32:64]
1338    part3 = section[64:96]
1339    values: Dict[str, Optional[int]] = {}
1340
1341    def _masked(byte: int, mask: int = 0x0F, shift: int = 0) -> Optional[int]:
1342        """Extract a bit field from one byte; 0xFF (not set) gives ``None``.
1343
1344        Args:
1345            byte: Raw byte value from the function block.
1346            mask: Bit mask applied after shifting (default ``0x0F``).
1347            shift: Number of bits to shift right before masking.
1348
1349        Returns:
1350            Optional[int]: ``(byte >> shift) & mask``, or ``None`` if ``byte`` is 0xFF.
1351        """
1352        if byte == 0xFF:
1353            return None
1354        return (byte >> shift) & mask
1355
1356    def _set(name: str, byte: int, mask: int = 0x0F, shift: int = 0) -> None:
1357        """Store the masked value of ``byte`` under ``name``.
1358
1359        Args:
1360            name: Setting key in the ``values`` dictionary.
1361            byte: Raw byte value from the function block.
1362            mask: Bit mask passed to ``_masked`` (default ``0x0F``).
1363            shift: Right shift passed to ``_masked``.
1364        """
1365        values[name] = _masked(byte, mask, shift)
1366
1367    _set("sql", part1[0])
1368    _set("save_mode", part1[1])
1369    _set("vox", part1[2])
1370    _set("auto_backlight", part1[3])
1371    _set("tdr", part1[4])
1372    _set("tot", part1[5])
1373    _set("beep_prompt", part1[6])
1374    _set("voice_prompt", part1[7])
1375    _set("language", part1[8])
1376    _set("dtmf_mode", part1[9])
1377    _set("scan_mode", part1[10])
1378    _set("ptt_id", part1[11])
1379    _set("send_id_delay", part1[12])
1380    _set("display_mode_a", part1[13])
1381    _set("display_mode_b", part1[14])
1382    _set("display_mode_c", part1[15])
1383    _set("auto_key_lock", part1[16])
1384    _set("alarm_mode", part1[17])
1385    _set("alarm_sound", part1[18])
1386    _set("tail_noise_clear", part1[20])
1387    _set("pass_repeater_noise_clear", part1[21])
1388    _set("pass_repeater_noise_detect", part1[22])
1389    _set("sound_tx_end", part1[23])
1390    _set("current_work_mode", part1[24])
1391    _set("fm_radio", part1[25])
1392    if part1[26] == 0xFF:
1393        values["work_mode_a"] = None
1394        values["work_mode_b"] = None
1395        values["work_mode_c"] = None
1396    else:
1397        values["work_mode_a"] = part1[26] & 0x03
1398        values["work_mode_b"] = (part1[26] >> 2) & 0x03
1399        values["work_mode_c"] = (part1[26] >> 4) & 0x03
1400    _set("lock_keyboard", part1[27])
1401    _set("power_on_message", part1[28])
1402    _set("bt_write_switch", part1[29])
1403    _set("rtone", part1[30])
1404
1405    _set("vox_delay", part2[0])
1406    _set("timer_menu_quit", part2[1])
1407    _set("weather_channel", part2[5])
1408    _set("divide_channel", part2[6])
1409    _set("subaudio_scan_save", part2[7])
1410    _set("vox_switch", part2[8])
1411    _set("key_side1_short", part2[9])
1412    _set("key_side1_long", part2[10])
1413    _set("key_side2_short", part2[11])
1414    _set("key_side2_long", part2[12])
1415    _set("current_work_area_a", part2[13])
1416    _set("current_work_area_b", part2[14])
1417    _set("current_work_area_c", part2[15])
1418    _set("ab_uv_transfer", part2[25])
1419    _set("sound_transfer", part2[26])
1420    _set("key0_long", part2[27], mask=0x1F)
1421    _set("key1_long", part2[28], mask=0x1F)
1422    _set("key2_long", part2[29], mask=0x1F)
1423    _set("key3_long", part2[30], mask=0x1F)
1424    _set("key4_long", part2[31], mask=0x1F)
1425
1426    _set("key5_long", part3[0], mask=0x1F)
1427    _set("key6_long", part3[1], mask=0x1F)
1428    _set("key7_long", part3[2], mask=0x1F)
1429    _set("key8_long", part3[3], mask=0x1F)
1430    _set("key9_long", part3[4], mask=0x1F)
1431
1432    return FunctionSettings(values=values)
1433
1434def parse_dtmf_section(section: bytes) -> DTMFSettings:
1435    """Decode the 384-byte DTMF block.
1436
1437    Args:
1438        section: Exactly 384 bytes: 32 info bytes plus 22 code groups of
1439            16 bytes.
1440
1441    Returns:
1442        DTMFSettings: Own ID, PTT ID mode, timing values and code groups.
1443
1444    Raises:
1445        ValueError: If ``section`` is not 384 bytes.
1446    """
1447    if len(section) != 384:
1448        raise ValueError("DTMF section must be 384 bytes")
1449    info = section[0:32]
1450    groups = section[32:]
1451    current_id = _decode_dtmf_sequence(info[0:5])
1452    ptt_id = info[6] & 0x0F if info[6] != 0xFF else None
1453    last_send = info[7] & 0x0F if info[7] != 0xFF else None
1454    last_stop = info[8] & 0x0F if info[8] != 0xFF else None
1455    code_groups: List[str] = []
1456    for offset in range(0, len(groups), 16):
1457        code_groups.append(_decode_dtmf_sequence(groups[offset : offset + 16], max_len=6))
1458    return DTMFSettings(
1459        current_id=current_id,
1460        ptt_id_mode=ptt_id,
1461        last_time_send=last_send,
1462        last_time_stop=last_stop,
1463        code_groups=code_groups,
1464    )
1465
1466def parse_modulation_sections(mod_block: bytes, name_block: bytes) -> ModulationSettings:
1467    """Decode the modulation parameter and name blocks.
1468
1469    Parameter block layout (offsets in bytes):
1470
1471        0-31     16 FM frequencies, LE uint16, 10 kHz units
1472        32       FM current channel     33  work mode
1473        34-65    16 AM frequencies, LE uint16, 10 kHz units
1474        66       AM current channel     67  modulation mode   68  AM RX gain
1475        69-148   16 SSB entries of 5 bytes: freq (LE uint16, 10 kHz units),
1476                 bandwidth (u8), beat offset (LE int16)
1477        149      SSB current channel   150  SSB step   151  AM step
1478        152      SSB RX gain
1479
1480    Name block: three tables (FM, AM, SSB) of 16 names x 16 bytes, GB2312.
1481
1482    Args:
1483        mod_block: Exactly 256 parameter bytes.
1484        name_block: Exactly 768 name bytes.
1485
1486    Returns:
1487        ModulationSettings: Decoded parameters and the 16 entries.
1488
1489    Raises:
1490        ValueError: If a block has the wrong length.
1491    """
1492    if len(mod_block) != 256:
1493        raise ValueError("Modulation parameter block must be 256 bytes")
1494    if len(name_block) != 768:
1495        raise ValueError("Modulation name block must be 768 bytes")
1496
1497    channels: List[ModulationChannelEntry] = []
1498
1499    def _optional(value: int, modulus: int) -> Optional[int]:
1500        """Return ``value % modulus``, or ``None`` for 0xFF (not set).
1501
1502        Args:
1503            value: Raw byte value from the modulation parameter block.
1504            modulus: Number of valid values; the result is wrapped into ``0..modulus-1``.
1505
1506        Returns:
1507            Optional[int]: ``value % modulus``, or ``None`` if ``value`` is 0xFF.
1508        """
1509        if value == 0xFF:
1510            return None
1511        return value % modulus
1512
1513    fm_freqs = [_decode_le_uint16(mod_block, idx * 2) for idx in range(16)]
1514    fm_current = _optional(mod_block[32], 15)
1515    work_mode = _optional(mod_block[33], 2)
1516    am_freqs = [_decode_le_uint16(mod_block, 34 + idx * 2) for idx in range(16)]
1517    am_current = _optional(mod_block[66], 15)
1518    modulation_mode = _optional(mod_block[67], 5)
1519    am_rx_gain = _optional(mod_block[68], 37)
1520    ssb_freqs = []
1521    ssb_bandwidths = []
1522    ssb_offsets = []
1523    for idx in range(16):
1524        base = 69 + idx * 5
1525        ssb_freqs.append(_decode_le_uint16(mod_block, base))
1526        ssb_bandwidths.append(mod_block[base + 2])
1527        ssb_offsets.append(_decode_le_int16(mod_block, base + 3))
1528    ssb_current = _optional(mod_block[149], 15)
1529    ssb_step = _optional(mod_block[150], 6)
1530    am_step = _optional(mod_block[151], 4)
1531    ssb_rx_gain = _optional(mod_block[152], 37)
1532
1533    fm_names = [_decode_gb2312(name_block, idx * 16) for idx in range(16)]
1534    am_names = [_decode_gb2312(name_block, 256 + idx * 16) for idx in range(16)]
1535    ssb_names = [_decode_gb2312(name_block, 512 + idx * 16) for idx in range(16)]
1536
1537    def _scale_freq(value: int) -> Optional[int]:
1538        """Convert a stored 10 kHz-unit value to Hz; 0 and 0xFFFF mean empty.
1539
1540        Args:
1541            value: Stored LE uint16 frequency in 10 kHz units.
1542
1543        Returns:
1544            Optional[int]: Frequency in Hz, or ``None`` for 0 or 0xFFFF.
1545        """
1546        if value in (0, 0xFFFF):
1547            return None
1548        return value * 10_000
1549
1550    for idx in range(16):
1551        fm_freq = _scale_freq(fm_freqs[idx])
1552        am_freq = _scale_freq(am_freqs[idx])
1553        ssb_freq = _scale_freq(ssb_freqs[idx])
1554        channels.append(
1555            ModulationChannelEntry(
1556                fm_frequency=fm_freq,
1557                fm_name=fm_names[idx],
1558                am_frequency=am_freq,
1559                am_name=am_names[idx],
1560                ssb_frequency=ssb_freq,
1561                ssb_bandwidth=(
1562                    None if ssb_bandwidths[idx] in (0, 0xFF) else int(ssb_bandwidths[idx])
1563                ),
1564                ssb_beat_offset=ssb_offsets[idx] if ssb_freq is not None else None,
1565                ssb_name=ssb_names[idx],
1566            )
1567        )
1568
1569    return ModulationSettings(
1570        fm_current_channel=fm_current,
1571        am_current_channel=am_current,
1572        ssb_current_channel=ssb_current,
1573        work_mode=work_mode,
1574        modulation_mode=modulation_mode,
1575        am_step_index=am_step,
1576        am_rx_gain=am_rx_gain,
1577        ssb_step_index=ssb_step,
1578        ssb_rx_gain=ssb_rx_gain,
1579        channels=channels,
1580    )
1581
1582def parse_aprs_section(section: bytes) -> APRSSettings:
1583    """Decode the 128-byte APRS block.
1584
1585    Latitude is stored at bytes 7-10 (N/S letter, minute, degree, second)
1586    and longitude at bytes 11-14 (W/E letter, minute, degree, second).
1587    ``north_south``/``east_west`` decode ``N``/``W`` as 0 and any other byte
1588    as 1. Minutes and seconds are clamped to 59, degrees to 90/180.
1589    Altitude (bytes 15-16) is a little-endian signed 16-bit value clamped to
1590    +/-10000. Single-byte settings keep their low nibble (byte 6: 5 bits,
1591    byte 27: 7 bits). Text fields are ASCII (call sign, routes) or GB2312
1592    (custom message).
1593
1594    Args:
1595        section: Exactly 128 bytes.
1596
1597    Returns:
1598        APRSSettings: All known fields; 0xFF bytes become ``None``.
1599
1600    Raises:
1601        ValueError: If ``section`` is not 128 bytes.
1602    """
1603    if len(section) != 128:
1604        raise ValueError("APRS section must be 128 bytes")
1605    data = section
1606    fields: Dict[str, Optional[object]] = {}
1607
1608    def _set(name: str, idx: int, mask: int = 0x0F) -> None:
1609        """Store the masked byte at ``idx`` under ``name``; 0xFF gives ``None``.
1610
1611        Args:
1612            name: Field key in the ``fields`` dictionary.
1613            idx: Byte offset within the 128-byte APRS block.
1614            mask: Bit mask applied to the byte (default ``0x0F``).
1615        """
1616        byte = data[idx]
1617        if byte == 0xFF:
1618            fields[name] = None
1619        else:
1620            fields[name] = byte & mask
1621
1622    _set("aprs_switch", 0)
1623    _set("gps_switch", 1)
1624    _set("latlon_unit", 2)
1625    _set("speed_unit", 3)
1626    _set("distance_unit", 4)
1627    _set("altitude_unit", 5)
1628    _set("time_zone", 6, mask=0x1F)
1629    north_byte = data[7]
1630    if north_byte == 0xFF:
1631        fields["north_south"] = None
1632    else:
1633        fields["north_south"] = 0 if north_byte == 0x4E else 1
1634    fields["latitude_minute"] = None if data[8] == 0xFF else min(59, data[8])
1635    fields["latitude_degree"] = None if data[9] == 0xFF else min(90, data[9])
1636    fields["latitude_second"] = None if data[10] == 0xFF else min(59, data[10])
1637    east_byte = data[11]
1638    if east_byte == 0xFF:
1639        fields["east_west"] = None
1640    else:
1641        fields["east_west"] = 0 if east_byte == 0x57 else 1
1642    fields["longitude_minute"] = None if data[12] == 0xFF else min(59, data[12])
1643    fields["longitude_degree"] = None if data[13] == 0xFF else min(180, data[13])
1644    fields["longitude_second"] = None if data[14] == 0xFF else min(59, data[14])
1645    alt_bytes = data[15:17]
1646    if all(b == 0xFF for b in alt_bytes):
1647        fields["altitude"] = None
1648    else:
1649        altitude = int.from_bytes(bytes(alt_bytes), "little", signed=True)
1650        fields["altitude"] = max(-10000, min(10000, altitude))
1651
1652    fields["call_sign"] = _decode_ascii(data, 17, 6)
1653    _set("ssid", 23)
1654    _set("routing_select", 24)
1655    _set("my_position", 25)
1656    _set("radio_symbol", 26)
1657    if data[27] == 0xFF:
1658        fields["user_defined_icon"] = None
1659    else:
1660        fields["user_defined_icon"] = data[27] & 0x7F
1661    _set("aprs_priority", 29)
1662    _set("data_tx_delay", 30)
1663    _set("aprs_decode_prompt_tone", 32)
1664    _set("aprs_rx_auto_popup", 33)
1665    _set("beacon_tx_type", 34)
1666    _set("timed_beacon_time", 36)
1667    _set("mice_type", 38)
1668    _set("tnc_data_type", 39)
1669    _set("aprs_forward_channel", 40)
1670    _set("aprs_forward_routing", 41)
1671    _set("aprs_wait_forward", 42)
1672    fields["custom_routing_one"] = _decode_ascii(data, 43, 6)
1673    _set("custom_routing_one_ssid", 49)
1674    fields["custom_routing_two"] = _decode_ascii(data, 50, 6)
1675    _set("custom_routing_two_ssid", 56)
1676    _set("send_custom_messages", 78)
1677    fields["custom_messages"] = _decode_gb2312(data, 79, max_len=40)
1678
1679    return APRSSettings(fields=fields)
1680
1681# ---------------------------------------------------------------------------
1682# Encoding helpers
1683# ---------------------------------------------------------------------------
1684
1685def encode_vfo_section(vfos: Optional[List[VFOSettings]], raw: Optional[bytes]) -> bytes:
1686    """Encode VFO entries into the 96-byte VFO block.
1687
1688    Unchanged entries are copied back verbatim. Changed entries are written
1689    over their previous bytes, so bits the driver does not know survive,
1690    except that a field byte holding 0xFF is treated as 0 first.
1691    ``rx_hz`` or ``offset_hz`` of ``None`` keeps the stored digits. Entries
1692    beyond the third are ignored. Each re-encoded entry's change-tracking
1693    snapshot is updated to the new bytes.
1694
1695    Args:
1696        vfos: Up to three entries; ``None`` or empty leaves ``raw`` as is.
1697        raw: The original 96 bytes; anything else starts from 0xFF.
1698
1699    Returns:
1700        bytes: The 96-byte VFO block.
1701    """
1702    if raw and len(raw) == 96:
1703        buffer = bytearray(raw)
1704    else:
1705        buffer = bytearray(b"\xFF" * 96)
1706    if not vfos:
1707        return bytes(buffer)
1708    mv = memoryview(buffer)
1709    for idx, entry in enumerate(vfos[:3]):
1710        start = idx * 32
1711        current_state = entry._state_tuple()
1712        if (
1713            entry._original_state is not None
1714            and current_state == entry._original_state
1715            and entry._raw_bytes
1716        ):
1717            mv[start : start + 32] = entry._raw_bytes
1718            continue
1719        source = (
1720            entry._raw_bytes if len(entry._raw_bytes) == 32 else bytes(mv[start : start + 32])
1721        )
1722        chunk = bytearray(source)
1723        if entry.rx_hz is not None:
1724            chunk[0:8] = _encode_vfo_frequency(entry.rx_hz)
1725        chunk[8:10] = entry.rx_tone.to_bytes()
1726        chunk[10:12] = entry.tx_tone.to_bytes()
1727        base13 = 0 if chunk[13] == 0xFF else chunk[13] & ~0x01
1728        chunk[13] = base13 | (0x01 if entry.busy_lockout else 0x00)
1729        preserved14 = 0 if chunk[14] == 0xFF else chunk[14] & 0xC0
1730        chunk[14] = (
1731            preserved14
1732            | ((entry.offset_direction & 0x03) << 4)
1733            | (entry.signalling_group & 0x0F)
1734        )
1735        chunk[16] = ((entry.scrambler & 0x0F) << 4) | (entry.tx_power.value & 0x0F)
1736        flags = 0 if chunk[17] == 0xFF else chunk[17] & ~(0x80 | 0x40 | 0x30 | 0x01)
1737        if entry.learn_fhss:
1738            flags |= 0x80
1739        # Radio uses bit6: 1 = NARROW, 0 = WIDE
1740        if entry.bandwidth is Bandwidth.NARROW:
1741            flags |= 0x40
1742        flags |= (entry.encryption & 0x03) << 4
1743        if entry.rx_modulation is Modulation.AM:
1744            flags |= 0x01
1745        chunk[17] = flags
1746        preserved18 = 0 if chunk[18] == 0xFF else chunk[18] & 0xF0
1747        chunk[18] = preserved18 | (entry.freq_band & 0x0F)
1748        preserved19 = 0 if chunk[19] == 0xFF else chunk[19] & 0xF0
1749        chunk[19] = preserved19 | (entry.step_freq_index & 0x0F)
1750        if entry.offset_hz is not None:
1751            chunk[20:27] = _encode_offset_frequency(entry.offset_hz)
1752        encoded = bytes(chunk)
1753        mv[start : start + 32] = encoded
1754        entry._raw_bytes = encoded
1755        entry._original_state = entry._state_tuple()
1756    return bytes(buffer)
1757
1758def encode_function_section(settings: Optional[FunctionSettings], raw: Optional[bytes]) -> bytes:
1759    """Encode function settings into the 96-byte function block.
1760
1761    Only the bits of each field are replaced; other bits in the same byte
1762    are preserved, but a byte holding 0xFF is treated as 0 when merging
1763    bits. A value of ``None``, or a key missing from ``settings.values``,
1764    writes 0xFF over the whole byte. Byte 26 packs ``work_mode_a/b/c``
1765    (bits 1-0, 3-2, 5-4); it becomes 0xFF if any of the three is ``None``.
1766
1767    Args:
1768        settings: Settings to write; ``None`` leaves ``raw`` as is.
1769        raw: The original 96 bytes; anything else starts from 0xFF.
1770
1771    Returns:
1772        bytes: The 96-byte function block.
1773    """
1774    if raw and len(raw) == 96:
1775        buffer = bytearray(raw)
1776    else:
1777        buffer = bytearray(b"\xFF" * 96)
1778    if settings is None:
1779        return bytes(buffer)
1780    part1 = memoryview(buffer)[0:32]
1781    part2 = memoryview(buffer)[32:64]
1782    part3 = memoryview(buffer)[64:96]
1783    values = settings.values
1784
1785    def _set(part: memoryview, index: int, key: str, mask: int = 0x0F, shift: int = 0) -> None:
1786        """Write ``values[key]`` into ``part[index]`` under ``mask``/``shift``.
1787
1788        ``None`` writes 0xFF; otherwise bits outside ``mask << shift`` are kept,
1789        except that a 0xFF byte is treated as 0.
1790
1791        Args:
1792            part: 32-byte view of one third of the function block.
1793            index: Byte offset within ``part`` (0-31).
1794            key: Setting key in ``settings.values``.
1795            mask: Bit mask of the field before shifting (default ``0x0F``).
1796            shift: Bit position of the field within the byte.
1797        """
1798        value = values.get(key)
1799        if value is None:
1800            part[index] = 0xFF
1801            return
1802        encoded = (int(value) & mask) << shift
1803        current = part[index]
1804        if current == 0xFF:
1805            base = 0
1806        else:
1807            base = current & ~(mask << shift)
1808        part[index] = base | encoded
1809
1810    _set(part1, 0, "sql")
1811    _set(part1, 1, "save_mode")
1812    _set(part1, 2, "vox")
1813    _set(part1, 3, "auto_backlight")
1814    _set(part1, 4, "tdr")
1815    _set(part1, 5, "tot")
1816    _set(part1, 6, "beep_prompt")
1817    _set(part1, 7, "voice_prompt")
1818    _set(part1, 8, "language")
1819    _set(part1, 9, "dtmf_mode")
1820    _set(part1, 10, "scan_mode")
1821    _set(part1, 11, "ptt_id")
1822    _set(part1, 12, "send_id_delay")
1823    _set(part1, 13, "display_mode_a")
1824    _set(part1, 14, "display_mode_b")
1825    _set(part1, 15, "display_mode_c")
1826    _set(part1, 16, "auto_key_lock")
1827    _set(part1, 17, "alarm_mode")
1828    _set(part1, 18, "alarm_sound")
1829    _set(part1, 20, "tail_noise_clear")
1830    _set(part1, 21, "pass_repeater_noise_clear")
1831    _set(part1, 22, "pass_repeater_noise_detect")
1832    _set(part1, 23, "sound_tx_end")
1833    _set(part1, 24, "current_work_mode")
1834    _set(part1, 25, "fm_radio")
1835    a = values.get("work_mode_a")
1836    b = values.get("work_mode_b")
1837    c = values.get("work_mode_c")
1838    if any(v is None for v in (a, b, c)):
1839        part1[26] = 0xFF
1840    else:
1841        preserved = 0 if part1[26] == 0xFF else part1[26] & 0xC0
1842        part1[26] = preserved | ((int(c) & 0x03) << 4) | ((int(b) & 0x03) << 2) | (int(a) & 0x03)
1843    _set(part1, 27, "lock_keyboard")
1844    _set(part1, 28, "power_on_message")
1845    _set(part1, 29, "bt_write_switch")
1846    _set(part1, 30, "rtone")
1847
1848    _set(part2, 0, "vox_delay")
1849    _set(part2, 1, "timer_menu_quit")
1850    _set(part2, 5, "weather_channel")
1851    _set(part2, 6, "divide_channel")
1852    _set(part2, 7, "subaudio_scan_save")
1853    _set(part2, 8, "vox_switch")
1854    _set(part2, 9, "key_side1_short")
1855    _set(part2, 10, "key_side1_long")
1856    _set(part2, 11, "key_side2_short")
1857    _set(part2, 12, "key_side2_long")
1858    _set(part2, 13, "current_work_area_a")
1859    _set(part2, 14, "current_work_area_b")
1860    _set(part2, 15, "current_work_area_c")
1861    _set(part2, 25, "ab_uv_transfer")
1862    _set(part2, 26, "sound_transfer")
1863    _set(part2, 27, "key0_long", mask=0x1F)
1864    _set(part2, 28, "key1_long", mask=0x1F)
1865    _set(part2, 29, "key2_long", mask=0x1F)
1866    _set(part2, 30, "key3_long", mask=0x1F)
1867    _set(part2, 31, "key4_long", mask=0x1F)
1868
1869    _set(part3, 0, "key5_long", mask=0x1F)
1870    _set(part3, 1, "key6_long", mask=0x1F)
1871    _set(part3, 2, "key7_long", mask=0x1F)
1872    _set(part3, 3, "key8_long", mask=0x1F)
1873    _set(part3, 4, "key9_long", mask=0x1F)
1874
1875    return bytes(buffer)
1876
1877def encode_dtmf_section(settings: Optional[DTMFSettings], raw: Optional[bytes]) -> bytes:
1878    """Encode DTMF settings into the 384-byte DTMF block.
1879
1880    The own ID and code groups are rewritten only when their text changed,
1881    so the radio's original padding bytes survive otherwise. A rewritten
1882    code group has bytes 6-15 set to 0xFF; groups missing from
1883    ``settings.code_groups`` are encoded as empty. Info bytes 6-8 (PTT ID
1884    mode, last-time send/stop) are always written to the low nibble.
1885
1886    Args:
1887        settings: Settings to write; ``None`` leaves ``raw`` as is.
1888        raw: The original 384 bytes; anything else starts from 0xFF.
1889
1890    Returns:
1891        bytes: The 384-byte DTMF block.
1892    """
1893    if raw and len(raw) == 384:
1894        buffer = bytearray(raw)
1895    else:
1896        buffer = bytearray(b"\xFF" * 384)
1897    if settings is None:
1898        return bytes(buffer)
1899    info = memoryview(buffer)[0:32]
1900    groups = memoryview(buffer)[32:384]
1901
1902    current_raw_id = _decode_dtmf_sequence(bytes(info[0:5]))
1903    if settings.current_id != current_raw_id:
1904        info[0:5] = _encode_dtmf_sequence(settings.current_id, 5)
1905
1906    def _write_mode(index: int, value: Optional[int]) -> None:
1907        """Write a nibble value at info byte ``index``; ``None`` writes 0xFF.
1908
1909        Args:
1910            index: Byte offset within the 32-byte DTMF info area (6, 7 or 8).
1911            value: Value for the low nibble; the high nibble is kept unless 0xFF.
1912        """
1913        if value is None:
1914            info[index] = 0xFF
1915        else:
1916            current = info[index]
1917            base = 0 if current == 0xFF else current & 0xF0
1918            info[index] = base | (int(value) & 0x0F)
1919
1920    _write_mode(6, settings.ptt_id_mode)
1921    _write_mode(7, settings.last_time_send)
1922    _write_mode(8, settings.last_time_stop)
1923
1924    for idx in range(22):
1925        start = idx * 16
1926        seq = settings.code_groups[idx] if idx < len(settings.code_groups) else ""
1927        encoded = _encode_dtmf_sequence(seq, 6)
1928        chunk = bytearray(groups[start : start + 16])
1929        raw_sequence = _decode_dtmf_sequence(bytes(chunk[:16]), max_len=6)
1930        if seq == raw_sequence:
1931            continue
1932        chunk[0:6] = encoded
1933        chunk[6:16] = b"\xFF" * 10
1934        groups[start : start + 16] = chunk
1935
1936    return bytes(buffer)
1937
1938def encode_modulation_sections(
1939    settings: Optional[ModulationSettings],
1940    params_raw: Optional[bytes],
1941    names_raw: Optional[bytes],
1942) -> tuple[bytes, bytes]:
1943    """Encode modulation settings into the parameter and name blocks.
1944
1945    Every field is only rewritten when its value differs from what
1946    :func:`parse_modulation_sections` decodes from the original blocks, so
1947    unedited blocks, including unset (0xFF) fields, are written back
1948    byte-identical. A rewritten frequency of ``None`` is stored as 0x0000,
1949    a bandwidth or beat offset of ``None`` as 0. Entries beyond
1950    ``len(settings.channels)`` (up to 16) are cleared to 0xFF. Parameter
1951    bytes 32, 33, 66-68 and 149-152 are written when their value differs
1952    (``None`` never overwrites).
1953
1954    Args:
1955        settings: Settings to write; ``None`` leaves both blocks as is.
1956        params_raw: The original 256 parameter bytes.
1957        names_raw: The original 768 name bytes.
1958
1959    Returns:
1960        tuple[bytes, bytes]: The 256-byte parameter block and the 768-byte
1961        name block.
1962    """
1963    params = (
1964        bytearray(params_raw) if params_raw and len(params_raw) == 256 else bytearray(b"\xff" * 256)
1965    )
1966    names = (
1967        bytearray(names_raw) if names_raw and len(names_raw) == 768 else bytearray(b"\xff" * 768)
1968    )
1969    if settings is None:
1970        return bytes(params), bytes(names)
1971
1972    stored = parse_modulation_sections(bytes(params), bytes(names))
1973    channels = settings.channels[:16]
1974
1975    def _encode_freq(value: Optional[int]) -> bytes:
1976        """Convert Hz to a LE uint16 in 10 kHz units; ``None``/<=0 gives 0.
1977
1978        Args:
1979            value: Frequency in Hz, or ``None``.
1980
1981        Returns:
1982            bytes: Two bytes, LE uint16 of ``value / 10000`` rounded and clamped
1983            to 0-0xFFFF.
1984        """
1985        if value is None or value <= 0:
1986            return b'\x00\x00'
1987        scaled = max(0, min(0xFFFF, int(round(value / 10_000))))
1988        return _encode_le_uint16(scaled)
1989
1990    for idx, channel in enumerate(channels):
1991        old = stored.channels[idx]
1992        if channel.fm_frequency != old.fm_frequency:
1993            params[idx * 2 : idx * 2 + 2] = _encode_freq(channel.fm_frequency)
1994        if channel.am_frequency != old.am_frequency:
1995            params[34 + idx * 2 : 36 + idx * 2] = _encode_freq(channel.am_frequency)
1996        base = 69 + idx * 5
1997        if channel.ssb_frequency != old.ssb_frequency:
1998            params[base : base + 2] = _encode_freq(channel.ssb_frequency)
1999        if channel.ssb_bandwidth != old.ssb_bandwidth:
2000            params[base + 2] = 0 if channel.ssb_bandwidth is None else channel.ssb_bandwidth & 0xFF
2001        if channel.ssb_beat_offset != old.ssb_beat_offset:
2002            beat_value = (
2003                0
2004                if channel.ssb_beat_offset is None
2005                else max(-32768, min(32767, int(channel.ssb_beat_offset)))
2006            )
2007            params[base + 3 : base + 5] = _encode_le_int16(beat_value)
2008
2009        for table, new_name, old_name in ((0, channel.fm_name, old.fm_name),
2010                                          (256, channel.am_name, old.am_name),
2011                                          (512, channel.ssb_name, old.ssb_name)):
2012            if new_name.rstrip('\x00') != old_name.rstrip('\x00'):
2013                offset = table + idx * 16
2014                names[offset : offset + 16] = _encode_gb2312(new_name, 16)
2015
2016    for idx in range(len(channels), 16):
2017        params[idx * 2 : idx * 2 + 2] = b"\xFF\xFF"
2018        params[34 + idx * 2 : 34 + idx * 2 + 2] = b"\xFF\xFF"
2019        base = 69 + idx * 5
2020        params[base : base + 5] = b"\xFF" * 5
2021        names[idx * 16 : idx * 16 + 16] = b"\xFF" * 16
2022        names[256 + idx * 16 : 256 + idx * 16 + 16] = b"\xFF" * 16
2023        names[512 + idx * 16 : 512 + idx * 16 + 16] = b"\xFF" * 16
2024
2025    for index, attr in ((32, 'fm_current_channel'), (33, 'work_mode'),
2026                        (66, 'am_current_channel'), (67, 'modulation_mode'),
2027                        (68, 'am_rx_gain'), (149, 'ssb_current_channel'),
2028                        (150, 'ssb_step_index'), (151, 'am_step_index'),
2029                        (152, 'ssb_rx_gain')):
2030        value = getattr(settings, attr)
2031        if value is not None and value != getattr(stored, attr):
2032            params[index] = value & 0xFF
2033
2034    return bytes(params), bytes(names)
2035
2036def encode_aprs_section(settings: Optional[APRSSettings], raw: Optional[bytes]) -> bytes:
2037    """Encode APRS settings into the 128-byte APRS block.
2038
2039    Every field is only changed when its value differs from what
2040    :func:`parse_aprs_section` decodes from ``raw``, so an unedited block is
2041    written back byte-identical, including stored values outside the normal
2042    ranges (an N/S or W/E byte other than the letters, minutes above 59, bit
2043    7 of byte 27). A changed field is written normalised. A key missing from
2044    ``settings.fields`` writes 0xFF.
2045
2046    Args:
2047        settings: Settings to write; ``None`` leaves ``raw`` as is.
2048        raw: The original 128 bytes; anything else starts from 0xFF.
2049
2050    Returns:
2051        bytes: The 128-byte APRS block.
2052    """
2053    if raw and len(raw) == 128:
2054        data = bytearray(raw)
2055    else:
2056        data = bytearray(b"\xFF" * 128)
2057    if settings is None:
2058        return bytes(data)
2059
2060    fields = settings.fields
2061    stored = parse_aprs_section(bytes(data)).fields
2062
2063    def _edited(key: str) -> bool:
2064        """Return whether ``fields[key]`` differs from the value decoded from ``raw``.
2065
2066        Args:
2067            key: Field key in ``settings.fields``.
2068
2069        Returns:
2070            bool: ``True`` if the field must be written.
2071        """
2072        return fields.get(key) != stored.get(key)
2073
2074    def _set(idx: int, key: str, mask: int = 0x0F) -> None:
2075        """Write ``fields[key]`` at ``idx`` under ``mask``; ``None`` writes 0xFF.
2076
2077        Args:
2078            idx: Byte offset within the 128-byte APRS block.
2079            key: Field key in ``settings.fields``.
2080            mask: Bit mask of the field (default ``0x0F``).
2081        """
2082        value = fields.get(key)
2083        current = data[idx]
2084        if value is None:
2085            if current != 0xFF:
2086                data[idx] = 0xFF
2087            return
2088        encoded = int(value) & mask
2089        base = 0 if current == 0xFF else current & ~mask
2090        new_value = base | encoded
2091        if new_value != current:
2092            data[idx] = new_value
2093
2094    _set(0, "aprs_switch")
2095    _set(1, "gps_switch")
2096    _set(2, "latlon_unit")
2097    _set(3, "speed_unit")
2098    _set(4, "distance_unit")
2099    _set(5, "altitude_unit")
2100    _set(6, "time_zone", mask=0x1F)
2101
2102    if _edited("north_south"):
2103        north = fields.get("north_south")
2104        data[7] = 0xFF if north is None else (0x4E if int(north) == 0 else 0x53)
2105    for idx, key, limit in ((8, "latitude_minute", 59), (9, "latitude_degree", 90),
2106                            (10, "latitude_second", 59), (12, "longitude_minute", 59),
2107                            (13, "longitude_degree", 180), (14, "longitude_second", 59)):
2108        if _edited(key):
2109            data[idx] = _encode_optional_bounded(fields.get(key), limit)
2110    if _edited("east_west"):
2111        east = fields.get("east_west")
2112        data[11] = 0xFF if east is None else (0x57 if int(east) == 0 else 0x45)
2113
2114    if _edited("altitude"):
2115        altitude = fields.get("altitude")
2116        if altitude is None:
2117            data[15:17] = b"\xFF\xFF"
2118        else:
2119            alt = max(-10000, min(10000, int(altitude)))
2120            data[15:17] = alt.to_bytes(2, "little", signed=True)
2121
2122    call_sign_value = fields.get("call_sign")
2123    raw_call_sign_bytes = data[17:23]
2124    raw_call_sign = _decode_ascii(data, 17, 6)
2125    if call_sign_value is None:
2126        if any(b != 0xFF for b in raw_call_sign_bytes):
2127            data[17:23] = _encode_ascii(None, 6)
2128    elif call_sign_value != raw_call_sign:
2129        data[17:23] = _encode_ascii(call_sign_value, 6)
2130    _set(23, "ssid")
2131    _set(24, "routing_select")
2132    _set(25, "my_position")
2133    _set(26, "radio_symbol")
2134    if _edited("user_defined_icon"):
2135        icon = fields.get("user_defined_icon")
2136        data[27] = 0xFF if icon is None else int(icon) & 0x7F
2137    _set(29, "aprs_priority")
2138    _set(30, "data_tx_delay")
2139    _set(32, "aprs_decode_prompt_tone")
2140    _set(33, "aprs_rx_auto_popup")
2141    _set(34, "beacon_tx_type")
2142    _set(36, "timed_beacon_time")
2143    _set(38, "mice_type")
2144    _set(39, "tnc_data_type")
2145    _set(40, "aprs_forward_channel")
2146    _set(41, "aprs_forward_routing")
2147    _set(42, "aprs_wait_forward")
2148    custom_one = fields.get("custom_routing_one")
2149    raw_custom_one_bytes = data[43:49]
2150    raw_custom_one = _decode_ascii(data, 43, 6)
2151    if custom_one is None:
2152        if any(b != 0xFF for b in raw_custom_one_bytes):
2153            data[43:49] = _encode_ascii(None, 6)
2154    elif custom_one != raw_custom_one:
2155        data[43:49] = _encode_ascii(custom_one, 6)
2156    _set(49, "custom_routing_one_ssid")
2157    custom_two = fields.get("custom_routing_two")
2158    raw_custom_two_bytes = data[50:56]
2159    raw_custom_two = _decode_ascii(data, 50, 6)
2160    if custom_two is None:
2161        if any(b != 0xFF for b in raw_custom_two_bytes):
2162            data[50:56] = _encode_ascii(None, 6)
2163    elif custom_two != raw_custom_two:
2164        data[50:56] = _encode_ascii(custom_two, 6)
2165    _set(56, "custom_routing_two_ssid")
2166    _set(78, "send_custom_messages")
2167    custom_messages = fields.get("custom_messages")
2168    raw_custom_messages_bytes = data[79:119]
2169    raw_custom_messages = _decode_gb2312(data, 79, max_len=40)
2170    if custom_messages is None:
2171        if any(b != 0xFF for b in raw_custom_messages_bytes):
2172            data[79:119] = b"\xFF" * 40
2173    elif custom_messages != raw_custom_messages:
2174        data[79:119] = _encode_gb2312(custom_messages, 40)
2175
2176    return bytes(data)
2177
2178# ---------------------------------------------------------------------------
2179# Decode helpers
2180# ---------------------------------------------------------------------------
2181
2182def _decode_vfo_frequency(digits: bytes) -> Optional[int]:
2183    """Decode an 8-byte VFO frequency (one decimal digit per byte).
2184
2185    The digits read as MHz with five decimals: ``1 4 5 5 0 0 0 0`` is
2186    145.50000 MHz.
2187
2188    Args:
2189        digits: Eight bytes, each 0-9. Bytes outside 0-9 are not validated
2190            and produce a wrong value.
2191
2192    Returns:
2193        int | None: Frequency in Hz, or ``None`` if all bytes are 0x00/0xFF.
2194    """
2195    if all(b in (0x00, 0xFF) for b in digits):
2196        return None
2197    value = int("".join(str(b) for b in digits))
2198    mhz = value / 100000.0
2199    return int(round(mhz * 1_000_000))
2200
2201def _decode_offset_frequency(digits: bytes) -> Optional[int]:
2202    """Decode a 7-byte VFO offset (one decimal digit per byte).
2203
2204    The digits read as MHz with four decimals: ``0 0 0 6 0 0 0`` is
2205    0.6000 MHz.
2206
2207    Args:
2208        digits: Seven bytes, each 0-9.
2209
2210    Returns:
2211        int | None: Offset in Hz, or ``None`` if all bytes are 0x00/0xFF.
2212    """
2213    if all(b in (0x00, 0xFF) for b in digits):
2214        return None
2215    value = int("".join(str(b) for b in digits))
2216    mhz = value / 10000.0
2217    return int(round(mhz * 1_000_000))
2218
2219def _decode_dtmf_sequence(data: bytes, *, max_len: int = 5) -> str:
2220    """Decode a DTMF sequence stored as indexes into ``_DTMF_DIGITS``.
2221
2222    Args:
2223        data: The stored bytes.
2224        max_len: Maximum number of symbols to read.
2225
2226    Returns:
2227        str: The symbols up to the first 0xFF or ``max_len`` bytes; bytes
2228        that are not valid symbol indexes are skipped.
2229    """
2230    sequence = []
2231    for byte in data[:max_len]:
2232        if byte == 0xFF:
2233            break
2234        if 0 <= byte < len(_DTMF_DIGITS):
2235            sequence.append(_DTMF_DIGITS[byte])
2236    return "".join(sequence)
2237
2238def _decode_le_uint16(buffer: bytes, offset: int) -> int:
2239    """Read an unsigned little-endian 16-bit value at ``offset``.
2240
2241    Args:
2242        buffer: Source bytes.
2243        offset: Byte offset of the low byte.
2244
2245    Returns:
2246        int: The value, 0-65535.
2247    """
2248    return int.from_bytes(buffer[offset : offset + 2], "little")
2249
2250def _decode_le_int16(buffer: bytes, offset: int) -> int:
2251    """Read a signed little-endian 16-bit value at ``offset``.
2252
2253    Args:
2254        buffer: Source bytes.
2255        offset: Byte offset of the low byte.
2256
2257    Returns:
2258        int: The value, -32768 to 32767.
2259    """
2260    return int.from_bytes(buffer[offset : offset + 2], "little", signed=True)
2261
2262def _decode_gb2312(buffer: bytes, offset: int, max_len: int = 12) -> str:
2263    """Decode a GB2312 string of at most ``max_len`` bytes.
2264
2265    Bytes >= 0xA1 start a two-byte character. Decoding stops at 0x00 or
2266    0xFF; invalid sequences are replaced.
2267
2268    Args:
2269        buffer: Source bytes.
2270        offset: Start of the string.
2271        max_len: Maximum number of bytes to consume.
2272
2273    Returns:
2274        str: The decoded, stripped text.
2275    """
2276    data = bytearray()
2277    consumed = 0
2278    buf_len = len(buffer)
2279    while consumed < max_len and (offset + consumed) < buf_len:
2280        byte = buffer[offset + consumed]
2281        if byte in (0xFF, 0x00):
2282            break
2283        if (
2284            byte >= 0xA1
2285            and consumed + 1 < max_len
2286            and (offset + consumed + 1) < buf_len
2287        ):
2288            data.extend(buffer[offset + consumed : offset + consumed + 2])
2289            consumed += 2
2290        else:
2291            data.append(byte)
2292            consumed += 1
2293    if not data:
2294        return ""
2295    return bytes(data).decode("gb2312", errors="replace").strip()
2296
2297def _decode_ascii(buffer: bytes, offset: int, max_len: int) -> str:
2298    """Decode an ASCII string of at most ``max_len`` bytes.
2299
2300    Args:
2301        buffer: Source bytes.
2302        offset: Start of the string.
2303        max_len: Maximum length; 0x00 or 0xFF ends the string earlier.
2304
2305    Returns:
2306        str: The decoded, stripped text; non-ASCII bytes are dropped.
2307    """
2308    length = 0
2309    buf_len = len(buffer)
2310    for idx in range(max_len):
2311        if (offset + idx) >= buf_len:
2312            break
2313        if buffer[offset + idx] in (0xFF, 0x00):
2314            break
2315        length += 1
2316    if length == 0:
2317        return ""
2318    return buffer[offset : offset + length].decode("ascii", errors="ignore").strip()
2319
2320# ---------------------------------------------------------------------------
2321# Encode helper utilities
2322# ---------------------------------------------------------------------------
2323
2324def _encode_vfo_frequency(hz: Optional[int]) -> bytes:
2325    """Encode a frequency into 8 VFO digit bytes (MHz with five decimals).
2326
2327    Args:
2328        hz: Frequency in Hz, or ``None`` for 0xFF x 8.
2329
2330    Returns:
2331        bytes: Eight bytes, one decimal digit each.
2332    """
2333    if hz is None:
2334        return b"\xFF" * 8
2335    mhz = hz / 1_000_000.0
2336    digits = f"{mhz:0.5f}".replace(".", "")
2337    digits = digits[:8].rjust(8, "0")
2338    return bytes(int(ch) for ch in digits)
2339
2340def _encode_offset_frequency(hz: Optional[int]) -> bytes:
2341    """Encode an offset into 7 VFO digit bytes (MHz with four decimals).
2342
2343    Args:
2344        hz: Offset in Hz, or ``None`` for 0xFF x 7.
2345
2346    Returns:
2347        bytes: Seven bytes, one decimal digit each.
2348    """
2349    if hz is None:
2350        return b"\xFF" * 7
2351    value = int(round((hz / 1_000_000.0) * 10000))
2352    digits = f"{value:07d}"
2353    return bytes(int(ch) for ch in digits)
2354
2355def _encode_dtmf_sequence(seq: str, max_len: int) -> bytes:
2356    """Encode DTMF symbols as indexes into ``_DTMF_DIGITS``.
2357
2358    Unknown symbols are skipped (their position stays 0xFF).
2359
2360    Args:
2361        seq: DTMF symbols, e.g. ``"123A#"``.
2362        max_len: Field length in bytes.
2363
2364    Returns:
2365        bytes: ``max_len`` bytes padded with 0xFF.
2366    """
2367    out = bytearray(b"\xFF" * max_len)
2368    if not seq:
2369        return bytes(out)
2370    for idx, char in enumerate(seq[:max_len]):
2371        pos = _DTMF_DIGITS.find(char)
2372        if pos == -1:
2373            pos = _DTMF_DIGITS.find(char.upper())
2374        if pos == -1:
2375            continue
2376        out[idx] = pos
2377    return bytes(out)
2378
2379def _encode_le_uint16(value: int) -> bytes:
2380    """Encode a value as unsigned little-endian 16-bit; negatives become 0.
2381
2382    Args:
2383        value: Value to encode; must not exceed 0xFFFF.
2384
2385    Returns:
2386        bytes: Two bytes, low byte first.
2387    """
2388    return int(max(0, value)).to_bytes(2, "little", signed=False)
2389
2390def _encode_le_int16(value: int) -> bytes:
2391    """Encode a value as signed little-endian 16-bit.
2392
2393    Args:
2394        value: Value to encode, -32768 to 32767.
2395
2396    Returns:
2397        bytes: Two bytes, low byte first (two's complement).
2398    """
2399    return int(value).to_bytes(2, "little", signed=True)
2400
2401def _encode_gb2312(text: Optional[str], max_len: int) -> bytes:
2402    """Encode text as GB2312 into a fixed-length field.
2403
2404    Text longer than ``max_len`` bytes is cut before the first character
2405    that does not fit completely, so a two-byte character is never halved.
2406
2407    Args:
2408        text: Text to encode; unencodable characters are dropped.
2409        max_len: Field length in bytes.
2410
2411    Returns:
2412        bytes: ``max_len`` bytes padded with 0xFF.
2413    """
2414    if not text:
2415        return b"\xFF" * max_len
2416    encoded = bytearray()
2417    for char in text:
2418        char_bytes = char.encode("gb2312", errors="ignore")
2419        if len(encoded) + len(char_bytes) > max_len:
2420            break
2421        encoded += char_bytes
2422    return bytes(encoded) + b"\xFF" * (max_len - len(encoded))
2423
2424def _encode_ascii(text: Optional[str], length: int) -> bytes:
2425    """Encode text as ASCII into a fixed-length field.
2426
2427    Args:
2428        text: Text to encode; non-ASCII characters are dropped.
2429        length: Field length in bytes.
2430
2431    Returns:
2432        bytes: ``length`` bytes padded with 0xFF.
2433    """
2434    if not text:
2435        return b"\xFF" * length
2436    encoded = text.encode("ascii", errors="ignore")[:length]
2437    return encoded + b"\xFF" * (length - len(encoded))
2438
2439def _encode_optional_bounded(value: Optional[object], maximum: int) -> int:
2440    """Encode an optional value as one byte, capped at ``maximum``.
2441
2442    Args:
2443        value: Value to encode, or ``None``.
2444        maximum: Upper bound.
2445
2446    Returns:
2447        int: 0xFF for ``None``, otherwise ``min(maximum, value)``.
2448    """
2449    if value is None:
2450        return 0xFF
2451    return min(maximum, int(value)) & 0xFF
2452
2453
2454# ===========================================================================
2455# 3. Settings API: validated access to the settings sections
2456# ===========================================================================
2457
2458class SettingsError(ValueError):
2459    """Raised when a setting is given a value outside its allowed range."""
2460
2461@dataclass(frozen=True)
2462class SettingSpec:
2463    """Validation rule for one setting."""
2464
2465    kind: str  # "bool", "int", "enum", "string"
2466    """``"bool"``, ``"int"``, ``"enum"`` or ``"string"``."""
2467    min_value: Optional[int] = None
2468    """Lowest allowed value for ``"int"``."""
2469    max_value: Optional[int] = None
2470    """Highest allowed value for ``"int"``."""
2471    choices: Optional[Iterable[int]] = None
2472    """Allowed values for ``"enum"``."""
2473    max_length: Optional[int] = None
2474    """Maximum length for ``"string"``."""
2475
2476# ---------------------------------------------------------------------------
2477# Function block helpers ----------------------------------------------------
2478# ---------------------------------------------------------------------------
2479
2480CHANNEL_DIVIDE_ZONE = 0
2481"""Value of the function setting ``divide_channel`` (byte 0x9026) for the
2482CPS choice *Zone CH Mode*: the radio shows 10 zones of 99 channels.
2483Measured on hardware (firmware 0.29, CPS v1.3.3)."""
2484
2485CHANNEL_DIVIDE_ALL = 1
2486"""Value of the function setting ``divide_channel`` (byte 0x9026) for the
2487CPS choice *All CH Mode*: the radio shows one list of channels 1-990, the
2488zones placed one after the other; empty channels stay empty. Measured on
2489hardware (firmware 0.29, CPS v1.3.3); switching the mode changed no other
2490byte of the clone image."""
2491
2492_FUNCTION_SPECS: Dict[str, SettingSpec] = {
2493    "sql": SettingSpec("int", 0, 9),
2494    "save_mode": SettingSpec("int", 0, 3),
2495    "vox": SettingSpec("int", 0, 9),
2496    "auto_backlight": SettingSpec("int", 0, 9),
2497    "tdr": SettingSpec("bool"),
2498    "tot": SettingSpec("int", 0, 9),
2499    "beep_prompt": SettingSpec("bool"),
2500    "voice_prompt": SettingSpec("enum", choices=tuple(range(0, 3))),
2501    "language": SettingSpec("enum", choices=tuple(range(0, 3))),
2502    "dtmf_mode": SettingSpec("enum", choices=tuple(range(0, 4))),
2503    "scan_mode": SettingSpec("enum", choices=tuple(range(0, 3))),
2504    "ptt_id": SettingSpec("enum", choices=tuple(range(0, 4))),
2505    "send_id_delay": SettingSpec("int", 0, 9),
2506    "display_mode_a": SettingSpec("enum", choices=(0, 1, 2)),
2507    "display_mode_b": SettingSpec("enum", choices=(0, 1, 2)),
2508    "display_mode_c": SettingSpec("enum", choices=(0, 1, 2)),
2509    "auto_key_lock": SettingSpec("bool"),
2510    "alarm_mode": SettingSpec("enum", choices=tuple(range(0, 3))),
2511    "alarm_sound": SettingSpec("enum", choices=tuple(range(0, 3))),
2512    "tail_noise_clear": SettingSpec("bool"),
2513    "pass_repeater_noise_clear": SettingSpec("bool"),
2514    "pass_repeater_noise_detect": SettingSpec("bool"),
2515    "sound_tx_end": SettingSpec("bool"),
2516    "current_work_mode": SettingSpec("enum", choices=(0, 1, 2)),
2517    "fm_radio": SettingSpec("bool"),
2518    "work_mode_a": SettingSpec("enum", choices=(0, 1, 2, 3)),
2519    "work_mode_b": SettingSpec("enum", choices=(0, 1, 2, 3)),
2520    "work_mode_c": SettingSpec("enum", choices=(0, 1, 2, 3)),
2521    "lock_keyboard": SettingSpec("bool"),
2522    "power_on_message": SettingSpec("enum", choices=tuple(range(0, 3))),
2523    "bt_write_switch": SettingSpec("bool"),
2524    "rtone": SettingSpec("enum", choices=tuple(range(0, 3))),
2525    "vox_delay": SettingSpec("int", 0, 9),
2526    "timer_menu_quit": SettingSpec("int", 0, 9),
2527    "weather_channel": SettingSpec("enum", choices=tuple(range(0, 10))),
2528    "divide_channel": SettingSpec(
2529        "enum", choices=(CHANNEL_DIVIDE_ZONE, CHANNEL_DIVIDE_ALL)),
2530    "subaudio_scan_save": SettingSpec("bool"),
2531    "vox_switch": SettingSpec("bool"),
2532    "key_side1_short": SettingSpec("enum", choices=tuple(range(0, 8))),
2533    "key_side1_long": SettingSpec("enum", choices=tuple(range(0, 8))),
2534    "key_side2_short": SettingSpec("enum", choices=tuple(range(0, 7))),
2535    "key_side2_long": SettingSpec("enum", choices=tuple(range(0, 7))),
2536    "current_work_area_a": SettingSpec("enum", choices=tuple(range(0, 16))),
2537    "current_work_area_b": SettingSpec("enum", choices=tuple(range(0, 16))),
2538    "current_work_area_c": SettingSpec("enum", choices=tuple(range(0, 16))),
2539    "ab_uv_transfer": SettingSpec("bool"),
2540    "sound_transfer": SettingSpec("bool"),
2541    "key0_long": SettingSpec("enum", choices=tuple(range(0, 32))),
2542    "key1_long": SettingSpec("enum", choices=tuple(range(0, 32))),
2543    "key2_long": SettingSpec("enum", choices=tuple(range(0, 32))),
2544    "key3_long": SettingSpec("enum", choices=tuple(range(0, 32))),
2545    "key4_long": SettingSpec("enum", choices=tuple(range(0, 32))),
2546    "key5_long": SettingSpec("enum", choices=tuple(range(0, 32))),
2547    "key6_long": SettingSpec("enum", choices=tuple(range(0, 32))),
2548    "key7_long": SettingSpec("enum", choices=tuple(range(0, 32))),
2549    "key8_long": SettingSpec("enum", choices=tuple(range(0, 32))),
2550    "key9_long": SettingSpec("enum", choices=tuple(range(0, 32))),
2551}
2552"""Validation rule per function setting, keyed by the names in
2553:class:`FunctionSettings`.
2554
2555``key_side1_short/long`` are PF1 Short/Long in the CPS (8 functions: Radio,
2556Moni, Scan, Search, SOS, Spectrum, BeaconTx, PTTC = 0-7); ``key_side2_*``
2557are PF2 (the same without PTTC, 0-6). Confirmed on a radio.
2558"""
2559
2560def function_keys() -> Iterable[str]:
2561    """List the names of all function settings.
2562
2563    Returns:
2564        Iterable[str]: Keys accepted by :func:`get_function_value` and
2565        :func:`set_function_value`.
2566    """
2567    return _FUNCTION_SPECS.keys()
2568
2569def _coerce_bool(value) -> int:
2570    """Convert ``True``/``False``/0/1 to 0 or 1.
2571
2572    Args:
2573        value: Proposed value for a boolean setting.
2574
2575    Returns:
2576        int: 1 for ``True``/1, 0 for ``False``/0.
2577
2578    Raises:
2579        SettingsError: For any other value.
2580    """
2581    if isinstance(value, bool):
2582        return 1 if value else 0
2583    if value in (0, 1):
2584        return int(value)
2585    raise SettingsError("Boolean setting expects True/False or 0/1")
2586
2587def _validate(spec: SettingSpec, value) -> int:
2588    """Check ``value`` against ``spec`` and return the value to store.
2589
2590    Args:
2591        spec: Validation rule.
2592        value: Proposed value.
2593
2594    Returns:
2595        int: The value to store (0/1 for booleans).
2596
2597    Raises:
2598        SettingsError: If the value is of the wrong type or out of range, or
2599            if ``spec.kind`` is not ``bool``/``int``/``enum`` (strings are
2600            validated by :func:`set_aprs_value`).
2601    """
2602    if spec.kind == "bool":
2603        return _coerce_bool(value)
2604    if not isinstance(value, int):
2605        raise SettingsError("Setting expects integer value")
2606    if spec.kind == "int":
2607        if spec.min_value is not None and value < spec.min_value:
2608            raise SettingsError(f"Value {value} below minimum {spec.min_value}")
2609        if spec.max_value is not None and value > spec.max_value:
2610            raise SettingsError(f"Value {value} above maximum {spec.max_value}")
2611        return value
2612    if spec.kind == "enum":
2613        if spec.choices is not None and value not in spec.choices:
2614            raise SettingsError(f"Value {value} not in allowed choices {tuple(spec.choices)}")
2615        return value
2616    raise SettingsError(f"Unsupported setting kind {spec.kind}")
2617
2618def get_function_value(settings: FunctionSettings, key: str):
2619    """Read one function setting.
2620
2621    Args:
2622        settings: Function settings.
2623        key: Setting name (see :func:`function_keys`).
2624
2625    Returns:
2626        bool | int | None: A ``bool`` for boolean settings, otherwise the
2627        stored integer; ``None`` if not set.
2628
2629    Raises:
2630        KeyError: If ``key`` is unknown.
2631    """
2632    if key not in _FUNCTION_SPECS:
2633        raise KeyError(key)
2634    value = settings.values.get(key)
2635    if value is None:
2636        return None
2637    spec = _FUNCTION_SPECS[key]
2638    if spec.kind == "bool":
2639        return bool(value)
2640    return value
2641
2642def set_function_value(settings: FunctionSettings, key: str, value) -> None:
2643    """Validate and store one function setting.
2644
2645    Args:
2646        settings: Function settings to update.
2647        key: Setting name (see :func:`function_keys`).
2648        value: New value, or ``None`` to mark it as not set.
2649
2650    Raises:
2651        KeyError: If ``key`` is unknown.
2652        SettingsError: If ``value`` is not allowed.
2653    """
2654    if key not in _FUNCTION_SPECS:
2655        raise KeyError(key)
2656    if value is None:
2657        settings.values[key] = None
2658        return
2659    spec = _FUNCTION_SPECS[key]
2660    encoded = _validate(spec, value)
2661    settings.values[key] = encoded
2662
2663# ---------------------------------------------------------------------------
2664# APRS helpers --------------------------------------------------------------
2665# ---------------------------------------------------------------------------
2666
2667_APRS_SPECS: Dict[str, SettingSpec] = {
2668    "aprs_switch": SettingSpec("bool"),
2669    "gps_switch": SettingSpec("bool"),
2670    "latlon_unit": SettingSpec("enum", choices=(0, 1)),
2671    "speed_unit": SettingSpec("enum", choices=(0, 1)),
2672    "distance_unit": SettingSpec("enum", choices=(0, 1)),
2673    "altitude_unit": SettingSpec("enum", choices=(0, 1)),
2674    "time_zone": SettingSpec("int", 0, 23),
2675    "north_south": SettingSpec("enum", choices=(0, 1)),
2676    "latitude_minute": SettingSpec("int", 0, 59),
2677    "latitude_degree": SettingSpec("int", 0, 90),
2678    "latitude_second": SettingSpec("int", 0, 59),
2679    "east_west": SettingSpec("enum", choices=(0, 1)),
2680    "longitude_minute": SettingSpec("int", 0, 59),
2681    "longitude_degree": SettingSpec("int", 0, 180),
2682    "longitude_second": SettingSpec("int", 0, 59),
2683    "altitude": SettingSpec("int", -10000, 10000),
2684    "call_sign": SettingSpec("string", max_length=6),
2685    "ssid": SettingSpec("enum", choices=tuple(range(0, 16))),
2686    "routing_select": SettingSpec("enum", choices=tuple(range(0, 6))),
2687    "my_position": SettingSpec("enum", choices=tuple(range(0, 6))),
2688    "radio_symbol": SettingSpec("enum", choices=tuple(range(0, 5))),
2689    "user_defined_icon": SettingSpec("enum", choices=tuple(range(0, 128))),
2690    "aprs_priority": SettingSpec("enum", choices=tuple(range(0, 3))),
2691    "data_tx_delay": SettingSpec("int", 0, 9),
2692    "aprs_decode_prompt_tone": SettingSpec("bool"),
2693    "aprs_rx_auto_popup": SettingSpec("bool"),
2694    "beacon_tx_type": SettingSpec("enum", choices=tuple(range(0, 3))),
2695    "timed_beacon_time": SettingSpec("enum", choices=tuple(range(0, 10))),
2696    "mice_type": SettingSpec("enum", choices=tuple(range(0, 4))),
2697    "tnc_data_type": SettingSpec("enum", choices=tuple(range(0, 4))),
2698    "aprs_forward_channel": SettingSpec("enum", choices=tuple(range(0, 16))),
2699    "aprs_forward_routing": SettingSpec("enum", choices=tuple(range(0, 6))),
2700    "aprs_wait_forward": SettingSpec("int", 0, 9),
2701    "custom_routing_one": SettingSpec("string", max_length=6),
2702    "custom_routing_one_ssid": SettingSpec("enum", choices=tuple(range(0, 16))),
2703    "custom_routing_two": SettingSpec("string", max_length=6),
2704    "custom_routing_two_ssid": SettingSpec("enum", choices=tuple(range(0, 16))),
2705    "send_custom_messages": SettingSpec("bool"),
2706    "custom_messages": SettingSpec("string", max_length=40),
2707}
2708"""Validation rule per APRS setting, keyed by the names in
2709:class:`APRSSettings`.
2710
2711``timed_beacon_time`` is the index of CPS *Timed Beacon Time* (30 sec, 1, 2,
27123, 5, 10, 15, 20, 30, 60 min = 0-9; 30 sec = 0 confirmed on a radio, the
2713rest follows the CPS list order). ``radio_symbol`` is the index of CPS
2714*Radio Symbol* (Pedestrians, Bicycles, Cars, RecreationalVehicles,
2715UserDefined = 0-4; 0 and 4 confirmed on a radio).
2716"""
2717
2718def aprs_keys() -> Iterable[str]:
2719    """List the names of all APRS settings.
2720
2721    Returns:
2722        Iterable[str]: Keys accepted by :func:`get_aprs_value` and
2723        :func:`set_aprs_value`.
2724    """
2725    return _APRS_SPECS.keys()
2726
2727def get_aprs_value(settings: APRSSettings, key: str):
2728    """Read one APRS setting.
2729
2730    Args:
2731        settings: APRS settings.
2732        key: Setting name (see :func:`aprs_keys`).
2733
2734    Returns:
2735        bool | int | str | None: A ``bool`` for boolean settings, otherwise
2736        the stored value; ``None`` if not set.
2737
2738    Raises:
2739        KeyError: If ``key`` is unknown.
2740    """
2741    if key not in _APRS_SPECS:
2742        raise KeyError(key)
2743    value = settings.fields.get(key)
2744    spec = _APRS_SPECS[key]
2745    if value is None:
2746        return None
2747    if spec.kind == "bool":
2748        return bool(value)
2749    return value
2750
2751def set_aprs_value(settings: APRSSettings, key: str, value) -> None:
2752    """Validate and store one APRS setting.
2753
2754    Args:
2755        settings: APRS settings to update.
2756        key: Setting name (see :func:`aprs_keys`).
2757        value: New value, or ``None`` to mark it as not set.
2758
2759    Raises:
2760        KeyError: If ``key`` is unknown.
2761        SettingsError: If ``value`` is not allowed.
2762    """
2763    if key not in _APRS_SPECS:
2764        raise KeyError(key)
2765    if value is None:
2766        settings.fields[key] = None
2767        return
2768    spec = _APRS_SPECS[key]
2769    if spec.kind == "string":
2770        if not isinstance(value, str):
2771            raise SettingsError("String setting expects str value")
2772        if spec.max_length is not None and len(value) > spec.max_length:
2773            raise SettingsError(
2774                f"String '{value}' longer than allowed {spec.max_length} characters"
2775            )
2776        settings.fields[key] = value
2777        return
2778    encoded = _validate(spec, value)
2779    settings.fields[key] = encoded
2780
2781# ---------------------------------------------------------------------------
2782# DTMF helpers --------------------------------------------------------------
2783# ---------------------------------------------------------------------------
2784
2785_ALLOWED_DTMF = set("0123456789ABCD*#")
2786"""Characters accepted in DTMF IDs and code groups."""
2787
2788def _validate_dtmf_string(value: str, max_len: int) -> str:
2789    """Check a DTMF string and return it stripped.
2790
2791    Args:
2792        value: DTMF symbols (``0-9``, ``A-D``, ``*``, ``#``).
2793        max_len: Maximum number of symbols.
2794
2795    Returns:
2796        str: The stripped value.
2797
2798    Raises:
2799        SettingsError: If the value is not a string, too long or contains
2800            other characters.
2801    """
2802    if not isinstance(value, str):
2803        raise SettingsError("DTMF sequence must be a string")
2804    filtered = value.strip()
2805    if len(filtered) > max_len:
2806        raise SettingsError(f"DTMF value '{value}' exceeds {max_len} characters")
2807    if not all(ch in _ALLOWED_DTMF for ch in filtered):
2808        raise SettingsError("DTMF value contains invalid characters")
2809    return filtered
2810
2811def get_dtmf_current_id(settings: DTMFSettings) -> str:
2812    """Return the radio's own DTMF ID.
2813
2814    Args:
2815        settings: DTMF settings to read.
2816
2817    Returns:
2818        str: The own ID as DTMF symbols (up to 5).
2819    """
2820    return settings.current_id
2821
2822def set_dtmf_current_id(settings: DTMFSettings, value: str) -> None:
2823    """Set the radio's own DTMF ID (up to 5 symbols).
2824
2825    Args:
2826        settings: DTMF settings to update.
2827        value: New ID; surrounding whitespace is stripped.
2828
2829    Raises:
2830        SettingsError: If the ID is invalid.
2831    """
2832    settings.current_id = _validate_dtmf_string(value, 5)
2833
2834def get_dtmf_ptt_mode(settings: DTMFSettings) -> Optional[int]:
2835    """Return the PTT ID mode (0 off, 1 BOT, 2 EOT, 3 both), or ``None``.
2836
2837    Args:
2838        settings: DTMF settings to read.
2839
2840    Returns:
2841        Optional[int]: The mode, or ``None`` if not set.
2842    """
2843    return settings.ptt_id_mode
2844
2845def set_dtmf_ptt_mode(settings: DTMFSettings, value: Optional[int]) -> None:
2846    """Set the PTT ID mode.
2847
2848    Args:
2849        settings: DTMF settings to update.
2850        value: 0 off, 1 BOT, 2 EOT, 3 both, or ``None`` for not set.
2851
2852    Raises:
2853        SettingsError: If ``value`` is not 0-3 or ``None``.
2854    """
2855    if value is None:
2856        settings.ptt_id_mode = None
2857        return
2858    if value not in (0, 1, 2, 3):
2859        raise SettingsError("DTMF PTT mode must be 0-3")
2860    settings.ptt_id_mode = value
2861
2862def get_dtmf_code_group(settings: DTMFSettings, index: int) -> str:
2863    """Return DTMF code group ``index`` (0-based).
2864
2865    Args:
2866        settings: DTMF settings to read.
2867        index: Code group number, 0-based.
2868
2869    Returns:
2870        str: The code group as DTMF symbols (up to 6).
2871
2872    Raises:
2873        IndexError: If ``index`` is negative or not below the number of
2874            code groups.
2875    """
2876    if not 0 <= index < len(settings.code_groups):
2877        raise IndexError(index)
2878    return settings.code_groups[index]
2879
2880def set_dtmf_code_group(settings: DTMFSettings, index: int, value: str) -> None:
2881    """Set DTMF code group ``index`` (0-based, up to 6 symbols).
2882
2883    Args:
2884        settings: DTMF settings to update.
2885        index: Code group number, 0-based.
2886        value: New code; surrounding whitespace is stripped.
2887
2888    Raises:
2889        IndexError: If ``index`` is out of range.
2890        SettingsError: If the code is invalid.
2891    """
2892    if not 0 <= index < len(settings.code_groups):
2893        raise IndexError(index)
2894    settings.code_groups[index] = _validate_dtmf_string(value, 6)
2895
2896
2897# ===========================================================================
2898# 4. Image: the parsed form of a complete clone image
2899# ===========================================================================
2900
2901CHANNEL_LOG = logging.getLogger(__name__ + ".image")
2902"""Default logger for :class:`RadioImage` parsing and serialisation."""
2903
2904ZONE_COUNT = 10
2905"""Number of zones in the radio (CPS: arrayZoneName[10])."""
2906
2907ZONE_SIZE = 99
2908"""Channels per zone (CPS: channelList[990] = 10 x 99)."""
2909
2910CHANNEL_COUNT = ZONE_COUNT * ZONE_SIZE
2911"""Total number of memory channels supported by the radio (990)."""
2912
2913CHANNEL_SIZE = 32
2914"""Size in bytes of a single channel record."""
2915
2916CHANNEL_DATA_BYTES = CHANNEL_COUNT * CHANNEL_SIZE
2917"""Bytes occupied by the 990 channel records (0x0000-0x7BBF)."""
2918
2919CHANNEL_SECTION_BYTES = 0x8000
2920"""Total byte length of the channel segment within the clone image.
2921
2922The segment runs up to the VFO block at 0x8000. Bytes after the last channel
2923record (0x7BC0-0x7FFF) are kept verbatim in the image; the driver never
2924writes past 0x7BFF."""
2925
2926LEGACY_CHANNEL_SECTION_BYTES = 0x7800
2927"""Channel segment size used by older versions of this driver (960 slots)."""
2928
2929VFO_DATA_BYTES = 96
2930"""Used bytes of the VFO segment (three 32-byte entries)."""
2931VFO_SEGMENT_BYTES = 0x100
2932"""Size of the VFO segment read from 0x8000."""
2933FUNCTION_DATA_BYTES = 96
2934"""Used bytes of the function segment."""
2935FUNCTION_SEGMENT_BYTES = 0x100
2936"""Size of the function segment read from 0x9000."""
2937DTMF_DATA_BYTES = 384
2938"""Used bytes of the DTMF segment (32 info + 22 x 16 code groups)."""
2939DTMF_SEGMENT_BYTES = 0x200
2940"""Size of the DTMF segment read from 0xA000."""
2941MODULATION_PARAM_DATA_BYTES = 256
2942"""Used bytes of the modulation parameter segment."""
2943MODULATION_PARAM_SEGMENT_BYTES = 0x200
2944"""Size of the modulation parameter segment read from 0xB000."""
2945MODULATION_NAME_SEGMENT_BYTES = 0x300
2946"""Size of the modulation name segment read from 0xD000
2947(3 tables x 16 names x 16 bytes).
2948"""
2949APRS_SEGMENT_BYTES = 0x80
2950"""Size of the APRS block (separate address space, commands 0x54/0x58)."""
2951ZONE_NAME_SEGMENT_BYTES = 0x100
2952"""Zone names at radio address 0xC000: 10 x 16 bytes (confirmed on a real
2953RT-950 Pro: zone 1 at 0xC000, zone 2 at 0xC010 ... zone 10 at 0xC090).
2954Read as two 0x80 blocks (0xC000-0xC0FF)."""
2955ZONE_NAME_ADDRESS = 0xC000
2956"""Radio address of the first zone name."""
2957ZONE_NAME_STRIDE = 16
2958"""Distance in bytes between consecutive zone-name slots."""
2959ZONE_NAME_READ_LENGTH = 16
2960"""Decode up to the full 16-byte slot, stopping at 0x00/0xFF padding."""
2961ZONE_NAME_LENGTH = 12
2962"""Maximum length of a zone name: the CPS (*Cur Zone Name*) cuts a name to
296312 characters, confirmed on a radio. The 16-byte slot is padded after it."""
2964
2965KNOWN_SEGMENT_BYTES = (
2966    VFO_SEGMENT_BYTES
2967    + FUNCTION_SEGMENT_BYTES
2968    + DTMF_SEGMENT_BYTES
2969    + MODULATION_PARAM_SEGMENT_BYTES
2970    + MODULATION_NAME_SEGMENT_BYTES
2971    + APRS_SEGMENT_BYTES
2972    + ZONE_NAME_SEGMENT_BYTES
2973)
2974"""Total size of all segments after the channel segment."""
2975
2976def _decode_zone_name(raw: bytes) -> str:
2977    """Decode one 16-byte zone-name slot as ASCII up to the first 0x00/0xFF.
2978
2979    Args:
2980        raw: The slot bytes; only the first ``ZONE_NAME_READ_LENGTH`` are used.
2981
2982    Returns:
2983        str: The stripped name; invalid bytes are replaced, ``""`` if empty.
2984    """
2985    text = bytearray()
2986    for byte in raw[:ZONE_NAME_READ_LENGTH]:
2987        if byte in (0x00, 0xFF):
2988            break
2989        text.append(byte)
2990    return text.decode("ascii", errors="replace").strip()
2991
2992
2993def parse_zone_names(segment: bytes) -> List[str]:
2994    """Decode the ten zone names from the zone-name segment.
2995
2996    Args:
2997        segment: The segment read from 0xC000 (at least 160 bytes).
2998
2999    Returns:
3000        list[str]: Ten names; ``""`` means no name is set.
3001    """
3002    return [
3003        _decode_zone_name(segment[i * ZONE_NAME_STRIDE : (i + 1) * ZONE_NAME_STRIDE])
3004        for i in range(ZONE_COUNT)
3005    ]
3006
3007
3008def encode_zone_names(names: Optional[List[str]], raw: bytes) -> bytes:
3009    """Write changed zone names into the zone-name segment.
3010
3011    Unchanged names stay byte-identical. A changed name is cut to
3012    ``ZONE_NAME_LENGTH`` ASCII characters and padded with the padding byte
3013    (0x00 or 0xFF) the slot already used.
3014
3015    Args:
3016        names: Ten names, or ``None`` to leave the segment untouched.
3017        raw: The original segment; padded with 0xFF to
3018            ``ZONE_NAME_SEGMENT_BYTES``.
3019
3020    Returns:
3021        bytes: The segment, ``ZONE_NAME_SEGMENT_BYTES`` long.
3022    """
3023    data = bytearray(raw.ljust(ZONE_NAME_SEGMENT_BYTES, b"\xFF"))
3024    if names is None:
3025        return bytes(data)
3026    for i, name in enumerate(names[:ZONE_COUNT]):
3027        start = i * ZONE_NAME_STRIDE
3028        if name == _decode_zone_name(data[start : start + ZONE_NAME_STRIDE]):
3029            continue
3030        encoded = name.encode("ascii", errors="ignore")[:ZONE_NAME_LENGTH]
3031        old = bytes(data[start : start + ZONE_NAME_STRIDE])
3032        # keep the padding byte the radio already uses for this slot
3033        used = len(old.rstrip(b"\x00\xFF"))
3034        pad = 0x00 if used < len(old) and old[used] == 0x00 else 0xFF
3035        width = max(ZONE_NAME_LENGTH, used)
3036        data[start : start + width] = encoded.ljust(width, bytes([pad]))
3037    return bytes(data)
3038
3039
3040def _chunk(iterable: Sequence[int], size: int) -> Iterable[bytes]:
3041    """Yield consecutive ``size``-byte chunks; a short final chunk is dropped.
3042
3043    Args:
3044        iterable: Byte sequence to split (the channel segment).
3045        size: Chunk length in bytes (``CHANNEL_SIZE`` at the call site).
3046
3047    Yields:
3048        bytes: The next chunk of exactly ``size`` bytes.
3049    """
3050    for i in range(0, len(iterable), size):
3051        chunk = iterable[i : i + size]
3052        if len(chunk) == size:
3053            yield bytes(chunk)
3054
3055@dataclass
3056class RadioImage:
3057    """Parsed contents of a complete clone image.
3058
3059    The image bytes are the concatenation of ``DEFAULT_SEGMENTS``: the
3060    0x8000-byte channel segment followed by the settings segments, the APRS
3061    block and the zone names. :meth:`from_bytes` and :meth:`to_bytes`
3062    convert between bytes and this structure.
3063    """
3064
3065    channels: List[ChannelRecord]
3066    """The 990 channel records, slot 0 first."""
3067    vfo: Optional[List[VFOSettings]] = None
3068    """VFO A/B/C, or ``None`` if the image is too short."""
3069    function: Optional[FunctionSettings] = None
3070    """Function settings, or ``None``."""
3071    dtmf: Optional[DTMFSettings] = None
3072    """DTMF settings, or ``None``."""
3073    modulation: Optional[ModulationSettings] = None
3074    """Modulation settings, or ``None``."""
3075    aprs: Optional[APRSSettings] = None
3076    """APRS settings, or ``None``."""
3077    remainder: bytes = b""
3078    """All bytes after the channel segment, as read. Used as the base when re-
3079    encoding, so unknown bytes survive.
3080    """
3081    channel_extra: bytes = b""
3082    """Bytes 0x7BC0-0x7FFF after the last channel, kept verbatim."""
3083    zone_names: Optional[List[str]] = None
3084    """Ten zone names, or ``None`` if not present."""
3085
3086    @classmethod
3087    def from_bytes(
3088        cls,
3089        blob: bytes,
3090        *,
3091        logger: Optional[logging.Logger] = None,
3092    ) -> "RadioImage":
3093        """Parse a raw clone image.
3094
3095        Sections beyond the end of ``blob`` are left as ``None``.
3096
3097        Args:
3098            blob: Image bytes in ``DEFAULT_SEGMENTS`` order; at least the
3099                0x8000-byte channel segment.
3100            logger: Logger for decoding warnings; defaults to ``CHANNEL_LOG``.
3101
3102        Returns:
3103            RadioImage: The parsed image.
3104
3105        Raises:
3106            ValueError: If ``blob`` is shorter than the channel segment or a
3107                channel cannot be decoded.
3108        """
3109        logger = logger or CHANNEL_LOG
3110        if len(blob) < CHANNEL_SECTION_BYTES:
3111            raise ValueError(
3112                f"Clone image is too small ({len(blob)} bytes); "
3113                f"expected at least {CHANNEL_SECTION_BYTES}"
3114            )
3115
3116        channel_bytes = memoryview(blob)[:CHANNEL_DATA_BYTES]
3117        channels: List[ChannelRecord] = []
3118        for index, chunk in enumerate(_chunk(channel_bytes, CHANNEL_SIZE)):
3119            try:
3120                record = ChannelRecord.from_bytes(chunk, logger=logger)
3121            except ValueError as exc:
3122                raise ValueError(f"Failed to decode channel {index}: {exc}") from exc
3123            channels.append(record)
3124
3125        offset = CHANNEL_SECTION_BYTES
3126        vfo: Optional[List[VFOSettings]] = None
3127        function: Optional[FunctionSettings] = None
3128        dtmf: Optional[DTMFSettings] = None
3129        modulation: Optional[ModulationSettings] = None
3130        aprs: Optional[APRSSettings] = None
3131
3132        if len(blob) >= offset + VFO_SEGMENT_BYTES:
3133            vfo_segment = bytes(blob[offset : offset + VFO_SEGMENT_BYTES])
3134            vfo = parse_vfo_section(vfo_segment[:VFO_DATA_BYTES])
3135        offset += VFO_SEGMENT_BYTES
3136
3137        if len(blob) >= offset + FUNCTION_SEGMENT_BYTES:
3138            function_segment = bytes(blob[offset : offset + FUNCTION_SEGMENT_BYTES])
3139            function = parse_function_section(function_segment[:FUNCTION_DATA_BYTES])
3140        offset += FUNCTION_SEGMENT_BYTES
3141
3142        if len(blob) >= offset + DTMF_SEGMENT_BYTES:
3143            dtmf_segment = bytes(blob[offset : offset + DTMF_SEGMENT_BYTES])
3144            dtmf = parse_dtmf_section(dtmf_segment[:DTMF_DATA_BYTES])
3145        offset += DTMF_SEGMENT_BYTES
3146
3147        if len(blob) >= offset + MODULATION_PARAM_SEGMENT_BYTES + MODULATION_NAME_SEGMENT_BYTES:
3148            params_segment = bytes(blob[offset : offset + MODULATION_PARAM_SEGMENT_BYTES])
3149            names_segment = bytes(
3150                blob[
3151                    offset
3152                    + MODULATION_PARAM_SEGMENT_BYTES : offset
3153                    + MODULATION_PARAM_SEGMENT_BYTES
3154                    + MODULATION_NAME_SEGMENT_BYTES
3155                ]
3156            )
3157            modulation = parse_modulation_sections(
3158                params_segment[:MODULATION_PARAM_DATA_BYTES],
3159                names_segment[:MODULATION_NAME_SEGMENT_BYTES],
3160            )
3161        offset += MODULATION_PARAM_SEGMENT_BYTES + MODULATION_NAME_SEGMENT_BYTES
3162
3163        if len(blob) >= offset + APRS_SEGMENT_BYTES:
3164            aprs_data = bytes(blob[offset : offset + APRS_SEGMENT_BYTES])
3165            aprs = parse_aprs_section(aprs_data[:APRS_SEGMENT_BYTES])
3166        offset += APRS_SEGMENT_BYTES
3167
3168        zone_names: Optional[List[str]] = None
3169        if len(blob) >= offset + ZONE_NAME_SEGMENT_BYTES:
3170            zone_names = parse_zone_names(bytes(blob[offset : offset + ZONE_NAME_SEGMENT_BYTES]))
3171
3172        remainder = bytes(blob[CHANNEL_SECTION_BYTES:])
3173        channel_extra = bytes(blob[CHANNEL_DATA_BYTES:CHANNEL_SECTION_BYTES])
3174        return cls(
3175            channels=channels,
3176            vfo=vfo,
3177            function=function,
3178            dtmf=dtmf,
3179            modulation=modulation,
3180            aprs=aprs,
3181            remainder=remainder,
3182            channel_extra=channel_extra,
3183            zone_names=zone_names,
3184        )
3185
3186    @classmethod
3187    def from_file(
3188        cls,
3189        path: Path,
3190        *,
3191        logger: Optional[logging.Logger] = None,
3192    ) -> "RadioImage":
3193        """Load and parse an image file.
3194
3195        Args:
3196            path: File containing a raw clone image.
3197            logger: Logger for decoding warnings.
3198
3199        Returns:
3200            RadioImage: The parsed image (see :meth:`from_bytes`).
3201
3202        Raises:
3203            ValueError: If the file cannot be read or parsed.
3204        """
3205        try:
3206            data = path.read_bytes()
3207        except OSError as exc:
3208            raise ValueError(f"Unable to read image file {path}: {exc}") from exc
3209        return cls.from_bytes(data, logger=logger)
3210
3211    def to_bytes(self, *, logger: Optional[logging.Logger] = None) -> bytes:
3212        """Serialise the image back into clone-image bytes.
3213
3214        Each settings section is re-encoded on top of its original bytes from
3215        ``remainder``; channels use their own change tracking. Zone names are
3216        re-encoded the same way. A missing or short ``remainder`` is padded
3217        with 0xFF. Encoding updates the change-tracking snapshots of edited
3218        channels and VFO entries.
3219
3220        Args:
3221            logger: Logger for encoding warnings; defaults to ``CHANNEL_LOG``.
3222
3223        Returns:
3224            bytes: Image bytes in ``DEFAULT_SEGMENTS`` order.
3225
3226        Raises:
3227            ValueError: If the image does not hold exactly ``CHANNEL_COUNT``
3228                channels or a channel cannot be encoded.
3229        """
3230        logger = logger or CHANNEL_LOG
3231        if len(self.channels) != CHANNEL_COUNT:
3232            raise ValueError(
3233                f"Image must contain {CHANNEL_COUNT} channels; has {len(self.channels)}"
3234            )
3235
3236        tail = bytearray(self.remainder)
3237        if len(tail) < KNOWN_SEGMENT_BYTES:
3238            tail.extend(b"\xFF" * (KNOWN_SEGMENT_BYTES - len(tail)))
3239
3240        offset = 0
3241
3242        vfo_segment = bytearray(tail[offset : offset + VFO_SEGMENT_BYTES])
3243        vfo_encoded = encode_vfo_section(self.vfo, bytes(vfo_segment[:VFO_DATA_BYTES]))
3244        vfo_segment[:VFO_DATA_BYTES] = vfo_encoded
3245        tail[offset : offset + VFO_SEGMENT_BYTES] = vfo_segment
3246        offset += VFO_SEGMENT_BYTES
3247
3248        function_segment = bytearray(tail[offset : offset + FUNCTION_SEGMENT_BYTES])
3249        function_encoded = encode_function_section(
3250            self.function, bytes(function_segment[:FUNCTION_DATA_BYTES])
3251        )
3252        function_segment[:FUNCTION_DATA_BYTES] = function_encoded
3253        tail[offset : offset + FUNCTION_SEGMENT_BYTES] = function_segment
3254        offset += FUNCTION_SEGMENT_BYTES
3255
3256        dtmf_segment = bytearray(tail[offset : offset + DTMF_SEGMENT_BYTES])
3257        dtmf_encoded = encode_dtmf_section(self.dtmf, bytes(dtmf_segment[:DTMF_DATA_BYTES]))
3258        dtmf_segment[:DTMF_DATA_BYTES] = dtmf_encoded
3259        tail[offset : offset + DTMF_SEGMENT_BYTES] = dtmf_segment
3260        offset += DTMF_SEGMENT_BYTES
3261
3262        params_offset = offset
3263        names_offset = params_offset + MODULATION_PARAM_SEGMENT_BYTES
3264
3265        params_segment = bytearray(
3266            tail[params_offset : params_offset + MODULATION_PARAM_SEGMENT_BYTES]
3267        )
3268        names_segment = bytearray(tail[names_offset : names_offset + MODULATION_NAME_SEGMENT_BYTES])
3269        params_raw = bytes(params_segment[:MODULATION_PARAM_DATA_BYTES])
3270        names_raw = bytes(names_segment[:MODULATION_NAME_SEGMENT_BYTES])
3271        mod_params, mod_names = encode_modulation_sections(
3272            self.modulation, params_raw, names_raw
3273        )
3274        params_segment[:MODULATION_PARAM_DATA_BYTES] = mod_params
3275        names_segment[:MODULATION_NAME_SEGMENT_BYTES] = mod_names
3276        tail[params_offset : params_offset + MODULATION_PARAM_SEGMENT_BYTES] = params_segment
3277        tail[names_offset : names_offset + MODULATION_NAME_SEGMENT_BYTES] = names_segment
3278        offset = names_offset + MODULATION_NAME_SEGMENT_BYTES
3279
3280        aprs_segment = bytearray(tail[offset : offset + APRS_SEGMENT_BYTES])
3281        aprs_encoded = encode_aprs_section(self.aprs, bytes(aprs_segment))
3282        tail[offset : offset + APRS_SEGMENT_BYTES] = aprs_encoded
3283        offset += APRS_SEGMENT_BYTES
3284
3285        zone_segment = bytes(tail[offset : offset + ZONE_NAME_SEGMENT_BYTES])
3286        tail[offset : offset + ZONE_NAME_SEGMENT_BYTES] = encode_zone_names(
3287            self.zone_names, zone_segment
3288        )
3289
3290        buffer = bytearray(CHANNEL_SECTION_BYTES + len(tail))
3291        extra = bytes(self.channel_extra[: CHANNEL_SECTION_BYTES - CHANNEL_DATA_BYTES])
3292        extra = extra.ljust(CHANNEL_SECTION_BYTES - CHANNEL_DATA_BYTES, b"\xFF")
3293        buffer[CHANNEL_DATA_BYTES:CHANNEL_SECTION_BYTES] = extra
3294        for index, channel in enumerate(self.channels):
3295            start = index * CHANNEL_SIZE
3296            buffer[start : start + CHANNEL_SIZE] = channel.to_bytes(logger=logger)
3297
3298        buffer[CHANNEL_SECTION_BYTES:] = tail
3299        return bytes(buffer)
3300
3301    def empty_slot_indexes(self) -> List[int]:
3302        """Return the 0-based slots that have no receive frequency.
3303
3304        Returns:
3305            list[int]: Indexes of empty channels.
3306        """
3307        return [idx for idx, channel in enumerate(self.channels) if channel.rx_hz is None]
3308
3309    def iter_populated_channels(self) -> Iterable[tuple[int, ChannelRecord]]:
3310        """Iterate over channels that have a receive frequency.
3311
3312        Yields:
3313            tuple[int, ChannelRecord]: 0-based slot index and its record.
3314        """
3315        for index, channel in enumerate(self.channels):
3316            if channel.rx_hz is not None:
3317                yield index, channel
3318
3319    def save(self, path: Path, *, logger: Optional[logging.Logger] = None) -> None:
3320        """Write the image to a file.
3321
3322        Args:
3323            path: Destination file.
3324            logger: Logger for encoding warnings.
3325
3326        Raises:
3327            ValueError: If the image cannot be encoded or written.
3328        """
3329        data = self.to_bytes(logger=logger)
3330        try:
3331            path.write_bytes(data)
3332        except OSError as exc:
3333            raise ValueError(f"Unable to write image file {path}: {exc}") from exc
3334
3335
3336# ===========================================================================
3337# 5. Transport: serial clone protocol
3338# ===========================================================================
3339
3340HANDSHAKE_STRING = b"PROGRAMBT9000U"
3341"""Magic string that puts the radio into clone mode."""
3342
3343ACK = b"\x06"
3344"""Single-byte acknowledgement sent by the radio."""
3345
3346END_COMMAND = b"E"
3347"""Command that ends a clone session."""
3348
3349READ_BLOCK = 0x80
3350"""Payload size in bytes of every read and write block."""
3351
3352BLOCK_HEADER = 4
3353"""Size of the block header: command, address high, address low, length."""
3354
3355ENCRYPT_STRINGS: Tuple[bytes, ...] = (
3356    b"BHT ",
3357    b"CO 7",
3358    b"A ES",
3359    b" EIY",
3360    b"M PQ",
3361    b"XN Y",
3362    b"RVB ",
3363    b" HQP",
3364    b"W RC",
3365    b"MS N",
3366    b" SAT",
3367    b"K DH",
3368    b"ZO R",
3369    b"C SL",
3370    b"6RB ",
3371    b" JCG",
3372    b"PN V",
3373    b"J PK",
3374    b"EK L",
3375    b"I LZ",
3376)
3377"""Candidate 4-byte XOR keys; the handshake frame selects one of them."""
3378
3379
3380@dataclass(slots=True)
3381class CloneSegment:
3382    """A contiguous memory region transferred in 0x80-byte blocks."""
3383
3384    read_command: int
3385    """Command byte for reading (0x52, or 0x54 for APRS)."""
3386    write_command: int
3387    """Command byte for writing (0x57, or 0x58 for APRS)."""
3388    start: int
3389    """Start address in the radio."""
3390    length: int
3391    """Length in bytes; a multiple of ``READ_BLOCK``."""
3392
3393DEFAULT_SEGMENTS: Tuple[CloneSegment, ...] = (
3394    CloneSegment(0x52, 0x57, 0x0000, 0x8000),
3395    CloneSegment(0x52, 0x57, 0x8000, 0x0100),
3396    CloneSegment(0x52, 0x57, 0x9000, 0x0100),
3397    CloneSegment(0x52, 0x57, 0xA000, 0x0200),
3398    CloneSegment(0x52, 0x57, 0xB000, 0x0200),
3399    CloneSegment(0x52, 0x57, 0xD000, 0x0300),
3400    # APRS: read 0x54, write 0x58. 0x55 (old notes) gets no ACK / an error
3401    # frame; 0x58 per NeonPlug (infamy/NeonPlug PR #197, radio-confirmed).
3402    CloneSegment(0x54, 0x58, 0x0000, 0x0080),
3403    CloneSegment(0x52, 0x57, ZONE_NAME_ADDRESS, 0x0100),
3404)
3405"""Clone image layout, in image order.
3406
3407Reading follows this order; the image (``.img``) is the concatenation of
3408these segments. Writing uses these segments in the order and lengths given
3409by ``_WRITE_PLAN`` / :func:`_build_write_plan`: the channel segment is cut to
34100x7800 or 0x7C00, and zone names and APRS are optional.
3411"""
3412
3413
3414class CloneTransportError(RuntimeError):
3415    """Raised when the serial clone protocol fails.
3416
3417    Causes include a timeout, a missing ACK, a short write or unexpected
3418    data.
3419    """
3420
3421@dataclass(slots=True)
3422class CloneSerialConfig:
3423    """Settings for opening the programming cable's serial port."""
3424
3425    port: str
3426    """Device name, e.g. ``"/dev/ttyUSB0"`` or ``"COM3"``."""
3427    baudrate: int = 115200
3428    """Serial speed."""
3429    timeout: float = 1.0
3430    """Read timeout in seconds (raised to at least 3 s)."""
3431    write_timeout: float = 1.0
3432    """Write timeout in seconds (raised to at least 3 s)."""
3433
3434class CloneSerialTransport:
3435    """The RT-950 Pro serial clone protocol.
3436
3437    Session outline:
3438
3439    1. Send ``PROGRAMBT9000U``; the radio answers ACK (0x06).
3440    2. ``F``: the radio returns a 16-byte blob (logged only).
3441    3. ``M``: the radio returns its 12-byte model string.
3442    4. Send a 25-byte ``SEND`` frame whose random contents select one of
3443       ``ENCRYPT_STRINGS`` as the 4-byte XOR key; the radio answers ACK.
3444    5. Transfer 0x80-byte blocks: header ``cmd, addr_hi, addr_lo, 0x80``;
3445       reads return header plus payload, writes are answered with ACK.
3446    6. Send ``E`` to end the session.
3447
3448    Payload bytes are XOR-ed with the key, except 0x00, 0xFF, the key byte
3449    itself and its complement, and positions where the key byte is a space.
3450    """
3451
3452    def __init__(
3453        self,
3454        serial_port,
3455        *,
3456        logger=None,
3457        rng: Optional[random.Random] = None,
3458    ) -> None:
3459        """Wrap an already open port.
3460
3461        Read and write timeouts below 3 s are raised to 3 s.
3462
3463        Args:
3464            serial_port: Open serial port or CHIRP pipe.
3465            logger: Logger for protocol tracing; defaults to the module's
3466                transport logger.
3467            rng: Random source for the key-selection frame; inject a seeded
3468                one for reproducible tests.
3469        """
3470        self.serial = serial_port
3471        """The open port or CHIRP pipe; its timeouts are raised to at least 3 s."""
3472        self.logger = logger or logging.getLogger(__name__ + ".transport")
3473        """Logger for protocol tracing (debug level: commands, addresses)."""
3474        # Enforce sensible minimums to avoid premature timeouts during clone.
3475        # The port object may be any pipe-like object, so any failure while
3476        # inspecting it falls back to the minimum.
3477        try:
3478            to = getattr(self.serial, "timeout", None)
3479            if to is None or float(to) < 3.0:
3480                self.serial.timeout = 3.0
3481        except Exception:  # pylint: disable=broad-exception-caught
3482            self.serial.timeout = 3.0
3483        try:
3484            wto = getattr(self.serial, "write_timeout", None)
3485            if wto is None or float(wto) < 3.0:
3486                self.serial.write_timeout = 3.0
3487        except Exception:  # pylint: disable=broad-exception-caught
3488            self.serial.write_timeout = 3.0
3489        self._rng = rng or random.Random()
3490        """Random source for the 25-byte ``SEND`` frame that selects the key."""
3491        self._xor_key: Optional[bytearray] = None
3492        """4-byte XOR key chosen during :meth:`handshake`; ``None`` before."""
3493        self._model: Optional[str] = None
3494        """Model string reported by the radio (``M`` command); ``None`` before
3495        :meth:`handshake`."""
3496        self.progress_cb: Optional[Callable[[int, int, str], None]] = None
3497        """Optional ``callback(done, total, phase)`` called after every block;
3498        ``phase`` is ``"read"`` or ``"write"``."""
3499
3500    @classmethod
3501    def open(
3502        cls,
3503        config: CloneSerialConfig,
3504        *,
3505        logger=None,
3506        rng: Optional[random.Random] = None,
3507        serial_class=None,
3508    ) -> "CloneSerialTransport":
3509        """Open a real serial port and return a transport on it.
3510
3511        Args:
3512            config: Port name and timing.
3513            logger: Logger for protocol tracing; defaults to the module's
3514                transport logger.
3515            rng: Random source for the key-selection frame; inject a seeded
3516                one for reproducible tests.
3517            serial_class: Port class to instantiate; defaults to
3518                ``serial.Serial`` (pyserial).
3519
3520        Returns:
3521            CloneSerialTransport: Transport on the opened port.
3522
3523        Raises:
3524            CloneTransportError: If no ``serial_class`` is given and
3525                pyserial is not installed. Errors raised by ``serial_class``
3526                (e.g. ``serial.SerialException``) propagate unchanged.
3527        """
3528        if serial_class is None:
3529            if serial is None:
3530                raise CloneTransportError("pyserial is not installed")
3531            serial_class = serial.Serial
3532        port = serial_class(
3533            config.port,
3534            baudrate=config.baudrate,
3535            timeout=config.timeout,
3536            write_timeout=config.write_timeout,
3537        )
3538        return cls(port, logger=logger, rng=rng)
3539
3540    def __enter__(self) -> "CloneSerialTransport":
3541        """Return the transport itself for use in a ``with`` statement.
3542
3543        Returns:
3544            CloneSerialTransport: This transport.
3545        """
3546        return self
3547
3548    def __exit__(self, exc_type, exc, tb) -> None:  # type: ignore[override]
3549        """Close the port when leaving a ``with`` block.
3550
3551        Exceptions are not suppressed.
3552
3553        Args:
3554            exc_type: Exception class raised in the block, or ``None``; unused.
3555            exc: Exception instance, or ``None``; unused.
3556            tb: Traceback, or ``None``; unused.
3557        """
3558        self.close()
3559
3560    @property
3561    def model(self) -> Optional[str]:
3562        """Model string reported during the handshake, or ``None`` before it."""
3563        return self._model
3564
3565    def close(self) -> None:
3566        """Close the underlying port, ignoring any error."""
3567        try:
3568            self.serial.close()
3569        # Closing must never raise during cleanup.
3570        except Exception:  # pragma: no cover  # pylint: disable=broad-exception-caught
3571            pass
3572
3573    def handshake(self) -> str:
3574        """Enter clone mode and negotiate the XOR key.
3575
3576        Returns:
3577            str: The model string reported by the radio.
3578
3579        Raises:
3580            CloneTransportError: If an ACK is missing or wrong, the model
3581                string is empty, a read times out or a write is short.
3582        """
3583        self.logger.debug("Starting clone handshake")
3584        if hasattr(self.serial, "reset_input_buffer"):
3585            self.serial.reset_input_buffer()
3586        if hasattr(self.serial, "reset_output_buffer"):
3587            self.serial.reset_output_buffer()
3588
3589        self._write(HANDSHAKE_STRING)
3590        if self._read_exact(1) != ACK:
3591            raise CloneTransportError("Handshake ACK not received")
3592
3593        self._write(b"F")
3594        blob = self._read_exact(16)
3595        self.logger.debug("Received handshake blob: %s", blob.hex())
3596
3597        self._write(b"M")
3598        model_raw = self._read_exact(12)
3599        self._model = model_raw.decode("ascii", errors="ignore").strip("\x00 ")
3600        if not self._model:
3601            raise CloneTransportError("Radio did not return a model identifier")
3602        self.logger.debug("Radio model reported as %s", self._model)
3603
3604        frame, key = self._build_encryption_frame()
3605        self._write(frame)
3606        if self._read_exact(1) != ACK:
3607            raise CloneTransportError("Encryption ACK not received")
3608        self._xor_key = key
3609        self.logger.debug("Negotiated XOR key: %s", key.hex())
3610        return self._model
3611
3612    def read_clone(self, *, segments: Sequence[CloneSegment] | None = None) -> bytes:
3613        """Read memory from the radio.
3614
3615        Performs the handshake first if needed and ends the session with
3616        ``E``.
3617
3618        Args:
3619            segments: Regions to read, in order; defaults to
3620                ``DEFAULT_SEGMENTS``.
3621
3622        Returns:
3623            bytes: The decrypted payloads concatenated in segment order.
3624
3625        Raises:
3626            CloneTransportError: On a timeout or protocol error.
3627        """
3628        if segments is None:
3629            segments = DEFAULT_SEGMENTS
3630        if self._xor_key is None:
3631            self.handshake()
3632
3633        raw = bytearray()
3634        total_blocks = sum(seg.length for seg in segments) // READ_BLOCK
3635        done = 0
3636        for command, address in self._iter_read_commands(segments):
3637            header = bytes((command, (address >> 8) & 0xFF, address & 0xFF, READ_BLOCK))
3638            self.logger.debug(
3639                "Requesting block: command=0x%02X address=0x%04X", command, address
3640            )
3641            self._write(header)
3642            block = self._read_exact(BLOCK_HEADER + READ_BLOCK)
3643            payload = bytearray(block[BLOCK_HEADER:])
3644            decrypted = self._apply_xor(payload)
3645            raw.extend(decrypted)
3646            done += 1
3647            if self.progress_cb:
3648                try:
3649                    self.progress_cb(done, total_blocks, "read")
3650                # Progress reporting must never break the clone operation.
3651                except Exception:  # pylint: disable=broad-exception-caught
3652                    pass
3653        self._write(END_COMMAND)
3654        return bytes(raw)
3655
3656    def write_clone(self, data: bytes, *, segments: Sequence[CloneSegment] | None = None) -> None:
3657        """Write memory to the radio.
3658
3659        Each block must be acknowledged. Flash commits are slow, so the ACK
3660        timeout is 8 s for channel blocks, 10 s for settings blocks (address
3661        >= 0x8000) and 30 s for the APRS block (command 0x58). Performs the
3662        handshake first if needed and ends the session with ``E``. Pauses:
3663        0.05 s after blocks at >= 0x8000, 0.1 s + 0.5 s after the APRS block.
3664
3665        Args:
3666            data: Payloads concatenated in segment order; its length must equal
3667                the total segment length.
3668            segments: Regions to write, in order; defaults to
3669                ``DEFAULT_SEGMENTS``.
3670
3671        Raises:
3672            CloneTransportError: On a length mismatch, timeout, missing ACK
3673                or wrong ACK byte.
3674        """
3675        if segments is None:
3676            segments = DEFAULT_SEGMENTS
3677        if self._xor_key is None:
3678            self.handshake()
3679
3680        expected = sum(segment.length for segment in segments)
3681        if len(data) != expected:
3682            raise CloneTransportError(
3683                f"Write buffer length {len(data)} does not match expected {expected}"
3684            )
3685
3686        offset = 0
3687        total_blocks = sum(seg.length for seg in segments) // READ_BLOCK
3688        done = 0
3689        for command, address in self._iter_write_commands(segments):
3690            chunk = data[offset : offset + READ_BLOCK]
3691            if len(chunk) != READ_BLOCK:
3692                raise CloneTransportError("Write chunk size mismatch")
3693            payload = self._apply_xor(bytearray(chunk))
3694            header = bytes((command, (address >> 8) & 0xFF, address & 0xFF, READ_BLOCK))
3695            self.logger.debug("Writing block: command=0x%02X address=0x%04X", command, address)
3696            self._write(header + payload)
3697            # Flash commits can take seconds: settings blocks up to 10 s,
3698            # APRS up to 30 s (pacing as in NeonPlug's RT-950 Pro support).
3699            if command == 0x58:
3700                ack_timeout, pause = 30.0, 0.1
3701            elif address >= 0x8000:
3702                ack_timeout, pause = 10.0, 0.05
3703            else:
3704                ack_timeout, pause = 8.0, 0.0
3705            old_timeout = getattr(self.serial, "timeout", None)
3706            # Pipe-like objects may not support changing the timeout.
3707            try:
3708                self.serial.timeout = ack_timeout
3709            except Exception:  # pylint: disable=broad-exception-caught
3710                pass
3711            try:
3712                ack = self._read_exact(1)
3713            except CloneTransportError as exc:
3714                raise CloneTransportError(
3715                    f"No ACK for write cmd 0x{command:02X} address 0x{address:04X} ({exc})"
3716                ) from exc
3717            if ack != ACK:
3718                raise CloneTransportError(
3719                    f"Write ACK mismatch at 0x{address:04X}: expected 0x06, got {ack.hex()}"
3720                )
3721            self.logger.debug("Received ACK for 0x%04X", address)
3722            try:
3723                self.serial.timeout = old_timeout
3724            except Exception:  # pylint: disable=broad-exception-caught
3725                pass
3726            if pause:
3727                time.sleep(pause)
3728            if command == 0x58:
3729                time.sleep(0.5)  # let the APRS commit settle before 'E'
3730            offset += READ_BLOCK
3731            done += 1
3732            if self.progress_cb:
3733                try:
3734                    self.progress_cb(done, total_blocks, "write")
3735                # Progress reporting must never break the clone operation.
3736                except Exception:  # pylint: disable=broad-exception-caught
3737                    pass
3738
3739        self._write(END_COMMAND)
3740
3741    # ------------------------------------------------------------------
3742    # Internal helpers
3743    # ------------------------------------------------------------------
3744
3745    def _write(self, data: bytes) -> None:
3746        """Send bytes to the radio.
3747
3748        Args:
3749            data: Raw bytes to write; empty data sends nothing.
3750
3751        Raises:
3752            CloneTransportError: If the port reports a short write.
3753        """
3754        if not data:
3755            return
3756        written = self.serial.write(data)
3757        if written is None:
3758            return
3759        if written != len(data):
3760            raise CloneTransportError("Serial write truncated")
3761
3762    def _read_exact(self, size: int) -> bytes:
3763        """Read exactly ``size`` bytes.
3764
3765        Args:
3766            size: Number of bytes to read.
3767
3768        Returns:
3769            bytes: Exactly ``size`` bytes as received (not XOR-decoded).
3770
3771        Raises:
3772            CloneTransportError: If the port times out first.
3773        """
3774        buf = bytearray()
3775        while len(buf) < size:
3776            chunk = self.serial.read(size - len(buf))
3777            if not chunk:
3778                raise CloneTransportError("Serial read timed out")
3779            buf.extend(chunk)
3780        return bytes(buf)
3781
3782    def _build_encryption_frame(self) -> Tuple[bytes, bytearray]:
3783        """Build the 25-byte ``SEND`` frame and the key it selects.
3784
3785        Bytes 0-3 are ``SEND``. Byte 4 is a random code 0x10-0x14 or
3786        0x20-0x24. Bytes 5-23 are random indexes 0-19. Byte 24 is 0. Code
3787        0x1n selects ``frame[5 + 2n]``, code 0x2n selects ``frame[6 + 2n]``;
3788        that byte is the index into ``ENCRYPT_STRINGS`` of the key.
3789
3790        Returns:
3791            tuple[bytes, bytearray]: The frame to send and the 4-byte XOR key.
3792        """
3793        frame = bytearray(25)
3794        frame[0:4] = b"SEND"
3795        frame[4] = (self._rng.randint(1, 2) << 4) | self._rng.randint(0, 4)
3796        for index in range(19):
3797            frame[5 + index] = self._rng.randint(0, 19)
3798        code = frame[4]
3799        if code & 0x20:
3800            idx = (code - 0x20) * 2 + 1
3801        else:
3802            idx = (code - 0x10) * 2
3803        idx += 1
3804        symbol_index = frame[4 + idx]
3805        key = bytearray(ENCRYPT_STRINGS[symbol_index])
3806        return bytes(frame), key
3807
3808    def _apply_xor(self, payload: bytearray) -> bytearray:
3809        """XOR a payload in place with the session key and return it.
3810
3811        The operation is its own inverse, so it both encrypts and decrypts.
3812
3813        Bytes 0x00 and 0xFF, bytes equal to the key byte or its complement, and
3814        positions where the key byte is a space (0x20) are left unchanged.
3815
3816        Args:
3817            payload: Block payload; modified in place.
3818
3819        Returns:
3820            bytearray: The same ``payload`` object after XOR.
3821        """
3822        assert self._xor_key is not None, "XOR key not initialised"
3823        key = self._xor_key
3824        key_idx = 0
3825        for i, value in enumerate(payload):
3826            k = key[key_idx]
3827            key_idx = (key_idx + 1) % len(key)
3828            if k != 0x20 and value not in (0x00, 0xFF) and value not in (k, k ^ 0xFF):
3829                payload[i] = value ^ k
3830        return payload
3831
3832    @staticmethod
3833    def _iter_read_commands(segments: Sequence[CloneSegment]) -> Iterable[Tuple[int, int]]:
3834        """Yield ``(read_command, address)`` for every block of ``segments``.
3835
3836        Args:
3837            segments: Regions to read, in order.
3838
3839        Yields:
3840            tuple[int, int]: The segment's read command and the start address of
3841            each ``READ_BLOCK``-byte block.
3842        """
3843        for segment in segments:
3844            for offset in range(0, segment.length, READ_BLOCK):
3845                yield segment.read_command, segment.start + offset
3846
3847    @staticmethod
3848    def _iter_write_commands(segments: Sequence[CloneSegment]) -> Iterable[Tuple[int, int]]:
3849        """Yield ``(write_command, address)`` for every block of ``segments``.
3850
3851        Args:
3852            segments: Regions to write, in order.
3853
3854        Yields:
3855            tuple[int, int]: The segment's write command and the start address of
3856            each ``READ_BLOCK``-byte block.
3857        """
3858        for segment in segments:
3859            for offset in range(0, segment.length, READ_BLOCK):
3860                yield segment.write_command, segment.start + offset
3861
3862
3863# ===========================================================================
3864# 6. CHIRP integration
3865# ===========================================================================
3866
3867LOG = logging.getLogger(__name__)
3868"""Driver logger; rebinds the section-1 ``LOG`` (see there)."""
3869
3870# ---------------------------------------------------------------------------
3871# CHIRP compatibility layer
3872#
3873# Inside CHIRP the real modules are imported. Without CHIRP (documentation
3874# builds) minimal stand-ins with the same names are defined so the module
3875# still imports; the radio cannot be used then (HAVE_CHIRP is False;
3876# get_features, get_settings, get_memory and set_memory raise RadioError). The stand-ins mimic CHIRP's module and
3877# class names, hence the naming-style exceptions below.
3878# ---------------------------------------------------------------------------
3879
3880try:  # pragma: no cover - executed when real CHIRP is available
3881    from chirp import chirp_common, directory, errors, memmap  # type: ignore
3882    from chirp import bitwise  # type: ignore
3883    from chirp.settings import (
3884        RadioSetting,
3885        RadioSettingGroup,
3886        RadioSettingValueBoolean,
3887        RadioSettingValueInteger,
3888        RadioSettingValueList,
3889        RadioSettingValueString,
3890        RadioSettings,
3891    )
3892
3893    _CHIRP_IMPORT_ERROR: Optional[ImportError] = None
3894    """Why CHIRP could not be imported; ``None`` when it was."""
3895
3896except ImportError as _chirp_import_error:  # pragma: no cover - documentation builds
3897    _CHIRP_IMPORT_ERROR = _chirp_import_error
3898    # The stand-ins keep CHIRP's signatures, so some arguments are unused.
3899    # pylint: disable=unused-argument
3900
3901    class _Memory:
3902        """Stand-in for ``chirp_common.Memory``: plain attributes, not all the driver sets."""
3903
3904        def __init__(self) -> None:
3905            """Create a memory with zero or blank fields.
3906
3907            These are not CHIRP's defaults; ``empty`` is ``False``.
3908            """
3909            self.number = 0
3910            """Memory number."""
3911            self.freq = 0
3912            """Receive frequency in Hz."""
3913            self.offset = 0
3914            """Offset in Hz, or the TX frequency for ``split``."""
3915            self.duplex = ""
3916            """``""``, ``"+"``, ``"-"`` or ``"split"``."""
3917            self.tmode = ""
3918            """CHIRP tone mode, e.g. ``"Tone"``."""
3919            self.rtone = 0.0
3920            """Tone-mode CTCSS tone in Hz."""
3921            self.ctone = 0.0
3922            """TSQL CTCSS tone in Hz."""
3923            self.dtcs = 0
3924            """DCS code."""
3925            self.dtcs_pol = "N"
3926            """DCS polarity; CHIRP's attribute is ``dtcs_polarity`` (e.g. ``"NN"``)."""
3927            self.mode = "FM"
3928            """Modulation."""
3929            self.power = ""
3930            """Power level."""
3931            self.skip = ""
3932            """``""`` scanned or ``"S"`` skipped."""
3933            self.name = ""
3934            """Channel name."""
3935            self.empty = False
3936            """``True`` for an unused memory."""
3937            self.extra = {}
3938            """Extra per-memory settings."""
3939
3940    class _RadioFeatures:
3941        """Stand-in for ``chirp_common.RadioFeatures``: plain attributes."""
3942
3943        def __init__(self) -> None:
3944            """Set the attributes the driver reads or overwrites."""
3945            self.has_bank = False
3946            """Banks supported."""
3947            self.has_bank_names = False
3948            """Bank names supported."""
3949            self.has_name = True
3950            """Channel names supported."""
3951            self.has_ctone = True
3952            """Separate TSQL tone supported."""
3953            self.has_dtcs = True
3954            """DCS supported."""
3955            self.has_dtcs_polarity = True
3956            """DCS polarity supported."""
3957            self.has_mode = True
3958            """Modulation selectable."""
3959            self.has_offset = True
3960            """Offset supported."""
3961            self.has_tuning_step = False
3962            """Per-channel tuning step supported."""
3963            self.can_delete = True
3964            """Memories can be erased."""
3965            self.can_odd_split = True
3966            """``split`` (any TX frequency) supported."""
3967            self.memory_bounds = (0, 0)
3968            """First and last memory number."""
3969            self.valid_bands = []
3970            """``(low, high)`` bands in Hz."""
3971            self.valid_duplexes = ["", "+", "-", "split"]
3972            """Allowed duplex values."""
3973            self.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
3974            """Allowed tone modes."""
3975            self.valid_modes = ["FM", "NFM", "AM"]
3976            """Allowed modulations."""
3977            self.valid_power_levels = ["Low", "Medium", "High"]
3978            """Allowed power levels."""
3979            self.valid_skips = ["", "S"]
3980            """Allowed skip values."""
3981            self.valid_name_length = 12
3982            """Maximum name length in characters."""
3983
3984    class _CloneModeRadio:
3985        """Stand-in for ``chirp_common.CloneModeRadio``."""
3986
3987        VENDOR = ""
3988        """Vendor name; set by the driver class."""
3989        MODEL = ""
3990        """Model name; set by the driver class."""
3991        BAUD_RATE = 115200
3992        """Serial speed in baud."""
3993
3994        def __init__(self, *args, **kwargs) -> None:
3995            """Store ``pipe`` if given as keyword.
3996
3997            Unlike CHIRP's base class, a positional port is ignored and
3998            nothing is loaded.
3999
4000            Args:
4001                *args: Positional arguments; ignored.
4002                **kwargs: Keyword arguments; only ``pipe`` is used and stored
4003                    as ``self.pipe``.
4004            """
4005            self.pipe = kwargs.get("pipe")
4006            """Serial port object, or ``None``."""
4007
4008    class _Directory:
4009        """Stand-in for ``chirp.directory``."""
4010
4011        @staticmethod
4012        def register(radio_class):
4013            """Return ``radio_class`` unchanged; nothing is registered.
4014
4015            Args:
4016                radio_class: The driver class being decorated.
4017
4018            Returns:
4019                type: ``radio_class`` itself.
4020            """
4021            return radio_class
4022
4023    class _Errors:
4024        """Stand-in for ``chirp.errors``."""
4025
4026        class RadioError(Exception):
4027            """Stand-in for ``chirp.errors.RadioError``."""
4028
4029    class _MemoryMapBytes(bytearray):
4030        """Stand-in for ``chirp.memmap.MemoryMapBytes``: a mutable byte buffer."""
4031
4032        def get_packed(self):
4033            """Return the buffer as bytes.
4034
4035            Returns:
4036                bytes: A copy of the buffer.
4037            """
4038            return bytes(self)
4039
4040    class memmap:  # type: ignore  # pylint: disable=invalid-name
4041        """Stand-in for the ``chirp.memmap`` module."""
4042
4043        MemoryMapBytes = _MemoryMapBytes
4044        """The stand-in memory map class."""
4045
4046    class _PowerLevel(str):
4047        """Stand-in for ``chirp_common.PowerLevel``: a label with ``watts``."""
4048
4049        def __new__(cls, label, watts=0.0):
4050            """Create the level as a string with a ``watts`` attribute.
4051
4052            Args:
4053                label: Display label, e.g. ``"High"``.
4054                watts: Nominal power in watts.
4055
4056            Returns:
4057                _PowerLevel: The new level.
4058            """
4059            obj = str.__new__(cls, label)
4060            obj.watts = watts
4061            return obj
4062
4063    class _RadioSettingValue:
4064        """Stand-in base for ``chirp.settings.RadioSettingValue*``."""
4065
4066        def __init__(self, value=None):
4067            """Store the initial value; the value starts editable.
4068
4069            Args:
4070                value: Initial current value.
4071            """
4072            self._value = value
4073            """Current value."""
4074            self._mutable = True
4075            """``False`` after ``set_mutable(False)``."""
4076
4077        def initialize(self):
4078            """Do nothing.
4079
4080            In CHIRP it sets the value stashed by ``queue_current``; the
4081            stand-in stores that value at once.
4082            """
4083
4084        def set_mutable(self, mutable):
4085            """Mark the value as editable or read-only, as CHIRP does.
4086
4087            Args:
4088                mutable: ``False`` for a read-only value.
4089            """
4090            self._mutable = mutable
4091
4092        def get_mutable(self):
4093            """Return whether the value is editable.
4094
4095            Returns:
4096                bool: ``False`` after ``set_mutable(False)``.
4097            """
4098            return self._mutable
4099
4100        def set_value(self, value):
4101            """Store ``value`` without checks.
4102
4103            Args:
4104                value: New value.
4105            """
4106            self._value = value
4107
4108        def get_value(self):
4109            """Return the current value.
4110
4111            Returns:
4112                object: The stored value.
4113            """
4114            return self._value
4115
4116        def queue_current(self, value):
4117            """Store ``value`` at once (CHIRP stashes it until ``initialize``).
4118
4119            Args:
4120                value: New value.
4121            """
4122            self._value = value
4123
4124        def __int__(self):
4125            """Return the value as an integer.
4126
4127            Returns:
4128                int: ``int(value)``.
4129            """
4130            return int(self._value)
4131
4132        def __bool__(self):
4133            """Return the value as a boolean.
4134
4135            Returns:
4136                bool: ``bool(value)``.
4137            """
4138            return bool(self._value)
4139
4140        def __str__(self):
4141            """Return the value as text.
4142
4143            Returns:
4144                str: ``str(value)``.
4145            """
4146            return str(self._value)
4147
4148    class RadioSettingValueBoolean(_RadioSettingValue):
4149        """Stand-in for ``chirp.settings.RadioSettingValueBoolean``."""
4150
4151        def __init__(self, current, mem_vals=(0, 1)):
4152            """Store ``bool(current)``.
4153
4154            Args:
4155                current: Initial value; stored as ``bool(current)``.
4156                mem_vals: Ignored by the stand-in.
4157            """
4158            super().__init__(bool(current))
4159
4160        def set_value(self, value):
4161            """Store ``bool(value)``.
4162
4163            Args:
4164                value: New value.
4165            """
4166            super().set_value(bool(value))
4167
4168    class RadioSettingValueInteger(_RadioSettingValue):
4169        """Stand-in for ``chirp.settings.RadioSettingValueInteger``."""
4170
4171        def __init__(self, minval, maxval, current, step=1):
4172            """Store the range and ``int(current)``.
4173
4174            Args:
4175                minval: Lowest value accepted by ``set_value``.
4176                maxval: Highest value accepted by ``set_value``.
4177                current: Initial value; stored as ``int(current)``.
4178                step: Ignored by the stand-in.
4179            """
4180            self._min = minval
4181            """Lowest accepted value."""
4182            self._max = maxval
4183            """Highest accepted value."""
4184            super().__init__(int(current))
4185
4186        def set_value(self, value):
4187            """Store ``int(value)`` if it lies within the range.
4188
4189            Args:
4190                value: New value.
4191
4192            Raises:
4193                ValueError: If ``int(value)`` fails or lies outside
4194                    ``minval``-``maxval``.
4195            """
4196            value = int(value)
4197            if value < self._min or value > self._max:
4198                raise ValueError
4199            super().set_value(value)
4200
4201    class RadioSettingValueList(_RadioSettingValue):
4202        """Stand-in for ``chirp.settings.RadioSettingValueList``."""
4203
4204        def __init__(self, choices, current_index=0):
4205            """Store the choices and select ``choices[current_index]``.
4206
4207            Args:
4208                choices: Allowed values, in display order.
4209                current_index: Index into ``choices`` of the initial value.
4210            """
4211            self.choices = list(choices)
4212            """Allowed values, in display order."""
4213            index = int(current_index) if self.choices else 0
4214            super().__init__(self.choices[index] if self.choices else None)
4215
4216        def set_value(self, value):
4217            """Select a choice by index or by value.
4218
4219            Args:
4220                value: Index into ``choices`` (``int``) or one of the choices.
4221
4222            Raises:
4223                ValueError: If the index is out of range or the value is not
4224                    one of the choices.
4225            """
4226            if isinstance(value, int):
4227                if value < 0 or value >= len(self.choices):
4228                    raise ValueError
4229                self._value = self.choices[value]
4230            else:
4231                if value not in self.choices:
4232                    raise ValueError
4233                self._value = value
4234
4235        def __int__(self):
4236            """Return the index of the current value in ``choices``.
4237
4238            Returns:
4239                int: The index.
4240
4241            Raises:
4242                ValueError: If the current value is not one of the choices.
4243            """
4244            if self._value in self.choices:
4245                return self.choices.index(self._value)
4246            raise ValueError
4247
4248    class RadioSettingValueString(_RadioSettingValue):
4249        """Stand-in for ``chirp.settings.RadioSettingValueString``."""
4250
4251        def __init__(self, minlength, maxlength, current, autopad=True,
4252                     charset=None, mem_pad_char=' '):
4253            """Store the limits and the initial text.
4254
4255            Args:
4256                minlength: Ignored by the stand-in.
4257                maxlength: Maximum length accepted by ``set_value``.
4258                current: Initial text; ``None`` or empty becomes ``""``.
4259                autopad: Stored as ``self.autopad``; not otherwise used.
4260                charset: Ignored by the stand-in.
4261                mem_pad_char: Stored as ``self.mem_pad_char``; not otherwise used.
4262            """
4263            self.maxlength = maxlength
4264            """Maximum length accepted by ``set_value``."""
4265            self.autopad = autopad
4266            """Stored only."""
4267            self.mem_pad_char = mem_pad_char
4268            """Stored only."""
4269            super().__init__(current or "")
4270
4271        def set_value(self, value):
4272            """Store ``str(value)`` if it is not too long.
4273
4274            Args:
4275                value: New text.
4276
4277            Raises:
4278                ValueError: If the text is longer than ``maxlength``.
4279            """
4280            value = str(value)
4281            if len(value) > self.maxlength:
4282                raise ValueError
4283            super().set_value(value)
4284
4285    class RadioSettingGroup:
4286        """Stand-in for ``chirp.settings.RadioSettingGroup``."""
4287
4288        def __init__(self, name, label, *elements):
4289            """Store name and label and append ``elements`` in order.
4290
4291            Args:
4292                name: Internal group name.
4293                label: Display label.
4294                *elements: Initial child settings or groups, appended in order.
4295            """
4296            self.name = name
4297            """Internal group name."""
4298            self.label = label
4299            """Display label."""
4300            self._children = []
4301            """Child settings and groups, in order."""
4302            for element in elements:
4303                self.append(element)
4304
4305        def append(self, element):
4306            """Add a child setting or group at the end.
4307
4308            Args:
4309                element: A ``RadioSetting`` or ``RadioSettingGroup``.
4310            """
4311            self._children.append(element)
4312
4313        def __iter__(self):
4314            """Iterate over the direct children.
4315
4316            Returns:
4317                Iterator: Over the children, in order.
4318            """
4319            return iter(self._children)
4320
4321        def get(self, name, default=None):
4322            """Return the value of the direct child setting called ``name``.
4323
4324            Args:
4325                name: Setting name.
4326                default: Returned when no direct child has that name.
4327
4328            Returns:
4329                object: The setting's ``get_value()`` (or its value object
4330                if it has none), or ``default``.
4331            """
4332            for child in self._children:
4333                if isinstance(child, RadioSetting) and child.name == name:
4334                    value_obj = getattr(child, 'value', None)
4335                    if hasattr(value_obj, 'get_value'):
4336                        return value_obj.get_value()
4337                    return value_obj
4338            return default
4339
4340        def __getitem__(self, name):
4341            """Return the value of the direct child setting called ``name``.
4342
4343            Args:
4344                name: Setting name.
4345
4346            Returns:
4347                object: As :meth:`get`.
4348
4349            Raises:
4350                KeyError: If no direct child has that name or its value is
4351                    ``None``.
4352            """
4353            result = self.get(name, None)
4354            if result is None:
4355                raise KeyError(name)
4356            return result
4357
4358        def walk(self) -> Iterable["RadioSetting"]:
4359            """Yield every setting in the tree, depth first.
4360
4361            Yields:
4362                RadioSetting: Each setting below this group, in order.
4363            """
4364            for child in self._children:
4365                if isinstance(child, RadioSetting):
4366                    yield child
4367                elif isinstance(child, RadioSettingGroup):
4368                    yield from child.walk()
4369
4370    class RadioSetting(RadioSettingGroup):
4371        """Stand-in for ``chirp.settings.RadioSetting``."""
4372
4373        def __init__(self, name, label, value):
4374            """Store the setting with ``value`` as its only child.
4375
4376            Args:
4377                name: Internal setting name.
4378                label: Display label.
4379                value: The ``RadioSettingValue*`` object holding the value.
4380            """
4381            super().__init__(name, label, value)
4382            self._value = value
4383            """The ``RadioSettingValue*`` object."""
4384            self._apply = None
4385            """Apply callback without arguments, or ``None``."""
4386
4387        @property
4388        def value(self):
4389            """The ``RadioSettingValue*`` object holding the value."""
4390            return self._value
4391
4392        def set_apply_callback(self, callback, *args):
4393            """Register ``callback(setting, *args)`` to run on apply.
4394
4395            Args:
4396                callback: Function called with this setting and ``args``.
4397                *args: Extra arguments passed to ``callback``.
4398            """
4399            self._apply = lambda: callback(self, *args)
4400
4401        def has_apply_callback(self):
4402            """Return whether an apply callback is registered.
4403
4404            Returns:
4405                bool: ``True`` after :meth:`set_apply_callback`.
4406            """
4407            return self._apply is not None
4408
4409        def run_apply_callback(self):
4410            """Run the apply callback, if any."""
4411            if self._apply:
4412                self._apply()
4413
4414        def get_name(self):
4415            """Return the internal setting name.
4416
4417            Returns:
4418                str: ``self.name``.
4419            """
4420            return self.name
4421
4422    class RadioSettings(RadioSettingGroup):
4423        """Stand-in for ``chirp.settings.RadioSettings``."""
4424
4425        def __init__(self, *groups):
4426            """Create the root group ``root`` holding ``groups``.
4427
4428            Args:
4429                *groups: Top-level setting groups, appended in order.
4430            """
4431            super().__init__('root', 'root', *groups)
4432
4433    class chirp_common:  # type: ignore  # pylint: disable=invalid-name
4434        """Stand-in for the ``chirp.chirp_common`` module.
4435
4436        Only enough to import the module and build the documentation. It
4437        lacks, among others, ``Status``, ``DTCS_CODES``, ``CHARSET_ASCII``,
4438        ``CROSS_MODES``, ``is_split`` and ``split_tone_decode``/``encode``.
4439        ``get_features``, ``get_settings``, ``get_memory`` and ``set_memory``
4440        check :data:`HAVE_CHIRP` and raise a ``RadioError``; other methods may
4441        fail with ``AttributeError``.
4442        """
4443
4444        Memory = _Memory
4445        """The stand-in memory class."""
4446        RadioFeatures = _RadioFeatures
4447        """The stand-in features class."""
4448        CloneModeRadio = _CloneModeRadio
4449        """The stand-in radio base class."""
4450        PowerLevel = _PowerLevel
4451        """The stand-in power level class."""
4452
4453        @staticmethod
4454        def format_freq(hz):
4455            """Format a frequency in Hz as MHz with six decimals.
4456
4457            Args:
4458                hz: Frequency in Hz; ``None`` or ``""`` counts as 0.
4459
4460            Returns:
4461                str: E.g. ``"145.500000"`` for 145500000.
4462            """
4463            hz = 0 if hz in (None, "") else int(hz)
4464            return f"{hz / 1_000_000:.6f}"
4465
4466        @staticmethod
4467        def parse_freq(text):
4468            """Parse a frequency text into Hz.
4469
4470            Without a unit or with ``MHz`` the number is MHz, e.g.
4471            ``"145.5"``, unless it is at least 1000000, then it is Hz.
4472            ``kHz`` and ``Hz`` suffixes are accepted too; units are
4473            case-insensitive.
4474
4475            Args:
4476                text: The frequency text; empty gives 0.
4477
4478            Returns:
4479                int: The frequency in Hz, rounded.
4480
4481            Raises:
4482                ValueError: If the text is not a number or is negative.
4483                OverflowError: If the number is infinite (e.g. ``"inf"``).
4484            """
4485            value = str(text).strip().lower()
4486            if not value:
4487                return 0
4488            multiplier = 1_000_000
4489            if value.endswith('mhz'):
4490                value = value[:-3].strip()
4491                multiplier = 1_000_000
4492            elif value.endswith('khz'):
4493                value = value[:-3].strip()
4494                multiplier = 1_000
4495            elif value.endswith('hz'):
4496                value = value[:-2].strip()
4497                multiplier = 1
4498            try:
4499                numeric = float(value)
4500            except ValueError as exc:
4501                raise ValueError(f"Invalid frequency '{text}'") from exc
4502            if numeric < 0:
4503                raise ValueError('Frequency must be non-negative')
4504            if multiplier == 1 and numeric >= 1_000_000:
4505                return int(round(numeric))
4506            if multiplier == 1_000_000 and numeric >= 1_000_000:
4507                return int(round(numeric))
4508            return int(round(numeric * multiplier))
4509
4510    directory = _Directory()  # type: ignore
4511    errors = _Errors()  # type: ignore
4512    # pylint: enable=unused-argument
4513
4514HAVE_CHIRP: bool = _CHIRP_IMPORT_ERROR is None
4515"""``True`` when the real CHIRP modules were imported.
4516
4517``False`` means the stand-ins above are in use: the module imports (for
4518documentation builds) but :meth:`RT950ProRadio.get_features`,
4519:meth:`RT950ProRadio.get_settings`, :meth:`RT950ProRadio.get_memory` and
4520:meth:`RT950ProRadio.set_memory` (and the same methods of a zone) raise
4521``RadioError``."""
4522
4523
4524def _require_chirp(what: str) -> None:
4525    """Raise a clear error when CHIRP is not available.
4526
4527    Args:
4528        what: Name of the method that needs CHIRP, used in the message.
4529
4530    Raises:
4531        RadioError: If :data:`HAVE_CHIRP` is ``False``; the message names
4532            ``what`` and the original import error.
4533    """
4534    if not HAVE_CHIRP:
4535        raise errors.RadioError(
4536            f"{what} needs CHIRP, which could not be imported "
4537            f"({_CHIRP_IMPORT_ERROR}); without CHIRP the driver only loads "
4538            "for documentation builds"
4539        )
4540
4541# ---------------------------------------------------------------------------
4542# Constants and lookup tables for the CHIRP layer
4543# ---------------------------------------------------------------------------
4544
4545_SEGMENT_LENGTH = sum(segment.length for segment in DEFAULT_SEGMENTS)
4546"""Size in bytes of a complete clone image (all ``DEFAULT_SEGMENTS``)."""
4547
4548_CHIRP_POWER_LEVELS = [
4549    chirp_common.PowerLevel('Low', watts=1.0),
4550    chirp_common.PowerLevel('Medium', watts=5.0),
4551    chirp_common.PowerLevel('High', watts=10.0),
4552]
4553"""Power levels offered in CHIRP, lowest first.
4554
4555The wattages are nominal values for display; the radio stores only
4556the level.
4557"""
4558
4559_POWER_ENUM_TO_CHIRP = {
4560    PowerLevel.LOW: _CHIRP_POWER_LEVELS[0],
4561    PowerLevel.MEDIUM: _CHIRP_POWER_LEVELS[1],
4562    PowerLevel.HIGH: _CHIRP_POWER_LEVELS[2],
4563}
4564"""Maps :class:`PowerLevel` to the CHIRP power level."""
4565
4566_POWER_LABEL_TO_ENUM = {str(level).upper(): enum for enum, level in _POWER_ENUM_TO_CHIRP.items()}
4567"""Maps an upper-case CHIRP power label (``"HIGH"``) to :class:`PowerLevel`."""
4568
4569_CHANNEL_DIVIDE_CHOICES = [
4570    ('Zone CH Mode', CHANNEL_DIVIDE_ZONE),
4571    ('All CH Mode', CHANNEL_DIVIDE_ALL),
4572]
4573"""Labels (as in the CPS list *Channel Divide*, in its order) and stored
4574values of the function setting ``divide_channel``."""
4575
4576_FUNCTION_UI = {
4577    'sql': {'label': 'Squelch Level', 'type': 'int', 'min': 0, 'max': 9},
4578    'save_mode': {'label': 'Battery Save', 'type': 'int', 'min': 0, 'max': 3},
4579    'vox': {'label': 'VOX Gain', 'type': 'int', 'min': 0, 'max': 9},
4580    'vox_delay': {'label': 'VOX Delay', 'type': 'int', 'min': 0, 'max': 9},
4581    'auto_backlight': {'label': 'Auto Backlight', 'type': 'int', 'min': 0, 'max': 9},
4582    'tot': {'label': 'Time-out Timer', 'type': 'int', 'min': 0, 'max': 9},
4583    'beep_prompt': {'label': 'Key Beep', 'type': 'bool'},
4584    'voice_prompt': {
4585        'label': 'Voice Prompt',
4586        'type': 'enum',
4587        'choices': [('Off', 0), ('English', 1), ('Chinese', 2)],
4588    },
4589    'language': {
4590        'label': 'Menu Language',
4591        'type': 'enum',
4592        'choices': [('English', 0), ('Chinese', 1), ('Other', 2)],
4593    },
4594    'dtmf_mode': {
4595        'label': 'DTMF Mode',
4596        'type': 'enum',
4597        'choices': [('Off', 0), ('DT-ST', 1), ('ANI-ID', 2), ('DTMF', 3)],
4598    },
4599    'scan_mode': {
4600        'label': 'Scan Mode',
4601        'type': 'enum',
4602        'choices': [('Time', 0), ('Carrier', 1), ('Search', 2)],
4603    },
4604    'ptt_id': {
4605        'label': 'PTT ID',
4606        'type': 'enum',
4607        'choices': [('Off', 0), ('BOT', 1), ('EOT', 2), ('Both', 3)],
4608    },
4609    'display_mode_a': {
4610        'label': 'Display Mode A',
4611        'type': 'enum',
4612        'choices': [('Channel', 0), ('Frequency', 1), ('Name', 2)],
4613    },
4614    'display_mode_b': {
4615        'label': 'Display Mode B',
4616        'type': 'enum',
4617        'choices': [('Channel', 0), ('Frequency', 1), ('Name', 2)],
4618    },
4619    'display_mode_c': {
4620        'label': 'Display Mode C',
4621        'type': 'enum',
4622        'choices': [('Channel', 0), ('Frequency', 1), ('Name', 2)],
4623    },
4624    'auto_key_lock': {'label': 'Auto Key Lock', 'type': 'bool'},
4625    'alarm_mode': {
4626        'label': 'Alarm Mode',
4627        'type': 'enum',
4628        'choices': [('Local', 0), ('Remote', 1), ('Tone', 2)],
4629    },
4630    'alarm_sound': {
4631        'label': 'Alarm Sound',
4632        'type': 'enum',
4633        'choices': [('Off', 0), ('Type 1', 1), ('Type 2', 2)],
4634    },
4635    'tail_noise_clear': {'label': 'Tail Noise Clear', 'type': 'bool'},
4636    'pass_repeater_noise_clear': {'label': 'Repeater Noise Clear', 'type': 'bool'},
4637    'sound_tx_end': {'label': 'Roger Beep', 'type': 'bool'},
4638    'fm_radio': {'label': 'FM Radio', 'type': 'bool'},
4639    'lock_keyboard': {'label': 'Keypad Lock', 'type': 'bool'},
4640    'power_on_message': {
4641        'label': 'Power-on Message',
4642        'type': 'enum',
4643        'choices': [('Full', 0), ('Message', 1), ('Voltage', 2)],
4644    },
4645    'bt_write_switch': {'label': 'Bluetooth Enable', 'type': 'bool'},
4646    'vox_switch': {'label': 'VOX Enable', 'type': 'bool'},
4647    'divide_channel': {
4648        'label': 'Channel Divide',
4649        'type': 'enum',
4650        'choices': _CHANNEL_DIVIDE_CHOICES,
4651        'volatile': True,
4652    },
4653}
4654"""Function settings shown in CHIRP: key to label, type and range or
4655choices. Keys not listed here are kept but not shown.
4656
4657An entry with ``'volatile': True`` is marked volatile in CHIRP (see
4658:func:`_create_function_setting`): changing it makes CHIRP rebuild the
4659editor, so the memory tabs follow the new value at once.
4660"""
4661
4662_APRS_UI = {
4663    'aprs_switch': {'label': 'APRS Enable', 'type': 'bool'},
4664    'gps_switch': {'label': 'GPS Enable', 'type': 'bool'},
4665    'call_sign': {'label': 'Callsign', 'type': 'string', 'length': 6},
4666    'ssid': {'label': 'SSID', 'type': 'enum', 'choices': [(str(i), i) for i in range(16)]},
4667    'aprs_priority': {
4668        'label': 'Priority',
4669        'type': 'enum',
4670        'choices': [('Low', 0), ('Normal', 1), ('High', 2)],
4671    },
4672    'data_tx_delay': {'label': 'Data TX Delay', 'type': 'int', 'min': 0, 'max': 9},
4673    'aprs_decode_prompt_tone': {'label': 'RX Prompt Tone', 'type': 'bool'},
4674    'aprs_rx_auto_popup': {'label': 'RX Auto Popup', 'type': 'bool'},
4675    'aprs_forward_channel': {
4676        'label': 'Forward Channel',
4677        'type': 'enum',
4678        'choices': [(str(i), i) for i in range(16)],
4679    },
4680    'aprs_wait_forward': {'label': 'Forward Wait', 'type': 'int', 'min': 0, 'max': 9},
4681    'custom_messages': {'label': 'Custom Message', 'type': 'string', 'length': 40},
4682}
4683"""APRS settings shown in CHIRP: key to label, type and range or choices.
4684Keys not listed here are kept but not shown.
4685"""
4686
4687_DTMF_GROUP_LIMIT = 5
4688"""Number of DTMF code groups shown in CHIRP (the radio has 22)."""
4689
4690_DTMF_ID_MAXLEN = 5
4691"""Maximum length of the own DTMF ID."""
4692
4693_DTMF_CODE_MAXLEN = 6
4694"""Maximum length of a DTMF code group."""
4695
4696_DTMF_MODE_CHOICES = [('Off', 0), ('BOT', 1), ('EOT', 2), ('Both', 3)]
4697"""PTT ID mode labels and stored values."""
4698
4699_VFO_LABELS = ['A', 'B', 'C']
4700"""Letters of the three VFOs; the groups are named ``VFO-A`` to ``VFO-C`` as in the CPS."""
4701_VFO_OFFSET_CHOICES = [('None', 0), ('Plus', 1), ('Minus', 2)]
4702"""Offset Dir labels of the CPS and the stored values (byte 14, bits 5-4).
4703Stored value 3 is not offered and is shown as unknown."""
4704_VFO_BANDWIDTH_CHOICES = [('Wide', Bandwidth.WIDE), ('Narrow', Bandwidth.NARROW)]
4705"""Bandwidth labels of the CPS and :class:`Bandwidth` values."""
4706_VFO_MODULATION_CHOICES = [('FM', Modulation.FM), ('AM', Modulation.AM)]
4707"""RxModulation labels of the CPS and :class:`Modulation` values."""
4708_VFO_POWER_CHOICES = [
4709    ('High', PowerLevel.HIGH),
4710    ('Middle', PowerLevel.MEDIUM),
4711    ('Low', PowerLevel.LOW),
4712]
4713"""Tx Power labels of the CPS and :class:`PowerLevel` values (stored 0, 1, 2)."""
4714_VFO_ENCRYPTION_CHOICES = [('OFF', 0), ('Encryption 1', 1), ('Encryption 2', 2),
4715                           ('Encryption 3', 3)]
4716"""Encryption labels of the CPS and the stored values (byte 17, bits 5-4)."""
4717_VFO_BAND_CHOICES = [('VHF', 0), ('UHF', 1)]
4718"""Freq Band labels of the CPS and the stored values (byte 18, low nibble).
4719
4720Confirmed on a radio: 439.4 MHz stores 1 (UHF), 145.025 MHz and 27.025 MHz
4721store 0 (VHF). The CPS shows the field read-only and derives it from Rx
4722Freq; so does the driver (see ``_VFO_UHF_FROM_HZ``).
4723"""
4724_VFO_UHF_FROM_HZ = 300_000_000
4725"""Lowest Rx Freq the CPS shows as UHF: 299.99999 MHz is VHF, 300.00000 MHz
4726UHF (measured in the CPS VFO Mode screen)."""
4727_VFO_STEP_CHOICES = [
4728    ('2.5KHz', 0),
4729    ('5.0KHz', 1),
4730    ('6.25KHz', 2),
4731    ('8.33KHz', 3),
4732    ('10.0KHz', 4),
4733    ('12.5KHz', 5),
4734    ('20.0KHz', 6),
4735    ('25.0KHz', 7),
4736    ('50.0KHz', 8),
4737    ('100.0KHz', 9),
4738]
4739"""Step Freq labels of the CPS and the stored index (byte 19, low nibble).
4740
4741Confirmed on a radio: 100.0KHz stores 9, 25.0KHz 7, 12.5KHz 5.
4742"""
4743_VFO_SCRAMBLE_CHOICES = [('OFF', 0)] + [(f'Scramble {n}', n) for n in range(1, 9)]
4744"""Scramble labels of the CPS and the stored values 0-8 (byte 16, high nibble)."""
4745_VFO_SIGNALLING_CHOICES = [(str(n + 1), n) for n in range(15)]
4746"""Signalling labels of the CPS (1-15) and the stored values 0-14.
4747
4748The CPS stores the shown number minus one (byte 14, low nibble); confirmed
4749on a radio: 15 stores 14, 1 stores 0. A stored 15 is not offered and shows
4750as ``Unknown (15)``, the stored value.
4751"""
4752_VFO_BUSY_LOCKOUT_CHOICES = [('OFF', False), ('ON', True)]
4753"""Busy Lockout labels of the CPS and the flag value (byte 13, bit 0)."""
4754_CTCSS_TONES = (
4755    67.0, 69.3, 71.9, 74.4, 77.0, 79.7, 82.5, 85.4, 88.5, 91.5,
4756    94.8, 97.4, 100.0, 103.5, 107.2, 110.9, 114.8, 118.8, 123.0, 127.3,
4757    131.8, 136.5, 141.3, 146.2, 151.4, 156.7, 159.8, 162.2, 165.5, 167.9,
4758    171.3, 173.8, 177.3, 179.9, 183.5, 186.2, 189.9, 192.8, 196.6, 199.5,
4759    203.5, 206.5, 210.7, 218.1, 225.7, 229.1, 233.6, 241.8, 250.3, 254.1,
4760)
4761"""The 50 standard CTCSS tones in Hz, offered for the VFO QT/DQT fields.
4762
4763The CPS list starts with 67.0 and ends its CTCSS part with 254.1, like
4764this one; the tones in between were not compared one by one.
4765"""
4766_VFO_TONE_LABELS = (['OFF'] + [f'{hz:.1f}' for hz in _CTCSS_TONES] + list(_DCS_CODES))
4767"""Rx/Tx QT/DQT choices as the CPS writes them: ``OFF``, the CTCSS tones
4768(e.g. ``88.5``), then the DCS codes of ``_DCS_CODES`` (``D023N`` ...
4769``D754I``)."""
4770
4771def _build_memory_extra(channel: ChannelRecord) -> RadioSettingGroup:
4772    """Build the per-channel *RT-950 Pro Extras* settings shown by CHIRP.
4773
4774    Args:
4775        channel: The channel record.
4776
4777    Returns:
4778        RadioSettingGroup: Scrambler code and encryption mode.
4779    """
4780    group = RadioSettingGroup('rt950_extra', 'RT-950 Pro Extras')
4781    scrambler_value = RadioSettingValueInteger(0, 8, channel.scrambler or 0)
4782    scrambler = RadioSetting('scrambler', 'Scrambler Code', scrambler_value)
4783    group.append(scrambler)
4784    encryption_raw = channel.encryption if channel.encryption is not None else 0
4785    encryption_value = RadioSettingValueInteger(0, 3, encryption_raw)
4786    encryption = RadioSetting('encryption', 'Encryption Mode', encryption_value)
4787    group.append(encryption)
4788    return group
4789
4790def _extract_memory_extra(mem) -> Dict[str, int]:
4791    """Collect the extra settings from a CHIRP memory.
4792
4793    Accepts both a plain dict and a CHIRP settings group in ``mem.extra``.
4794
4795    Args:
4796        mem: A CHIRP ``Memory``.
4797
4798    Returns:
4799        dict[str, int]: Setting name to value.
4800    """
4801    extras: Dict[str, int] = {}
4802    container = getattr(mem, 'extra', None)
4803    if isinstance(container, dict):
4804        for key in ('scrambler', 'encryption'):
4805            value = container.get(key)
4806            if value is not None:
4807                extras[key] = value
4808        return extras
4809    if container is None:
4810        return extras
4811    if hasattr(container, 'walk'):
4812        iterable = list(container.walk())
4813    else:
4814        try:
4815            iterable = list(container)
4816        except TypeError:
4817            iterable = []
4818    for setting in iterable:
4819        if not isinstance(setting, RadioSetting):
4820            continue
4821        value_obj = getattr(setting, 'value', None)
4822        if hasattr(value_obj, 'get_value'):
4823            raw = value_obj.get_value()
4824        else:
4825            raw = value_obj
4826        extras[setting.get_name()] = raw
4827    return extras
4828
4829def _format_frequency(hz: Optional[int]) -> str:
4830    """Format Hz for a text setting; ``None`` and 0 give ``""``.
4831
4832    Args:
4833        hz: Frequency in Hz, or ``None``.
4834
4835    Returns:
4836        str: The text from ``chirp_common.format_freq``, or ``""``.
4837    """
4838    if hz in (None, 0):
4839        return ""
4840    return chirp_common.format_freq(hz)
4841
4842def _parse_frequency(text: str) -> Optional[int]:
4843    """Parse a frequency text as CHIRP does.
4844
4845    Args:
4846        text: Frequency text, e.g. ``"145.500"``.
4847
4848    Returns:
4849        int | None: Frequency in Hz, or ``None`` for empty text.
4850
4851    Raises:
4852        ValueError: If the text is invalid or not positive.
4853    """
4854    value = text.strip()
4855    if not value:
4856        return None
4857    hz = chirp_common.parse_freq(value)
4858    if hz <= 0:
4859        raise ValueError("Frequency must be positive")
4860    return hz
4861
4862_MOD_WORK_MODE_CHOICES = [('VFO Mode', 0), ('CH Mode', 1)]
4863"""Work Mode labels of the CPS and the stored values (modulation byte 33).
4864VFO Mode = 0 confirmed on a radio; CH Mode = 1 follows the CPS list order."""
4865_MOD_MODULATION_CHOICES = [('FM', 0), ('AM', 1), ('LSB', 2), ('USB', 3), ('CW', 4)]
4866"""Modulation Mode labels of the CPS and the stored values (byte 67).
4867AM = 1 confirmed on a radio; the others follow the CPS list order."""
4868_MOD_AM_STEP_CHOICES = [('1K', 0), ('5K', 1), ('10K', 2), ('100K', 3)]
4869"""AM Step Freq labels of the CPS and the stored values (byte 151).
48701K = 0 confirmed on a radio; the others follow the CPS list order."""
4871_MOD_SSB_STEP_CHOICES = [('1K', 0), ('5K', 1), ('10K', 2), ('100K', 3), ('500K', 4),
4872                         ('1000K', 5)]
4873"""SSB Step Freq labels of the CPS and the stored values (byte 150).
48741K = 0 confirmed on a radio; the others follow the CPS list order."""
4875_MOD_RX_GAIN_CHOICES = ([('AGC', 0), ('0dB', 1)]
4876                        + [(f'-{n}dB', n + 1) for n in range(1, 36)])
4877"""AM/SSB Rx Gain labels of the CPS (AGC, 0dB, -1dB ... -35dB; 37 entries)
4878and the stored values 0-36 (bytes 68 and 152). AGC = 0 confirmed on a radio;
4879the others follow the CPS list order."""
4880
4881
4882def _make_integer_setting(
4883    name: str, label: str, current: Optional[int], minimum: int, maximum: int, callback, *args
4884) -> RadioSetting:
4885    """Create an integer ``RadioSetting`` with an apply callback.
4886
4887    Args:
4888        name: Internal setting name.
4889        label: Label shown in CHIRP.
4890        current: Current value; ``None`` shows ``minimum``.
4891        minimum: Lowest allowed value.
4892        maximum: Highest allowed value.
4893        callback: Called as ``callback(setting, *args)`` on apply.
4894        *args: Extra arguments for ``callback``.
4895
4896    Returns:
4897        RadioSetting: The configured setting.
4898    """
4899    active = minimum if current is None else int(current)
4900    setting = RadioSetting(name, label, RadioSettingValueInteger(minimum, maximum, active))
4901    setting.set_apply_callback(callback, *args)
4902    return setting
4903
4904
4905def _unknown_label(value) -> str:
4906    """Return the list label for a stored value the CPS does not offer.
4907
4908    Args:
4909        value: The stored value (e.g. ``3`` for an offset direction).
4910
4911    Returns:
4912        str: ``"Unknown (<value>)"``, e.g. ``"Unknown (3)"``.
4913    """
4914    return f'Unknown ({value})'
4915
4916
4917def _make_list_setting(name: str, label: str, choices, current, target, attr: str) -> RadioSetting:
4918    """Create a list setting for one field of a settings object.
4919
4920    Used for the VFO and modulation screens. The options are the labels of
4921    ``choices``. A current value that is not in ``choices`` gets an extra
4922    option, which is selected: ``Not set`` for ``None`` (byte 0xFF), else
4923    one made by :func:`_unknown_label`. Choosing it (or leaving it) keeps the
4924    stored value, see :func:`_apply_list_choice`.
4925
4926    Args:
4927        name: Internal setting name, e.g. ``"vfo.0.step"``.
4928        label: Label shown in CHIRP, as in the CPS (e.g. ``"Step Freq"``).
4929        choices: ``(label, value)`` pairs in CPS order.
4930        current: The field's current value.
4931        target: Object the callback updates (a :class:`VFOSettings` or
4932            :class:`ModulationSettings`).
4933        attr: Name of the field on ``target``.
4934
4935    Returns:
4936        RadioSetting: The setting, wired to :func:`_apply_list_choice`.
4937    """
4938    labels = [text for text, _ in choices]
4939    values = [value for _, value in choices]
4940    if current in values:
4941        index = values.index(current)
4942    else:
4943        labels.append('Not set' if current is None else _unknown_label(current))
4944        index = len(labels) - 1
4945    setting = RadioSetting(name, label, RadioSettingValueList(labels, current_index=index))
4946    setting.set_apply_callback(_apply_list_choice, target, attr, choices)
4947    return setting
4948
4949
4950def _make_vfo_tone(name: str, label: str, tone: ToneSetting, vfo, attr: str) -> RadioSetting:
4951    """Create a Rx or Tx QT/DQT list setting for one VFO.
4952
4953    The options are ``_VFO_TONE_LABELS``. A tone that is not in that list
4954    (a non-standard CTCSS value) gets an extra option made by
4955    :func:`_unknown_label` with the tone as the CPS writes it; it stays
4956    unchanged unless another tone is chosen (see :func:`_apply_vfo_tone`).
4957    An unknown DCS index is decoded as OFF and shown as OFF; its bytes are
4958    kept unless another tone is chosen.
4959
4960    Args:
4961        name: Internal setting name, e.g. ``"vfo.0.rx_tone"``.
4962        label: ``"Rx QT/DQT"`` or ``"Tx QT/DQT"``.
4963        tone: The current tone.
4964        vfo: VFO entry the callback updates.
4965        attr: ``"rx_tone"`` or ``"tx_tone"``.
4966
4967    Returns:
4968        RadioSetting: The setting, wired to :func:`_apply_vfo_tone`.
4969    """
4970    labels = list(_VFO_TONE_LABELS)
4971    shown = tone.to_display()
4972    if shown in labels:
4973        index = labels.index(shown)
4974    else:
4975        labels.append(_unknown_label(shown))
4976        index = len(labels) - 1
4977    setting = RadioSetting(name, label, RadioSettingValueList(labels, current_index=index))
4978    setting.set_apply_callback(_apply_vfo_tone, vfo, attr)
4979    return setting
4980
4981
4982def _make_vfo_frequency(name: str, label: str, hz: Optional[int], callback, vfo) -> RadioSetting:
4983    """Create a frequency text setting (MHz) for one VFO.
4984
4985    Args:
4986        name: Internal setting name, e.g. ``"vfo.0.freq"``.
4987        label: ``"Rx Freq"`` or ``"Offset Freq"``.
4988        hz: Current frequency in Hz, or ``None`` (shown empty).
4989        callback: :func:`_apply_vfo_frequency` or :func:`_apply_vfo_offset`.
4990        vfo: VFO entry the callback updates.
4991
4992    Returns:
4993        RadioSetting: The setting, wired to ``callback``.
4994    """
4995    value = RadioSettingValueString(0, 12, _format_frequency(hz) or '', autopad=False)
4996    setting = RadioSetting(name, label, value)
4997    setting.set_apply_callback(callback, vfo)
4998    return setting
4999
5000
5001def _build_vfo_group(vfos: Optional[List[VFOSettings]]) -> RadioSettingGroup:
5002    """Build the *VFO Profiles* settings group (one subgroup per VFO).
5003
5004    Each subgroup (``VFO-A`` to ``VFO-C``) shows the fields of the CPS
5005    *VFO Mode* screen, with its labels, choices and order: Rx Freq,
5006    Rx QT/DQT, Tx QT/DQT, Busy Lockout, Offset Dir, Signalling, Tx Power,
5007    Scramble, Bandwidth, Encryption, RxModulation, Freq Band (read-only, no
5008    callback), Step Freq and Offset Freq. Learn FHSS and the offset
5009    direction "split" are not shown, as in the CPS; their stored bits are
5010    kept. A stored value outside a list is shown as ``Unknown (<value>)``
5011    and left unchanged on apply. Exceptions: a power nibble above 2 is shown
5012    as Low and an unknown DCS index as OFF; both are kept unless that field
5013    is edited, and OFF cannot be chosen to clear such a DCS index.
5014
5015    Args:
5016        vfos: VFO entries, or ``None``.
5017
5018    Returns:
5019        RadioSettingGroup: One subgroup per VFO; empty if ``vfos`` is empty
5020        or ``None``.
5021    """
5022    group = RadioSettingGroup('vfo', 'VFO Profiles')
5023    if not vfos:
5024        return group
5025    for idx, vfo in enumerate(vfos):
5026        letter = _VFO_LABELS[idx] if idx < len(_VFO_LABELS) else str(idx)
5027        sub = RadioSettingGroup(f'vfo.{idx}', f'VFO-{letter}')
5028        key = f'vfo.{idx}'
5029        sub.append(_make_vfo_frequency(f'{key}.freq', 'Rx Freq', vfo.rx_hz,
5030                                       _apply_vfo_frequency, vfo))
5031        sub.append(_make_vfo_tone(f'{key}.rx_tone', 'Rx QT/DQT', vfo.rx_tone, vfo, 'rx_tone'))
5032        sub.append(_make_vfo_tone(f'{key}.tx_tone', 'Tx QT/DQT', vfo.tx_tone, vfo, 'tx_tone'))
5033        sub.append(_make_list_setting(f'{key}.busy_lockout', 'Busy Lockout',
5034                                  _VFO_BUSY_LOCKOUT_CHOICES, vfo.busy_lockout, vfo,
5035                                  'busy_lockout'))
5036        sub.append(_make_list_setting(f'{key}.offset_direction', 'Offset Dir',
5037                                  _VFO_OFFSET_CHOICES, vfo.offset_direction, vfo,
5038                                  'offset_direction'))
5039        sub.append(_make_list_setting(f'{key}.signalling_group', 'Signalling',
5040                                  _VFO_SIGNALLING_CHOICES, vfo.signalling_group, vfo,
5041                                  'signalling_group'))
5042        sub.append(_make_list_setting(f'{key}.power', 'Tx Power', _VFO_POWER_CHOICES,
5043                                  vfo.tx_power, vfo, 'tx_power'))
5044        sub.append(_make_list_setting(f'{key}.scrambler', 'Scramble', _VFO_SCRAMBLE_CHOICES,
5045                                  vfo.scrambler, vfo, 'scrambler'))
5046        sub.append(_make_list_setting(f'{key}.bandwidth', 'Bandwidth', _VFO_BANDWIDTH_CHOICES,
5047                                  vfo.bandwidth, vfo, 'bandwidth'))
5048        sub.append(_make_list_setting(f'{key}.encryption', 'Encryption', _VFO_ENCRYPTION_CHOICES,
5049                                  vfo.encryption, vfo, 'encryption'))
5050        sub.append(_make_list_setting(f'{key}.modulation', 'RxModulation',
5051                                  _VFO_MODULATION_CHOICES, vfo.rx_modulation, vfo,
5052                                  'rx_modulation'))
5053        band_labels = [text for text, _ in _VFO_BAND_CHOICES]
5054        band_values = [value for _, value in _VFO_BAND_CHOICES]
5055        if vfo.freq_band in band_values:
5056            band_index = band_values.index(vfo.freq_band)
5057        else:
5058            band_labels.append(_unknown_label(vfo.freq_band))
5059            band_index = len(band_labels) - 1
5060        band_value = RadioSettingValueList(band_labels, current_index=band_index)
5061        band_value.set_mutable(False)
5062        sub.append(RadioSetting(f'{key}.freq_band', 'Freq Band', band_value))
5063        sub.append(_make_list_setting(f'{key}.step', 'Step Freq', _VFO_STEP_CHOICES,
5064                                  vfo.step_freq_index, vfo, 'step_freq_index'))
5065        sub.append(_make_vfo_frequency(f'{key}.offset', 'Offset Freq', vfo.offset_hz,
5066                                       _apply_vfo_offset, vfo))
5067        group.append(sub)
5068    return group
5069
5070def _build_modulation_group(modulation: ModulationSettings) -> RadioSettingGroup:
5071    """Build the *Broadcast/Modulation* settings group.
5072
5073    The global settings follow the CPS screen *FM/AM/SSB Modulation*: Work
5074    Mode, Modulation Mode, AM/SSB Step Freq and AM/SSB Rx Gain are lists with
5075    the CPS labels (``_MOD_*_CHOICES``); a field that is not set (0xFF) shows
5076    ``Not set`` and is left unchanged unless a value is chosen. The current
5077    FM/AM/SSB channel is a number 0-14, the range the decoder returns (the
5078    CPS does not show it).
5079
5080    Args:
5081        modulation: Modulation settings.
5082
5083    Returns:
5084        RadioSettingGroup: Global parameters, plus FM, AM and SSB memory
5085        subgroups when ``modulation.channels`` is not empty.
5086    """
5087    group = RadioSettingGroup('modulation', 'Broadcast/Modulation')
5088    global_group = RadioSettingGroup('modulation.global', 'Global Settings')
5089    for key, label in (('fm_current_channel', 'FM Current Channel'),
5090                       ('am_current_channel', 'AM Current Channel'),
5091                       ('ssb_current_channel', 'SSB Current Channel')):
5092        global_group.append(
5093            _make_integer_setting(
5094                f'modulation.{key}', label, getattr(modulation, key), 0, 14,
5095                _apply_modulation_int, modulation, key,
5096            )
5097        )
5098    for key, label, choices, attr in (
5099            ('work_mode', 'Work Mode', _MOD_WORK_MODE_CHOICES, 'work_mode'),
5100            ('modulation_mode', 'Modulation Mode', _MOD_MODULATION_CHOICES,
5101             'modulation_mode'),
5102            ('am_step', 'AM Step Freq', _MOD_AM_STEP_CHOICES, 'am_step_index'),
5103            ('am_rx_gain', 'AM Rx Gain', _MOD_RX_GAIN_CHOICES, 'am_rx_gain'),
5104            ('ssb_step', 'SSB Step Freq', _MOD_SSB_STEP_CHOICES, 'ssb_step_index'),
5105            ('ssb_rx_gain', 'SSB Rx Gain', _MOD_RX_GAIN_CHOICES, 'ssb_rx_gain')):
5106        global_group.append(
5107            _make_list_setting(f'modulation.{key}', label, choices,
5108                               getattr(modulation, attr), modulation, attr))
5109    group.append(global_group)
5110
5111    if modulation.channels:
5112        group.append(
5113            _build_modulation_channel_group(
5114                'modulation.fm_channels', 'FM Broadcast Channels', modulation, 'fm'
5115            )
5116        )
5117        group.append(
5118            _build_modulation_channel_group(
5119                'modulation.am_channels', 'AM Broadcast Channels', modulation, 'am'
5120            )
5121        )
5122        group.append(
5123            _build_modulation_channel_group(
5124                'modulation.ssb_channels', 'SSB Channels', modulation, 'ssb'
5125            )
5126        )
5127    return group
5128
5129
5130def _build_modulation_channel_group(
5131    name_prefix: str, label: str, modulation: ModulationSettings, mode: str
5132) -> RadioSettingGroup:
5133    """Build the settings subgroup for the FM, AM or SSB memories.
5134
5135    Args:
5136        name_prefix: Prefix for the internal setting names.
5137        label: Label shown in CHIRP.
5138        modulation: Modulation settings.
5139        mode: ``"fm"``, ``"am"`` or ``"ssb"``.
5140
5141    Returns:
5142        RadioSettingGroup: One subgroup per memory entry.
5143    """
5144    subgroup = RadioSettingGroup(name_prefix, label)
5145    for idx, channel in enumerate(modulation.channels):
5146        channel_group = RadioSettingGroup(f'{name_prefix}.{idx}', f'Channel {idx + 1}')
5147        if mode == 'fm':
5148            freq_setting = RadioSetting(
5149                f'{name_prefix}.{idx}.freq',
5150                'Frequency',
5151                RadioSettingValueString(
5152                    0, 12, _format_frequency(channel.fm_frequency) or '', autopad=False
5153                ),
5154            )
5155            freq_setting.set_apply_callback(
5156                _apply_modulation_channel_frequency, modulation, idx, 'fm_frequency'
5157            )
5158            channel_group.append(freq_setting)
5159            name_setting = RadioSetting(
5160                f'{name_prefix}.{idx}.name',
5161                'Name',
5162                RadioSettingValueString(0, 16, channel.fm_name or '', autopad=False),
5163            )
5164            name_setting.set_apply_callback(
5165                _apply_modulation_channel_name, modulation, idx, 'fm_name'
5166            )
5167            channel_group.append(name_setting)
5168        elif mode == 'am':
5169            freq_setting = RadioSetting(
5170                f'{name_prefix}.{idx}.freq',
5171                'Frequency',
5172                RadioSettingValueString(
5173                    0, 12, _format_frequency(channel.am_frequency) or '', autopad=False
5174                ),
5175            )
5176            freq_setting.set_apply_callback(
5177                _apply_modulation_channel_frequency, modulation, idx, 'am_frequency'
5178            )
5179            channel_group.append(freq_setting)
5180            name_setting = RadioSetting(
5181                f'{name_prefix}.{idx}.name',
5182                'Name',
5183                RadioSettingValueString(0, 16, channel.am_name or '', autopad=False),
5184            )
5185            name_setting.set_apply_callback(
5186                _apply_modulation_channel_name, modulation, idx, 'am_name'
5187            )
5188            channel_group.append(name_setting)
5189        elif mode == 'ssb':
5190            freq_setting = RadioSetting(
5191                f'{name_prefix}.{idx}.freq',
5192                'Frequency',
5193                RadioSettingValueString(
5194                    0, 12, _format_frequency(channel.ssb_frequency) or '', autopad=False
5195                ),
5196            )
5197            freq_setting.set_apply_callback(
5198                _apply_modulation_channel_frequency, modulation, idx, 'ssb_frequency'
5199            )
5200            channel_group.append(freq_setting)
5201            bandwidth_setting = _make_integer_setting(
5202                f'{name_prefix}.{idx}.bandwidth',
5203                'Bandwidth',
5204                channel.ssb_bandwidth,
5205                0,
5206                255,
5207                _apply_modulation_channel_int,
5208                modulation,
5209                idx,
5210                'ssb_bandwidth'
5211            )
5212            channel_group.append(bandwidth_setting)
5213            beat_setting = RadioSetting(
5214                f'{name_prefix}.{idx}.beat',
5215                'Beat Offset',
5216                RadioSettingValueInteger(-32768, 32767, int(channel.ssb_beat_offset or 0)),
5217            )
5218            beat_setting.set_apply_callback(_apply_modulation_channel_beat, modulation, idx)
5219            channel_group.append(beat_setting)
5220            name_setting = RadioSetting(
5221                f'{name_prefix}.{idx}.name',
5222                'Name',
5223                RadioSettingValueString(0, 16, channel.ssb_name or '', autopad=False),
5224            )
5225            name_setting.set_apply_callback(
5226                _apply_modulation_channel_name, modulation, idx, 'ssb_name'
5227            )
5228            channel_group.append(name_setting)
5229        subgroup.append(channel_group)
5230    return subgroup
5231
5232
5233def _apply_modulation_int(rsetting, modulation, attr):
5234    """Settings callback: store a non-negative integer in ``modulation.attr``.
5235
5236    Args:
5237        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5238        modulation: Modulation settings to update.
5239        attr: Attribute name on ``modulation``, e.g. ``"fm_current_channel"``.
5240    """
5241    setattr(modulation, attr, max(0, _value_as_int(rsetting.value)))
5242
5243def _apply_modulation_channel_frequency(rsetting, modulation, index, attr):
5244    """Settings callback: store a parsed frequency (or ``None``) in an entry.
5245
5246    Empty text stores ``None``; otherwise the text is parsed to Hz.
5247
5248    Args:
5249        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5250        modulation: Modulation settings to update.
5251        index: Index into ``modulation.channels`` (0-15).
5252        attr: ``"fm_frequency"``, ``"am_frequency"`` or ``"ssb_frequency"``.
5253
5254    Raises:
5255        ValueError: If the text is not a valid positive frequency.
5256    """
5257    try:
5258        value = _value_as_string(rsetting.value).strip()
5259    except AttributeError:
5260        value = str(rsetting.value).strip()
5261    freq = _parse_frequency(value) if value else None
5262    setattr(modulation.channels[index], attr, freq)
5263
5264def _apply_modulation_channel_name(rsetting, modulation, index, attr):
5265    """Settings callback: store a memory name in an entry.
5266
5267    Args:
5268        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5269        modulation: Modulation settings to update.
5270        index: Index into ``modulation.channels`` (0-15).
5271        attr: ``"fm_name"``, ``"am_name"`` or ``"ssb_name"``.
5272    """
5273    name = _value_as_string(rsetting.value)
5274    setattr(modulation.channels[index], attr, name)
5275
5276def _apply_modulation_channel_int(rsetting, modulation, index, attr):
5277    """Settings callback: store a non-negative integer in an entry.
5278
5279    Args:
5280        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5281        modulation: Modulation settings to update.
5282        index: Index into ``modulation.channels`` (0-15).
5283        attr: Attribute name on the entry (``"ssb_bandwidth"`` at the call site).
5284    """
5285    value = max(0, _value_as_int(rsetting.value))
5286    setattr(modulation.channels[index], attr, value)
5287
5288def _apply_modulation_channel_beat(rsetting, modulation, index):
5289    """Settings callback: store the SSB beat offset, clamped to int16.
5290
5291    Args:
5292        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5293        modulation: Modulation settings to update.
5294        index: Index into ``modulation.channels`` (0-15).
5295    """
5296    value = _value_as_int(rsetting.value)
5297    if value < -32768:
5298        value = -32768
5299    elif value > 32767:
5300        value = 32767
5301    modulation.channels[index].ssb_beat_offset = value
5302
5303def _apply_vfo_frequency(rsetting, vfo):
5304    """Settings callback: set the VFO receive frequency.
5305
5306    An empty field sets ``rx_hz`` to ``None``; :func:`encode_vfo_section`
5307    then keeps the stored digits. A changed frequency also sets
5308    ``freq_band`` as the CPS does: 1 (UHF) from ``_VFO_UHF_FROM_HZ`` (300
5309    MHz) up, else 0 (VHF).
5310
5311    Args:
5312        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5313        vfo: VFO entry to update (``rx_hz``, in Hz).
5314
5315    Returns:
5316        None: Nothing; ``vfo`` is updated in place.
5317
5318    Raises:
5319        RadioError: If the text is not a valid frequency.
5320    """
5321    try:
5322        value = _value_as_string(rsetting.value).strip()
5323    except AttributeError:
5324        value = str(rsetting.value).strip()
5325    if not value:
5326        vfo.rx_hz = None
5327        return
5328    try:
5329        rx_hz = _parse_frequency(value)
5330    except ValueError as exc:
5331        raise errors.RadioError(str(exc)) from exc
5332    if rx_hz != vfo.rx_hz:
5333        vfo.rx_hz = rx_hz
5334        vfo.freq_band = 1 if rx_hz >= _VFO_UHF_FROM_HZ else 0
5335
5336def _apply_vfo_offset(rsetting, vfo):
5337    """Settings callback: set the VFO offset.
5338
5339    An empty field sets ``offset_hz`` to ``None``; :func:`encode_vfo_section`
5340    then keeps the stored digits.
5341
5342    Args:
5343        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5344        vfo: VFO entry to update (``offset_hz``, in Hz).
5345
5346    Returns:
5347        None: Nothing; ``vfo`` is updated in place.
5348
5349    Raises:
5350        RadioError: If the text is not a valid frequency.
5351    """
5352    try:
5353        value = _value_as_string(rsetting.value).strip()
5354    except AttributeError:
5355        value = str(rsetting.value).strip()
5356    if not value:
5357        vfo.offset_hz = None
5358        return
5359    try:
5360        vfo.offset_hz = _parse_frequency(value)
5361    except ValueError as exc:
5362        raise errors.RadioError(str(exc)) from exc
5363
5364def _apply_list_choice(rsetting, target, attr, choices):
5365    """Settings callback: set one field from a list choice.
5366
5367    Looks the chosen label up in ``choices`` and stores its value in
5368    ``target.<attr>``. A label that is not in ``choices`` (the ``Not set`` or
5369    ``Unknown (<value>)`` option of :func:`_make_list_setting`) leaves the
5370    field unchanged, so a stored value the CPS does not offer survives a
5371    settings apply.
5372
5373    Args:
5374        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5375        target: Object to update (a :class:`VFOSettings` or
5376            :class:`ModulationSettings`).
5377        attr: Name of the field on ``target``.
5378        choices: ``(label, value)`` pairs the setting was built from.
5379
5380    Returns:
5381        None: Nothing; ``target`` is updated in place.
5382    """
5383    chosen = str(rsetting.value)
5384    for text, value in choices:
5385        if text == chosen:
5386            setattr(target, attr, value)
5387            return
5388
5389
5390def _apply_vfo_tone(rsetting, vfo, attr):
5391    """Settings callback: set the VFO receive or transmit tone.
5392
5393    The tone is only replaced when the chosen label differs from the current
5394    tone as the CPS writes it (:meth:`ToneSetting.to_display`), so an
5395    unchanged tone keeps its original bytes. ``OFF`` clears the tone, a
5396    label starting with ``D`` (``D023N``) sets that DCS code and polarity,
5397    any other label of ``_VFO_TONE_LABELS`` sets that CTCSS tone in Hz. An
5398    ``Unknown (...)`` label leaves the tone unchanged.
5399
5400    Args:
5401        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5402        vfo: VFO entry to update.
5403        attr: ``"rx_tone"`` or ``"tx_tone"``.
5404
5405    Returns:
5406        None: Nothing; ``vfo`` is updated in place.
5407    """
5408    chosen = str(rsetting.value)
5409    current = getattr(vfo, attr)
5410    if chosen == current.to_display() or chosen not in _VFO_TONE_LABELS:
5411        return
5412    if chosen == 'OFF':
5413        tone = ToneSetting.off()
5414    elif chosen.startswith('D'):
5415        tone = ToneSetting.dcs(int(chosen[1:4]), chosen[4])
5416    else:
5417        tone = ToneSetting.ctcss(float(chosen))
5418    setattr(vfo, attr, tone)
5419
5420def _build_setting_value(meta, current):
5421    """Create the CHIRP value object described by a UI table entry.
5422
5423    Args:
5424        meta: Entry from ``_FUNCTION_UI`` or ``_APRS_UI`` with ``type`` and
5425            its parameters (``min``/``max``, ``choices`` or ``length``).
5426        current: Current value, or ``None``.
5427
5428    Returns:
5429        RadioSettingValue: Boolean, integer, list or string value.
5430
5431    Raises:
5432        SettingsError: If ``meta['type']`` is unknown.
5433    """
5434    kind = meta['type']
5435    if kind == 'bool':
5436        return RadioSettingValueBoolean(bool(current))
5437    if kind == 'int':
5438        minimum = meta.get('min', 0)
5439        maximum = meta.get('max', minimum)
5440        active = minimum if current is None else int(current)
5441        return RadioSettingValueInteger(minimum, maximum, active)
5442    if kind == 'enum':
5443        choices = meta['choices']
5444        labels = [label for label, _ in choices]
5445        values = [value for _, value in choices]
5446        active = values[0]
5447        if current in values:
5448            active = current
5449        index = values.index(active)
5450        return RadioSettingValueList(labels, current_index=index)
5451    if kind == 'string':
5452        length = meta['length']
5453        return RadioSettingValueString(0, length, (current or ''), autopad=False)
5454    raise SettingsError(f"Unsupported setting type: {kind}")
5455
5456def _value_as_bool(value_obj):
5457    """Read a CHIRP value object (or plain value) as ``bool``.
5458
5459    Args:
5460        value_obj: A ``RadioSettingValue*`` object (``get_value`` is used) or a plain value.
5461
5462    Returns:
5463        bool: Truth value of the underlying value.
5464    """
5465    if hasattr(value_obj, 'get_value'):
5466        return bool(value_obj.get_value())
5467    return bool(value_obj)
5468
5469def _value_as_int(value_obj, default=0):
5470    """Read a CHIRP value object (or plain value) as ``int``.
5471
5472    Returns ``default`` if the value cannot be converted.
5473
5474    Args:
5475        value_obj: A ``RadioSettingValue*`` object (``get_value`` is used) or a plain value.
5476        default: Value returned when the conversion raises.
5477
5478    Returns:
5479        int: ``int()`` of the underlying value, or ``default``.
5480    """
5481    try:
5482        if hasattr(value_obj, 'get_value'):
5483            raw = value_obj.get_value()
5484        else:
5485            raw = value_obj
5486        return int(raw)
5487    # Any unreadable value falls back to the default.
5488    except Exception:  # pylint: disable=broad-exception-caught
5489        return default
5490
5491def _value_as_index(value_obj, choices):
5492    """Read a list value as an index into ``choices``.
5493
5494    Tries ``int(value)`` first, then looks the label up in ``choices``.
5495    Falls back to 0.
5496
5497    Args:
5498        value_obj: A list ``RadioSettingValue`` object or a plain value.
5499        choices: Sequence of ``(label, value)`` pairs.
5500
5501    Returns:
5502        int: ``int(value_obj)`` if that works (not range-checked), else the
5503        position of the label in ``choices``, else 0.
5504    """
5505    try:
5506        return int(value_obj)
5507    # Not an index: fall back to matching the label text below.
5508    except Exception:  # pylint: disable=broad-exception-caught
5509        if hasattr(value_obj, 'get_value'):
5510            raw = value_obj.get_value()
5511        else:
5512            raw = value_obj
5513        labels = [label for label, _ in choices]
5514        try:
5515            return labels.index(raw)
5516        except ValueError:
5517            return 0
5518
5519def _value_as_string(value_obj):
5520    """Read a CHIRP value object (or plain value) as ``str``.
5521
5522    Args:
5523        value_obj: A ``RadioSettingValue*`` object (``get_value`` is used) or a plain value.
5524
5525    Returns:
5526        str: ``str()`` of the underlying value.
5527    """
5528    if hasattr(value_obj, 'get_value'):
5529        raw = value_obj.get_value()
5530    else:
5531        raw = value_obj
5532    return str(raw)
5533
5534def _create_function_setting(func_settings, key, meta):
5535    """Create one function ``RadioSetting`` from its UI table entry.
5536
5537    Args:
5538        func_settings: Function settings that hold the current value and are
5539            updated on apply.
5540        key: Setting name, a key of ``_FUNCTION_UI``.
5541        meta: The ``_FUNCTION_UI`` entry for ``key`` (label, type, parameters;
5542            ``'volatile': True`` marks the setting volatile).
5543
5544    Returns:
5545        RadioSetting | None: The setting, or ``None`` for an unknown key.
5546    """
5547    try:
5548        current = get_function_value(func_settings, key)
5549    except KeyError:
5550        LOG.debug('Skipping unknown function key %s', key)
5551        return None
5552    value_obj = _build_setting_value(meta, current)
5553    rsetting = RadioSetting(f'function.{key}', meta['label'], value_obj)
5554    rsetting.set_apply_callback(_apply_function_setting, func_settings, key, meta)
5555    # A volatile setting makes CHIRP's settings editor ask for a refresh
5556    # after it is changed; together with has_dynamic_subdevices CHIRP then
5557    # rebuilds the whole editor (memory tabs included) from the image.
5558    # The stand-in RadioSetting and old CHIRP versions lack set_volatile.
5559    set_volatile = getattr(rsetting, 'set_volatile', None)
5560    if meta.get('volatile') and set_volatile is not None:
5561        set_volatile(True)
5562    return rsetting
5563
5564def _create_aprs_setting(aprs_settings, key, meta):
5565    """Create one APRS ``RadioSetting`` from its UI table entry.
5566
5567    Args:
5568        aprs_settings: APRS settings that hold the current value and are
5569            updated on apply.
5570        key: Setting name, a key of ``_APRS_UI``.
5571        meta: The ``_APRS_UI`` entry for ``key`` (label, type, parameters).
5572
5573    Returns:
5574        RadioSetting | None: The setting, or ``None`` for an unknown key.
5575    """
5576    try:
5577        current = get_aprs_value(aprs_settings, key)
5578    except KeyError:
5579        LOG.debug('Skipping unknown APRS key %s', key)
5580        return None
5581    value_obj = _build_setting_value(meta, current)
5582    rsetting = RadioSetting(f'aprs.{key}', meta['label'], value_obj)
5583    rsetting.set_apply_callback(_apply_aprs_setting, aprs_settings, key, meta)
5584    return rsetting
5585
5586def _build_function_group(func_settings):
5587    """Build the *Function Settings* group from ``_FUNCTION_UI``.
5588
5589    Args:
5590        func_settings: Function settings of the image.
5591
5592    Returns:
5593        RadioSettingGroup: One setting per known key of ``_FUNCTION_UI``.
5594    """
5595    group = RadioSettingGroup('function', 'Function Settings')
5596    for key, meta in _FUNCTION_UI.items():
5597        setting = _create_function_setting(func_settings, key, meta)
5598        if setting is not None:
5599            group.append(setting)
5600    return group
5601
5602def _build_aprs_group(aprs_settings):
5603    """Build the *APRS Settings* group from ``_APRS_UI``.
5604
5605    Args:
5606        aprs_settings: APRS settings of the image.
5607
5608    Returns:
5609        RadioSettingGroup: One setting per known key of ``_APRS_UI``.
5610    """
5611    group = RadioSettingGroup('aprs', 'APRS Settings')
5612    for key, meta in _APRS_UI.items():
5613        setting = _create_aprs_setting(aprs_settings, key, meta)
5614        if setting is not None:
5615            group.append(setting)
5616    return group
5617
5618def _build_dtmf_group(dtmf_settings):
5619    """Build the *DTMF Settings* group.
5620
5621    Shows the own ID, the PTT ID mode and the first ``_DTMF_GROUP_LIMIT``
5622    code groups.
5623
5624    Args:
5625        dtmf_settings: DTMF settings of the image.
5626
5627    Returns:
5628        RadioSettingGroup: The ID, mode and code-group settings.
5629    """
5630    group = RadioSettingGroup('dtmf', 'DTMF Settings')
5631    current_id = get_dtmf_current_id(dtmf_settings)
5632    value_id = RadioSettingValueString(0, _DTMF_ID_MAXLEN, current_id or '', autopad=False)
5633    rset_id = RadioSetting('dtmf.current_id', 'Current ID', value_id)
5634    rset_id.set_apply_callback(_apply_dtmf_id, dtmf_settings)
5635    group.append(rset_id)
5636    mode = get_dtmf_ptt_mode(dtmf_settings)
5637    labels = [label for label, _ in _DTMF_MODE_CHOICES]
5638    values = [value for _, value in _DTMF_MODE_CHOICES]
5639    index = values.index(mode) if mode in values else 0
5640    mode_value = RadioSettingValueList(labels, current_index=index)
5641    rset_mode = RadioSetting('dtmf.ptt_mode', 'PTT ID Mode', mode_value)
5642    rset_mode.set_apply_callback(_apply_dtmf_mode, dtmf_settings)
5643    group.append(rset_mode)
5644    for idx in range(_DTMF_GROUP_LIMIT):
5645        try:
5646            code = get_dtmf_code_group(dtmf_settings, idx)
5647        except IndexError:
5648            code = ''
5649        code_value = RadioSettingValueString(0, _DTMF_CODE_MAXLEN, code or '', autopad=False)
5650        rset_code = RadioSetting(f'dtmf.code_group_{idx + 1}', f'Code Group {idx + 1}', code_value)
5651        rset_code.set_apply_callback(_apply_dtmf_group, dtmf_settings, idx)
5652        group.append(rset_code)
5653    return group
5654
5655def _apply_function_setting(rsetting, func_settings, key, meta):
5656    """Settings callback: validate and store a function setting.
5657
5658    Args:
5659        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5660        func_settings: Function settings to update.
5661        key: Setting name, a key of ``_FUNCTION_UI``.
5662        meta: The ``_FUNCTION_UI`` entry for ``key``; ``type`` selects the conversion.
5663
5664    Raises:
5665        RadioError: If the value is not allowed.
5666    """
5667    try:
5668        kind = meta['type']
5669        if kind == 'bool':
5670            set_function_value(func_settings, key, _value_as_bool(rsetting.value))
5671        elif kind == 'int':
5672            set_function_value(func_settings, key, _value_as_int(rsetting.value))
5673        elif kind == 'enum':
5674            index = _value_as_index(rsetting.value, meta['choices'])
5675            set_function_value(func_settings, key, meta['choices'][index][1])
5676        else:
5677            raise SettingsError(f"Unsupported function setting type {kind}")
5678    except (SettingsError, KeyError, IndexError, ValueError) as exc:
5679        raise errors.RadioError(str(exc)) from exc
5680
5681def _apply_aprs_setting(rsetting, aprs_settings, key, meta):
5682    """Settings callback: validate and store an APRS setting.
5683
5684    Args:
5685        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5686        aprs_settings: APRS settings to update.
5687        key: Setting name, a key of ``_APRS_UI``.
5688        meta: The ``_APRS_UI`` entry for ``key``; ``type`` selects the conversion.
5689
5690    Raises:
5691        RadioError: If the value is not allowed.
5692    """
5693    try:
5694        kind = meta['type']
5695        if kind == 'bool':
5696            set_aprs_value(aprs_settings, key, _value_as_bool(rsetting.value))
5697        elif kind == 'int':
5698            set_aprs_value(aprs_settings, key, _value_as_int(rsetting.value))
5699        elif kind == 'enum':
5700            index = _value_as_index(rsetting.value, meta['choices'])
5701            set_aprs_value(aprs_settings, key, meta['choices'][index][1])
5702        elif kind == 'string':
5703            set_aprs_value(aprs_settings, key, _value_as_string(rsetting.value).strip())
5704        else:
5705            raise SettingsError(f"Unsupported APRS setting type {kind}")
5706    except (SettingsError, KeyError, IndexError, ValueError) as exc:
5707        raise errors.RadioError(str(exc)) from exc
5708
5709def _apply_dtmf_id(rsetting, dtmf_settings):
5710    """Settings callback: store the own DTMF ID.
5711
5712    Args:
5713        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5714        dtmf_settings: DTMF settings to update.
5715
5716    Raises:
5717        RadioError: If the ID is invalid.
5718    """
5719    try:
5720        set_dtmf_current_id(dtmf_settings, _value_as_string(rsetting.value).strip())
5721    except SettingsError as exc:
5722        raise errors.RadioError(str(exc)) from exc
5723
5724def _apply_dtmf_mode(rsetting, dtmf_settings):
5725    """Settings callback: store the PTT ID mode.
5726
5727    Args:
5728        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5729        dtmf_settings: DTMF settings to update.
5730
5731    Raises:
5732        RadioError: If the mode is invalid.
5733    """
5734    try:
5735        index = _value_as_index(rsetting.value, _DTMF_MODE_CHOICES)
5736        set_dtmf_ptt_mode(dtmf_settings, _DTMF_MODE_CHOICES[index][1])
5737    except SettingsError as exc:
5738        raise errors.RadioError(str(exc)) from exc
5739
5740def _apply_dtmf_group(rsetting, dtmf_settings, index):
5741    """Settings callback: store one DTMF code group.
5742
5743    Args:
5744        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5745        dtmf_settings: DTMF settings to update.
5746        index: Code group number, 0-based (0 to ``_DTMF_GROUP_LIMIT - 1``).
5747
5748    Raises:
5749        RadioError: If the code is invalid.
5750    """
5751    try:
5752        set_dtmf_code_group(dtmf_settings, index, _value_as_string(rsetting.value).strip())
5753    except (SettingsError, IndexError) as exc:
5754        raise errors.RadioError(str(exc)) from exc
5755
5756_WRITE_PLAN: Tuple[Tuple[int, Optional[int]], ...] = (
5757    (0, 0x7C00),   # channels
5758    (1, None),     # VFO
5759    (2, 0x80),     # function: 0x9000-0x907F only (0x9080-0x90FF unknown)
5760    (3, None),     # DTMF
5761    (4, None),     # modulation params
5762    (5, None),     # modulation names
5763    (7, None),     # zone names 0xC000
5764    (6, None),     # APRS (read 0x54 / write 0x58) last
5765)
5766"""Order and extent used when *writing* to the radio.
5767
5768Each entry is ``(index into DEFAULT_SEGMENTS, length or None)``; ``None``
5769means the full segment length. The image layout and the read order stay
5770``DEFAULT_SEGMENTS``; only the write differs:
5771
5772* channels: at most 0x0000-0x7BFF (990 channels rounded up to a 0x80
5773  block) instead of up to 0x7FFF; ``RT950ProRadio._write_options`` may
5774  limit this further to 0x77FF;
5775* function settings: only the first block, 0x9000-0x907F (the driver uses
5776  0x9000-0x905F). The second block, 0x9080-0x90FF, changed on a radio after
5777  a CPS write while its meaning is unknown, so the driver leaves it to the
5778  radio instead of writing back what it read;
5779* zone names (0xC000) are written with the other 0x57 blocks, before the
5780  APRS segment, which is always last.
5781"""
5782
5783
5784_LAYOUT_VERSION = 4
5785"""Layout version stored in ``.img`` metadata (``rt950_layout``).
5786
5787Images without it, or with a lower value, predate the zone names at
57880xC000; their zone-name bytes are not trusted and not written back.
5789"""
5790
5791
5792def _build_write_plan(
5793    payload: bytes,
5794    *,
5795    write_zone_names: bool = True,
5796    channel_bytes: int = 0x7C00,
5797    write_aprs: bool = True,
5798) -> Tuple[List["CloneSegment"], bytes]:
5799    """Split the layout-ordered payload into the segments/data to write.
5800
5801    ``write_zone_names=False`` skips 0xC000 (the image's zone names were not
5802    read from there). ``channel_bytes`` caps the channel write;
5803    :meth:`RT950ProRadio._write_options` passes 0x7800 (channels 1-960)
5804    unless channels 961-990 changed.
5805
5806    Args:
5807        payload: Complete clone payload in ``DEFAULT_SEGMENTS`` order (as built
5808            by :func:`_build_clone_payload`).
5809        write_zone_names: Include the zone-name segment (0xC000).
5810        channel_bytes: Maximum number of channel-segment bytes to write from
5811            address 0x0000; the ``_WRITE_PLAN`` limit of 0x7C00 still applies.
5812        write_aprs: Include the APRS segment (write command 0x58).
5813
5814    Returns:
5815        tuple[list[CloneSegment], bytes]: The segments to write, in
5816        ``_WRITE_PLAN`` order, and their data concatenated in the same order.
5817    """
5818    offsets = []
5819    cursor = 0
5820    for seg in DEFAULT_SEGMENTS:
5821        offsets.append(cursor)
5822        cursor += seg.length
5823    segments: List[CloneSegment] = []
5824    data = bytearray()
5825    for index, length in _WRITE_PLAN:
5826        if index == 7 and not write_zone_names:
5827            continue
5828        if index == 6 and not write_aprs:
5829            continue
5830        seg = DEFAULT_SEGMENTS[index]
5831        length = seg.length if length is None else length
5832        if index == 0:
5833            length = min(length, channel_bytes)
5834        segments.append(CloneSegment(seg.read_command, seg.write_command, seg.start, length))
5835        data.extend(payload[offsets[index] : offsets[index] + length])
5836    return segments, bytes(data)
5837
5838
5839def _build_clone_payload(image: RadioImage) -> bytes:
5840    """Serialise ``image`` into the byte order of ``DEFAULT_SEGMENTS``.
5841
5842    Args:
5843        image: The parsed image to serialise.
5844
5845    Returns:
5846        bytes: ``_SEGMENT_LENGTH`` bytes.
5847
5848    Raises:
5849        ValueError: If ``image.to_bytes()`` fails (e.g. a tone that cannot be
5850            encoded) or the result has the wrong length.
5851    """
5852    buffer = image.to_bytes()
5853    payload = bytearray()
5854    payload.extend(buffer[:CHANNEL_SECTION_BYTES])
5855    cursor = CHANNEL_SECTION_BYTES
5856    for segment in DEFAULT_SEGMENTS[1:]:
5857        end = cursor + segment.length
5858        payload.extend(buffer[cursor:end])
5859        cursor = end
5860    if len(payload) != _SEGMENT_LENGTH:
5861        raise ValueError(
5862            f"Composed payload length {len(payload)} does not match expected {_SEGMENT_LENGTH}"
5863        )
5864    return bytes(payload)
5865
5866# ---------------------------------------------------------------------------
5867# Driver implementation -----------------------------------------------------
5868
5869# ---------------------------------------------------------------------------
5870
5871VALID_BANDS: Tuple[Tuple[int, int], ...] = (
5872    (18_000_000, 64_000_000),  # Low HF confirmed RX/TX (FM only)
5873    (118_000_000, 137_000_000),  # Airband RX (AM only, TX disabled)
5874    (70_000_000, 118_000_000),  # Lower VHF before airband
5875    (136_000_000, 174_000_000),
5876    (174_000_000, 400_000_000),
5877    (400_000_000, 480_000_000),
5878    (480_000_000, 580_000_000),
5879)
5880"""Frequency bands offered to CHIRP, as ``(low, high)`` in Hz.
5881
5882``is_split`` treats ``high`` as inclusive, CHIRP's ``validate_memory`` as
5883exclusive.
5884
5885Used for ``RadioFeatures.valid_bands`` and to decide when a channel is shown
5886as ``split``: RX and TX not inside one common band (CHIRP's
5887``chirp_common.is_split``). The bands are the driver's, not the amateur
5888bands: 136-174 MHz and 174-400 MHz are each one band, so RX 145 MHz with
5889TX 222 MHz is split, RX 145.6 with TX 145.0 MHz is not. The bands overlap at
5890136-137 MHz."""
5891
5892# Raw view of the clone image for CHIRP's developer-mode Browser tab.
5893# The driver itself works on RadioImage; this layout is for inspection only.
5894MEM_FORMAT = """
5895struct {
5896  u8 rx_freq[4];
5897  u8 tx_freq[4];
5898  u8 rx_tone[2];
5899  u8 tx_tone[2];
5900  u8 signalling_group;
5901  u8 ptt_id;
5902  u8 scram_power;
5903  u8 flags;
5904  u8 fhss_code[4];
5905  char name[12];
5906} channels[%d];
5907u8 channel_extra[%d];  // up to 0x8000
5908u8 vfo[0x100];
5909u8 function[0x100];
5910u8 dtmf[0x200];
5911u8 modulation_params[0x200];
5912u8 modulation_names[0x300];
5913u8 aprs[0x80];
5914struct {
5915  char name[12];
5916  u8 unused[4];
5917} zone_names[10];
5918u8 zone_names_pad[0x60];
5919""" % (CHANNEL_COUNT,  # pylint: disable=consider-using-f-string
5920       CHANNEL_SECTION_BYTES - CHANNEL_DATA_BYTES)
5921"""CHIRP bitwise layout of the clone image.
5922
5923Used only for CHIRP's developer-mode *Browser* tab; the driver itself
5924works on :class:`RadioImage`. ``%`` formatting is used because the layout
5925contains literal braces.
5926"""
5927
5928_MEMSIZE_V1 = _SEGMENT_LENGTH - ZONE_NAME_SEGMENT_BYTES
5929"""Image size of driver versions with 990 channels but no zone names."""
5930
5931_LEGACY_MEMSIZE = _MEMSIZE_V1 - (
5932    CHANNEL_SECTION_BYTES - LEGACY_CHANNEL_SECTION_BYTES)
5933"""Image size of the old 960-slot driver (channel segment 0x7800 bytes)."""
5934
5935
5936def _zone_label(image, zone: int) -> str:
5937    """Build the memory-tab label for one zone.
5938
5939    Args:
5940        image: The parent's :class:`RadioImage`, or ``None``.
5941        zone: Zone number, 1-10.
5942
5943    Returns:
5944        str: ``"1 VHF-LOCAL"`` for a named zone, ``"Zone 1"`` otherwise.
5945    """
5946    names = ((image.zone_names if image is not None else None)
5947             or [""] * ZONE_COUNT)
5948    name = names[zone - 1]
5949    return f"{zone} {name}" if name else f"Zone {zone}"
5950
5951
5952def _apply_zone_name(rsetting, image, index):
5953    """Settings callback: store an edited zone name in the image.
5954
5955    A value equal to the stored name is left as it is (also a stored name
5956    longer than ``ZONE_NAME_LENGTH``). Otherwise surrounding spaces are
5957    stripped, non-ASCII characters are dropped and the result is cut to
5958    ``ZONE_NAME_LENGTH`` (12). ``image.zone_names`` is
5959    created (ten empty names) if it is ``None``.
5960
5961    Args:
5962        rsetting: The CHIRP ``RadioSetting`` holding the new name.
5963        image: The :class:`RadioImage` to update.
5964        index: Zone index, 0-9.
5965
5966    Returns:
5967        None: Nothing; ``image.zone_names`` is updated in place.
5968    """
5969    if image.zone_names is None:
5970        image.zone_names = [""] * ZONE_COUNT
5971    value = str(rsetting.value).strip()
5972    if value == image.zone_names[index]:
5973        return
5974    image.zone_names[index] = value.encode("ascii", errors="ignore").decode()[:ZONE_NAME_LENGTH]
5975
5976
5977def _build_zone_group(image):
5978    """Build the *Zone Names* settings group (one string per zone).
5979
5980    Each field accepts ``ZONE_NAME_LENGTH`` (12) characters, or more when the
5981    stored name is already longer (up to the 16-byte slot).
5982
5983    Args:
5984        image: The :class:`RadioImage` providing the current names.
5985
5986    Returns:
5987        RadioSettingGroup: Ten string settings wired to
5988        :func:`_apply_zone_name`.
5989    """
5990    group = RadioSettingGroup('zones', 'Zone Names')
5991    names = image.zone_names or [""] * ZONE_COUNT
5992    for index in range(ZONE_COUNT):
5993        # A name longer than ZONE_NAME_LENGTH (written by other software; the
5994        # slot holds 16 bytes) must still load, so allow its own length.
5995        maximum = max(ZONE_NAME_LENGTH, len(names[index]))
5996        value = RadioSettingValueString(0, maximum, names[index],
5997                                        autopad=False,
5998                                        charset=chirp_common.CHARSET_ASCII)
5999        setting = RadioSetting(f'zone_name_{index + 1}',
6000                               f'Zone {index + 1} name', value)
6001        setting.set_apply_callback(_apply_zone_name, image, index)
6002        group.append(setting)
6003    return group
6004
6005
6006def _tone_to_chirp(tone: ToneSetting) -> tuple:
6007    """Convert a radio tone into a CHIRP tone spec for ``split_tone_decode``.
6008
6009    Args:
6010        tone: The radio tone.
6011
6012    Returns:
6013        tuple: ``(mode, value, polarity)``: ``("", None, None)`` for no tone,
6014        ``("Tone", hz, None)`` for CTCSS, ``("DTCS", code, "N" or "R")`` for
6015        DCS (the radio's inverted ``I`` becomes CHIRP's reverse ``R``).
6016    """
6017    if tone.mode is ToneMode.CTCSS and tone.ctcss_hz is not None:
6018        return ("Tone", tone.ctcss_hz, None)
6019    if tone.mode is ToneMode.DCS and tone.dcs_code is not None:
6020        polarity = "R" if (tone.dcs_polarity or "N").upper() == "I" else "N"
6021        return ("DTCS", tone.dcs_code, polarity)
6022    return ("", None, None)
6023
6024
6025def _tone_from_chirp(mode: str, value, polarity) -> ToneSetting:
6026    """Convert one CHIRP tone spec from ``split_tone_encode`` into a radio tone.
6027
6028    Args:
6029        mode: ``"Tone"``, ``"DTCS"`` or ``""``.
6030        value: CTCSS frequency in Hz or DCS code; a DCS code of 0 or a
6031            missing value gives no tone.
6032        polarity: CHIRP DCS polarity ``"N"`` or ``"R"`` (stored as ``"I"``),
6033            or ``None``.
6034
6035    Returns:
6036        ToneSetting: The radio tone.
6037    """
6038    if mode == "Tone" and value:
6039        return ToneSetting.ctcss(float(value))
6040    if mode == "DTCS" and value:
6041        return ToneSetting.dcs(int(value), "I" if (polarity or "N").upper() == "R" else "N")
6042    return ToneSetting.off()
6043
6044
6045class RT950ProRadio(chirp_common.CloneModeRadio):
6046    """CHIRP clone-mode driver for the Radtel RT-950 Pro.
6047
6048    Memories 1-990 on this object (memory ``(z - 1) * 99 + k`` is zone *z*,
6049    channel *k*) are the driver API. What CHIRP's user interface shows
6050    follows the radio setting *Channel Divide*: in Zone CH Mode the ten
6051    :class:`RT950ProZoneRadio` sub-devices (memories 1-99 each), which map
6052    onto them; in All CH Mode this object itself, as one list of memories
6053    1-990 (memory *n* is radio channel *n*).
6054
6055    Internally all data lives in a :class:`RadioImage`; the CHIRP memory
6056    map is rebuilt from it whenever CHIRP asks for it.
6057    """
6058
6059    _memsize = _SEGMENT_LENGTH
6060    """Size of a complete clone image in bytes (``_SEGMENT_LENGTH``).
6061
6062    CHIRP returns it from ``get_memsize()`` and shows it in the radio-info
6063    dialog; the driver itself does not use it.
6064    """
6065    VENDOR = "Radtel"
6066    """Vendor name shown by CHIRP."""
6067    MODEL = "RT-950 Pro"
6068    """Model name shown by CHIRP."""
6069    BAUD_RATE = 115200
6070    """Serial speed of the programming cable."""
6071
6072    def __init__(self, *args, **kwargs) -> None:
6073        """Create the driver; arguments are passed to CHIRP unchanged.
6074
6075        State used by :meth:`process_mmap` is initialised first, because
6076        CHIRP's constructor may load an image and call it.
6077
6078        Args:
6079            *args: Normally the single ``pipe`` argument of
6080                ``CloneModeRadio.__init__``: a serial port, an image file name
6081                or a ``MemoryMapBytes`` (the last two make CHIRP call
6082                :meth:`process_mmap`).
6083            **kwargs: Passed on unchanged; the stand-in only uses ``pipe``.
6084        """
6085        self._image: Optional[RadioImage] = None
6086        """Parsed clone image; the single source of all channel and settings
6087        data. ``None`` until an image is downloaded or loaded."""
6088        self._memory_cache: dict[int, chirp_common.Memory] = {}
6089        """CHIRP ``Memory`` objects by memory number (1-990), built on first
6090        :meth:`get_memory` and cleared when a new image is processed or settings
6091        are applied. The zone sub-devices share this dict."""
6092        self._memobj = None
6093        """Raw ``bitwise`` view of the memory map (``MEM_FORMAT``) for CHIRP's
6094        developer-mode Browser tab; ``None`` if it could not be built."""
6095        self._zone_names_valid = False
6096        """True when the image holds zone names read from 0xC000 (image of
6097        layout version ``_LAYOUT_VERSION`` or later); only then are zone names
6098        written to the radio."""
6099        self._legacy_960 = False
6100        """True for an image saved by the old 960-slot driver; channels
6101        961-990 are then never written."""
6102        self._aprs_original: Optional[bytes] = None
6103        """APRS block as it was when the image was processed; the APRS block
6104        is written only when the current bytes differ. ``None`` disables the
6105        APRS write."""
6106        self._high_channels_original: Optional[bytes] = None
6107        """Bytes 0x7800-0x7BFF (channels 961-990) as they were when the image
6108        was processed; that range is written only when it changed. ``None``
6109        disables writing it."""
6110        super().__init__(*args, **kwargs)
6111
6112    # ------------------------------------------------------------------
6113    # CHIRP hooks
6114    # ------------------------------------------------------------------
6115
6116    def get_features(self):  # type: ignore[override]
6117        """Describe the radio's capabilities to CHIRP.
6118
6119        ``has_sub_devices`` follows the setting *Channel Divide*
6120        (:meth:`_all_channels_mode`): ``True`` in Zone CH Mode (ten zone
6121        tabs), ``False`` in All CH Mode (one list, memories 1-990).
6122        ``has_dynamic_subdevices`` is set so that CHIRP rebuilds the tabs
6123        when that setting is changed.
6124
6125        Returns:
6126            chirp_common.RadioFeatures: Bands, modes, tones, power levels
6127            and name rules for this radio.
6128
6129        Raises:
6130            RadioError: If CHIRP is not available.
6131        """
6132        _require_chirp("get_features")
6133        # RadioFeatures accepts its attributes via __setattr__.
6134        # pylint: disable=attribute-defined-outside-init
6135        rf = chirp_common.RadioFeatures()
6136        # 1-based: memory 1 = zone 1 ch 1, memory 100 = zone 2 ch 1, ...
6137        rf.memory_bounds = (1, CHANNEL_COUNT)
6138        rf.valid_bands = list(VALID_BANDS)
6139        rf.has_bank = False
6140        rf.has_bank_names = False
6141        # Zone CH Mode: each zone is its own memory tab (channels 1-99).
6142        # All CH Mode: no sub-devices, so CHIRP shows memories 1-990 of
6143        # this object as one list.
6144        rf.has_sub_devices = not self._all_channels_mode()
6145        # The tabs depend on the setting Channel Divide: CHIRP rebuilds the
6146        # editor when that (volatile) setting is changed. Older CHIRP
6147        # versions without this feature reject the name; they then show the
6148        # new layout only after the image is reopened.
6149        try:
6150            rf.has_dynamic_subdevices = True
6151        except ValueError:
6152            pass
6153        rf.has_settings = True
6154        rf.has_name = True
6155        rf.has_ctone = True
6156        rf.has_dtcs = True
6157        rf.has_dtcs_polarity = True
6158        rf.has_mode = True
6159        rf.has_offset = True
6160        rf.has_tuning_step = False
6161        rf.can_delete = True
6162        rf.can_odd_split = True
6163        rf.has_cross = True
6164        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
6165        rf.valid_cross_modes = list(chirp_common.CROSS_MODES)
6166        rf.valid_duplexes = ["", "+", "-", "split"]
6167        rf.valid_modes = ["FM", "NFM", "AM"]
6168        rf.valid_power_levels = _CHIRP_POWER_LEVELS
6169        rf.valid_skips = ["", "S"]
6170        rf.valid_dtcs_pols = ["NN", "NR", "RN", "RR"]
6171        # Use CHIRP's standard DCS code list; do not include 0/"000"
6172        # to avoid invalid DTCS state during CSV export.
6173        rf.valid_dtcs_codes = list(chirp_common.DTCS_CODES)
6174        # The radio stores frequencies in 10 Hz units and has no per-channel
6175        # tuning step, so CHIRP must not require one: otherwise it refuses
6176        # e.g. UK CB 27.60125 MHz on paste, edit and import. The 10 Hz rule
6177        # itself is checked in validate_memory().
6178        rf.has_nostep_tuning = True
6179        rf.valid_characters = chirp_common.CHARSET_ASCII
6180        rf.valid_name_length = 12
6181        return rf
6182
6183    def validate_memory(self, mem):  # type: ignore[override]
6184        """Check ``mem`` against CHIRP's rules and the radio's 10 Hz grid.
6185
6186        Adds to CHIRP's checks (made from :meth:`get_features`) one error if
6187        the RX frequency is not a multiple of 10 Hz, and one if ``offset`` is
6188        not (for ``+``/``-`` the offset, for ``split`` the TX frequency); with
6189        the RX frequency on the 10 Hz grid this equals checking the TX
6190        frequency. The radio stores them in 10 Hz units, see
6191        :func:`_encode_frequency`; e.g. 27.60125 MHz passes, 145.500005 MHz
6192        does not. Empty memories get no extra check.
6193
6194        Args:
6195            mem: The CHIRP ``Memory`` (or ``FrozenMemory``) to check; not
6196                modified.
6197
6198        Returns:
6199            list: CHIRP's ``ValidationWarning`` and ``ValidationError``
6200            messages; empty when ``mem`` can be stored.
6201
6202        Raises:
6203            RadioError: If CHIRP is not available.
6204        """
6205        _require_chirp("validate_memory")
6206        # CHIRP's CloneModeRadio has validate_memory(); pylint may resolve the
6207        # base class to the stand-in, which lacks it (never reached: see above).
6208        msgs = super().validate_memory(mem)  # pylint: disable=no-member
6209        if mem.empty:
6210            return msgs
6211        if mem.freq % 10:
6212            msgs.append(chirp_common.ValidationError(
6213                f"Frequency {chirp_common.format_freq(mem.freq)} MHz is not a "
6214                "multiple of 10 Hz"))
6215        if mem.duplex in ("+", "-", "split") and mem.offset % 10:
6216            msgs.append(chirp_common.ValidationError(
6217                f"Offset or TX frequency {chirp_common.format_freq(mem.offset)} "
6218                "MHz is not a multiple of 10 Hz"))
6219        return msgs
6220
6221    def process_mmap(self):  # type: ignore[override]
6222        """Parse CHIRP's memory map into a :class:`RadioImage`.
6223
6224        Also upgrades images saved by earlier driver versions:
6225
6226        * full size without ``rt950_layout`` metadata, or with a version
6227          below ``_LAYOUT_VERSION``: zone-name bytes are replaced by 0xFF and
6228          not written;
6229        * without zone-name segment: 0xFF zone names are appended;
6230        * old 960-slot image: the missing 0x7800-0x7FFF range is inserted as
6231          empty, so channels 961-990 show as empty.
6232
6233        Finally it snapshots the APRS block and channels 961-990 so that
6234        :meth:`_write_options` can tell whether they changed.
6235
6236        Returns:
6237            None: Nothing; the result is stored in ``self._image`` (``None`` when
6238            there is no memory map or it is empty).
6239
6240        Raises:
6241            RadioError: If the image cannot be parsed.
6242        """
6243        mmap_obj = getattr(self, '_mmap', None)
6244        if mmap_obj is None:
6245            self._image = None
6246            return
6247        if hasattr(mmap_obj, 'get_packed'):
6248            data = mmap_obj.get_packed()
6249        else:
6250            data = bytes(mmap_obj)
6251        if not data:
6252            self._image = None
6253            return
6254        meta = getattr(self, '_metadata', None) or {}
6255        self._zone_names_valid = (len(data) == _SEGMENT_LENGTH
6256                                  and meta.get('rt950_layout', 0) >= _LAYOUT_VERSION)
6257        self._legacy_960 = False
6258        if len(data) == _SEGMENT_LENGTH and not self._zone_names_valid:
6259            LOG.warning('RT-950 Pro image from an older driver version: zone '
6260                        'names not valid and will not be written. Read the '
6261                        'radio again to get them.')
6262            data = bytes(data[:-ZONE_NAME_SEGMENT_BYTES]) + b'\xFF' * ZONE_NAME_SEGMENT_BYTES
6263            self._mmap = memmap.MemoryMapBytes(data)
6264        if len(data) == _MEMSIZE_V1:
6265            LOG.warning('RT-950 Pro image without zone names; names not read')
6266            data = bytes(data) + b'\xFF' * ZONE_NAME_SEGMENT_BYTES
6267            self._mmap = memmap.MemoryMapBytes(data)
6268        elif len(data) == _LEGACY_MEMSIZE:
6269            self._legacy_960 = True
6270            # Image saved by the old 960-slot driver: insert the missing
6271            # 0x7800-0x7FFF range as empty (0xFF) so offsets line up again.
6272            LOG.warning(
6273                'Legacy RT-950 Pro image (%d bytes): channels 961-990 were '
6274                'not read from the radio and are shown empty', len(data))
6275            data = (bytes(data[:LEGACY_CHANNEL_SECTION_BYTES])
6276                    + b'\xFF' * (CHANNEL_SECTION_BYTES - LEGACY_CHANNEL_SECTION_BYTES)
6277                    + bytes(data[LEGACY_CHANNEL_SECTION_BYTES:])
6278                    + b'\xFF' * ZONE_NAME_SEGMENT_BYTES)
6279            self._mmap = memmap.MemoryMapBytes(data)
6280        try:
6281            self._image = RadioImage.from_bytes(data)
6282        except ValueError as exc:
6283            raise errors.RadioError(f'Failed to parse memory map: {exc}') from exc
6284        self._memory_cache.clear()
6285        self._parse_memobj()
6286        self._log_channel_extra()
6287        try:
6288            payload = _build_clone_payload(self._image)
6289            self._aprs_original = self._aprs_bytes(payload)
6290            self._high_channels_original = bytes(
6291                payload[LEGACY_CHANNEL_SECTION_BYTES:0x7C00])
6292        # Without these snapshots the write simply skips APRS and channels
6293        # 961-990 (the safe default), so any failure here is non-fatal.
6294        except Exception:  # pylint: disable=broad-exception-caught
6295            self._aprs_original = None
6296            self._high_channels_original = None
6297
6298    def _parse_memobj(self) -> None:
6299        """Build the raw bitwise view for CHIRP's Browser tab (never fatal)."""
6300        try:
6301            self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
6302        # Developer view only; never fatal.
6303        except Exception as exc:  # pylint: disable=broad-exception-caught
6304            LOG.debug('Could not build raw memory view: %s', exc)
6305            self._memobj = None
6306
6307    def _log_channel_extra(self) -> None:
6308        """Log printable text found after the last channel record.
6309
6310        Diagnostic aid from the search for the zone-name location (now known
6311        to be 0xC000); it logs runs of three or more printable ASCII bytes in
6312        0x7BC0-0x7FFF.
6313        """
6314        if self._image is None:
6315            return
6316        extra = self._image.channel_extra
6317        run = bytearray()
6318        start = 0
6319        for idx, byte in enumerate(extra + b'\x00'):
6320            if 0x20 <= byte < 0x7F:
6321                if not run:
6322                    start = idx
6323                run.append(byte)
6324                continue
6325            if len(run) >= 3:
6326                LOG.info('Text at 0x%04X: %r', CHANNEL_DATA_BYTES + start,
6327                         run.decode('ascii'))
6328            run = bytearray()
6329
6330    def _refresh_mmap(self) -> None:
6331        """Copy edits held in the :class:`RadioImage` back into CHIRP's memory map."""
6332        if self._image is None:
6333            return
6334        self._mmap = memmap.MemoryMapBytes(_build_clone_payload(self._image))
6335        self._parse_memobj()
6336
6337    def get_mmap(self):  # type: ignore[override]
6338        """Return the memory map, refreshed from the current image.
6339
6340        Returns:
6341            memmap.MemoryMapBytes: ``self._mmap``, rebuilt from the image when one
6342            is loaded.
6343
6344        Raises:
6345            ValueError: If the image cannot be serialised.
6346        """
6347        self._refresh_mmap()
6348        return self._mmap
6349
6350    def save_mmap(self, filename):  # type: ignore[override]
6351        """Refresh the memory map from the image, then save it as CHIRP does.
6352
6353        Args:
6354            filename: Destination ``.img`` file.
6355
6356        Returns:
6357            None: CHIRP's ``CloneModeRadio.save_mmap`` returns nothing; the
6358            ``return`` only passes that through.
6359
6360        Raises:
6361            ValueError: If the image cannot be serialised.
6362            Exception: ``"File Access Error"`` from CHIRP on an ``IOError``.
6363        """
6364        self._refresh_mmap()
6365        # pylint cannot see save_mmap on the stand-in base class.
6366        return super().save_mmap(filename)  # pylint: disable=no-member
6367
6368    def _aprs_bytes(self, payload: bytes) -> bytes:
6369        """Return the APRS block (segment 6) from a clone payload.
6370
6371        Args:
6372            payload: Clone payload in ``DEFAULT_SEGMENTS`` order.
6373
6374        Returns:
6375            bytes: The ``APRS_SEGMENT_BYTES`` (128) bytes of the APRS block.
6376        """
6377        start = sum(seg.length for seg in DEFAULT_SEGMENTS[:6])
6378        return bytes(payload[start : start + DEFAULT_SEGMENTS[6].length])
6379
6380    def _write_options(self) -> dict:
6381        """Decide which optional parts of the image to write.
6382
6383        * APRS is written only when its bytes changed since the read. The
6384          APRS commit is slow and an old write command (0x55) was never
6385          acknowledged, so it is skipped whenever possible.
6386        * 0x7800-0x7BFF holds channels 961-990 on firmware with 10x99
6387          zones, but NeonPlug reports calibration-like data there on other
6388          units. It is written only when one of channels 961-990 changed,
6389          and never for an image from the old 960-slot driver.
6390        * Zone names are written only when they were read from 0xC000.
6391
6392        Returns:
6393            dict: Keyword arguments for :func:`_build_write_plan`
6394            (``write_zone_names``, ``channel_bytes``, ``write_aprs``).
6395        """
6396        write_aprs = False
6397        channel_bytes = LEGACY_CHANNEL_SECTION_BYTES
6398        if self._image is not None:
6399            payload = _build_clone_payload(self._image)
6400            if getattr(self, '_aprs_original', None) is not None:
6401                write_aprs = self._aprs_bytes(payload) != self._aprs_original
6402            original_high = getattr(self, '_high_channels_original', None)
6403            if (original_high is not None and not getattr(self, '_legacy_960', False)
6404                    and bytes(payload[LEGACY_CHANNEL_SECTION_BYTES:0x7C00]) != original_high):
6405                channel_bytes = 0x7C00
6406        return {
6407            'write_zone_names': getattr(self, '_zone_names_valid', False),
6408            'channel_bytes': channel_bytes,
6409            'write_aprs': write_aprs,
6410        }
6411
6412    def _all_channels_mode(self) -> bool:
6413        """Return whether the image is set to *All CH Mode*.
6414
6415        Reads the function setting ``divide_channel`` (byte 0x9026) of the
6416        loaded image. Only the value ``CHANNEL_DIVIDE_ALL`` (1) counts as
6417        All CH Mode; Zone CH Mode (0), a value that is not set (0xFF), an
6418        unknown value, a missing function block and no image at all give
6419        ``False``, i.e. the zone view.
6420
6421        Returns:
6422            bool: ``True`` for All CH Mode, otherwise ``False``.
6423        """
6424        image = self._image
6425        function = getattr(image, 'function', None) if image is not None else None
6426        if function is None:
6427            return False
6428        try:
6429            value = get_function_value(function, 'divide_channel')
6430        except KeyError:
6431            return False
6432        return value == CHANNEL_DIVIDE_ALL
6433
6434    def get_sub_devices(self):  # type: ignore[override]
6435        """Return the zone sub-devices for the current *Channel Divide* mode.
6436
6437        Zone CH Mode: one :class:`RT950ProZoneRadio` per zone (memory tabs
6438        1-10). All CH Mode: none, because the radio then has no zones to
6439        show; CHIRP uses this object itself (memories 1-990) as the only
6440        memory list.
6441
6442        Returns:
6443            list[RT950ProZoneRadio]: Ten sub-devices, zone 1 first, or an
6444            empty list in All CH Mode.
6445        """
6446        if self._all_channels_mode():
6447            return []
6448        return [RT950ProZoneRadio(self, zone) for zone in range(1, ZONE_COUNT + 1)]
6449
6450    def sync_in(self):  # type: ignore[override]
6451        """Download the complete image from the radio.
6452
6453        Reports progress per block through CHIRP's ``status_fn`` when
6454        available, then replaces ``self._metadata`` with
6455        ``{'rt950_layout': _LAYOUT_VERSION}`` and parses the image with
6456        :meth:`process_mmap` (which relies on that version).
6457
6458        Raises:
6459            RadioError: If no port is open, the clone read fails, or the
6460                image cannot be parsed.
6461        """
6462        if self.pipe is None:
6463            raise errors.RadioError("Serial pipe not initialised")
6464        transport = CloneSerialTransport(self.pipe, logger=LOG)
6465        # Hook progress into CHIRP status if available
6466        status = None
6467        try:
6468            status = chirp_common.Status()
6469            status.msg = "Cloning from radio…"
6470            status.max = 0
6471        # Status is optional (absent from the stand-in); clone without it.
6472        except Exception:  # pylint: disable=broad-exception-caught
6473            status = None
6474        if status is not None and hasattr(self, "status_fn"):
6475            blocks_per_segment = [seg.length // READ_BLOCK for seg in DEFAULT_SEGMENTS]
6476            seg_labels = [
6477                "Channels",
6478                "VFO settings",
6479                "Function settings",
6480                "DTMF settings",
6481                "Modulation params",
6482                "Modulation names",
6483                "APRS settings",
6484                "Zone names",
6485            ]
6486
6487            def _progress(done: int, total: int, phase: str) -> None:
6488                """Map a block count to a 'Reading ...' status message.
6489
6490                Args:
6491                    done: Blocks transferred so far (1-based count).
6492                    total: Total number of blocks in the transfer.
6493                    phase: ``"read"`` or ``"write"``; selects the message verb.
6494                """
6495                try:
6496                    block_index = max(0, int(done) - 1)
6497                    seg_idx = 0
6498                    offset_blocks = block_index
6499                    for count in blocks_per_segment:
6500                        if offset_blocks < count:
6501                            break
6502                        offset_blocks -= count
6503                        seg_idx += 1
6504                    direction = "Reading" if phase == "read" else "Writing"
6505                    if seg_idx == 0:
6506                        per_block = max(1, READ_BLOCK // CHANNEL_SIZE)
6507                        start_ch = offset_blocks * per_block + 1
6508                        end_ch = min(start_ch + per_block - 1, CHANNEL_COUNT)
6509                        status.msg = f"{direction} channels {start_ch:03d}-{end_ch:03d}…"
6510                    else:
6511                        status.msg = f"{direction} {seg_labels[seg_idx]}…"
6512                    status.cur = done
6513                    status.max = total
6514                    self.status_fn(status)
6515                # Progress reporting must never break the clone.
6516                except Exception:  # pylint: disable=broad-exception-caught
6517                    pass
6518            transport.progress_cb = _progress
6519        try:
6520            raw = transport.read_clone()
6521        except Exception as exc:
6522            raise errors.RadioError(f'Clone read failed: {exc}') from exc
6523        self._mmap = memmap.MemoryMapBytes(raw)
6524        self._metadata = {'rt950_layout': _LAYOUT_VERSION}
6525        self.process_mmap()
6526
6527    def sync_out(self):  # type: ignore[override]
6528        """Upload the image to the radio.
6529
6530        The parts written are chosen by :meth:`_write_options` and ordered by
6531        ``_WRITE_PLAN``: channels (up to 0x77FF, or 0x7BFF when channels
6532        961-990 changed), settings blocks, zone names if valid, and APRS last
6533        and only if changed.
6534
6535        Raises:
6536            RadioError: If no port or image is available or the write fails.
6537                A missing APRS acknowledgement gets its own message, because
6538                everything else was already written at that point.
6539            ValueError: If the image cannot be serialised (e.g. a DCS tone
6540                with polarity ``R``); raised before anything is sent.
6541        """
6542        if self.pipe is None:
6543            raise errors.RadioError("Serial pipe not initialised")
6544        if self._image is None:
6545            raise errors.RadioError("No image loaded")
6546        payload = _build_clone_payload(self._image)
6547        transport = CloneSerialTransport(self.pipe, logger=LOG)
6548        status = None
6549        try:
6550            status = chirp_common.Status()
6551            status.msg = "Cloning to radio…"
6552            status.max = 0
6553        # Status is optional (absent from the stand-in); clone without it.
6554        except Exception:  # pylint: disable=broad-exception-caught
6555            status = None
6556        if status is not None and hasattr(self, "status_fn"):
6557            all_labels = [
6558                "Channels",
6559                "VFO settings",
6560                "Function settings",
6561                "DTMF settings",
6562                "Modulation params",
6563                "Modulation names",
6564                "APRS settings",
6565                "Zone names",
6566            ]
6567            plan_segments, _ = _build_write_plan(payload, **self._write_options())
6568            blocks_per_segment = [seg.length // READ_BLOCK for seg in plan_segments]
6569            opts = self._write_options()
6570            seg_labels = [all_labels[index] for index, _ in _WRITE_PLAN
6571                          if (index != 7 or opts['write_zone_names'])
6572                          and (index != 6 or opts['write_aprs'])]
6573
6574            def _progress(done: int, total: int, phase: str) -> None:
6575                """Map a block count to a 'Writing ...' status message.
6576
6577                Args:
6578                    done: Blocks transferred so far (1-based count).
6579                    total: Total number of blocks in the transfer.
6580                    phase: Transfer phase from the transport; unused.
6581                """
6582                del phase  # always "write" here
6583                try:
6584                    block_index = max(0, int(done) - 1)
6585                    seg_idx = 0
6586                    offset_blocks = block_index
6587                    for count in blocks_per_segment:
6588                        if offset_blocks < count:
6589                            break
6590                        offset_blocks -= count
6591                        seg_idx += 1
6592                    if seg_idx == 0:
6593                        per_block = max(1, READ_BLOCK // CHANNEL_SIZE)
6594                        start_ch = offset_blocks * per_block + 1
6595                        end_ch = min(start_ch + per_block - 1, CHANNEL_COUNT)
6596                        status.msg = f"Writing channels {start_ch:03d}-{end_ch:03d}…"
6597                    else:
6598                        status.msg = f"Writing {seg_labels[seg_idx]}…"
6599                    status.cur = done
6600                    status.max = total
6601                    self.status_fn(status)
6602                # Progress reporting must never break the clone.
6603                except Exception:  # pylint: disable=broad-exception-caught
6604                    pass
6605            transport.progress_cb = _progress
6606        try:
6607            write_segments, write_data = _build_write_plan(
6608                payload, **self._write_options())
6609            transport.write_clone(write_data, segments=write_segments)
6610        # Any failure is reported to the user as a RadioError.
6611        except Exception as exc:  # pylint: disable=broad-exception-caught
6612            if 'cmd 0x58' in str(exc):
6613                raise errors.RadioError(
6614                    'All channels, settings and zone names were written, but the '
6615                    'radio did not acknowledge the APRS block (cmd 0x58); APRS '
6616                    'changes may NOT be saved. Power-cycle the radio and read back.') from exc
6617            raise errors.RadioError(f'Clone write failed: {exc}') from exc
6618        self._mmap = memmap.MemoryMapBytes(payload)
6619        self._parse_memobj()
6620    # ------------------------------------------------------------------
6621    # Settings integration
6622    # ------------------------------------------------------------------
6623
6624    def get_settings(self):  # type: ignore[override]
6625        """Build the settings tree shown in CHIRP's *Settings* tab.
6626
6627        Returns:
6628            RadioSettings: VFO, modulation, function, APRS, DTMF and zone-name
6629            groups (sections absent from the image are skipped).
6630
6631        Raises:
6632            RadioError: If CHIRP is not available or no image is loaded.
6633        """
6634        _require_chirp("get_settings")
6635        image = self._require_image()
6636        groups = []
6637        if getattr(image, 'vfo', None):
6638            groups.append(_build_vfo_group(image.vfo))
6639        if getattr(image, 'modulation', None) is not None:
6640            groups.append(_build_modulation_group(image.modulation))
6641        if getattr(image, 'function', None) is not None:
6642            groups.append(_build_function_group(image.function))
6643        if getattr(image, 'aprs', None) is not None:
6644            groups.append(_build_aprs_group(image.aprs))
6645        if getattr(image, 'dtmf', None) is not None:
6646            groups.append(_build_dtmf_group(image.dtmf))
6647        groups.append(_build_zone_group(image))
6648        if not groups:
6649            return RadioSettings()
6650        return RadioSettings(*groups)
6651
6652    def set_settings(self, settings):  # type: ignore[override]
6653        """Apply edited settings to the image.
6654
6655        CHIRP passes the whole tree on every apply. The apply callback runs
6656        only for settings whose value was changed (CHIRP's
6657        ``RadioSetting.changed()``; without it, as with the stand-in classes,
6658        every callback runs). The callbacks write into the
6659        :class:`RadioImage`. Then clears the memory cache.
6660
6661        Args:
6662            settings: The tree returned by :meth:`get_settings`, edited.
6663
6664        Raises:
6665            RadioError: If no image is loaded, the container is unexpected or a
6666                callback rejects a value.
6667            ValueError: For an invalid modulation-memory frequency.
6668        """
6669        self._require_image()
6670        if not isinstance(settings, RadioSettings):
6671            raise errors.RadioError('Unexpected settings container')
6672        walker = getattr(settings, 'walk', None)
6673        if walker is None:
6674            raise errors.RadioError('Settings container missing walk()')
6675        for element in walker():
6676            if not (isinstance(element, RadioSetting) and element.has_apply_callback()):
6677                continue
6678            # CHIRP marks a value as changed once the user edits it; unchanged
6679            # settings are skipped, so a value the driver cannot show exactly
6680            # (e.g. "not set", 0xFF) is never rewritten as a default.
6681            changed = getattr(element, 'changed', None)
6682            if changed is not None and not changed():
6683                continue
6684            element.run_apply_callback()
6685        self._memory_cache.clear()
6686    # ------------------------------------------------------------------
6687    # Memory translation helpers
6688    # ------------------------------------------------------------------
6689
6690    def _require_image(self) -> RadioImage:
6691        """Return the loaded image.
6692
6693        Returns:
6694            RadioImage: The parsed clone image.
6695
6696        Raises:
6697            RadioError: If no image is loaded.
6698        """
6699        if self._image is None:
6700            raise errors.RadioError("Memory image not loaded")
6701        return self._image
6702
6703    def get_memory(self, number: int):  # type: ignore[override]
6704        """Return memory ``number`` (1-990) as a CHIRP ``Memory``.
6705
6706        Results are cached until the memory or the settings change.
6707
6708        Args:
6709            number: Memory number, 1-990 (slot ``number - 1``).
6710
6711        Returns:
6712            chirp_common.Memory: The memory, from the cache when available.
6713
6714        Raises:
6715            RadioError: If CHIRP is not available, no image is loaded or
6716                ``number`` is out of range.
6717        """
6718        _require_chirp("get_memory")
6719        image = self._require_image()
6720        if not 1 <= number <= len(image.channels):
6721            raise errors.RadioError(f"Memory index {number} out of range")
6722        if number in self._memory_cache:
6723            return self._memory_cache[number]
6724        channel = image.channels[number - 1]
6725        mem = self._channel_to_memory(number, channel)
6726        self._memory_cache[number] = mem
6727        return mem
6728
6729    def set_memory(self, mem):  # type: ignore[override]
6730        """Store a CHIRP ``Memory`` in the image.
6731
6732        The sanitised result is cached and returned by later
6733        :meth:`get_memory` calls. ``mem`` is not modified, so CHIRP's
6734        ``FrozenMemory`` can be passed directly.
6735
6736        Args:
6737            mem: The CHIRP ``Memory`` to store; ``mem.number`` is 1-990.
6738
6739        Raises:
6740            RadioError: If CHIRP is not available, no image is loaded or the
6741                number is out of range.
6742        """
6743        _require_chirp("set_memory")
6744        image = self._require_image()
6745        if not 1 <= mem.number <= len(image.channels):
6746            raise errors.RadioError(f"Memory index {mem.number} out of range")
6747        channel = image.channels[mem.number - 1]
6748        self._apply_memory_to_channel(mem, channel)
6749        # The cache holds the sanitised version that get_memory() returns
6750        # from now on.
6751        sanitized = self._channel_to_memory(mem.number, channel)
6752        self._memory_cache[mem.number] = sanitized
6753    # ------------------------------------------------------------------
6754    # Conversion routines
6755    # ------------------------------------------------------------------
6756
6757    def _channel_to_memory(self, number: int, channel: ChannelRecord):
6758        """Convert a channel record into a CHIRP ``Memory``.
6759
6760        Mode is ``AM`` for AM channels, otherwise ``NFM`` or ``FM`` from the
6761        bandwidth; skip is ``S`` when the channel is not in the scan list.
6762
6763        Args:
6764            number: CHIRP memory number.
6765            channel: The channel record.
6766
6767        Returns:
6768            chirp_common.Memory: The memory (``empty`` if ``rx_hz`` is ``None``).
6769        """
6770        mem = chirp_common.Memory()
6771        mem.number = number
6772        if channel.rx_hz is None:
6773            mem.empty = True
6774            return mem
6775        mem.freq = channel.rx_hz
6776        mem.empty = False
6777        mem.name = (channel.name or "").strip()
6778        self._apply_offset(mem, channel)
6779        self._apply_tones(mem, channel)
6780        if channel.rx_modulation is Modulation.AM:
6781            mem.mode = "AM"
6782        else:
6783            mem.mode = "NFM" if channel.bandwidth is Bandwidth.NARROW else "FM"
6784        mem.power = _POWER_ENUM_TO_CHIRP.get(channel.power, _CHIRP_POWER_LEVELS[0])
6785        mem.skip = "" if channel.scan_add else "S"
6786        mem.extra = _build_memory_extra(channel)
6787        return mem
6788
6789    def _apply_offset(self, mem, channel: ChannelRecord) -> None:
6790        """Derive CHIRP duplex and offset from the RX and TX frequencies.
6791
6792        Equal or missing TX gives simplex. When RX and TX lie in different
6793        bands of ``VALID_BANDS`` (CHIRP's ``chirp_common.is_split``) the
6794        result is ``split`` with the TX frequency as offset, e.g. RX 145.5 /
6795        TX 435.0 MHz. Otherwise ``+`` or ``-`` with the difference as
6796        offset, e.g. RX 145.6 / TX 145.0 MHz gives ``-`` 600 kHz.
6797
6798        Args:
6799            mem: The CHIRP ``Memory`` to update (``duplex``, ``offset`` in Hz).
6800            channel: The channel record providing ``rx_hz`` and ``tx_hz``.
6801        """
6802        if channel.tx_hz is None or channel.tx_hz == channel.rx_hz:
6803            mem.duplex = ""
6804            mem.offset = 0
6805            return
6806        if chirp_common.is_split(VALID_BANDS, channel.rx_hz, channel.tx_hz):
6807            mem.duplex = "split"
6808            mem.offset = channel.tx_hz
6809            return
6810        diff = channel.tx_hz - channel.rx_hz
6811        mem.duplex = "+" if diff > 0 else "-"
6812        mem.offset = abs(diff)
6813
6814    def _apply_tones(self, mem, channel: ChannelRecord) -> None:
6815        """Translate the channel's TX/RX tones into CHIRP tone fields.
6816
6817        Uses CHIRP's ``chirp_common.split_tone_decode``: no tone gives ``""``,
6818        TX CTCSS only ``Tone``, equal TX/RX CTCSS ``TSQL``, equal TX/RX DCS
6819        code ``DTCS``, and every other combination ``Cross`` with the
6820        matching ``cross_mode`` (e.g. ``"->Tone"`` for an RX-only tone). The
6821        radio's inverted DCS polarity ``I`` is given to CHIRP as ``R``. DCS
6822        fields default to a valid code (023) when unused, because CHIRP's CSV
6823        export validates them.
6824
6825        Args:
6826            mem: The CHIRP ``Memory`` to update (``tmode``, ``cross_mode``,
6827                tones, DCS fields).
6828            channel: The channel record providing ``tx_tone`` and ``rx_tone``.
6829        """
6830        # CHIRP's CSV exporter validates DtcsCode/RxDtcsCode even when
6831        # tmode is not DTCS. Use a valid default (e.g. 023) instead of 000
6832        # to avoid exporter errors.
6833        default_dcs = chirp_common.DTCS_CODES[0]
6834        mem.dtcs = default_dcs
6835        mem.rx_dtcs = default_dcs
6836        mem.dtcs_polarity = "NN"
6837        mem.tmode = ""
6838        chirp_common.split_tone_decode(
6839            mem, _tone_to_chirp(channel.tx_tone), _tone_to_chirp(channel.rx_tone))
6840
6841    def _apply_memory_to_channel(self, mem, channel: ChannelRecord) -> None:
6842        """Copy a CHIRP ``Memory`` into a channel record.
6843
6844        An empty memory clears ``rx_hz``, ``tx_hz`` and ``name`` only.
6845        Otherwise frequencies, name, tones, mode, power (unchanged if the
6846        label is unknown) and skip are copied. Band rules: 118-137 MHz is
6847        forced to AM, wide, with ``tx_enabled`` cleared; 18-64 MHz is forced
6848        to FM. ``tx_enabled`` is never set back to True. Learn-FHSS and the
6849        FHSS code are cleared. Scrambler (0-8) and encryption (0-3) come from
6850        the memory's extras; missing or out-of-range values become 0.
6851
6852        Args:
6853            mem: The CHIRP memory.
6854            channel: The record to update in place.
6855        """
6856        if getattr(mem, "empty", False):
6857            channel.rx_hz = None
6858            channel.tx_hz = None
6859            channel.name = ""
6860            return
6861        channel.rx_hz = mem.freq
6862        if mem.duplex == "+":
6863            channel.tx_hz = mem.freq + mem.offset
6864        elif mem.duplex == "-":
6865            channel.tx_hz = mem.freq - mem.offset
6866        elif mem.duplex == "split":
6867            channel.tx_hz = mem.offset
6868        else:
6869            channel.tx_hz = mem.freq
6870        channel.name = (mem.name or "").strip()
6871        self._update_tones_from_memory(mem, channel)
6872
6873        extras = _extract_memory_extra(mem)
6874        scrambler_raw = extras.get('scrambler', getattr(mem, '_rt950_scrambler', None))
6875        encryption_raw = extras.get('encryption', getattr(mem, '_rt950_encryption', None))
6876        try:
6877            channel.scrambler = int(scrambler_raw)
6878        except (TypeError, ValueError):
6879            channel.scrambler = 0
6880        if channel.scrambler < 0 or channel.scrambler > 8:
6881            channel.scrambler = 0
6882        try:
6883            channel.encryption = int(encryption_raw)
6884        except (TypeError, ValueError):
6885            channel.encryption = 0
6886        if channel.encryption not in (0, 1, 2, 3):
6887            channel.encryption = 0
6888        channel.learn_fhss = False
6889        channel.fhss_code = None
6890
6891        mode = (mem.mode or "").upper()
6892        if mode not in {"AM", "FM", "NFM"}:
6893            mode = "AM" if channel.rx_modulation is Modulation.AM else "FM"
6894
6895        # Band-specific constraints
6896        freq = channel.rx_hz or 0
6897        in_airband = 118_000_000 <= freq <= 137_000_000
6898        in_low_hf = 18_000_000 <= freq <= 64_000_000
6899
6900        if in_airband:
6901            # Airband: AM only, TX disabled
6902            channel.rx_modulation = Modulation.AM
6903            channel.bandwidth = Bandwidth.WIDE
6904            channel.tx_enabled = False
6905        elif in_low_hf:
6906            # Low HF: FM only
6907            channel.rx_modulation = Modulation.FM
6908            channel.bandwidth = Bandwidth.NARROW if mode == "NFM" else Bandwidth.WIDE
6909        else:
6910            # Default behavior for VHF/UHF
6911            if mode == "AM":
6912                channel.rx_modulation = Modulation.AM
6913                channel.bandwidth = Bandwidth.WIDE
6914            else:
6915                channel.rx_modulation = Modulation.FM
6916                channel.bandwidth = Bandwidth.NARROW if mode == "NFM" else Bandwidth.WIDE
6917        if isinstance(mem.power, chirp_common.PowerLevel):
6918            key = str(mem.power).upper()
6919        elif isinstance(mem.power, str) and mem.power:
6920            key = mem.power.upper()
6921        else:
6922            key = None
6923        if key and key in _POWER_LABEL_TO_ENUM:
6924            channel.power = _POWER_LABEL_TO_ENUM[key]
6925        channel.scan_add = mem.skip != "S"
6926
6927    def _update_tones_from_memory(self, mem, channel: ChannelRecord) -> None:
6928        """Translate CHIRP tone fields into the channel's TX/RX tones.
6929
6930        Uses CHIRP's ``chirp_common.split_tone_encode``, so every tone mode
6931        including ``Cross`` is honoured (``TSQL`` uses ``ctone`` for TX and
6932        RX, as in CHIRP). CHIRP's reverse polarity ``R`` is stored as the
6933        radio's ``I``. A DCS code of 0 is stored as no tone. ``mem`` is not
6934        modified.
6935
6936        Args:
6937            mem: The CHIRP ``Memory`` to read.
6938            channel: The channel record whose ``tx_tone``/``rx_tone`` are replaced.
6939        """
6940        tx_spec, rx_spec = chirp_common.split_tone_encode(mem)
6941        channel.tx_tone = _tone_from_chirp(*tx_spec)
6942        channel.rx_tone = _tone_from_chirp(*rx_spec)
6943
6944class RT950ProZoneRadio(RT950ProRadio):  # pylint: disable=too-many-ancestors
6945    """One zone of the radio, shown by CHIRP as its own memory tab.
6946
6947    Memory *n* (1-99) in zone *z* is channel ``(z - 1) * 99 + n`` of the
6948    parent radio. All data lives in the parent's :class:`RadioImage`; this
6949    object only maps memory numbers and delegates everything else.
6950    """
6951
6952    # Deliberately no super().__init__(): there is no pipe or file here.
6953    def __init__(  # pylint: disable=super-init-not-called
6954            self, parent: "RT950ProRadio", zone: int) -> None:
6955        """Create the sub-device for one zone.
6956
6957        Args:
6958            parent: The radio that owns the image.
6959            zone: Zone number, 1-10.
6960        """
6961        self._parent = parent
6962        """The radio that owns the image and does all reading and writing."""
6963        self._zone = zone
6964        """Zone number, 1-10."""
6965        self._first = (zone - 1) * ZONE_SIZE
6966        """Offset added to a zone memory number (1-99) to get the parent's
6967        memory number: ``(zone - 1) * 99``."""
6968        self.VARIANT = _zone_label(  # pylint: disable=invalid-name
6969            parent._image, zone)
6970        """Tab title suffix shown by CHIRP (``"1 VHF-LOCAL"``, or ``"Zone 1"``
6971        when unnamed); fixed when the sub-device is created."""
6972        # The attributes below are normally set by CHIRP's constructor,
6973        # which is deliberately not called (see above).
6974        self.pipe = None
6975        """No serial port of its own (CHIRP attribute); the parent talks to
6976        the radio."""
6977        self._mmap = None
6978        """No memory map of its own (CHIRP attribute); see :meth:`get_mmap`."""
6979        self._memobj = None
6980        """No raw memory view of its own (CHIRP attribute)."""
6981        self._metadata = {}
6982        """Empty metadata (CHIRP attribute); CHIRP replaces it with the
6983        parent's ``_metadata[VARIANT]`` via ``link_device_metadata``."""
6984        self._memory_cache = parent._memory_cache
6985        """The parent's memory cache, shared so both views stay in step."""
6986        self.errors = []
6987        """Error list that CHIRP expects on every radio object (CHIRP attribute)."""
6988
6989    @property
6990    def _image(self):  # type: ignore[override]
6991        """Return the parent's image; this sub-device has none of its own."""
6992        return self._parent._image
6993
6994    @_image.setter
6995    def _image(self, value):
6996        """Ignore assignments; the image is owned by the parent radio.
6997
6998        Args:
6999            value: Assigned value; discarded.
7000        """
7001        del value
7002
7003    def get_features(self):  # type: ignore[override]
7004        """Return the parent's features limited to one zone (memories 1-99).
7005
7006        Returns:
7007            chirp_common.RadioFeatures: The parent's features with memory bounds
7008            1-99 and no sub-devices (static or dynamic) or settings.
7009
7010        Raises:
7011            RadioError: If CHIRP is not available.
7012        """
7013        rf = super().get_features()
7014        rf.memory_bounds = (1, ZONE_SIZE)
7015        rf.has_sub_devices = False
7016        if hasattr(rf, 'has_dynamic_subdevices'):
7017            rf.has_dynamic_subdevices = False
7018        rf.has_settings = False
7019        return rf
7020
7021    def get_sub_devices(self):  # type: ignore[override]
7022        """Return no sub-devices; a zone has no zones of its own.
7023
7024        Returns:
7025            list: An empty list.
7026        """
7027        return []
7028
7029    def get_memory(self, number: int):  # type: ignore[override]
7030        """Return memory ``number`` (1-99) of this zone.
7031
7032        Args:
7033            number: Memory number within the zone, 1-99.
7034
7035        Returns:
7036            chirp_common.Memory: A copy of the parent's memory, renumbered to
7037            ``number``.
7038
7039        Raises:
7040            RadioError: If CHIRP is not available, ``number`` is out of range
7041                or no image is loaded.
7042        """
7043        _require_chirp("get_memory")
7044        if not 1 <= number <= ZONE_SIZE:
7045            raise errors.RadioError(f"Memory {number} out of range 1-{ZONE_SIZE}")
7046        mem = self._parent.get_memory(self._first + number).dupe()
7047        mem.number = number
7048        return mem
7049
7050    def set_memory(self, mem):  # type: ignore[override]
7051        """Store ``mem`` (numbered 1-99) in this zone via the parent.
7052
7053        Args:
7054            mem: The CHIRP ``Memory`` to store; it is copied, not modified.
7055
7056        Raises:
7057            RadioError: If CHIRP is not available, the number is out of range
7058                or no image is loaded.
7059        """
7060        _require_chirp("set_memory")
7061        if not 1 <= mem.number <= ZONE_SIZE:
7062            raise errors.RadioError(f"Memory {mem.number} out of range 1-{ZONE_SIZE}")
7063        # CHIRP passes a frozen Memory: never modify it, work on a copy.
7064        glob = mem.dupe()
7065        glob.number = self._first + mem.number
7066        self._parent.set_memory(glob)
7067
7068    def get_mmap(self):  # type: ignore[override]
7069        """Return the parent's memory map.
7070
7071        Returns:
7072            memmap.MemoryMapBytes: The result of the parent's :meth:`get_mmap`.
7073        """
7074        return self._parent.get_mmap()
7075
7076    def save_mmap(self, filename):  # type: ignore[override]
7077        """Save the parent's image.
7078
7079        Args:
7080            filename: Destination ``.img`` file.
7081
7082        Returns:
7083            None: The parent's :meth:`save_mmap` returns nothing.
7084        """
7085        return self._parent.save_mmap(filename)
7086
7087
7088@directory.register
7089class RT950ProDriver(RT950ProRadio):  # pylint: disable=too-many-ancestors
7090    """The class registered in CHIRP's driver directory.
7091
7092    :class:`RT950ProRadio` itself is not registered; it is the shared base
7093    of this class and of :class:`RT950ProZoneRadio`.
7094    """
7095
7096
7097DRIVER_CLASS = RT950ProDriver  # pylint: disable=invalid-name
7098"""Entry point used by loaders that look for a ``DRIVER_CLASS`` name."""

Functional and technical design — radtel_rt950pro.py

Document · names in code font link to the API reference

Functional and technical design (FTO) of the CHIRP driver for the Radtel RT-950 Pro. It describes what the program does (functional part) and how it is built (technical part). The interaction with CHIRP, with sequence diagrams, is in chirp-interface.md; byte-level reference in memory-map.md and protocol.md; every class and function is documented in the API documentation.

Program radtel_rt950pro.py (single file, 7,098 lines)
Version 0.1.8 (2026-11-15)
Radio Radtel RT-950 Pro, firmware 0.24 and later (tested on 0.29)
Reference CPS RT-950PRO_CPS v1.3.3
Licence MIT; © 2025 Nathan G. Barguss (2E0NBS), © 2026 PE1HVH
Status Experimental

Part A — Functional design

A1. Purpose

The driver lets CHIRP read, edit and write the memory of the RT-950 Pro over its USB programming cable, as an alternative to the vendor CPS. Its main point is full support for the radio's channel organisation since firmware 0.24: 10 zones of 99 channels (990 channels) with zone names, each zone shown as its own memory tab in CHIRP.

A2. Users and context

  • Radio amateurs who program the RT-950 Pro with CHIRP on Linux, macOS or Windows.
  • The driver runs inside CHIRP; it has no user interface of its own. It is installed by loading it from CHIRP issue #12180 or by copying it into CHIRP's drivers directory (see README).

A3. Functions

ID Function Read Write Where
F-01 Download the complete memory from the radio, with progress per block ✅ – sync_in
F-02 Upload the edited memory to the radio, with progress per block – ✅ sync_out
F-03 990 channels shown as 10 zone tabs of 99 channels, tab titled with the zone name (Zone CH Mode) ✅ ✅ RT950ProZoneRadio
F-04 Channel fields: RX/TX frequency (simplex, ±offset, split when RX and TX are in different bands), name (12 bytes), CTCSS/DCS, power (3 levels), FM/NFM/AM, scan skip, scrambler, encryption ✅ ✅ _channel_to_memory, _apply_memory_to_channel
F-05 Zone names (10, max. 12 ASCII characters) ✅ ✅ _build_zone_group, encode_zone_names
F-06 VFO A/B/C settings ✅ ✅ _build_vfo_group
F-07 Function settings (27 shown, 57 known) ✅ ✅ _build_function_group
F-08 DTMF: own ID, PTT ID mode, code groups 1–5 (of 22) ✅ ✅ _build_dtmf_group
F-09 Broadcast/modulation settings and FM/AM/SSB memories ✅ ✅ _build_modulation_group
F-10 APRS settings (11 shown, 39 known), written with command 0x58 ✅ ✅ _build_aprs_group, DEFAULT_SEGMENTS
F-11 Save and open CHIRP .img files, including images of older driver versions ✅ ✅ process_mmap, save_mmap
F-12 Band rules: airband 118–137 MHz forced to AM, wide, TX disabled; 18–64 MHz forced to FM – ✅ _apply_memory_to_channel
F-13 Channel Divide (Zone CH Mode / All CH Mode): setting with the CPS labels; the view follows it (All CH Mode: one list 1–990, empty channels stay in place) and changes at once when the setting is changed ✅ ✅ _FUNCTION_UI, _all_channels_mode, get_features, get_sub_devices

A4. Safety rules (functional)

The radio can be damaged or mis-programmed by a wrong write; these rules limit what is written.

ID Rule
S-01 Only data that was read from the radio is written back; unknown bytes are preserved.
S-02 An unedited channel record or VFO entry is written back byte-identical.
S-03 Channels 961–990 (0x7800–0x7BFF) are written only when one of them changed, and never for an image of the old 960-slot driver.
S-04 0x7C00–0x7FFF, 0x9080–0x90FF and anything from 0xE000 are never written.
S-05 Zone names are written only when they were read from 0xC000 (image layout version 4 or later).
S-06 The APRS block is written only when it changed, and as the last block.
S-07 A record that cannot be encoded stops the upload before any byte is sent.
S-08 A failed write names the command and address; a missing ACK on the APRS block gets its own message telling the user what was and was not saved.

A5. Out of scope

  • Firmware with 960 channels (15 zones × 64): channels 961–990 are not written; the driver does not detect the firmware layout (open item).
  • Settings added in CPS 1.3.x (offsets unknown).
  • Function settings not in _FUNCTION_UI, APRS settings not in _APRS_UI, DTMF code groups 6–22: kept, not editable.
  • Banks, live mode, radio detection.
  • Calibration data.

Part B — Technical design

B1. Constraints

Constraint Consequence
CHIRP loads one Python file per driver everything in radtel_rt950pro.py; structure by banner comments and layers
Must import without CHIRP (pydoc, docs/build.py) try: from chirp import … with stand-in classes in the except branch; HAVE_CHIRP is then False; get_features, get_settings, get_memory and set_memory raise RadioError
Must import without pyserial serial = None; CloneSerialTransport.open() then raises CloneTransportError
Python ≥ 3.10; CHIRP and pyserial at run time otherwise standard library only (dataclasses, enum, logging, random, time, typing, unicodedata, pathlib); imports without CHIRP and pyserial
Code quality pylint 10/10 (100 characters), pydocstyle Google convention, pydoclint; CHIRP itself uses 79 characters (reformat before a CHIRP PR)
Documentation Google-style docstrings for every object, public and private; published by docs/build.py

B2. Architecture

Driver layers

The file is divided into six layers, from raw bytes up to CHIRP. Each layer uses only the layers below it; layer 6 drives layer 5 (transport) and layer 4 (image).

Layer Banner Responsibility Main objects
1 Channel records 32-byte channel record and its codecs ToneSetting, ChannelRecord, ToneMode, PowerLevel, Bandwidth, Modulation, _encode/_decode_frequency, _encode/_decode_name, FHSS codec
2 Settings sections one dataclass and one parse_*/encode_* pair per settings block VFOSettings, FunctionSettings, DTMFSettings, ModulationSettings, ModulationChannelEntry, APRSSettings
3 Settings API validated access by key SettingSpec, SettingsError, get_/set_function_value, get_/set_aprs_value, DTMF accessors
4 Image complete clone image ↔ parsed structure RadioImage, parse_zone_names, encode_zone_names, layout constants
5 Transport serial clone protocol CloneSerialTransport, CloneSegment, CloneSerialConfig, CloneTransportError, DEFAULT_SEGMENTS
6 CHIRP integration CHIRP radio classes, memory and settings translation, write plan RT950ProRadio, RT950ProZoneRadio, RT950ProDriver, _WRITE_PLAN, settings builders and apply callbacks, CHIRP stand-ins, MEM_FORMAT

The public API is listed in __all__ (53 names); everything with a leading underscore is internal.

Main classes

B3. Design principles

  1. One source of truth. All data lives in one RadioImage. CHIRP's memory map is parsed into it in process_mmap() and derived from it (_build_clone_payload) on save and upload.
  2. Change tracking instead of re-encoding. ToneSetting, ChannelRecord and VFOSettings remember the bytes they were decoded from (_raw_bytes) and a tuple of their visible fields (_original_state). to_bytes() / encode_vfo_section() return the original bytes while the state is unchanged. After encoding, the new bytes become the reference.
  3. Read-modify-write for settings. Section encoders start from the stored bytes (RadioImage.remainder) and replace only the bits of known fields. The modulation and APRS encoders write a field only when its value differs from what was read, so an unedited block stays byte-identical. One deviation is documented in the code: a field byte holding 0xFF is treated as 0 before its bits are merged.
  4. Write less than you read. The write plan is a filtered, re-ordered subset of the read layout (§B8).
  5. Fail before sending. The complete payload is built before the serial session starts, so encoding errors never leave a half-written radio.

B4. Data model

B4.1 Clone image

Image layout and write plan

The image is the concatenation of DEFAULT_SEGMENTS in read order, 35,456 bytes (_SEGMENT_LENGTH):

Image offset Length Radio address Content Parsed into
0x0000 0x7BC0 0x0000 990 × 32-byte channel records channels
0x7BC0 0x440 0x7BC0 unused channel_extra (verbatim)
0x8000 0x100 0x8000 VFO A/B/C (96 bytes used) vfo
0x8100 0x100 0x9000 function settings (96 used) function
0x8200 0x200 0xA000 DTMF (384 used) dtmf
0x8400 0x200 0xB000 modulation parameters (256 used) modulation
0x8600 0x300 0xD000 modulation names modulation
0x8900 0x80 APRS 0x0000 APRS block aprs
0x8980 0x100 0xC000 zone names, 10 × 16 bytes zone_names

Image offsets differ from radio addresses from 0x8100 on: the image is packed, the radio address space is not.

RadioImage.remainder holds all bytes from image offset 0x8000 as read; encoders use it as the base, so bytes the driver does not understand survive.

B4.2 Channel record (32 bytes)

Offset Field Encoding
0–3 RX frequency packed BCD, 10 Hz units, least significant byte first; all 0x00/0xFF = empty slot
4–7 TX frequency same
8–9 RX tone 00 00 / FF FF off; nn 00 DCS index 1–210 into _DCS_CODES; otherwise CTCSS in 0.1 Hz, little-endian
10–11 TX tone same
12 signalling group low nibble
13 PTT ID low nibble
14 scrambler / power high nibble / low nibble (0 high, 1 medium, 2 low)
15 flags b7 learn FHSS, b6 narrow, b5–4 encryption, b3 busy lockout, b2 scan add, b1 TX enable, b0 AM
16–19 FHSS code byte 19 = 0xA0 when set; bytes 18, 17, 16 = six hex digits
20–31 name GB2312, padded with 0xFF

_DCS_CODES has 210 entries: index 1–105 normal (N), 106–210 inverted (I).

Name encoding (_encode_name): if the name is not GB2312-encodable it is NFKD-normalised and reduced to ASCII; characters that still cannot be encoded are dropped; the result is cut to 12 bytes without splitting a character. Every alteration is logged.

B4.3 Settings sections

Section Dataclass Storage Notes
VFO VFOSettings × 3 typed fields, change tracking frequency 8 digits (10 Hz), offset 7 digits (100 Hz), one decimal digit per byte
Function FunctionSettings.values dict[key → int or None] 57 keys in _FUNCTION_SPECS; mostly low nibble per byte; byte 26 packs work_mode_a/b/c
DTMF DTMFSettings ID (5), PTT ID mode, two timing values, 22 code groups (6 symbols) symbols 0-9 A-D * #, 0xFF terminates
Modulation ModulationSettings + 16 × ModulationChannelEntry global values + FM/AM/SSB memories frequencies in 10 kHz units; names in a separate block
APRS APRSSettings.fields dict[key → int, str or None] 39 keys in _APRS_SPECS; lat/lon as letter + minute/degree/second; altitude signed 16-bit; custom message at offset 79, 40 bytes
Zone names RadioImage.zone_names list[str] × 10 read up to 16 bytes; an edited name is written max. 12, an unedited one as read; padding byte of the slot kept

None in a section means "byte was 0xFF (not set)".

B5. Layer 1 — channel records

  • ChannelRecord.from_bytes() decodes all fields and stores _raw_bytes and _original_state. A power nibble above 2 decodes as LOW.
  • ChannelRecord.to_bytes() returns _raw_bytes when the state is unchanged. Otherwise it rebuilds the record from 0xFF: known fields only, bytes 12 and 13 keep their high nibble (0 when the old byte was 0xFF), the FHSS field is 0xFF × 4 without a code, the name is padded with 0xFF. The new bytes become the reference.
  • ToneSetting follows the same pattern for its two bytes, so an unknown DCS index (decoded as OFF and logged) is written back unchanged unless the tone is edited.
  • Errors (ValueError): record not 32 bytes, non-BCD nibble, frequency not a multiple of 10 Hz or above 8 digits, unknown DCS code, CTCSS out of 0.1–6553.5 Hz, FHSS code not 6 hex digits.

B6. Layers 2 and 3 — settings

Parsing (parse_*_section) takes the used part of a block and returns its dataclass; length errors raise ValueError.

Encoding (encode_*_section(settings, raw)) starts from raw (or 0xFF when raw has the wrong length), returns raw unchanged when settings is None, and otherwise writes only known bits:

Encoder Specific behaviour
encode_vfo_section unchanged entries copied verbatim; rx_hz/offset_hz None keep the stored digits; entries beyond the third ignored
encode_function_section value None or missing key writes 0xFF over the whole byte; byte 26 becomes 0xFF if any work mode is None
encode_dtmf_section own ID and code groups rewritten only when their text changed (a rewritten group gets 0xFF in bytes 6–15); info bytes 6–8 always written to the low nibble
encode_modulation_sections each field compared with the value parsed from the stored blocks and written only when it differs; a global field that is None (not set) is never written; names only when the text changed; entries beyond len(channels) cleared to 0xFF
encode_aprs_section each field and text compared with the value parsed from the stored block and written only when it differs, so unusual stored bytes (hemisphere letters, position digits, altitude, icon) are kept
encode_zone_names unchanged names byte-identical; changed name cut to 12 ASCII characters, padded with the slot's own padding byte (0x00 or 0xFF)

Settings API (layer 3). SettingSpec(kind, min_value, max_value, choices, max_length) describes one setting; _validate() enforces it (bool accepts True/False/0/1, int a range, enum a set of values; strings are checked in set_aprs_value). Violations raise SettingsError (a ValueError); an unknown key raises KeyError. None marks a setting as not set. DTMF has dedicated accessors that check the symbol set and maximum length.

B7. Layer 4 — image

RadioImage.from_bytes(blob):

  1. Rejects data shorter than 0x8000.
  2. Decodes 990 channel records from 0x0000–0x7BBF.
  3. Parses each following section only if the blob is long enough for it; otherwise that section stays None.
  4. Stores remainder = blob[0x8000:] and channel_extra = blob[0x7BC0:0x8000].

RadioImage.to_bytes():

  1. Requires exactly 990 channels.
  2. Pads remainder with 0xFF to the known length (KNOWN_SEGMENT_BYTES).
  3. Re-encodes each section in place within that tail (VFO, function, DTMF, modulation, APRS, zone names).
  4. Builds the channel segment: channel_extra verbatim, then every channel's to_bytes().
  5. Returns channel segment + tail. Side effect: change-tracking snapshots of edited channels and VFO entries are updated.

_build_clone_payload(image) (layer 6) calls to_bytes() and checks the result is exactly _SEGMENT_LENGTH bytes.

B8. Layer 5 — transport

CloneSerialTransport wraps an open port (CHIRP's pipe) or opens one with open(CloneSerialConfig).

Step Bytes Answer Failure
Enter clone mode PROGRAMBT9000U 0x06 Handshake ACK not received
Identify F 16 bytes (logged) time-out
Model M 12 bytes ASCII Radio did not return a model identifier
Key 25-byte SEND frame 0x06 Encryption ACK not received
Read block cmd, hi, lo, 0x80 4 + 128 bytes Serial read timed out
Write block cmd, hi, lo, 0x80 + 128 bytes 0x06 No ACK for write cmd … address …, Write ACK mismatch at …
End E – –

Key selection (_build_encryption_frame): bytes 0–3 SEND; byte 4 a random code 0x10–0x14 or 0x20–0x24; bytes 5–23 random indexes 0–19; byte 24 0x00. Code 0x1n selects frame[5 + 2n], code 0x2n selects frame[6 + 2n]; that byte indexes ENCRYPT_STRINGS (20 four-byte keys). The random source can be injected (rng) for reproducible tests.

XOR (_apply_xor): byte i uses key byte i mod 4; a byte stays unchanged if it is 0x00 or 0xFF, equals the key byte or its complement, or if the key byte is 0x20.

Timing: port time-outs are raised to at least 3 s. During a write the time-out for the ACK is set per block (8 s channels, 10 s from 0x8000, 30 s APRS) and restored after a successful ACK (a failure leaves before the restore); pauses of 0.05 s (from 0x8000) and 0.1 s + 0.5 s (APRS) follow the ACK. Values follow NeonPlug's RT-950 Pro pacing.

Progress: optional progress_cb(done, total, phase) after every block; exceptions in the callback are swallowed so progress can never break a clone.

B9. Layer 6 — CHIRP integration

B9.1 Classes

Class Base Purpose
RT950ProRadio chirp_common.CloneModeRadio all behaviour; memories 1–990
RT950ProDriver RT950ProRadio the registered class (@directory.register); empty
RT950ProZoneRadio RT950ProRadio one zone as a sub-device (Zone CH Mode only); maps 1–99 to the parent; no own data, does not call CHIRP's constructor

B9.2 State of RT950ProRadio

Attribute Set in Meaning
_image process_mmap the parsed RadioImage, or None
_memory_cache get_memory, set_memory; cleared in process_mmap, set_settings Memory objects by number 1–990, shared with the zones
_memobj _parse_memobj bitwise view for the developer Browser tab only
_zone_names_valid process_mmap image size complete and rt950_layout ≥ 4 → zone names may be written
_legacy_960 process_mmap image of the old 960-slot driver → never write 0x7800–0x7BFF
_aprs_original process_mmap APRS block at load time; None disables the APRS write
_high_channels_original process_mmap bytes 0x7800–0x7BFF at load time; None disables writing them
_metadata CHIRP, sync_in image metadata; sync_in sets {'rt950_layout': 4}

__init__ sets all of these before calling CHIRP's constructor, because that constructor may already call process_mmap().

B9.3 Image versions

_LAYOUT_VERSION = 4 is stored in the .img metadata as rt950_layout. process_mmap() recognises: complete images (35,456 bytes) with or without a valid layout version, images without the zone-name segment (35,200), and images of the old 960-slot driver (33,152). Older images are padded with 0xFF so all offsets line up; their zone names are never written, and legacy images never write channels 961–990 (table in chirp-interface.md §6).

B9.4 Memory translation

_channel_to_memory, _apply_offset, _apply_tones (radio → CHIRP) and _apply_memory_to_channel, _update_tones_from_memory (CHIRP → radio). Field and tone mapping tables are in chirp-interface.md §8. Extra per-memory settings (scrambler, encryption) travel in Memory.extra as a RadioSettingGroup (_build_memory_extra, _extract_memory_extra, which accepts a dict as well).

B9.5 Settings UI

The UI tables _FUNCTION_UI (27 keys) and _APRS_UI (11 keys) map a key to label, type (bool, int, enum, string) and range or choices. A _FUNCTION_UI entry with 'volatile': True (only Channel Divide) is marked volatile by _create_function_setting, so CHIRP rebuilds the editor after it is changed (chirp-interface.md §7.4). _build_setting_value() turns an entry into the matching CHIRP value object; _create_function_setting / _create_aprs_setting attach _apply_function_setting / _apply_aprs_setting as callback. VFO, modulation, DTMF and zone names have hand-written builders: VFO lists use one shared builder and callback (_make_list_setting, _apply_list_choice, which leaves a value outside the list unchanged), tones _apply_vfo_tone, frequencies _apply_vfo_frequency (which also sets Freq Band: UHF from 300 MHz) and _apply_vfo_offset; Freq Band is read-only without callback; modulation uses _apply_modulation_int for the three current channels (0–14) and the same list builder for work mode, modulation mode, AM/SSB step and AM/SSB Rx Gain, with the CPS labels; DTMF has one per kind (ID, mode, group), zone names one (_apply_zone_name). Value readers _value_as_bool, _value_as_int, _value_as_index (index or label lookup) and _value_as_string hide the difference between CHIRP's value objects and plain values.

B9.6 Write plan

_WRITE_PLAN lists (index into DEFAULT_SEGMENTS, length) in write order: channels (0x7C00), VFO, function (0x80: only 0x9000–0x907F; the meaning of 0x9080–0x90FF is unknown and the radio changes it), DTMF, modulation parameters, modulation names, zone names, APRS. _write_options() decides three switches; _build_write_plan(payload, write_zone_names, channel_bytes, write_aprs) applies them:

Condition Channels written Zone names APRS Blocks
nothing optional 0x0000–0x77FF no no 257
typical (fresh download, no APRS edit) 0x0000–0x77FF yes no 259
ch. 961–990 edited, APRS edited 0x0000–0x7BFF yes yes (0x58, last) 268

B9.7 Error mapping

Origin Mapped to
any exception in read_clone RadioError('Clone read failed: …')
CloneTransportError with cmd 0x58 RadioError with the APRS explanation
any other exception in the write RadioError('Clone write failed: …')
ValueError in RadioImage.from_bytes RadioError('Failed to parse memory map: …')
exceptions in an apply callback RadioError(message) for function and APRS (all four kinds), partly for DTMF and VFO; modulation-memory frequency raises a plain ValueError (table in chirp-interface §10)
memory number out of range, no image, no port RadioError

Errors are swallowed (broad except Exception) only where a failure must not stop the main operation: progress reporting and Status creation, the Browser view, the snapshots in process_mmap, adjusting port time-outs, closing the port, and the fallbacks of _value_as_int / _value_as_index. Each place is commented in the code.

B10. Processing flows

Flow Steps Diagram
Load driver import → register RT950ProDriver chirp-interface §3
Download transport handshake → 277 blocks → _metadata → process_mmap §4, §5
Open .img metadata match → load_mmap → process_mmap (upgrade) §6
Show memories zone → parent → cache or _channel_to_memory §7
Edit memory zone copy → parent → _apply_memory_to_channel → cache §9
Settings builders → callbacks → sections §10
Save to_bytes → MemoryMapBytes → CHIRP writes file + metadata §11
Upload payload → options → plan → handshake → blocks → E §12

B11. Logging

Logger Name Content
LOG module name driver warnings (old images, parse problems, unknown DCS index), diagnostic text in 0x7BC0–0x7FFF, and the protocol trace of sync_in/sync_out (debug)
CHANNEL_LOG module name + .image decoding and encoding warnings of RadioImage (invalid GB2312, altered or truncated names)
transport default module name + .transport protocol trace when a transport is created without a logger

LOG is first defined in layer 1 (.channel) and rebound in layer 6; functions look it up at call time, so all direct LOG use goes to the final driver logger.

B12. Testing

Tests run against a CHIRP source tree:

git clone https://github.com/kk7ds/chirp ~/src/chirp
CHIRP_SRC=~/src/chirp python3 -m pytest tests

tests/sample.py builds a neutral two-zone image (VHF-LOCAL, UHF-LOCAL, eight invented channels) and loads it as if freshly read.

Test Checks
test_layout_constants 990 channels, 0x7BC0, 0xC000, APRS write command 0x58
test_zone_mapping 10 sub-devices, zone/channel → memory mapping
test_zone_names_and_labels zone names and tab labels
test_untouched_roundtrip_is_byte_identical S-01 / S-02
test_aprs_message_nul_padding custom message NUL padding kept
test_set_memory_does_not_modify_frozen_input zone path does not modify CHIRP's memory
test_zone_name_via_settings zone name edit reaches the saved image
test_edits_reach_saved_image memory edit reaches the saved image
test_plan_unchanged_skips_aprs_and_high_channels S-03 / S-06 without edits
test_plan_writes_high_channels_only_when_changed S-03
test_plan_writes_aprs_last_with_0x58_when_changed S-06
test_old_images_never_write_zone_names S-05
test_legacy_960_image_never_writes_past_0x7800 S-03 for legacy images
test_write_error_names_command_and_address S-08, transport message only (the dedicated APRS RadioError in sync_out is not tested)

tests/test_radio_values.py pins down values measured on a radio with the CPS (encodings from the radio, frequencies invented):

Test Checks
test_vfo_power_decodes_all_three_levels VFO power 0/1/2 decodes as High/Middle/Low
test_settings_apply_without_edit_keeps_vfo_bytes a settings apply without an edit leaves the VFO bytes unchanged (S-02)
test_vfo_screen_follows_cps_labels_and_order VFO-A to VFO-C with the CPS fields in CPS order
test_vfo_screen_shows_measured_values every VFO field shows what the CPS showed for the same bytes
test_vfo_choice_lists_match_cps Step Freq, Tx Power, Scramble, Signalling, Offset Dir, Encryption and tone lists
test_vfo_freq_band_is_read_only Freq Band read-only, no callback
test_vfo_edit_writes_cps_encoding edited step, power, signalling and tone stored as the CPS stores them
test_vfo_value_outside_list_is_left_alone a value the CPS does not offer is shown as unknown and kept
test_channel_encryption_3_is_kept channel encryption 3 and scramble 8
test_side_key_ranges_match_cps PF1 0-7, PF2 0-6
test_aprs_ranges_match_cps Timed Beacon Time 0-9, Radio Symbol 0-4
test_zone_name_of_twelve_characters_loads_and_saves 12-character zone names
test_zone_name_longer_than_twelve_is_shown_and_kept a longer name written by other software loads and is kept
test_vfo_group_builds_with_the_stand_in_classes the VFO group also builds without CHIRP
test_vfo_band_follows_rx_freq Freq Band becomes VHF below and UHF from 300 MHz when Rx Freq is edited
test_modulation_screen_uses_cps_lists modulation labels and lists as in the CPS
test_modulation_edit_and_unset_value an edited modulation list is stored; a value that is not set is shown as such and kept
test_modulation_current_channel_range_matches_decoding current channels 0–14

tests/test_known_issues.py covers the known issues 2–4, 7, 8 and 10 of status.md (1, 6 and 9 are in test_radio_values.py) and three smaller fixes of 0.1.5 (GB2312 cut, DTMF index, function segment):

Test Checks
test_inverted_dcs_reads_as_chirp_reverse_polarity radio I → CHIRP R
test_chirp_reverse_polarity_is_written_as_inverted CHIRP R → radio I
test_mixed_tones_are_shown_as_cross_and_written_back RX-only and mixed tones as CHIRP Cross, written back unchanged (seven cross modes)
test_features_offer_cross_modes Cross and CHIRP's cross modes in the features
test_set_memory_does_not_change_the_callers_memory set_memory leaves CHIRP's memory unchanged
test_edited_channel_keeps_high_nibbles_of_bytes_12_and_13 unused nibbles of an edited channel record kept
test_settings_apply_writes_only_the_changed_setting an apply runs only the callback of the changed setting
test_unset_modulation_block_is_written_back_unchanged an all-0xFF modulation block stays 0xFF
test_modulation_bandwidth_zero_is_kept SSB bandwidth 0 kept
test_unusual_aprs_bytes_are_written_back_unchanged unusual stored APRS bytes kept
test_gb2312_text_is_not_cut_inside_a_character a GB2312 name is cut between characters
test_negative_dtmf_code_group_index_is_refused DTMF code group index below 0 refused
test_function_segment_write_stops_before_0x9080 function segment written as one block (S-04)

tests/test_ident_dump.py checks tools/ident_dump.py against a simulated radio with invented answers:

Test Checks
test_identify_records_all_answers_and_ends_session all four answers recorded; only the handshake string, F, M, the SEND frame and E are sent (5 writes); port closed
test_find_version_reports_answer_and_offset an ASCII version is found with answer number and offset
test_find_version_bcd_and_binary BCD and binary forms are found
test_version_patterns_rejects_bad_input a version that is not <major>.<minor> is refused
test_main_prints_answers hex/ASCII output and search result on the command line
test_empty_expect_is_refused an empty --expect stops with exit code 2
test_version_patterns_rejects_non_ascii_digits non-ASCII digits are refused

tests/test_cleanup.py covers the clean-up of 0.1.6:

Test Checks
test_duplex_follows_the_bands simplex, - 600 kHz, + 7.6 MHz within one band; RX 145.5 / TX 435.0 MHz is split
test_split_channel_round_trips a split channel entered in CHIRP (RX and TX in different bands) is written with TX = offset and read back as split
test_unused_tone_info_class_is_gone _ToneInfo removed
test_without_chirp_the_driver_says_chirp_is_required with CHIRP blocked (subprocess) HAVE_CHIRP is False and get_features, get_settings, get_memory, set_memory raise RadioError naming CHIRP
test_with_chirp_the_flag_is_set HAVE_CHIRP is True with CHIRP
test_find_zone_names_usage_has_a_single_backslash the usage text of find_zone_names.py continues the shell line

tests/test_channel_divide.py covers Channel Divide (values measured on a radio: byte 0x9026, 0 Zone CH Mode, 1 All CH Mode):

Test Checks
test_measured_values constants 0 and 1, offset 0x9026
test_setting_follows_cps_label_and_list label Channel Divide, CPS choices in CPS order, volatile
test_stored_value_is_shown 0 and 1 are shown as the matching choice
test_zone_mode_shows_ten_zone_tabs Zone CH Mode: ten sub-devices of 99, has_dynamic_subdevices
test_all_mode_shows_one_list_of_990 All CH Mode: no sub-devices, bounds 1–990
test_all_mode_numbering_keeps_empty_channels channel n is slot n; empty channels stay in place
test_unset_value_shows_zones_and_is_kept 0xFF shows the zones and is kept without an edit
test_changing_the_setting_switches_view_and_one_byte an edit in both directions changes only 0x9026 and switches the view without a reload
test_all_mode_edit_writes_the_same_slot a memory edited in the single list lands in the same zone slot

tests/test_check_docstrings.py checks tools/check_docstrings.py and the repository itself:

Test Checks
test_reports_public_private_nested_and_stand_in_objects public, private, nested and except-block functions without a docstring are reported
test_reports_missing_module_docstring a module without a docstring is reported
test_main_exit_status exit status 1 with a report line, 0 when complete
test_repository_is_fully_documented the driver, tools/*.py and docs/build.py pass
test_unreadable_file_is_reported_not_raised a file that is not UTF-8 is reported, not a traceback

Tools: tools/make_sample_image.py (sample .img), tools/find_zone_names.py (read-only scan of unread address ranges; found 0xC000), tools/raw_dump.py (read-only dump of the clone image, XOR-decoded, without the driver's encoders), tools/ident_dump.py (read-only: every byte of the handshake answers, with a search for the firmware version), tools/check_docstrings.py (every object has a docstring), tools/chirp_list_left.py (optional CHIRP patch).

B13. Documentation build

docs/build.py builds one page, radtel_rt950pro.html:

  1. Documents. fto.md and chirp-interface.md (list DOCUMENTS) are converted from Markdown with pdoc's markdown2 settings and placed above the API reference, with a Documents group in the side menu. Headings get the anchor GitHub would give them, prefixed per document (design-, interface-), so the same links work on GitHub and on the page. Links to other Markdown files go to GitHub for the branch being built; names in code font are linked to the API by pdoc's linkify; diagrams are copied next to the page and open full size on click. A link between documents to a missing anchor stops the build. Each layer heading of the API links back to its design chapter (B5–B9).
  2. API reference. pdoc renders the module, grouped by the layer and section banners in the source; private objects are included (closed lock) next to public ones (open lock).

The GitHub Action .github/workflows/docs.yml checks the driver's docstrings with pydocstyle, pylint and pydoclint, then builds main into the site root and develop into /develop/ and publishes both to GitHub Pages on every push to either branch. The checks cover the driver, docs/build.py and tools/*.py. pydocstyle only checks public names (in a module with __all__: the names in it); pylint's missing-docstring checks (with no exemption for names starting with _) cover every other module-level class, function and method; neither looks at nested functions. tools/check_docstrings.py closes that gap: it walks the syntax tree and reports every module, class and function without a docstring, nested functions and the CHIRP stand-ins in the except branch included. The Action runs it only in a checkout that contains it (0.1.6 and later), so an older main still builds.

Diagrams. The SVG files in docs/diagrams are generated, not drawn by hand:

Script Writes
tools/make_diagrams.py the sequence diagrams seq-01 to seq-09, one function per diagram, rendered with tools/seqsvg.py
tools/make_fto_diagrams.py the structure diagrams fto-layers, fto-classes and fto-write-plan

After changing a diagram, run both from the repository root and check the result in a browser (text widths are estimated, positions are fixed):

python3 tools/make_diagrams.py
python3 tools/make_fto_diagrams.py

Both write to docs/diagrams by default, or to the directory given as the first argument. Only the standard library is needed.

B14. Known issues and observations

Known issues are listed in status.md; they are not repeated here. Still open: a VFO tone with a DCS index the driver does not know, which is shown as OFF (choosing OFF then does not clear it). Known issues 1–4 and 6–10 are fixed in 0.1.5, each with a test; the unused _ToneInfo (5) is removed in 0.1.6.

Additional observations from the interface analysis (snapshots not refreshed after an upload, comments lost after a zone rename, progress text past channel 990, repeated payload builds, comments that differ per Channel Divide view) are in chirp-interface.md §15.

B15. Open items

From status.md:

  • a VFO tone with a DCS index the driver does not know is shown as OFF;
  • find out what 0x9080–0x90FF is;
  • detect the firmware layout (960 vs 990 channels) before writing;
  • compare the handshake with CHIRP's RT-920 driver;
  • await the maintainers' response to the proposal in #12180.

The route to official CHIRP support (subclass of the RT-920 driver, GPLv3, test image) is described separately in status.md.


Glossary

Term Meaning
ACK 0x06, the radio's acknowledgement of a command or block
Block 0x80 (128) bytes, the unit of every read and write
Clone image / .img the complete memory as CHIRP stores it, plus CHIRP metadata
CPS the vendor's programming software (RT-950PRO_CPS)
Payload the 35,456 image bytes in DEFAULT_SEGMENTS order
Segment a contiguous address range with its read and write command (CloneSegment)
Slot 0-based channel position 0–989 in RadioImage.channels
Sub-device a CHIRP radio object that shows part of a radio as its own tab (here: a zone)
VARIANT CHIRP's variant name; for a zone the tab suffix, e.g. 1 VHF-LOCAL
Write plan the ordered, filtered list of segments sent on upload
XOR key one of 20 four-byte strings selected during the handshake

CHIRP ↔ driver interface

Document · names in code font link to the API reference

This document describes how CHIRP and the RT-950 Pro driver (radtel_rt950pro.py) work together: which CHIRP calls reach the driver, in which order, what the driver does with them, and what it hands back. The driver's internal design is described in fto.md; the byte layout in memory-map.md and the wire protocol in protocol.md.

Driver radtel_rt950pro.py, version 0.1.8 (2026-11-15)
CHIRP reference kk7ds/chirp at commit 0a9be8e (2026-10-17), wxPython UI (chirp/wxui); the rebuild of the editor after a volatile setting (§7.4) checked at commit c604141 (2026-10-23)
Radio Radtel RT-950 Pro, firmware 0.29 (10 zones × 99 channels)

The CHIRP behaviour described here was read from the CHIRP source at the commit above (chirp/chirp_common.py, chirp/directory.py, chirp/settings.py, chirp/wxui/main.py, clone.py, memedit.py, settingsedit.py). Other CHIRP versions may differ in detail.


1. Overview

CHIRP treats the RT-950 Pro as a clone-mode radio: the whole memory is downloaded into an image, edited offline, and uploaded again. The driver plugs into CHIRP through one registered class and, in Zone CH Mode, ten sub-devices (in All CH Mode CHIRP uses the registered class itself as the only memory list; see §7.4):

Object Role towards CHIRP
RT950ProDriver The class registered with @directory.register. CHIRP instantiates it for Download, for Open of an .img file, and keeps it as the radio behind the editor. It adds nothing to RT950ProRadio.
RT950ProRadio Shared base class with all behaviour: clone (sync_in/sync_out), image handling (process_mmap, get_mmap, save_mmap), memories 1–990, settings, sub-devices. Subclass of chirp_common.CloneModeRadio.
RT950ProZoneRadio One object per zone (10), only in Zone CH Mode. CHIRP shows each as a memory tab with memories 1–99. It owns no data: every call is mapped to the parent's memory (zone − 1) × 99 + n.

All channel and settings data lives in one RadioImage object owned by the parent (RT950ProRadio._image). CHIRP's own memory map (_mmap) is rebuilt from that object when the image is saved; an upload builds its own payload from it.

1.1 Entry points

CHIRP action CHIRP calls Driver method(s) Diagram
Start CHIRP / Load module from issue import_drivers() / load_module() module import, @directory.register 1
Radio → Download from radio RT950ProDriver(serial), sync_in() __init__, sync_in, process_mmap 2, 3
File → Open .img get_radio_by_image() → DynamicRadioAlias(filename) __init__, process_mmap 8
Editor opens get_features(), get_sub_devices(), link_device_metadata() get_features, get_sub_devices 4
Show a row get_memory(n) on the zone RT950ProZoneRadio.get_memory → RT950ProRadio.get_memory 4
Edit / delete a row set_memory(FrozenMemory) / erase_memory(n) on the zone RT950ProZoneRadio.set_memory → RT950ProRadio.set_memory 5
Settings tab get_settings(), set_settings(copy) get_settings, set_settings + apply callbacks 6
File → Save save(filename) save_mmap 7
Radio → Upload to radio set_pipe(serial), sync_out() sync_out, _write_options, _build_write_plan 9
Developer Browser tab reads radio._memobj _parse_memobj (MEM_FORMAT), run in process_mmap, save_mmap, sync_out –

2. What the driver declares

2.1 Class attributes

Attribute Value Used by CHIRP for
VENDOR "Radtel" radio list, image metadata, driver id
MODEL "RT-950 Pro" radio list, image metadata, driver id
BAUD_RATE 115200 opening the serial port
_memsize 35,456 (_SEGMENT_LENGTH) get_memsize(), radio-info dialog only

The directory id built by CHIRP (radio_class_id) is Radtel_RT-950_Pro.

2.2 get_features()

Feature Parent (RT950ProRadio) Zone (RT950ProZoneRadio)
memory_bounds (1, 990) (1, 99)
has_sub_devices True in Zone CH Mode, False in All CH Mode (§7.4) False
has_dynamic_subdevices True (left out on CHIRP versions without it) False
has_settings True False
has_bank, has_bank_names False False
has_name, valid_name_length True, 12 same
valid_characters chirp_common.CHARSET_ASCII same
valid_modes FM, NFM, AM same
valid_tmodes "", Tone, TSQL, DTCS, Cross same
has_cross, valid_cross_modes True, chirp_common.CROSS_MODES same
valid_duplexes "", +, -, split (can_odd_split) same
valid_dtcs_pols NN, NR, RN, RR same
valid_dtcs_codes chirp_common.DTCS_CODES same
valid_power_levels Low 1 W, Medium 5 W, High 10 W (nominal) same
valid_skips "", S same
valid_bands 18–64, 70–118, 118–137, 136–174, 174–400, 400–480, 480–580 MHz same
has_tuning_step, has_nostep_tuning False, True: no tuning step required (0.1.8) same
has_comment not set (CHIRP default False) same

The radio stores frequencies in 10 Hz units and has no per-channel tuning step. With has_nostep_tuning CHIRP's validate_memory() skips its two step checks, so a frequency such as UK CB 27.60125 MHz (10 kHz raster, 1.25 kHz offset) can be pasted, edited and imported. CHIRP's airband check (108–137 MHz) still applies: there a frequency must be on the 25 kHz or 8.33 kHz raster, so e.g. 118.020 MHz is refused. The driver's own validate_memory() adds an error for an RX or TX frequency that is not a multiple of 10 Hz, before set_memory() would fail on it. Up to 0.1.7 the driver set valid_tuning_steps to 2.5–25 kHz, which refused such channels (issue 12180).

Because has_comment is False, CHIRP keeps memory comments itself, in the image metadata (mem_extra), not in the radio (see §7.3).


3. Loading the driver

Loading and registering the driver

There are two ways in, as described in the README:

  1. Load module from issue (#12180). CHIRP saves the chosen attachment to a temporary file (loaded-<attachment id>-….py) and calls load_module(). That first calls directory.enable_reregistrations(), so the module may replace a driver with the same id, then executes the file as chirp.loaded.<temporary file name>. The module is gone when CHIRP exits.
  2. Copy into chirp/drivers/. At start-up directory.import_drivers() imports every *.py in that directory. The Windows installer build does not scan the directory (it imports the names in chirp.drivers.__all__), so this route does not work there.

Executing the module:

  • defines layers 1–5 (standard library only);
  • at the start of layer 6 imports chirp_common, directory, errors, memmap, bitwise and chirp.settings. If that import fails (no CHIRP, e.g. pydoc), the module defines small stand-ins so it still imports (§14);
  • defines the rest of layer 6;
  • registers RT950ProDriver with @directory.register. RT950ProRadio itself is not registered;
  • sets DRIVER_CLASS = RT950ProDriver for loaders that look for that name.

4. Download from the radio

Download from radio

  1. CHIRP's download dialog opens the port and first calls detect_from_serial(). The driver does not implement detection, so the default raises NotImplementedError and CHIRP keeps the chosen class.
  2. CHIRP creates RT950ProDriver(serial). The driver's __init__ sets its own state before calling CHIRP's constructor, because CHIRP's constructor may call process_mmap() (it does so for a file name or a MemoryMapBytes; for a serial port it resets errors, _mmap, _memobj, _metadata and stores self.pipe).
  3. CHIRP's CloneThread sets radio.status_fn and runs sync_in() in a background thread.
  4. sync_in() wraps the port in a CloneSerialTransport (read and write time-outs raised to at least 3 s), attaches a progress callback and calls read_clone(). The transport reads all DEFAULT_SEGMENTS: 277 blocks of 0x80 bytes, 35,456 bytes in total.
  5. After every block the progress callback converts the block count into a chirp_common.Status and calls status_fn. Messages are Reading channels 001-004… for the channel segment (4 channels per block) and Reading VFO settings…, Reading Zone names… etc. for the others.
  6. On success the driver stores the bytes as MemoryMapBytes, replaces _metadata with {'rt950_layout': 4} and calls process_mmap() (§6).
  7. Any exception in the read is re-raised as errors.RadioError('Clone read failed: …'), which CHIRP shows in the dialog. CHIRP closes the port in all cases.

Read order (= image order, DEFAULT_SEGMENTS):

# Command Address Length Blocks Content
0 0x52 0x0000 0x8000 256 channels 1–990 + 0x7BC0–0x7FFF
1 0x52 0x8000 0x100 2 VFO A/B/C
2 0x52 0x9000 0x100 2 function settings
3 0x52 0xA000 0x200 4 DTMF
4 0x52 0xB000 0x200 4 modulation parameters
5 0x52 0xD000 0x300 6 modulation names
6 0x54 APRS 0x0000 0x80 1 APRS (separate address space)
7 0x52 0xC000 0x100 2 zone names

5. Clone session on the wire

Clone session on the wire

CloneSerialTransport implements the session for both directions:

  • Handshake: PROGRAMBT9000U → 0x06; F → 16 bytes (only logged); M → 12-byte model string (an empty string is an error); a 25-byte SEND frame that selects one of 20 four-byte XOR keys (ENCRYPT_STRINGS) → 0x06.
  • Read block: cmd, addr_hi, addr_lo, 0x80 → 4-byte header + 128 bytes; the payload is XOR-decoded.
  • Write block: header + XOR-encoded 128 bytes → 0x06. The ACK time-out is 8 s below 0x8000, 10 s from 0x8000, 30 s for command 0x58; after the ACK the driver pauses 0.05 s (from 0x8000) or 0.1 s + 0.5 s (APRS).
  • End: E. It is sent only after the last block; when a block fails, the exception leaves the loop before E is sent.

XOR rule: a payload byte is left unchanged when it is 0x00 or 0xFF, equal to the key byte or its complement, or when the key byte is a space (0x20). The operation is its own inverse.


6. Opening an .img file (process_mmap)

Opening an image

directory.get_radio_by_image() strips CHIRP's metadata block from the file and matches vendor / model against the registered classes. For a match it creates a DynamicRadioAlias — a subclass of RT950ProDriver with the vendor, model and variant from the file — with the file name. CHIRP's constructor calls load_mmap(), which sets _metadata from the file and _mmap to the image bytes, and then calls the driver's process_mmap().

process_mmap() recognises three image sizes (four cases), so that images from earlier driver versions still open safely:

Image size (bytes) Origin Action Effect on upload
35,456 with rt950_layout ≥ 4 downloaded with this driver (layout version 4) none; _zone_names_valid = True zone names written
35,456 without / older rt950_layout earlier driver version, from before zone names were read at 0xC000 zone-name segment replaced by 0xFF; warning logged zone names not written
35,200 (_MEMSIZE_V1) 990 channels, no zone-name segment 0xFF × 0x100 appended zone names not written
33,152 (_LEGACY_MEMSIZE) old 960-slot driver 0xFF × 0x800 inserted at 0x7800, zone segment appended; _legacy_960 = True 0x7800–0x7BFF never written

When the bytes are adapted, CHIRP's _mmap is replaced by the adapted version, so a later save writes the new size.

Then:

  1. RadioImage.from_bytes() parses the 990 channel records and every section that fits in the data. A ValueError (image too short, invalid BCD digit, …) becomes errors.RadioError('Failed to parse memory map: …').
  2. The memory cache is cleared, the developer Browser view is rebuilt (bitwise.parse(MEM_FORMAT, _mmap), never fatal) and printable text in 0x7BC0–0x7FFF is logged (diagnostic only).
  3. Two snapshots are taken from a freshly built payload: the APRS block (_aprs_original) and bytes 0x7800–0x7BFF (_high_channels_original). They decide later whether these parts are uploaded (§12). If building the payload fails, both stay None, which disables both writes.

The same process_mmap() runs after a download (§4), always with the current layout version.


7. The editor: zones as sub-devices

Opening the editor

7.1 Tabs

ChirpEditorSet asks the parent for its features. In Zone CH Mode has_sub_devices is set, so it calls get_sub_devices() and gets ten new RT950ProZoneRadio objects (All CH Mode: §7.4). Each one:

  • stores the parent, its zone number and _first = (zone − 1) × 99;
  • sets VARIANT from the zone name: "1 VHF-LOCAL" for a named zone, "Zone 1" for an empty name. CHIRP uses it in the tab title Memories (1 VHF-LOCAL);
  • shares the parent's _memory_cache and reads the parent's image through the _image property (assignments to _image on a zone are ignored);
  • deliberately does not call CHIRP's constructor: it has no port, file or memory map of its own. It sets the attributes CHIRP expects (pipe, _mmap, _memobj, _metadata, errors) itself.

CHIRP then calls link_device_metadata(zones), which points each zone's _metadata at parent._metadata[VARIANT], so per-zone data ends up in the parent's image metadata when saving. With more than two devices, or with has_dynamic_subdevices set (always, since 0.1.7), CHIRP uses a wx.Treebook, which puts the tab list on the right (the optional tools/chirp_list_left.py patch moves it).

As has_settings is set on the parent, CHIRP also creates a settings editor for the parent radio (§10).

7.2 Memory numbering

View Numbers Mapping
Zone tab z (Zone CH Mode) 1–99 parent memory (z − 1) × 99 + n
Single list (All CH Mode) 1–990 the parent itself: memory n is radio channel n
Parent (driver API, tests) 1–990 slot number − 1 in RadioImage.channels
Radio address – (number − 1) × 32

RT950ProZoneRadio.get_memory(n) asks the parent for memory _first + n, takes a dupe() and renumbers it to n. The parent builds the Memory with _channel_to_memory() on first use and caches it by its 1–990 number until the memory, the settings or the image change.

7.3 Memory comments

The driver does not store comments. CHIRP's ExternalMemoryProperties (get_memory_extra / set_memory_extra) keeps them in the zone's _metadata['mem_extra'], which is linked to parent._metadata[VARIANT] and saved in the .img metadata. They are never sent to the radio. In All CH Mode CHIRP keeps them in the parent's own _metadata['mem_extra'], by memory number 1–990 (see §15, item 6).

7.4 Channel Divide: zone tabs or one list

The radio setting Channel Divide (function byte 0x9026: 0 Zone CH Mode, 1 All CH Mode, measured with the CPS) decides the view. The driver reads it from the image in _all_channels_mode(); only 1 counts as All CH Mode, so 0xFF (not set) or an unknown value gives the zone view.

Zone CH Mode All CH Mode
get_features().has_sub_devices True False
get_sub_devices() ten RT950ProZoneRadio []
What CHIRP shows ten zone tabs, memories 1–99 one list Memories: the parent, memories 1–990
Empty channels empty rows in their zone empty rows at their place in 1–990; nothing is moved up

The channel records are the same in both modes; only the numbering in the view differs (§7.2).

In the settings the setting is a list Channel Divide (Function Settings) with the CPS choices Zone CH Mode and All CH Mode. It is marked volatile (RadioSetting.set_volatile(True)), and get_features() sets has_dynamic_subdevices. When the user changes it, CHIRP (settingsedit.py, common.py):

  1. shows "Changing this setting requires refreshing the settings from the image, which will happen now.";
  2. calls set_settings(), which stores the new value in the image (one byte) — synchronously for a clone-mode radio;
  3. because has_dynamic_subdevices is set, posts an EditorRefresh event; _reload_editorset() in main.py builds a new ChirpEditorSet for the same radio object and file name, keeps the modified flag, and replaces the old one. The new editor set calls get_features() and get_sub_devices() again, so it shows the other view.

Nothing is saved or reread from disk; unsaved edits stay in the image. On a CHIRP version without has_dynamic_subdevices the driver leaves the flag out; CHIRP then only refreshes the settings tab, and the new view appears after the image is saved and reopened.


8. Memory ↔ channel record mapping

8.1 Radio → CHIRP (_channel_to_memory)

CHIRP Memory field Source in ChannelRecord
empty True when rx_hz is None (RX frequency bytes all 0x00/0xFF); nothing else is filled
freq rx_hz
duplex, offset TX missing or equal to RX → "", 0; RX and TX in different bands of VALID_BANDS (chirp_common.is_split) → split, TX frequency; otherwise TX above RX → +, difference; TX below RX → -, difference
name name, stripped
tmode, rtone, ctone, dtcs, rx_dtcs, dtcs_polarity see §8.3
mode AM if rx_modulation is AM, else NFM (narrow) or FM (wide)
power PowerLevel → Low / Medium / High
skip "" if scan_add, else S
extra group RT-950 Pro Extras: scrambler (0–8), encryption (0–3)

Not shown in CHIRP but kept: signalling group, PTT ID, busy lockout, TX-enable flag, and learn-FHSS and FHSS code until the memory is edited (they are then cleared, §8.2). An unedited record is written back byte for byte (§9).

8.2 CHIRP → radio (_apply_memory_to_channel)

ChannelRecord field From Memory
rx_hz, tx_hz, name empty memory: None, None, "" (other fields unchanged)
rx_hz freq
tx_hz +: freq + offset; -: freq − offset; split: offset; else freq
name name, stripped (encoded later as GB2312, max. 12 bytes)
tx_tone, rx_tone see §8.3
scrambler extra['scrambler'], 0–8, otherwise 0
encryption extra['encryption'], 0–3, otherwise 0
learn_fhss, fhss_code always cleared
rx_modulation, bandwidth 118–137 MHz: AM, wide, tx_enabled = False; 18–64 MHz: FM, narrow for NFM; otherwise AM/wide for AM, FM narrow/wide for NFM/FM
power CHIRP label Low/Medium/High; unknown label leaves it unchanged
scan_add skip != "S"

tx_enabled is only ever cleared (airband), never set back to True.

8.3 Tones

Both directions use CHIRP's own helpers, so every CHIRP tone mode including Cross is supported (has_cross = True, valid_cross_modes = chirp_common.CROSS_MODES).

Radio → CHIRP (_apply_tones): each radio tone becomes a CHIRP tone spec (_tone_to_chirp) and chirp_common.split_tone_decode picks the mode:

TX tone RX tone CHIRP result
off off tmode = ""
CTCSS off Tone, rtone = TX
CTCSS same CTCSS TSQL, ctone = TX tone
DCS same DCS code DTCS, dtcs = the code (rx_dtcs stays 023), polarity TX + RX
any other combination Cross with the matching cross_mode, e.g. ->Tone (RX tone only), DTCS-> (TX DCS only), Tone->Tone (two different CTCSS tones), DTCS->Tone, Tone->DTCS, DTCS->DTCS (two different codes)

The radio's inverted DCS polarity I is given to CHIRP as reverse R; normal stays N. dtcs and rx_dtcs are set to a valid code (023) and the polarity to NN first, because CHIRP's CSV export checks them even when tmode is not DTCS.

CHIRP → radio (_update_tones_from_memory): chirp_common.split_tone_encode gives a TX and an RX tone spec for every mode, including Cross; each spec becomes a radio tone (_tone_from_chirp). CHIRP's R is stored as the radio's I. A DCS code of 0 is stored as no tone. The CHIRP memory is not modified.

In CHIRP's memory grid, choosing Cross as Tone Mode opens a dialog that asks for the cross mode; in the memory's Properties dialog all tone fields can be set at once.


9. Editing and deleting a memory

Editing a memory

  • CHIRP's memory editor wraps the edited memory in FrozenMemory(mem, strict=False) and calls set_memory() on the zone. The zone checks the number (1–99), takes a dupe(), renumbers it to (zone − 1) × 99 + n and passes the copy to the parent, so CHIRP's frozen object is never modified on this path.
  • The parent checks the number (1–990), updates the ChannelRecord in place (§8.2), converts the record back to a Memory and caches that sanitised version. CHIRP's refresh (get_memory) shows it, so the user sees what will actually be written (e.g. AM forced in the airband).
  • The record now differs from its _original_state; at the next to_bytes() it is rebuilt from its fields instead of returning the original 32 bytes.
  • Deleting uses CHIRP's default Radio.erase_memory(): it builds Memory(number=n, empty=True) and calls the zone's set_memory(). The driver then clears RX, TX and name only; the RX frequency 0xFF × 4 marks the slot empty on the radio.

No serial traffic happens while editing; everything changes the in-memory RadioImage only.


10. Settings

Settings

CHIRP calls get_settings() the first time the Settings tab is selected. The driver builds a RadioSettings tree from the image; a group is left out when its section is missing from the image (VFO also when the list is empty), except Zone Names, which is always present:

Group Builder Content
VFO Profiles _build_vfo_group per VFO (VFO-A to VFO-C) the fields of the CPS VFO Mode screen, with its labels, choices and order: Rx Freq, Rx QT/DQT, Tx QT/DQT, Busy Lockout, Offset Dir, Signalling, Tx Power, Scramble, Bandwidth, Encryption, RxModulation, Freq Band (read-only), Step Freq, Offset Freq
Broadcast/Modulation _build_modulation_group current FM/AM/SSB channel, work mode, modulation mode, AM/SSB step and RX gain; FM, AM and SSB memories (frequency, name; SSB also bandwidth and beat offset)
Function Settings _build_function_group the 27 keys of _FUNCTION_UI (squelch, VOX, time-out, beeps, display modes, …, Channel Divide)
APRS Settings _build_aprs_group the 11 keys of _APRS_UI (enable, GPS, callsign, SSID, priority, custom message, …)
DTMF Settings _build_dtmf_group own ID, PTT ID mode, code groups 1–5 (of 22)
Zone Names _build_zone_group ten strings, max. 12 ASCII characters

Every RadioSetting gets an apply callback bound to the object it changes (a VFOSettings entry, the FunctionSettings, APRSSettings, DTMFSettings, ModulationSettings, or the RadioImage for zone names).

When the user changes a value, CHIRP puts the new value into its settings tree, makes a copy.deepcopy() of the tree, removes immutable and uninitialised settings, and calls set_settings(copy). The driver walks the tree and runs the apply callback only of settings whose changed() is True; CHIRP marks a setting as changed once its value has been set in this editor session, and the mark stays until CHIRP rebuilds the settings tab with get_settings() (for example when the image is reopened). A setting object without changed() always has its callback run. The callbacks still update the driver's own objects: CHIRP stores the callback as a closure (lambda: callback(self, *args)), and deepcopy keeps functions by reference, so the closure still refers to the original setting and section objects. The callbacks validate through the settings API (set_function_value, set_aprs_value, set_dtmf_*). Error wrapping differs per group:

Callbacks Wrapped into errors.RadioError
_apply_function_setting, _apply_aprs_setting SettingsError, KeyError, IndexError, ValueError
_apply_dtmf_id, _apply_dtmf_mode SettingsError
_apply_dtmf_group SettingsError, IndexError
_apply_vfo_frequency, _apply_vfo_offset ValueError
_apply_modulation_channel_frequency none: an invalid frequency raises a plain ValueError

CHIRP shows any exception from set_settings() as an error dialog. Because the callbacks run in tree order, an exception also stops the callbacks after it. If all succeed, the memory cache is cleared.

Because only changed settings are applied, opening the Settings tab and applying an edit of one setting leaves all other settings as they were read. The list callbacks (VFO, modulation) also store a value only when the chosen label is one of the offered choices, so a stored value shown as Unknown (<value>) is kept. Two VFO values are not shown as unknown: a power nibble above 2 is read as Low, and a tone with a DCS index the driver does not know is shown as OFF.

A renamed zone gets its new tab title only when the sub-devices are created again, i.e. after the image is reopened (or after Channel Divide is changed, which rebuilds the editor; §7.4).


11. Saving an .img file

Saving an image

CHIRP's save() calls save_mmap(). The driver first rebuilds CHIRP's memory map from the RadioImage (_refresh_mmap → _build_clone_payload → RadioImage.to_bytes()), then lets CHIRP's CloneModeRadio.save_mmap() write the file:

[35,456 image bytes] [MAGIC b'\x00\xffchirp\xeeimg\x00\x01'] [base64(JSON metadata)]

The metadata contains CHIRP's own keys (rclass, vendor, model, variant, chirp_version), the driver's rt950_layout (when the image came from a download, or from a file that already had it) and one entry per zone VARIANT with that zone's mem_extra comments.

to_bytes() writes unedited channel records and VFO entries back byte-identical and keeps 0x7BC0–0x7FFF and unknown bytes. The modulation and APRS encoders compare each field with the bytes that were read and write only the fields that were edited, so an unedited image is saved byte-identical. An edited channel record keeps the high nibbles of bytes 12 and 13, which the driver does not use.


12. Upload to the radio

Upload to radio

CHIRP's upload dialog opens the port, calls set_pipe(serial) on the radio that is open in the editor and runs sync_out() in a CloneThread.

  1. sync_out() refuses to start without a port or an image (RadioError).
  2. It builds the complete payload. A record that cannot be encoded raises ValueError here, before anything is sent.
  3. _write_options() decides the optional parts:

    Option Rule
    channel_bytes 0x7C00 (channels 1–990) only when bytes 0x7800–0x7BFF differ from the snapshot taken in process_mmap() and the image is not a legacy 960-slot image; otherwise 0x7800 (channels 1–960)
    write_zone_names _zone_names_valid (zone names were read from 0xC000)
    write_aprs the APRS block differs from its snapshot
  4. _build_write_plan() cuts the payload into segments in _WRITE_PLAN order: channels, VFO, function, DTMF, modulation parameters, modulation names, zone names, APRS last. Of the function segment only 0x9000–0x907F is written (one block); 0x9080–0x90FF is left to the radio, see memory-map.md. That is 257 blocks minimum (no zone names, no APRS), 259 typically, 268 maximum.

    Write plan

  5. write_clone() performs the handshake and writes block by block; the progress callback reports Writing channels … / Writing Zone names….

  6. Errors:
    • a missing ACK on the APRS block (message contains cmd 0x58) → RadioError('All channels, settings and zone names were written, but the radio did not acknowledge the APRS block (cmd 0x58); APRS changes may NOT be saved. Power-cycle the radio and read back.');
    • any other failure → RadioError('Clone write failed: …'), e.g. No ACK for write cmd 0x57 address 0xC000 (Serial read timed out). This includes a wrong ACK byte on the APRS block (Write ACK mismatch at 0x0000: …), which does not contain cmd 0x58.
  7. On success CHIRP's memory map is replaced by the payload that was built in step 2.

Never written: 0x7C00–0x7FFF, 0x9080–0x90FF and anything from 0xE000.


13. Errors and logging

Situation Raised in driver What CHIRP shows
Serial time-out, missing or wrong ACK, short write CloneTransportError wrapped: Clone read failed: … / Clone write failed: …
APRS block: no ACK CloneTransportError (cmd 0x58) dedicated RadioError message (§12)
APRS block: wrong ACK byte CloneTransportError (Write ACK mismatch) generic Clone write failed: …
No port / no image RadioError message in the clone dialog
Image cannot be parsed ValueError → RadioError('Failed to parse memory map: …') open fails
Memory number out of range RadioError row error
Setting value rejected SettingsError etc., mostly wrapped in RadioError (§10) error dialog in the settings tab
Record cannot be encoded (e.g. an unsupported CTCSS tone) ValueError save / upload fails before sending

Loggers are named after the module: chirp.drivers.radtel_rt950pro when copied into the driver directory, chirp.loaded.<file name> when loaded as a module (from the issue that is a temporary loaded-… name):

  • the module name itself (LOG): driver messages and, because sync_in() and sync_out() pass logger=LOG to the transport, also the protocol trace at debug level (commands, addresses, XOR key);
  • ….image (CHANNEL_LOG): decode and encode warnings of RadioImage, such as altered channel names;
  • ….transport: only used when a transport is created without a logger (external callers; the tools and tests in this repository pass LOG).

Inside CHIRP these messages appear in CHIRP's debug log.


14. Running without CHIRP

When from chirp import … fails, the module defines minimal stand-ins for chirp_common (Memory, RadioFeatures, CloneModeRadio, PowerLevel, format_freq, parse_freq), directory.register, errors.RadioError, memmap.MemoryMapBytes and the chirp.settings classes. They exist so that pydoc and docs/build.py can import the module. There is no bitwise stand-in, so _parse_memobj() fails silently and _memobj stays None. The stand-ins lack, among others, chirp_common.Status, DTCS_CODES, CHARSET_ASCII, CROSS_MODES, is_split and split_tone_decode/encode. HAVE_CHIRP is then False, and get_features(), get_settings(), get_memory() and set_memory() raise RadioError ("… needs CHIRP …") before using them; other methods may fail with AttributeError. The tests in tests/ therefore run against a CHIRP source tree (CHIRP_SRC); tests/test_cleanup.py checks the error in a subprocess with CHIRP blocked.


15. Observations from this analysis

Found while tracing the interface; not in the known-issues list of status.md and not changed in the code.

  1. Snapshots are not refreshed after an upload. _aprs_original and _high_channels_original are only set in process_mmap(). After a successful sync_out() the driver replaces _mmap but keeps the old snapshots, so a second upload in the same session writes the APRS block (and 0x7800–0x7BFF) again if they differ from the download, even when nothing changed since the first upload. Effect: an extra, slow APRS write; no wrong data.
  2. Zone rename and memory comments. CHIRP stores memory comments under the zone's VARIANT (§7.3), and VARIANT contains the zone name. After a rename, a save and a reopen, the zone has a new VARIANT, so comments saved under the old name are no longer found (they remain in the file's metadata).
  3. Progress text past channel 990. The channel segment is read as 256 blocks, but blocks 249–256 (0x7C00–0x7FFF) contain no channels. The read progress then shows Reading channels 993-990… up to Reading channels 1021-990…. Cosmetic.
  4. Repeated work in sync_out(). With a status callback, _write_options() runs three times and the payload is built four times (once in sync_out(), once in each _write_options() call). Correct but redundant.
  5. Developer Browser tab is a snapshot. CHIRP's Browser reads radio._memobj, which is rebuilt only in process_mmap(), save_mmap() and after sync_out(). After a memory or settings edit it shows the old bytes until the next save or upload. Edits made in the Browser are never parsed back into the RadioImage and are overwritten by the next _refresh_mmap().
  6. Memory comments differ per view. CHIRP keys comments by memory number in the metadata of the device that shows the memory (§7.3): in Zone CH Mode per zone (_metadata[VARIANT], numbers 1–99), in All CH Mode in the parent (numbers 1–990). A comment made in one view is not shown in the other (it remains in the file's metadata).

Sources

  • Driver: radtel_rt950pro.py 0.1.6, docs/memory-map.md, docs/protocol.md, docs/status.md.
  • CHIRP: kk7ds/chirp at commit 0a9be8e — chirp/chirp_common.py (CloneModeRadio, ExternalMemoryProperties, Radio.erase_memory), chirp/directory.py (register, get_radio_by_image, import_drivers), chirp/settings.py (RadioSetting.set_apply_callback), chirp/wxui/main.py (ChirpEditorSet, load_module), chirp/wxui/clone.py (CloneThread, download and upload dialogs), chirp/wxui/memedit.py (set_memory, erase_memory), chirp/wxui/settingsedit.py (_changed).
  • CHIRP issue #12180.

API reference

Every class, function, method, field and constant, public and private, grouped by driver layer.

1. Channel records

ToneSetting, ChannelRecord and the BCD/GB2312 codecs for the 32-byte channel structure.

Public class class ToneMode(enum.Enum):
416class ToneMode(Enum):
417    """Kind of sub-audio tone used by a channel for transmit or receive."""
418
419    OFF = "off"
420    """No tone; carrier squelch."""
421    CTCSS = "ctcss"
422    """Analog sub-audio tone (``ctcss_hz``)."""
423    DCS = "dcs"
424    """Digital coded squelch (``dcs_code`` and ``dcs_polarity``)."""

Kind of sub-audio tone used by a channel for transmit or receive.

Fields
Public field OFF = <ToneMode.OFF: 'off'>

No tone; carrier squelch.

Public field CTCSS = <ToneMode.CTCSS: 'ctcss'>

Analog sub-audio tone (ctcss_hz).

Public field DCS = <ToneMode.DCS: 'dcs'>

Digital coded squelch (dcs_code and dcs_polarity).

Public class
@dataclass(slots=True)
class ToneSetting:
427@dataclass(slots=True)
428class ToneSetting:
429    """Transmit or receive tone of one channel or VFO.
430
431    The radio stores a tone in two bytes:
432
433    * ``00 00`` (or ``FF FF``): no tone.
434    * ``nn 00``: DCS, ``nn`` is a 1-based index into ``_DCS_CODES``.
435    * otherwise: CTCSS in tenths of a hertz, little-endian.
436
437    An instance remembers the bytes it was decoded from. As long as the
438    tone is not changed, :meth:`to_bytes` returns those original bytes, so
439    unknown encodings survive a read/write cycle unchanged.
440    """
441
442    mode: ToneMode
443    """Tone kind."""
444    ctcss_hz: Optional[float] = None
445    """CTCSS frequency in Hz when ``mode`` is CTCSS."""
446    dcs_code: Optional[int] = None
447    """DCS code as an octal-looking integer (e.g. ``23`` for D023) when
448    ``mode`` is DCS.
449    """
450    dcs_polarity: Optional[str] = None
451    """``"N"`` (normal) or ``"I"`` (inverted) for DCS."""
452    _raw_bytes: bytes = field(default=b"", repr=False, compare=False)
453    """The two bytes this tone was decoded from (empty for a new tone).
454    Returned unchanged by :meth:`to_bytes` while the tone is not edited.
455    """
456    _original_state: Optional[tuple] = field(
457        default=None, repr=False, compare=False)
458    """``(mode, ctcss_hz, dcs_code, dcs_polarity)`` when the tone was
459    created or last encoded; compared with the current state to detect an
460    edit.
461    """
462
463    def __post_init__(self) -> None:
464        """Snapshot the initial state for change tracking."""
465        if self._original_state is None:
466            object.__setattr__(self, "_original_state", self._state_tuple())
467
468    def _state_tuple(self) -> tuple:
469        """Return the user-visible fields as a tuple for change detection.
470
471        Returns:
472            tuple: ``(mode, ctcss_hz, dcs_code, dcs_polarity)``.
473        """
474        return (
475            self.mode,
476            self.ctcss_hz,
477            self.dcs_code,
478            self.dcs_polarity,
479        )
480
481    @property
482    def is_off(self) -> bool:
483        """Whether no tone is set (``mode`` is OFF)."""
484        return self.mode is ToneMode.OFF
485
486    @classmethod
487    def off(cls) -> "ToneSetting":
488        """Create a tone setting without a tone.
489
490        Returns:
491            ToneSetting: A setting with ``mode`` OFF.
492        """
493        return cls(ToneMode.OFF)
494
495    @classmethod
496    def ctcss(cls, hz: float) -> "ToneSetting":
497        """Create a CTCSS tone setting.
498
499        Args:
500            hz: CTCSS frequency in hertz, e.g. ``88.5``.
501
502        Returns:
503            ToneSetting: A setting with ``mode`` CTCSS.
504        """
505        return cls(ToneMode.CTCSS, ctcss_hz=hz)
506
507    @classmethod
508    def dcs(cls, code: int, polarity: str) -> "ToneSetting":
509        """Create a DCS tone setting.
510
511        Args:
512            code: DCS code as written, e.g. ``23`` for D023.
513            polarity: ``"N"`` or ``"I"`` (case-insensitive).
514
515        Returns:
516            ToneSetting: A setting with ``mode`` DCS.
517        """
518        return cls(ToneMode.DCS, dcs_code=code, dcs_polarity=polarity.upper())
519
520    def to_display(self) -> str:
521        """Format the tone the way the CPS shows it.
522
523        Returns:
524            str: ``"OFF"``, a CTCSS value such as ``"88.5"`` or a DCS code
525            such as ``"D023N"``.
526        """
527        if self.mode is ToneMode.OFF:
528            return "OFF"
529        if self.mode is ToneMode.CTCSS and self.ctcss_hz is not None:
530            return f"{self.ctcss_hz:.1f}"
531        if (self.mode is ToneMode.DCS and self.dcs_code is not None
532                and self.dcs_polarity):
533            return f"D{self.dcs_code:03}{self.dcs_polarity.upper()}"
534        return "OFF"
535
536    def to_bytes(self) -> bytes:
537        """Encode the tone into the radio's two-byte format.
538
539        Unchanged tones return the bytes they were decoded from. A DCS or
540        CTCSS tone without a code, polarity or frequency encodes as ``00 00``
541        (no tone). After encoding, the new bytes become the reference for
542        the next change check.
543
544        Returns:
545            bytes: Two bytes as stored in a channel or VFO record.
546
547        Raises:
548            ValueError: If the DCS code is not in ``_DCS_CODES`` or the
549                CTCSS value is not within 0.1-6553.5 Hz.
550        """
551        current_state = self._state_tuple()
552        if (
553            self._original_state is not None
554            and current_state == self._original_state
555            and self._raw_bytes
556        ):
557            return self._raw_bytes
558
559        if self.mode is ToneMode.OFF:
560            result = b"\x00\x00"
561        elif self.mode is ToneMode.DCS and self.dcs_code is not None and self.dcs_polarity:
562            token = f"D{self.dcs_code:03}{self.dcs_polarity.upper()}"
563            try:
564                index = _DCS_CODES.index(token)
565            except ValueError as exc:
566                raise ValueError(f"Unsupported DCS code {token}") from exc
567            result = bytes((index + 1, 0x00))
568        elif self.mode is ToneMode.CTCSS and self.ctcss_hz is not None:
569            value = int(round(self.ctcss_hz * 10))
570            if value <= 0 or value > 0xFFFF:
571                raise ValueError(f"CTCSS value out of range: {self.ctcss_hz}")
572            result = bytes((value & 0xFF, (value >> 8) & 0xFF))
573        else:
574            result = b"\x00\x00"
575
576        object.__setattr__(self, "_raw_bytes", result)
577        object.__setattr__(self, "_original_state", current_state)
578        return result
579
580    @staticmethod
581    def from_bytes(raw: bytes) -> "ToneSetting":
582        """Decode a two-byte tone field.
583
584        Unknown DCS indexes are logged and decoded as OFF; the original bytes
585        are kept, so they are written back unchanged unless the tone is edited.
586
587        Args:
588            raw: The two tone bytes from a channel or VFO record.
589
590        Returns:
591            ToneSetting: The decoded tone, remembering ``raw``.
592
593        Raises:
594            ValueError: If ``raw`` is not exactly two bytes long.
595        """
596        if len(raw) != 2:
597            raise ValueError("Tone bytes must be length 2")
598        first, second = raw
599        if first == 0 and second == 0:
600            setting = ToneSetting.off()
601        elif second == 0:
602            index = first
603            if 1 <= index <= len(_DCS_CODES):
604                token = _DCS_CODES[index - 1]
605                code = int(token[1:4])
606                polarity = token[4]
607                setting = ToneSetting.dcs(code, polarity)
608            else:
609                LOG.warning("Unknown DCS index %s", index)
610                setting = ToneSetting.off()
611        else:
612            value = (second << 8) | first
613            if value == 0xFFFF:
614                setting = ToneSetting.off()
615            else:
616                hz = value / 10.0
617                setting = ToneSetting.ctcss(hz)
618
619        object.__setattr__(setting, "_raw_bytes", bytes(raw))
620        object.__setattr__(setting, "_original_state", setting._state_tuple())
621        return setting

Transmit or receive tone of one channel or VFO.

The radio stores a tone in two bytes:

  • 00 00 (or FF FF): no tone.
  • nn 00: DCS, nn is a 1-based index into _DCS_CODES.
  • otherwise: CTCSS in tenths of a hertz, little-endian.

An instance remembers the bytes it was decoded from. As long as the tone is not changed, to_bytes() returns those original bytes, so unknown encodings survive a read/write cycle unchanged.

Fields
Public field mode: ToneMode

Tone kind.

Public field ctcss_hz: Optional[float]

CTCSS frequency in Hz when mode is CTCSS.

Public field dcs_code: Optional[int]

DCS code as an octal-looking integer (e.g. 23 for D023) when mode is DCS.

Public field dcs_polarity: Optional[str]

"N" (normal) or "I" (inverted) for DCS.

Private field _raw_bytes: bytes

The two bytes this tone was decoded from (empty for a new tone). Returned unchanged by to_bytes() while the tone is not edited.

Private field _original_state: Optional[tuple]

(mode, ctcss_hz, dcs_code, dcs_polarity) when the tone was created or last encoded; compared with the current state to detect an edit.

Properties
Public property is_off: bool
481    @property
482    def is_off(self) -> bool:
483        """Whether no tone is set (``mode`` is OFF)."""
484        return self.mode is ToneMode.OFF

Whether no tone is set (mode is OFF).

Methods
Public method def __post_init__(self) -> None:
463    def __post_init__(self) -> None:
464        """Snapshot the initial state for change tracking."""
465        if self._original_state is None:
466            object.__setattr__(self, "_original_state", self._state_tuple())

Snapshot the initial state for change tracking.

Public method
@classmethod
def off(cls) -> ToneSetting:
486    @classmethod
487    def off(cls) -> "ToneSetting":
488        """Create a tone setting without a tone.
489
490        Returns:
491            ToneSetting: A setting with ``mode`` OFF.
492        """
493        return cls(ToneMode.OFF)

Create a tone setting without a tone.

Returns:

ToneSetting: A setting with mode OFF.

Public method
@classmethod
def ctcss(cls, hz: float) -> ToneSetting:
495    @classmethod
496    def ctcss(cls, hz: float) -> "ToneSetting":
497        """Create a CTCSS tone setting.
498
499        Args:
500            hz: CTCSS frequency in hertz, e.g. ``88.5``.
501
502        Returns:
503            ToneSetting: A setting with ``mode`` CTCSS.
504        """
505        return cls(ToneMode.CTCSS, ctcss_hz=hz)

Create a CTCSS tone setting.

Arguments:
  • hz: CTCSS frequency in hertz, e.g. 88.5.
Returns:

ToneSetting: A setting with mode CTCSS.

Public method
@classmethod
def dcs(cls, code: int, polarity: str) -> ToneSetting:
507    @classmethod
508    def dcs(cls, code: int, polarity: str) -> "ToneSetting":
509        """Create a DCS tone setting.
510
511        Args:
512            code: DCS code as written, e.g. ``23`` for D023.
513            polarity: ``"N"`` or ``"I"`` (case-insensitive).
514
515        Returns:
516            ToneSetting: A setting with ``mode`` DCS.
517        """
518        return cls(ToneMode.DCS, dcs_code=code, dcs_polarity=polarity.upper())

Create a DCS tone setting.

Arguments:
  • code: DCS code as written, e.g. 23 for D023.
  • polarity: "N" or "I" (case-insensitive).
Returns:

ToneSetting: A setting with mode DCS.

Public method def to_display(self) -> str:
520    def to_display(self) -> str:
521        """Format the tone the way the CPS shows it.
522
523        Returns:
524            str: ``"OFF"``, a CTCSS value such as ``"88.5"`` or a DCS code
525            such as ``"D023N"``.
526        """
527        if self.mode is ToneMode.OFF:
528            return "OFF"
529        if self.mode is ToneMode.CTCSS and self.ctcss_hz is not None:
530            return f"{self.ctcss_hz:.1f}"
531        if (self.mode is ToneMode.DCS and self.dcs_code is not None
532                and self.dcs_polarity):
533            return f"D{self.dcs_code:03}{self.dcs_polarity.upper()}"
534        return "OFF"

Format the tone the way the CPS shows it.

Returns:

str: "OFF", a CTCSS value such as "88.5" or a DCS code such as "D023N".

Public method def to_bytes(self) -> bytes:
536    def to_bytes(self) -> bytes:
537        """Encode the tone into the radio's two-byte format.
538
539        Unchanged tones return the bytes they were decoded from. A DCS or
540        CTCSS tone without a code, polarity or frequency encodes as ``00 00``
541        (no tone). After encoding, the new bytes become the reference for
542        the next change check.
543
544        Returns:
545            bytes: Two bytes as stored in a channel or VFO record.
546
547        Raises:
548            ValueError: If the DCS code is not in ``_DCS_CODES`` or the
549                CTCSS value is not within 0.1-6553.5 Hz.
550        """
551        current_state = self._state_tuple()
552        if (
553            self._original_state is not None
554            and current_state == self._original_state
555            and self._raw_bytes
556        ):
557            return self._raw_bytes
558
559        if self.mode is ToneMode.OFF:
560            result = b"\x00\x00"
561        elif self.mode is ToneMode.DCS and self.dcs_code is not None and self.dcs_polarity:
562            token = f"D{self.dcs_code:03}{self.dcs_polarity.upper()}"
563            try:
564                index = _DCS_CODES.index(token)
565            except ValueError as exc:
566                raise ValueError(f"Unsupported DCS code {token}") from exc
567            result = bytes((index + 1, 0x00))
568        elif self.mode is ToneMode.CTCSS and self.ctcss_hz is not None:
569            value = int(round(self.ctcss_hz * 10))
570            if value <= 0 or value > 0xFFFF:
571                raise ValueError(f"CTCSS value out of range: {self.ctcss_hz}")
572            result = bytes((value & 0xFF, (value >> 8) & 0xFF))
573        else:
574            result = b"\x00\x00"
575
576        object.__setattr__(self, "_raw_bytes", result)
577        object.__setattr__(self, "_original_state", current_state)
578        return result

Encode the tone into the radio's two-byte format.

Unchanged tones return the bytes they were decoded from. A DCS or CTCSS tone without a code, polarity or frequency encodes as 00 00 (no tone). After encoding, the new bytes become the reference for the next change check.

Returns:

bytes: Two bytes as stored in a channel or VFO record.

Raises:
  • ValueError: If the DCS code is not in _DCS_CODES or the CTCSS value is not within 0.1-6553.5 Hz.
Public method
@staticmethod
def from_bytes(raw: bytes) -> ToneSetting:
580    @staticmethod
581    def from_bytes(raw: bytes) -> "ToneSetting":
582        """Decode a two-byte tone field.
583
584        Unknown DCS indexes are logged and decoded as OFF; the original bytes
585        are kept, so they are written back unchanged unless the tone is edited.
586
587        Args:
588            raw: The two tone bytes from a channel or VFO record.
589
590        Returns:
591            ToneSetting: The decoded tone, remembering ``raw``.
592
593        Raises:
594            ValueError: If ``raw`` is not exactly two bytes long.
595        """
596        if len(raw) != 2:
597            raise ValueError("Tone bytes must be length 2")
598        first, second = raw
599        if first == 0 and second == 0:
600            setting = ToneSetting.off()
601        elif second == 0:
602            index = first
603            if 1 <= index <= len(_DCS_CODES):
604                token = _DCS_CODES[index - 1]
605                code = int(token[1:4])
606                polarity = token[4]
607                setting = ToneSetting.dcs(code, polarity)
608            else:
609                LOG.warning("Unknown DCS index %s", index)
610                setting = ToneSetting.off()
611        else:
612            value = (second << 8) | first
613            if value == 0xFFFF:
614                setting = ToneSetting.off()
615            else:
616                hz = value / 10.0
617                setting = ToneSetting.ctcss(hz)
618
619        object.__setattr__(setting, "_raw_bytes", bytes(raw))
620        object.__setattr__(setting, "_original_state", setting._state_tuple())
621        return setting

Decode a two-byte tone field.

Unknown DCS indexes are logged and decoded as OFF; the original bytes are kept, so they are written back unchanged unless the tone is edited.

Arguments:
  • raw: The two tone bytes from a channel or VFO record.
Returns:

ToneSetting: The decoded tone, remembering raw.

Raises:
  • ValueError: If raw is not exactly two bytes long.
Private method def _state_tuple(self) -> tuple:
468    def _state_tuple(self) -> tuple:
469        """Return the user-visible fields as a tuple for change detection.
470
471        Returns:
472            tuple: ``(mode, ctcss_hz, dcs_code, dcs_polarity)``.
473        """
474        return (
475            self.mode,
476            self.ctcss_hz,
477            self.dcs_code,
478            self.dcs_polarity,
479        )

Return the user-visible fields as a tuple for change detection.

Returns:

tuple: (mode, ctcss_hz, dcs_code, dcs_polarity).

Public class class PowerLevel(enum.Enum):
623class PowerLevel(Enum):
624    """Transmit power as stored in the low nibble of channel byte 14."""
625
626    HIGH = 0
627    """High power (stored value 0)."""
628    MEDIUM = 1
629    """Medium power (stored value 1)."""
630    LOW = 2
631    """Low power (stored value 2)."""

Transmit power as stored in the low nibble of channel byte 14.

Fields
Public field HIGH = <PowerLevel.HIGH: 0>

High power (stored value 0).

Public field MEDIUM = <PowerLevel.MEDIUM: 1>

Medium power (stored value 1).

Public field LOW = <PowerLevel.LOW: 2>

Low power (stored value 2).

Public class class Bandwidth(enum.Enum):
633class Bandwidth(Enum):
634    """FM channel bandwidth (bit 6 of the channel flags byte).
635
636    Note:
637        The enum values do not equal the stored bit; the codecs translate.
638    """
639
640    NARROW = 0
641    """Narrow FM, 12.5 kHz; stored as bit 6 = 1."""
642    WIDE = 1
643    """Wide FM, 25 kHz; stored as bit 6 = 0."""

FM channel bandwidth (bit 6 of the channel flags byte).

Note:

The enum values do not equal the stored bit; the codecs translate.

Fields
Public field NARROW = <Bandwidth.NARROW: 0>

Narrow FM, 12.5 kHz; stored as bit 6 = 1.

Public field WIDE = <Bandwidth.WIDE: 1>

Wide FM, 25 kHz; stored as bit 6 = 0.

Public class class Modulation(enum.Enum):
645class Modulation(Enum):
646    """Receive modulation (bit 0 of the channel flags byte)."""
647
648    FM = 0
649    """Frequency modulation; stored as bit 0 = 0."""
650    AM = 1
651    """Amplitude modulation, e.g. airband; stored as bit 0 = 1."""

Receive modulation (bit 0 of the channel flags byte).

Fields
Public field FM = <Modulation.FM: 0>

Frequency modulation; stored as bit 0 = 0.

Public field AM = <Modulation.AM: 1>

Amplitude modulation, e.g. airband; stored as bit 0 = 1.

Public class
@dataclass(slots=True)
class ChannelRecord:
653@dataclass(slots=True)
654class ChannelRecord:
655    """One 32-byte memory channel.
656
657    Byte layout:
658
659        0-3    RX frequency, packed BCD, 10 Hz units, little-endian
660        4-7    TX frequency, same format
661        8-9    RX tone (see ToneSetting)
662        10-11  TX tone
663        12     signalling group (low nibble); high nibble unknown, kept
664        13     PTT ID (low nibble); high nibble unknown, kept
665        14     scrambler (high nibble) | power (low nibble)
666        15     flags: b7 learn FHSS, b6 narrow, b5-4 encryption,
667               b3 busy lockout, b2 scan add, b1 TX enabled, b0 AM
668        16-19  FHSS code (byte 3 == 0xA0 when set)
669        20-31  name, GB2312, padded with 0xFF
670
671    An unchanged record serialises to exactly the bytes it was read from.
672    """
673
674    rx_hz: Optional[int]
675    """Receive frequency in Hz, or ``None`` for an empty slot."""
676    tx_hz: Optional[int]
677    """Transmit frequency in Hz, or ``None``."""
678    rx_tone: ToneSetting
679    """Receive (decode) tone."""
680    tx_tone: ToneSetting
681    """Transmit (encode) tone."""
682    signalling_group: int
683    """DTMF signalling group, 0-15."""
684    ptt_id: int
685    """PTT ID mode, 0-15."""
686    power: PowerLevel
687    """Transmit power."""
688    scrambler: int
689    """Scrambler code, 0-15 (0 = off)."""
690    learn_fhss: bool
691    """Learn-FHSS flag."""
692    bandwidth: Bandwidth
693    """FM bandwidth."""
694    encryption: int
695    """Encryption mode, 0-3 (0 = off)."""
696    busy_lockout: bool
697    """Busy-channel lockout."""
698    scan_add: bool
699    """``True`` if the channel is included in scanning."""
700    tx_enabled: bool
701    """TX-enable flag as stored by the radio."""
702    rx_modulation: Modulation
703    """Receive modulation."""
704    fhss_code: Optional[str]
705    """Six hex digits, or ``None``."""
706    name: str
707    """Channel name, up to 12 bytes in GB2312."""
708    _raw_bytes: bytes = field(default=b"", repr=False, compare=False)
709    """The 32 bytes this record was decoded from (empty for a new record).
710    Returned unchanged by :meth:`to_bytes` while the record is not edited,
711    so unknown bits survive a read/write cycle.
712    """
713    _original_state: Optional[tuple] = field(default=None, repr=False, compare=False)
714    """Result of ``_state_tuple()`` when the record was decoded or last
715    encoded, or ``None`` for a new record; used to detect an edit.
716    """
717
718    @classmethod
719    def from_bytes(cls, data: bytes, *, logger: Optional[logging.Logger] = None) -> "ChannelRecord":
720        """Parse a raw 32-byte channel record.
721
722        A power nibble above 2 is decoded as LOW; the raw bytes are kept, so
723        they are written back unchanged unless the record is edited.
724
725        Args:
726            data: Exactly 32 bytes from the channel area.
727            logger: Logger for name-decoding warnings; defaults to ``LOG``.
728
729        Returns:
730            ChannelRecord: The decoded record, remembering ``data``.
731
732        Raises:
733            ValueError: If ``data`` is not 32 bytes or holds invalid BCD.
734        """
735        if len(data) != 32:
736            raise ValueError("Channel record must be exactly 32 bytes")
737        logger = logger or LOG
738        rx_hz = _decode_frequency(data[0:4])
739        tx_hz = _decode_frequency(data[4:8])
740        rx_tone = ToneSetting.from_bytes(data[8:10])
741        tx_tone = ToneSetting.from_bytes(data[10:12])
742        signalling_group = data[12] & 0x0F
743        ptt_id = data[13] & 0x0F
744        power = PowerLevel(min(data[14] & 0x0F, 2))
745        scrambler = (data[14] >> 4) & 0x0F
746        flags = data[15]
747        learn_fhss = bool(flags & 0x80)
748        # Radio uses bit6: 1 = NARROW, 0 = WIDE
749        bandwidth = Bandwidth.NARROW if ((flags >> 6) & 0x01) else Bandwidth.WIDE
750        encryption = (flags >> 4) & 0x03
751        busy_lockout = bool(flags & 0x08)
752        scan_add = bool(flags & 0x04)
753        tx_enabled = bool(flags & 0x02)
754        rx_modulation = Modulation(flags & 0x01)
755        fhss_code = _decode_fhss_code(data[16:20])
756        name = _decode_name(data[20:32], logger)
757        record = cls(
758            rx_hz=rx_hz,
759            tx_hz=tx_hz,
760            rx_tone=rx_tone,
761            tx_tone=tx_tone,
762            signalling_group=signalling_group,
763            ptt_id=ptt_id,
764            power=power,
765            scrambler=scrambler,
766            learn_fhss=learn_fhss,
767            bandwidth=bandwidth,
768            encryption=encryption,
769            busy_lockout=busy_lockout,
770            scan_add=scan_add,
771            tx_enabled=tx_enabled,
772            rx_modulation=rx_modulation,
773            fhss_code=fhss_code,
774            name=name,
775        )
776        record._raw_bytes = bytes(data)
777        record._original_state = record._state_tuple()
778        return record
779
780    def to_bytes(self, *, logger: Optional[logging.Logger] = None) -> bytes:
781        """Serialise the record into the radio's 32-byte format.
782
783        An unchanged record returns its original bytes. A changed record is
784        rebuilt from scratch; the new bytes then become the reference for the
785        next change check. Rebuilding writes the known fields; the high
786        nibbles of bytes 12 and 13 (meaning unknown) are taken from the
787        original bytes (0 if that byte was 0xFF), the FHSS field becomes
788        0xFF x 4 when no code is set, and the name is padded with 0xFF.
789
790        Args:
791            logger: Logger for name-encoding warnings; defaults to ``LOG``.
792
793        Returns:
794            bytes: 32 bytes ready to be written to the channel area.
795
796        Raises:
797            ValueError: If a frequency, tone or FHSS code cannot be encoded.
798        """
799        logger = logger or LOG
800
801        current_state = self._state_tuple()
802        if self._original_state is not None and current_state == self._original_state:
803            if self._raw_bytes:
804                return self._raw_bytes
805
806        buf = bytearray(b"\xFF" * 32)
807        buf[0:4] = _encode_frequency(self.rx_hz)
808        buf[4:8] = _encode_frequency(self.tx_hz)
809        buf[8:10] = self.rx_tone.to_bytes()
810        buf[10:12] = self.tx_tone.to_bytes()
811        # Keep the high nibbles of bytes 12-13 (meaning unknown) from the
812        # bytes this record was decoded from; 0xFF counts as 0.
813        old = self._raw_bytes if len(self._raw_bytes) == 32 else b""
814        high12 = old[12] & 0xF0 if old and old[12] != 0xFF else 0
815        high13 = old[13] & 0xF0 if old and old[13] != 0xFF else 0
816        buf[12] = high12 | (self.signalling_group & 0x0F)
817        buf[13] = high13 | (self.ptt_id & 0x0F)
818        scram = self.scrambler & 0x0F
819        power_value = self.power.value & 0x0F
820        buf[14] = (scram << 4) | power_value
821        flags = 0
822        if self.learn_fhss:
823            flags |= 0x80
824        # Radio uses bit6: 1 = NARROW, 0 = WIDE
825        if self.bandwidth is Bandwidth.NARROW:
826            flags |= 0x40
827        flags |= (self.encryption & 0x03) << 4
828        if self.busy_lockout:
829            flags |= 0x08
830        if self.scan_add:
831            flags |= 0x04
832        if self.tx_enabled:
833            flags |= 0x02
834        if self.rx_modulation is Modulation.AM:
835            flags |= 0x01
836        buf[15] = flags
837        buf[16:20] = _encode_fhss_code(self.fhss_code)
838        buf[20:32] = _encode_name(self.name, logger)
839        result = bytes(buf)
840        self._raw_bytes = result
841        self._original_state = current_state
842        return result
843
844    def _state_tuple(self) -> tuple:
845        """Return all user-visible fields as a tuple for change detection.
846
847        Returns:
848            tuple: The field values, with tones reduced to their own state
849            tuples.
850        """
851        return (
852            self.rx_hz,
853            self.tx_hz,
854            self.rx_tone._state_tuple(),
855            self.tx_tone._state_tuple(),
856            self.signalling_group,
857            self.ptt_id,
858            self.power,
859            self.scrambler,
860            self.learn_fhss,
861            self.bandwidth,
862            self.encryption,
863            self.busy_lockout,
864            self.scan_add,
865            self.tx_enabled,
866            self.rx_modulation,
867            self.fhss_code,
868            self.name,
869        )

One 32-byte memory channel.

Byte layout:

0-3 RX frequency, packed BCD, 10 Hz units, little-endian 4-7 TX frequency, same format 8-9 RX tone (see ToneSetting) 10-11 TX tone 12 signalling group (low nibble); high nibble unknown, kept 13 PTT ID (low nibble); high nibble unknown, kept 14 scrambler (high nibble) | power (low nibble) 15 flags: b7 learn FHSS, b6 narrow, b5-4 encryption, b3 busy lockout, b2 scan add, b1 TX enabled, b0 AM 16-19 FHSS code (byte 3 == 0xA0 when set) 20-31 name, GB2312, padded with 0xFF

An unchanged record serialises to exactly the bytes it was read from.

Fields
Public field rx_hz: Optional[int]

Receive frequency in Hz, or None for an empty slot.

Public field tx_hz: Optional[int]

Transmit frequency in Hz, or None.

Public field rx_tone: ToneSetting

Receive (decode) tone.

Public field tx_tone: ToneSetting

Transmit (encode) tone.

Public field signalling_group: int

DTMF signalling group, 0-15.

Public field ptt_id: int

PTT ID mode, 0-15.

Public field power: PowerLevel

Transmit power.

Public field scrambler: int

Scrambler code, 0-15 (0 = off).

Public field learn_fhss: bool

Learn-FHSS flag.

Public field bandwidth: Bandwidth

FM bandwidth.

Public field encryption: int

Encryption mode, 0-3 (0 = off).

Public field busy_lockout: bool

Busy-channel lockout.

Public field scan_add: bool

True if the channel is included in scanning.

Public field tx_enabled: bool

TX-enable flag as stored by the radio.

Public field rx_modulation: Modulation

Receive modulation.

Public field fhss_code: Optional[str]

Six hex digits, or None.

Public field name: str

Channel name, up to 12 bytes in GB2312.

Private field _raw_bytes: bytes

The 32 bytes this record was decoded from (empty for a new record). Returned unchanged by to_bytes() while the record is not edited, so unknown bits survive a read/write cycle.

Private field _original_state: Optional[tuple]

Result of _state_tuple() when the record was decoded or last encoded, or None for a new record; used to detect an edit.

Methods
Public method
@classmethod
def from_bytes( cls, data: bytes, *, logger: Optional[logging.Logger] = None) -> ChannelRecord:
718    @classmethod
719    def from_bytes(cls, data: bytes, *, logger: Optional[logging.Logger] = None) -> "ChannelRecord":
720        """Parse a raw 32-byte channel record.
721
722        A power nibble above 2 is decoded as LOW; the raw bytes are kept, so
723        they are written back unchanged unless the record is edited.
724
725        Args:
726            data: Exactly 32 bytes from the channel area.
727            logger: Logger for name-decoding warnings; defaults to ``LOG``.
728
729        Returns:
730            ChannelRecord: The decoded record, remembering ``data``.
731
732        Raises:
733            ValueError: If ``data`` is not 32 bytes or holds invalid BCD.
734        """
735        if len(data) != 32:
736            raise ValueError("Channel record must be exactly 32 bytes")
737        logger = logger or LOG
738        rx_hz = _decode_frequency(data[0:4])
739        tx_hz = _decode_frequency(data[4:8])
740        rx_tone = ToneSetting.from_bytes(data[8:10])
741        tx_tone = ToneSetting.from_bytes(data[10:12])
742        signalling_group = data[12] & 0x0F
743        ptt_id = data[13] & 0x0F
744        power = PowerLevel(min(data[14] & 0x0F, 2))
745        scrambler = (data[14] >> 4) & 0x0F
746        flags = data[15]
747        learn_fhss = bool(flags & 0x80)
748        # Radio uses bit6: 1 = NARROW, 0 = WIDE
749        bandwidth = Bandwidth.NARROW if ((flags >> 6) & 0x01) else Bandwidth.WIDE
750        encryption = (flags >> 4) & 0x03
751        busy_lockout = bool(flags & 0x08)
752        scan_add = bool(flags & 0x04)
753        tx_enabled = bool(flags & 0x02)
754        rx_modulation = Modulation(flags & 0x01)
755        fhss_code = _decode_fhss_code(data[16:20])
756        name = _decode_name(data[20:32], logger)
757        record = cls(
758            rx_hz=rx_hz,
759            tx_hz=tx_hz,
760            rx_tone=rx_tone,
761            tx_tone=tx_tone,
762            signalling_group=signalling_group,
763            ptt_id=ptt_id,
764            power=power,
765            scrambler=scrambler,
766            learn_fhss=learn_fhss,
767            bandwidth=bandwidth,
768            encryption=encryption,
769            busy_lockout=busy_lockout,
770            scan_add=scan_add,
771            tx_enabled=tx_enabled,
772            rx_modulation=rx_modulation,
773            fhss_code=fhss_code,
774            name=name,
775        )
776        record._raw_bytes = bytes(data)
777        record._original_state = record._state_tuple()
778        return record

Parse a raw 32-byte channel record.

A power nibble above 2 is decoded as LOW; the raw bytes are kept, so they are written back unchanged unless the record is edited.

Arguments:
  • data: Exactly 32 bytes from the channel area.
  • logger: Logger for name-decoding warnings; defaults to LOG.
Returns:

ChannelRecord: The decoded record, remembering data.

Raises:
  • ValueError: If data is not 32 bytes or holds invalid BCD.
Public method def to_bytes(self, *, logger: Optional[logging.Logger] = None) -> bytes:
780    def to_bytes(self, *, logger: Optional[logging.Logger] = None) -> bytes:
781        """Serialise the record into the radio's 32-byte format.
782
783        An unchanged record returns its original bytes. A changed record is
784        rebuilt from scratch; the new bytes then become the reference for the
785        next change check. Rebuilding writes the known fields; the high
786        nibbles of bytes 12 and 13 (meaning unknown) are taken from the
787        original bytes (0 if that byte was 0xFF), the FHSS field becomes
788        0xFF x 4 when no code is set, and the name is padded with 0xFF.
789
790        Args:
791            logger: Logger for name-encoding warnings; defaults to ``LOG``.
792
793        Returns:
794            bytes: 32 bytes ready to be written to the channel area.
795
796        Raises:
797            ValueError: If a frequency, tone or FHSS code cannot be encoded.
798        """
799        logger = logger or LOG
800
801        current_state = self._state_tuple()
802        if self._original_state is not None and current_state == self._original_state:
803            if self._raw_bytes:
804                return self._raw_bytes
805
806        buf = bytearray(b"\xFF" * 32)
807        buf[0:4] = _encode_frequency(self.rx_hz)
808        buf[4:8] = _encode_frequency(self.tx_hz)
809        buf[8:10] = self.rx_tone.to_bytes()
810        buf[10:12] = self.tx_tone.to_bytes()
811        # Keep the high nibbles of bytes 12-13 (meaning unknown) from the
812        # bytes this record was decoded from; 0xFF counts as 0.
813        old = self._raw_bytes if len(self._raw_bytes) == 32 else b""
814        high12 = old[12] & 0xF0 if old and old[12] != 0xFF else 0
815        high13 = old[13] & 0xF0 if old and old[13] != 0xFF else 0
816        buf[12] = high12 | (self.signalling_group & 0x0F)
817        buf[13] = high13 | (self.ptt_id & 0x0F)
818        scram = self.scrambler & 0x0F
819        power_value = self.power.value & 0x0F
820        buf[14] = (scram << 4) | power_value
821        flags = 0
822        if self.learn_fhss:
823            flags |= 0x80
824        # Radio uses bit6: 1 = NARROW, 0 = WIDE
825        if self.bandwidth is Bandwidth.NARROW:
826            flags |= 0x40
827        flags |= (self.encryption & 0x03) << 4
828        if self.busy_lockout:
829            flags |= 0x08
830        if self.scan_add:
831            flags |= 0x04
832        if self.tx_enabled:
833            flags |= 0x02
834        if self.rx_modulation is Modulation.AM:
835            flags |= 0x01
836        buf[15] = flags
837        buf[16:20] = _encode_fhss_code(self.fhss_code)
838        buf[20:32] = _encode_name(self.name, logger)
839        result = bytes(buf)
840        self._raw_bytes = result
841        self._original_state = current_state
842        return result

Serialise the record into the radio's 32-byte format.

An unchanged record returns its original bytes. A changed record is rebuilt from scratch; the new bytes then become the reference for the next change check. Rebuilding writes the known fields; the high nibbles of bytes 12 and 13 (meaning unknown) are taken from the original bytes (0 if that byte was 0xFF), the FHSS field becomes 0xFF x 4 when no code is set, and the name is padded with 0xFF.

Arguments:
  • logger: Logger for name-encoding warnings; defaults to LOG.
Returns:

bytes: 32 bytes ready to be written to the channel area.

Raises:
  • ValueError: If a frequency, tone or FHSS code cannot be encoded.
Private method def _state_tuple(self) -> tuple:
844    def _state_tuple(self) -> tuple:
845        """Return all user-visible fields as a tuple for change detection.
846
847        Returns:
848            tuple: The field values, with tones reduced to their own state
849            tuples.
850        """
851        return (
852            self.rx_hz,
853            self.tx_hz,
854            self.rx_tone._state_tuple(),
855            self.tx_tone._state_tuple(),
856            self.signalling_group,
857            self.ptt_id,
858            self.power,
859            self.scrambler,
860            self.learn_fhss,
861            self.bandwidth,
862            self.encryption,
863            self.busy_lockout,
864            self.scan_add,
865            self.tx_enabled,
866            self.rx_modulation,
867            self.fhss_code,
868            self.name,
869        )

Return all user-visible fields as a tuple for change detection.

Returns:

tuple: The field values, with tones reduced to their own state tuples.

Private function def _decode_frequency(raw: bytes) -> Optional[int]:
871def _decode_frequency(raw: bytes) -> Optional[int]:
872    """Decode a channel frequency field.
873
874    The four bytes are packed BCD, least significant byte first, in units
875    of 10 Hz (``50 12 52 14`` is 145.21250 MHz).
876
877    Args:
878        raw: Four frequency bytes.
879
880    Returns:
881        int | None: Frequency in Hz, or ``None`` if all bytes are 0x00/0xFF.
882
883    Raises:
884        ValueError: If ``raw`` is not four bytes or contains a non-BCD nibble.
885    """
886    if len(raw) != 4:
887        raise ValueError("Frequency field must be 4 bytes")
888    if all(b in (0x00, 0xFF) for b in raw):
889        return None
890    digits = []
891    for byte in raw:
892        high = (byte >> 4) & 0x0F
893        low = byte & 0x0F
894        if high > 9 or low > 9:
895            raise ValueError(f"Invalid BCD digit in frequency byte {byte:02X}")
896        digits.append(high * 10 + low)
897    value = 0
898    for chunk in reversed(digits):
899        value = value * 100 + chunk
900    return value * 10

Decode a channel frequency field.

The four bytes are packed BCD, least significant byte first, in units of 10 Hz (50 12 52 14 is 145.21250 MHz).

Arguments:
  • raw: Four frequency bytes.
Returns:

int | None: Frequency in Hz, or None if all bytes are 0x00/0xFF.

Raises:
  • ValueError: If raw is not four bytes or contains a non-BCD nibble.
Private function def _encode_frequency(hz: Optional[int]) -> bytes:
902def _encode_frequency(hz: Optional[int]) -> bytes:
903    """Encode a frequency into the four-byte channel format.
904
905    Args:
906        hz: Frequency in Hz; ``None`` or 0 gives an empty field (0xFF x 4).
907
908    Returns:
909        bytes: Four bytes, packed BCD, 10 Hz units, least significant first.
910
911    Raises:
912        ValueError: If ``hz`` is not a multiple of 10 or exceeds 8 digits.
913    """
914    if hz is None or hz == 0:
915        return b"\xFF" * 4
916    if hz % 10 != 0:
917        raise ValueError("Frequency must align to 10 Hz steps")
918    value = hz // 10
919    digits = []
920    for _ in range(4):
921        digits.append(value % 100)
922        value //= 100
923    if value:
924        raise ValueError("Frequency value exceeds 32-bit packed BCD range")
925    out = bytearray()
926    for chunk in digits:
927        high = chunk // 10
928        low = chunk % 10
929        out.append((high << 4) | low)
930    return bytes(out)

Encode a frequency into the four-byte channel format.

Arguments:
  • hz: Frequency in Hz; None or 0 gives an empty field (0xFF x 4).
Returns:

bytes: Four bytes, packed BCD, 10 Hz units, least significant first.

Raises:
  • ValueError: If hz is not a multiple of 10 or exceeds 8 digits.
Private function def _decode_fhss_code(raw: bytes) -> Optional[str]:
932def _decode_fhss_code(raw: bytes) -> Optional[str]:
933    """Decode the FHSS code field.
934
935    Byte 3 is 0xA0 when a code is set; bytes 2, 1, 0 hold its six hex
936    digits from most to least significant.
937
938    Args:
939        raw: Four FHSS bytes.
940
941    Returns:
942        str | None: Six upper-case hex digits, or ``None`` if not set.
943
944    Raises:
945        ValueError: If ``raw`` is not four bytes.
946    """
947    if len(raw) != 4:
948        raise ValueError("FHSS field must be 4 bytes")
949    if raw[3] != 0xA0:
950        return None
951    digits = "0123456789ABCDEF"
952    parts = []
953    for byte in reversed(raw[:3]):
954        parts.append(digits[(byte >> 4) & 0x0F])
955        parts.append(digits[byte & 0x0F])
956    return "".join(parts)

Decode the FHSS code field.

Byte 3 is 0xA0 when a code is set; bytes 2, 1, 0 hold its six hex digits from most to least significant.

Arguments:
  • raw: Four FHSS bytes.
Returns:

str | None: Six upper-case hex digits, or None if not set.

Raises:
  • ValueError: If raw is not four bytes.
Private function def _encode_fhss_code(code: Optional[str]) -> bytes:
958def _encode_fhss_code(code: Optional[str]) -> bytes:
959    """Encode an FHSS code into its four-byte field.
960
961    Args:
962        code: Six hex digits, or empty/``None`` for no code.
963
964    Returns:
965        bytes: Four bytes; 0xFF x 4 when no code is given.
966
967    Raises:
968        ValueError: If ``code`` is not six hex characters.
969    """
970    buf = bytearray(b"\xFF\xFF\xFF\xFF")
971    if not code:
972        return bytes(buf)
973    token = code.strip().upper()
974    if len(token) != 6 or any(c not in "0123456789ABCDEF" for c in token):
975        raise ValueError(f"FHSS code must be 6 hex characters: {code}")
976    buf[3] = 0xA0
977    digits = "0123456789ABCDEF"
978    buf[2] = (digits.index(token[0]) << 4) | digits.index(token[1])
979    buf[1] = (digits.index(token[2]) << 4) | digits.index(token[3])
980    buf[0] = (digits.index(token[4]) << 4) | digits.index(token[5])
981    return bytes(buf)

Encode an FHSS code into its four-byte field.

Arguments:
  • code: Six hex digits, or empty/None for no code.
Returns:

bytes: Four bytes; 0xFF x 4 when no code is given.

Raises:
  • ValueError: If code is not six hex characters.
Private function def _decode_name(raw: bytes, logger: logging.Logger) -> str:
 983def _decode_name(raw: bytes, logger: logging.Logger) -> str:
 984    """Decode a channel name.
 985
 986    Decoding stops at the first 0x00 or 0xFF byte. Invalid GB2312 bytes
 987    are replaced and logged.
 988
 989    Args:
 990        raw: The 12-byte name field.
 991        logger: Logger for decoding warnings.
 992
 993    Returns:
 994        str: The name, or ``""`` if empty.
 995    """
 996    data = bytearray()
 997    for byte in raw:
 998        if byte in (0xFF, 0x00):
 999            break
1000        data.append(byte)
1001    if not data:
1002        return ""
1003    try:
1004        return data.decode("gb2312")
1005    except UnicodeDecodeError:
1006        name = data.decode("gb2312", errors="replace")
1007        logger.warning("Channel name contained invalid GB2312 bytes: %s", data.hex())
1008        return name

Decode a channel name.

Decoding stops at the first 0x00 or 0xFF byte. Invalid GB2312 bytes are replaced and logged.

Arguments:
  • raw: The 12-byte name field.
  • logger: Logger for decoding warnings.
Returns:

str: The name, or "" if empty.

Private function def _encode_name(name: str, logger: logging.Logger) -> bytes:
1010def _encode_name(name: str, logger: logging.Logger) -> bytes:
1011    """Encode a channel name into the 12-byte GB2312 field.
1012
1013    If the name cannot be encoded as GB2312, the whole name is
1014    NFKD-normalised and reduced to its ASCII characters (all non-ASCII
1015    characters, including valid GB2312 ones, are dropped); if nothing ASCII
1016    remains, the GB2312-encodable characters are kept instead. Characters
1017    that still cannot be encoded are dropped, and the result is truncated to
1018    12 bytes without splitting a character. Every change is logged.
1019
1020    Args:
1021        name: Channel name.
1022        logger: Logger for warnings about altered names.
1023
1024    Returns:
1025        bytes: 12 bytes, padded with 0xFF.
1026    """
1027    if not name:
1028        return b"\xFF" * 12
1029    working = name
1030    try:
1031        working.encode("gb2312")
1032    except UnicodeEncodeError:
1033        normalised = unicodedata.normalize("NFKD", working)
1034        ascii_only = normalised.encode("ascii", errors="ignore").decode("ascii")
1035        if not ascii_only:
1036            ascii_only = normalised.encode("gb2312", errors="ignore").decode(
1037                "gb2312", errors="ignore"
1038            )
1039        logger.warning(
1040            "Channel name '%s' contains non-GB2312 characters; stored as '%s'",
1041            name,
1042            ascii_only,
1043        )
1044        working = ascii_only
1045    encoded = bytearray()
1046    for char in working:
1047        try:
1048            char_bytes = char.encode("gb2312")
1049        except UnicodeEncodeError:
1050            logger.warning(
1051                "Dropping character '%s' from channel name '%s' during encoding",
1052                char,
1053                name,
1054            )
1055            continue
1056        if len(encoded) + len(char_bytes) > 12:
1057            logger.warning("Channel name '%s' truncated to 12 bytes", name)
1058            break
1059        encoded.extend(char_bytes)
1060    while len(encoded) < 12:
1061        encoded.append(0xFF)
1062    return bytes(encoded[:12])

Encode a channel name into the 12-byte GB2312 field.

If the name cannot be encoded as GB2312, the whole name is NFKD-normalised and reduced to its ASCII characters (all non-ASCII characters, including valid GB2312 ones, are dropped); if nothing ASCII remains, the GB2312-encodable characters are kept instead. Characters that still cannot be encoded are dropped, and the result is truncated to 12 bytes without splitting a character. Every change is logged.

Arguments:
  • name: Channel name.
  • logger: Logger for warnings about altered names.
Returns:

bytes: 12 bytes, padded with 0xFF.

Private constant LOG = <Logger radtel_rt950pro (WARNING)>

Driver logger; rebinds the section-1 LOG (see there).

Private constant _DCS_CODES = ['D023N', 'D025N', 'D026N', 'D031N', 'D032N', 'D036N', 'D043N', 'D047N', 'D051N', 'D053N', 'D054N', 'D065N', 'D071N', 'D072N', 'D073N', 'D074N', 'D114N', 'D115N', 'D116N', 'D122N', 'D125N', 'D131N', 'D132N', 'D134N', 'D143N', 'D145N', 'D152N', 'D155N', 'D156N', 'D162N', 'D165N', 'D172N', 'D174N', 'D205N', 'D212N', 'D223N', 'D225N', 'D226N', 'D243N', 'D244N', 'D245N', 'D246N', 'D251N', 'D252N', 'D255N', 'D261N', 'D263N', 'D265N', 'D266N', 'D271N', 'D274N', 'D306N', 'D311N', 'D315N', 'D325N', 'D331N', 'D332N', 'D343N', 'D346N', 'D351N', 'D356N', 'D364N', 'D365N', 'D371N', 'D411N', 'D412N', 'D413N', 'D423N', 'D431N', 'D432N', 'D445N', 'D446N', 'D452N', 'D454N', 'D455N', 'D462N', 'D464N', 'D465N', 'D466N', 'D503N', 'D506N', 'D516N', 'D523N', 'D526N', 'D532N', 'D546N', 'D565N', 'D606N', 'D612N', 'D624N', 'D627N', 'D631N', 'D632N', 'D645N', 'D654N', 'D662N', 'D664N', 'D703N', 'D712N', 'D723N', 'D731N', 'D732N', 'D734N', 'D743N', 'D754N', 'D023I', 'D025I', 'D026I', 'D031I', 'D032I', 'D036I', 'D043I', 'D047I', 'D051I', 'D053I', 'D054I', 'D065I', 'D071I', 'D072I', 'D073I', 'D074I', 'D114I', 'D115I', 'D116I', 'D122I', 'D125I', 'D131I', 'D132I', 'D134I', 'D143I', 'D145I', 'D152I', 'D155I', 'D156I', 'D162I', 'D165I', 'D172I', 'D174I', 'D205I', 'D212I', 'D223I', 'D225I', 'D226I', 'D243I', 'D244I', 'D245I', 'D246I', 'D251I', 'D252I', 'D255I', 'D261I', 'D263I', 'D265I', 'D266I', 'D271I', 'D274I', 'D306I', 'D311I', 'D315I', 'D325I', 'D331I', 'D332I', 'D343I', 'D346I', 'D351I', 'D356I', 'D364I', 'D365I', 'D371I', 'D411I', 'D412I', 'D413I', 'D423I', 'D431I', 'D432I', 'D445I', 'D446I', 'D452I', 'D454I', 'D455I', 'D462I', 'D464I', 'D465I', 'D466I', 'D503I', 'D506I', 'D516I', 'D523I', 'D526I', 'D532I', 'D546I', 'D565I', 'D606I', 'D612I', 'D624I', 'D627I', 'D631I', 'D632I', 'D645I', 'D654I', 'D662I', 'D664I', 'D703I', 'D712I', 'D723I', 'D731I', 'D732I', 'D734I', 'D743I', 'D754I']

DCS codes in radio order.

A tone field with second byte 0x00 stores a DCS code as a 1-based index into this list: indexes 1-105 are normal polarity (N) and 106-210 are inverted (I).

2. Settings sections: data structures and codecs

dataclasses plus parse_*/encode_* functions for the VFO, function, DTMF, modulation and APRS blocks.

Public class
@dataclass(slots=True)
class VFOSettings:
1075@dataclass(slots=True)
1076class VFOSettings:
1077    """One 32-byte VFO entry (VFO A, B or C) from the block at 0x8000.
1078
1079    Byte layout:
1080
1081        0-7    RX frequency, one decimal digit per byte, 10 Hz units
1082        8-9    RX tone
1083        10-11  TX tone
1084        13     b0 busy lockout
1085        14     b5-4 offset direction | b3-0 signalling group
1086        16     scrambler (high nibble) | power (low nibble)
1087        17     b7 learn FHSS, b6 narrow, b5-4 encryption, b0 AM
1088        18     frequency band (low nibble)
1089        19     step index (low nibble)
1090        20-26  offset, one decimal digit per byte, 100 Hz units
1091
1092    Bits and bytes not listed are preserved when encoding, except that a
1093    listed byte holding 0xFF is treated as 0 before its fields are written.
1094    """
1095
1096    rx_hz: Optional[int]
1097    """Receive frequency in Hz, or ``None``."""
1098    offset_hz: Optional[int]
1099    """Repeater offset in Hz, or ``None``."""
1100    rx_tone: ToneSetting
1101    """Receive tone."""
1102    tx_tone: ToneSetting
1103    """Transmit tone."""
1104    busy_lockout: bool
1105    """Busy-channel lockout."""
1106    offset_direction: int
1107    """0 none, 1 plus, 2 minus (CPS *Offset Dir*). 3 (split) is not offered
1108    by the CPS or in CHIRP; a stored 3 is kept."""
1109    signalling_group: int
1110    """DTMF signalling group as stored, 0-14; the CPS shows it plus one
1111    (1-15)."""
1112    tx_power: PowerLevel
1113    """Transmit power: stored 0 High, 1 Middle (``MEDIUM``), 2 Low."""
1114    scrambler: int
1115    """Scrambler code, 0 (off) to 8; the nibble can hold up to 15."""
1116    learn_fhss: bool
1117    """Learn-FHSS flag; not shown in the CPS *VFO Mode* screen or in CHIRP,
1118    kept as stored."""
1119    bandwidth: Bandwidth
1120    """FM bandwidth."""
1121    encryption: int
1122    """Encryption mode, 0-3."""
1123    rx_modulation: Modulation
1124    """Receive modulation."""
1125    freq_band: int
1126    """Frequency band, 0 VHF or 1 UHF (see ``_VFO_BAND_CHOICES``)."""
1127    step_freq_index: int
1128    """Step index 0-9, 2.5 kHz to 100 kHz (see ``_VFO_STEP_CHOICES``)."""
1129    _raw_bytes: bytes = field(default=b"", repr=False, compare=False)
1130    """The 32-byte VFO entry this object was decoded from (empty when new).
1131    Written back unchanged by :func:`encode_vfo_section` while the entry
1132    is not edited.
1133    """
1134    _original_state: Optional[tuple] = field(default=None, repr=False, compare=False)
1135    """Result of ``_state_tuple()`` when the entry was decoded or last
1136    encoded, or ``None`` when new; used to detect an edit.
1137    """
1138
1139    def _state_tuple(self) -> tuple:
1140        """Return all user-visible fields as a tuple for change detection.
1141
1142        Returns:
1143            tuple: The field values, with tones reduced to their own state
1144            tuples.
1145        """
1146        return (
1147            self.rx_hz,
1148            self.offset_hz,
1149            self.rx_tone._state_tuple(),
1150            self.tx_tone._state_tuple(),
1151            self.busy_lockout,
1152            self.offset_direction,
1153            self.signalling_group,
1154            self.tx_power,
1155            self.scrambler,
1156            self.learn_fhss,
1157            self.bandwidth,
1158            self.encryption,
1159            self.rx_modulation,
1160            self.freq_band,
1161            self.step_freq_index,
1162        )

One 32-byte VFO entry (VFO A, B or C) from the block at 0x8000.

Byte layout:

0-7 RX frequency, one decimal digit per byte, 10 Hz units 8-9 RX tone 10-11 TX tone 13 b0 busy lockout 14 b5-4 offset direction | b3-0 signalling group 16 scrambler (high nibble) | power (low nibble) 17 b7 learn FHSS, b6 narrow, b5-4 encryption, b0 AM 18 frequency band (low nibble) 19 step index (low nibble) 20-26 offset, one decimal digit per byte, 100 Hz units

Bits and bytes not listed are preserved when encoding, except that a listed byte holding 0xFF is treated as 0 before its fields are written.

Fields
Public field rx_hz: Optional[int]

Receive frequency in Hz, or None.

Public field offset_hz: Optional[int]

Repeater offset in Hz, or None.

Public field rx_tone: ToneSetting

Receive tone.

Public field tx_tone: ToneSetting

Transmit tone.

Public field busy_lockout: bool

Busy-channel lockout.

Public field offset_direction: int

0 none, 1 plus, 2 minus (CPS Offset Dir). 3 (split) is not offered by the CPS or in CHIRP; a stored 3 is kept.

Public field signalling_group: int

DTMF signalling group as stored, 0-14; the CPS shows it plus one (1-15).

Public field tx_power: PowerLevel

Transmit power: stored 0 High, 1 Middle (MEDIUM), 2 Low.

Public field scrambler: int

Scrambler code, 0 (off) to 8; the nibble can hold up to 15.

Public field learn_fhss: bool

Learn-FHSS flag; not shown in the CPS VFO Mode screen or in CHIRP, kept as stored.

Public field bandwidth: Bandwidth

FM bandwidth.

Public field encryption: int

Encryption mode, 0-3.

Public field rx_modulation: Modulation

Receive modulation.

Public field freq_band: int

Frequency band, 0 VHF or 1 UHF (see _VFO_BAND_CHOICES).

Public field step_freq_index: int

Step index 0-9, 2.5 kHz to 100 kHz (see _VFO_STEP_CHOICES).

Private field _raw_bytes: bytes

The 32-byte VFO entry this object was decoded from (empty when new). Written back unchanged by encode_vfo_section() while the entry is not edited.

Private field _original_state: Optional[tuple]

Result of _state_tuple() when the entry was decoded or last encoded, or None when new; used to detect an edit.

Methods
Private method def _state_tuple(self) -> tuple:
1139    def _state_tuple(self) -> tuple:
1140        """Return all user-visible fields as a tuple for change detection.
1141
1142        Returns:
1143            tuple: The field values, with tones reduced to their own state
1144            tuples.
1145        """
1146        return (
1147            self.rx_hz,
1148            self.offset_hz,
1149            self.rx_tone._state_tuple(),
1150            self.tx_tone._state_tuple(),
1151            self.busy_lockout,
1152            self.offset_direction,
1153            self.signalling_group,
1154            self.tx_power,
1155            self.scrambler,
1156            self.learn_fhss,
1157            self.bandwidth,
1158            self.encryption,
1159            self.rx_modulation,
1160            self.freq_band,
1161            self.step_freq_index,
1162        )

Return all user-visible fields as a tuple for change detection.

Returns:

tuple: The field values, with tones reduced to their own state tuples.

Public class
@dataclass(slots=True)
class FunctionSettings:
1164@dataclass(slots=True)
1165class FunctionSettings:
1166    """Function settings from the 96-byte block at 0x9000.
1167
1168    Values are kept in a flat dictionary keyed by the names used in
1169    ``_FUNCTION_SPECS`` (e.g. ``"sql"``, ``"tot"``, ``"key1_long"``).
1170    """
1171
1172    values: Dict[str, Optional[int]] = field(default_factory=dict)
1173    """Setting name to raw integer value; ``None`` means the byte was 0xFF (not
1174    set).
1175    """

Function settings from the 96-byte block at 0x9000.

Values are kept in a flat dictionary keyed by the names used in _FUNCTION_SPECS (e.g. "sql", "tot", "key1_long").

Fields
Public field values: Dict[str, Optional[int]]

Setting name to raw integer value; None means the byte was 0xFF (not set).

Public class
@dataclass(slots=True)
class DTMFSettings:
1177@dataclass(slots=True)
1178class DTMFSettings:
1179    """DTMF settings from the 384-byte block at 0xA000.
1180
1181    Layout: a 32-byte info part followed by 22 code groups of 16 bytes.
1182    """
1183
1184    current_id: str
1185    """Own DTMF ID, up to 5 symbols."""
1186    ptt_id_mode: Optional[int]
1187    """PTT ID mode 0-3 (off, BOT, EOT, both), or ``None``."""
1188    last_time_send: Optional[int]
1189    """Raw "last time send" value, or ``None``."""
1190    last_time_stop: Optional[int]
1191    """Raw "last time stop" value, or ``None``."""
1192    code_groups: List[str]
1193    """The 22 code groups, up to 6 symbols each."""

DTMF settings from the 384-byte block at 0xA000.

Layout: a 32-byte info part followed by 22 code groups of 16 bytes.

Fields
Public field current_id: str

Own DTMF ID, up to 5 symbols.

Public field ptt_id_mode: Optional[int]

PTT ID mode 0-3 (off, BOT, EOT, both), or None.

Public field last_time_send: Optional[int]

Raw "last time send" value, or None.

Public field last_time_stop: Optional[int]

Raw "last time stop" value, or None.

Public field code_groups: List[str]

The 22 code groups, up to 6 symbols each.

Public class
@dataclass(slots=True)
class ModulationChannelEntry:
1195@dataclass(slots=True)
1196class ModulationChannelEntry:
1197    """One of the 16 broadcast/SSB memory entries of the modulation screen.
1198
1199    Each entry holds an FM, an AM and an SSB memory side by side.
1200    """
1201
1202    fm_frequency: Optional[int]
1203    """FM broadcast frequency in Hz (stored in 10 kHz units), or ``None``."""
1204    fm_name: str
1205    """FM memory name."""
1206    am_frequency: Optional[int]
1207    """AM broadcast frequency in Hz (stored in 10 kHz units), or ``None``."""
1208    am_name: str
1209    """AM memory name."""
1210    ssb_frequency: Optional[int]
1211    """SSB frequency in Hz (stored in 10 kHz units), or ``None``."""
1212    ssb_bandwidth: Optional[int]
1213    """Raw SSB bandwidth index, or ``None``."""
1214    ssb_beat_offset: Optional[int]
1215    """SSB BFO offset (signed), or ``None``."""
1216    ssb_name: str
1217    """SSB memory name."""

One of the 16 broadcast/SSB memory entries of the modulation screen.

Each entry holds an FM, an AM and an SSB memory side by side.

Fields
Public field fm_frequency: Optional[int]

FM broadcast frequency in Hz (stored in 10 kHz units), or None.

Public field fm_name: str

FM memory name.

Public field am_frequency: Optional[int]

AM broadcast frequency in Hz (stored in 10 kHz units), or None.

Public field am_name: str

AM memory name.

Public field ssb_frequency: Optional[int]

SSB frequency in Hz (stored in 10 kHz units), or None.

Public field ssb_bandwidth: Optional[int]

Raw SSB bandwidth index, or None.

Public field ssb_beat_offset: Optional[int]

SSB BFO offset (signed), or None.

Public field ssb_name: str

SSB memory name.

Public class
@dataclass(slots=True)
class ModulationSettings:
1219@dataclass(slots=True)
1220class ModulationSettings:
1221    """Contents of the modulation blocks (parameters at 0xB000, names at 0xD000)."""
1222
1223    fm_current_channel: Optional[int]
1224    """Selected FM memory, 0-14, or ``None``."""
1225    am_current_channel: Optional[int]
1226    """Selected AM memory, 0-14, or ``None``."""
1227    ssb_current_channel: Optional[int]
1228    """Selected SSB memory, 0-14, or ``None``."""
1229    work_mode: Optional[int]
1230    """Work mode, 0-1, or ``None``."""
1231    modulation_mode: Optional[int]
1232    """Modulation mode, 0-4, or ``None``."""
1233    am_step_index: Optional[int]
1234    """AM step index, 0-3, or ``None``."""
1235    am_rx_gain: Optional[int]
1236    """AM RX gain, 0-36, or ``None``."""
1237    ssb_step_index: Optional[int]
1238    """SSB step index, 0-5, or ``None``."""
1239    ssb_rx_gain: Optional[int]
1240    """SSB RX gain, 0-36, or ``None``."""
1241    channels: List[ModulationChannelEntry]
1242    """The 16 :class:`ModulationChannelEntry` items."""

Contents of the modulation blocks (parameters at 0xB000, names at 0xD000).

Fields
Public field fm_current_channel: Optional[int]

Selected FM memory, 0-14, or None.

Public field am_current_channel: Optional[int]

Selected AM memory, 0-14, or None.

Public field ssb_current_channel: Optional[int]

Selected SSB memory, 0-14, or None.

Public field work_mode: Optional[int]

Work mode, 0-1, or None.

Public field modulation_mode: Optional[int]

Modulation mode, 0-4, or None.

Public field am_step_index: Optional[int]

AM step index, 0-3, or None.

Public field am_rx_gain: Optional[int]

AM RX gain, 0-36, or None.

Public field ssb_step_index: Optional[int]

SSB step index, 0-5, or None.

Public field ssb_rx_gain: Optional[int]

SSB RX gain, 0-36, or None.

Public field channels: List[ModulationChannelEntry]

The 16 ModulationChannelEntry items.

Public class
@dataclass(slots=True)
class APRSSettings:
1244@dataclass(slots=True)
1245class APRSSettings:
1246    """APRS settings from the separate 128-byte APRS space.
1247
1248    Values are kept in a flat dictionary keyed by the names used in
1249    ``_APRS_SPECS`` (e.g. ``"call_sign"``, ``"ssid"``, ``"altitude"``).
1250    """
1251
1252    fields: Dict[str, Optional[object]] = field(default_factory=dict)
1253    """Setting name to value (int or str); ``None`` means not set."""

APRS settings from the separate 128-byte APRS space.

Values are kept in a flat dictionary keyed by the names used in _APRS_SPECS (e.g. "call_sign", "ssid", "altitude").

Fields
Public field fields: Dict[str, Optional[object]]

Setting name to value (int or str); None means not set.

Public function def parse_vfo_section(section: bytes) -> List[VFOSettings]:
1255def parse_vfo_section(section: bytes) -> List[VFOSettings]:
1256    """Decode the VFO block into VFO entries.
1257
1258    Args:
1259        section: The used part of the VFO block (normally 96 bytes, three
1260            32-byte entries).
1261
1262    Returns:
1263        list[VFOSettings]: One entry per 32 bytes, in order A, B, C. Each
1264        entry remembers its raw bytes.
1265
1266    Raises:
1267        ValueError: If the length is not a multiple of 32.
1268
1269    Note:
1270        The power nibble (byte 16) holds 0 High, 1 Middle, 2 Low; a higher
1271        value is decoded as Low, as for channels, and written back as 2 only
1272        if that VFO entry is re-encoded because another field changed.
1273    """
1274    if len(section) % 32 != 0:
1275        raise ValueError("VFO section must be a multiple of 32 bytes")
1276    entries: List[VFOSettings] = []
1277    for offset in range(0, len(section), 32):
1278        chunk = section[offset : offset + 32]
1279        rx_hz = _decode_vfo_frequency(chunk[0:8])
1280        rx_tone = ToneSetting.from_bytes(bytes(chunk[8:10]))
1281        tx_tone = ToneSetting.from_bytes(bytes(chunk[10:12]))
1282        busy_lockout = bool(chunk[13] & 0x01)
1283        offset_dir = (chunk[14] >> 4) & 0x03
1284        signalling_group = chunk[14] & 0x0F
1285        tx_power_raw = chunk[16] & 0x0F
1286        tx_power = PowerLevel(min(tx_power_raw, PowerLevel.LOW.value))
1287        scrambler = (chunk[16] >> 4) & 0x0F
1288        learn_fhss = bool((chunk[17] >> 7) & 0x01)
1289        # Radio uses bit6: 1 = NARROW, 0 = WIDE
1290        bandwidth = Bandwidth.NARROW if ((chunk[17] >> 6) & 0x01) else Bandwidth.WIDE
1291        encryption = (chunk[17] >> 4) & 0x03
1292        rx_modulation = Modulation.AM if (chunk[17] & 0x01) else Modulation.FM
1293        freq_band = chunk[18] & 0x0F
1294        step_freq = chunk[19] & 0x0F
1295        offset_hz = _decode_offset_frequency(chunk[20:27])
1296        entry = VFOSettings(
1297            rx_hz=rx_hz,
1298            offset_hz=offset_hz,
1299            rx_tone=rx_tone,
1300            tx_tone=tx_tone,
1301            busy_lockout=busy_lockout,
1302            offset_direction=offset_dir,
1303            signalling_group=signalling_group,
1304            tx_power=tx_power,
1305            scrambler=scrambler,
1306            learn_fhss=learn_fhss,
1307            bandwidth=bandwidth,
1308            encryption=encryption,
1309            rx_modulation=rx_modulation,
1310            freq_band=freq_band,
1311            step_freq_index=step_freq,
1312        )
1313        entry._raw_bytes = bytes(chunk)
1314        entry._original_state = entry._state_tuple()
1315        entries.append(entry)
1316    return entries

Decode the VFO block into VFO entries.

Arguments:
  • section: The used part of the VFO block (normally 96 bytes, three 32-byte entries).
Returns:

list[VFOSettings]: One entry per 32 bytes, in order A, B, C. Each entry remembers its raw bytes.

Raises:
  • ValueError: If the length is not a multiple of 32.
Note:

The power nibble (byte 16) holds 0 High, 1 Middle, 2 Low; a higher value is decoded as Low, as for channels, and written back as 2 only if that VFO entry is re-encoded because another field changed.

Public function def parse_function_section(section: bytes) -> FunctionSettings:
1318def parse_function_section(section: bytes) -> FunctionSettings:
1319    """Decode the 96-byte function block.
1320
1321    The block is read as three 32-byte parts; each known byte is mapped to
1322    a named setting (see the ``_set`` calls for the offsets). Each value is
1323    the low nibble of its byte (5 bits for ``key*_long``); byte 26 holds
1324    ``work_mode_a/b/c`` in bits 1-0, 3-2 and 5-4.
1325
1326    Args:
1327        section: Exactly 96 bytes.
1328
1329    Returns:
1330        FunctionSettings: All known settings; 0xFF bytes become ``None``.
1331
1332    Raises:
1333        ValueError: If ``section`` is not 96 bytes.
1334    """
1335    if len(section) != 96:
1336        raise ValueError("Function config section must be 96 bytes")
1337    part1 = section[0:32]
1338    part2 = section[32:64]
1339    part3 = section[64:96]
1340    values: Dict[str, Optional[int]] = {}
1341
1342    def _masked(byte: int, mask: int = 0x0F, shift: int = 0) -> Optional[int]:
1343        """Extract a bit field from one byte; 0xFF (not set) gives ``None``.
1344
1345        Args:
1346            byte: Raw byte value from the function block.
1347            mask: Bit mask applied after shifting (default ``0x0F``).
1348            shift: Number of bits to shift right before masking.
1349
1350        Returns:
1351            Optional[int]: ``(byte >> shift) & mask``, or ``None`` if ``byte`` is 0xFF.
1352        """
1353        if byte == 0xFF:
1354            return None
1355        return (byte >> shift) & mask
1356
1357    def _set(name: str, byte: int, mask: int = 0x0F, shift: int = 0) -> None:
1358        """Store the masked value of ``byte`` under ``name``.
1359
1360        Args:
1361            name: Setting key in the ``values`` dictionary.
1362            byte: Raw byte value from the function block.
1363            mask: Bit mask passed to ``_masked`` (default ``0x0F``).
1364            shift: Right shift passed to ``_masked``.
1365        """
1366        values[name] = _masked(byte, mask, shift)
1367
1368    _set("sql", part1[0])
1369    _set("save_mode", part1[1])
1370    _set("vox", part1[2])
1371    _set("auto_backlight", part1[3])
1372    _set("tdr", part1[4])
1373    _set("tot", part1[5])
1374    _set("beep_prompt", part1[6])
1375    _set("voice_prompt", part1[7])
1376    _set("language", part1[8])
1377    _set("dtmf_mode", part1[9])
1378    _set("scan_mode", part1[10])
1379    _set("ptt_id", part1[11])
1380    _set("send_id_delay", part1[12])
1381    _set("display_mode_a", part1[13])
1382    _set("display_mode_b", part1[14])
1383    _set("display_mode_c", part1[15])
1384    _set("auto_key_lock", part1[16])
1385    _set("alarm_mode", part1[17])
1386    _set("alarm_sound", part1[18])
1387    _set("tail_noise_clear", part1[20])
1388    _set("pass_repeater_noise_clear", part1[21])
1389    _set("pass_repeater_noise_detect", part1[22])
1390    _set("sound_tx_end", part1[23])
1391    _set("current_work_mode", part1[24])
1392    _set("fm_radio", part1[25])
1393    if part1[26] == 0xFF:
1394        values["work_mode_a"] = None
1395        values["work_mode_b"] = None
1396        values["work_mode_c"] = None
1397    else:
1398        values["work_mode_a"] = part1[26] & 0x03
1399        values["work_mode_b"] = (part1[26] >> 2) & 0x03
1400        values["work_mode_c"] = (part1[26] >> 4) & 0x03
1401    _set("lock_keyboard", part1[27])
1402    _set("power_on_message", part1[28])
1403    _set("bt_write_switch", part1[29])
1404    _set("rtone", part1[30])
1405
1406    _set("vox_delay", part2[0])
1407    _set("timer_menu_quit", part2[1])
1408    _set("weather_channel", part2[5])
1409    _set("divide_channel", part2[6])
1410    _set("subaudio_scan_save", part2[7])
1411    _set("vox_switch", part2[8])
1412    _set("key_side1_short", part2[9])
1413    _set("key_side1_long", part2[10])
1414    _set("key_side2_short", part2[11])
1415    _set("key_side2_long", part2[12])
1416    _set("current_work_area_a", part2[13])
1417    _set("current_work_area_b", part2[14])
1418    _set("current_work_area_c", part2[15])
1419    _set("ab_uv_transfer", part2[25])
1420    _set("sound_transfer", part2[26])
1421    _set("key0_long", part2[27], mask=0x1F)
1422    _set("key1_long", part2[28], mask=0x1F)
1423    _set("key2_long", part2[29], mask=0x1F)
1424    _set("key3_long", part2[30], mask=0x1F)
1425    _set("key4_long", part2[31], mask=0x1F)
1426
1427    _set("key5_long", part3[0], mask=0x1F)
1428    _set("key6_long", part3[1], mask=0x1F)
1429    _set("key7_long", part3[2], mask=0x1F)
1430    _set("key8_long", part3[3], mask=0x1F)
1431    _set("key9_long", part3[4], mask=0x1F)
1432
1433    return FunctionSettings(values=values)

Decode the 96-byte function block.

The block is read as three 32-byte parts; each known byte is mapped to a named setting (see the _set calls for the offsets). Each value is the low nibble of its byte (5 bits for key*_long); byte 26 holds work_mode_a/b/c in bits 1-0, 3-2 and 5-4.

Arguments:
  • section: Exactly 96 bytes.
Returns:

FunctionSettings: All known settings; 0xFF bytes become None.

Raises:
  • ValueError: If section is not 96 bytes.
Public function def parse_dtmf_section(section: bytes) -> DTMFSettings:
1435def parse_dtmf_section(section: bytes) -> DTMFSettings:
1436    """Decode the 384-byte DTMF block.
1437
1438    Args:
1439        section: Exactly 384 bytes: 32 info bytes plus 22 code groups of
1440            16 bytes.
1441
1442    Returns:
1443        DTMFSettings: Own ID, PTT ID mode, timing values and code groups.
1444
1445    Raises:
1446        ValueError: If ``section`` is not 384 bytes.
1447    """
1448    if len(section) != 384:
1449        raise ValueError("DTMF section must be 384 bytes")
1450    info = section[0:32]
1451    groups = section[32:]
1452    current_id = _decode_dtmf_sequence(info[0:5])
1453    ptt_id = info[6] & 0x0F if info[6] != 0xFF else None
1454    last_send = info[7] & 0x0F if info[7] != 0xFF else None
1455    last_stop = info[8] & 0x0F if info[8] != 0xFF else None
1456    code_groups: List[str] = []
1457    for offset in range(0, len(groups), 16):
1458        code_groups.append(_decode_dtmf_sequence(groups[offset : offset + 16], max_len=6))
1459    return DTMFSettings(
1460        current_id=current_id,
1461        ptt_id_mode=ptt_id,
1462        last_time_send=last_send,
1463        last_time_stop=last_stop,
1464        code_groups=code_groups,
1465    )

Decode the 384-byte DTMF block.

Arguments:
  • section: Exactly 384 bytes: 32 info bytes plus 22 code groups of 16 bytes.
Returns:

DTMFSettings: Own ID, PTT ID mode, timing values and code groups.

Raises:
  • ValueError: If section is not 384 bytes.
Public function def parse_modulation_sections( mod_block: bytes, name_block: bytes) -> ModulationSettings:
1467def parse_modulation_sections(mod_block: bytes, name_block: bytes) -> ModulationSettings:
1468    """Decode the modulation parameter and name blocks.
1469
1470    Parameter block layout (offsets in bytes):
1471
1472        0-31     16 FM frequencies, LE uint16, 10 kHz units
1473        32       FM current channel     33  work mode
1474        34-65    16 AM frequencies, LE uint16, 10 kHz units
1475        66       AM current channel     67  modulation mode   68  AM RX gain
1476        69-148   16 SSB entries of 5 bytes: freq (LE uint16, 10 kHz units),
1477                 bandwidth (u8), beat offset (LE int16)
1478        149      SSB current channel   150  SSB step   151  AM step
1479        152      SSB RX gain
1480
1481    Name block: three tables (FM, AM, SSB) of 16 names x 16 bytes, GB2312.
1482
1483    Args:
1484        mod_block: Exactly 256 parameter bytes.
1485        name_block: Exactly 768 name bytes.
1486
1487    Returns:
1488        ModulationSettings: Decoded parameters and the 16 entries.
1489
1490    Raises:
1491        ValueError: If a block has the wrong length.
1492    """
1493    if len(mod_block) != 256:
1494        raise ValueError("Modulation parameter block must be 256 bytes")
1495    if len(name_block) != 768:
1496        raise ValueError("Modulation name block must be 768 bytes")
1497
1498    channels: List[ModulationChannelEntry] = []
1499
1500    def _optional(value: int, modulus: int) -> Optional[int]:
1501        """Return ``value % modulus``, or ``None`` for 0xFF (not set).
1502
1503        Args:
1504            value: Raw byte value from the modulation parameter block.
1505            modulus: Number of valid values; the result is wrapped into ``0..modulus-1``.
1506
1507        Returns:
1508            Optional[int]: ``value % modulus``, or ``None`` if ``value`` is 0xFF.
1509        """
1510        if value == 0xFF:
1511            return None
1512        return value % modulus
1513
1514    fm_freqs = [_decode_le_uint16(mod_block, idx * 2) for idx in range(16)]
1515    fm_current = _optional(mod_block[32], 15)
1516    work_mode = _optional(mod_block[33], 2)
1517    am_freqs = [_decode_le_uint16(mod_block, 34 + idx * 2) for idx in range(16)]
1518    am_current = _optional(mod_block[66], 15)
1519    modulation_mode = _optional(mod_block[67], 5)
1520    am_rx_gain = _optional(mod_block[68], 37)
1521    ssb_freqs = []
1522    ssb_bandwidths = []
1523    ssb_offsets = []
1524    for idx in range(16):
1525        base = 69 + idx * 5
1526        ssb_freqs.append(_decode_le_uint16(mod_block, base))
1527        ssb_bandwidths.append(mod_block[base + 2])
1528        ssb_offsets.append(_decode_le_int16(mod_block, base + 3))
1529    ssb_current = _optional(mod_block[149], 15)
1530    ssb_step = _optional(mod_block[150], 6)
1531    am_step = _optional(mod_block[151], 4)
1532    ssb_rx_gain = _optional(mod_block[152], 37)
1533
1534    fm_names = [_decode_gb2312(name_block, idx * 16) for idx in range(16)]
1535    am_names = [_decode_gb2312(name_block, 256 + idx * 16) for idx in range(16)]
1536    ssb_names = [_decode_gb2312(name_block, 512 + idx * 16) for idx in range(16)]
1537
1538    def _scale_freq(value: int) -> Optional[int]:
1539        """Convert a stored 10 kHz-unit value to Hz; 0 and 0xFFFF mean empty.
1540
1541        Args:
1542            value: Stored LE uint16 frequency in 10 kHz units.
1543
1544        Returns:
1545            Optional[int]: Frequency in Hz, or ``None`` for 0 or 0xFFFF.
1546        """
1547        if value in (0, 0xFFFF):
1548            return None
1549        return value * 10_000
1550
1551    for idx in range(16):
1552        fm_freq = _scale_freq(fm_freqs[idx])
1553        am_freq = _scale_freq(am_freqs[idx])
1554        ssb_freq = _scale_freq(ssb_freqs[idx])
1555        channels.append(
1556            ModulationChannelEntry(
1557                fm_frequency=fm_freq,
1558                fm_name=fm_names[idx],
1559                am_frequency=am_freq,
1560                am_name=am_names[idx],
1561                ssb_frequency=ssb_freq,
1562                ssb_bandwidth=(
1563                    None if ssb_bandwidths[idx] in (0, 0xFF) else int(ssb_bandwidths[idx])
1564                ),
1565                ssb_beat_offset=ssb_offsets[idx] if ssb_freq is not None else None,
1566                ssb_name=ssb_names[idx],
1567            )
1568        )
1569
1570    return ModulationSettings(
1571        fm_current_channel=fm_current,
1572        am_current_channel=am_current,
1573        ssb_current_channel=ssb_current,
1574        work_mode=work_mode,
1575        modulation_mode=modulation_mode,
1576        am_step_index=am_step,
1577        am_rx_gain=am_rx_gain,
1578        ssb_step_index=ssb_step,
1579        ssb_rx_gain=ssb_rx_gain,
1580        channels=channels,
1581    )

Decode the modulation parameter and name blocks.

Parameter block layout (offsets in bytes):

0-31     16 FM frequencies, LE uint16, 10 kHz units
32       FM current channel     33  work mode
34-65    16 AM frequencies, LE uint16, 10 kHz units
66       AM current channel     67  modulation mode   68  AM RX gain
69-148   16 SSB entries of 5 bytes: freq (LE uint16, 10 kHz units),
         bandwidth (u8), beat offset (LE int16)
149      SSB current channel   150  SSB step   151  AM step
152      SSB RX gain

Name block: three tables (FM, AM, SSB) of 16 names x 16 bytes, GB2312.

Arguments:
  • mod_block: Exactly 256 parameter bytes.
  • name_block: Exactly 768 name bytes.
Returns:

ModulationSettings: Decoded parameters and the 16 entries.

Raises:
  • ValueError: If a block has the wrong length.
Public function def parse_aprs_section(section: bytes) -> APRSSettings:
1583def parse_aprs_section(section: bytes) -> APRSSettings:
1584    """Decode the 128-byte APRS block.
1585
1586    Latitude is stored at bytes 7-10 (N/S letter, minute, degree, second)
1587    and longitude at bytes 11-14 (W/E letter, minute, degree, second).
1588    ``north_south``/``east_west`` decode ``N``/``W`` as 0 and any other byte
1589    as 1. Minutes and seconds are clamped to 59, degrees to 90/180.
1590    Altitude (bytes 15-16) is a little-endian signed 16-bit value clamped to
1591    +/-10000. Single-byte settings keep their low nibble (byte 6: 5 bits,
1592    byte 27: 7 bits). Text fields are ASCII (call sign, routes) or GB2312
1593    (custom message).
1594
1595    Args:
1596        section: Exactly 128 bytes.
1597
1598    Returns:
1599        APRSSettings: All known fields; 0xFF bytes become ``None``.
1600
1601    Raises:
1602        ValueError: If ``section`` is not 128 bytes.
1603    """
1604    if len(section) != 128:
1605        raise ValueError("APRS section must be 128 bytes")
1606    data = section
1607    fields: Dict[str, Optional[object]] = {}
1608
1609    def _set(name: str, idx: int, mask: int = 0x0F) -> None:
1610        """Store the masked byte at ``idx`` under ``name``; 0xFF gives ``None``.
1611
1612        Args:
1613            name: Field key in the ``fields`` dictionary.
1614            idx: Byte offset within the 128-byte APRS block.
1615            mask: Bit mask applied to the byte (default ``0x0F``).
1616        """
1617        byte = data[idx]
1618        if byte == 0xFF:
1619            fields[name] = None
1620        else:
1621            fields[name] = byte & mask
1622
1623    _set("aprs_switch", 0)
1624    _set("gps_switch", 1)
1625    _set("latlon_unit", 2)
1626    _set("speed_unit", 3)
1627    _set("distance_unit", 4)
1628    _set("altitude_unit", 5)
1629    _set("time_zone", 6, mask=0x1F)
1630    north_byte = data[7]
1631    if north_byte == 0xFF:
1632        fields["north_south"] = None
1633    else:
1634        fields["north_south"] = 0 if north_byte == 0x4E else 1
1635    fields["latitude_minute"] = None if data[8] == 0xFF else min(59, data[8])
1636    fields["latitude_degree"] = None if data[9] == 0xFF else min(90, data[9])
1637    fields["latitude_second"] = None if data[10] == 0xFF else min(59, data[10])
1638    east_byte = data[11]
1639    if east_byte == 0xFF:
1640        fields["east_west"] = None
1641    else:
1642        fields["east_west"] = 0 if east_byte == 0x57 else 1
1643    fields["longitude_minute"] = None if data[12] == 0xFF else min(59, data[12])
1644    fields["longitude_degree"] = None if data[13] == 0xFF else min(180, data[13])
1645    fields["longitude_second"] = None if data[14] == 0xFF else min(59, data[14])
1646    alt_bytes = data[15:17]
1647    if all(b == 0xFF for b in alt_bytes):
1648        fields["altitude"] = None
1649    else:
1650        altitude = int.from_bytes(bytes(alt_bytes), "little", signed=True)
1651        fields["altitude"] = max(-10000, min(10000, altitude))
1652
1653    fields["call_sign"] = _decode_ascii(data, 17, 6)
1654    _set("ssid", 23)
1655    _set("routing_select", 24)
1656    _set("my_position", 25)
1657    _set("radio_symbol", 26)
1658    if data[27] == 0xFF:
1659        fields["user_defined_icon"] = None
1660    else:
1661        fields["user_defined_icon"] = data[27] & 0x7F
1662    _set("aprs_priority", 29)
1663    _set("data_tx_delay", 30)
1664    _set("aprs_decode_prompt_tone", 32)
1665    _set("aprs_rx_auto_popup", 33)
1666    _set("beacon_tx_type", 34)
1667    _set("timed_beacon_time", 36)
1668    _set("mice_type", 38)
1669    _set("tnc_data_type", 39)
1670    _set("aprs_forward_channel", 40)
1671    _set("aprs_forward_routing", 41)
1672    _set("aprs_wait_forward", 42)
1673    fields["custom_routing_one"] = _decode_ascii(data, 43, 6)
1674    _set("custom_routing_one_ssid", 49)
1675    fields["custom_routing_two"] = _decode_ascii(data, 50, 6)
1676    _set("custom_routing_two_ssid", 56)
1677    _set("send_custom_messages", 78)
1678    fields["custom_messages"] = _decode_gb2312(data, 79, max_len=40)
1679
1680    return APRSSettings(fields=fields)

Decode the 128-byte APRS block.

Latitude is stored at bytes 7-10 (N/S letter, minute, degree, second) and longitude at bytes 11-14 (W/E letter, minute, degree, second). north_south/east_west decode N/W as 0 and any other byte as 1. Minutes and seconds are clamped to 59, degrees to 90/180. Altitude (bytes 15-16) is a little-endian signed 16-bit value clamped to +/-10000. Single-byte settings keep their low nibble (byte 6: 5 bits, byte 27: 7 bits). Text fields are ASCII (call sign, routes) or GB2312 (custom message).

Arguments:
  • section: Exactly 128 bytes.
Returns:

APRSSettings: All known fields; 0xFF bytes become None.

Raises:
  • ValueError: If section is not 128 bytes.
Private constant _DTMF_DIGITS = '0123456789ABCD*#'

DTMF symbols in radio order; a stored byte is an index into this string.

0xFF terminates a sequence.

Encoding helpers

Public function def encode_vfo_section( vfos: Optional[List[VFOSettings]], raw: Optional[bytes]) -> bytes:
1686def encode_vfo_section(vfos: Optional[List[VFOSettings]], raw: Optional[bytes]) -> bytes:
1687    """Encode VFO entries into the 96-byte VFO block.
1688
1689    Unchanged entries are copied back verbatim. Changed entries are written
1690    over their previous bytes, so bits the driver does not know survive,
1691    except that a field byte holding 0xFF is treated as 0 first.
1692    ``rx_hz`` or ``offset_hz`` of ``None`` keeps the stored digits. Entries
1693    beyond the third are ignored. Each re-encoded entry's change-tracking
1694    snapshot is updated to the new bytes.
1695
1696    Args:
1697        vfos: Up to three entries; ``None`` or empty leaves ``raw`` as is.
1698        raw: The original 96 bytes; anything else starts from 0xFF.
1699
1700    Returns:
1701        bytes: The 96-byte VFO block.
1702    """
1703    if raw and len(raw) == 96:
1704        buffer = bytearray(raw)
1705    else:
1706        buffer = bytearray(b"\xFF" * 96)
1707    if not vfos:
1708        return bytes(buffer)
1709    mv = memoryview(buffer)
1710    for idx, entry in enumerate(vfos[:3]):
1711        start = idx * 32
1712        current_state = entry._state_tuple()
1713        if (
1714            entry._original_state is not None
1715            and current_state == entry._original_state
1716            and entry._raw_bytes
1717        ):
1718            mv[start : start + 32] = entry._raw_bytes
1719            continue
1720        source = (
1721            entry._raw_bytes if len(entry._raw_bytes) == 32 else bytes(mv[start : start + 32])
1722        )
1723        chunk = bytearray(source)
1724        if entry.rx_hz is not None:
1725            chunk[0:8] = _encode_vfo_frequency(entry.rx_hz)
1726        chunk[8:10] = entry.rx_tone.to_bytes()
1727        chunk[10:12] = entry.tx_tone.to_bytes()
1728        base13 = 0 if chunk[13] == 0xFF else chunk[13] & ~0x01
1729        chunk[13] = base13 | (0x01 if entry.busy_lockout else 0x00)
1730        preserved14 = 0 if chunk[14] == 0xFF else chunk[14] & 0xC0
1731        chunk[14] = (
1732            preserved14
1733            | ((entry.offset_direction & 0x03) << 4)
1734            | (entry.signalling_group & 0x0F)
1735        )
1736        chunk[16] = ((entry.scrambler & 0x0F) << 4) | (entry.tx_power.value & 0x0F)
1737        flags = 0 if chunk[17] == 0xFF else chunk[17] & ~(0x80 | 0x40 | 0x30 | 0x01)
1738        if entry.learn_fhss:
1739            flags |= 0x80
1740        # Radio uses bit6: 1 = NARROW, 0 = WIDE
1741        if entry.bandwidth is Bandwidth.NARROW:
1742            flags |= 0x40
1743        flags |= (entry.encryption & 0x03) << 4
1744        if entry.rx_modulation is Modulation.AM:
1745            flags |= 0x01
1746        chunk[17] = flags
1747        preserved18 = 0 if chunk[18] == 0xFF else chunk[18] & 0xF0
1748        chunk[18] = preserved18 | (entry.freq_band & 0x0F)
1749        preserved19 = 0 if chunk[19] == 0xFF else chunk[19] & 0xF0
1750        chunk[19] = preserved19 | (entry.step_freq_index & 0x0F)
1751        if entry.offset_hz is not None:
1752            chunk[20:27] = _encode_offset_frequency(entry.offset_hz)
1753        encoded = bytes(chunk)
1754        mv[start : start + 32] = encoded
1755        entry._raw_bytes = encoded
1756        entry._original_state = entry._state_tuple()
1757    return bytes(buffer)

Encode VFO entries into the 96-byte VFO block.

Unchanged entries are copied back verbatim. Changed entries are written over their previous bytes, so bits the driver does not know survive, except that a field byte holding 0xFF is treated as 0 first. rx_hz or offset_hz of None keeps the stored digits. Entries beyond the third are ignored. Each re-encoded entry's change-tracking snapshot is updated to the new bytes.

Arguments:
  • vfos: Up to three entries; None or empty leaves raw as is.
  • raw: The original 96 bytes; anything else starts from 0xFF.
Returns:

bytes: The 96-byte VFO block.

Public function def encode_function_section( settings: Optional[FunctionSettings], raw: Optional[bytes]) -> bytes:
1759def encode_function_section(settings: Optional[FunctionSettings], raw: Optional[bytes]) -> bytes:
1760    """Encode function settings into the 96-byte function block.
1761
1762    Only the bits of each field are replaced; other bits in the same byte
1763    are preserved, but a byte holding 0xFF is treated as 0 when merging
1764    bits. A value of ``None``, or a key missing from ``settings.values``,
1765    writes 0xFF over the whole byte. Byte 26 packs ``work_mode_a/b/c``
1766    (bits 1-0, 3-2, 5-4); it becomes 0xFF if any of the three is ``None``.
1767
1768    Args:
1769        settings: Settings to write; ``None`` leaves ``raw`` as is.
1770        raw: The original 96 bytes; anything else starts from 0xFF.
1771
1772    Returns:
1773        bytes: The 96-byte function block.
1774    """
1775    if raw and len(raw) == 96:
1776        buffer = bytearray(raw)
1777    else:
1778        buffer = bytearray(b"\xFF" * 96)
1779    if settings is None:
1780        return bytes(buffer)
1781    part1 = memoryview(buffer)[0:32]
1782    part2 = memoryview(buffer)[32:64]
1783    part3 = memoryview(buffer)[64:96]
1784    values = settings.values
1785
1786    def _set(part: memoryview, index: int, key: str, mask: int = 0x0F, shift: int = 0) -> None:
1787        """Write ``values[key]`` into ``part[index]`` under ``mask``/``shift``.
1788
1789        ``None`` writes 0xFF; otherwise bits outside ``mask << shift`` are kept,
1790        except that a 0xFF byte is treated as 0.
1791
1792        Args:
1793            part: 32-byte view of one third of the function block.
1794            index: Byte offset within ``part`` (0-31).
1795            key: Setting key in ``settings.values``.
1796            mask: Bit mask of the field before shifting (default ``0x0F``).
1797            shift: Bit position of the field within the byte.
1798        """
1799        value = values.get(key)
1800        if value is None:
1801            part[index] = 0xFF
1802            return
1803        encoded = (int(value) & mask) << shift
1804        current = part[index]
1805        if current == 0xFF:
1806            base = 0
1807        else:
1808            base = current & ~(mask << shift)
1809        part[index] = base | encoded
1810
1811    _set(part1, 0, "sql")
1812    _set(part1, 1, "save_mode")
1813    _set(part1, 2, "vox")
1814    _set(part1, 3, "auto_backlight")
1815    _set(part1, 4, "tdr")
1816    _set(part1, 5, "tot")
1817    _set(part1, 6, "beep_prompt")
1818    _set(part1, 7, "voice_prompt")
1819    _set(part1, 8, "language")
1820    _set(part1, 9, "dtmf_mode")
1821    _set(part1, 10, "scan_mode")
1822    _set(part1, 11, "ptt_id")
1823    _set(part1, 12, "send_id_delay")
1824    _set(part1, 13, "display_mode_a")
1825    _set(part1, 14, "display_mode_b")
1826    _set(part1, 15, "display_mode_c")
1827    _set(part1, 16, "auto_key_lock")
1828    _set(part1, 17, "alarm_mode")
1829    _set(part1, 18, "alarm_sound")
1830    _set(part1, 20, "tail_noise_clear")
1831    _set(part1, 21, "pass_repeater_noise_clear")
1832    _set(part1, 22, "pass_repeater_noise_detect")
1833    _set(part1, 23, "sound_tx_end")
1834    _set(part1, 24, "current_work_mode")
1835    _set(part1, 25, "fm_radio")
1836    a = values.get("work_mode_a")
1837    b = values.get("work_mode_b")
1838    c = values.get("work_mode_c")
1839    if any(v is None for v in (a, b, c)):
1840        part1[26] = 0xFF
1841    else:
1842        preserved = 0 if part1[26] == 0xFF else part1[26] & 0xC0
1843        part1[26] = preserved | ((int(c) & 0x03) << 4) | ((int(b) & 0x03) << 2) | (int(a) & 0x03)
1844    _set(part1, 27, "lock_keyboard")
1845    _set(part1, 28, "power_on_message")
1846    _set(part1, 29, "bt_write_switch")
1847    _set(part1, 30, "rtone")
1848
1849    _set(part2, 0, "vox_delay")
1850    _set(part2, 1, "timer_menu_quit")
1851    _set(part2, 5, "weather_channel")
1852    _set(part2, 6, "divide_channel")
1853    _set(part2, 7, "subaudio_scan_save")
1854    _set(part2, 8, "vox_switch")
1855    _set(part2, 9, "key_side1_short")
1856    _set(part2, 10, "key_side1_long")
1857    _set(part2, 11, "key_side2_short")
1858    _set(part2, 12, "key_side2_long")
1859    _set(part2, 13, "current_work_area_a")
1860    _set(part2, 14, "current_work_area_b")
1861    _set(part2, 15, "current_work_area_c")
1862    _set(part2, 25, "ab_uv_transfer")
1863    _set(part2, 26, "sound_transfer")
1864    _set(part2, 27, "key0_long", mask=0x1F)
1865    _set(part2, 28, "key1_long", mask=0x1F)
1866    _set(part2, 29, "key2_long", mask=0x1F)
1867    _set(part2, 30, "key3_long", mask=0x1F)
1868    _set(part2, 31, "key4_long", mask=0x1F)
1869
1870    _set(part3, 0, "key5_long", mask=0x1F)
1871    _set(part3, 1, "key6_long", mask=0x1F)
1872    _set(part3, 2, "key7_long", mask=0x1F)
1873    _set(part3, 3, "key8_long", mask=0x1F)
1874    _set(part3, 4, "key9_long", mask=0x1F)
1875
1876    return bytes(buffer)

Encode function settings into the 96-byte function block.

Only the bits of each field are replaced; other bits in the same byte are preserved, but a byte holding 0xFF is treated as 0 when merging bits. A value of None, or a key missing from settings.values, writes 0xFF over the whole byte. Byte 26 packs work_mode_a/b/c (bits 1-0, 3-2, 5-4); it becomes 0xFF if any of the three is None.

Arguments:
  • settings: Settings to write; None leaves raw as is.
  • raw: The original 96 bytes; anything else starts from 0xFF.
Returns:

bytes: The 96-byte function block.

Public function def encode_dtmf_section( settings: Optional[DTMFSettings], raw: Optional[bytes]) -> bytes:
1878def encode_dtmf_section(settings: Optional[DTMFSettings], raw: Optional[bytes]) -> bytes:
1879    """Encode DTMF settings into the 384-byte DTMF block.
1880
1881    The own ID and code groups are rewritten only when their text changed,
1882    so the radio's original padding bytes survive otherwise. A rewritten
1883    code group has bytes 6-15 set to 0xFF; groups missing from
1884    ``settings.code_groups`` are encoded as empty. Info bytes 6-8 (PTT ID
1885    mode, last-time send/stop) are always written to the low nibble.
1886
1887    Args:
1888        settings: Settings to write; ``None`` leaves ``raw`` as is.
1889        raw: The original 384 bytes; anything else starts from 0xFF.
1890
1891    Returns:
1892        bytes: The 384-byte DTMF block.
1893    """
1894    if raw and len(raw) == 384:
1895        buffer = bytearray(raw)
1896    else:
1897        buffer = bytearray(b"\xFF" * 384)
1898    if settings is None:
1899        return bytes(buffer)
1900    info = memoryview(buffer)[0:32]
1901    groups = memoryview(buffer)[32:384]
1902
1903    current_raw_id = _decode_dtmf_sequence(bytes(info[0:5]))
1904    if settings.current_id != current_raw_id:
1905        info[0:5] = _encode_dtmf_sequence(settings.current_id, 5)
1906
1907    def _write_mode(index: int, value: Optional[int]) -> None:
1908        """Write a nibble value at info byte ``index``; ``None`` writes 0xFF.
1909
1910        Args:
1911            index: Byte offset within the 32-byte DTMF info area (6, 7 or 8).
1912            value: Value for the low nibble; the high nibble is kept unless 0xFF.
1913        """
1914        if value is None:
1915            info[index] = 0xFF
1916        else:
1917            current = info[index]
1918            base = 0 if current == 0xFF else current & 0xF0
1919            info[index] = base | (int(value) & 0x0F)
1920
1921    _write_mode(6, settings.ptt_id_mode)
1922    _write_mode(7, settings.last_time_send)
1923    _write_mode(8, settings.last_time_stop)
1924
1925    for idx in range(22):
1926        start = idx * 16
1927        seq = settings.code_groups[idx] if idx < len(settings.code_groups) else ""
1928        encoded = _encode_dtmf_sequence(seq, 6)
1929        chunk = bytearray(groups[start : start + 16])
1930        raw_sequence = _decode_dtmf_sequence(bytes(chunk[:16]), max_len=6)
1931        if seq == raw_sequence:
1932            continue
1933        chunk[0:6] = encoded
1934        chunk[6:16] = b"\xFF" * 10
1935        groups[start : start + 16] = chunk
1936
1937    return bytes(buffer)

Encode DTMF settings into the 384-byte DTMF block.

The own ID and code groups are rewritten only when their text changed, so the radio's original padding bytes survive otherwise. A rewritten code group has bytes 6-15 set to 0xFF; groups missing from settings.code_groups are encoded as empty. Info bytes 6-8 (PTT ID mode, last-time send/stop) are always written to the low nibble.

Arguments:
  • settings: Settings to write; None leaves raw as is.
  • raw: The original 384 bytes; anything else starts from 0xFF.
Returns:

bytes: The 384-byte DTMF block.

Public function def encode_modulation_sections( settings: Optional[ModulationSettings], params_raw: Optional[bytes], names_raw: Optional[bytes]) -> tuple[bytes, bytes]:
1939def encode_modulation_sections(
1940    settings: Optional[ModulationSettings],
1941    params_raw: Optional[bytes],
1942    names_raw: Optional[bytes],
1943) -> tuple[bytes, bytes]:
1944    """Encode modulation settings into the parameter and name blocks.
1945
1946    Every field is only rewritten when its value differs from what
1947    :func:`parse_modulation_sections` decodes from the original blocks, so
1948    unedited blocks, including unset (0xFF) fields, are written back
1949    byte-identical. A rewritten frequency of ``None`` is stored as 0x0000,
1950    a bandwidth or beat offset of ``None`` as 0. Entries beyond
1951    ``len(settings.channels)`` (up to 16) are cleared to 0xFF. Parameter
1952    bytes 32, 33, 66-68 and 149-152 are written when their value differs
1953    (``None`` never overwrites).
1954
1955    Args:
1956        settings: Settings to write; ``None`` leaves both blocks as is.
1957        params_raw: The original 256 parameter bytes.
1958        names_raw: The original 768 name bytes.
1959
1960    Returns:
1961        tuple[bytes, bytes]: The 256-byte parameter block and the 768-byte
1962        name block.
1963    """
1964    params = (
1965        bytearray(params_raw) if params_raw and len(params_raw) == 256 else bytearray(b"\xff" * 256)
1966    )
1967    names = (
1968        bytearray(names_raw) if names_raw and len(names_raw) == 768 else bytearray(b"\xff" * 768)
1969    )
1970    if settings is None:
1971        return bytes(params), bytes(names)
1972
1973    stored = parse_modulation_sections(bytes(params), bytes(names))
1974    channels = settings.channels[:16]
1975
1976    def _encode_freq(value: Optional[int]) -> bytes:
1977        """Convert Hz to a LE uint16 in 10 kHz units; ``None``/<=0 gives 0.
1978
1979        Args:
1980            value: Frequency in Hz, or ``None``.
1981
1982        Returns:
1983            bytes: Two bytes, LE uint16 of ``value / 10000`` rounded and clamped
1984            to 0-0xFFFF.
1985        """
1986        if value is None or value <= 0:
1987            return b'\x00\x00'
1988        scaled = max(0, min(0xFFFF, int(round(value / 10_000))))
1989        return _encode_le_uint16(scaled)
1990
1991    for idx, channel in enumerate(channels):
1992        old = stored.channels[idx]
1993        if channel.fm_frequency != old.fm_frequency:
1994            params[idx * 2 : idx * 2 + 2] = _encode_freq(channel.fm_frequency)
1995        if channel.am_frequency != old.am_frequency:
1996            params[34 + idx * 2 : 36 + idx * 2] = _encode_freq(channel.am_frequency)
1997        base = 69 + idx * 5
1998        if channel.ssb_frequency != old.ssb_frequency:
1999            params[base : base + 2] = _encode_freq(channel.ssb_frequency)
2000        if channel.ssb_bandwidth != old.ssb_bandwidth:
2001            params[base + 2] = 0 if channel.ssb_bandwidth is None else channel.ssb_bandwidth & 0xFF
2002        if channel.ssb_beat_offset != old.ssb_beat_offset:
2003            beat_value = (
2004                0
2005                if channel.ssb_beat_offset is None
2006                else max(-32768, min(32767, int(channel.ssb_beat_offset)))
2007            )
2008            params[base + 3 : base + 5] = _encode_le_int16(beat_value)
2009
2010        for table, new_name, old_name in ((0, channel.fm_name, old.fm_name),
2011                                          (256, channel.am_name, old.am_name),
2012                                          (512, channel.ssb_name, old.ssb_name)):
2013            if new_name.rstrip('\x00') != old_name.rstrip('\x00'):
2014                offset = table + idx * 16
2015                names[offset : offset + 16] = _encode_gb2312(new_name, 16)
2016
2017    for idx in range(len(channels), 16):
2018        params[idx * 2 : idx * 2 + 2] = b"\xFF\xFF"
2019        params[34 + idx * 2 : 34 + idx * 2 + 2] = b"\xFF\xFF"
2020        base = 69 + idx * 5
2021        params[base : base + 5] = b"\xFF" * 5
2022        names[idx * 16 : idx * 16 + 16] = b"\xFF" * 16
2023        names[256 + idx * 16 : 256 + idx * 16 + 16] = b"\xFF" * 16
2024        names[512 + idx * 16 : 512 + idx * 16 + 16] = b"\xFF" * 16
2025
2026    for index, attr in ((32, 'fm_current_channel'), (33, 'work_mode'),
2027                        (66, 'am_current_channel'), (67, 'modulation_mode'),
2028                        (68, 'am_rx_gain'), (149, 'ssb_current_channel'),
2029                        (150, 'ssb_step_index'), (151, 'am_step_index'),
2030                        (152, 'ssb_rx_gain')):
2031        value = getattr(settings, attr)
2032        if value is not None and value != getattr(stored, attr):
2033            params[index] = value & 0xFF
2034
2035    return bytes(params), bytes(names)

Encode modulation settings into the parameter and name blocks.

Every field is only rewritten when its value differs from what parse_modulation_sections() decodes from the original blocks, so unedited blocks, including unset (0xFF) fields, are written back byte-identical. A rewritten frequency of None is stored as 0x0000, a bandwidth or beat offset of None as 0. Entries beyond len(settings.channels) (up to 16) are cleared to 0xFF. Parameter bytes 32, 33, 66-68 and 149-152 are written when their value differs (None never overwrites).

Arguments:
  • settings: Settings to write; None leaves both blocks as is.
  • params_raw: The original 256 parameter bytes.
  • names_raw: The original 768 name bytes.
Returns:

tuple[bytes, bytes]: The 256-byte parameter block and the 768-byte name block.

Public function def encode_aprs_section( settings: Optional[APRSSettings], raw: Optional[bytes]) -> bytes:
2037def encode_aprs_section(settings: Optional[APRSSettings], raw: Optional[bytes]) -> bytes:
2038    """Encode APRS settings into the 128-byte APRS block.
2039
2040    Every field is only changed when its value differs from what
2041    :func:`parse_aprs_section` decodes from ``raw``, so an unedited block is
2042    written back byte-identical, including stored values outside the normal
2043    ranges (an N/S or W/E byte other than the letters, minutes above 59, bit
2044    7 of byte 27). A changed field is written normalised. A key missing from
2045    ``settings.fields`` writes 0xFF.
2046
2047    Args:
2048        settings: Settings to write; ``None`` leaves ``raw`` as is.
2049        raw: The original 128 bytes; anything else starts from 0xFF.
2050
2051    Returns:
2052        bytes: The 128-byte APRS block.
2053    """
2054    if raw and len(raw) == 128:
2055        data = bytearray(raw)
2056    else:
2057        data = bytearray(b"\xFF" * 128)
2058    if settings is None:
2059        return bytes(data)
2060
2061    fields = settings.fields
2062    stored = parse_aprs_section(bytes(data)).fields
2063
2064    def _edited(key: str) -> bool:
2065        """Return whether ``fields[key]`` differs from the value decoded from ``raw``.
2066
2067        Args:
2068            key: Field key in ``settings.fields``.
2069
2070        Returns:
2071            bool: ``True`` if the field must be written.
2072        """
2073        return fields.get(key) != stored.get(key)
2074
2075    def _set(idx: int, key: str, mask: int = 0x0F) -> None:
2076        """Write ``fields[key]`` at ``idx`` under ``mask``; ``None`` writes 0xFF.
2077
2078        Args:
2079            idx: Byte offset within the 128-byte APRS block.
2080            key: Field key in ``settings.fields``.
2081            mask: Bit mask of the field (default ``0x0F``).
2082        """
2083        value = fields.get(key)
2084        current = data[idx]
2085        if value is None:
2086            if current != 0xFF:
2087                data[idx] = 0xFF
2088            return
2089        encoded = int(value) & mask
2090        base = 0 if current == 0xFF else current & ~mask
2091        new_value = base | encoded
2092        if new_value != current:
2093            data[idx] = new_value
2094
2095    _set(0, "aprs_switch")
2096    _set(1, "gps_switch")
2097    _set(2, "latlon_unit")
2098    _set(3, "speed_unit")
2099    _set(4, "distance_unit")
2100    _set(5, "altitude_unit")
2101    _set(6, "time_zone", mask=0x1F)
2102
2103    if _edited("north_south"):
2104        north = fields.get("north_south")
2105        data[7] = 0xFF if north is None else (0x4E if int(north) == 0 else 0x53)
2106    for idx, key, limit in ((8, "latitude_minute", 59), (9, "latitude_degree", 90),
2107                            (10, "latitude_second", 59), (12, "longitude_minute", 59),
2108                            (13, "longitude_degree", 180), (14, "longitude_second", 59)):
2109        if _edited(key):
2110            data[idx] = _encode_optional_bounded(fields.get(key), limit)
2111    if _edited("east_west"):
2112        east = fields.get("east_west")
2113        data[11] = 0xFF if east is None else (0x57 if int(east) == 0 else 0x45)
2114
2115    if _edited("altitude"):
2116        altitude = fields.get("altitude")
2117        if altitude is None:
2118            data[15:17] = b"\xFF\xFF"
2119        else:
2120            alt = max(-10000, min(10000, int(altitude)))
2121            data[15:17] = alt.to_bytes(2, "little", signed=True)
2122
2123    call_sign_value = fields.get("call_sign")
2124    raw_call_sign_bytes = data[17:23]
2125    raw_call_sign = _decode_ascii(data, 17, 6)
2126    if call_sign_value is None:
2127        if any(b != 0xFF for b in raw_call_sign_bytes):
2128            data[17:23] = _encode_ascii(None, 6)
2129    elif call_sign_value != raw_call_sign:
2130        data[17:23] = _encode_ascii(call_sign_value, 6)
2131    _set(23, "ssid")
2132    _set(24, "routing_select")
2133    _set(25, "my_position")
2134    _set(26, "radio_symbol")
2135    if _edited("user_defined_icon"):
2136        icon = fields.get("user_defined_icon")
2137        data[27] = 0xFF if icon is None else int(icon) & 0x7F
2138    _set(29, "aprs_priority")
2139    _set(30, "data_tx_delay")
2140    _set(32, "aprs_decode_prompt_tone")
2141    _set(33, "aprs_rx_auto_popup")
2142    _set(34, "beacon_tx_type")
2143    _set(36, "timed_beacon_time")
2144    _set(38, "mice_type")
2145    _set(39, "tnc_data_type")
2146    _set(40, "aprs_forward_channel")
2147    _set(41, "aprs_forward_routing")
2148    _set(42, "aprs_wait_forward")
2149    custom_one = fields.get("custom_routing_one")
2150    raw_custom_one_bytes = data[43:49]
2151    raw_custom_one = _decode_ascii(data, 43, 6)
2152    if custom_one is None:
2153        if any(b != 0xFF for b in raw_custom_one_bytes):
2154            data[43:49] = _encode_ascii(None, 6)
2155    elif custom_one != raw_custom_one:
2156        data[43:49] = _encode_ascii(custom_one, 6)
2157    _set(49, "custom_routing_one_ssid")
2158    custom_two = fields.get("custom_routing_two")
2159    raw_custom_two_bytes = data[50:56]
2160    raw_custom_two = _decode_ascii(data, 50, 6)
2161    if custom_two is None:
2162        if any(b != 0xFF for b in raw_custom_two_bytes):
2163            data[50:56] = _encode_ascii(None, 6)
2164    elif custom_two != raw_custom_two:
2165        data[50:56] = _encode_ascii(custom_two, 6)
2166    _set(56, "custom_routing_two_ssid")
2167    _set(78, "send_custom_messages")
2168    custom_messages = fields.get("custom_messages")
2169    raw_custom_messages_bytes = data[79:119]
2170    raw_custom_messages = _decode_gb2312(data, 79, max_len=40)
2171    if custom_messages is None:
2172        if any(b != 0xFF for b in raw_custom_messages_bytes):
2173            data[79:119] = b"\xFF" * 40
2174    elif custom_messages != raw_custom_messages:
2175        data[79:119] = _encode_gb2312(custom_messages, 40)
2176
2177    return bytes(data)

Encode APRS settings into the 128-byte APRS block.

Every field is only changed when its value differs from what parse_aprs_section() decodes from raw, so an unedited block is written back byte-identical, including stored values outside the normal ranges (an N/S or W/E byte other than the letters, minutes above 59, bit 7 of byte 27). A changed field is written normalised. A key missing from settings.fields writes 0xFF.

Arguments:
  • settings: Settings to write; None leaves raw as is.
  • raw: The original 128 bytes; anything else starts from 0xFF.
Returns:

bytes: The 128-byte APRS block.

Decode helpers

Private function def _decode_vfo_frequency(digits: bytes) -> Optional[int]:
2183def _decode_vfo_frequency(digits: bytes) -> Optional[int]:
2184    """Decode an 8-byte VFO frequency (one decimal digit per byte).
2185
2186    The digits read as MHz with five decimals: ``1 4 5 5 0 0 0 0`` is
2187    145.50000 MHz.
2188
2189    Args:
2190        digits: Eight bytes, each 0-9. Bytes outside 0-9 are not validated
2191            and produce a wrong value.
2192
2193    Returns:
2194        int | None: Frequency in Hz, or ``None`` if all bytes are 0x00/0xFF.
2195    """
2196    if all(b in (0x00, 0xFF) for b in digits):
2197        return None
2198    value = int("".join(str(b) for b in digits))
2199    mhz = value / 100000.0
2200    return int(round(mhz * 1_000_000))

Decode an 8-byte VFO frequency (one decimal digit per byte).

The digits read as MHz with five decimals: 1 4 5 5 0 0 0 0 is 145.50000 MHz.

Arguments:
  • digits: Eight bytes, each 0-9. Bytes outside 0-9 are not validated and produce a wrong value.
Returns:

int | None: Frequency in Hz, or None if all bytes are 0x00/0xFF.

Private function def _decode_offset_frequency(digits: bytes) -> Optional[int]:
2202def _decode_offset_frequency(digits: bytes) -> Optional[int]:
2203    """Decode a 7-byte VFO offset (one decimal digit per byte).
2204
2205    The digits read as MHz with four decimals: ``0 0 0 6 0 0 0`` is
2206    0.6000 MHz.
2207
2208    Args:
2209        digits: Seven bytes, each 0-9.
2210
2211    Returns:
2212        int | None: Offset in Hz, or ``None`` if all bytes are 0x00/0xFF.
2213    """
2214    if all(b in (0x00, 0xFF) for b in digits):
2215        return None
2216    value = int("".join(str(b) for b in digits))
2217    mhz = value / 10000.0
2218    return int(round(mhz * 1_000_000))

Decode a 7-byte VFO offset (one decimal digit per byte).

The digits read as MHz with four decimals: 0 0 0 6 0 0 0 is 0.6000 MHz.

Arguments:
  • digits: Seven bytes, each 0-9.
Returns:

int | None: Offset in Hz, or None if all bytes are 0x00/0xFF.

Private function def _decode_dtmf_sequence(data: bytes, *, max_len: int = 5) -> str:
2220def _decode_dtmf_sequence(data: bytes, *, max_len: int = 5) -> str:
2221    """Decode a DTMF sequence stored as indexes into ``_DTMF_DIGITS``.
2222
2223    Args:
2224        data: The stored bytes.
2225        max_len: Maximum number of symbols to read.
2226
2227    Returns:
2228        str: The symbols up to the first 0xFF or ``max_len`` bytes; bytes
2229        that are not valid symbol indexes are skipped.
2230    """
2231    sequence = []
2232    for byte in data[:max_len]:
2233        if byte == 0xFF:
2234            break
2235        if 0 <= byte < len(_DTMF_DIGITS):
2236            sequence.append(_DTMF_DIGITS[byte])
2237    return "".join(sequence)

Decode a DTMF sequence stored as indexes into _DTMF_DIGITS.

Arguments:
  • data: The stored bytes.
  • max_len: Maximum number of symbols to read.
Returns:

str: The symbols up to the first 0xFF or max_len bytes; bytes that are not valid symbol indexes are skipped.

Private function def _decode_le_uint16(buffer: bytes, offset: int) -> int:
2239def _decode_le_uint16(buffer: bytes, offset: int) -> int:
2240    """Read an unsigned little-endian 16-bit value at ``offset``.
2241
2242    Args:
2243        buffer: Source bytes.
2244        offset: Byte offset of the low byte.
2245
2246    Returns:
2247        int: The value, 0-65535.
2248    """
2249    return int.from_bytes(buffer[offset : offset + 2], "little")

Read an unsigned little-endian 16-bit value at offset.

Arguments:
  • buffer: Source bytes.
  • offset: Byte offset of the low byte.
Returns:

int: The value, 0-65535.

Private function def _decode_le_int16(buffer: bytes, offset: int) -> int:
2251def _decode_le_int16(buffer: bytes, offset: int) -> int:
2252    """Read a signed little-endian 16-bit value at ``offset``.
2253
2254    Args:
2255        buffer: Source bytes.
2256        offset: Byte offset of the low byte.
2257
2258    Returns:
2259        int: The value, -32768 to 32767.
2260    """
2261    return int.from_bytes(buffer[offset : offset + 2], "little", signed=True)

Read a signed little-endian 16-bit value at offset.

Arguments:
  • buffer: Source bytes.
  • offset: Byte offset of the low byte.
Returns:

int: The value, -32768 to 32767.

Private function def _decode_gb2312(buffer: bytes, offset: int, max_len: int = 12) -> str:
2263def _decode_gb2312(buffer: bytes, offset: int, max_len: int = 12) -> str:
2264    """Decode a GB2312 string of at most ``max_len`` bytes.
2265
2266    Bytes >= 0xA1 start a two-byte character. Decoding stops at 0x00 or
2267    0xFF; invalid sequences are replaced.
2268
2269    Args:
2270        buffer: Source bytes.
2271        offset: Start of the string.
2272        max_len: Maximum number of bytes to consume.
2273
2274    Returns:
2275        str: The decoded, stripped text.
2276    """
2277    data = bytearray()
2278    consumed = 0
2279    buf_len = len(buffer)
2280    while consumed < max_len and (offset + consumed) < buf_len:
2281        byte = buffer[offset + consumed]
2282        if byte in (0xFF, 0x00):
2283            break
2284        if (
2285            byte >= 0xA1
2286            and consumed + 1 < max_len
2287            and (offset + consumed + 1) < buf_len
2288        ):
2289            data.extend(buffer[offset + consumed : offset + consumed + 2])
2290            consumed += 2
2291        else:
2292            data.append(byte)
2293            consumed += 1
2294    if not data:
2295        return ""
2296    return bytes(data).decode("gb2312", errors="replace").strip()

Decode a GB2312 string of at most max_len bytes.

Bytes >= 0xA1 start a two-byte character. Decoding stops at 0x00 or 0xFF; invalid sequences are replaced.

Arguments:
  • buffer: Source bytes.
  • offset: Start of the string.
  • max_len: Maximum number of bytes to consume.
Returns:

str: The decoded, stripped text.

Private function def _decode_ascii(buffer: bytes, offset: int, max_len: int) -> str:
2298def _decode_ascii(buffer: bytes, offset: int, max_len: int) -> str:
2299    """Decode an ASCII string of at most ``max_len`` bytes.
2300
2301    Args:
2302        buffer: Source bytes.
2303        offset: Start of the string.
2304        max_len: Maximum length; 0x00 or 0xFF ends the string earlier.
2305
2306    Returns:
2307        str: The decoded, stripped text; non-ASCII bytes are dropped.
2308    """
2309    length = 0
2310    buf_len = len(buffer)
2311    for idx in range(max_len):
2312        if (offset + idx) >= buf_len:
2313            break
2314        if buffer[offset + idx] in (0xFF, 0x00):
2315            break
2316        length += 1
2317    if length == 0:
2318        return ""
2319    return buffer[offset : offset + length].decode("ascii", errors="ignore").strip()

Decode an ASCII string of at most max_len bytes.

Arguments:
  • buffer: Source bytes.
  • offset: Start of the string.
  • max_len: Maximum length; 0x00 or 0xFF ends the string earlier.
Returns:

str: The decoded, stripped text; non-ASCII bytes are dropped.

Encode helper utilities

Private function def _encode_vfo_frequency(hz: Optional[int]) -> bytes:
2325def _encode_vfo_frequency(hz: Optional[int]) -> bytes:
2326    """Encode a frequency into 8 VFO digit bytes (MHz with five decimals).
2327
2328    Args:
2329        hz: Frequency in Hz, or ``None`` for 0xFF x 8.
2330
2331    Returns:
2332        bytes: Eight bytes, one decimal digit each.
2333    """
2334    if hz is None:
2335        return b"\xFF" * 8
2336    mhz = hz / 1_000_000.0
2337    digits = f"{mhz:0.5f}".replace(".", "")
2338    digits = digits[:8].rjust(8, "0")
2339    return bytes(int(ch) for ch in digits)

Encode a frequency into 8 VFO digit bytes (MHz with five decimals).

Arguments:
  • hz: Frequency in Hz, or None for 0xFF x 8.
Returns:

bytes: Eight bytes, one decimal digit each.

Private function def _encode_offset_frequency(hz: Optional[int]) -> bytes:
2341def _encode_offset_frequency(hz: Optional[int]) -> bytes:
2342    """Encode an offset into 7 VFO digit bytes (MHz with four decimals).
2343
2344    Args:
2345        hz: Offset in Hz, or ``None`` for 0xFF x 7.
2346
2347    Returns:
2348        bytes: Seven bytes, one decimal digit each.
2349    """
2350    if hz is None:
2351        return b"\xFF" * 7
2352    value = int(round((hz / 1_000_000.0) * 10000))
2353    digits = f"{value:07d}"
2354    return bytes(int(ch) for ch in digits)

Encode an offset into 7 VFO digit bytes (MHz with four decimals).

Arguments:
  • hz: Offset in Hz, or None for 0xFF x 7.
Returns:

bytes: Seven bytes, one decimal digit each.

Private function def _encode_dtmf_sequence(seq: str, max_len: int) -> bytes:
2356def _encode_dtmf_sequence(seq: str, max_len: int) -> bytes:
2357    """Encode DTMF symbols as indexes into ``_DTMF_DIGITS``.
2358
2359    Unknown symbols are skipped (their position stays 0xFF).
2360
2361    Args:
2362        seq: DTMF symbols, e.g. ``"123A#"``.
2363        max_len: Field length in bytes.
2364
2365    Returns:
2366        bytes: ``max_len`` bytes padded with 0xFF.
2367    """
2368    out = bytearray(b"\xFF" * max_len)
2369    if not seq:
2370        return bytes(out)
2371    for idx, char in enumerate(seq[:max_len]):
2372        pos = _DTMF_DIGITS.find(char)
2373        if pos == -1:
2374            pos = _DTMF_DIGITS.find(char.upper())
2375        if pos == -1:
2376            continue
2377        out[idx] = pos
2378    return bytes(out)

Encode DTMF symbols as indexes into _DTMF_DIGITS.

Unknown symbols are skipped (their position stays 0xFF).

Arguments:
  • seq: DTMF symbols, e.g. "123A#".
  • max_len: Field length in bytes.
Returns:

bytes: max_len bytes padded with 0xFF.

Private function def _encode_le_uint16(value: int) -> bytes:
2380def _encode_le_uint16(value: int) -> bytes:
2381    """Encode a value as unsigned little-endian 16-bit; negatives become 0.
2382
2383    Args:
2384        value: Value to encode; must not exceed 0xFFFF.
2385
2386    Returns:
2387        bytes: Two bytes, low byte first.
2388    """
2389    return int(max(0, value)).to_bytes(2, "little", signed=False)

Encode a value as unsigned little-endian 16-bit; negatives become 0.

Arguments:
  • value: Value to encode; must not exceed 0xFFFF.
Returns:

bytes: Two bytes, low byte first.

Private function def _encode_le_int16(value: int) -> bytes:
2391def _encode_le_int16(value: int) -> bytes:
2392    """Encode a value as signed little-endian 16-bit.
2393
2394    Args:
2395        value: Value to encode, -32768 to 32767.
2396
2397    Returns:
2398        bytes: Two bytes, low byte first (two's complement).
2399    """
2400    return int(value).to_bytes(2, "little", signed=True)

Encode a value as signed little-endian 16-bit.

Arguments:
  • value: Value to encode, -32768 to 32767.
Returns:

bytes: Two bytes, low byte first (two's complement).

Private function def _encode_gb2312(text: Optional[str], max_len: int) -> bytes:
2402def _encode_gb2312(text: Optional[str], max_len: int) -> bytes:
2403    """Encode text as GB2312 into a fixed-length field.
2404
2405    Text longer than ``max_len`` bytes is cut before the first character
2406    that does not fit completely, so a two-byte character is never halved.
2407
2408    Args:
2409        text: Text to encode; unencodable characters are dropped.
2410        max_len: Field length in bytes.
2411
2412    Returns:
2413        bytes: ``max_len`` bytes padded with 0xFF.
2414    """
2415    if not text:
2416        return b"\xFF" * max_len
2417    encoded = bytearray()
2418    for char in text:
2419        char_bytes = char.encode("gb2312", errors="ignore")
2420        if len(encoded) + len(char_bytes) > max_len:
2421            break
2422        encoded += char_bytes
2423    return bytes(encoded) + b"\xFF" * (max_len - len(encoded))

Encode text as GB2312 into a fixed-length field.

Text longer than max_len bytes is cut before the first character that does not fit completely, so a two-byte character is never halved.

Arguments:
  • text: Text to encode; unencodable characters are dropped.
  • max_len: Field length in bytes.
Returns:

bytes: max_len bytes padded with 0xFF.

Private function def _encode_ascii(text: Optional[str], length: int) -> bytes:
2425def _encode_ascii(text: Optional[str], length: int) -> bytes:
2426    """Encode text as ASCII into a fixed-length field.
2427
2428    Args:
2429        text: Text to encode; non-ASCII characters are dropped.
2430        length: Field length in bytes.
2431
2432    Returns:
2433        bytes: ``length`` bytes padded with 0xFF.
2434    """
2435    if not text:
2436        return b"\xFF" * length
2437    encoded = text.encode("ascii", errors="ignore")[:length]
2438    return encoded + b"\xFF" * (length - len(encoded))

Encode text as ASCII into a fixed-length field.

Arguments:
  • text: Text to encode; non-ASCII characters are dropped.
  • length: Field length in bytes.
Returns:

bytes: length bytes padded with 0xFF.

Private function def _encode_optional_bounded(value: Optional[object], maximum: int) -> int:
2440def _encode_optional_bounded(value: Optional[object], maximum: int) -> int:
2441    """Encode an optional value as one byte, capped at ``maximum``.
2442
2443    Args:
2444        value: Value to encode, or ``None``.
2445        maximum: Upper bound.
2446
2447    Returns:
2448        int: 0xFF for ``None``, otherwise ``min(maximum, value)``.
2449    """
2450    if value is None:
2451        return 0xFF
2452    return min(maximum, int(value)) & 0xFF

Encode an optional value as one byte, capped at maximum.

Arguments:
  • value: Value to encode, or None.
  • maximum: Upper bound.
Returns:

int: 0xFF for None, otherwise min(maximum, value).

3. Settings API: validated access to the settings sections

validated getters and setters (get_*/set_*).

Public class class SettingsError(builtins.ValueError):
2459class SettingsError(ValueError):
2460    """Raised when a setting is given a value outside its allowed range."""

Raised when a setting is given a value outside its allowed range.

Public class
@dataclass(frozen=True)
class SettingSpec:
2462@dataclass(frozen=True)
2463class SettingSpec:
2464    """Validation rule for one setting."""
2465
2466    kind: str  # "bool", "int", "enum", "string"
2467    """``"bool"``, ``"int"``, ``"enum"`` or ``"string"``."""
2468    min_value: Optional[int] = None
2469    """Lowest allowed value for ``"int"``."""
2470    max_value: Optional[int] = None
2471    """Highest allowed value for ``"int"``."""
2472    choices: Optional[Iterable[int]] = None
2473    """Allowed values for ``"enum"``."""
2474    max_length: Optional[int] = None
2475    """Maximum length for ``"string"``."""

Validation rule for one setting.

Fields
Public field kind: str

"bool", "int", "enum" or "string".

Public field min_value: Optional[int] = None

Lowest allowed value for "int".

Public field max_value: Optional[int] = None

Highest allowed value for "int".

Public field choices: Optional[Iterable[int]] = None

Allowed values for "enum".

Public field max_length: Optional[int] = None

Maximum length for "string".

Function block helpers

Public function def function_keys() -> Iterable[str]:
2561def function_keys() -> Iterable[str]:
2562    """List the names of all function settings.
2563
2564    Returns:
2565        Iterable[str]: Keys accepted by :func:`get_function_value` and
2566        :func:`set_function_value`.
2567    """
2568    return _FUNCTION_SPECS.keys()

List the names of all function settings.

Returns:

Iterable[str]: Keys accepted by get_function_value() and set_function_value().

Public function def get_function_value(settings: FunctionSettings, key: str):
2619def get_function_value(settings: FunctionSettings, key: str):
2620    """Read one function setting.
2621
2622    Args:
2623        settings: Function settings.
2624        key: Setting name (see :func:`function_keys`).
2625
2626    Returns:
2627        bool | int | None: A ``bool`` for boolean settings, otherwise the
2628        stored integer; ``None`` if not set.
2629
2630    Raises:
2631        KeyError: If ``key`` is unknown.
2632    """
2633    if key not in _FUNCTION_SPECS:
2634        raise KeyError(key)
2635    value = settings.values.get(key)
2636    if value is None:
2637        return None
2638    spec = _FUNCTION_SPECS[key]
2639    if spec.kind == "bool":
2640        return bool(value)
2641    return value

Read one function setting.

Arguments:
Returns:

bool | int | None: A bool for boolean settings, otherwise the stored integer; None if not set.

Raises:
  • KeyError: If key is unknown.
Public function def set_function_value(settings: FunctionSettings, key: str, value) -> None:
2643def set_function_value(settings: FunctionSettings, key: str, value) -> None:
2644    """Validate and store one function setting.
2645
2646    Args:
2647        settings: Function settings to update.
2648        key: Setting name (see :func:`function_keys`).
2649        value: New value, or ``None`` to mark it as not set.
2650
2651    Raises:
2652        KeyError: If ``key`` is unknown.
2653        SettingsError: If ``value`` is not allowed.
2654    """
2655    if key not in _FUNCTION_SPECS:
2656        raise KeyError(key)
2657    if value is None:
2658        settings.values[key] = None
2659        return
2660    spec = _FUNCTION_SPECS[key]
2661    encoded = _validate(spec, value)
2662    settings.values[key] = encoded

Validate and store one function setting.

Arguments:
  • settings: Function settings to update.
  • key: Setting name (see function_keys()).
  • value: New value, or None to mark it as not set.
Raises:
  • KeyError: If key is unknown.
  • SettingsError: If value is not allowed.
Private function def _coerce_bool(value) -> int:
2570def _coerce_bool(value) -> int:
2571    """Convert ``True``/``False``/0/1 to 0 or 1.
2572
2573    Args:
2574        value: Proposed value for a boolean setting.
2575
2576    Returns:
2577        int: 1 for ``True``/1, 0 for ``False``/0.
2578
2579    Raises:
2580        SettingsError: For any other value.
2581    """
2582    if isinstance(value, bool):
2583        return 1 if value else 0
2584    if value in (0, 1):
2585        return int(value)
2586    raise SettingsError("Boolean setting expects True/False or 0/1")

Convert True/False/0/1 to 0 or 1.

Arguments:
  • value: Proposed value for a boolean setting.
Returns:

int: 1 for True/1, 0 for False/0.

Raises:
  • SettingsError: For any other value.
Private function def _validate(spec: SettingSpec, value) -> int:
2588def _validate(spec: SettingSpec, value) -> int:
2589    """Check ``value`` against ``spec`` and return the value to store.
2590
2591    Args:
2592        spec: Validation rule.
2593        value: Proposed value.
2594
2595    Returns:
2596        int: The value to store (0/1 for booleans).
2597
2598    Raises:
2599        SettingsError: If the value is of the wrong type or out of range, or
2600            if ``spec.kind`` is not ``bool``/``int``/``enum`` (strings are
2601            validated by :func:`set_aprs_value`).
2602    """
2603    if spec.kind == "bool":
2604        return _coerce_bool(value)
2605    if not isinstance(value, int):
2606        raise SettingsError("Setting expects integer value")
2607    if spec.kind == "int":
2608        if spec.min_value is not None and value < spec.min_value:
2609            raise SettingsError(f"Value {value} below minimum {spec.min_value}")
2610        if spec.max_value is not None and value > spec.max_value:
2611            raise SettingsError(f"Value {value} above maximum {spec.max_value}")
2612        return value
2613    if spec.kind == "enum":
2614        if spec.choices is not None and value not in spec.choices:
2615            raise SettingsError(f"Value {value} not in allowed choices {tuple(spec.choices)}")
2616        return value
2617    raise SettingsError(f"Unsupported setting kind {spec.kind}")

Check value against spec and return the value to store.

Arguments:
  • spec: Validation rule.
  • value: Proposed value.
Returns:

int: The value to store (0/1 for booleans).

Raises:
  • SettingsError: If the value is of the wrong type or out of range, or if spec.kind is not bool/int/enum (strings are validated by set_aprs_value()).
Public constant CHANNEL_DIVIDE_ZONE = 0

Value of the function setting divide_channel (byte 0x9026) for the CPS choice Zone CH Mode: the radio shows 10 zones of 99 channels. Measured on hardware (firmware 0.29, CPS v1.3.3).

Public constant CHANNEL_DIVIDE_ALL = 1

Value of the function setting divide_channel (byte 0x9026) for the CPS choice All CH Mode: the radio shows one list of channels 1-990, the zones placed one after the other; empty channels stay empty. Measured on hardware (firmware 0.29, CPS v1.3.3); switching the mode changed no other byte of the clone image.

Private constant _FUNCTION_SPECS: Dict[str, SettingSpec] = {'sql': SettingSpec(kind='int', min_value=0, max_value=9, choices=None, max_length=None), 'save_mode': SettingSpec(kind='int', min_value=0, max_value=3, choices=None, max_length=None), 'vox': SettingSpec(kind='int', min_value=0, max_value=9, choices=None, max_length=None), 'auto_backlight': SettingSpec(kind='int', min_value=0, max_value=9, choices=None, max_length=None), 'tdr': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'tot': SettingSpec(kind='int', min_value=0, max_value=9, choices=None, max_length=None), 'beep_prompt': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'voice_prompt': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'language': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'dtmf_mode': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3), max_length=None), 'scan_mode': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'ptt_id': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3), max_length=None), 'send_id_delay': SettingSpec(kind='int', min_value=0, max_value=9, choices=None, max_length=None), 'display_mode_a': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'display_mode_b': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'display_mode_c': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'auto_key_lock': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'alarm_mode': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'alarm_sound': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'tail_noise_clear': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'pass_repeater_noise_clear': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'pass_repeater_noise_detect': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'sound_tx_end': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'current_work_mode': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'fm_radio': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'work_mode_a': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3), max_length=None), 'work_mode_b': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3), max_length=None), 'work_mode_c': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3), max_length=None), 'lock_keyboard': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'power_on_message': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'bt_write_switch': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'rtone': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'vox_delay': SettingSpec(kind='int', min_value=0, max_value=9, choices=None, max_length=None), 'timer_menu_quit': SettingSpec(kind='int', min_value=0, max_value=9, choices=None, max_length=None), 'weather_channel': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), max_length=None), 'divide_channel': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1), max_length=None), 'subaudio_scan_save': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'vox_switch': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'key_side1_short': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7), max_length=None), 'key_side1_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7), max_length=None), 'key_side2_short': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6), max_length=None), 'key_side2_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6), max_length=None), 'current_work_area_a': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), max_length=None), 'current_work_area_b': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), max_length=None), 'current_work_area_c': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), max_length=None), 'ab_uv_transfer': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'sound_transfer': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'key0_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), max_length=None), 'key1_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), max_length=None), 'key2_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), max_length=None), 'key3_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), max_length=None), 'key4_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), max_length=None), 'key5_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), max_length=None), 'key6_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), max_length=None), 'key7_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), max_length=None), 'key8_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), max_length=None), 'key9_long': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31), max_length=None)}

Validation rule per function setting, keyed by the names in FunctionSettings.

key_side1_short/long are PF1 Short/Long in the CPS (8 functions: Radio, Moni, Scan, Search, SOS, Spectrum, BeaconTx, PTTC = 0-7); key_side2_* are PF2 (the same without PTTC, 0-6). Confirmed on a radio.

APRS helpers

Public function def aprs_keys() -> Iterable[str]:
2719def aprs_keys() -> Iterable[str]:
2720    """List the names of all APRS settings.
2721
2722    Returns:
2723        Iterable[str]: Keys accepted by :func:`get_aprs_value` and
2724        :func:`set_aprs_value`.
2725    """
2726    return _APRS_SPECS.keys()

List the names of all APRS settings.

Returns:

Iterable[str]: Keys accepted by get_aprs_value() and set_aprs_value().

Public function def get_aprs_value(settings: APRSSettings, key: str):
2728def get_aprs_value(settings: APRSSettings, key: str):
2729    """Read one APRS setting.
2730
2731    Args:
2732        settings: APRS settings.
2733        key: Setting name (see :func:`aprs_keys`).
2734
2735    Returns:
2736        bool | int | str | None: A ``bool`` for boolean settings, otherwise
2737        the stored value; ``None`` if not set.
2738
2739    Raises:
2740        KeyError: If ``key`` is unknown.
2741    """
2742    if key not in _APRS_SPECS:
2743        raise KeyError(key)
2744    value = settings.fields.get(key)
2745    spec = _APRS_SPECS[key]
2746    if value is None:
2747        return None
2748    if spec.kind == "bool":
2749        return bool(value)
2750    return value

Read one APRS setting.

Arguments:
  • settings: APRS settings.
  • key: Setting name (see aprs_keys()).
Returns:

bool | int | str | None: A bool for boolean settings, otherwise the stored value; None if not set.

Raises:
  • KeyError: If key is unknown.
Public function def set_aprs_value(settings: APRSSettings, key: str, value) -> None:
2752def set_aprs_value(settings: APRSSettings, key: str, value) -> None:
2753    """Validate and store one APRS setting.
2754
2755    Args:
2756        settings: APRS settings to update.
2757        key: Setting name (see :func:`aprs_keys`).
2758        value: New value, or ``None`` to mark it as not set.
2759
2760    Raises:
2761        KeyError: If ``key`` is unknown.
2762        SettingsError: If ``value`` is not allowed.
2763    """
2764    if key not in _APRS_SPECS:
2765        raise KeyError(key)
2766    if value is None:
2767        settings.fields[key] = None
2768        return
2769    spec = _APRS_SPECS[key]
2770    if spec.kind == "string":
2771        if not isinstance(value, str):
2772            raise SettingsError("String setting expects str value")
2773        if spec.max_length is not None and len(value) > spec.max_length:
2774            raise SettingsError(
2775                f"String '{value}' longer than allowed {spec.max_length} characters"
2776            )
2777        settings.fields[key] = value
2778        return
2779    encoded = _validate(spec, value)
2780    settings.fields[key] = encoded

Validate and store one APRS setting.

Arguments:
  • settings: APRS settings to update.
  • key: Setting name (see aprs_keys()).
  • value: New value, or None to mark it as not set.
Raises:
  • KeyError: If key is unknown.
  • SettingsError: If value is not allowed.
Private constant _APRS_SPECS: Dict[str, SettingSpec] = {'aprs_switch': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'gps_switch': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'latlon_unit': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1), max_length=None), 'speed_unit': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1), max_length=None), 'distance_unit': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1), max_length=None), 'altitude_unit': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1), max_length=None), 'time_zone': SettingSpec(kind='int', min_value=0, max_value=23, choices=None, max_length=None), 'north_south': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1), max_length=None), 'latitude_minute': SettingSpec(kind='int', min_value=0, max_value=59, choices=None, max_length=None), 'latitude_degree': SettingSpec(kind='int', min_value=0, max_value=90, choices=None, max_length=None), 'latitude_second': SettingSpec(kind='int', min_value=0, max_value=59, choices=None, max_length=None), 'east_west': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1), max_length=None), 'longitude_minute': SettingSpec(kind='int', min_value=0, max_value=59, choices=None, max_length=None), 'longitude_degree': SettingSpec(kind='int', min_value=0, max_value=180, choices=None, max_length=None), 'longitude_second': SettingSpec(kind='int', min_value=0, max_value=59, choices=None, max_length=None), 'altitude': SettingSpec(kind='int', min_value=-10000, max_value=10000, choices=None, max_length=None), 'call_sign': SettingSpec(kind='string', min_value=None, max_value=None, choices=None, max_length=6), 'ssid': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), max_length=None), 'routing_select': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5), max_length=None), 'my_position': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5), max_length=None), 'radio_symbol': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4), max_length=None), 'user_defined_icon': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127), max_length=None), 'aprs_priority': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'data_tx_delay': SettingSpec(kind='int', min_value=0, max_value=9, choices=None, max_length=None), 'aprs_decode_prompt_tone': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'aprs_rx_auto_popup': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'beacon_tx_type': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2), max_length=None), 'timed_beacon_time': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), max_length=None), 'mice_type': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3), max_length=None), 'tnc_data_type': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3), max_length=None), 'aprs_forward_channel': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), max_length=None), 'aprs_forward_routing': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5), max_length=None), 'aprs_wait_forward': SettingSpec(kind='int', min_value=0, max_value=9, choices=None, max_length=None), 'custom_routing_one': SettingSpec(kind='string', min_value=None, max_value=None, choices=None, max_length=6), 'custom_routing_one_ssid': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), max_length=None), 'custom_routing_two': SettingSpec(kind='string', min_value=None, max_value=None, choices=None, max_length=6), 'custom_routing_two_ssid': SettingSpec(kind='enum', min_value=None, max_value=None, choices=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15), max_length=None), 'send_custom_messages': SettingSpec(kind='bool', min_value=None, max_value=None, choices=None, max_length=None), 'custom_messages': SettingSpec(kind='string', min_value=None, max_value=None, choices=None, max_length=40)}

Validation rule per APRS setting, keyed by the names in APRSSettings.

timed_beacon_time is the index of CPS Timed Beacon Time (30 sec, 1, 2, 3, 5, 10, 15, 20, 30, 60 min = 0-9; 30 sec = 0 confirmed on a radio, the rest follows the CPS list order). radio_symbol is the index of CPS Radio Symbol (Pedestrians, Bicycles, Cars, RecreationalVehicles, UserDefined = 0-4; 0 and 4 confirmed on a radio).

DTMF helpers

Public function def get_dtmf_current_id(settings: DTMFSettings) -> str:
2812def get_dtmf_current_id(settings: DTMFSettings) -> str:
2813    """Return the radio's own DTMF ID.
2814
2815    Args:
2816        settings: DTMF settings to read.
2817
2818    Returns:
2819        str: The own ID as DTMF symbols (up to 5).
2820    """
2821    return settings.current_id

Return the radio's own DTMF ID.

Arguments:
  • settings: DTMF settings to read.
Returns:

str: The own ID as DTMF symbols (up to 5).

Public function def set_dtmf_current_id(settings: DTMFSettings, value: str) -> None:
2823def set_dtmf_current_id(settings: DTMFSettings, value: str) -> None:
2824    """Set the radio's own DTMF ID (up to 5 symbols).
2825
2826    Args:
2827        settings: DTMF settings to update.
2828        value: New ID; surrounding whitespace is stripped.
2829
2830    Raises:
2831        SettingsError: If the ID is invalid.
2832    """
2833    settings.current_id = _validate_dtmf_string(value, 5)

Set the radio's own DTMF ID (up to 5 symbols).

Arguments:
  • settings: DTMF settings to update.
  • value: New ID; surrounding whitespace is stripped.
Raises:
  • SettingsError: If the ID is invalid.
Public function def get_dtmf_ptt_mode(settings: DTMFSettings) -> Optional[int]:
2835def get_dtmf_ptt_mode(settings: DTMFSettings) -> Optional[int]:
2836    """Return the PTT ID mode (0 off, 1 BOT, 2 EOT, 3 both), or ``None``.
2837
2838    Args:
2839        settings: DTMF settings to read.
2840
2841    Returns:
2842        Optional[int]: The mode, or ``None`` if not set.
2843    """
2844    return settings.ptt_id_mode

Return the PTT ID mode (0 off, 1 BOT, 2 EOT, 3 both), or None.

Arguments:
  • settings: DTMF settings to read.
Returns:

Optional[int]: The mode, or None if not set.

Public function def set_dtmf_ptt_mode(settings: DTMFSettings, value: Optional[int]) -> None:
2846def set_dtmf_ptt_mode(settings: DTMFSettings, value: Optional[int]) -> None:
2847    """Set the PTT ID mode.
2848
2849    Args:
2850        settings: DTMF settings to update.
2851        value: 0 off, 1 BOT, 2 EOT, 3 both, or ``None`` for not set.
2852
2853    Raises:
2854        SettingsError: If ``value`` is not 0-3 or ``None``.
2855    """
2856    if value is None:
2857        settings.ptt_id_mode = None
2858        return
2859    if value not in (0, 1, 2, 3):
2860        raise SettingsError("DTMF PTT mode must be 0-3")
2861    settings.ptt_id_mode = value

Set the PTT ID mode.

Arguments:
  • settings: DTMF settings to update.
  • value: 0 off, 1 BOT, 2 EOT, 3 both, or None for not set.
Raises:
  • SettingsError: If value is not 0-3 or None.
Public function def get_dtmf_code_group(settings: DTMFSettings, index: int) -> str:
2863def get_dtmf_code_group(settings: DTMFSettings, index: int) -> str:
2864    """Return DTMF code group ``index`` (0-based).
2865
2866    Args:
2867        settings: DTMF settings to read.
2868        index: Code group number, 0-based.
2869
2870    Returns:
2871        str: The code group as DTMF symbols (up to 6).
2872
2873    Raises:
2874        IndexError: If ``index`` is negative or not below the number of
2875            code groups.
2876    """
2877    if not 0 <= index < len(settings.code_groups):
2878        raise IndexError(index)
2879    return settings.code_groups[index]

Return DTMF code group index (0-based).

Arguments:
  • settings: DTMF settings to read.
  • index: Code group number, 0-based.
Returns:

str: The code group as DTMF symbols (up to 6).

Raises:
  • IndexError: If index is negative or not below the number of code groups.
Public function def set_dtmf_code_group(settings: DTMFSettings, index: int, value: str) -> None:
2881def set_dtmf_code_group(settings: DTMFSettings, index: int, value: str) -> None:
2882    """Set DTMF code group ``index`` (0-based, up to 6 symbols).
2883
2884    Args:
2885        settings: DTMF settings to update.
2886        index: Code group number, 0-based.
2887        value: New code; surrounding whitespace is stripped.
2888
2889    Raises:
2890        IndexError: If ``index`` is out of range.
2891        SettingsError: If the code is invalid.
2892    """
2893    if not 0 <= index < len(settings.code_groups):
2894        raise IndexError(index)
2895    settings.code_groups[index] = _validate_dtmf_string(value, 6)

Set DTMF code group index (0-based, up to 6 symbols).

Arguments:
  • settings: DTMF settings to update.
  • index: Code group number, 0-based.
  • value: New code; surrounding whitespace is stripped.
Raises:
  • IndexError: If index is out of range.
  • SettingsError: If the code is invalid.
Private function def _validate_dtmf_string(value: str, max_len: int) -> str:
2789def _validate_dtmf_string(value: str, max_len: int) -> str:
2790    """Check a DTMF string and return it stripped.
2791
2792    Args:
2793        value: DTMF symbols (``0-9``, ``A-D``, ``*``, ``#``).
2794        max_len: Maximum number of symbols.
2795
2796    Returns:
2797        str: The stripped value.
2798
2799    Raises:
2800        SettingsError: If the value is not a string, too long or contains
2801            other characters.
2802    """
2803    if not isinstance(value, str):
2804        raise SettingsError("DTMF sequence must be a string")
2805    filtered = value.strip()
2806    if len(filtered) > max_len:
2807        raise SettingsError(f"DTMF value '{value}' exceeds {max_len} characters")
2808    if not all(ch in _ALLOWED_DTMF for ch in filtered):
2809        raise SettingsError("DTMF value contains invalid characters")
2810    return filtered

Check a DTMF string and return it stripped.

Arguments:
  • value: DTMF symbols (0-9, A-D, *, #).
  • max_len: Maximum number of symbols.
Returns:

str: The stripped value.

Raises:
  • SettingsError: If the value is not a string, too long or contains other characters.
Private constant _ALLOWED_DTMF = {'2', 'C', '7', '9', '*', '6', '8', '0', '3', 'A', 'D', '4', '#', 'B', '1', '5'}

Characters accepted in DTMF IDs and code groups.

4. Image: the parsed form of a complete clone image

RadioImage, the parsed form of a complete clone image.

Public class
@dataclass
class RadioImage:
3056@dataclass
3057class RadioImage:
3058    """Parsed contents of a complete clone image.
3059
3060    The image bytes are the concatenation of ``DEFAULT_SEGMENTS``: the
3061    0x8000-byte channel segment followed by the settings segments, the APRS
3062    block and the zone names. :meth:`from_bytes` and :meth:`to_bytes`
3063    convert between bytes and this structure.
3064    """
3065
3066    channels: List[ChannelRecord]
3067    """The 990 channel records, slot 0 first."""
3068    vfo: Optional[List[VFOSettings]] = None
3069    """VFO A/B/C, or ``None`` if the image is too short."""
3070    function: Optional[FunctionSettings] = None
3071    """Function settings, or ``None``."""
3072    dtmf: Optional[DTMFSettings] = None
3073    """DTMF settings, or ``None``."""
3074    modulation: Optional[ModulationSettings] = None
3075    """Modulation settings, or ``None``."""
3076    aprs: Optional[APRSSettings] = None
3077    """APRS settings, or ``None``."""
3078    remainder: bytes = b""
3079    """All bytes after the channel segment, as read. Used as the base when re-
3080    encoding, so unknown bytes survive.
3081    """
3082    channel_extra: bytes = b""
3083    """Bytes 0x7BC0-0x7FFF after the last channel, kept verbatim."""
3084    zone_names: Optional[List[str]] = None
3085    """Ten zone names, or ``None`` if not present."""
3086
3087    @classmethod
3088    def from_bytes(
3089        cls,
3090        blob: bytes,
3091        *,
3092        logger: Optional[logging.Logger] = None,
3093    ) -> "RadioImage":
3094        """Parse a raw clone image.
3095
3096        Sections beyond the end of ``blob`` are left as ``None``.
3097
3098        Args:
3099            blob: Image bytes in ``DEFAULT_SEGMENTS`` order; at least the
3100                0x8000-byte channel segment.
3101            logger: Logger for decoding warnings; defaults to ``CHANNEL_LOG``.
3102
3103        Returns:
3104            RadioImage: The parsed image.
3105
3106        Raises:
3107            ValueError: If ``blob`` is shorter than the channel segment or a
3108                channel cannot be decoded.
3109        """
3110        logger = logger or CHANNEL_LOG
3111        if len(blob) < CHANNEL_SECTION_BYTES:
3112            raise ValueError(
3113                f"Clone image is too small ({len(blob)} bytes); "
3114                f"expected at least {CHANNEL_SECTION_BYTES}"
3115            )
3116
3117        channel_bytes = memoryview(blob)[:CHANNEL_DATA_BYTES]
3118        channels: List[ChannelRecord] = []
3119        for index, chunk in enumerate(_chunk(channel_bytes, CHANNEL_SIZE)):
3120            try:
3121                record = ChannelRecord.from_bytes(chunk, logger=logger)
3122            except ValueError as exc:
3123                raise ValueError(f"Failed to decode channel {index}: {exc}") from exc
3124            channels.append(record)
3125
3126        offset = CHANNEL_SECTION_BYTES
3127        vfo: Optional[List[VFOSettings]] = None
3128        function: Optional[FunctionSettings] = None
3129        dtmf: Optional[DTMFSettings] = None
3130        modulation: Optional[ModulationSettings] = None
3131        aprs: Optional[APRSSettings] = None
3132
3133        if len(blob) >= offset + VFO_SEGMENT_BYTES:
3134            vfo_segment = bytes(blob[offset : offset + VFO_SEGMENT_BYTES])
3135            vfo = parse_vfo_section(vfo_segment[:VFO_DATA_BYTES])
3136        offset += VFO_SEGMENT_BYTES
3137
3138        if len(blob) >= offset + FUNCTION_SEGMENT_BYTES:
3139            function_segment = bytes(blob[offset : offset + FUNCTION_SEGMENT_BYTES])
3140            function = parse_function_section(function_segment[:FUNCTION_DATA_BYTES])
3141        offset += FUNCTION_SEGMENT_BYTES
3142
3143        if len(blob) >= offset + DTMF_SEGMENT_BYTES:
3144            dtmf_segment = bytes(blob[offset : offset + DTMF_SEGMENT_BYTES])
3145            dtmf = parse_dtmf_section(dtmf_segment[:DTMF_DATA_BYTES])
3146        offset += DTMF_SEGMENT_BYTES
3147
3148        if len(blob) >= offset + MODULATION_PARAM_SEGMENT_BYTES + MODULATION_NAME_SEGMENT_BYTES:
3149            params_segment = bytes(blob[offset : offset + MODULATION_PARAM_SEGMENT_BYTES])
3150            names_segment = bytes(
3151                blob[
3152                    offset
3153                    + MODULATION_PARAM_SEGMENT_BYTES : offset
3154                    + MODULATION_PARAM_SEGMENT_BYTES
3155                    + MODULATION_NAME_SEGMENT_BYTES
3156                ]
3157            )
3158            modulation = parse_modulation_sections(
3159                params_segment[:MODULATION_PARAM_DATA_BYTES],
3160                names_segment[:MODULATION_NAME_SEGMENT_BYTES],
3161            )
3162        offset += MODULATION_PARAM_SEGMENT_BYTES + MODULATION_NAME_SEGMENT_BYTES
3163
3164        if len(blob) >= offset + APRS_SEGMENT_BYTES:
3165            aprs_data = bytes(blob[offset : offset + APRS_SEGMENT_BYTES])
3166            aprs = parse_aprs_section(aprs_data[:APRS_SEGMENT_BYTES])
3167        offset += APRS_SEGMENT_BYTES
3168
3169        zone_names: Optional[List[str]] = None
3170        if len(blob) >= offset + ZONE_NAME_SEGMENT_BYTES:
3171            zone_names = parse_zone_names(bytes(blob[offset : offset + ZONE_NAME_SEGMENT_BYTES]))
3172
3173        remainder = bytes(blob[CHANNEL_SECTION_BYTES:])
3174        channel_extra = bytes(blob[CHANNEL_DATA_BYTES:CHANNEL_SECTION_BYTES])
3175        return cls(
3176            channels=channels,
3177            vfo=vfo,
3178            function=function,
3179            dtmf=dtmf,
3180            modulation=modulation,
3181            aprs=aprs,
3182            remainder=remainder,
3183            channel_extra=channel_extra,
3184            zone_names=zone_names,
3185        )
3186
3187    @classmethod
3188    def from_file(
3189        cls,
3190        path: Path,
3191        *,
3192        logger: Optional[logging.Logger] = None,
3193    ) -> "RadioImage":
3194        """Load and parse an image file.
3195
3196        Args:
3197            path: File containing a raw clone image.
3198            logger: Logger for decoding warnings.
3199
3200        Returns:
3201            RadioImage: The parsed image (see :meth:`from_bytes`).
3202
3203        Raises:
3204            ValueError: If the file cannot be read or parsed.
3205        """
3206        try:
3207            data = path.read_bytes()
3208        except OSError as exc:
3209            raise ValueError(f"Unable to read image file {path}: {exc}") from exc
3210        return cls.from_bytes(data, logger=logger)
3211
3212    def to_bytes(self, *, logger: Optional[logging.Logger] = None) -> bytes:
3213        """Serialise the image back into clone-image bytes.
3214
3215        Each settings section is re-encoded on top of its original bytes from
3216        ``remainder``; channels use their own change tracking. Zone names are
3217        re-encoded the same way. A missing or short ``remainder`` is padded
3218        with 0xFF. Encoding updates the change-tracking snapshots of edited
3219        channels and VFO entries.
3220
3221        Args:
3222            logger: Logger for encoding warnings; defaults to ``CHANNEL_LOG``.
3223
3224        Returns:
3225            bytes: Image bytes in ``DEFAULT_SEGMENTS`` order.
3226
3227        Raises:
3228            ValueError: If the image does not hold exactly ``CHANNEL_COUNT``
3229                channels or a channel cannot be encoded.
3230        """
3231        logger = logger or CHANNEL_LOG
3232        if len(self.channels) != CHANNEL_COUNT:
3233            raise ValueError(
3234                f"Image must contain {CHANNEL_COUNT} channels; has {len(self.channels)}"
3235            )
3236
3237        tail = bytearray(self.remainder)
3238        if len(tail) < KNOWN_SEGMENT_BYTES:
3239            tail.extend(b"\xFF" * (KNOWN_SEGMENT_BYTES - len(tail)))
3240
3241        offset = 0
3242
3243        vfo_segment = bytearray(tail[offset : offset + VFO_SEGMENT_BYTES])
3244        vfo_encoded = encode_vfo_section(self.vfo, bytes(vfo_segment[:VFO_DATA_BYTES]))
3245        vfo_segment[:VFO_DATA_BYTES] = vfo_encoded
3246        tail[offset : offset + VFO_SEGMENT_BYTES] = vfo_segment
3247        offset += VFO_SEGMENT_BYTES
3248
3249        function_segment = bytearray(tail[offset : offset + FUNCTION_SEGMENT_BYTES])
3250        function_encoded = encode_function_section(
3251            self.function, bytes(function_segment[:FUNCTION_DATA_BYTES])
3252        )
3253        function_segment[:FUNCTION_DATA_BYTES] = function_encoded
3254        tail[offset : offset + FUNCTION_SEGMENT_BYTES] = function_segment
3255        offset += FUNCTION_SEGMENT_BYTES
3256
3257        dtmf_segment = bytearray(tail[offset : offset + DTMF_SEGMENT_BYTES])
3258        dtmf_encoded = encode_dtmf_section(self.dtmf, bytes(dtmf_segment[:DTMF_DATA_BYTES]))
3259        dtmf_segment[:DTMF_DATA_BYTES] = dtmf_encoded
3260        tail[offset : offset + DTMF_SEGMENT_BYTES] = dtmf_segment
3261        offset += DTMF_SEGMENT_BYTES
3262
3263        params_offset = offset
3264        names_offset = params_offset + MODULATION_PARAM_SEGMENT_BYTES
3265
3266        params_segment = bytearray(
3267            tail[params_offset : params_offset + MODULATION_PARAM_SEGMENT_BYTES]
3268        )
3269        names_segment = bytearray(tail[names_offset : names_offset + MODULATION_NAME_SEGMENT_BYTES])
3270        params_raw = bytes(params_segment[:MODULATION_PARAM_DATA_BYTES])
3271        names_raw = bytes(names_segment[:MODULATION_NAME_SEGMENT_BYTES])
3272        mod_params, mod_names = encode_modulation_sections(
3273            self.modulation, params_raw, names_raw
3274        )
3275        params_segment[:MODULATION_PARAM_DATA_BYTES] = mod_params
3276        names_segment[:MODULATION_NAME_SEGMENT_BYTES] = mod_names
3277        tail[params_offset : params_offset + MODULATION_PARAM_SEGMENT_BYTES] = params_segment
3278        tail[names_offset : names_offset + MODULATION_NAME_SEGMENT_BYTES] = names_segment
3279        offset = names_offset + MODULATION_NAME_SEGMENT_BYTES
3280
3281        aprs_segment = bytearray(tail[offset : offset + APRS_SEGMENT_BYTES])
3282        aprs_encoded = encode_aprs_section(self.aprs, bytes(aprs_segment))
3283        tail[offset : offset + APRS_SEGMENT_BYTES] = aprs_encoded
3284        offset += APRS_SEGMENT_BYTES
3285
3286        zone_segment = bytes(tail[offset : offset + ZONE_NAME_SEGMENT_BYTES])
3287        tail[offset : offset + ZONE_NAME_SEGMENT_BYTES] = encode_zone_names(
3288            self.zone_names, zone_segment
3289        )
3290
3291        buffer = bytearray(CHANNEL_SECTION_BYTES + len(tail))
3292        extra = bytes(self.channel_extra[: CHANNEL_SECTION_BYTES - CHANNEL_DATA_BYTES])
3293        extra = extra.ljust(CHANNEL_SECTION_BYTES - CHANNEL_DATA_BYTES, b"\xFF")
3294        buffer[CHANNEL_DATA_BYTES:CHANNEL_SECTION_BYTES] = extra
3295        for index, channel in enumerate(self.channels):
3296            start = index * CHANNEL_SIZE
3297            buffer[start : start + CHANNEL_SIZE] = channel.to_bytes(logger=logger)
3298
3299        buffer[CHANNEL_SECTION_BYTES:] = tail
3300        return bytes(buffer)
3301
3302    def empty_slot_indexes(self) -> List[int]:
3303        """Return the 0-based slots that have no receive frequency.
3304
3305        Returns:
3306            list[int]: Indexes of empty channels.
3307        """
3308        return [idx for idx, channel in enumerate(self.channels) if channel.rx_hz is None]
3309
3310    def iter_populated_channels(self) -> Iterable[tuple[int, ChannelRecord]]:
3311        """Iterate over channels that have a receive frequency.
3312
3313        Yields:
3314            tuple[int, ChannelRecord]: 0-based slot index and its record.
3315        """
3316        for index, channel in enumerate(self.channels):
3317            if channel.rx_hz is not None:
3318                yield index, channel
3319
3320    def save(self, path: Path, *, logger: Optional[logging.Logger] = None) -> None:
3321        """Write the image to a file.
3322
3323        Args:
3324            path: Destination file.
3325            logger: Logger for encoding warnings.
3326
3327        Raises:
3328            ValueError: If the image cannot be encoded or written.
3329        """
3330        data = self.to_bytes(logger=logger)
3331        try:
3332            path.write_bytes(data)
3333        except OSError as exc:
3334            raise ValueError(f"Unable to write image file {path}: {exc}") from exc

Parsed contents of a complete clone image.

The image bytes are the concatenation of DEFAULT_SEGMENTS: the 0x8000-byte channel segment followed by the settings segments, the APRS block and the zone names. from_bytes() and to_bytes() convert between bytes and this structure.

Fields
Public field channels: List[ChannelRecord]

The 990 channel records, slot 0 first.

Public field vfo: Optional[List[VFOSettings]] = None

VFO A/B/C, or None if the image is too short.

Public field function: Optional[FunctionSettings] = None

Function settings, or None.

Public field dtmf: Optional[DTMFSettings] = None

DTMF settings, or None.

Public field modulation: Optional[ModulationSettings] = None

Modulation settings, or None.

Public field aprs: Optional[APRSSettings] = None

APRS settings, or None.

Public field remainder: bytes = b''

All bytes after the channel segment, as read. Used as the base when re- encoding, so unknown bytes survive.

Public field channel_extra: bytes = b''

Bytes 0x7BC0-0x7FFF after the last channel, kept verbatim.

Public field zone_names: Optional[List[str]] = None

Ten zone names, or None if not present.

Methods
Public method
@classmethod
def from_bytes( cls, blob: bytes, *, logger: Optional[logging.Logger] = None) -> RadioImage:
3087    @classmethod
3088    def from_bytes(
3089        cls,
3090        blob: bytes,
3091        *,
3092        logger: Optional[logging.Logger] = None,
3093    ) -> "RadioImage":
3094        """Parse a raw clone image.
3095
3096        Sections beyond the end of ``blob`` are left as ``None``.
3097
3098        Args:
3099            blob: Image bytes in ``DEFAULT_SEGMENTS`` order; at least the
3100                0x8000-byte channel segment.
3101            logger: Logger for decoding warnings; defaults to ``CHANNEL_LOG``.
3102
3103        Returns:
3104            RadioImage: The parsed image.
3105
3106        Raises:
3107            ValueError: If ``blob`` is shorter than the channel segment or a
3108                channel cannot be decoded.
3109        """
3110        logger = logger or CHANNEL_LOG
3111        if len(blob) < CHANNEL_SECTION_BYTES:
3112            raise ValueError(
3113                f"Clone image is too small ({len(blob)} bytes); "
3114                f"expected at least {CHANNEL_SECTION_BYTES}"
3115            )
3116
3117        channel_bytes = memoryview(blob)[:CHANNEL_DATA_BYTES]
3118        channels: List[ChannelRecord] = []
3119        for index, chunk in enumerate(_chunk(channel_bytes, CHANNEL_SIZE)):
3120            try:
3121                record = ChannelRecord.from_bytes(chunk, logger=logger)
3122            except ValueError as exc:
3123                raise ValueError(f"Failed to decode channel {index}: {exc}") from exc
3124            channels.append(record)
3125
3126        offset = CHANNEL_SECTION_BYTES
3127        vfo: Optional[List[VFOSettings]] = None
3128        function: Optional[FunctionSettings] = None
3129        dtmf: Optional[DTMFSettings] = None
3130        modulation: Optional[ModulationSettings] = None
3131        aprs: Optional[APRSSettings] = None
3132
3133        if len(blob) >= offset + VFO_SEGMENT_BYTES:
3134            vfo_segment = bytes(blob[offset : offset + VFO_SEGMENT_BYTES])
3135            vfo = parse_vfo_section(vfo_segment[:VFO_DATA_BYTES])
3136        offset += VFO_SEGMENT_BYTES
3137
3138        if len(blob) >= offset + FUNCTION_SEGMENT_BYTES:
3139            function_segment = bytes(blob[offset : offset + FUNCTION_SEGMENT_BYTES])
3140            function = parse_function_section(function_segment[:FUNCTION_DATA_BYTES])
3141        offset += FUNCTION_SEGMENT_BYTES
3142
3143        if len(blob) >= offset + DTMF_SEGMENT_BYTES:
3144            dtmf_segment = bytes(blob[offset : offset + DTMF_SEGMENT_BYTES])
3145            dtmf = parse_dtmf_section(dtmf_segment[:DTMF_DATA_BYTES])
3146        offset += DTMF_SEGMENT_BYTES
3147
3148        if len(blob) >= offset + MODULATION_PARAM_SEGMENT_BYTES + MODULATION_NAME_SEGMENT_BYTES:
3149            params_segment = bytes(blob[offset : offset + MODULATION_PARAM_SEGMENT_BYTES])
3150            names_segment = bytes(
3151                blob[
3152                    offset
3153                    + MODULATION_PARAM_SEGMENT_BYTES : offset
3154                    + MODULATION_PARAM_SEGMENT_BYTES
3155                    + MODULATION_NAME_SEGMENT_BYTES
3156                ]
3157            )
3158            modulation = parse_modulation_sections(
3159                params_segment[:MODULATION_PARAM_DATA_BYTES],
3160                names_segment[:MODULATION_NAME_SEGMENT_BYTES],
3161            )
3162        offset += MODULATION_PARAM_SEGMENT_BYTES + MODULATION_NAME_SEGMENT_BYTES
3163
3164        if len(blob) >= offset + APRS_SEGMENT_BYTES:
3165            aprs_data = bytes(blob[offset : offset + APRS_SEGMENT_BYTES])
3166            aprs = parse_aprs_section(aprs_data[:APRS_SEGMENT_BYTES])
3167        offset += APRS_SEGMENT_BYTES
3168
3169        zone_names: Optional[List[str]] = None
3170        if len(blob) >= offset + ZONE_NAME_SEGMENT_BYTES:
3171            zone_names = parse_zone_names(bytes(blob[offset : offset + ZONE_NAME_SEGMENT_BYTES]))
3172
3173        remainder = bytes(blob[CHANNEL_SECTION_BYTES:])
3174        channel_extra = bytes(blob[CHANNEL_DATA_BYTES:CHANNEL_SECTION_BYTES])
3175        return cls(
3176            channels=channels,
3177            vfo=vfo,
3178            function=function,
3179            dtmf=dtmf,
3180            modulation=modulation,
3181            aprs=aprs,
3182            remainder=remainder,
3183            channel_extra=channel_extra,
3184            zone_names=zone_names,
3185        )

Parse a raw clone image.

Sections beyond the end of blob are left as None.

Arguments:
  • blob: Image bytes in DEFAULT_SEGMENTS order; at least the 0x8000-byte channel segment.
  • logger: Logger for decoding warnings; defaults to CHANNEL_LOG.
Returns:

RadioImage: The parsed image.

Raises:
  • ValueError: If blob is shorter than the channel segment or a channel cannot be decoded.
Public method
@classmethod
def from_file( cls, path: pathlib.Path, *, logger: Optional[logging.Logger] = None) -> RadioImage:
3187    @classmethod
3188    def from_file(
3189        cls,
3190        path: Path,
3191        *,
3192        logger: Optional[logging.Logger] = None,
3193    ) -> "RadioImage":
3194        """Load and parse an image file.
3195
3196        Args:
3197            path: File containing a raw clone image.
3198            logger: Logger for decoding warnings.
3199
3200        Returns:
3201            RadioImage: The parsed image (see :meth:`from_bytes`).
3202
3203        Raises:
3204            ValueError: If the file cannot be read or parsed.
3205        """
3206        try:
3207            data = path.read_bytes()
3208        except OSError as exc:
3209            raise ValueError(f"Unable to read image file {path}: {exc}") from exc
3210        return cls.from_bytes(data, logger=logger)

Load and parse an image file.

Arguments:
  • path: File containing a raw clone image.
  • logger: Logger for decoding warnings.
Returns:

RadioImage: The parsed image (see from_bytes()).

Raises:
  • ValueError: If the file cannot be read or parsed.
Public method def to_bytes(self, *, logger: Optional[logging.Logger] = None) -> bytes:
3212    def to_bytes(self, *, logger: Optional[logging.Logger] = None) -> bytes:
3213        """Serialise the image back into clone-image bytes.
3214
3215        Each settings section is re-encoded on top of its original bytes from
3216        ``remainder``; channels use their own change tracking. Zone names are
3217        re-encoded the same way. A missing or short ``remainder`` is padded
3218        with 0xFF. Encoding updates the change-tracking snapshots of edited
3219        channels and VFO entries.
3220
3221        Args:
3222            logger: Logger for encoding warnings; defaults to ``CHANNEL_LOG``.
3223
3224        Returns:
3225            bytes: Image bytes in ``DEFAULT_SEGMENTS`` order.
3226
3227        Raises:
3228            ValueError: If the image does not hold exactly ``CHANNEL_COUNT``
3229                channels or a channel cannot be encoded.
3230        """
3231        logger = logger or CHANNEL_LOG
3232        if len(self.channels) != CHANNEL_COUNT:
3233            raise ValueError(
3234                f"Image must contain {CHANNEL_COUNT} channels; has {len(self.channels)}"
3235            )
3236
3237        tail = bytearray(self.remainder)
3238        if len(tail) < KNOWN_SEGMENT_BYTES:
3239            tail.extend(b"\xFF" * (KNOWN_SEGMENT_BYTES - len(tail)))
3240
3241        offset = 0
3242
3243        vfo_segment = bytearray(tail[offset : offset + VFO_SEGMENT_BYTES])
3244        vfo_encoded = encode_vfo_section(self.vfo, bytes(vfo_segment[:VFO_DATA_BYTES]))
3245        vfo_segment[:VFO_DATA_BYTES] = vfo_encoded
3246        tail[offset : offset + VFO_SEGMENT_BYTES] = vfo_segment
3247        offset += VFO_SEGMENT_BYTES
3248
3249        function_segment = bytearray(tail[offset : offset + FUNCTION_SEGMENT_BYTES])
3250        function_encoded = encode_function_section(
3251            self.function, bytes(function_segment[:FUNCTION_DATA_BYTES])
3252        )
3253        function_segment[:FUNCTION_DATA_BYTES] = function_encoded
3254        tail[offset : offset + FUNCTION_SEGMENT_BYTES] = function_segment
3255        offset += FUNCTION_SEGMENT_BYTES
3256
3257        dtmf_segment = bytearray(tail[offset : offset + DTMF_SEGMENT_BYTES])
3258        dtmf_encoded = encode_dtmf_section(self.dtmf, bytes(dtmf_segment[:DTMF_DATA_BYTES]))
3259        dtmf_segment[:DTMF_DATA_BYTES] = dtmf_encoded
3260        tail[offset : offset + DTMF_SEGMENT_BYTES] = dtmf_segment
3261        offset += DTMF_SEGMENT_BYTES
3262
3263        params_offset = offset
3264        names_offset = params_offset + MODULATION_PARAM_SEGMENT_BYTES
3265
3266        params_segment = bytearray(
3267            tail[params_offset : params_offset + MODULATION_PARAM_SEGMENT_BYTES]
3268        )
3269        names_segment = bytearray(tail[names_offset : names_offset + MODULATION_NAME_SEGMENT_BYTES])
3270        params_raw = bytes(params_segment[:MODULATION_PARAM_DATA_BYTES])
3271        names_raw = bytes(names_segment[:MODULATION_NAME_SEGMENT_BYTES])
3272        mod_params, mod_names = encode_modulation_sections(
3273            self.modulation, params_raw, names_raw
3274        )
3275        params_segment[:MODULATION_PARAM_DATA_BYTES] = mod_params
3276        names_segment[:MODULATION_NAME_SEGMENT_BYTES] = mod_names
3277        tail[params_offset : params_offset + MODULATION_PARAM_SEGMENT_BYTES] = params_segment
3278        tail[names_offset : names_offset + MODULATION_NAME_SEGMENT_BYTES] = names_segment
3279        offset = names_offset + MODULATION_NAME_SEGMENT_BYTES
3280
3281        aprs_segment = bytearray(tail[offset : offset + APRS_SEGMENT_BYTES])
3282        aprs_encoded = encode_aprs_section(self.aprs, bytes(aprs_segment))
3283        tail[offset : offset + APRS_SEGMENT_BYTES] = aprs_encoded
3284        offset += APRS_SEGMENT_BYTES
3285
3286        zone_segment = bytes(tail[offset : offset + ZONE_NAME_SEGMENT_BYTES])
3287        tail[offset : offset + ZONE_NAME_SEGMENT_BYTES] = encode_zone_names(
3288            self.zone_names, zone_segment
3289        )
3290
3291        buffer = bytearray(CHANNEL_SECTION_BYTES + len(tail))
3292        extra = bytes(self.channel_extra[: CHANNEL_SECTION_BYTES - CHANNEL_DATA_BYTES])
3293        extra = extra.ljust(CHANNEL_SECTION_BYTES - CHANNEL_DATA_BYTES, b"\xFF")
3294        buffer[CHANNEL_DATA_BYTES:CHANNEL_SECTION_BYTES] = extra
3295        for index, channel in enumerate(self.channels):
3296            start = index * CHANNEL_SIZE
3297            buffer[start : start + CHANNEL_SIZE] = channel.to_bytes(logger=logger)
3298
3299        buffer[CHANNEL_SECTION_BYTES:] = tail
3300        return bytes(buffer)

Serialise the image back into clone-image bytes.

Each settings section is re-encoded on top of its original bytes from remainder; channels use their own change tracking. Zone names are re-encoded the same way. A missing or short remainder is padded with 0xFF. Encoding updates the change-tracking snapshots of edited channels and VFO entries.

Arguments:
  • logger: Logger for encoding warnings; defaults to CHANNEL_LOG.
Returns:

bytes: Image bytes in DEFAULT_SEGMENTS order.

Raises:
  • ValueError: If the image does not hold exactly CHANNEL_COUNT channels or a channel cannot be encoded.
Public method def empty_slot_indexes(self) -> List[int]:
3302    def empty_slot_indexes(self) -> List[int]:
3303        """Return the 0-based slots that have no receive frequency.
3304
3305        Returns:
3306            list[int]: Indexes of empty channels.
3307        """
3308        return [idx for idx, channel in enumerate(self.channels) if channel.rx_hz is None]

Return the 0-based slots that have no receive frequency.

Returns:

list[int]: Indexes of empty channels.

Public method def iter_populated_channels(self) -> Iterable[tuple[int, ChannelRecord]]:
3310    def iter_populated_channels(self) -> Iterable[tuple[int, ChannelRecord]]:
3311        """Iterate over channels that have a receive frequency.
3312
3313        Yields:
3314            tuple[int, ChannelRecord]: 0-based slot index and its record.
3315        """
3316        for index, channel in enumerate(self.channels):
3317            if channel.rx_hz is not None:
3318                yield index, channel

Iterate over channels that have a receive frequency.

Yields:

tuple[int, ChannelRecord]: 0-based slot index and its record.

Public method def save( self, path: pathlib.Path, *, logger: Optional[logging.Logger] = None) -> None:
3320    def save(self, path: Path, *, logger: Optional[logging.Logger] = None) -> None:
3321        """Write the image to a file.
3322
3323        Args:
3324            path: Destination file.
3325            logger: Logger for encoding warnings.
3326
3327        Raises:
3328            ValueError: If the image cannot be encoded or written.
3329        """
3330        data = self.to_bytes(logger=logger)
3331        try:
3332            path.write_bytes(data)
3333        except OSError as exc:
3334            raise ValueError(f"Unable to write image file {path}: {exc}") from exc

Write the image to a file.

Arguments:
  • path: Destination file.
  • logger: Logger for encoding warnings.
Raises:
  • ValueError: If the image cannot be encoded or written.
Public function def parse_zone_names(segment: bytes) -> List[str]:
2994def parse_zone_names(segment: bytes) -> List[str]:
2995    """Decode the ten zone names from the zone-name segment.
2996
2997    Args:
2998        segment: The segment read from 0xC000 (at least 160 bytes).
2999
3000    Returns:
3001        list[str]: Ten names; ``""`` means no name is set.
3002    """
3003    return [
3004        _decode_zone_name(segment[i * ZONE_NAME_STRIDE : (i + 1) * ZONE_NAME_STRIDE])
3005        for i in range(ZONE_COUNT)
3006    ]

Decode the ten zone names from the zone-name segment.

Arguments:
  • segment: The segment read from 0xC000 (at least 160 bytes).
Returns:

list[str]: Ten names; "" means no name is set.

Public function def encode_zone_names(names: Optional[List[str]], raw: bytes) -> bytes:
3009def encode_zone_names(names: Optional[List[str]], raw: bytes) -> bytes:
3010    """Write changed zone names into the zone-name segment.
3011
3012    Unchanged names stay byte-identical. A changed name is cut to
3013    ``ZONE_NAME_LENGTH`` ASCII characters and padded with the padding byte
3014    (0x00 or 0xFF) the slot already used.
3015
3016    Args:
3017        names: Ten names, or ``None`` to leave the segment untouched.
3018        raw: The original segment; padded with 0xFF to
3019            ``ZONE_NAME_SEGMENT_BYTES``.
3020
3021    Returns:
3022        bytes: The segment, ``ZONE_NAME_SEGMENT_BYTES`` long.
3023    """
3024    data = bytearray(raw.ljust(ZONE_NAME_SEGMENT_BYTES, b"\xFF"))
3025    if names is None:
3026        return bytes(data)
3027    for i, name in enumerate(names[:ZONE_COUNT]):
3028        start = i * ZONE_NAME_STRIDE
3029        if name == _decode_zone_name(data[start : start + ZONE_NAME_STRIDE]):
3030            continue
3031        encoded = name.encode("ascii", errors="ignore")[:ZONE_NAME_LENGTH]
3032        old = bytes(data[start : start + ZONE_NAME_STRIDE])
3033        # keep the padding byte the radio already uses for this slot
3034        used = len(old.rstrip(b"\x00\xFF"))
3035        pad = 0x00 if used < len(old) and old[used] == 0x00 else 0xFF
3036        width = max(ZONE_NAME_LENGTH, used)
3037        data[start : start + width] = encoded.ljust(width, bytes([pad]))
3038    return bytes(data)

Write changed zone names into the zone-name segment.

Unchanged names stay byte-identical. A changed name is cut to ZONE_NAME_LENGTH ASCII characters and padded with the padding byte (0x00 or 0xFF) the slot already used.

Arguments:
  • names: Ten names, or None to leave the segment untouched.
  • raw: The original segment; padded with 0xFF to ZONE_NAME_SEGMENT_BYTES.
Returns:

bytes: The segment, ZONE_NAME_SEGMENT_BYTES long.

Private function def _decode_zone_name(raw: bytes) -> str:
2977def _decode_zone_name(raw: bytes) -> str:
2978    """Decode one 16-byte zone-name slot as ASCII up to the first 0x00/0xFF.
2979
2980    Args:
2981        raw: The slot bytes; only the first ``ZONE_NAME_READ_LENGTH`` are used.
2982
2983    Returns:
2984        str: The stripped name; invalid bytes are replaced, ``""`` if empty.
2985    """
2986    text = bytearray()
2987    for byte in raw[:ZONE_NAME_READ_LENGTH]:
2988        if byte in (0x00, 0xFF):
2989            break
2990        text.append(byte)
2991    return text.decode("ascii", errors="replace").strip()

Decode one 16-byte zone-name slot as ASCII up to the first 0x00/0xFF.

Arguments:
Returns:

str: The stripped name; invalid bytes are replaced, "" if empty.

Private function def _chunk(iterable: Sequence[int], size: int) -> Iterable[bytes]:
3041def _chunk(iterable: Sequence[int], size: int) -> Iterable[bytes]:
3042    """Yield consecutive ``size``-byte chunks; a short final chunk is dropped.
3043
3044    Args:
3045        iterable: Byte sequence to split (the channel segment).
3046        size: Chunk length in bytes (``CHANNEL_SIZE`` at the call site).
3047
3048    Yields:
3049        bytes: The next chunk of exactly ``size`` bytes.
3050    """
3051    for i in range(0, len(iterable), size):
3052        chunk = iterable[i : i + size]
3053        if len(chunk) == size:
3054            yield bytes(chunk)

Yield consecutive size-byte chunks; a short final chunk is dropped.

Arguments:
  • iterable: Byte sequence to split (the channel segment).
  • size: Chunk length in bytes (CHANNEL_SIZE at the call site).
Yields:

bytes: The next chunk of exactly size bytes.

Public constant ZONE_COUNT = 10

Number of zones in the radio (CPS: arrayZoneName[10]).

Public constant ZONE_SIZE = 99

Channels per zone (CPS: channelList[990] = 10 x 99).

Public constant CHANNEL_COUNT = 990

Total number of memory channels supported by the radio (990).

Public constant CHANNEL_SIZE = 32

Size in bytes of a single channel record.

Public constant CHANNEL_SECTION_BYTES = 32768

Total byte length of the channel segment within the clone image.

The segment runs up to the VFO block at 0x8000. Bytes after the last channel record (0x7BC0-0x7FFF) are kept verbatim in the image; the driver never writes past 0x7BFF.

Private constant CHANNEL_LOG = <Logger radtel_rt950pro.image (WARNING)>

Default logger for RadioImage parsing and serialisation.

Private constant CHANNEL_DATA_BYTES = 31680

Bytes occupied by the 990 channel records (0x0000-0x7BBF).

Private constant LEGACY_CHANNEL_SECTION_BYTES = 30720

Channel segment size used by older versions of this driver (960 slots).

Private constant VFO_DATA_BYTES = 96

Used bytes of the VFO segment (three 32-byte entries).

Private constant VFO_SEGMENT_BYTES = 256

Size of the VFO segment read from 0x8000.

Private constant FUNCTION_DATA_BYTES = 96

Used bytes of the function segment.

Private constant FUNCTION_SEGMENT_BYTES = 256

Size of the function segment read from 0x9000.

Private constant DTMF_DATA_BYTES = 384

Used bytes of the DTMF segment (32 info + 22 x 16 code groups).

Private constant DTMF_SEGMENT_BYTES = 512

Size of the DTMF segment read from 0xA000.

Private constant MODULATION_PARAM_DATA_BYTES = 256

Used bytes of the modulation parameter segment.

Private constant MODULATION_PARAM_SEGMENT_BYTES = 512

Size of the modulation parameter segment read from 0xB000.

Private constant MODULATION_NAME_SEGMENT_BYTES = 768

Size of the modulation name segment read from 0xD000 (3 tables x 16 names x 16 bytes).

Private constant APRS_SEGMENT_BYTES = 128

Size of the APRS block (separate address space, commands 0x54/0x58).

Private constant ZONE_NAME_SEGMENT_BYTES = 256

Zone names at radio address 0xC000: 10 x 16 bytes (confirmed on a real RT-950 Pro: zone 1 at 0xC000, zone 2 at 0xC010 ... zone 10 at 0xC090). Read as two 0x80 blocks (0xC000-0xC0FF).

Private constant ZONE_NAME_ADDRESS = 49152

Radio address of the first zone name.

Private constant ZONE_NAME_STRIDE = 16

Distance in bytes between consecutive zone-name slots.

Private constant ZONE_NAME_READ_LENGTH = 16

Decode up to the full 16-byte slot, stopping at 0x00/0xFF padding.

Private constant ZONE_NAME_LENGTH = 12

Maximum length of a zone name: the CPS (Cur Zone Name) cuts a name to 12 characters, confirmed on a radio. The 16-byte slot is padded after it.

Private constant KNOWN_SEGMENT_BYTES = 2688

Total size of all segments after the channel segment.

5. Transport: serial clone protocol

CloneSerialTransport, the serial clone protocol (PROGRAMBT9000U handshake and XOR-obfuscated 0x80-byte blocks).

Public class
@dataclass(slots=True)
class CloneSegment:
3381@dataclass(slots=True)
3382class CloneSegment:
3383    """A contiguous memory region transferred in 0x80-byte blocks."""
3384
3385    read_command: int
3386    """Command byte for reading (0x52, or 0x54 for APRS)."""
3387    write_command: int
3388    """Command byte for writing (0x57, or 0x58 for APRS)."""
3389    start: int
3390    """Start address in the radio."""
3391    length: int
3392    """Length in bytes; a multiple of ``READ_BLOCK``."""

A contiguous memory region transferred in 0x80-byte blocks.

Fields
Public field read_command: int

Command byte for reading (0x52, or 0x54 for APRS).

Public field write_command: int

Command byte for writing (0x57, or 0x58 for APRS).

Public field start: int

Start address in the radio.

Public field length: int

Length in bytes; a multiple of READ_BLOCK.

Public class class CloneTransportError(builtins.RuntimeError):
3415class CloneTransportError(RuntimeError):
3416    """Raised when the serial clone protocol fails.
3417
3418    Causes include a timeout, a missing ACK, a short write or unexpected
3419    data.
3420    """

Raised when the serial clone protocol fails.

Causes include a timeout, a missing ACK, a short write or unexpected data.

Public class
@dataclass(slots=True)
class CloneSerialConfig:
3422@dataclass(slots=True)
3423class CloneSerialConfig:
3424    """Settings for opening the programming cable's serial port."""
3425
3426    port: str
3427    """Device name, e.g. ``"/dev/ttyUSB0"`` or ``"COM3"``."""
3428    baudrate: int = 115200
3429    """Serial speed."""
3430    timeout: float = 1.0
3431    """Read timeout in seconds (raised to at least 3 s)."""
3432    write_timeout: float = 1.0
3433    """Write timeout in seconds (raised to at least 3 s)."""

Settings for opening the programming cable's serial port.

Fields
Public field port: str

Device name, e.g. "/dev/ttyUSB0" or "COM3".

Public field baudrate: int

Serial speed.

Public field timeout: float

Read timeout in seconds (raised to at least 3 s).

Public field write_timeout: float

Write timeout in seconds (raised to at least 3 s).

Public class class CloneSerialTransport:
3435class CloneSerialTransport:
3436    """The RT-950 Pro serial clone protocol.
3437
3438    Session outline:
3439
3440    1. Send ``PROGRAMBT9000U``; the radio answers ACK (0x06).
3441    2. ``F``: the radio returns a 16-byte blob (logged only).
3442    3. ``M``: the radio returns its 12-byte model string.
3443    4. Send a 25-byte ``SEND`` frame whose random contents select one of
3444       ``ENCRYPT_STRINGS`` as the 4-byte XOR key; the radio answers ACK.
3445    5. Transfer 0x80-byte blocks: header ``cmd, addr_hi, addr_lo, 0x80``;
3446       reads return header plus payload, writes are answered with ACK.
3447    6. Send ``E`` to end the session.
3448
3449    Payload bytes are XOR-ed with the key, except 0x00, 0xFF, the key byte
3450    itself and its complement, and positions where the key byte is a space.
3451    """
3452
3453    def __init__(
3454        self,
3455        serial_port,
3456        *,
3457        logger=None,
3458        rng: Optional[random.Random] = None,
3459    ) -> None:
3460        """Wrap an already open port.
3461
3462        Read and write timeouts below 3 s are raised to 3 s.
3463
3464        Args:
3465            serial_port: Open serial port or CHIRP pipe.
3466            logger: Logger for protocol tracing; defaults to the module's
3467                transport logger.
3468            rng: Random source for the key-selection frame; inject a seeded
3469                one for reproducible tests.
3470        """
3471        self.serial = serial_port
3472        """The open port or CHIRP pipe; its timeouts are raised to at least 3 s."""
3473        self.logger = logger or logging.getLogger(__name__ + ".transport")
3474        """Logger for protocol tracing (debug level: commands, addresses)."""
3475        # Enforce sensible minimums to avoid premature timeouts during clone.
3476        # The port object may be any pipe-like object, so any failure while
3477        # inspecting it falls back to the minimum.
3478        try:
3479            to = getattr(self.serial, "timeout", None)
3480            if to is None or float(to) < 3.0:
3481                self.serial.timeout = 3.0
3482        except Exception:  # pylint: disable=broad-exception-caught
3483            self.serial.timeout = 3.0
3484        try:
3485            wto = getattr(self.serial, "write_timeout", None)
3486            if wto is None or float(wto) < 3.0:
3487                self.serial.write_timeout = 3.0
3488        except Exception:  # pylint: disable=broad-exception-caught
3489            self.serial.write_timeout = 3.0
3490        self._rng = rng or random.Random()
3491        """Random source for the 25-byte ``SEND`` frame that selects the key."""
3492        self._xor_key: Optional[bytearray] = None
3493        """4-byte XOR key chosen during :meth:`handshake`; ``None`` before."""
3494        self._model: Optional[str] = None
3495        """Model string reported by the radio (``M`` command); ``None`` before
3496        :meth:`handshake`."""
3497        self.progress_cb: Optional[Callable[[int, int, str], None]] = None
3498        """Optional ``callback(done, total, phase)`` called after every block;
3499        ``phase`` is ``"read"`` or ``"write"``."""
3500
3501    @classmethod
3502    def open(
3503        cls,
3504        config: CloneSerialConfig,
3505        *,
3506        logger=None,
3507        rng: Optional[random.Random] = None,
3508        serial_class=None,
3509    ) -> "CloneSerialTransport":
3510        """Open a real serial port and return a transport on it.
3511
3512        Args:
3513            config: Port name and timing.
3514            logger: Logger for protocol tracing; defaults to the module's
3515                transport logger.
3516            rng: Random source for the key-selection frame; inject a seeded
3517                one for reproducible tests.
3518            serial_class: Port class to instantiate; defaults to
3519                ``serial.Serial`` (pyserial).
3520
3521        Returns:
3522            CloneSerialTransport: Transport on the opened port.
3523
3524        Raises:
3525            CloneTransportError: If no ``serial_class`` is given and
3526                pyserial is not installed. Errors raised by ``serial_class``
3527                (e.g. ``serial.SerialException``) propagate unchanged.
3528        """
3529        if serial_class is None:
3530            if serial is None:
3531                raise CloneTransportError("pyserial is not installed")
3532            serial_class = serial.Serial
3533        port = serial_class(
3534            config.port,
3535            baudrate=config.baudrate,
3536            timeout=config.timeout,
3537            write_timeout=config.write_timeout,
3538        )
3539        return cls(port, logger=logger, rng=rng)
3540
3541    def __enter__(self) -> "CloneSerialTransport":
3542        """Return the transport itself for use in a ``with`` statement.
3543
3544        Returns:
3545            CloneSerialTransport: This transport.
3546        """
3547        return self
3548
3549    def __exit__(self, exc_type, exc, tb) -> None:  # type: ignore[override]
3550        """Close the port when leaving a ``with`` block.
3551
3552        Exceptions are not suppressed.
3553
3554        Args:
3555            exc_type: Exception class raised in the block, or ``None``; unused.
3556            exc: Exception instance, or ``None``; unused.
3557            tb: Traceback, or ``None``; unused.
3558        """
3559        self.close()
3560
3561    @property
3562    def model(self) -> Optional[str]:
3563        """Model string reported during the handshake, or ``None`` before it."""
3564        return self._model
3565
3566    def close(self) -> None:
3567        """Close the underlying port, ignoring any error."""
3568        try:
3569            self.serial.close()
3570        # Closing must never raise during cleanup.
3571        except Exception:  # pragma: no cover  # pylint: disable=broad-exception-caught
3572            pass
3573
3574    def handshake(self) -> str:
3575        """Enter clone mode and negotiate the XOR key.
3576
3577        Returns:
3578            str: The model string reported by the radio.
3579
3580        Raises:
3581            CloneTransportError: If an ACK is missing or wrong, the model
3582                string is empty, a read times out or a write is short.
3583        """
3584        self.logger.debug("Starting clone handshake")
3585        if hasattr(self.serial, "reset_input_buffer"):
3586            self.serial.reset_input_buffer()
3587        if hasattr(self.serial, "reset_output_buffer"):
3588            self.serial.reset_output_buffer()
3589
3590        self._write(HANDSHAKE_STRING)
3591        if self._read_exact(1) != ACK:
3592            raise CloneTransportError("Handshake ACK not received")
3593
3594        self._write(b"F")
3595        blob = self._read_exact(16)
3596        self.logger.debug("Received handshake blob: %s", blob.hex())
3597
3598        self._write(b"M")
3599        model_raw = self._read_exact(12)
3600        self._model = model_raw.decode("ascii", errors="ignore").strip("\x00 ")
3601        if not self._model:
3602            raise CloneTransportError("Radio did not return a model identifier")
3603        self.logger.debug("Radio model reported as %s", self._model)
3604
3605        frame, key = self._build_encryption_frame()
3606        self._write(frame)
3607        if self._read_exact(1) != ACK:
3608            raise CloneTransportError("Encryption ACK not received")
3609        self._xor_key = key
3610        self.logger.debug("Negotiated XOR key: %s", key.hex())
3611        return self._model
3612
3613    def read_clone(self, *, segments: Sequence[CloneSegment] | None = None) -> bytes:
3614        """Read memory from the radio.
3615
3616        Performs the handshake first if needed and ends the session with
3617        ``E``.
3618
3619        Args:
3620            segments: Regions to read, in order; defaults to
3621                ``DEFAULT_SEGMENTS``.
3622
3623        Returns:
3624            bytes: The decrypted payloads concatenated in segment order.
3625
3626        Raises:
3627            CloneTransportError: On a timeout or protocol error.
3628        """
3629        if segments is None:
3630            segments = DEFAULT_SEGMENTS
3631        if self._xor_key is None:
3632            self.handshake()
3633
3634        raw = bytearray()
3635        total_blocks = sum(seg.length for seg in segments) // READ_BLOCK
3636        done = 0
3637        for command, address in self._iter_read_commands(segments):
3638            header = bytes((command, (address >> 8) & 0xFF, address & 0xFF, READ_BLOCK))
3639            self.logger.debug(
3640                "Requesting block: command=0x%02X address=0x%04X", command, address
3641            )
3642            self._write(header)
3643            block = self._read_exact(BLOCK_HEADER + READ_BLOCK)
3644            payload = bytearray(block[BLOCK_HEADER:])
3645            decrypted = self._apply_xor(payload)
3646            raw.extend(decrypted)
3647            done += 1
3648            if self.progress_cb:
3649                try:
3650                    self.progress_cb(done, total_blocks, "read")
3651                # Progress reporting must never break the clone operation.
3652                except Exception:  # pylint: disable=broad-exception-caught
3653                    pass
3654        self._write(END_COMMAND)
3655        return bytes(raw)
3656
3657    def write_clone(self, data: bytes, *, segments: Sequence[CloneSegment] | None = None) -> None:
3658        """Write memory to the radio.
3659
3660        Each block must be acknowledged. Flash commits are slow, so the ACK
3661        timeout is 8 s for channel blocks, 10 s for settings blocks (address
3662        >= 0x8000) and 30 s for the APRS block (command 0x58). Performs the
3663        handshake first if needed and ends the session with ``E``. Pauses:
3664        0.05 s after blocks at >= 0x8000, 0.1 s + 0.5 s after the APRS block.
3665
3666        Args:
3667            data: Payloads concatenated in segment order; its length must equal
3668                the total segment length.
3669            segments: Regions to write, in order; defaults to
3670                ``DEFAULT_SEGMENTS``.
3671
3672        Raises:
3673            CloneTransportError: On a length mismatch, timeout, missing ACK
3674                or wrong ACK byte.
3675        """
3676        if segments is None:
3677            segments = DEFAULT_SEGMENTS
3678        if self._xor_key is None:
3679            self.handshake()
3680
3681        expected = sum(segment.length for segment in segments)
3682        if len(data) != expected:
3683            raise CloneTransportError(
3684                f"Write buffer length {len(data)} does not match expected {expected}"
3685            )
3686
3687        offset = 0
3688        total_blocks = sum(seg.length for seg in segments) // READ_BLOCK
3689        done = 0
3690        for command, address in self._iter_write_commands(segments):
3691            chunk = data[offset : offset + READ_BLOCK]
3692            if len(chunk) != READ_BLOCK:
3693                raise CloneTransportError("Write chunk size mismatch")
3694            payload = self._apply_xor(bytearray(chunk))
3695            header = bytes((command, (address >> 8) & 0xFF, address & 0xFF, READ_BLOCK))
3696            self.logger.debug("Writing block: command=0x%02X address=0x%04X", command, address)
3697            self._write(header + payload)
3698            # Flash commits can take seconds: settings blocks up to 10 s,
3699            # APRS up to 30 s (pacing as in NeonPlug's RT-950 Pro support).
3700            if command == 0x58:
3701                ack_timeout, pause = 30.0, 0.1
3702            elif address >= 0x8000:
3703                ack_timeout, pause = 10.0, 0.05
3704            else:
3705                ack_timeout, pause = 8.0, 0.0
3706            old_timeout = getattr(self.serial, "timeout", None)
3707            # Pipe-like objects may not support changing the timeout.
3708            try:
3709                self.serial.timeout = ack_timeout
3710            except Exception:  # pylint: disable=broad-exception-caught
3711                pass
3712            try:
3713                ack = self._read_exact(1)
3714            except CloneTransportError as exc:
3715                raise CloneTransportError(
3716                    f"No ACK for write cmd 0x{command:02X} address 0x{address:04X} ({exc})"
3717                ) from exc
3718            if ack != ACK:
3719                raise CloneTransportError(
3720                    f"Write ACK mismatch at 0x{address:04X}: expected 0x06, got {ack.hex()}"
3721                )
3722            self.logger.debug("Received ACK for 0x%04X", address)
3723            try:
3724                self.serial.timeout = old_timeout
3725            except Exception:  # pylint: disable=broad-exception-caught
3726                pass
3727            if pause:
3728                time.sleep(pause)
3729            if command == 0x58:
3730                time.sleep(0.5)  # let the APRS commit settle before 'E'
3731            offset += READ_BLOCK
3732            done += 1
3733            if self.progress_cb:
3734                try:
3735                    self.progress_cb(done, total_blocks, "write")
3736                # Progress reporting must never break the clone operation.
3737                except Exception:  # pylint: disable=broad-exception-caught
3738                    pass
3739
3740        self._write(END_COMMAND)
3741
3742    # ------------------------------------------------------------------
3743    # Internal helpers
3744    # ------------------------------------------------------------------
3745
3746    def _write(self, data: bytes) -> None:
3747        """Send bytes to the radio.
3748
3749        Args:
3750            data: Raw bytes to write; empty data sends nothing.
3751
3752        Raises:
3753            CloneTransportError: If the port reports a short write.
3754        """
3755        if not data:
3756            return
3757        written = self.serial.write(data)
3758        if written is None:
3759            return
3760        if written != len(data):
3761            raise CloneTransportError("Serial write truncated")
3762
3763    def _read_exact(self, size: int) -> bytes:
3764        """Read exactly ``size`` bytes.
3765
3766        Args:
3767            size: Number of bytes to read.
3768
3769        Returns:
3770            bytes: Exactly ``size`` bytes as received (not XOR-decoded).
3771
3772        Raises:
3773            CloneTransportError: If the port times out first.
3774        """
3775        buf = bytearray()
3776        while len(buf) < size:
3777            chunk = self.serial.read(size - len(buf))
3778            if not chunk:
3779                raise CloneTransportError("Serial read timed out")
3780            buf.extend(chunk)
3781        return bytes(buf)
3782
3783    def _build_encryption_frame(self) -> Tuple[bytes, bytearray]:
3784        """Build the 25-byte ``SEND`` frame and the key it selects.
3785
3786        Bytes 0-3 are ``SEND``. Byte 4 is a random code 0x10-0x14 or
3787        0x20-0x24. Bytes 5-23 are random indexes 0-19. Byte 24 is 0. Code
3788        0x1n selects ``frame[5 + 2n]``, code 0x2n selects ``frame[6 + 2n]``;
3789        that byte is the index into ``ENCRYPT_STRINGS`` of the key.
3790
3791        Returns:
3792            tuple[bytes, bytearray]: The frame to send and the 4-byte XOR key.
3793        """
3794        frame = bytearray(25)
3795        frame[0:4] = b"SEND"
3796        frame[4] = (self._rng.randint(1, 2) << 4) | self._rng.randint(0, 4)
3797        for index in range(19):
3798            frame[5 + index] = self._rng.randint(0, 19)
3799        code = frame[4]
3800        if code & 0x20:
3801            idx = (code - 0x20) * 2 + 1
3802        else:
3803            idx = (code - 0x10) * 2
3804        idx += 1
3805        symbol_index = frame[4 + idx]
3806        key = bytearray(ENCRYPT_STRINGS[symbol_index])
3807        return bytes(frame), key
3808
3809    def _apply_xor(self, payload: bytearray) -> bytearray:
3810        """XOR a payload in place with the session key and return it.
3811
3812        The operation is its own inverse, so it both encrypts and decrypts.
3813
3814        Bytes 0x00 and 0xFF, bytes equal to the key byte or its complement, and
3815        positions where the key byte is a space (0x20) are left unchanged.
3816
3817        Args:
3818            payload: Block payload; modified in place.
3819
3820        Returns:
3821            bytearray: The same ``payload`` object after XOR.
3822        """
3823        assert self._xor_key is not None, "XOR key not initialised"
3824        key = self._xor_key
3825        key_idx = 0
3826        for i, value in enumerate(payload):
3827            k = key[key_idx]
3828            key_idx = (key_idx + 1) % len(key)
3829            if k != 0x20 and value not in (0x00, 0xFF) and value not in (k, k ^ 0xFF):
3830                payload[i] = value ^ k
3831        return payload
3832
3833    @staticmethod
3834    def _iter_read_commands(segments: Sequence[CloneSegment]) -> Iterable[Tuple[int, int]]:
3835        """Yield ``(read_command, address)`` for every block of ``segments``.
3836
3837        Args:
3838            segments: Regions to read, in order.
3839
3840        Yields:
3841            tuple[int, int]: The segment's read command and the start address of
3842            each ``READ_BLOCK``-byte block.
3843        """
3844        for segment in segments:
3845            for offset in range(0, segment.length, READ_BLOCK):
3846                yield segment.read_command, segment.start + offset
3847
3848    @staticmethod
3849    def _iter_write_commands(segments: Sequence[CloneSegment]) -> Iterable[Tuple[int, int]]:
3850        """Yield ``(write_command, address)`` for every block of ``segments``.
3851
3852        Args:
3853            segments: Regions to write, in order.
3854
3855        Yields:
3856            tuple[int, int]: The segment's write command and the start address of
3857            each ``READ_BLOCK``-byte block.
3858        """
3859        for segment in segments:
3860            for offset in range(0, segment.length, READ_BLOCK):
3861                yield segment.write_command, segment.start + offset

The RT-950 Pro serial clone protocol.

Session outline:

  1. Send PROGRAMBT9000U; the radio answers ACK (0x06).
  2. F: the radio returns a 16-byte blob (logged only).
  3. M: the radio returns its 12-byte model string.
  4. Send a 25-byte SEND frame whose random contents select one of ENCRYPT_STRINGS as the 4-byte XOR key; the radio answers ACK.
  5. Transfer 0x80-byte blocks: header cmd, addr_hi, addr_lo, 0x80; reads return header plus payload, writes are answered with ACK.
  6. Send E to end the session.

Payload bytes are XOR-ed with the key, except 0x00, 0xFF, the key byte itself and its complement, and positions where the key byte is a space.

Constructor
Public constructor CloneSerialTransport(serial_port, *, logger=None, rng: Optional[random.Random] = None)
3453    def __init__(
3454        self,
3455        serial_port,
3456        *,
3457        logger=None,
3458        rng: Optional[random.Random] = None,
3459    ) -> None:
3460        """Wrap an already open port.
3461
3462        Read and write timeouts below 3 s are raised to 3 s.
3463
3464        Args:
3465            serial_port: Open serial port or CHIRP pipe.
3466            logger: Logger for protocol tracing; defaults to the module's
3467                transport logger.
3468            rng: Random source for the key-selection frame; inject a seeded
3469                one for reproducible tests.
3470        """
3471        self.serial = serial_port
3472        """The open port or CHIRP pipe; its timeouts are raised to at least 3 s."""
3473        self.logger = logger or logging.getLogger(__name__ + ".transport")
3474        """Logger for protocol tracing (debug level: commands, addresses)."""
3475        # Enforce sensible minimums to avoid premature timeouts during clone.
3476        # The port object may be any pipe-like object, so any failure while
3477        # inspecting it falls back to the minimum.
3478        try:
3479            to = getattr(self.serial, "timeout", None)
3480            if to is None or float(to) < 3.0:
3481                self.serial.timeout = 3.0
3482        except Exception:  # pylint: disable=broad-exception-caught
3483            self.serial.timeout = 3.0
3484        try:
3485            wto = getattr(self.serial, "write_timeout", None)
3486            if wto is None or float(wto) < 3.0:
3487                self.serial.write_timeout = 3.0
3488        except Exception:  # pylint: disable=broad-exception-caught
3489            self.serial.write_timeout = 3.0
3490        self._rng = rng or random.Random()
3491        """Random source for the 25-byte ``SEND`` frame that selects the key."""
3492        self._xor_key: Optional[bytearray] = None
3493        """4-byte XOR key chosen during :meth:`handshake`; ``None`` before."""
3494        self._model: Optional[str] = None
3495        """Model string reported by the radio (``M`` command); ``None`` before
3496        :meth:`handshake`."""
3497        self.progress_cb: Optional[Callable[[int, int, str], None]] = None
3498        """Optional ``callback(done, total, phase)`` called after every block;
3499        ``phase`` is ``"read"`` or ``"write"``."""

Wrap an already open port.

Read and write timeouts below 3 s are raised to 3 s.

Arguments:
  • serial_port: Open serial port or CHIRP pipe.
  • logger: Logger for protocol tracing; defaults to the module's transport logger.
  • rng: Random source for the key-selection frame; inject a seeded one for reproducible tests.
Fields
Public field serial

The open port or CHIRP pipe; its timeouts are raised to at least 3 s.

Public field logger

Logger for protocol tracing (debug level: commands, addresses).

Public field progress_cb: Optional[Callable[[int, int, str], NoneType]]

Optional callback(done, total, phase) called after every block; phase is "read" or "write".

Private field _rng

Random source for the 25-byte SEND frame that selects the key.

Private field _xor_key: Optional[bytearray]

4-byte XOR key chosen during handshake(); None before.

Private field _model: Optional[str]

Model string reported by the radio (M command); None before handshake().

Properties
Public property model: Optional[str]
3561    @property
3562    def model(self) -> Optional[str]:
3563        """Model string reported during the handshake, or ``None`` before it."""
3564        return self._model

Model string reported during the handshake, or None before it.

Methods
Public method
@classmethod
def open( cls, config: CloneSerialConfig, *, logger=None, rng: Optional[random.Random] = None, serial_class=None) -> CloneSerialTransport:
3501    @classmethod
3502    def open(
3503        cls,
3504        config: CloneSerialConfig,
3505        *,
3506        logger=None,
3507        rng: Optional[random.Random] = None,
3508        serial_class=None,
3509    ) -> "CloneSerialTransport":
3510        """Open a real serial port and return a transport on it.
3511
3512        Args:
3513            config: Port name and timing.
3514            logger: Logger for protocol tracing; defaults to the module's
3515                transport logger.
3516            rng: Random source for the key-selection frame; inject a seeded
3517                one for reproducible tests.
3518            serial_class: Port class to instantiate; defaults to
3519                ``serial.Serial`` (pyserial).
3520
3521        Returns:
3522            CloneSerialTransport: Transport on the opened port.
3523
3524        Raises:
3525            CloneTransportError: If no ``serial_class`` is given and
3526                pyserial is not installed. Errors raised by ``serial_class``
3527                (e.g. ``serial.SerialException``) propagate unchanged.
3528        """
3529        if serial_class is None:
3530            if serial is None:
3531                raise CloneTransportError("pyserial is not installed")
3532            serial_class = serial.Serial
3533        port = serial_class(
3534            config.port,
3535            baudrate=config.baudrate,
3536            timeout=config.timeout,
3537            write_timeout=config.write_timeout,
3538        )
3539        return cls(port, logger=logger, rng=rng)

Open a real serial port and return a transport on it.

Arguments:
  • config: Port name and timing.
  • logger: Logger for protocol tracing; defaults to the module's transport logger.
  • rng: Random source for the key-selection frame; inject a seeded one for reproducible tests.
  • serial_class: Port class to instantiate; defaults to serial.Serial (pyserial).
Returns:

CloneSerialTransport: Transport on the opened port.

Raises:
  • CloneTransportError: If no serial_class is given and pyserial is not installed. Errors raised by serial_class (e.g. serial.SerialException) propagate unchanged.
Public method def __enter__(self) -> CloneSerialTransport:
3541    def __enter__(self) -> "CloneSerialTransport":
3542        """Return the transport itself for use in a ``with`` statement.
3543
3544        Returns:
3545            CloneSerialTransport: This transport.
3546        """
3547        return self

Return the transport itself for use in a with statement.

Returns:

CloneSerialTransport: This transport.

Public method def __exit__(self, exc_type, exc, tb) -> None:
3549    def __exit__(self, exc_type, exc, tb) -> None:  # type: ignore[override]
3550        """Close the port when leaving a ``with`` block.
3551
3552        Exceptions are not suppressed.
3553
3554        Args:
3555            exc_type: Exception class raised in the block, or ``None``; unused.
3556            exc: Exception instance, or ``None``; unused.
3557            tb: Traceback, or ``None``; unused.
3558        """
3559        self.close()

Close the port when leaving a with block.

Exceptions are not suppressed.

Arguments:
  • exc_type: Exception class raised in the block, or None; unused.
  • exc: Exception instance, or None; unused.
  • tb: Traceback, or None; unused.
Public method def close(self) -> None:
3566    def close(self) -> None:
3567        """Close the underlying port, ignoring any error."""
3568        try:
3569            self.serial.close()
3570        # Closing must never raise during cleanup.
3571        except Exception:  # pragma: no cover  # pylint: disable=broad-exception-caught
3572            pass

Close the underlying port, ignoring any error.

Public method def handshake(self) -> str:
3574    def handshake(self) -> str:
3575        """Enter clone mode and negotiate the XOR key.
3576
3577        Returns:
3578            str: The model string reported by the radio.
3579
3580        Raises:
3581            CloneTransportError: If an ACK is missing or wrong, the model
3582                string is empty, a read times out or a write is short.
3583        """
3584        self.logger.debug("Starting clone handshake")
3585        if hasattr(self.serial, "reset_input_buffer"):
3586            self.serial.reset_input_buffer()
3587        if hasattr(self.serial, "reset_output_buffer"):
3588            self.serial.reset_output_buffer()
3589
3590        self._write(HANDSHAKE_STRING)
3591        if self._read_exact(1) != ACK:
3592            raise CloneTransportError("Handshake ACK not received")
3593
3594        self._write(b"F")
3595        blob = self._read_exact(16)
3596        self.logger.debug("Received handshake blob: %s", blob.hex())
3597
3598        self._write(b"M")
3599        model_raw = self._read_exact(12)
3600        self._model = model_raw.decode("ascii", errors="ignore").strip("\x00 ")
3601        if not self._model:
3602            raise CloneTransportError("Radio did not return a model identifier")
3603        self.logger.debug("Radio model reported as %s", self._model)
3604
3605        frame, key = self._build_encryption_frame()
3606        self._write(frame)
3607        if self._read_exact(1) != ACK:
3608            raise CloneTransportError("Encryption ACK not received")
3609        self._xor_key = key
3610        self.logger.debug("Negotiated XOR key: %s", key.hex())
3611        return self._model

Enter clone mode and negotiate the XOR key.

Returns:

str: The model string reported by the radio.

Raises:
  • CloneTransportError: If an ACK is missing or wrong, the model string is empty, a read times out or a write is short.
Public method def read_clone( self, *, segments: Optional[Sequence[CloneSegment]] = None) -> bytes:
3613    def read_clone(self, *, segments: Sequence[CloneSegment] | None = None) -> bytes:
3614        """Read memory from the radio.
3615
3616        Performs the handshake first if needed and ends the session with
3617        ``E``.
3618
3619        Args:
3620            segments: Regions to read, in order; defaults to
3621                ``DEFAULT_SEGMENTS``.
3622
3623        Returns:
3624            bytes: The decrypted payloads concatenated in segment order.
3625
3626        Raises:
3627            CloneTransportError: On a timeout or protocol error.
3628        """
3629        if segments is None:
3630            segments = DEFAULT_SEGMENTS
3631        if self._xor_key is None:
3632            self.handshake()
3633
3634        raw = bytearray()
3635        total_blocks = sum(seg.length for seg in segments) // READ_BLOCK
3636        done = 0
3637        for command, address in self._iter_read_commands(segments):
3638            header = bytes((command, (address >> 8) & 0xFF, address & 0xFF, READ_BLOCK))
3639            self.logger.debug(
3640                "Requesting block: command=0x%02X address=0x%04X", command, address
3641            )
3642            self._write(header)
3643            block = self._read_exact(BLOCK_HEADER + READ_BLOCK)
3644            payload = bytearray(block[BLOCK_HEADER:])
3645            decrypted = self._apply_xor(payload)
3646            raw.extend(decrypted)
3647            done += 1
3648            if self.progress_cb:
3649                try:
3650                    self.progress_cb(done, total_blocks, "read")
3651                # Progress reporting must never break the clone operation.
3652                except Exception:  # pylint: disable=broad-exception-caught
3653                    pass
3654        self._write(END_COMMAND)
3655        return bytes(raw)

Read memory from the radio.

Performs the handshake first if needed and ends the session with E.

Arguments:
Returns:

bytes: The decrypted payloads concatenated in segment order.

Raises:
  • CloneTransportError: On a timeout or protocol error.
Public method def write_clone( self, data: bytes, *, segments: Optional[Sequence[CloneSegment]] = None) -> None:
3657    def write_clone(self, data: bytes, *, segments: Sequence[CloneSegment] | None = None) -> None:
3658        """Write memory to the radio.
3659
3660        Each block must be acknowledged. Flash commits are slow, so the ACK
3661        timeout is 8 s for channel blocks, 10 s for settings blocks (address
3662        >= 0x8000) and 30 s for the APRS block (command 0x58). Performs the
3663        handshake first if needed and ends the session with ``E``. Pauses:
3664        0.05 s after blocks at >= 0x8000, 0.1 s + 0.5 s after the APRS block.
3665
3666        Args:
3667            data: Payloads concatenated in segment order; its length must equal
3668                the total segment length.
3669            segments: Regions to write, in order; defaults to
3670                ``DEFAULT_SEGMENTS``.
3671
3672        Raises:
3673            CloneTransportError: On a length mismatch, timeout, missing ACK
3674                or wrong ACK byte.
3675        """
3676        if segments is None:
3677            segments = DEFAULT_SEGMENTS
3678        if self._xor_key is None:
3679            self.handshake()
3680
3681        expected = sum(segment.length for segment in segments)
3682        if len(data) != expected:
3683            raise CloneTransportError(
3684                f"Write buffer length {len(data)} does not match expected {expected}"
3685            )
3686
3687        offset = 0
3688        total_blocks = sum(seg.length for seg in segments) // READ_BLOCK
3689        done = 0
3690        for command, address in self._iter_write_commands(segments):
3691            chunk = data[offset : offset + READ_BLOCK]
3692            if len(chunk) != READ_BLOCK:
3693                raise CloneTransportError("Write chunk size mismatch")
3694            payload = self._apply_xor(bytearray(chunk))
3695            header = bytes((command, (address >> 8) & 0xFF, address & 0xFF, READ_BLOCK))
3696            self.logger.debug("Writing block: command=0x%02X address=0x%04X", command, address)
3697            self._write(header + payload)
3698            # Flash commits can take seconds: settings blocks up to 10 s,
3699            # APRS up to 30 s (pacing as in NeonPlug's RT-950 Pro support).
3700            if command == 0x58:
3701                ack_timeout, pause = 30.0, 0.1
3702            elif address >= 0x8000:
3703                ack_timeout, pause = 10.0, 0.05
3704            else:
3705                ack_timeout, pause = 8.0, 0.0
3706            old_timeout = getattr(self.serial, "timeout", None)
3707            # Pipe-like objects may not support changing the timeout.
3708            try:
3709                self.serial.timeout = ack_timeout
3710            except Exception:  # pylint: disable=broad-exception-caught
3711                pass
3712            try:
3713                ack = self._read_exact(1)
3714            except CloneTransportError as exc:
3715                raise CloneTransportError(
3716                    f"No ACK for write cmd 0x{command:02X} address 0x{address:04X} ({exc})"
3717                ) from exc
3718            if ack != ACK:
3719                raise CloneTransportError(
3720                    f"Write ACK mismatch at 0x{address:04X}: expected 0x06, got {ack.hex()}"
3721                )
3722            self.logger.debug("Received ACK for 0x%04X", address)
3723            try:
3724                self.serial.timeout = old_timeout
3725            except Exception:  # pylint: disable=broad-exception-caught
3726                pass
3727            if pause:
3728                time.sleep(pause)
3729            if command == 0x58:
3730                time.sleep(0.5)  # let the APRS commit settle before 'E'
3731            offset += READ_BLOCK
3732            done += 1
3733            if self.progress_cb:
3734                try:
3735                    self.progress_cb(done, total_blocks, "write")
3736                # Progress reporting must never break the clone operation.
3737                except Exception:  # pylint: disable=broad-exception-caught
3738                    pass
3739
3740        self._write(END_COMMAND)

Write memory to the radio.

Each block must be acknowledged. Flash commits are slow, so the ACK timeout is 8 s for channel blocks, 10 s for settings blocks (address

= 0x8000) and 30 s for the APRS block (command 0x58). Performs the handshake first if needed and ends the session with E. Pauses: 0.05 s after blocks at >= 0x8000, 0.1 s + 0.5 s after the APRS block.

Arguments:
  • data: Payloads concatenated in segment order; its length must equal the total segment length.
  • segments: Regions to write, in order; defaults to DEFAULT_SEGMENTS.
Raises:
  • CloneTransportError: On a length mismatch, timeout, missing ACK or wrong ACK byte.
Private method def _write(self, data: bytes) -> None:
3746    def _write(self, data: bytes) -> None:
3747        """Send bytes to the radio.
3748
3749        Args:
3750            data: Raw bytes to write; empty data sends nothing.
3751
3752        Raises:
3753            CloneTransportError: If the port reports a short write.
3754        """
3755        if not data:
3756            return
3757        written = self.serial.write(data)
3758        if written is None:
3759            return
3760        if written != len(data):
3761            raise CloneTransportError("Serial write truncated")

Send bytes to the radio.

Arguments:
  • data: Raw bytes to write; empty data sends nothing.
Raises:
  • CloneTransportError: If the port reports a short write.
Private method def _read_exact(self, size: int) -> bytes:
3763    def _read_exact(self, size: int) -> bytes:
3764        """Read exactly ``size`` bytes.
3765
3766        Args:
3767            size: Number of bytes to read.
3768
3769        Returns:
3770            bytes: Exactly ``size`` bytes as received (not XOR-decoded).
3771
3772        Raises:
3773            CloneTransportError: If the port times out first.
3774        """
3775        buf = bytearray()
3776        while len(buf) < size:
3777            chunk = self.serial.read(size - len(buf))
3778            if not chunk:
3779                raise CloneTransportError("Serial read timed out")
3780            buf.extend(chunk)
3781        return bytes(buf)

Read exactly size bytes.

Arguments:
  • size: Number of bytes to read.
Returns:

bytes: Exactly size bytes as received (not XOR-decoded).

Raises:
  • CloneTransportError: If the port times out first.
Private method def _build_encryption_frame(self) -> Tuple[bytes, bytearray]:
3783    def _build_encryption_frame(self) -> Tuple[bytes, bytearray]:
3784        """Build the 25-byte ``SEND`` frame and the key it selects.
3785
3786        Bytes 0-3 are ``SEND``. Byte 4 is a random code 0x10-0x14 or
3787        0x20-0x24. Bytes 5-23 are random indexes 0-19. Byte 24 is 0. Code
3788        0x1n selects ``frame[5 + 2n]``, code 0x2n selects ``frame[6 + 2n]``;
3789        that byte is the index into ``ENCRYPT_STRINGS`` of the key.
3790
3791        Returns:
3792            tuple[bytes, bytearray]: The frame to send and the 4-byte XOR key.
3793        """
3794        frame = bytearray(25)
3795        frame[0:4] = b"SEND"
3796        frame[4] = (self._rng.randint(1, 2) << 4) | self._rng.randint(0, 4)
3797        for index in range(19):
3798            frame[5 + index] = self._rng.randint(0, 19)
3799        code = frame[4]
3800        if code & 0x20:
3801            idx = (code - 0x20) * 2 + 1
3802        else:
3803            idx = (code - 0x10) * 2
3804        idx += 1
3805        symbol_index = frame[4 + idx]
3806        key = bytearray(ENCRYPT_STRINGS[symbol_index])
3807        return bytes(frame), key

Build the 25-byte SEND frame and the key it selects.

Bytes 0-3 are SEND. Byte 4 is a random code 0x10-0x14 or 0x20-0x24. Bytes 5-23 are random indexes 0-19. Byte 24 is 0. Code 0x1n selects frame[5 + 2n], code 0x2n selects frame[6 + 2n]; that byte is the index into ENCRYPT_STRINGS of the key.

Returns:

tuple[bytes, bytearray]: The frame to send and the 4-byte XOR key.

Private method def _apply_xor(self, payload: bytearray) -> bytearray:
3809    def _apply_xor(self, payload: bytearray) -> bytearray:
3810        """XOR a payload in place with the session key and return it.
3811
3812        The operation is its own inverse, so it both encrypts and decrypts.
3813
3814        Bytes 0x00 and 0xFF, bytes equal to the key byte or its complement, and
3815        positions where the key byte is a space (0x20) are left unchanged.
3816
3817        Args:
3818            payload: Block payload; modified in place.
3819
3820        Returns:
3821            bytearray: The same ``payload`` object after XOR.
3822        """
3823        assert self._xor_key is not None, "XOR key not initialised"
3824        key = self._xor_key
3825        key_idx = 0
3826        for i, value in enumerate(payload):
3827            k = key[key_idx]
3828            key_idx = (key_idx + 1) % len(key)
3829            if k != 0x20 and value not in (0x00, 0xFF) and value not in (k, k ^ 0xFF):
3830                payload[i] = value ^ k
3831        return payload

XOR a payload in place with the session key and return it.

The operation is its own inverse, so it both encrypts and decrypts.

Bytes 0x00 and 0xFF, bytes equal to the key byte or its complement, and positions where the key byte is a space (0x20) are left unchanged.

Arguments:
  • payload: Block payload; modified in place.
Returns:

bytearray: The same payload object after XOR.

Private method
@staticmethod
def _iter_read_commands( segments: Sequence[CloneSegment]) -> Iterable[Tuple[int, int]]:
3833    @staticmethod
3834    def _iter_read_commands(segments: Sequence[CloneSegment]) -> Iterable[Tuple[int, int]]:
3835        """Yield ``(read_command, address)`` for every block of ``segments``.
3836
3837        Args:
3838            segments: Regions to read, in order.
3839
3840        Yields:
3841            tuple[int, int]: The segment's read command and the start address of
3842            each ``READ_BLOCK``-byte block.
3843        """
3844        for segment in segments:
3845            for offset in range(0, segment.length, READ_BLOCK):
3846                yield segment.read_command, segment.start + offset

Yield (read_command, address) for every block of segments.

Arguments:
  • segments: Regions to read, in order.
Yields:

tuple[int, int]: The segment's read command and the start address of each READ_BLOCK-byte block.

Private method
@staticmethod
def _iter_write_commands( segments: Sequence[CloneSegment]) -> Iterable[Tuple[int, int]]:
3848    @staticmethod
3849    def _iter_write_commands(segments: Sequence[CloneSegment]) -> Iterable[Tuple[int, int]]:
3850        """Yield ``(write_command, address)`` for every block of ``segments``.
3851
3852        Args:
3853            segments: Regions to write, in order.
3854
3855        Yields:
3856            tuple[int, int]: The segment's write command and the start address of
3857            each ``READ_BLOCK``-byte block.
3858        """
3859        for segment in segments:
3860            for offset in range(0, segment.length, READ_BLOCK):
3861                yield segment.write_command, segment.start + offset

Yield (write_command, address) for every block of segments.

Arguments:
  • segments: Regions to write, in order.
Yields:

tuple[int, int]: The segment's write command and the start address of each READ_BLOCK-byte block.

Public constant DEFAULT_SEGMENTS: Tuple[CloneSegment, ...] = (CloneSegment(read_command=82, write_command=87, start=0, length=32768), CloneSegment(read_command=82, write_command=87, start=32768, length=256), CloneSegment(read_command=82, write_command=87, start=36864, length=256), CloneSegment(read_command=82, write_command=87, start=40960, length=512), CloneSegment(read_command=82, write_command=87, start=45056, length=512), CloneSegment(read_command=82, write_command=87, start=53248, length=768), CloneSegment(read_command=84, write_command=88, start=0, length=128), CloneSegment(read_command=82, write_command=87, start=49152, length=256))

Clone image layout, in image order.

Reading follows this order; the image (.img) is the concatenation of these segments. Writing uses these segments in the order and lengths given by _WRITE_PLAN / _build_write_plan(): the channel segment is cut to 0x7800 or 0x7C00, and zone names and APRS are optional.

Private constant HANDSHAKE_STRING = b'PROGRAMBT9000U'

Magic string that puts the radio into clone mode.

Private constant ACK = b'\x06'

Single-byte acknowledgement sent by the radio.

Private constant END_COMMAND = b'E'

Command that ends a clone session.

Private constant READ_BLOCK = 128

Payload size in bytes of every read and write block.

Private constant BLOCK_HEADER = 4

Size of the block header: command, address high, address low, length.

Private constant ENCRYPT_STRINGS: Tuple[bytes, ...] = (b'BHT ', b'CO 7', b'A ES', b' EIY', b'M PQ', b'XN Y', b'RVB ', b' HQP', b'W RC', b'MS N', b' SAT', b'K DH', b'ZO R', b'C SL', b'6RB ', b' JCG', b'PN V', b'J PK', b'EK L', b'I LZ')

Candidate 4-byte XOR keys; the handshake frame selects one of them.

6. CHIRP integration

RT950ProRadio and one RT950ProZoneRadio sub-device per zone.

CHIRP compatibility layer

Private function def _require_chirp(what: str) -> None:
4525def _require_chirp(what: str) -> None:
4526    """Raise a clear error when CHIRP is not available.
4527
4528    Args:
4529        what: Name of the method that needs CHIRP, used in the message.
4530
4531    Raises:
4532        RadioError: If :data:`HAVE_CHIRP` is ``False``; the message names
4533            ``what`` and the original import error.
4534    """
4535    if not HAVE_CHIRP:
4536        raise errors.RadioError(
4537            f"{what} needs CHIRP, which could not be imported "
4538            f"({_CHIRP_IMPORT_ERROR}); without CHIRP the driver only loads "
4539            "for documentation builds"
4540        )

Raise a clear error when CHIRP is not available.

Arguments:
  • what: Name of the method that needs CHIRP, used in the message.
Raises:
  • RadioError: If HAVE_CHIRP is False; the message names what and the original import error.
Public constant HAVE_CHIRP: bool = False

True when the real CHIRP modules were imported.

False means the stand-ins above are in use: the module imports (for documentation builds) but RT950ProRadio.get_features(), RT950ProRadio.get_settings(), RT950ProRadio.get_memory() and RT950ProRadio.set_memory() (and the same methods of a zone) raise RadioError.

Constants and lookup tables for the CHIRP layer

Private function def _build_memory_extra( channel: ChannelRecord) -> radtel_rt950pro.RadioSettingGroup:
4772def _build_memory_extra(channel: ChannelRecord) -> RadioSettingGroup:
4773    """Build the per-channel *RT-950 Pro Extras* settings shown by CHIRP.
4774
4775    Args:
4776        channel: The channel record.
4777
4778    Returns:
4779        RadioSettingGroup: Scrambler code and encryption mode.
4780    """
4781    group = RadioSettingGroup('rt950_extra', 'RT-950 Pro Extras')
4782    scrambler_value = RadioSettingValueInteger(0, 8, channel.scrambler or 0)
4783    scrambler = RadioSetting('scrambler', 'Scrambler Code', scrambler_value)
4784    group.append(scrambler)
4785    encryption_raw = channel.encryption if channel.encryption is not None else 0
4786    encryption_value = RadioSettingValueInteger(0, 3, encryption_raw)
4787    encryption = RadioSetting('encryption', 'Encryption Mode', encryption_value)
4788    group.append(encryption)
4789    return group

Build the per-channel RT-950 Pro Extras settings shown by CHIRP.

Arguments:
  • channel: The channel record.
Returns:

RadioSettingGroup: Scrambler code and encryption mode.

Private function def _extract_memory_extra(mem) -> Dict[str, int]:
4791def _extract_memory_extra(mem) -> Dict[str, int]:
4792    """Collect the extra settings from a CHIRP memory.
4793
4794    Accepts both a plain dict and a CHIRP settings group in ``mem.extra``.
4795
4796    Args:
4797        mem: A CHIRP ``Memory``.
4798
4799    Returns:
4800        dict[str, int]: Setting name to value.
4801    """
4802    extras: Dict[str, int] = {}
4803    container = getattr(mem, 'extra', None)
4804    if isinstance(container, dict):
4805        for key in ('scrambler', 'encryption'):
4806            value = container.get(key)
4807            if value is not None:
4808                extras[key] = value
4809        return extras
4810    if container is None:
4811        return extras
4812    if hasattr(container, 'walk'):
4813        iterable = list(container.walk())
4814    else:
4815        try:
4816            iterable = list(container)
4817        except TypeError:
4818            iterable = []
4819    for setting in iterable:
4820        if not isinstance(setting, RadioSetting):
4821            continue
4822        value_obj = getattr(setting, 'value', None)
4823        if hasattr(value_obj, 'get_value'):
4824            raw = value_obj.get_value()
4825        else:
4826            raw = value_obj
4827        extras[setting.get_name()] = raw
4828    return extras

Collect the extra settings from a CHIRP memory.

Accepts both a plain dict and a CHIRP settings group in mem.extra.

Arguments:
  • mem: A CHIRP Memory.
Returns:

dict[str, int]: Setting name to value.

Private function def _format_frequency(hz: Optional[int]) -> str:
4830def _format_frequency(hz: Optional[int]) -> str:
4831    """Format Hz for a text setting; ``None`` and 0 give ``""``.
4832
4833    Args:
4834        hz: Frequency in Hz, or ``None``.
4835
4836    Returns:
4837        str: The text from ``chirp_common.format_freq``, or ``""``.
4838    """
4839    if hz in (None, 0):
4840        return ""
4841    return chirp_common.format_freq(hz)

Format Hz for a text setting; None and 0 give "".

Arguments:
  • hz: Frequency in Hz, or None.
Returns:

str: The text from chirp_common.format_freq, or "".

Private function def _parse_frequency(text: str) -> Optional[int]:
4843def _parse_frequency(text: str) -> Optional[int]:
4844    """Parse a frequency text as CHIRP does.
4845
4846    Args:
4847        text: Frequency text, e.g. ``"145.500"``.
4848
4849    Returns:
4850        int | None: Frequency in Hz, or ``None`` for empty text.
4851
4852    Raises:
4853        ValueError: If the text is invalid or not positive.
4854    """
4855    value = text.strip()
4856    if not value:
4857        return None
4858    hz = chirp_common.parse_freq(value)
4859    if hz <= 0:
4860        raise ValueError("Frequency must be positive")
4861    return hz

Parse a frequency text as CHIRP does.

Arguments:
  • text: Frequency text, e.g. "145.500".
Returns:

int | None: Frequency in Hz, or None for empty text.

Raises:
  • ValueError: If the text is invalid or not positive.
Private function def _make_integer_setting( name: str, label: str, current: Optional[int], minimum: int, maximum: int, callback, *args) -> radtel_rt950pro.RadioSetting:
4883def _make_integer_setting(
4884    name: str, label: str, current: Optional[int], minimum: int, maximum: int, callback, *args
4885) -> RadioSetting:
4886    """Create an integer ``RadioSetting`` with an apply callback.
4887
4888    Args:
4889        name: Internal setting name.
4890        label: Label shown in CHIRP.
4891        current: Current value; ``None`` shows ``minimum``.
4892        minimum: Lowest allowed value.
4893        maximum: Highest allowed value.
4894        callback: Called as ``callback(setting, *args)`` on apply.
4895        *args: Extra arguments for ``callback``.
4896
4897    Returns:
4898        RadioSetting: The configured setting.
4899    """
4900    active = minimum if current is None else int(current)
4901    setting = RadioSetting(name, label, RadioSettingValueInteger(minimum, maximum, active))
4902    setting.set_apply_callback(callback, *args)
4903    return setting

Create an integer RadioSetting with an apply callback.

Arguments:
  • name: Internal setting name.
  • label: Label shown in CHIRP.
  • current: Current value; None shows minimum.
  • minimum: Lowest allowed value.
  • maximum: Highest allowed value.
  • callback: Called as callback(setting, *args) on apply.
  • *args: Extra arguments for callback.
Returns:

RadioSetting: The configured setting.

Private function def _unknown_label(value) -> str:
4906def _unknown_label(value) -> str:
4907    """Return the list label for a stored value the CPS does not offer.
4908
4909    Args:
4910        value: The stored value (e.g. ``3`` for an offset direction).
4911
4912    Returns:
4913        str: ``"Unknown (<value>)"``, e.g. ``"Unknown (3)"``.
4914    """
4915    return f'Unknown ({value})'

Return the list label for a stored value the CPS does not offer.

Arguments:
  • value: The stored value (e.g. 3 for an offset direction).
Returns:

str: "Unknown (<value>)", e.g. "Unknown (3)".

Private function def _make_list_setting( name: str, label: str, choices, current, target, attr: str) -> radtel_rt950pro.RadioSetting:
4918def _make_list_setting(name: str, label: str, choices, current, target, attr: str) -> RadioSetting:
4919    """Create a list setting for one field of a settings object.
4920
4921    Used for the VFO and modulation screens. The options are the labels of
4922    ``choices``. A current value that is not in ``choices`` gets an extra
4923    option, which is selected: ``Not set`` for ``None`` (byte 0xFF), else
4924    one made by :func:`_unknown_label`. Choosing it (or leaving it) keeps the
4925    stored value, see :func:`_apply_list_choice`.
4926
4927    Args:
4928        name: Internal setting name, e.g. ``"vfo.0.step"``.
4929        label: Label shown in CHIRP, as in the CPS (e.g. ``"Step Freq"``).
4930        choices: ``(label, value)`` pairs in CPS order.
4931        current: The field's current value.
4932        target: Object the callback updates (a :class:`VFOSettings` or
4933            :class:`ModulationSettings`).
4934        attr: Name of the field on ``target``.
4935
4936    Returns:
4937        RadioSetting: The setting, wired to :func:`_apply_list_choice`.
4938    """
4939    labels = [text for text, _ in choices]
4940    values = [value for _, value in choices]
4941    if current in values:
4942        index = values.index(current)
4943    else:
4944        labels.append('Not set' if current is None else _unknown_label(current))
4945        index = len(labels) - 1
4946    setting = RadioSetting(name, label, RadioSettingValueList(labels, current_index=index))
4947    setting.set_apply_callback(_apply_list_choice, target, attr, choices)
4948    return setting

Create a list setting for one field of a settings object.

Used for the VFO and modulation screens. The options are the labels of choices. A current value that is not in choices gets an extra option, which is selected: Not set for None (byte 0xFF), else one made by _unknown_label(). Choosing it (or leaving it) keeps the stored value, see _apply_list_choice().

Arguments:
  • name: Internal setting name, e.g. "vfo.0.step".
  • label: Label shown in CHIRP, as in the CPS (e.g. "Step Freq").
  • choices: (label, value) pairs in CPS order.
  • current: The field's current value.
  • target: Object the callback updates (a VFOSettings or ModulationSettings).
  • attr: Name of the field on target.
Returns:

RadioSetting: The setting, wired to _apply_list_choice().

Private function def _make_vfo_tone( name: str, label: str, tone: ToneSetting, vfo, attr: str) -> radtel_rt950pro.RadioSetting:
4951def _make_vfo_tone(name: str, label: str, tone: ToneSetting, vfo, attr: str) -> RadioSetting:
4952    """Create a Rx or Tx QT/DQT list setting for one VFO.
4953
4954    The options are ``_VFO_TONE_LABELS``. A tone that is not in that list
4955    (a non-standard CTCSS value) gets an extra option made by
4956    :func:`_unknown_label` with the tone as the CPS writes it; it stays
4957    unchanged unless another tone is chosen (see :func:`_apply_vfo_tone`).
4958    An unknown DCS index is decoded as OFF and shown as OFF; its bytes are
4959    kept unless another tone is chosen.
4960
4961    Args:
4962        name: Internal setting name, e.g. ``"vfo.0.rx_tone"``.
4963        label: ``"Rx QT/DQT"`` or ``"Tx QT/DQT"``.
4964        tone: The current tone.
4965        vfo: VFO entry the callback updates.
4966        attr: ``"rx_tone"`` or ``"tx_tone"``.
4967
4968    Returns:
4969        RadioSetting: The setting, wired to :func:`_apply_vfo_tone`.
4970    """
4971    labels = list(_VFO_TONE_LABELS)
4972    shown = tone.to_display()
4973    if shown in labels:
4974        index = labels.index(shown)
4975    else:
4976        labels.append(_unknown_label(shown))
4977        index = len(labels) - 1
4978    setting = RadioSetting(name, label, RadioSettingValueList(labels, current_index=index))
4979    setting.set_apply_callback(_apply_vfo_tone, vfo, attr)
4980    return setting

Create a Rx or Tx QT/DQT list setting for one VFO.

The options are _VFO_TONE_LABELS. A tone that is not in that list (a non-standard CTCSS value) gets an extra option made by _unknown_label() with the tone as the CPS writes it; it stays unchanged unless another tone is chosen (see _apply_vfo_tone()). An unknown DCS index is decoded as OFF and shown as OFF; its bytes are kept unless another tone is chosen.

Arguments:
  • name: Internal setting name, e.g. "vfo.0.rx_tone".
  • label: "Rx QT/DQT" or "Tx QT/DQT".
  • tone: The current tone.
  • vfo: VFO entry the callback updates.
  • attr: "rx_tone" or "tx_tone".
Returns:

RadioSetting: The setting, wired to _apply_vfo_tone().

Private function def _make_vfo_frequency( name: str, label: str, hz: Optional[int], callback, vfo) -> radtel_rt950pro.RadioSetting:
4983def _make_vfo_frequency(name: str, label: str, hz: Optional[int], callback, vfo) -> RadioSetting:
4984    """Create a frequency text setting (MHz) for one VFO.
4985
4986    Args:
4987        name: Internal setting name, e.g. ``"vfo.0.freq"``.
4988        label: ``"Rx Freq"`` or ``"Offset Freq"``.
4989        hz: Current frequency in Hz, or ``None`` (shown empty).
4990        callback: :func:`_apply_vfo_frequency` or :func:`_apply_vfo_offset`.
4991        vfo: VFO entry the callback updates.
4992
4993    Returns:
4994        RadioSetting: The setting, wired to ``callback``.
4995    """
4996    value = RadioSettingValueString(0, 12, _format_frequency(hz) or '', autopad=False)
4997    setting = RadioSetting(name, label, value)
4998    setting.set_apply_callback(callback, vfo)
4999    return setting

Create a frequency text setting (MHz) for one VFO.

Arguments:
  • name: Internal setting name, e.g. "vfo.0.freq".
  • label: "Rx Freq" or "Offset Freq".
  • hz: Current frequency in Hz, or None (shown empty).
  • callback: _apply_vfo_frequency() or _apply_vfo_offset().
  • vfo: VFO entry the callback updates.
Returns:

RadioSetting: The setting, wired to callback.

Private function def _build_vfo_group( vfos: Optional[List[VFOSettings]]) -> radtel_rt950pro.RadioSettingGroup:
5002def _build_vfo_group(vfos: Optional[List[VFOSettings]]) -> RadioSettingGroup:
5003    """Build the *VFO Profiles* settings group (one subgroup per VFO).
5004
5005    Each subgroup (``VFO-A`` to ``VFO-C``) shows the fields of the CPS
5006    *VFO Mode* screen, with its labels, choices and order: Rx Freq,
5007    Rx QT/DQT, Tx QT/DQT, Busy Lockout, Offset Dir, Signalling, Tx Power,
5008    Scramble, Bandwidth, Encryption, RxModulation, Freq Band (read-only, no
5009    callback), Step Freq and Offset Freq. Learn FHSS and the offset
5010    direction "split" are not shown, as in the CPS; their stored bits are
5011    kept. A stored value outside a list is shown as ``Unknown (<value>)``
5012    and left unchanged on apply. Exceptions: a power nibble above 2 is shown
5013    as Low and an unknown DCS index as OFF; both are kept unless that field
5014    is edited, and OFF cannot be chosen to clear such a DCS index.
5015
5016    Args:
5017        vfos: VFO entries, or ``None``.
5018
5019    Returns:
5020        RadioSettingGroup: One subgroup per VFO; empty if ``vfos`` is empty
5021        or ``None``.
5022    """
5023    group = RadioSettingGroup('vfo', 'VFO Profiles')
5024    if not vfos:
5025        return group
5026    for idx, vfo in enumerate(vfos):
5027        letter = _VFO_LABELS[idx] if idx < len(_VFO_LABELS) else str(idx)
5028        sub = RadioSettingGroup(f'vfo.{idx}', f'VFO-{letter}')
5029        key = f'vfo.{idx}'
5030        sub.append(_make_vfo_frequency(f'{key}.freq', 'Rx Freq', vfo.rx_hz,
5031                                       _apply_vfo_frequency, vfo))
5032        sub.append(_make_vfo_tone(f'{key}.rx_tone', 'Rx QT/DQT', vfo.rx_tone, vfo, 'rx_tone'))
5033        sub.append(_make_vfo_tone(f'{key}.tx_tone', 'Tx QT/DQT', vfo.tx_tone, vfo, 'tx_tone'))
5034        sub.append(_make_list_setting(f'{key}.busy_lockout', 'Busy Lockout',
5035                                  _VFO_BUSY_LOCKOUT_CHOICES, vfo.busy_lockout, vfo,
5036                                  'busy_lockout'))
5037        sub.append(_make_list_setting(f'{key}.offset_direction', 'Offset Dir',
5038                                  _VFO_OFFSET_CHOICES, vfo.offset_direction, vfo,
5039                                  'offset_direction'))
5040        sub.append(_make_list_setting(f'{key}.signalling_group', 'Signalling',
5041                                  _VFO_SIGNALLING_CHOICES, vfo.signalling_group, vfo,
5042                                  'signalling_group'))
5043        sub.append(_make_list_setting(f'{key}.power', 'Tx Power', _VFO_POWER_CHOICES,
5044                                  vfo.tx_power, vfo, 'tx_power'))
5045        sub.append(_make_list_setting(f'{key}.scrambler', 'Scramble', _VFO_SCRAMBLE_CHOICES,
5046                                  vfo.scrambler, vfo, 'scrambler'))
5047        sub.append(_make_list_setting(f'{key}.bandwidth', 'Bandwidth', _VFO_BANDWIDTH_CHOICES,
5048                                  vfo.bandwidth, vfo, 'bandwidth'))
5049        sub.append(_make_list_setting(f'{key}.encryption', 'Encryption', _VFO_ENCRYPTION_CHOICES,
5050                                  vfo.encryption, vfo, 'encryption'))
5051        sub.append(_make_list_setting(f'{key}.modulation', 'RxModulation',
5052                                  _VFO_MODULATION_CHOICES, vfo.rx_modulation, vfo,
5053                                  'rx_modulation'))
5054        band_labels = [text for text, _ in _VFO_BAND_CHOICES]
5055        band_values = [value for _, value in _VFO_BAND_CHOICES]
5056        if vfo.freq_band in band_values:
5057            band_index = band_values.index(vfo.freq_band)
5058        else:
5059            band_labels.append(_unknown_label(vfo.freq_band))
5060            band_index = len(band_labels) - 1
5061        band_value = RadioSettingValueList(band_labels, current_index=band_index)
5062        band_value.set_mutable(False)
5063        sub.append(RadioSetting(f'{key}.freq_band', 'Freq Band', band_value))
5064        sub.append(_make_list_setting(f'{key}.step', 'Step Freq', _VFO_STEP_CHOICES,
5065                                  vfo.step_freq_index, vfo, 'step_freq_index'))
5066        sub.append(_make_vfo_frequency(f'{key}.offset', 'Offset Freq', vfo.offset_hz,
5067                                       _apply_vfo_offset, vfo))
5068        group.append(sub)
5069    return group

Build the VFO Profiles settings group (one subgroup per VFO).

Each subgroup (VFO-A to VFO-C) shows the fields of the CPS VFO Mode screen, with its labels, choices and order: Rx Freq, Rx QT/DQT, Tx QT/DQT, Busy Lockout, Offset Dir, Signalling, Tx Power, Scramble, Bandwidth, Encryption, RxModulation, Freq Band (read-only, no callback), Step Freq and Offset Freq. Learn FHSS and the offset direction "split" are not shown, as in the CPS; their stored bits are kept. A stored value outside a list is shown as Unknown (<value>) and left unchanged on apply. Exceptions: a power nibble above 2 is shown as Low and an unknown DCS index as OFF; both are kept unless that field is edited, and OFF cannot be chosen to clear such a DCS index.

Arguments:
  • vfos: VFO entries, or None.
Returns:

RadioSettingGroup: One subgroup per VFO; empty if vfos is empty or None.

Private function def _build_modulation_group( modulation: ModulationSettings) -> radtel_rt950pro.RadioSettingGroup:
5071def _build_modulation_group(modulation: ModulationSettings) -> RadioSettingGroup:
5072    """Build the *Broadcast/Modulation* settings group.
5073
5074    The global settings follow the CPS screen *FM/AM/SSB Modulation*: Work
5075    Mode, Modulation Mode, AM/SSB Step Freq and AM/SSB Rx Gain are lists with
5076    the CPS labels (``_MOD_*_CHOICES``); a field that is not set (0xFF) shows
5077    ``Not set`` and is left unchanged unless a value is chosen. The current
5078    FM/AM/SSB channel is a number 0-14, the range the decoder returns (the
5079    CPS does not show it).
5080
5081    Args:
5082        modulation: Modulation settings.
5083
5084    Returns:
5085        RadioSettingGroup: Global parameters, plus FM, AM and SSB memory
5086        subgroups when ``modulation.channels`` is not empty.
5087    """
5088    group = RadioSettingGroup('modulation', 'Broadcast/Modulation')
5089    global_group = RadioSettingGroup('modulation.global', 'Global Settings')
5090    for key, label in (('fm_current_channel', 'FM Current Channel'),
5091                       ('am_current_channel', 'AM Current Channel'),
5092                       ('ssb_current_channel', 'SSB Current Channel')):
5093        global_group.append(
5094            _make_integer_setting(
5095                f'modulation.{key}', label, getattr(modulation, key), 0, 14,
5096                _apply_modulation_int, modulation, key,
5097            )
5098        )
5099    for key, label, choices, attr in (
5100            ('work_mode', 'Work Mode', _MOD_WORK_MODE_CHOICES, 'work_mode'),
5101            ('modulation_mode', 'Modulation Mode', _MOD_MODULATION_CHOICES,
5102             'modulation_mode'),
5103            ('am_step', 'AM Step Freq', _MOD_AM_STEP_CHOICES, 'am_step_index'),
5104            ('am_rx_gain', 'AM Rx Gain', _MOD_RX_GAIN_CHOICES, 'am_rx_gain'),
5105            ('ssb_step', 'SSB Step Freq', _MOD_SSB_STEP_CHOICES, 'ssb_step_index'),
5106            ('ssb_rx_gain', 'SSB Rx Gain', _MOD_RX_GAIN_CHOICES, 'ssb_rx_gain')):
5107        global_group.append(
5108            _make_list_setting(f'modulation.{key}', label, choices,
5109                               getattr(modulation, attr), modulation, attr))
5110    group.append(global_group)
5111
5112    if modulation.channels:
5113        group.append(
5114            _build_modulation_channel_group(
5115                'modulation.fm_channels', 'FM Broadcast Channels', modulation, 'fm'
5116            )
5117        )
5118        group.append(
5119            _build_modulation_channel_group(
5120                'modulation.am_channels', 'AM Broadcast Channels', modulation, 'am'
5121            )
5122        )
5123        group.append(
5124            _build_modulation_channel_group(
5125                'modulation.ssb_channels', 'SSB Channels', modulation, 'ssb'
5126            )
5127        )
5128    return group

Build the Broadcast/Modulation settings group.

The global settings follow the CPS screen FM/AM/SSB Modulation: Work Mode, Modulation Mode, AM/SSB Step Freq and AM/SSB Rx Gain are lists with the CPS labels (_MOD_*_CHOICES); a field that is not set (0xFF) shows Not set and is left unchanged unless a value is chosen. The current FM/AM/SSB channel is a number 0-14, the range the decoder returns (the CPS does not show it).

Arguments:
  • modulation: Modulation settings.
Returns:

RadioSettingGroup: Global parameters, plus FM, AM and SSB memory subgroups when modulation.channels is not empty.

Private function def _build_modulation_channel_group( name_prefix: str, label: str, modulation: ModulationSettings, mode: str) -> radtel_rt950pro.RadioSettingGroup:
5131def _build_modulation_channel_group(
5132    name_prefix: str, label: str, modulation: ModulationSettings, mode: str
5133) -> RadioSettingGroup:
5134    """Build the settings subgroup for the FM, AM or SSB memories.
5135
5136    Args:
5137        name_prefix: Prefix for the internal setting names.
5138        label: Label shown in CHIRP.
5139        modulation: Modulation settings.
5140        mode: ``"fm"``, ``"am"`` or ``"ssb"``.
5141
5142    Returns:
5143        RadioSettingGroup: One subgroup per memory entry.
5144    """
5145    subgroup = RadioSettingGroup(name_prefix, label)
5146    for idx, channel in enumerate(modulation.channels):
5147        channel_group = RadioSettingGroup(f'{name_prefix}.{idx}', f'Channel {idx + 1}')
5148        if mode == 'fm':
5149            freq_setting = RadioSetting(
5150                f'{name_prefix}.{idx}.freq',
5151                'Frequency',
5152                RadioSettingValueString(
5153                    0, 12, _format_frequency(channel.fm_frequency) or '', autopad=False
5154                ),
5155            )
5156            freq_setting.set_apply_callback(
5157                _apply_modulation_channel_frequency, modulation, idx, 'fm_frequency'
5158            )
5159            channel_group.append(freq_setting)
5160            name_setting = RadioSetting(
5161                f'{name_prefix}.{idx}.name',
5162                'Name',
5163                RadioSettingValueString(0, 16, channel.fm_name or '', autopad=False),
5164            )
5165            name_setting.set_apply_callback(
5166                _apply_modulation_channel_name, modulation, idx, 'fm_name'
5167            )
5168            channel_group.append(name_setting)
5169        elif mode == 'am':
5170            freq_setting = RadioSetting(
5171                f'{name_prefix}.{idx}.freq',
5172                'Frequency',
5173                RadioSettingValueString(
5174                    0, 12, _format_frequency(channel.am_frequency) or '', autopad=False
5175                ),
5176            )
5177            freq_setting.set_apply_callback(
5178                _apply_modulation_channel_frequency, modulation, idx, 'am_frequency'
5179            )
5180            channel_group.append(freq_setting)
5181            name_setting = RadioSetting(
5182                f'{name_prefix}.{idx}.name',
5183                'Name',
5184                RadioSettingValueString(0, 16, channel.am_name or '', autopad=False),
5185            )
5186            name_setting.set_apply_callback(
5187                _apply_modulation_channel_name, modulation, idx, 'am_name'
5188            )
5189            channel_group.append(name_setting)
5190        elif mode == 'ssb':
5191            freq_setting = RadioSetting(
5192                f'{name_prefix}.{idx}.freq',
5193                'Frequency',
5194                RadioSettingValueString(
5195                    0, 12, _format_frequency(channel.ssb_frequency) or '', autopad=False
5196                ),
5197            )
5198            freq_setting.set_apply_callback(
5199                _apply_modulation_channel_frequency, modulation, idx, 'ssb_frequency'
5200            )
5201            channel_group.append(freq_setting)
5202            bandwidth_setting = _make_integer_setting(
5203                f'{name_prefix}.{idx}.bandwidth',
5204                'Bandwidth',
5205                channel.ssb_bandwidth,
5206                0,
5207                255,
5208                _apply_modulation_channel_int,
5209                modulation,
5210                idx,
5211                'ssb_bandwidth'
5212            )
5213            channel_group.append(bandwidth_setting)
5214            beat_setting = RadioSetting(
5215                f'{name_prefix}.{idx}.beat',
5216                'Beat Offset',
5217                RadioSettingValueInteger(-32768, 32767, int(channel.ssb_beat_offset or 0)),
5218            )
5219            beat_setting.set_apply_callback(_apply_modulation_channel_beat, modulation, idx)
5220            channel_group.append(beat_setting)
5221            name_setting = RadioSetting(
5222                f'{name_prefix}.{idx}.name',
5223                'Name',
5224                RadioSettingValueString(0, 16, channel.ssb_name or '', autopad=False),
5225            )
5226            name_setting.set_apply_callback(
5227                _apply_modulation_channel_name, modulation, idx, 'ssb_name'
5228            )
5229            channel_group.append(name_setting)
5230        subgroup.append(channel_group)
5231    return subgroup

Build the settings subgroup for the FM, AM or SSB memories.

Arguments:
  • name_prefix: Prefix for the internal setting names.
  • label: Label shown in CHIRP.
  • modulation: Modulation settings.
  • mode: "fm", "am" or "ssb".
Returns:

RadioSettingGroup: One subgroup per memory entry.

Private function def _apply_modulation_int(rsetting, modulation, attr):
5234def _apply_modulation_int(rsetting, modulation, attr):
5235    """Settings callback: store a non-negative integer in ``modulation.attr``.
5236
5237    Args:
5238        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5239        modulation: Modulation settings to update.
5240        attr: Attribute name on ``modulation``, e.g. ``"fm_current_channel"``.
5241    """
5242    setattr(modulation, attr, max(0, _value_as_int(rsetting.value)))

Settings callback: store a non-negative integer in modulation.attr.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • modulation: Modulation settings to update.
  • attr: Attribute name on modulation, e.g. "fm_current_channel".
Private function def _apply_modulation_channel_frequency(rsetting, modulation, index, attr):
5244def _apply_modulation_channel_frequency(rsetting, modulation, index, attr):
5245    """Settings callback: store a parsed frequency (or ``None``) in an entry.
5246
5247    Empty text stores ``None``; otherwise the text is parsed to Hz.
5248
5249    Args:
5250        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5251        modulation: Modulation settings to update.
5252        index: Index into ``modulation.channels`` (0-15).
5253        attr: ``"fm_frequency"``, ``"am_frequency"`` or ``"ssb_frequency"``.
5254
5255    Raises:
5256        ValueError: If the text is not a valid positive frequency.
5257    """
5258    try:
5259        value = _value_as_string(rsetting.value).strip()
5260    except AttributeError:
5261        value = str(rsetting.value).strip()
5262    freq = _parse_frequency(value) if value else None
5263    setattr(modulation.channels[index], attr, freq)

Settings callback: store a parsed frequency (or None) in an entry.

Empty text stores None; otherwise the text is parsed to Hz.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • modulation: Modulation settings to update.
  • index: Index into modulation.channels (0-15).
  • attr: "fm_frequency", "am_frequency" or "ssb_frequency".
Raises:
  • ValueError: If the text is not a valid positive frequency.
Private function def _apply_modulation_channel_name(rsetting, modulation, index, attr):
5265def _apply_modulation_channel_name(rsetting, modulation, index, attr):
5266    """Settings callback: store a memory name in an entry.
5267
5268    Args:
5269        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5270        modulation: Modulation settings to update.
5271        index: Index into ``modulation.channels`` (0-15).
5272        attr: ``"fm_name"``, ``"am_name"`` or ``"ssb_name"``.
5273    """
5274    name = _value_as_string(rsetting.value)
5275    setattr(modulation.channels[index], attr, name)

Settings callback: store a memory name in an entry.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • modulation: Modulation settings to update.
  • index: Index into modulation.channels (0-15).
  • attr: "fm_name", "am_name" or "ssb_name".
Private function def _apply_modulation_channel_int(rsetting, modulation, index, attr):
5277def _apply_modulation_channel_int(rsetting, modulation, index, attr):
5278    """Settings callback: store a non-negative integer in an entry.
5279
5280    Args:
5281        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5282        modulation: Modulation settings to update.
5283        index: Index into ``modulation.channels`` (0-15).
5284        attr: Attribute name on the entry (``"ssb_bandwidth"`` at the call site).
5285    """
5286    value = max(0, _value_as_int(rsetting.value))
5287    setattr(modulation.channels[index], attr, value)

Settings callback: store a non-negative integer in an entry.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • modulation: Modulation settings to update.
  • index: Index into modulation.channels (0-15).
  • attr: Attribute name on the entry ("ssb_bandwidth" at the call site).
Private function def _apply_modulation_channel_beat(rsetting, modulation, index):
5289def _apply_modulation_channel_beat(rsetting, modulation, index):
5290    """Settings callback: store the SSB beat offset, clamped to int16.
5291
5292    Args:
5293        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5294        modulation: Modulation settings to update.
5295        index: Index into ``modulation.channels`` (0-15).
5296    """
5297    value = _value_as_int(rsetting.value)
5298    if value < -32768:
5299        value = -32768
5300    elif value > 32767:
5301        value = 32767
5302    modulation.channels[index].ssb_beat_offset = value

Settings callback: store the SSB beat offset, clamped to int16.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • modulation: Modulation settings to update.
  • index: Index into modulation.channels (0-15).
Private function def _apply_vfo_frequency(rsetting, vfo):
5304def _apply_vfo_frequency(rsetting, vfo):
5305    """Settings callback: set the VFO receive frequency.
5306
5307    An empty field sets ``rx_hz`` to ``None``; :func:`encode_vfo_section`
5308    then keeps the stored digits. A changed frequency also sets
5309    ``freq_band`` as the CPS does: 1 (UHF) from ``_VFO_UHF_FROM_HZ`` (300
5310    MHz) up, else 0 (VHF).
5311
5312    Args:
5313        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5314        vfo: VFO entry to update (``rx_hz``, in Hz).
5315
5316    Returns:
5317        None: Nothing; ``vfo`` is updated in place.
5318
5319    Raises:
5320        RadioError: If the text is not a valid frequency.
5321    """
5322    try:
5323        value = _value_as_string(rsetting.value).strip()
5324    except AttributeError:
5325        value = str(rsetting.value).strip()
5326    if not value:
5327        vfo.rx_hz = None
5328        return
5329    try:
5330        rx_hz = _parse_frequency(value)
5331    except ValueError as exc:
5332        raise errors.RadioError(str(exc)) from exc
5333    if rx_hz != vfo.rx_hz:
5334        vfo.rx_hz = rx_hz
5335        vfo.freq_band = 1 if rx_hz >= _VFO_UHF_FROM_HZ else 0

Settings callback: set the VFO receive frequency.

An empty field sets rx_hz to None; encode_vfo_section() then keeps the stored digits. A changed frequency also sets freq_band as the CPS does: 1 (UHF) from _VFO_UHF_FROM_HZ (300 MHz) up, else 0 (VHF).

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • vfo: VFO entry to update (rx_hz, in Hz).
Returns:

None: Nothing; vfo is updated in place.

Raises:
  • RadioError: If the text is not a valid frequency.
Private function def _apply_vfo_offset(rsetting, vfo):
5337def _apply_vfo_offset(rsetting, vfo):
5338    """Settings callback: set the VFO offset.
5339
5340    An empty field sets ``offset_hz`` to ``None``; :func:`encode_vfo_section`
5341    then keeps the stored digits.
5342
5343    Args:
5344        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5345        vfo: VFO entry to update (``offset_hz``, in Hz).
5346
5347    Returns:
5348        None: Nothing; ``vfo`` is updated in place.
5349
5350    Raises:
5351        RadioError: If the text is not a valid frequency.
5352    """
5353    try:
5354        value = _value_as_string(rsetting.value).strip()
5355    except AttributeError:
5356        value = str(rsetting.value).strip()
5357    if not value:
5358        vfo.offset_hz = None
5359        return
5360    try:
5361        vfo.offset_hz = _parse_frequency(value)
5362    except ValueError as exc:
5363        raise errors.RadioError(str(exc)) from exc

Settings callback: set the VFO offset.

An empty field sets offset_hz to None; encode_vfo_section() then keeps the stored digits.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • vfo: VFO entry to update (offset_hz, in Hz).
Returns:

None: Nothing; vfo is updated in place.

Raises:
  • RadioError: If the text is not a valid frequency.
Private function def _apply_list_choice(rsetting, target, attr, choices):
5365def _apply_list_choice(rsetting, target, attr, choices):
5366    """Settings callback: set one field from a list choice.
5367
5368    Looks the chosen label up in ``choices`` and stores its value in
5369    ``target.<attr>``. A label that is not in ``choices`` (the ``Not set`` or
5370    ``Unknown (<value>)`` option of :func:`_make_list_setting`) leaves the
5371    field unchanged, so a stored value the CPS does not offer survives a
5372    settings apply.
5373
5374    Args:
5375        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5376        target: Object to update (a :class:`VFOSettings` or
5377            :class:`ModulationSettings`).
5378        attr: Name of the field on ``target``.
5379        choices: ``(label, value)`` pairs the setting was built from.
5380
5381    Returns:
5382        None: Nothing; ``target`` is updated in place.
5383    """
5384    chosen = str(rsetting.value)
5385    for text, value in choices:
5386        if text == chosen:
5387            setattr(target, attr, value)
5388            return

Settings callback: set one field from a list choice.

Looks the chosen label up in choices and stores its value in target.<attr>. A label that is not in choices (the Not set or Unknown (<value>) option of _make_list_setting()) leaves the field unchanged, so a stored value the CPS does not offer survives a settings apply.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • target: Object to update (a VFOSettings or ModulationSettings).
  • attr: Name of the field on target.
  • choices: (label, value) pairs the setting was built from.
Returns:

None: Nothing; target is updated in place.

Private function def _apply_vfo_tone(rsetting, vfo, attr):
5391def _apply_vfo_tone(rsetting, vfo, attr):
5392    """Settings callback: set the VFO receive or transmit tone.
5393
5394    The tone is only replaced when the chosen label differs from the current
5395    tone as the CPS writes it (:meth:`ToneSetting.to_display`), so an
5396    unchanged tone keeps its original bytes. ``OFF`` clears the tone, a
5397    label starting with ``D`` (``D023N``) sets that DCS code and polarity,
5398    any other label of ``_VFO_TONE_LABELS`` sets that CTCSS tone in Hz. An
5399    ``Unknown (...)`` label leaves the tone unchanged.
5400
5401    Args:
5402        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5403        vfo: VFO entry to update.
5404        attr: ``"rx_tone"`` or ``"tx_tone"``.
5405
5406    Returns:
5407        None: Nothing; ``vfo`` is updated in place.
5408    """
5409    chosen = str(rsetting.value)
5410    current = getattr(vfo, attr)
5411    if chosen == current.to_display() or chosen not in _VFO_TONE_LABELS:
5412        return
5413    if chosen == 'OFF':
5414        tone = ToneSetting.off()
5415    elif chosen.startswith('D'):
5416        tone = ToneSetting.dcs(int(chosen[1:4]), chosen[4])
5417    else:
5418        tone = ToneSetting.ctcss(float(chosen))
5419    setattr(vfo, attr, tone)

Settings callback: set the VFO receive or transmit tone.

The tone is only replaced when the chosen label differs from the current tone as the CPS writes it (ToneSetting.to_display()), so an unchanged tone keeps its original bytes. OFF clears the tone, a label starting with D (D023N) sets that DCS code and polarity, any other label of _VFO_TONE_LABELS sets that CTCSS tone in Hz. An Unknown (...) label leaves the tone unchanged.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • vfo: VFO entry to update.
  • attr: "rx_tone" or "tx_tone".
Returns:

None: Nothing; vfo is updated in place.

Private function def _build_setting_value(meta, current):
5421def _build_setting_value(meta, current):
5422    """Create the CHIRP value object described by a UI table entry.
5423
5424    Args:
5425        meta: Entry from ``_FUNCTION_UI`` or ``_APRS_UI`` with ``type`` and
5426            its parameters (``min``/``max``, ``choices`` or ``length``).
5427        current: Current value, or ``None``.
5428
5429    Returns:
5430        RadioSettingValue: Boolean, integer, list or string value.
5431
5432    Raises:
5433        SettingsError: If ``meta['type']`` is unknown.
5434    """
5435    kind = meta['type']
5436    if kind == 'bool':
5437        return RadioSettingValueBoolean(bool(current))
5438    if kind == 'int':
5439        minimum = meta.get('min', 0)
5440        maximum = meta.get('max', minimum)
5441        active = minimum if current is None else int(current)
5442        return RadioSettingValueInteger(minimum, maximum, active)
5443    if kind == 'enum':
5444        choices = meta['choices']
5445        labels = [label for label, _ in choices]
5446        values = [value for _, value in choices]
5447        active = values[0]
5448        if current in values:
5449            active = current
5450        index = values.index(active)
5451        return RadioSettingValueList(labels, current_index=index)
5452    if kind == 'string':
5453        length = meta['length']
5454        return RadioSettingValueString(0, length, (current or ''), autopad=False)
5455    raise SettingsError(f"Unsupported setting type: {kind}")

Create the CHIRP value object described by a UI table entry.

Arguments:
  • meta: Entry from _FUNCTION_UI or _APRS_UI with type and its parameters (min/max, choices or length).
  • current: Current value, or None.
Returns:

RadioSettingValue: Boolean, integer, list or string value.

Raises:
  • SettingsError: If meta['type'] is unknown.
Private function def _value_as_bool(value_obj):
5457def _value_as_bool(value_obj):
5458    """Read a CHIRP value object (or plain value) as ``bool``.
5459
5460    Args:
5461        value_obj: A ``RadioSettingValue*`` object (``get_value`` is used) or a plain value.
5462
5463    Returns:
5464        bool: Truth value of the underlying value.
5465    """
5466    if hasattr(value_obj, 'get_value'):
5467        return bool(value_obj.get_value())
5468    return bool(value_obj)

Read a CHIRP value object (or plain value) as bool.

Arguments:
  • value_obj: A RadioSettingValue* object (get_value is used) or a plain value.
Returns:

bool: Truth value of the underlying value.

Private function def _value_as_int(value_obj, default=0):
5470def _value_as_int(value_obj, default=0):
5471    """Read a CHIRP value object (or plain value) as ``int``.
5472
5473    Returns ``default`` if the value cannot be converted.
5474
5475    Args:
5476        value_obj: A ``RadioSettingValue*`` object (``get_value`` is used) or a plain value.
5477        default: Value returned when the conversion raises.
5478
5479    Returns:
5480        int: ``int()`` of the underlying value, or ``default``.
5481    """
5482    try:
5483        if hasattr(value_obj, 'get_value'):
5484            raw = value_obj.get_value()
5485        else:
5486            raw = value_obj
5487        return int(raw)
5488    # Any unreadable value falls back to the default.
5489    except Exception:  # pylint: disable=broad-exception-caught
5490        return default

Read a CHIRP value object (or plain value) as int.

Returns default if the value cannot be converted.

Arguments:
  • value_obj: A RadioSettingValue* object (get_value is used) or a plain value.
  • default: Value returned when the conversion raises.
Returns:

int: int() of the underlying value, or default.

Private function def _value_as_index(value_obj, choices):
5492def _value_as_index(value_obj, choices):
5493    """Read a list value as an index into ``choices``.
5494
5495    Tries ``int(value)`` first, then looks the label up in ``choices``.
5496    Falls back to 0.
5497
5498    Args:
5499        value_obj: A list ``RadioSettingValue`` object or a plain value.
5500        choices: Sequence of ``(label, value)`` pairs.
5501
5502    Returns:
5503        int: ``int(value_obj)`` if that works (not range-checked), else the
5504        position of the label in ``choices``, else 0.
5505    """
5506    try:
5507        return int(value_obj)
5508    # Not an index: fall back to matching the label text below.
5509    except Exception:  # pylint: disable=broad-exception-caught
5510        if hasattr(value_obj, 'get_value'):
5511            raw = value_obj.get_value()
5512        else:
5513            raw = value_obj
5514        labels = [label for label, _ in choices]
5515        try:
5516            return labels.index(raw)
5517        except ValueError:
5518            return 0

Read a list value as an index into choices.

Tries int(value) first, then looks the label up in choices. Falls back to 0.

Arguments:
  • value_obj: A list RadioSettingValue object or a plain value.
  • choices: Sequence of (label, value) pairs.
Returns:

int: int(value_obj) if that works (not range-checked), else the position of the label in choices, else 0.

Private function def _value_as_string(value_obj):
5520def _value_as_string(value_obj):
5521    """Read a CHIRP value object (or plain value) as ``str``.
5522
5523    Args:
5524        value_obj: A ``RadioSettingValue*`` object (``get_value`` is used) or a plain value.
5525
5526    Returns:
5527        str: ``str()`` of the underlying value.
5528    """
5529    if hasattr(value_obj, 'get_value'):
5530        raw = value_obj.get_value()
5531    else:
5532        raw = value_obj
5533    return str(raw)

Read a CHIRP value object (or plain value) as str.

Arguments:
  • value_obj: A RadioSettingValue* object (get_value is used) or a plain value.
Returns:

str: str() of the underlying value.

Private function def _create_function_setting(func_settings, key, meta):
5535def _create_function_setting(func_settings, key, meta):
5536    """Create one function ``RadioSetting`` from its UI table entry.
5537
5538    Args:
5539        func_settings: Function settings that hold the current value and are
5540            updated on apply.
5541        key: Setting name, a key of ``_FUNCTION_UI``.
5542        meta: The ``_FUNCTION_UI`` entry for ``key`` (label, type, parameters;
5543            ``'volatile': True`` marks the setting volatile).
5544
5545    Returns:
5546        RadioSetting | None: The setting, or ``None`` for an unknown key.
5547    """
5548    try:
5549        current = get_function_value(func_settings, key)
5550    except KeyError:
5551        LOG.debug('Skipping unknown function key %s', key)
5552        return None
5553    value_obj = _build_setting_value(meta, current)
5554    rsetting = RadioSetting(f'function.{key}', meta['label'], value_obj)
5555    rsetting.set_apply_callback(_apply_function_setting, func_settings, key, meta)
5556    # A volatile setting makes CHIRP's settings editor ask for a refresh
5557    # after it is changed; together with has_dynamic_subdevices CHIRP then
5558    # rebuilds the whole editor (memory tabs included) from the image.
5559    # The stand-in RadioSetting and old CHIRP versions lack set_volatile.
5560    set_volatile = getattr(rsetting, 'set_volatile', None)
5561    if meta.get('volatile') and set_volatile is not None:
5562        set_volatile(True)
5563    return rsetting

Create one function RadioSetting from its UI table entry.

Arguments:
  • func_settings: Function settings that hold the current value and are updated on apply.
  • key: Setting name, a key of _FUNCTION_UI.
  • meta: The _FUNCTION_UI entry for key (label, type, parameters; 'volatile': True marks the setting volatile).
Returns:

RadioSetting | None: The setting, or None for an unknown key.

Private function def _create_aprs_setting(aprs_settings, key, meta):
5565def _create_aprs_setting(aprs_settings, key, meta):
5566    """Create one APRS ``RadioSetting`` from its UI table entry.
5567
5568    Args:
5569        aprs_settings: APRS settings that hold the current value and are
5570            updated on apply.
5571        key: Setting name, a key of ``_APRS_UI``.
5572        meta: The ``_APRS_UI`` entry for ``key`` (label, type, parameters).
5573
5574    Returns:
5575        RadioSetting | None: The setting, or ``None`` for an unknown key.
5576    """
5577    try:
5578        current = get_aprs_value(aprs_settings, key)
5579    except KeyError:
5580        LOG.debug('Skipping unknown APRS key %s', key)
5581        return None
5582    value_obj = _build_setting_value(meta, current)
5583    rsetting = RadioSetting(f'aprs.{key}', meta['label'], value_obj)
5584    rsetting.set_apply_callback(_apply_aprs_setting, aprs_settings, key, meta)
5585    return rsetting

Create one APRS RadioSetting from its UI table entry.

Arguments:
  • aprs_settings: APRS settings that hold the current value and are updated on apply.
  • key: Setting name, a key of _APRS_UI.
  • meta: The _APRS_UI entry for key (label, type, parameters).
Returns:

RadioSetting | None: The setting, or None for an unknown key.

Private function def _build_function_group(func_settings):
5587def _build_function_group(func_settings):
5588    """Build the *Function Settings* group from ``_FUNCTION_UI``.
5589
5590    Args:
5591        func_settings: Function settings of the image.
5592
5593    Returns:
5594        RadioSettingGroup: One setting per known key of ``_FUNCTION_UI``.
5595    """
5596    group = RadioSettingGroup('function', 'Function Settings')
5597    for key, meta in _FUNCTION_UI.items():
5598        setting = _create_function_setting(func_settings, key, meta)
5599        if setting is not None:
5600            group.append(setting)
5601    return group

Build the Function Settings group from _FUNCTION_UI.

Arguments:
  • func_settings: Function settings of the image.
Returns:

RadioSettingGroup: One setting per known key of _FUNCTION_UI.

Private function def _build_aprs_group(aprs_settings):
5603def _build_aprs_group(aprs_settings):
5604    """Build the *APRS Settings* group from ``_APRS_UI``.
5605
5606    Args:
5607        aprs_settings: APRS settings of the image.
5608
5609    Returns:
5610        RadioSettingGroup: One setting per known key of ``_APRS_UI``.
5611    """
5612    group = RadioSettingGroup('aprs', 'APRS Settings')
5613    for key, meta in _APRS_UI.items():
5614        setting = _create_aprs_setting(aprs_settings, key, meta)
5615        if setting is not None:
5616            group.append(setting)
5617    return group

Build the APRS Settings group from _APRS_UI.

Arguments:
  • aprs_settings: APRS settings of the image.
Returns:

RadioSettingGroup: One setting per known key of _APRS_UI.

Private function def _build_dtmf_group(dtmf_settings):
5619def _build_dtmf_group(dtmf_settings):
5620    """Build the *DTMF Settings* group.
5621
5622    Shows the own ID, the PTT ID mode and the first ``_DTMF_GROUP_LIMIT``
5623    code groups.
5624
5625    Args:
5626        dtmf_settings: DTMF settings of the image.
5627
5628    Returns:
5629        RadioSettingGroup: The ID, mode and code-group settings.
5630    """
5631    group = RadioSettingGroup('dtmf', 'DTMF Settings')
5632    current_id = get_dtmf_current_id(dtmf_settings)
5633    value_id = RadioSettingValueString(0, _DTMF_ID_MAXLEN, current_id or '', autopad=False)
5634    rset_id = RadioSetting('dtmf.current_id', 'Current ID', value_id)
5635    rset_id.set_apply_callback(_apply_dtmf_id, dtmf_settings)
5636    group.append(rset_id)
5637    mode = get_dtmf_ptt_mode(dtmf_settings)
5638    labels = [label for label, _ in _DTMF_MODE_CHOICES]
5639    values = [value for _, value in _DTMF_MODE_CHOICES]
5640    index = values.index(mode) if mode in values else 0
5641    mode_value = RadioSettingValueList(labels, current_index=index)
5642    rset_mode = RadioSetting('dtmf.ptt_mode', 'PTT ID Mode', mode_value)
5643    rset_mode.set_apply_callback(_apply_dtmf_mode, dtmf_settings)
5644    group.append(rset_mode)
5645    for idx in range(_DTMF_GROUP_LIMIT):
5646        try:
5647            code = get_dtmf_code_group(dtmf_settings, idx)
5648        except IndexError:
5649            code = ''
5650        code_value = RadioSettingValueString(0, _DTMF_CODE_MAXLEN, code or '', autopad=False)
5651        rset_code = RadioSetting(f'dtmf.code_group_{idx + 1}', f'Code Group {idx + 1}', code_value)
5652        rset_code.set_apply_callback(_apply_dtmf_group, dtmf_settings, idx)
5653        group.append(rset_code)
5654    return group

Build the DTMF Settings group.

Shows the own ID, the PTT ID mode and the first _DTMF_GROUP_LIMIT code groups.

Arguments:
  • dtmf_settings: DTMF settings of the image.
Returns:

RadioSettingGroup: The ID, mode and code-group settings.

Private function def _apply_function_setting(rsetting, func_settings, key, meta):
5656def _apply_function_setting(rsetting, func_settings, key, meta):
5657    """Settings callback: validate and store a function setting.
5658
5659    Args:
5660        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5661        func_settings: Function settings to update.
5662        key: Setting name, a key of ``_FUNCTION_UI``.
5663        meta: The ``_FUNCTION_UI`` entry for ``key``; ``type`` selects the conversion.
5664
5665    Raises:
5666        RadioError: If the value is not allowed.
5667    """
5668    try:
5669        kind = meta['type']
5670        if kind == 'bool':
5671            set_function_value(func_settings, key, _value_as_bool(rsetting.value))
5672        elif kind == 'int':
5673            set_function_value(func_settings, key, _value_as_int(rsetting.value))
5674        elif kind == 'enum':
5675            index = _value_as_index(rsetting.value, meta['choices'])
5676            set_function_value(func_settings, key, meta['choices'][index][1])
5677        else:
5678            raise SettingsError(f"Unsupported function setting type {kind}")
5679    except (SettingsError, KeyError, IndexError, ValueError) as exc:
5680        raise errors.RadioError(str(exc)) from exc

Settings callback: validate and store a function setting.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • func_settings: Function settings to update.
  • key: Setting name, a key of _FUNCTION_UI.
  • meta: The _FUNCTION_UI entry for key; type selects the conversion.
Raises:
  • RadioError: If the value is not allowed.
Private function def _apply_aprs_setting(rsetting, aprs_settings, key, meta):
5682def _apply_aprs_setting(rsetting, aprs_settings, key, meta):
5683    """Settings callback: validate and store an APRS setting.
5684
5685    Args:
5686        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5687        aprs_settings: APRS settings to update.
5688        key: Setting name, a key of ``_APRS_UI``.
5689        meta: The ``_APRS_UI`` entry for ``key``; ``type`` selects the conversion.
5690
5691    Raises:
5692        RadioError: If the value is not allowed.
5693    """
5694    try:
5695        kind = meta['type']
5696        if kind == 'bool':
5697            set_aprs_value(aprs_settings, key, _value_as_bool(rsetting.value))
5698        elif kind == 'int':
5699            set_aprs_value(aprs_settings, key, _value_as_int(rsetting.value))
5700        elif kind == 'enum':
5701            index = _value_as_index(rsetting.value, meta['choices'])
5702            set_aprs_value(aprs_settings, key, meta['choices'][index][1])
5703        elif kind == 'string':
5704            set_aprs_value(aprs_settings, key, _value_as_string(rsetting.value).strip())
5705        else:
5706            raise SettingsError(f"Unsupported APRS setting type {kind}")
5707    except (SettingsError, KeyError, IndexError, ValueError) as exc:
5708        raise errors.RadioError(str(exc)) from exc

Settings callback: validate and store an APRS setting.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • aprs_settings: APRS settings to update.
  • key: Setting name, a key of _APRS_UI.
  • meta: The _APRS_UI entry for key; type selects the conversion.
Raises:
  • RadioError: If the value is not allowed.
Private function def _apply_dtmf_id(rsetting, dtmf_settings):
5710def _apply_dtmf_id(rsetting, dtmf_settings):
5711    """Settings callback: store the own DTMF ID.
5712
5713    Args:
5714        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5715        dtmf_settings: DTMF settings to update.
5716
5717    Raises:
5718        RadioError: If the ID is invalid.
5719    """
5720    try:
5721        set_dtmf_current_id(dtmf_settings, _value_as_string(rsetting.value).strip())
5722    except SettingsError as exc:
5723        raise errors.RadioError(str(exc)) from exc

Settings callback: store the own DTMF ID.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • dtmf_settings: DTMF settings to update.
Raises:
  • RadioError: If the ID is invalid.
Private function def _apply_dtmf_mode(rsetting, dtmf_settings):
5725def _apply_dtmf_mode(rsetting, dtmf_settings):
5726    """Settings callback: store the PTT ID mode.
5727
5728    Args:
5729        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5730        dtmf_settings: DTMF settings to update.
5731
5732    Raises:
5733        RadioError: If the mode is invalid.
5734    """
5735    try:
5736        index = _value_as_index(rsetting.value, _DTMF_MODE_CHOICES)
5737        set_dtmf_ptt_mode(dtmf_settings, _DTMF_MODE_CHOICES[index][1])
5738    except SettingsError as exc:
5739        raise errors.RadioError(str(exc)) from exc

Settings callback: store the PTT ID mode.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • dtmf_settings: DTMF settings to update.
Raises:
  • RadioError: If the mode is invalid.
Private function def _apply_dtmf_group(rsetting, dtmf_settings, index):
5741def _apply_dtmf_group(rsetting, dtmf_settings, index):
5742    """Settings callback: store one DTMF code group.
5743
5744    Args:
5745        rsetting: The ``RadioSetting`` being applied; its ``value`` is read.
5746        dtmf_settings: DTMF settings to update.
5747        index: Code group number, 0-based (0 to ``_DTMF_GROUP_LIMIT - 1``).
5748
5749    Raises:
5750        RadioError: If the code is invalid.
5751    """
5752    try:
5753        set_dtmf_code_group(dtmf_settings, index, _value_as_string(rsetting.value).strip())
5754    except (SettingsError, IndexError) as exc:
5755        raise errors.RadioError(str(exc)) from exc

Settings callback: store one DTMF code group.

Arguments:
  • rsetting: The RadioSetting being applied; its value is read.
  • dtmf_settings: DTMF settings to update.
  • index: Code group number, 0-based (0 to _DTMF_GROUP_LIMIT - 1).
Raises:
  • RadioError: If the code is invalid.
Private function def _build_write_plan( payload: bytes, *, write_zone_names: bool = True, channel_bytes: int = 31744, write_aprs: bool = True) -> Tuple[List[CloneSegment], bytes]:
5793def _build_write_plan(
5794    payload: bytes,
5795    *,
5796    write_zone_names: bool = True,
5797    channel_bytes: int = 0x7C00,
5798    write_aprs: bool = True,
5799) -> Tuple[List["CloneSegment"], bytes]:
5800    """Split the layout-ordered payload into the segments/data to write.
5801
5802    ``write_zone_names=False`` skips 0xC000 (the image's zone names were not
5803    read from there). ``channel_bytes`` caps the channel write;
5804    :meth:`RT950ProRadio._write_options` passes 0x7800 (channels 1-960)
5805    unless channels 961-990 changed.
5806
5807    Args:
5808        payload: Complete clone payload in ``DEFAULT_SEGMENTS`` order (as built
5809            by :func:`_build_clone_payload`).
5810        write_zone_names: Include the zone-name segment (0xC000).
5811        channel_bytes: Maximum number of channel-segment bytes to write from
5812            address 0x0000; the ``_WRITE_PLAN`` limit of 0x7C00 still applies.
5813        write_aprs: Include the APRS segment (write command 0x58).
5814
5815    Returns:
5816        tuple[list[CloneSegment], bytes]: The segments to write, in
5817        ``_WRITE_PLAN`` order, and their data concatenated in the same order.
5818    """
5819    offsets = []
5820    cursor = 0
5821    for seg in DEFAULT_SEGMENTS:
5822        offsets.append(cursor)
5823        cursor += seg.length
5824    segments: List[CloneSegment] = []
5825    data = bytearray()
5826    for index, length in _WRITE_PLAN:
5827        if index == 7 and not write_zone_names:
5828            continue
5829        if index == 6 and not write_aprs:
5830            continue
5831        seg = DEFAULT_SEGMENTS[index]
5832        length = seg.length if length is None else length
5833        if index == 0:
5834            length = min(length, channel_bytes)
5835        segments.append(CloneSegment(seg.read_command, seg.write_command, seg.start, length))
5836        data.extend(payload[offsets[index] : offsets[index] + length])
5837    return segments, bytes(data)

Split the layout-ordered payload into the segments/data to write.

write_zone_names=False skips 0xC000 (the image's zone names were not read from there). channel_bytes caps the channel write; RT950ProRadio._write_options() passes 0x7800 (channels 1-960) unless channels 961-990 changed.

Arguments:
  • payload: Complete clone payload in DEFAULT_SEGMENTS order (as built by _build_clone_payload()).
  • write_zone_names: Include the zone-name segment (0xC000).
  • channel_bytes: Maximum number of channel-segment bytes to write from address 0x0000; the _WRITE_PLAN limit of 0x7C00 still applies.
  • write_aprs: Include the APRS segment (write command 0x58).
Returns:

tuple[list[CloneSegment], bytes]: The segments to write, in _WRITE_PLAN order, and their data concatenated in the same order.

Private function def _build_clone_payload(image: RadioImage) -> bytes:
5840def _build_clone_payload(image: RadioImage) -> bytes:
5841    """Serialise ``image`` into the byte order of ``DEFAULT_SEGMENTS``.
5842
5843    Args:
5844        image: The parsed image to serialise.
5845
5846    Returns:
5847        bytes: ``_SEGMENT_LENGTH`` bytes.
5848
5849    Raises:
5850        ValueError: If ``image.to_bytes()`` fails (e.g. a tone that cannot be
5851            encoded) or the result has the wrong length.
5852    """
5853    buffer = image.to_bytes()
5854    payload = bytearray()
5855    payload.extend(buffer[:CHANNEL_SECTION_BYTES])
5856    cursor = CHANNEL_SECTION_BYTES
5857    for segment in DEFAULT_SEGMENTS[1:]:
5858        end = cursor + segment.length
5859        payload.extend(buffer[cursor:end])
5860        cursor = end
5861    if len(payload) != _SEGMENT_LENGTH:
5862        raise ValueError(
5863            f"Composed payload length {len(payload)} does not match expected {_SEGMENT_LENGTH}"
5864        )
5865    return bytes(payload)

Serialise image into the byte order of DEFAULT_SEGMENTS.

Arguments:
  • image: The parsed image to serialise.
Returns:

bytes: _SEGMENT_LENGTH bytes.

Raises:
  • ValueError: If image.to_bytes() fails (e.g. a tone that cannot be encoded) or the result has the wrong length.
Private constant _SEGMENT_LENGTH = 35456

Size in bytes of a complete clone image (all DEFAULT_SEGMENTS).

Private constant _CHIRP_POWER_LEVELS = ['Low', 'Medium', 'High']

Power levels offered in CHIRP, lowest first.

The wattages are nominal values for display; the radio stores only the level.

Private constant _POWER_ENUM_TO_CHIRP = {<PowerLevel.LOW: 2>: 'Low', <PowerLevel.MEDIUM: 1>: 'Medium', <PowerLevel.HIGH: 0>: 'High'}

Maps PowerLevel to the CHIRP power level.

Private constant _POWER_LABEL_TO_ENUM = {'LOW': <PowerLevel.LOW: 2>, 'MEDIUM': <PowerLevel.MEDIUM: 1>, 'HIGH': <PowerLevel.HIGH: 0>}

Maps an upper-case CHIRP power label ("HIGH") to PowerLevel.

Private constant _CHANNEL_DIVIDE_CHOICES = [('Zone CH Mode', 0), ('All CH Mode', 1)]

Labels (as in the CPS list Channel Divide, in its order) and stored values of the function setting divide_channel.

Private constant _FUNCTION_UI = {'sql': {'label': 'Squelch Level', 'type': 'int', 'min': 0, 'max': 9}, 'save_mode': {'label': 'Battery Save', 'type': 'int', 'min': 0, 'max': 3}, 'vox': {'label': 'VOX Gain', 'type': 'int', 'min': 0, 'max': 9}, 'vox_delay': {'label': 'VOX Delay', 'type': 'int', 'min': 0, 'max': 9}, 'auto_backlight': {'label': 'Auto Backlight', 'type': 'int', 'min': 0, 'max': 9}, 'tot': {'label': 'Time-out Timer', 'type': 'int', 'min': 0, 'max': 9}, 'beep_prompt': {'label': 'Key Beep', 'type': 'bool'}, 'voice_prompt': {'label': 'Voice Prompt', 'type': 'enum', 'choices': [('Off', 0), ('English', 1), ('Chinese', 2)]}, 'language': {'label': 'Menu Language', 'type': 'enum', 'choices': [('English', 0), ('Chinese', 1), ('Other', 2)]}, 'dtmf_mode': {'label': 'DTMF Mode', 'type': 'enum', 'choices': [('Off', 0), ('DT-ST', 1), ('ANI-ID', 2), ('DTMF', 3)]}, 'scan_mode': {'label': 'Scan Mode', 'type': 'enum', 'choices': [('Time', 0), ('Carrier', 1), ('Search', 2)]}, 'ptt_id': {'label': 'PTT ID', 'type': 'enum', 'choices': [('Off', 0), ('BOT', 1), ('EOT', 2), ('Both', 3)]}, 'display_mode_a': {'label': 'Display Mode A', 'type': 'enum', 'choices': [('Channel', 0), ('Frequency', 1), ('Name', 2)]}, 'display_mode_b': {'label': 'Display Mode B', 'type': 'enum', 'choices': [('Channel', 0), ('Frequency', 1), ('Name', 2)]}, 'display_mode_c': {'label': 'Display Mode C', 'type': 'enum', 'choices': [('Channel', 0), ('Frequency', 1), ('Name', 2)]}, 'auto_key_lock': {'label': 'Auto Key Lock', 'type': 'bool'}, 'alarm_mode': {'label': 'Alarm Mode', 'type': 'enum', 'choices': [('Local', 0), ('Remote', 1), ('Tone', 2)]}, 'alarm_sound': {'label': 'Alarm Sound', 'type': 'enum', 'choices': [('Off', 0), ('Type 1', 1), ('Type 2', 2)]}, 'tail_noise_clear': {'label': 'Tail Noise Clear', 'type': 'bool'}, 'pass_repeater_noise_clear': {'label': 'Repeater Noise Clear', 'type': 'bool'}, 'sound_tx_end': {'label': 'Roger Beep', 'type': 'bool'}, 'fm_radio': {'label': 'FM Radio', 'type': 'bool'}, 'lock_keyboard': {'label': 'Keypad Lock', 'type': 'bool'}, 'power_on_message': {'label': 'Power-on Message', 'type': 'enum', 'choices': [('Full', 0), ('Message', 1), ('Voltage', 2)]}, 'bt_write_switch': {'label': 'Bluetooth Enable', 'type': 'bool'}, 'vox_switch': {'label': 'VOX Enable', 'type': 'bool'}, 'divide_channel': {'label': 'Channel Divide', 'type': 'enum', 'choices': [('Zone CH Mode', 0), ('All CH Mode', 1)], 'volatile': True}}

Function settings shown in CHIRP: key to label, type and range or choices. Keys not listed here are kept but not shown.

An entry with 'volatile': True is marked volatile in CHIRP (see _create_function_setting()): changing it makes CHIRP rebuild the editor, so the memory tabs follow the new value at once.

Private constant _APRS_UI = {'aprs_switch': {'label': 'APRS Enable', 'type': 'bool'}, 'gps_switch': {'label': 'GPS Enable', 'type': 'bool'}, 'call_sign': {'label': 'Callsign', 'type': 'string', 'length': 6}, 'ssid': {'label': 'SSID', 'type': 'enum', 'choices': [('0', 0), ('1', 1), ('2', 2), ('3', 3), ('4', 4), ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9), ('10', 10), ('11', 11), ('12', 12), ('13', 13), ('14', 14), ('15', 15)]}, 'aprs_priority': {'label': 'Priority', 'type': 'enum', 'choices': [('Low', 0), ('Normal', 1), ('High', 2)]}, 'data_tx_delay': {'label': 'Data TX Delay', 'type': 'int', 'min': 0, 'max': 9}, 'aprs_decode_prompt_tone': {'label': 'RX Prompt Tone', 'type': 'bool'}, 'aprs_rx_auto_popup': {'label': 'RX Auto Popup', 'type': 'bool'}, 'aprs_forward_channel': {'label': 'Forward Channel', 'type': 'enum', 'choices': [('0', 0), ('1', 1), ('2', 2), ('3', 3), ('4', 4), ('5', 5), ('6', 6), ('7', 7), ('8', 8), ('9', 9), ('10', 10), ('11', 11), ('12', 12), ('13', 13), ('14', 14), ('15', 15)]}, 'aprs_wait_forward': {'label': 'Forward Wait', 'type': 'int', 'min': 0, 'max': 9}, 'custom_messages': {'label': 'Custom Message', 'type': 'string', 'length': 40}}

APRS settings shown in CHIRP: key to label, type and range or choices. Keys not listed here are kept but not shown.

Private constant _DTMF_GROUP_LIMIT = 5

Number of DTMF code groups shown in CHIRP (the radio has 22).

Private constant _DTMF_ID_MAXLEN = 5

Maximum length of the own DTMF ID.

Private constant _DTMF_CODE_MAXLEN = 6

Maximum length of a DTMF code group.

Private constant _DTMF_MODE_CHOICES = [('Off', 0), ('BOT', 1), ('EOT', 2), ('Both', 3)]

PTT ID mode labels and stored values.

Private constant _VFO_LABELS = ['A', 'B', 'C']

Letters of the three VFOs; the groups are named VFO-A to VFO-C as in the CPS.

Private constant _VFO_OFFSET_CHOICES = [('None', 0), ('Plus', 1), ('Minus', 2)]

Offset Dir labels of the CPS and the stored values (byte 14, bits 5-4). Stored value 3 is not offered and is shown as unknown.

Private constant _VFO_BANDWIDTH_CHOICES = [('Wide', <Bandwidth.WIDE: 1>), ('Narrow', <Bandwidth.NARROW: 0>)]

Bandwidth labels of the CPS and Bandwidth values.

Private constant _VFO_MODULATION_CHOICES = [('FM', <Modulation.FM: 0>), ('AM', <Modulation.AM: 1>)]

RxModulation labels of the CPS and Modulation values.

Private constant _VFO_POWER_CHOICES = [('High', <PowerLevel.HIGH: 0>), ('Middle', <PowerLevel.MEDIUM: 1>), ('Low', <PowerLevel.LOW: 2>)]

Tx Power labels of the CPS and PowerLevel values (stored 0, 1, 2).

Private constant _VFO_ENCRYPTION_CHOICES = [('OFF', 0), ('Encryption 1', 1), ('Encryption 2', 2), ('Encryption 3', 3)]

Encryption labels of the CPS and the stored values (byte 17, bits 5-4).

Private constant _VFO_BAND_CHOICES = [('VHF', 0), ('UHF', 1)]

Freq Band labels of the CPS and the stored values (byte 18, low nibble).

Confirmed on a radio: 439.4 MHz stores 1 (UHF), 145.025 MHz and 27.025 MHz store 0 (VHF). The CPS shows the field read-only and derives it from Rx Freq; so does the driver (see _VFO_UHF_FROM_HZ).

Private constant _VFO_UHF_FROM_HZ = 300000000

Lowest Rx Freq the CPS shows as UHF: 299.99999 MHz is VHF, 300.00000 MHz UHF (measured in the CPS VFO Mode screen).

Private constant _VFO_STEP_CHOICES = [('2.5KHz', 0), ('5.0KHz', 1), ('6.25KHz', 2), ('8.33KHz', 3), ('10.0KHz', 4), ('12.5KHz', 5), ('20.0KHz', 6), ('25.0KHz', 7), ('50.0KHz', 8), ('100.0KHz', 9)]

Step Freq labels of the CPS and the stored index (byte 19, low nibble).

Confirmed on a radio: 100.0KHz stores 9, 25.0KHz 7, 12.5KHz 5.

Private constant _VFO_SCRAMBLE_CHOICES = [('OFF', 0), ('Scramble 1', 1), ('Scramble 2', 2), ('Scramble 3', 3), ('Scramble 4', 4), ('Scramble 5', 5), ('Scramble 6', 6), ('Scramble 7', 7), ('Scramble 8', 8)]

Scramble labels of the CPS and the stored values 0-8 (byte 16, high nibble).

Private constant _VFO_SIGNALLING_CHOICES = [('1', 0), ('2', 1), ('3', 2), ('4', 3), ('5', 4), ('6', 5), ('7', 6), ('8', 7), ('9', 8), ('10', 9), ('11', 10), ('12', 11), ('13', 12), ('14', 13), ('15', 14)]

Signalling labels of the CPS (1-15) and the stored values 0-14.

The CPS stores the shown number minus one (byte 14, low nibble); confirmed on a radio: 15 stores 14, 1 stores 0. A stored 15 is not offered and shows as Unknown (15), the stored value.

Private constant _VFO_BUSY_LOCKOUT_CHOICES = [('OFF', False), ('ON', True)]

Busy Lockout labels of the CPS and the flag value (byte 13, bit 0).

Private constant _CTCSS_TONES = (67.0, 69.3, 71.9, 74.4, 77.0, 79.7, 82.5, 85.4, 88.5, 91.5, 94.8, 97.4, 100.0, 103.5, 107.2, 110.9, 114.8, 118.8, 123.0, 127.3, 131.8, 136.5, 141.3, 146.2, 151.4, 156.7, 159.8, 162.2, 165.5, 167.9, 171.3, 173.8, 177.3, 179.9, 183.5, 186.2, 189.9, 192.8, 196.6, 199.5, 203.5, 206.5, 210.7, 218.1, 225.7, 229.1, 233.6, 241.8, 250.3, 254.1)

The 50 standard CTCSS tones in Hz, offered for the VFO QT/DQT fields.

The CPS list starts with 67.0 and ends its CTCSS part with 254.1, like this one; the tones in between were not compared one by one.

Private constant _VFO_TONE_LABELS = ['OFF', '67.0', '69.3', '71.9', '74.4', '77.0', '79.7', '82.5', '85.4', '88.5', '91.5', '94.8', '97.4', '100.0', '103.5', '107.2', '110.9', '114.8', '118.8', '123.0', '127.3', '131.8', '136.5', '141.3', '146.2', '151.4', '156.7', '159.8', '162.2', '165.5', '167.9', '171.3', '173.8', '177.3', '179.9', '183.5', '186.2', '189.9', '192.8', '196.6', '199.5', '203.5', '206.5', '210.7', '218.1', '225.7', '229.1', '233.6', '241.8', '250.3', '254.1', 'D023N', 'D025N', 'D026N', 'D031N', 'D032N', 'D036N', 'D043N', 'D047N', 'D051N', 'D053N', 'D054N', 'D065N', 'D071N', 'D072N', 'D073N', 'D074N', 'D114N', 'D115N', 'D116N', 'D122N', 'D125N', 'D131N', 'D132N', 'D134N', 'D143N', 'D145N', 'D152N', 'D155N', 'D156N', 'D162N', 'D165N', 'D172N', 'D174N', 'D205N', 'D212N', 'D223N', 'D225N', 'D226N', 'D243N', 'D244N', 'D245N', 'D246N', 'D251N', 'D252N', 'D255N', 'D261N', 'D263N', 'D265N', 'D266N', 'D271N', 'D274N', 'D306N', 'D311N', 'D315N', 'D325N', 'D331N', 'D332N', 'D343N', 'D346N', 'D351N', 'D356N', 'D364N', 'D365N', 'D371N', 'D411N', 'D412N', 'D413N', 'D423N', 'D431N', 'D432N', 'D445N', 'D446N', 'D452N', 'D454N', 'D455N', 'D462N', 'D464N', 'D465N', 'D466N', 'D503N', 'D506N', 'D516N', 'D523N', 'D526N', 'D532N', 'D546N', 'D565N', 'D606N', 'D612N', 'D624N', 'D627N', 'D631N', 'D632N', 'D645N', 'D654N', 'D662N', 'D664N', 'D703N', 'D712N', 'D723N', 'D731N', 'D732N', 'D734N', 'D743N', 'D754N', 'D023I', 'D025I', 'D026I', 'D031I', 'D032I', 'D036I', 'D043I', 'D047I', 'D051I', 'D053I', 'D054I', 'D065I', 'D071I', 'D072I', 'D073I', 'D074I', 'D114I', 'D115I', 'D116I', 'D122I', 'D125I', 'D131I', 'D132I', 'D134I', 'D143I', 'D145I', 'D152I', 'D155I', 'D156I', 'D162I', 'D165I', 'D172I', 'D174I', 'D205I', 'D212I', 'D223I', 'D225I', 'D226I', 'D243I', 'D244I', 'D245I', 'D246I', 'D251I', 'D252I', 'D255I', 'D261I', 'D263I', 'D265I', 'D266I', 'D271I', 'D274I', 'D306I', 'D311I', 'D315I', 'D325I', 'D331I', 'D332I', 'D343I', 'D346I', 'D351I', 'D356I', 'D364I', 'D365I', 'D371I', 'D411I', 'D412I', 'D413I', 'D423I', 'D431I', 'D432I', 'D445I', 'D446I', 'D452I', 'D454I', 'D455I', 'D462I', 'D464I', 'D465I', 'D466I', 'D503I', 'D506I', 'D516I', 'D523I', 'D526I', 'D532I', 'D546I', 'D565I', 'D606I', 'D612I', 'D624I', 'D627I', 'D631I', 'D632I', 'D645I', 'D654I', 'D662I', 'D664I', 'D703I', 'D712I', 'D723I', 'D731I', 'D732I', 'D734I', 'D743I', 'D754I']

Rx/Tx QT/DQT choices as the CPS writes them: OFF, the CTCSS tones (e.g. 88.5), then the DCS codes of _DCS_CODES (D023N ... D754I).

Private constant _MOD_WORK_MODE_CHOICES = [('VFO Mode', 0), ('CH Mode', 1)]

Work Mode labels of the CPS and the stored values (modulation byte 33). VFO Mode = 0 confirmed on a radio; CH Mode = 1 follows the CPS list order.

Private constant _MOD_MODULATION_CHOICES = [('FM', 0), ('AM', 1), ('LSB', 2), ('USB', 3), ('CW', 4)]

Modulation Mode labels of the CPS and the stored values (byte 67). AM = 1 confirmed on a radio; the others follow the CPS list order.

Private constant _MOD_AM_STEP_CHOICES = [('1K', 0), ('5K', 1), ('10K', 2), ('100K', 3)]

AM Step Freq labels of the CPS and the stored values (byte 151). 1K = 0 confirmed on a radio; the others follow the CPS list order.

Private constant _MOD_SSB_STEP_CHOICES = [('1K', 0), ('5K', 1), ('10K', 2), ('100K', 3), ('500K', 4), ('1000K', 5)]

SSB Step Freq labels of the CPS and the stored values (byte 150). 1K = 0 confirmed on a radio; the others follow the CPS list order.

Private constant _MOD_RX_GAIN_CHOICES = [('AGC', 0), ('0dB', 1), ('-1dB', 2), ('-2dB', 3), ('-3dB', 4), ('-4dB', 5), ('-5dB', 6), ('-6dB', 7), ('-7dB', 8), ('-8dB', 9), ('-9dB', 10), ('-10dB', 11), ('-11dB', 12), ('-12dB', 13), ('-13dB', 14), ('-14dB', 15), ('-15dB', 16), ('-16dB', 17), ('-17dB', 18), ('-18dB', 19), ('-19dB', 20), ('-20dB', 21), ('-21dB', 22), ('-22dB', 23), ('-23dB', 24), ('-24dB', 25), ('-25dB', 26), ('-26dB', 27), ('-27dB', 28), ('-28dB', 29), ('-29dB', 30), ('-30dB', 31), ('-31dB', 32), ('-32dB', 33), ('-33dB', 34), ('-34dB', 35), ('-35dB', 36)]

AM/SSB Rx Gain labels of the CPS (AGC, 0dB, -1dB ... -35dB; 37 entries) and the stored values 0-36 (bytes 68 and 152). AGC = 0 confirmed on a radio; the others follow the CPS list order.

Private constant _WRITE_PLAN: Tuple[Tuple[int, Optional[int]], ...] = ((0, 31744), (1, None), (2, 128), (3, None), (4, None), (5, None), (7, None), (6, None))

Order and extent used when writing to the radio.

Each entry is (index into DEFAULT_SEGMENTS, length or None); None means the full segment length. The image layout and the read order stay DEFAULT_SEGMENTS; only the write differs:

  • channels: at most 0x0000-0x7BFF (990 channels rounded up to a 0x80 block) instead of up to 0x7FFF; RT950ProRadio._write_options may limit this further to 0x77FF;
  • function settings: only the first block, 0x9000-0x907F (the driver uses 0x9000-0x905F). The second block, 0x9080-0x90FF, changed on a radio after a CPS write while its meaning is unknown, so the driver leaves it to the radio instead of writing back what it read;
  • zone names (0xC000) are written with the other 0x57 blocks, before the APRS segment, which is always last.
Private constant _LAYOUT_VERSION = 4

Layout version stored in .img metadata (rt950_layout).

Images without it, or with a lower value, predate the zone names at 0xC000; their zone-name bytes are not trusted and not written back.

Driver implementation

Public class class RT950ProRadio(_CloneModeRadio):
6046class RT950ProRadio(chirp_common.CloneModeRadio):
6047    """CHIRP clone-mode driver for the Radtel RT-950 Pro.
6048
6049    Memories 1-990 on this object (memory ``(z - 1) * 99 + k`` is zone *z*,
6050    channel *k*) are the driver API. What CHIRP's user interface shows
6051    follows the radio setting *Channel Divide*: in Zone CH Mode the ten
6052    :class:`RT950ProZoneRadio` sub-devices (memories 1-99 each), which map
6053    onto them; in All CH Mode this object itself, as one list of memories
6054    1-990 (memory *n* is radio channel *n*).
6055
6056    Internally all data lives in a :class:`RadioImage`; the CHIRP memory
6057    map is rebuilt from it whenever CHIRP asks for it.
6058    """
6059
6060    _memsize = _SEGMENT_LENGTH
6061    """Size of a complete clone image in bytes (``_SEGMENT_LENGTH``).
6062
6063    CHIRP returns it from ``get_memsize()`` and shows it in the radio-info
6064    dialog; the driver itself does not use it.
6065    """
6066    VENDOR = "Radtel"
6067    """Vendor name shown by CHIRP."""
6068    MODEL = "RT-950 Pro"
6069    """Model name shown by CHIRP."""
6070    BAUD_RATE = 115200
6071    """Serial speed of the programming cable."""
6072
6073    def __init__(self, *args, **kwargs) -> None:
6074        """Create the driver; arguments are passed to CHIRP unchanged.
6075
6076        State used by :meth:`process_mmap` is initialised first, because
6077        CHIRP's constructor may load an image and call it.
6078
6079        Args:
6080            *args: Normally the single ``pipe`` argument of
6081                ``CloneModeRadio.__init__``: a serial port, an image file name
6082                or a ``MemoryMapBytes`` (the last two make CHIRP call
6083                :meth:`process_mmap`).
6084            **kwargs: Passed on unchanged; the stand-in only uses ``pipe``.
6085        """
6086        self._image: Optional[RadioImage] = None
6087        """Parsed clone image; the single source of all channel and settings
6088        data. ``None`` until an image is downloaded or loaded."""
6089        self._memory_cache: dict[int, chirp_common.Memory] = {}
6090        """CHIRP ``Memory`` objects by memory number (1-990), built on first
6091        :meth:`get_memory` and cleared when a new image is processed or settings
6092        are applied. The zone sub-devices share this dict."""
6093        self._memobj = None
6094        """Raw ``bitwise`` view of the memory map (``MEM_FORMAT``) for CHIRP's
6095        developer-mode Browser tab; ``None`` if it could not be built."""
6096        self._zone_names_valid = False
6097        """True when the image holds zone names read from 0xC000 (image of
6098        layout version ``_LAYOUT_VERSION`` or later); only then are zone names
6099        written to the radio."""
6100        self._legacy_960 = False
6101        """True for an image saved by the old 960-slot driver; channels
6102        961-990 are then never written."""
6103        self._aprs_original: Optional[bytes] = None
6104        """APRS block as it was when the image was processed; the APRS block
6105        is written only when the current bytes differ. ``None`` disables the
6106        APRS write."""
6107        self._high_channels_original: Optional[bytes] = None
6108        """Bytes 0x7800-0x7BFF (channels 961-990) as they were when the image
6109        was processed; that range is written only when it changed. ``None``
6110        disables writing it."""
6111        super().__init__(*args, **kwargs)
6112
6113    # ------------------------------------------------------------------
6114    # CHIRP hooks
6115    # ------------------------------------------------------------------
6116
6117    def get_features(self):  # type: ignore[override]
6118        """Describe the radio's capabilities to CHIRP.
6119
6120        ``has_sub_devices`` follows the setting *Channel Divide*
6121        (:meth:`_all_channels_mode`): ``True`` in Zone CH Mode (ten zone
6122        tabs), ``False`` in All CH Mode (one list, memories 1-990).
6123        ``has_dynamic_subdevices`` is set so that CHIRP rebuilds the tabs
6124        when that setting is changed.
6125
6126        Returns:
6127            chirp_common.RadioFeatures: Bands, modes, tones, power levels
6128            and name rules for this radio.
6129
6130        Raises:
6131            RadioError: If CHIRP is not available.
6132        """
6133        _require_chirp("get_features")
6134        # RadioFeatures accepts its attributes via __setattr__.
6135        # pylint: disable=attribute-defined-outside-init
6136        rf = chirp_common.RadioFeatures()
6137        # 1-based: memory 1 = zone 1 ch 1, memory 100 = zone 2 ch 1, ...
6138        rf.memory_bounds = (1, CHANNEL_COUNT)
6139        rf.valid_bands = list(VALID_BANDS)
6140        rf.has_bank = False
6141        rf.has_bank_names = False
6142        # Zone CH Mode: each zone is its own memory tab (channels 1-99).
6143        # All CH Mode: no sub-devices, so CHIRP shows memories 1-990 of
6144        # this object as one list.
6145        rf.has_sub_devices = not self._all_channels_mode()
6146        # The tabs depend on the setting Channel Divide: CHIRP rebuilds the
6147        # editor when that (volatile) setting is changed. Older CHIRP
6148        # versions without this feature reject the name; they then show the
6149        # new layout only after the image is reopened.
6150        try:
6151            rf.has_dynamic_subdevices = True
6152        except ValueError:
6153            pass
6154        rf.has_settings = True
6155        rf.has_name = True
6156        rf.has_ctone = True
6157        rf.has_dtcs = True
6158        rf.has_dtcs_polarity = True
6159        rf.has_mode = True
6160        rf.has_offset = True
6161        rf.has_tuning_step = False
6162        rf.can_delete = True
6163        rf.can_odd_split = True
6164        rf.has_cross = True
6165        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
6166        rf.valid_cross_modes = list(chirp_common.CROSS_MODES)
6167        rf.valid_duplexes = ["", "+", "-", "split"]
6168        rf.valid_modes = ["FM", "NFM", "AM"]
6169        rf.valid_power_levels = _CHIRP_POWER_LEVELS
6170        rf.valid_skips = ["", "S"]
6171        rf.valid_dtcs_pols = ["NN", "NR", "RN", "RR"]
6172        # Use CHIRP's standard DCS code list; do not include 0/"000"
6173        # to avoid invalid DTCS state during CSV export.
6174        rf.valid_dtcs_codes = list(chirp_common.DTCS_CODES)
6175        # The radio stores frequencies in 10 Hz units and has no per-channel
6176        # tuning step, so CHIRP must not require one: otherwise it refuses
6177        # e.g. UK CB 27.60125 MHz on paste, edit and import. The 10 Hz rule
6178        # itself is checked in validate_memory().
6179        rf.has_nostep_tuning = True
6180        rf.valid_characters = chirp_common.CHARSET_ASCII
6181        rf.valid_name_length = 12
6182        return rf
6183
6184    def validate_memory(self, mem):  # type: ignore[override]
6185        """Check ``mem`` against CHIRP's rules and the radio's 10 Hz grid.
6186
6187        Adds to CHIRP's checks (made from :meth:`get_features`) one error if
6188        the RX frequency is not a multiple of 10 Hz, and one if ``offset`` is
6189        not (for ``+``/``-`` the offset, for ``split`` the TX frequency); with
6190        the RX frequency on the 10 Hz grid this equals checking the TX
6191        frequency. The radio stores them in 10 Hz units, see
6192        :func:`_encode_frequency`; e.g. 27.60125 MHz passes, 145.500005 MHz
6193        does not. Empty memories get no extra check.
6194
6195        Args:
6196            mem: The CHIRP ``Memory`` (or ``FrozenMemory``) to check; not
6197                modified.
6198
6199        Returns:
6200            list: CHIRP's ``ValidationWarning`` and ``ValidationError``
6201            messages; empty when ``mem`` can be stored.
6202
6203        Raises:
6204            RadioError: If CHIRP is not available.
6205        """
6206        _require_chirp("validate_memory")
6207        # CHIRP's CloneModeRadio has validate_memory(); pylint may resolve the
6208        # base class to the stand-in, which lacks it (never reached: see above).
6209        msgs = super().validate_memory(mem)  # pylint: disable=no-member
6210        if mem.empty:
6211            return msgs
6212        if mem.freq % 10:
6213            msgs.append(chirp_common.ValidationError(
6214                f"Frequency {chirp_common.format_freq(mem.freq)} MHz is not a "
6215                "multiple of 10 Hz"))
6216        if mem.duplex in ("+", "-", "split") and mem.offset % 10:
6217            msgs.append(chirp_common.ValidationError(
6218                f"Offset or TX frequency {chirp_common.format_freq(mem.offset)} "
6219                "MHz is not a multiple of 10 Hz"))
6220        return msgs
6221
6222    def process_mmap(self):  # type: ignore[override]
6223        """Parse CHIRP's memory map into a :class:`RadioImage`.
6224
6225        Also upgrades images saved by earlier driver versions:
6226
6227        * full size without ``rt950_layout`` metadata, or with a version
6228          below ``_LAYOUT_VERSION``: zone-name bytes are replaced by 0xFF and
6229          not written;
6230        * without zone-name segment: 0xFF zone names are appended;
6231        * old 960-slot image: the missing 0x7800-0x7FFF range is inserted as
6232          empty, so channels 961-990 show as empty.
6233
6234        Finally it snapshots the APRS block and channels 961-990 so that
6235        :meth:`_write_options` can tell whether they changed.
6236
6237        Returns:
6238            None: Nothing; the result is stored in ``self._image`` (``None`` when
6239            there is no memory map or it is empty).
6240
6241        Raises:
6242            RadioError: If the image cannot be parsed.
6243        """
6244        mmap_obj = getattr(self, '_mmap', None)
6245        if mmap_obj is None:
6246            self._image = None
6247            return
6248        if hasattr(mmap_obj, 'get_packed'):
6249            data = mmap_obj.get_packed()
6250        else:
6251            data = bytes(mmap_obj)
6252        if not data:
6253            self._image = None
6254            return
6255        meta = getattr(self, '_metadata', None) or {}
6256        self._zone_names_valid = (len(data) == _SEGMENT_LENGTH
6257                                  and meta.get('rt950_layout', 0) >= _LAYOUT_VERSION)
6258        self._legacy_960 = False
6259        if len(data) == _SEGMENT_LENGTH and not self._zone_names_valid:
6260            LOG.warning('RT-950 Pro image from an older driver version: zone '
6261                        'names not valid and will not be written. Read the '
6262                        'radio again to get them.')
6263            data = bytes(data[:-ZONE_NAME_SEGMENT_BYTES]) + b'\xFF' * ZONE_NAME_SEGMENT_BYTES
6264            self._mmap = memmap.MemoryMapBytes(data)
6265        if len(data) == _MEMSIZE_V1:
6266            LOG.warning('RT-950 Pro image without zone names; names not read')
6267            data = bytes(data) + b'\xFF' * ZONE_NAME_SEGMENT_BYTES
6268            self._mmap = memmap.MemoryMapBytes(data)
6269        elif len(data) == _LEGACY_MEMSIZE:
6270            self._legacy_960 = True
6271            # Image saved by the old 960-slot driver: insert the missing
6272            # 0x7800-0x7FFF range as empty (0xFF) so offsets line up again.
6273            LOG.warning(
6274                'Legacy RT-950 Pro image (%d bytes): channels 961-990 were '
6275                'not read from the radio and are shown empty', len(data))
6276            data = (bytes(data[:LEGACY_CHANNEL_SECTION_BYTES])
6277                    + b'\xFF' * (CHANNEL_SECTION_BYTES - LEGACY_CHANNEL_SECTION_BYTES)
6278                    + bytes(data[LEGACY_CHANNEL_SECTION_BYTES:])
6279                    + b'\xFF' * ZONE_NAME_SEGMENT_BYTES)
6280            self._mmap = memmap.MemoryMapBytes(data)
6281        try:
6282            self._image = RadioImage.from_bytes(data)
6283        except ValueError as exc:
6284            raise errors.RadioError(f'Failed to parse memory map: {exc}') from exc
6285        self._memory_cache.clear()
6286        self._parse_memobj()
6287        self._log_channel_extra()
6288        try:
6289            payload = _build_clone_payload(self._image)
6290            self._aprs_original = self._aprs_bytes(payload)
6291            self._high_channels_original = bytes(
6292                payload[LEGACY_CHANNEL_SECTION_BYTES:0x7C00])
6293        # Without these snapshots the write simply skips APRS and channels
6294        # 961-990 (the safe default), so any failure here is non-fatal.
6295        except Exception:  # pylint: disable=broad-exception-caught
6296            self._aprs_original = None
6297            self._high_channels_original = None
6298
6299    def _parse_memobj(self) -> None:
6300        """Build the raw bitwise view for CHIRP's Browser tab (never fatal)."""
6301        try:
6302            self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
6303        # Developer view only; never fatal.
6304        except Exception as exc:  # pylint: disable=broad-exception-caught
6305            LOG.debug('Could not build raw memory view: %s', exc)
6306            self._memobj = None
6307
6308    def _log_channel_extra(self) -> None:
6309        """Log printable text found after the last channel record.
6310
6311        Diagnostic aid from the search for the zone-name location (now known
6312        to be 0xC000); it logs runs of three or more printable ASCII bytes in
6313        0x7BC0-0x7FFF.
6314        """
6315        if self._image is None:
6316            return
6317        extra = self._image.channel_extra
6318        run = bytearray()
6319        start = 0
6320        for idx, byte in enumerate(extra + b'\x00'):
6321            if 0x20 <= byte < 0x7F:
6322                if not run:
6323                    start = idx
6324                run.append(byte)
6325                continue
6326            if len(run) >= 3:
6327                LOG.info('Text at 0x%04X: %r', CHANNEL_DATA_BYTES + start,
6328                         run.decode('ascii'))
6329            run = bytearray()
6330
6331    def _refresh_mmap(self) -> None:
6332        """Copy edits held in the :class:`RadioImage` back into CHIRP's memory map."""
6333        if self._image is None:
6334            return
6335        self._mmap = memmap.MemoryMapBytes(_build_clone_payload(self._image))
6336        self._parse_memobj()
6337
6338    def get_mmap(self):  # type: ignore[override]
6339        """Return the memory map, refreshed from the current image.
6340
6341        Returns:
6342            memmap.MemoryMapBytes: ``self._mmap``, rebuilt from the image when one
6343            is loaded.
6344
6345        Raises:
6346            ValueError: If the image cannot be serialised.
6347        """
6348        self._refresh_mmap()
6349        return self._mmap
6350
6351    def save_mmap(self, filename):  # type: ignore[override]
6352        """Refresh the memory map from the image, then save it as CHIRP does.
6353
6354        Args:
6355            filename: Destination ``.img`` file.
6356
6357        Returns:
6358            None: CHIRP's ``CloneModeRadio.save_mmap`` returns nothing; the
6359            ``return`` only passes that through.
6360
6361        Raises:
6362            ValueError: If the image cannot be serialised.
6363            Exception: ``"File Access Error"`` from CHIRP on an ``IOError``.
6364        """
6365        self._refresh_mmap()
6366        # pylint cannot see save_mmap on the stand-in base class.
6367        return super().save_mmap(filename)  # pylint: disable=no-member
6368
6369    def _aprs_bytes(self, payload: bytes) -> bytes:
6370        """Return the APRS block (segment 6) from a clone payload.
6371
6372        Args:
6373            payload: Clone payload in ``DEFAULT_SEGMENTS`` order.
6374
6375        Returns:
6376            bytes: The ``APRS_SEGMENT_BYTES`` (128) bytes of the APRS block.
6377        """
6378        start = sum(seg.length for seg in DEFAULT_SEGMENTS[:6])
6379        return bytes(payload[start : start + DEFAULT_SEGMENTS[6].length])
6380
6381    def _write_options(self) -> dict:
6382        """Decide which optional parts of the image to write.
6383
6384        * APRS is written only when its bytes changed since the read. The
6385          APRS commit is slow and an old write command (0x55) was never
6386          acknowledged, so it is skipped whenever possible.
6387        * 0x7800-0x7BFF holds channels 961-990 on firmware with 10x99
6388          zones, but NeonPlug reports calibration-like data there on other
6389          units. It is written only when one of channels 961-990 changed,
6390          and never for an image from the old 960-slot driver.
6391        * Zone names are written only when they were read from 0xC000.
6392
6393        Returns:
6394            dict: Keyword arguments for :func:`_build_write_plan`
6395            (``write_zone_names``, ``channel_bytes``, ``write_aprs``).
6396        """
6397        write_aprs = False
6398        channel_bytes = LEGACY_CHANNEL_SECTION_BYTES
6399        if self._image is not None:
6400            payload = _build_clone_payload(self._image)
6401            if getattr(self, '_aprs_original', None) is not None:
6402                write_aprs = self._aprs_bytes(payload) != self._aprs_original
6403            original_high = getattr(self, '_high_channels_original', None)
6404            if (original_high is not None and not getattr(self, '_legacy_960', False)
6405                    and bytes(payload[LEGACY_CHANNEL_SECTION_BYTES:0x7C00]) != original_high):
6406                channel_bytes = 0x7C00
6407        return {
6408            'write_zone_names': getattr(self, '_zone_names_valid', False),
6409            'channel_bytes': channel_bytes,
6410            'write_aprs': write_aprs,
6411        }
6412
6413    def _all_channels_mode(self) -> bool:
6414        """Return whether the image is set to *All CH Mode*.
6415
6416        Reads the function setting ``divide_channel`` (byte 0x9026) of the
6417        loaded image. Only the value ``CHANNEL_DIVIDE_ALL`` (1) counts as
6418        All CH Mode; Zone CH Mode (0), a value that is not set (0xFF), an
6419        unknown value, a missing function block and no image at all give
6420        ``False``, i.e. the zone view.
6421
6422        Returns:
6423            bool: ``True`` for All CH Mode, otherwise ``False``.
6424        """
6425        image = self._image
6426        function = getattr(image, 'function', None) if image is not None else None
6427        if function is None:
6428            return False
6429        try:
6430            value = get_function_value(function, 'divide_channel')
6431        except KeyError:
6432            return False
6433        return value == CHANNEL_DIVIDE_ALL
6434
6435    def get_sub_devices(self):  # type: ignore[override]
6436        """Return the zone sub-devices for the current *Channel Divide* mode.
6437
6438        Zone CH Mode: one :class:`RT950ProZoneRadio` per zone (memory tabs
6439        1-10). All CH Mode: none, because the radio then has no zones to
6440        show; CHIRP uses this object itself (memories 1-990) as the only
6441        memory list.
6442
6443        Returns:
6444            list[RT950ProZoneRadio]: Ten sub-devices, zone 1 first, or an
6445            empty list in All CH Mode.
6446        """
6447        if self._all_channels_mode():
6448            return []
6449        return [RT950ProZoneRadio(self, zone) for zone in range(1, ZONE_COUNT + 1)]
6450
6451    def sync_in(self):  # type: ignore[override]
6452        """Download the complete image from the radio.
6453
6454        Reports progress per block through CHIRP's ``status_fn`` when
6455        available, then replaces ``self._metadata`` with
6456        ``{'rt950_layout': _LAYOUT_VERSION}`` and parses the image with
6457        :meth:`process_mmap` (which relies on that version).
6458
6459        Raises:
6460            RadioError: If no port is open, the clone read fails, or the
6461                image cannot be parsed.
6462        """
6463        if self.pipe is None:
6464            raise errors.RadioError("Serial pipe not initialised")
6465        transport = CloneSerialTransport(self.pipe, logger=LOG)
6466        # Hook progress into CHIRP status if available
6467        status = None
6468        try:
6469            status = chirp_common.Status()
6470            status.msg = "Cloning from radio…"
6471            status.max = 0
6472        # Status is optional (absent from the stand-in); clone without it.
6473        except Exception:  # pylint: disable=broad-exception-caught
6474            status = None
6475        if status is not None and hasattr(self, "status_fn"):
6476            blocks_per_segment = [seg.length // READ_BLOCK for seg in DEFAULT_SEGMENTS]
6477            seg_labels = [
6478                "Channels",
6479                "VFO settings",
6480                "Function settings",
6481                "DTMF settings",
6482                "Modulation params",
6483                "Modulation names",
6484                "APRS settings",
6485                "Zone names",
6486            ]
6487
6488            def _progress(done: int, total: int, phase: str) -> None:
6489                """Map a block count to a 'Reading ...' status message.
6490
6491                Args:
6492                    done: Blocks transferred so far (1-based count).
6493                    total: Total number of blocks in the transfer.
6494                    phase: ``"read"`` or ``"write"``; selects the message verb.
6495                """
6496                try:
6497                    block_index = max(0, int(done) - 1)
6498                    seg_idx = 0
6499                    offset_blocks = block_index
6500                    for count in blocks_per_segment:
6501                        if offset_blocks < count:
6502                            break
6503                        offset_blocks -= count
6504                        seg_idx += 1
6505                    direction = "Reading" if phase == "read" else "Writing"
6506                    if seg_idx == 0:
6507                        per_block = max(1, READ_BLOCK // CHANNEL_SIZE)
6508                        start_ch = offset_blocks * per_block + 1
6509                        end_ch = min(start_ch + per_block - 1, CHANNEL_COUNT)
6510                        status.msg = f"{direction} channels {start_ch:03d}-{end_ch:03d}…"
6511                    else:
6512                        status.msg = f"{direction} {seg_labels[seg_idx]}…"
6513                    status.cur = done
6514                    status.max = total
6515                    self.status_fn(status)
6516                # Progress reporting must never break the clone.
6517                except Exception:  # pylint: disable=broad-exception-caught
6518                    pass
6519            transport.progress_cb = _progress
6520        try:
6521            raw = transport.read_clone()
6522        except Exception as exc:
6523            raise errors.RadioError(f'Clone read failed: {exc}') from exc
6524        self._mmap = memmap.MemoryMapBytes(raw)
6525        self._metadata = {'rt950_layout': _LAYOUT_VERSION}
6526        self.process_mmap()
6527
6528    def sync_out(self):  # type: ignore[override]
6529        """Upload the image to the radio.
6530
6531        The parts written are chosen by :meth:`_write_options` and ordered by
6532        ``_WRITE_PLAN``: channels (up to 0x77FF, or 0x7BFF when channels
6533        961-990 changed), settings blocks, zone names if valid, and APRS last
6534        and only if changed.
6535
6536        Raises:
6537            RadioError: If no port or image is available or the write fails.
6538                A missing APRS acknowledgement gets its own message, because
6539                everything else was already written at that point.
6540            ValueError: If the image cannot be serialised (e.g. a DCS tone
6541                with polarity ``R``); raised before anything is sent.
6542        """
6543        if self.pipe is None:
6544            raise errors.RadioError("Serial pipe not initialised")
6545        if self._image is None:
6546            raise errors.RadioError("No image loaded")
6547        payload = _build_clone_payload(self._image)
6548        transport = CloneSerialTransport(self.pipe, logger=LOG)
6549        status = None
6550        try:
6551            status = chirp_common.Status()
6552            status.msg = "Cloning to radio…"
6553            status.max = 0
6554        # Status is optional (absent from the stand-in); clone without it.
6555        except Exception:  # pylint: disable=broad-exception-caught
6556            status = None
6557        if status is not None and hasattr(self, "status_fn"):
6558            all_labels = [
6559                "Channels",
6560                "VFO settings",
6561                "Function settings",
6562                "DTMF settings",
6563                "Modulation params",
6564                "Modulation names",
6565                "APRS settings",
6566                "Zone names",
6567            ]
6568            plan_segments, _ = _build_write_plan(payload, **self._write_options())
6569            blocks_per_segment = [seg.length // READ_BLOCK for seg in plan_segments]
6570            opts = self._write_options()
6571            seg_labels = [all_labels[index] for index, _ in _WRITE_PLAN
6572                          if (index != 7 or opts['write_zone_names'])
6573                          and (index != 6 or opts['write_aprs'])]
6574
6575            def _progress(done: int, total: int, phase: str) -> None:
6576                """Map a block count to a 'Writing ...' status message.
6577
6578                Args:
6579                    done: Blocks transferred so far (1-based count).
6580                    total: Total number of blocks in the transfer.
6581                    phase: Transfer phase from the transport; unused.
6582                """
6583                del phase  # always "write" here
6584                try:
6585                    block_index = max(0, int(done) - 1)
6586                    seg_idx = 0
6587                    offset_blocks = block_index
6588                    for count in blocks_per_segment:
6589                        if offset_blocks < count:
6590                            break
6591                        offset_blocks -= count
6592                        seg_idx += 1
6593                    if seg_idx == 0:
6594                        per_block = max(1, READ_BLOCK // CHANNEL_SIZE)
6595                        start_ch = offset_blocks * per_block + 1
6596                        end_ch = min(start_ch + per_block - 1, CHANNEL_COUNT)
6597                        status.msg = f"Writing channels {start_ch:03d}-{end_ch:03d}…"
6598                    else:
6599                        status.msg = f"Writing {seg_labels[seg_idx]}…"
6600                    status.cur = done
6601                    status.max = total
6602                    self.status_fn(status)
6603                # Progress reporting must never break the clone.
6604                except Exception:  # pylint: disable=broad-exception-caught
6605                    pass
6606            transport.progress_cb = _progress
6607        try:
6608            write_segments, write_data = _build_write_plan(
6609                payload, **self._write_options())
6610            transport.write_clone(write_data, segments=write_segments)
6611        # Any failure is reported to the user as a RadioError.
6612        except Exception as exc:  # pylint: disable=broad-exception-caught
6613            if 'cmd 0x58' in str(exc):
6614                raise errors.RadioError(
6615                    'All channels, settings and zone names were written, but the '
6616                    'radio did not acknowledge the APRS block (cmd 0x58); APRS '
6617                    'changes may NOT be saved. Power-cycle the radio and read back.') from exc
6618            raise errors.RadioError(f'Clone write failed: {exc}') from exc
6619        self._mmap = memmap.MemoryMapBytes(payload)
6620        self._parse_memobj()
6621    # ------------------------------------------------------------------
6622    # Settings integration
6623    # ------------------------------------------------------------------
6624
6625    def get_settings(self):  # type: ignore[override]
6626        """Build the settings tree shown in CHIRP's *Settings* tab.
6627
6628        Returns:
6629            RadioSettings: VFO, modulation, function, APRS, DTMF and zone-name
6630            groups (sections absent from the image are skipped).
6631
6632        Raises:
6633            RadioError: If CHIRP is not available or no image is loaded.
6634        """
6635        _require_chirp("get_settings")
6636        image = self._require_image()
6637        groups = []
6638        if getattr(image, 'vfo', None):
6639            groups.append(_build_vfo_group(image.vfo))
6640        if getattr(image, 'modulation', None) is not None:
6641            groups.append(_build_modulation_group(image.modulation))
6642        if getattr(image, 'function', None) is not None:
6643            groups.append(_build_function_group(image.function))
6644        if getattr(image, 'aprs', None) is not None:
6645            groups.append(_build_aprs_group(image.aprs))
6646        if getattr(image, 'dtmf', None) is not None:
6647            groups.append(_build_dtmf_group(image.dtmf))
6648        groups.append(_build_zone_group(image))
6649        if not groups:
6650            return RadioSettings()
6651        return RadioSettings(*groups)
6652
6653    def set_settings(self, settings):  # type: ignore[override]
6654        """Apply edited settings to the image.
6655
6656        CHIRP passes the whole tree on every apply. The apply callback runs
6657        only for settings whose value was changed (CHIRP's
6658        ``RadioSetting.changed()``; without it, as with the stand-in classes,
6659        every callback runs). The callbacks write into the
6660        :class:`RadioImage`. Then clears the memory cache.
6661
6662        Args:
6663            settings: The tree returned by :meth:`get_settings`, edited.
6664
6665        Raises:
6666            RadioError: If no image is loaded, the container is unexpected or a
6667                callback rejects a value.
6668            ValueError: For an invalid modulation-memory frequency.
6669        """
6670        self._require_image()
6671        if not isinstance(settings, RadioSettings):
6672            raise errors.RadioError('Unexpected settings container')
6673        walker = getattr(settings, 'walk', None)
6674        if walker is None:
6675            raise errors.RadioError('Settings container missing walk()')
6676        for element in walker():
6677            if not (isinstance(element, RadioSetting) and element.has_apply_callback()):
6678                continue
6679            # CHIRP marks a value as changed once the user edits it; unchanged
6680            # settings are skipped, so a value the driver cannot show exactly
6681            # (e.g. "not set", 0xFF) is never rewritten as a default.
6682            changed = getattr(element, 'changed', None)
6683            if changed is not None and not changed():
6684                continue
6685            element.run_apply_callback()
6686        self._memory_cache.clear()
6687    # ------------------------------------------------------------------
6688    # Memory translation helpers
6689    # ------------------------------------------------------------------
6690
6691    def _require_image(self) -> RadioImage:
6692        """Return the loaded image.
6693
6694        Returns:
6695            RadioImage: The parsed clone image.
6696
6697        Raises:
6698            RadioError: If no image is loaded.
6699        """
6700        if self._image is None:
6701            raise errors.RadioError("Memory image not loaded")
6702        return self._image
6703
6704    def get_memory(self, number: int):  # type: ignore[override]
6705        """Return memory ``number`` (1-990) as a CHIRP ``Memory``.
6706
6707        Results are cached until the memory or the settings change.
6708
6709        Args:
6710            number: Memory number, 1-990 (slot ``number - 1``).
6711
6712        Returns:
6713            chirp_common.Memory: The memory, from the cache when available.
6714
6715        Raises:
6716            RadioError: If CHIRP is not available, no image is loaded or
6717                ``number`` is out of range.
6718        """
6719        _require_chirp("get_memory")
6720        image = self._require_image()
6721        if not 1 <= number <= len(image.channels):
6722            raise errors.RadioError(f"Memory index {number} out of range")
6723        if number in self._memory_cache:
6724            return self._memory_cache[number]
6725        channel = image.channels[number - 1]
6726        mem = self._channel_to_memory(number, channel)
6727        self._memory_cache[number] = mem
6728        return mem
6729
6730    def set_memory(self, mem):  # type: ignore[override]
6731        """Store a CHIRP ``Memory`` in the image.
6732
6733        The sanitised result is cached and returned by later
6734        :meth:`get_memory` calls. ``mem`` is not modified, so CHIRP's
6735        ``FrozenMemory`` can be passed directly.
6736
6737        Args:
6738            mem: The CHIRP ``Memory`` to store; ``mem.number`` is 1-990.
6739
6740        Raises:
6741            RadioError: If CHIRP is not available, no image is loaded or the
6742                number is out of range.
6743        """
6744        _require_chirp("set_memory")
6745        image = self._require_image()
6746        if not 1 <= mem.number <= len(image.channels):
6747            raise errors.RadioError(f"Memory index {mem.number} out of range")
6748        channel = image.channels[mem.number - 1]
6749        self._apply_memory_to_channel(mem, channel)
6750        # The cache holds the sanitised version that get_memory() returns
6751        # from now on.
6752        sanitized = self._channel_to_memory(mem.number, channel)
6753        self._memory_cache[mem.number] = sanitized
6754    # ------------------------------------------------------------------
6755    # Conversion routines
6756    # ------------------------------------------------------------------
6757
6758    def _channel_to_memory(self, number: int, channel: ChannelRecord):
6759        """Convert a channel record into a CHIRP ``Memory``.
6760
6761        Mode is ``AM`` for AM channels, otherwise ``NFM`` or ``FM`` from the
6762        bandwidth; skip is ``S`` when the channel is not in the scan list.
6763
6764        Args:
6765            number: CHIRP memory number.
6766            channel: The channel record.
6767
6768        Returns:
6769            chirp_common.Memory: The memory (``empty`` if ``rx_hz`` is ``None``).
6770        """
6771        mem = chirp_common.Memory()
6772        mem.number = number
6773        if channel.rx_hz is None:
6774            mem.empty = True
6775            return mem
6776        mem.freq = channel.rx_hz
6777        mem.empty = False
6778        mem.name = (channel.name or "").strip()
6779        self._apply_offset(mem, channel)
6780        self._apply_tones(mem, channel)
6781        if channel.rx_modulation is Modulation.AM:
6782            mem.mode = "AM"
6783        else:
6784            mem.mode = "NFM" if channel.bandwidth is Bandwidth.NARROW else "FM"
6785        mem.power = _POWER_ENUM_TO_CHIRP.get(channel.power, _CHIRP_POWER_LEVELS[0])
6786        mem.skip = "" if channel.scan_add else "S"
6787        mem.extra = _build_memory_extra(channel)
6788        return mem
6789
6790    def _apply_offset(self, mem, channel: ChannelRecord) -> None:
6791        """Derive CHIRP duplex and offset from the RX and TX frequencies.
6792
6793        Equal or missing TX gives simplex. When RX and TX lie in different
6794        bands of ``VALID_BANDS`` (CHIRP's ``chirp_common.is_split``) the
6795        result is ``split`` with the TX frequency as offset, e.g. RX 145.5 /
6796        TX 435.0 MHz. Otherwise ``+`` or ``-`` with the difference as
6797        offset, e.g. RX 145.6 / TX 145.0 MHz gives ``-`` 600 kHz.
6798
6799        Args:
6800            mem: The CHIRP ``Memory`` to update (``duplex``, ``offset`` in Hz).
6801            channel: The channel record providing ``rx_hz`` and ``tx_hz``.
6802        """
6803        if channel.tx_hz is None or channel.tx_hz == channel.rx_hz:
6804            mem.duplex = ""
6805            mem.offset = 0
6806            return
6807        if chirp_common.is_split(VALID_BANDS, channel.rx_hz, channel.tx_hz):
6808            mem.duplex = "split"
6809            mem.offset = channel.tx_hz
6810            return
6811        diff = channel.tx_hz - channel.rx_hz
6812        mem.duplex = "+" if diff > 0 else "-"
6813        mem.offset = abs(diff)
6814
6815    def _apply_tones(self, mem, channel: ChannelRecord) -> None:
6816        """Translate the channel's TX/RX tones into CHIRP tone fields.
6817
6818        Uses CHIRP's ``chirp_common.split_tone_decode``: no tone gives ``""``,
6819        TX CTCSS only ``Tone``, equal TX/RX CTCSS ``TSQL``, equal TX/RX DCS
6820        code ``DTCS``, and every other combination ``Cross`` with the
6821        matching ``cross_mode`` (e.g. ``"->Tone"`` for an RX-only tone). The
6822        radio's inverted DCS polarity ``I`` is given to CHIRP as ``R``. DCS
6823        fields default to a valid code (023) when unused, because CHIRP's CSV
6824        export validates them.
6825
6826        Args:
6827            mem: The CHIRP ``Memory`` to update (``tmode``, ``cross_mode``,
6828                tones, DCS fields).
6829            channel: The channel record providing ``tx_tone`` and ``rx_tone``.
6830        """
6831        # CHIRP's CSV exporter validates DtcsCode/RxDtcsCode even when
6832        # tmode is not DTCS. Use a valid default (e.g. 023) instead of 000
6833        # to avoid exporter errors.
6834        default_dcs = chirp_common.DTCS_CODES[0]
6835        mem.dtcs = default_dcs
6836        mem.rx_dtcs = default_dcs
6837        mem.dtcs_polarity = "NN"
6838        mem.tmode = ""
6839        chirp_common.split_tone_decode(
6840            mem, _tone_to_chirp(channel.tx_tone), _tone_to_chirp(channel.rx_tone))
6841
6842    def _apply_memory_to_channel(self, mem, channel: ChannelRecord) -> None:
6843        """Copy a CHIRP ``Memory`` into a channel record.
6844
6845        An empty memory clears ``rx_hz``, ``tx_hz`` and ``name`` only.
6846        Otherwise frequencies, name, tones, mode, power (unchanged if the
6847        label is unknown) and skip are copied. Band rules: 118-137 MHz is
6848        forced to AM, wide, with ``tx_enabled`` cleared; 18-64 MHz is forced
6849        to FM. ``tx_enabled`` is never set back to True. Learn-FHSS and the
6850        FHSS code are cleared. Scrambler (0-8) and encryption (0-3) come from
6851        the memory's extras; missing or out-of-range values become 0.
6852
6853        Args:
6854            mem: The CHIRP memory.
6855            channel: The record to update in place.
6856        """
6857        if getattr(mem, "empty", False):
6858            channel.rx_hz = None
6859            channel.tx_hz = None
6860            channel.name = ""
6861            return
6862        channel.rx_hz = mem.freq
6863        if mem.duplex == "+":
6864            channel.tx_hz = mem.freq + mem.offset
6865        elif mem.duplex == "-":
6866            channel.tx_hz = mem.freq - mem.offset
6867        elif mem.duplex == "split":
6868            channel.tx_hz = mem.offset
6869        else:
6870            channel.tx_hz = mem.freq
6871        channel.name = (mem.name or "").strip()
6872        self._update_tones_from_memory(mem, channel)
6873
6874        extras = _extract_memory_extra(mem)
6875        scrambler_raw = extras.get('scrambler', getattr(mem, '_rt950_scrambler', None))
6876        encryption_raw = extras.get('encryption', getattr(mem, '_rt950_encryption', None))
6877        try:
6878            channel.scrambler = int(scrambler_raw)
6879        except (TypeError, ValueError):
6880            channel.scrambler = 0
6881        if channel.scrambler < 0 or channel.scrambler > 8:
6882            channel.scrambler = 0
6883        try:
6884            channel.encryption = int(encryption_raw)
6885        except (TypeError, ValueError):
6886            channel.encryption = 0
6887        if channel.encryption not in (0, 1, 2, 3):
6888            channel.encryption = 0
6889        channel.learn_fhss = False
6890        channel.fhss_code = None
6891
6892        mode = (mem.mode or "").upper()
6893        if mode not in {"AM", "FM", "NFM"}:
6894            mode = "AM" if channel.rx_modulation is Modulation.AM else "FM"
6895
6896        # Band-specific constraints
6897        freq = channel.rx_hz or 0
6898        in_airband = 118_000_000 <= freq <= 137_000_000
6899        in_low_hf = 18_000_000 <= freq <= 64_000_000
6900
6901        if in_airband:
6902            # Airband: AM only, TX disabled
6903            channel.rx_modulation = Modulation.AM
6904            channel.bandwidth = Bandwidth.WIDE
6905            channel.tx_enabled = False
6906        elif in_low_hf:
6907            # Low HF: FM only
6908            channel.rx_modulation = Modulation.FM
6909            channel.bandwidth = Bandwidth.NARROW if mode == "NFM" else Bandwidth.WIDE
6910        else:
6911            # Default behavior for VHF/UHF
6912            if mode == "AM":
6913                channel.rx_modulation = Modulation.AM
6914                channel.bandwidth = Bandwidth.WIDE
6915            else:
6916                channel.rx_modulation = Modulation.FM
6917                channel.bandwidth = Bandwidth.NARROW if mode == "NFM" else Bandwidth.WIDE
6918        if isinstance(mem.power, chirp_common.PowerLevel):
6919            key = str(mem.power).upper()
6920        elif isinstance(mem.power, str) and mem.power:
6921            key = mem.power.upper()
6922        else:
6923            key = None
6924        if key and key in _POWER_LABEL_TO_ENUM:
6925            channel.power = _POWER_LABEL_TO_ENUM[key]
6926        channel.scan_add = mem.skip != "S"
6927
6928    def _update_tones_from_memory(self, mem, channel: ChannelRecord) -> None:
6929        """Translate CHIRP tone fields into the channel's TX/RX tones.
6930
6931        Uses CHIRP's ``chirp_common.split_tone_encode``, so every tone mode
6932        including ``Cross`` is honoured (``TSQL`` uses ``ctone`` for TX and
6933        RX, as in CHIRP). CHIRP's reverse polarity ``R`` is stored as the
6934        radio's ``I``. A DCS code of 0 is stored as no tone. ``mem`` is not
6935        modified.
6936
6937        Args:
6938            mem: The CHIRP ``Memory`` to read.
6939            channel: The channel record whose ``tx_tone``/``rx_tone`` are replaced.
6940        """
6941        tx_spec, rx_spec = chirp_common.split_tone_encode(mem)
6942        channel.tx_tone = _tone_from_chirp(*tx_spec)
6943        channel.rx_tone = _tone_from_chirp(*rx_spec)

CHIRP clone-mode driver for the Radtel RT-950 Pro.

Memories 1-990 on this object (memory (z - 1) * 99 + k is zone z, channel k) are the driver API. What CHIRP's user interface shows follows the radio setting Channel Divide: in Zone CH Mode the ten RT950ProZoneRadio sub-devices (memories 1-99 each), which map onto them; in All CH Mode this object itself, as one list of memories 1-990 (memory n is radio channel n).

Internally all data lives in a RadioImage; the CHIRP memory map is rebuilt from it whenever CHIRP asks for it.

Constructor
Public constructor RT950ProRadio(*args, **kwargs)
6073    def __init__(self, *args, **kwargs) -> None:
6074        """Create the driver; arguments are passed to CHIRP unchanged.
6075
6076        State used by :meth:`process_mmap` is initialised first, because
6077        CHIRP's constructor may load an image and call it.
6078
6079        Args:
6080            *args: Normally the single ``pipe`` argument of
6081                ``CloneModeRadio.__init__``: a serial port, an image file name
6082                or a ``MemoryMapBytes`` (the last two make CHIRP call
6083                :meth:`process_mmap`).
6084            **kwargs: Passed on unchanged; the stand-in only uses ``pipe``.
6085        """
6086        self._image: Optional[RadioImage] = None
6087        """Parsed clone image; the single source of all channel and settings
6088        data. ``None`` until an image is downloaded or loaded."""
6089        self._memory_cache: dict[int, chirp_common.Memory] = {}
6090        """CHIRP ``Memory`` objects by memory number (1-990), built on first
6091        :meth:`get_memory` and cleared when a new image is processed or settings
6092        are applied. The zone sub-devices share this dict."""
6093        self._memobj = None
6094        """Raw ``bitwise`` view of the memory map (``MEM_FORMAT``) for CHIRP's
6095        developer-mode Browser tab; ``None`` if it could not be built."""
6096        self._zone_names_valid = False
6097        """True when the image holds zone names read from 0xC000 (image of
6098        layout version ``_LAYOUT_VERSION`` or later); only then are zone names
6099        written to the radio."""
6100        self._legacy_960 = False
6101        """True for an image saved by the old 960-slot driver; channels
6102        961-990 are then never written."""
6103        self._aprs_original: Optional[bytes] = None
6104        """APRS block as it was when the image was processed; the APRS block
6105        is written only when the current bytes differ. ``None`` disables the
6106        APRS write."""
6107        self._high_channels_original: Optional[bytes] = None
6108        """Bytes 0x7800-0x7BFF (channels 961-990) as they were when the image
6109        was processed; that range is written only when it changed. ``None``
6110        disables writing it."""
6111        super().__init__(*args, **kwargs)

Create the driver; arguments are passed to CHIRP unchanged.

State used by process_mmap() is initialised first, because CHIRP's constructor may load an image and call it.

Arguments:
  • *args: Normally the single pipe argument of CloneModeRadio.__init__: a serial port, an image file name or a MemoryMapBytes (the last two make CHIRP call process_mmap()).
  • **kwargs: Passed on unchanged; the stand-in only uses pipe.
Fields
Public field VENDOR = 'Radtel'

Vendor name shown by CHIRP.

Public field MODEL = 'RT-950 Pro'

Model name shown by CHIRP.

Public field BAUD_RATE = 115200

Serial speed of the programming cable.

Private field _memsize = 35456

Size of a complete clone image in bytes (_SEGMENT_LENGTH).

CHIRP returns it from get_memsize() and shows it in the radio-info dialog; the driver itself does not use it.

Private field _image: Optional[RadioImage]

Parsed clone image; the single source of all channel and settings data. None until an image is downloaded or loaded.

Private field _memory_cache: dict[int, radtel_rt950pro._Memory]

CHIRP Memory objects by memory number (1-990), built on first get_memory() and cleared when a new image is processed or settings are applied. The zone sub-devices share this dict.

Private field _memobj

Raw bitwise view of the memory map (MEM_FORMAT) for CHIRP's developer-mode Browser tab; None if it could not be built.

Private field _zone_names_valid

True when the image holds zone names read from 0xC000 (image of layout version _LAYOUT_VERSION or later); only then are zone names written to the radio.

Private field _legacy_960

True for an image saved by the old 960-slot driver; channels 961-990 are then never written.

Private field _aprs_original: Optional[bytes]

APRS block as it was when the image was processed; the APRS block is written only when the current bytes differ. None disables the APRS write.

Private field _high_channels_original: Optional[bytes]

Bytes 0x7800-0x7BFF (channels 961-990) as they were when the image was processed; that range is written only when it changed. None disables writing it.

Methods
Public method def get_features(self):
6117    def get_features(self):  # type: ignore[override]
6118        """Describe the radio's capabilities to CHIRP.
6119
6120        ``has_sub_devices`` follows the setting *Channel Divide*
6121        (:meth:`_all_channels_mode`): ``True`` in Zone CH Mode (ten zone
6122        tabs), ``False`` in All CH Mode (one list, memories 1-990).
6123        ``has_dynamic_subdevices`` is set so that CHIRP rebuilds the tabs
6124        when that setting is changed.
6125
6126        Returns:
6127            chirp_common.RadioFeatures: Bands, modes, tones, power levels
6128            and name rules for this radio.
6129
6130        Raises:
6131            RadioError: If CHIRP is not available.
6132        """
6133        _require_chirp("get_features")
6134        # RadioFeatures accepts its attributes via __setattr__.
6135        # pylint: disable=attribute-defined-outside-init
6136        rf = chirp_common.RadioFeatures()
6137        # 1-based: memory 1 = zone 1 ch 1, memory 100 = zone 2 ch 1, ...
6138        rf.memory_bounds = (1, CHANNEL_COUNT)
6139        rf.valid_bands = list(VALID_BANDS)
6140        rf.has_bank = False
6141        rf.has_bank_names = False
6142        # Zone CH Mode: each zone is its own memory tab (channels 1-99).
6143        # All CH Mode: no sub-devices, so CHIRP shows memories 1-990 of
6144        # this object as one list.
6145        rf.has_sub_devices = not self._all_channels_mode()
6146        # The tabs depend on the setting Channel Divide: CHIRP rebuilds the
6147        # editor when that (volatile) setting is changed. Older CHIRP
6148        # versions without this feature reject the name; they then show the
6149        # new layout only after the image is reopened.
6150        try:
6151            rf.has_dynamic_subdevices = True
6152        except ValueError:
6153            pass
6154        rf.has_settings = True
6155        rf.has_name = True
6156        rf.has_ctone = True
6157        rf.has_dtcs = True
6158        rf.has_dtcs_polarity = True
6159        rf.has_mode = True
6160        rf.has_offset = True
6161        rf.has_tuning_step = False
6162        rf.can_delete = True
6163        rf.can_odd_split = True
6164        rf.has_cross = True
6165        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
6166        rf.valid_cross_modes = list(chirp_common.CROSS_MODES)
6167        rf.valid_duplexes = ["", "+", "-", "split"]
6168        rf.valid_modes = ["FM", "NFM", "AM"]
6169        rf.valid_power_levels = _CHIRP_POWER_LEVELS
6170        rf.valid_skips = ["", "S"]
6171        rf.valid_dtcs_pols = ["NN", "NR", "RN", "RR"]
6172        # Use CHIRP's standard DCS code list; do not include 0/"000"
6173        # to avoid invalid DTCS state during CSV export.
6174        rf.valid_dtcs_codes = list(chirp_common.DTCS_CODES)
6175        # The radio stores frequencies in 10 Hz units and has no per-channel
6176        # tuning step, so CHIRP must not require one: otherwise it refuses
6177        # e.g. UK CB 27.60125 MHz on paste, edit and import. The 10 Hz rule
6178        # itself is checked in validate_memory().
6179        rf.has_nostep_tuning = True
6180        rf.valid_characters = chirp_common.CHARSET_ASCII
6181        rf.valid_name_length = 12
6182        return rf

Describe the radio's capabilities to CHIRP.

has_sub_devices follows the setting Channel Divide (_all_channels_mode()): True in Zone CH Mode (ten zone tabs), False in All CH Mode (one list, memories 1-990). has_dynamic_subdevices is set so that CHIRP rebuilds the tabs when that setting is changed.

Returns:

chirp_common.RadioFeatures: Bands, modes, tones, power levels and name rules for this radio.

Raises:
  • RadioError: If CHIRP is not available.
Public method def validate_memory(self, mem):
6184    def validate_memory(self, mem):  # type: ignore[override]
6185        """Check ``mem`` against CHIRP's rules and the radio's 10 Hz grid.
6186
6187        Adds to CHIRP's checks (made from :meth:`get_features`) one error if
6188        the RX frequency is not a multiple of 10 Hz, and one if ``offset`` is
6189        not (for ``+``/``-`` the offset, for ``split`` the TX frequency); with
6190        the RX frequency on the 10 Hz grid this equals checking the TX
6191        frequency. The radio stores them in 10 Hz units, see
6192        :func:`_encode_frequency`; e.g. 27.60125 MHz passes, 145.500005 MHz
6193        does not. Empty memories get no extra check.
6194
6195        Args:
6196            mem: The CHIRP ``Memory`` (or ``FrozenMemory``) to check; not
6197                modified.
6198
6199        Returns:
6200            list: CHIRP's ``ValidationWarning`` and ``ValidationError``
6201            messages; empty when ``mem`` can be stored.
6202
6203        Raises:
6204            RadioError: If CHIRP is not available.
6205        """
6206        _require_chirp("validate_memory")
6207        # CHIRP's CloneModeRadio has validate_memory(); pylint may resolve the
6208        # base class to the stand-in, which lacks it (never reached: see above).
6209        msgs = super().validate_memory(mem)  # pylint: disable=no-member
6210        if mem.empty:
6211            return msgs
6212        if mem.freq % 10:
6213            msgs.append(chirp_common.ValidationError(
6214                f"Frequency {chirp_common.format_freq(mem.freq)} MHz is not a "
6215                "multiple of 10 Hz"))
6216        if mem.duplex in ("+", "-", "split") and mem.offset % 10:
6217            msgs.append(chirp_common.ValidationError(
6218                f"Offset or TX frequency {chirp_common.format_freq(mem.offset)} "
6219                "MHz is not a multiple of 10 Hz"))
6220        return msgs

Check mem against CHIRP's rules and the radio's 10 Hz grid.

Adds to CHIRP's checks (made from get_features()) one error if the RX frequency is not a multiple of 10 Hz, and one if offset is not (for +/- the offset, for split the TX frequency); with the RX frequency on the 10 Hz grid this equals checking the TX frequency. The radio stores them in 10 Hz units, see _encode_frequency(); e.g. 27.60125 MHz passes, 145.500005 MHz does not. Empty memories get no extra check.

Arguments:
  • mem: The CHIRP Memory (or FrozenMemory) to check; not modified.
Returns:

list: CHIRP's ValidationWarning and ValidationError messages; empty when mem can be stored.

Raises:
  • RadioError: If CHIRP is not available.
Public method def process_mmap(self):
6222    def process_mmap(self):  # type: ignore[override]
6223        """Parse CHIRP's memory map into a :class:`RadioImage`.
6224
6225        Also upgrades images saved by earlier driver versions:
6226
6227        * full size without ``rt950_layout`` metadata, or with a version
6228          below ``_LAYOUT_VERSION``: zone-name bytes are replaced by 0xFF and
6229          not written;
6230        * without zone-name segment: 0xFF zone names are appended;
6231        * old 960-slot image: the missing 0x7800-0x7FFF range is inserted as
6232          empty, so channels 961-990 show as empty.
6233
6234        Finally it snapshots the APRS block and channels 961-990 so that
6235        :meth:`_write_options` can tell whether they changed.
6236
6237        Returns:
6238            None: Nothing; the result is stored in ``self._image`` (``None`` when
6239            there is no memory map or it is empty).
6240
6241        Raises:
6242            RadioError: If the image cannot be parsed.
6243        """
6244        mmap_obj = getattr(self, '_mmap', None)
6245        if mmap_obj is None:
6246            self._image = None
6247            return
6248        if hasattr(mmap_obj, 'get_packed'):
6249            data = mmap_obj.get_packed()
6250        else:
6251            data = bytes(mmap_obj)
6252        if not data:
6253            self._image = None
6254            return
6255        meta = getattr(self, '_metadata', None) or {}
6256        self._zone_names_valid = (len(data) == _SEGMENT_LENGTH
6257                                  and meta.get('rt950_layout', 0) >= _LAYOUT_VERSION)
6258        self._legacy_960 = False
6259        if len(data) == _SEGMENT_LENGTH and not self._zone_names_valid:
6260            LOG.warning('RT-950 Pro image from an older driver version: zone '
6261                        'names not valid and will not be written. Read the '
6262                        'radio again to get them.')
6263            data = bytes(data[:-ZONE_NAME_SEGMENT_BYTES]) + b'\xFF' * ZONE_NAME_SEGMENT_BYTES
6264            self._mmap = memmap.MemoryMapBytes(data)
6265        if len(data) == _MEMSIZE_V1:
6266            LOG.warning('RT-950 Pro image without zone names; names not read')
6267            data = bytes(data) + b'\xFF' * ZONE_NAME_SEGMENT_BYTES
6268            self._mmap = memmap.MemoryMapBytes(data)
6269        elif len(data) == _LEGACY_MEMSIZE:
6270            self._legacy_960 = True
6271            # Image saved by the old 960-slot driver: insert the missing
6272            # 0x7800-0x7FFF range as empty (0xFF) so offsets line up again.
6273            LOG.warning(
6274                'Legacy RT-950 Pro image (%d bytes): channels 961-990 were '
6275                'not read from the radio and are shown empty', len(data))
6276            data = (bytes(data[:LEGACY_CHANNEL_SECTION_BYTES])
6277                    + b'\xFF' * (CHANNEL_SECTION_BYTES - LEGACY_CHANNEL_SECTION_BYTES)
6278                    + bytes(data[LEGACY_CHANNEL_SECTION_BYTES:])
6279                    + b'\xFF' * ZONE_NAME_SEGMENT_BYTES)
6280            self._mmap = memmap.MemoryMapBytes(data)
6281        try:
6282            self._image = RadioImage.from_bytes(data)
6283        except ValueError as exc:
6284            raise errors.RadioError(f'Failed to parse memory map: {exc}') from exc
6285        self._memory_cache.clear()
6286        self._parse_memobj()
6287        self._log_channel_extra()
6288        try:
6289            payload = _build_clone_payload(self._image)
6290            self._aprs_original = self._aprs_bytes(payload)
6291            self._high_channels_original = bytes(
6292                payload[LEGACY_CHANNEL_SECTION_BYTES:0x7C00])
6293        # Without these snapshots the write simply skips APRS and channels
6294        # 961-990 (the safe default), so any failure here is non-fatal.
6295        except Exception:  # pylint: disable=broad-exception-caught
6296            self._aprs_original = None
6297            self._high_channels_original = None

Parse CHIRP's memory map into a RadioImage.

Also upgrades images saved by earlier driver versions:

  • full size without rt950_layout metadata, or with a version below _LAYOUT_VERSION: zone-name bytes are replaced by 0xFF and not written;
  • without zone-name segment: 0xFF zone names are appended;
  • old 960-slot image: the missing 0x7800-0x7FFF range is inserted as empty, so channels 961-990 show as empty.

Finally it snapshots the APRS block and channels 961-990 so that _write_options() can tell whether they changed.

Returns:

None: Nothing; the result is stored in self._image (None when there is no memory map or it is empty).

Raises:
  • RadioError: If the image cannot be parsed.
Public method def get_mmap(self):
6338    def get_mmap(self):  # type: ignore[override]
6339        """Return the memory map, refreshed from the current image.
6340
6341        Returns:
6342            memmap.MemoryMapBytes: ``self._mmap``, rebuilt from the image when one
6343            is loaded.
6344
6345        Raises:
6346            ValueError: If the image cannot be serialised.
6347        """
6348        self._refresh_mmap()
6349        return self._mmap

Return the memory map, refreshed from the current image.

Returns:

memmap.MemoryMapBytes: self._mmap, rebuilt from the image when one is loaded.

Raises:
  • ValueError: If the image cannot be serialised.
Public method def save_mmap(self, filename):
6351    def save_mmap(self, filename):  # type: ignore[override]
6352        """Refresh the memory map from the image, then save it as CHIRP does.
6353
6354        Args:
6355            filename: Destination ``.img`` file.
6356
6357        Returns:
6358            None: CHIRP's ``CloneModeRadio.save_mmap`` returns nothing; the
6359            ``return`` only passes that through.
6360
6361        Raises:
6362            ValueError: If the image cannot be serialised.
6363            Exception: ``"File Access Error"`` from CHIRP on an ``IOError``.
6364        """
6365        self._refresh_mmap()
6366        # pylint cannot see save_mmap on the stand-in base class.
6367        return super().save_mmap(filename)  # pylint: disable=no-member

Refresh the memory map from the image, then save it as CHIRP does.

Arguments:
  • filename: Destination .img file.
Returns:

None: CHIRP's CloneModeRadio.save_mmap returns nothing; the return only passes that through.

Raises:
  • ValueError: If the image cannot be serialised.
  • Exception: "File Access Error" from CHIRP on an IOError.
Public method def get_sub_devices(self):
6435    def get_sub_devices(self):  # type: ignore[override]
6436        """Return the zone sub-devices for the current *Channel Divide* mode.
6437
6438        Zone CH Mode: one :class:`RT950ProZoneRadio` per zone (memory tabs
6439        1-10). All CH Mode: none, because the radio then has no zones to
6440        show; CHIRP uses this object itself (memories 1-990) as the only
6441        memory list.
6442
6443        Returns:
6444            list[RT950ProZoneRadio]: Ten sub-devices, zone 1 first, or an
6445            empty list in All CH Mode.
6446        """
6447        if self._all_channels_mode():
6448            return []
6449        return [RT950ProZoneRadio(self, zone) for zone in range(1, ZONE_COUNT + 1)]

Return the zone sub-devices for the current Channel Divide mode.

Zone CH Mode: one RT950ProZoneRadio per zone (memory tabs 1-10). All CH Mode: none, because the radio then has no zones to show; CHIRP uses this object itself (memories 1-990) as the only memory list.

Returns:

list[RT950ProZoneRadio]: Ten sub-devices, zone 1 first, or an empty list in All CH Mode.

Public method def sync_in(self):
6451    def sync_in(self):  # type: ignore[override]
6452        """Download the complete image from the radio.
6453
6454        Reports progress per block through CHIRP's ``status_fn`` when
6455        available, then replaces ``self._metadata`` with
6456        ``{'rt950_layout': _LAYOUT_VERSION}`` and parses the image with
6457        :meth:`process_mmap` (which relies on that version).
6458
6459        Raises:
6460            RadioError: If no port is open, the clone read fails, or the
6461                image cannot be parsed.
6462        """
6463        if self.pipe is None:
6464            raise errors.RadioError("Serial pipe not initialised")
6465        transport = CloneSerialTransport(self.pipe, logger=LOG)
6466        # Hook progress into CHIRP status if available
6467        status = None
6468        try:
6469            status = chirp_common.Status()
6470            status.msg = "Cloning from radio…"
6471            status.max = 0
6472        # Status is optional (absent from the stand-in); clone without it.
6473        except Exception:  # pylint: disable=broad-exception-caught
6474            status = None
6475        if status is not None and hasattr(self, "status_fn"):
6476            blocks_per_segment = [seg.length // READ_BLOCK for seg in DEFAULT_SEGMENTS]
6477            seg_labels = [
6478                "Channels",
6479                "VFO settings",
6480                "Function settings",
6481                "DTMF settings",
6482                "Modulation params",
6483                "Modulation names",
6484                "APRS settings",
6485                "Zone names",
6486            ]
6487
6488            def _progress(done: int, total: int, phase: str) -> None:
6489                """Map a block count to a 'Reading ...' status message.
6490
6491                Args:
6492                    done: Blocks transferred so far (1-based count).
6493                    total: Total number of blocks in the transfer.
6494                    phase: ``"read"`` or ``"write"``; selects the message verb.
6495                """
6496                try:
6497                    block_index = max(0, int(done) - 1)
6498                    seg_idx = 0
6499                    offset_blocks = block_index
6500                    for count in blocks_per_segment:
6501                        if offset_blocks < count:
6502                            break
6503                        offset_blocks -= count
6504                        seg_idx += 1
6505                    direction = "Reading" if phase == "read" else "Writing"
6506                    if seg_idx == 0:
6507                        per_block = max(1, READ_BLOCK // CHANNEL_SIZE)
6508                        start_ch = offset_blocks * per_block + 1
6509                        end_ch = min(start_ch + per_block - 1, CHANNEL_COUNT)
6510                        status.msg = f"{direction} channels {start_ch:03d}-{end_ch:03d}…"
6511                    else:
6512                        status.msg = f"{direction} {seg_labels[seg_idx]}…"
6513                    status.cur = done
6514                    status.max = total
6515                    self.status_fn(status)
6516                # Progress reporting must never break the clone.
6517                except Exception:  # pylint: disable=broad-exception-caught
6518                    pass
6519            transport.progress_cb = _progress
6520        try:
6521            raw = transport.read_clone()
6522        except Exception as exc:
6523            raise errors.RadioError(f'Clone read failed: {exc}') from exc
6524        self._mmap = memmap.MemoryMapBytes(raw)
6525        self._metadata = {'rt950_layout': _LAYOUT_VERSION}
6526        self.process_mmap()

Download the complete image from the radio.

Reports progress per block through CHIRP's status_fn when available, then replaces self._metadata with {'rt950_layout': _LAYOUT_VERSION} and parses the image with process_mmap() (which relies on that version).

Raises:
  • RadioError: If no port is open, the clone read fails, or the image cannot be parsed.
Public method def sync_out(self):
6528    def sync_out(self):  # type: ignore[override]
6529        """Upload the image to the radio.
6530
6531        The parts written are chosen by :meth:`_write_options` and ordered by
6532        ``_WRITE_PLAN``: channels (up to 0x77FF, or 0x7BFF when channels
6533        961-990 changed), settings blocks, zone names if valid, and APRS last
6534        and only if changed.
6535
6536        Raises:
6537            RadioError: If no port or image is available or the write fails.
6538                A missing APRS acknowledgement gets its own message, because
6539                everything else was already written at that point.
6540            ValueError: If the image cannot be serialised (e.g. a DCS tone
6541                with polarity ``R``); raised before anything is sent.
6542        """
6543        if self.pipe is None:
6544            raise errors.RadioError("Serial pipe not initialised")
6545        if self._image is None:
6546            raise errors.RadioError("No image loaded")
6547        payload = _build_clone_payload(self._image)
6548        transport = CloneSerialTransport(self.pipe, logger=LOG)
6549        status = None
6550        try:
6551            status = chirp_common.Status()
6552            status.msg = "Cloning to radio…"
6553            status.max = 0
6554        # Status is optional (absent from the stand-in); clone without it.
6555        except Exception:  # pylint: disable=broad-exception-caught
6556            status = None
6557        if status is not None and hasattr(self, "status_fn"):
6558            all_labels = [
6559                "Channels",
6560                "VFO settings",
6561                "Function settings",
6562                "DTMF settings",
6563                "Modulation params",
6564                "Modulation names",
6565                "APRS settings",
6566                "Zone names",
6567            ]
6568            plan_segments, _ = _build_write_plan(payload, **self._write_options())
6569            blocks_per_segment = [seg.length // READ_BLOCK for seg in plan_segments]
6570            opts = self._write_options()
6571            seg_labels = [all_labels[index] for index, _ in _WRITE_PLAN
6572                          if (index != 7 or opts['write_zone_names'])
6573                          and (index != 6 or opts['write_aprs'])]
6574
6575            def _progress(done: int, total: int, phase: str) -> None:
6576                """Map a block count to a 'Writing ...' status message.
6577
6578                Args:
6579                    done: Blocks transferred so far (1-based count).
6580                    total: Total number of blocks in the transfer.
6581                    phase: Transfer phase from the transport; unused.
6582                """
6583                del phase  # always "write" here
6584                try:
6585                    block_index = max(0, int(done) - 1)
6586                    seg_idx = 0
6587                    offset_blocks = block_index
6588                    for count in blocks_per_segment:
6589                        if offset_blocks < count:
6590                            break
6591                        offset_blocks -= count
6592                        seg_idx += 1
6593                    if seg_idx == 0:
6594                        per_block = max(1, READ_BLOCK // CHANNEL_SIZE)
6595                        start_ch = offset_blocks * per_block + 1
6596                        end_ch = min(start_ch + per_block - 1, CHANNEL_COUNT)
6597                        status.msg = f"Writing channels {start_ch:03d}-{end_ch:03d}…"
6598                    else:
6599                        status.msg = f"Writing {seg_labels[seg_idx]}…"
6600                    status.cur = done
6601                    status.max = total
6602                    self.status_fn(status)
6603                # Progress reporting must never break the clone.
6604                except Exception:  # pylint: disable=broad-exception-caught
6605                    pass
6606            transport.progress_cb = _progress
6607        try:
6608            write_segments, write_data = _build_write_plan(
6609                payload, **self._write_options())
6610            transport.write_clone(write_data, segments=write_segments)
6611        # Any failure is reported to the user as a RadioError.
6612        except Exception as exc:  # pylint: disable=broad-exception-caught
6613            if 'cmd 0x58' in str(exc):
6614                raise errors.RadioError(
6615                    'All channels, settings and zone names were written, but the '
6616                    'radio did not acknowledge the APRS block (cmd 0x58); APRS '
6617                    'changes may NOT be saved. Power-cycle the radio and read back.') from exc
6618            raise errors.RadioError(f'Clone write failed: {exc}') from exc
6619        self._mmap = memmap.MemoryMapBytes(payload)
6620        self._parse_memobj()

Upload the image to the radio.

The parts written are chosen by _write_options() and ordered by _WRITE_PLAN: channels (up to 0x77FF, or 0x7BFF when channels 961-990 changed), settings blocks, zone names if valid, and APRS last and only if changed.

Raises:
  • RadioError: If no port or image is available or the write fails. A missing APRS acknowledgement gets its own message, because everything else was already written at that point.
  • ValueError: If the image cannot be serialised (e.g. a DCS tone with polarity R); raised before anything is sent.
Public method def get_settings(self):
6625    def get_settings(self):  # type: ignore[override]
6626        """Build the settings tree shown in CHIRP's *Settings* tab.
6627
6628        Returns:
6629            RadioSettings: VFO, modulation, function, APRS, DTMF and zone-name
6630            groups (sections absent from the image are skipped).
6631
6632        Raises:
6633            RadioError: If CHIRP is not available or no image is loaded.
6634        """
6635        _require_chirp("get_settings")
6636        image = self._require_image()
6637        groups = []
6638        if getattr(image, 'vfo', None):
6639            groups.append(_build_vfo_group(image.vfo))
6640        if getattr(image, 'modulation', None) is not None:
6641            groups.append(_build_modulation_group(image.modulation))
6642        if getattr(image, 'function', None) is not None:
6643            groups.append(_build_function_group(image.function))
6644        if getattr(image, 'aprs', None) is not None:
6645            groups.append(_build_aprs_group(image.aprs))
6646        if getattr(image, 'dtmf', None) is not None:
6647            groups.append(_build_dtmf_group(image.dtmf))
6648        groups.append(_build_zone_group(image))
6649        if not groups:
6650            return RadioSettings()
6651        return RadioSettings(*groups)

Build the settings tree shown in CHIRP's Settings tab.

Returns:

RadioSettings: VFO, modulation, function, APRS, DTMF and zone-name groups (sections absent from the image are skipped).

Raises:
  • RadioError: If CHIRP is not available or no image is loaded.
Public method def set_settings(self, settings):
6653    def set_settings(self, settings):  # type: ignore[override]
6654        """Apply edited settings to the image.
6655
6656        CHIRP passes the whole tree on every apply. The apply callback runs
6657        only for settings whose value was changed (CHIRP's
6658        ``RadioSetting.changed()``; without it, as with the stand-in classes,
6659        every callback runs). The callbacks write into the
6660        :class:`RadioImage`. Then clears the memory cache.
6661
6662        Args:
6663            settings: The tree returned by :meth:`get_settings`, edited.
6664
6665        Raises:
6666            RadioError: If no image is loaded, the container is unexpected or a
6667                callback rejects a value.
6668            ValueError: For an invalid modulation-memory frequency.
6669        """
6670        self._require_image()
6671        if not isinstance(settings, RadioSettings):
6672            raise errors.RadioError('Unexpected settings container')
6673        walker = getattr(settings, 'walk', None)
6674        if walker is None:
6675            raise errors.RadioError('Settings container missing walk()')
6676        for element in walker():
6677            if not (isinstance(element, RadioSetting) and element.has_apply_callback()):
6678                continue
6679            # CHIRP marks a value as changed once the user edits it; unchanged
6680            # settings are skipped, so a value the driver cannot show exactly
6681            # (e.g. "not set", 0xFF) is never rewritten as a default.
6682            changed = getattr(element, 'changed', None)
6683            if changed is not None and not changed():
6684                continue
6685            element.run_apply_callback()
6686        self._memory_cache.clear()

Apply edited settings to the image.

CHIRP passes the whole tree on every apply. The apply callback runs only for settings whose value was changed (CHIRP's RadioSetting.changed(); without it, as with the stand-in classes, every callback runs). The callbacks write into the RadioImage. Then clears the memory cache.

Arguments:
Raises:
  • RadioError: If no image is loaded, the container is unexpected or a callback rejects a value.
  • ValueError: For an invalid modulation-memory frequency.
Public method def get_memory(self, number: int):
6704    def get_memory(self, number: int):  # type: ignore[override]
6705        """Return memory ``number`` (1-990) as a CHIRP ``Memory``.
6706
6707        Results are cached until the memory or the settings change.
6708
6709        Args:
6710            number: Memory number, 1-990 (slot ``number - 1``).
6711
6712        Returns:
6713            chirp_common.Memory: The memory, from the cache when available.
6714
6715        Raises:
6716            RadioError: If CHIRP is not available, no image is loaded or
6717                ``number`` is out of range.
6718        """
6719        _require_chirp("get_memory")
6720        image = self._require_image()
6721        if not 1 <= number <= len(image.channels):
6722            raise errors.RadioError(f"Memory index {number} out of range")
6723        if number in self._memory_cache:
6724            return self._memory_cache[number]
6725        channel = image.channels[number - 1]
6726        mem = self._channel_to_memory(number, channel)
6727        self._memory_cache[number] = mem
6728        return mem

Return memory number (1-990) as a CHIRP Memory.

Results are cached until the memory or the settings change.

Arguments:
  • number: Memory number, 1-990 (slot number - 1).
Returns:

chirp_common.Memory: The memory, from the cache when available.

Raises:
  • RadioError: If CHIRP is not available, no image is loaded or number is out of range.
Public method def set_memory(self, mem):
6730    def set_memory(self, mem):  # type: ignore[override]
6731        """Store a CHIRP ``Memory`` in the image.
6732
6733        The sanitised result is cached and returned by later
6734        :meth:`get_memory` calls. ``mem`` is not modified, so CHIRP's
6735        ``FrozenMemory`` can be passed directly.
6736
6737        Args:
6738            mem: The CHIRP ``Memory`` to store; ``mem.number`` is 1-990.
6739
6740        Raises:
6741            RadioError: If CHIRP is not available, no image is loaded or the
6742                number is out of range.
6743        """
6744        _require_chirp("set_memory")
6745        image = self._require_image()
6746        if not 1 <= mem.number <= len(image.channels):
6747            raise errors.RadioError(f"Memory index {mem.number} out of range")
6748        channel = image.channels[mem.number - 1]
6749        self._apply_memory_to_channel(mem, channel)
6750        # The cache holds the sanitised version that get_memory() returns
6751        # from now on.
6752        sanitized = self._channel_to_memory(mem.number, channel)
6753        self._memory_cache[mem.number] = sanitized

Store a CHIRP Memory in the image.

The sanitised result is cached and returned by later get_memory() calls. mem is not modified, so CHIRP's FrozenMemory can be passed directly.

Arguments:
  • mem: The CHIRP Memory to store; mem.number is 1-990.
Raises:
  • RadioError: If CHIRP is not available, no image is loaded or the number is out of range.
Private method def _parse_memobj(self) -> None:
6299    def _parse_memobj(self) -> None:
6300        """Build the raw bitwise view for CHIRP's Browser tab (never fatal)."""
6301        try:
6302            self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
6303        # Developer view only; never fatal.
6304        except Exception as exc:  # pylint: disable=broad-exception-caught
6305            LOG.debug('Could not build raw memory view: %s', exc)
6306            self._memobj = None

Build the raw bitwise view for CHIRP's Browser tab (never fatal).

Private method def _log_channel_extra(self) -> None:
6308    def _log_channel_extra(self) -> None:
6309        """Log printable text found after the last channel record.
6310
6311        Diagnostic aid from the search for the zone-name location (now known
6312        to be 0xC000); it logs runs of three or more printable ASCII bytes in
6313        0x7BC0-0x7FFF.
6314        """
6315        if self._image is None:
6316            return
6317        extra = self._image.channel_extra
6318        run = bytearray()
6319        start = 0
6320        for idx, byte in enumerate(extra + b'\x00'):
6321            if 0x20 <= byte < 0x7F:
6322                if not run:
6323                    start = idx
6324                run.append(byte)
6325                continue
6326            if len(run) >= 3:
6327                LOG.info('Text at 0x%04X: %r', CHANNEL_DATA_BYTES + start,
6328                         run.decode('ascii'))
6329            run = bytearray()

Log printable text found after the last channel record.

Diagnostic aid from the search for the zone-name location (now known to be 0xC000); it logs runs of three or more printable ASCII bytes in 0x7BC0-0x7FFF.

Private method def _refresh_mmap(self) -> None:
6331    def _refresh_mmap(self) -> None:
6332        """Copy edits held in the :class:`RadioImage` back into CHIRP's memory map."""
6333        if self._image is None:
6334            return
6335        self._mmap = memmap.MemoryMapBytes(_build_clone_payload(self._image))
6336        self._parse_memobj()

Copy edits held in the RadioImage back into CHIRP's memory map.

Private method def _aprs_bytes(self, payload: bytes) -> bytes:
6369    def _aprs_bytes(self, payload: bytes) -> bytes:
6370        """Return the APRS block (segment 6) from a clone payload.
6371
6372        Args:
6373            payload: Clone payload in ``DEFAULT_SEGMENTS`` order.
6374
6375        Returns:
6376            bytes: The ``APRS_SEGMENT_BYTES`` (128) bytes of the APRS block.
6377        """
6378        start = sum(seg.length for seg in DEFAULT_SEGMENTS[:6])
6379        return bytes(payload[start : start + DEFAULT_SEGMENTS[6].length])

Return the APRS block (segment 6) from a clone payload.

Arguments:
Returns:

bytes: The APRS_SEGMENT_BYTES (128) bytes of the APRS block.

Private method def _write_options(self) -> dict:
6381    def _write_options(self) -> dict:
6382        """Decide which optional parts of the image to write.
6383
6384        * APRS is written only when its bytes changed since the read. The
6385          APRS commit is slow and an old write command (0x55) was never
6386          acknowledged, so it is skipped whenever possible.
6387        * 0x7800-0x7BFF holds channels 961-990 on firmware with 10x99
6388          zones, but NeonPlug reports calibration-like data there on other
6389          units. It is written only when one of channels 961-990 changed,
6390          and never for an image from the old 960-slot driver.
6391        * Zone names are written only when they were read from 0xC000.
6392
6393        Returns:
6394            dict: Keyword arguments for :func:`_build_write_plan`
6395            (``write_zone_names``, ``channel_bytes``, ``write_aprs``).
6396        """
6397        write_aprs = False
6398        channel_bytes = LEGACY_CHANNEL_SECTION_BYTES
6399        if self._image is not None:
6400            payload = _build_clone_payload(self._image)
6401            if getattr(self, '_aprs_original', None) is not None:
6402                write_aprs = self._aprs_bytes(payload) != self._aprs_original
6403            original_high = getattr(self, '_high_channels_original', None)
6404            if (original_high is not None and not getattr(self, '_legacy_960', False)
6405                    and bytes(payload[LEGACY_CHANNEL_SECTION_BYTES:0x7C00]) != original_high):
6406                channel_bytes = 0x7C00
6407        return {
6408            'write_zone_names': getattr(self, '_zone_names_valid', False),
6409            'channel_bytes': channel_bytes,
6410            'write_aprs': write_aprs,
6411        }

Decide which optional parts of the image to write.

  • APRS is written only when its bytes changed since the read. The APRS commit is slow and an old write command (0x55) was never acknowledged, so it is skipped whenever possible.
  • 0x7800-0x7BFF holds channels 961-990 on firmware with 10x99 zones, but NeonPlug reports calibration-like data there on other units. It is written only when one of channels 961-990 changed, and never for an image from the old 960-slot driver.
  • Zone names are written only when they were read from 0xC000.
Returns:

dict: Keyword arguments for _build_write_plan() (write_zone_names, channel_bytes, write_aprs).

Private method def _all_channels_mode(self) -> bool:
6413    def _all_channels_mode(self) -> bool:
6414        """Return whether the image is set to *All CH Mode*.
6415
6416        Reads the function setting ``divide_channel`` (byte 0x9026) of the
6417        loaded image. Only the value ``CHANNEL_DIVIDE_ALL`` (1) counts as
6418        All CH Mode; Zone CH Mode (0), a value that is not set (0xFF), an
6419        unknown value, a missing function block and no image at all give
6420        ``False``, i.e. the zone view.
6421
6422        Returns:
6423            bool: ``True`` for All CH Mode, otherwise ``False``.
6424        """
6425        image = self._image
6426        function = getattr(image, 'function', None) if image is not None else None
6427        if function is None:
6428            return False
6429        try:
6430            value = get_function_value(function, 'divide_channel')
6431        except KeyError:
6432            return False
6433        return value == CHANNEL_DIVIDE_ALL

Return whether the image is set to All CH Mode.

Reads the function setting divide_channel (byte 0x9026) of the loaded image. Only the value CHANNEL_DIVIDE_ALL (1) counts as All CH Mode; Zone CH Mode (0), a value that is not set (0xFF), an unknown value, a missing function block and no image at all give False, i.e. the zone view.

Returns:

bool: True for All CH Mode, otherwise False.

Private method def _require_image(self) -> RadioImage:
6691    def _require_image(self) -> RadioImage:
6692        """Return the loaded image.
6693
6694        Returns:
6695            RadioImage: The parsed clone image.
6696
6697        Raises:
6698            RadioError: If no image is loaded.
6699        """
6700        if self._image is None:
6701            raise errors.RadioError("Memory image not loaded")
6702        return self._image

Return the loaded image.

Returns:

RadioImage: The parsed clone image.

Raises:
  • RadioError: If no image is loaded.
Private method def _channel_to_memory(self, number: int, channel: ChannelRecord):
6758    def _channel_to_memory(self, number: int, channel: ChannelRecord):
6759        """Convert a channel record into a CHIRP ``Memory``.
6760
6761        Mode is ``AM`` for AM channels, otherwise ``NFM`` or ``FM`` from the
6762        bandwidth; skip is ``S`` when the channel is not in the scan list.
6763
6764        Args:
6765            number: CHIRP memory number.
6766            channel: The channel record.
6767
6768        Returns:
6769            chirp_common.Memory: The memory (``empty`` if ``rx_hz`` is ``None``).
6770        """
6771        mem = chirp_common.Memory()
6772        mem.number = number
6773        if channel.rx_hz is None:
6774            mem.empty = True
6775            return mem
6776        mem.freq = channel.rx_hz
6777        mem.empty = False
6778        mem.name = (channel.name or "").strip()
6779        self._apply_offset(mem, channel)
6780        self._apply_tones(mem, channel)
6781        if channel.rx_modulation is Modulation.AM:
6782            mem.mode = "AM"
6783        else:
6784            mem.mode = "NFM" if channel.bandwidth is Bandwidth.NARROW else "FM"
6785        mem.power = _POWER_ENUM_TO_CHIRP.get(channel.power, _CHIRP_POWER_LEVELS[0])
6786        mem.skip = "" if channel.scan_add else "S"
6787        mem.extra = _build_memory_extra(channel)
6788        return mem

Convert a channel record into a CHIRP Memory.

Mode is AM for AM channels, otherwise NFM or FM from the bandwidth; skip is S when the channel is not in the scan list.

Arguments:
  • number: CHIRP memory number.
  • channel: The channel record.
Returns:

chirp_common.Memory: The memory (empty if rx_hz is None).

Private method def _apply_offset(self, mem, channel: ChannelRecord) -> None:
6790    def _apply_offset(self, mem, channel: ChannelRecord) -> None:
6791        """Derive CHIRP duplex and offset from the RX and TX frequencies.
6792
6793        Equal or missing TX gives simplex. When RX and TX lie in different
6794        bands of ``VALID_BANDS`` (CHIRP's ``chirp_common.is_split``) the
6795        result is ``split`` with the TX frequency as offset, e.g. RX 145.5 /
6796        TX 435.0 MHz. Otherwise ``+`` or ``-`` with the difference as
6797        offset, e.g. RX 145.6 / TX 145.0 MHz gives ``-`` 600 kHz.
6798
6799        Args:
6800            mem: The CHIRP ``Memory`` to update (``duplex``, ``offset`` in Hz).
6801            channel: The channel record providing ``rx_hz`` and ``tx_hz``.
6802        """
6803        if channel.tx_hz is None or channel.tx_hz == channel.rx_hz:
6804            mem.duplex = ""
6805            mem.offset = 0
6806            return
6807        if chirp_common.is_split(VALID_BANDS, channel.rx_hz, channel.tx_hz):
6808            mem.duplex = "split"
6809            mem.offset = channel.tx_hz
6810            return
6811        diff = channel.tx_hz - channel.rx_hz
6812        mem.duplex = "+" if diff > 0 else "-"
6813        mem.offset = abs(diff)

Derive CHIRP duplex and offset from the RX and TX frequencies.

Equal or missing TX gives simplex. When RX and TX lie in different bands of VALID_BANDS (CHIRP's chirp_common.is_split) the result is split with the TX frequency as offset, e.g. RX 145.5 / TX 435.0 MHz. Otherwise + or - with the difference as offset, e.g. RX 145.6 / TX 145.0 MHz gives - 600 kHz.

Arguments:
  • mem: The CHIRP Memory to update (duplex, offset in Hz).
  • channel: The channel record providing rx_hz and tx_hz.
Private method def _apply_tones(self, mem, channel: ChannelRecord) -> None:
6815    def _apply_tones(self, mem, channel: ChannelRecord) -> None:
6816        """Translate the channel's TX/RX tones into CHIRP tone fields.
6817
6818        Uses CHIRP's ``chirp_common.split_tone_decode``: no tone gives ``""``,
6819        TX CTCSS only ``Tone``, equal TX/RX CTCSS ``TSQL``, equal TX/RX DCS
6820        code ``DTCS``, and every other combination ``Cross`` with the
6821        matching ``cross_mode`` (e.g. ``"->Tone"`` for an RX-only tone). The
6822        radio's inverted DCS polarity ``I`` is given to CHIRP as ``R``. DCS
6823        fields default to a valid code (023) when unused, because CHIRP's CSV
6824        export validates them.
6825
6826        Args:
6827            mem: The CHIRP ``Memory`` to update (``tmode``, ``cross_mode``,
6828                tones, DCS fields).
6829            channel: The channel record providing ``tx_tone`` and ``rx_tone``.
6830        """
6831        # CHIRP's CSV exporter validates DtcsCode/RxDtcsCode even when
6832        # tmode is not DTCS. Use a valid default (e.g. 023) instead of 000
6833        # to avoid exporter errors.
6834        default_dcs = chirp_common.DTCS_CODES[0]
6835        mem.dtcs = default_dcs
6836        mem.rx_dtcs = default_dcs
6837        mem.dtcs_polarity = "NN"
6838        mem.tmode = ""
6839        chirp_common.split_tone_decode(
6840            mem, _tone_to_chirp(channel.tx_tone), _tone_to_chirp(channel.rx_tone))

Translate the channel's TX/RX tones into CHIRP tone fields.

Uses CHIRP's chirp_common.split_tone_decode: no tone gives "", TX CTCSS only Tone, equal TX/RX CTCSS TSQL, equal TX/RX DCS code DTCS, and every other combination Cross with the matching cross_mode (e.g. "->Tone" for an RX-only tone). The radio's inverted DCS polarity I is given to CHIRP as R. DCS fields default to a valid code (023) when unused, because CHIRP's CSV export validates them.

Arguments:
  • mem: The CHIRP Memory to update (tmode, cross_mode, tones, DCS fields).
  • channel: The channel record providing tx_tone and rx_tone.
Private method def _apply_memory_to_channel(self, mem, channel: ChannelRecord) -> None:
6842    def _apply_memory_to_channel(self, mem, channel: ChannelRecord) -> None:
6843        """Copy a CHIRP ``Memory`` into a channel record.
6844
6845        An empty memory clears ``rx_hz``, ``tx_hz`` and ``name`` only.
6846        Otherwise frequencies, name, tones, mode, power (unchanged if the
6847        label is unknown) and skip are copied. Band rules: 118-137 MHz is
6848        forced to AM, wide, with ``tx_enabled`` cleared; 18-64 MHz is forced
6849        to FM. ``tx_enabled`` is never set back to True. Learn-FHSS and the
6850        FHSS code are cleared. Scrambler (0-8) and encryption (0-3) come from
6851        the memory's extras; missing or out-of-range values become 0.
6852
6853        Args:
6854            mem: The CHIRP memory.
6855            channel: The record to update in place.
6856        """
6857        if getattr(mem, "empty", False):
6858            channel.rx_hz = None
6859            channel.tx_hz = None
6860            channel.name = ""
6861            return
6862        channel.rx_hz = mem.freq
6863        if mem.duplex == "+":
6864            channel.tx_hz = mem.freq + mem.offset
6865        elif mem.duplex == "-":
6866            channel.tx_hz = mem.freq - mem.offset
6867        elif mem.duplex == "split":
6868            channel.tx_hz = mem.offset
6869        else:
6870            channel.tx_hz = mem.freq
6871        channel.name = (mem.name or "").strip()
6872        self._update_tones_from_memory(mem, channel)
6873
6874        extras = _extract_memory_extra(mem)
6875        scrambler_raw = extras.get('scrambler', getattr(mem, '_rt950_scrambler', None))
6876        encryption_raw = extras.get('encryption', getattr(mem, '_rt950_encryption', None))
6877        try:
6878            channel.scrambler = int(scrambler_raw)
6879        except (TypeError, ValueError):
6880            channel.scrambler = 0
6881        if channel.scrambler < 0 or channel.scrambler > 8:
6882            channel.scrambler = 0
6883        try:
6884            channel.encryption = int(encryption_raw)
6885        except (TypeError, ValueError):
6886            channel.encryption = 0
6887        if channel.encryption not in (0, 1, 2, 3):
6888            channel.encryption = 0
6889        channel.learn_fhss = False
6890        channel.fhss_code = None
6891
6892        mode = (mem.mode or "").upper()
6893        if mode not in {"AM", "FM", "NFM"}:
6894            mode = "AM" if channel.rx_modulation is Modulation.AM else "FM"
6895
6896        # Band-specific constraints
6897        freq = channel.rx_hz or 0
6898        in_airband = 118_000_000 <= freq <= 137_000_000
6899        in_low_hf = 18_000_000 <= freq <= 64_000_000
6900
6901        if in_airband:
6902            # Airband: AM only, TX disabled
6903            channel.rx_modulation = Modulation.AM
6904            channel.bandwidth = Bandwidth.WIDE
6905            channel.tx_enabled = False
6906        elif in_low_hf:
6907            # Low HF: FM only
6908            channel.rx_modulation = Modulation.FM
6909            channel.bandwidth = Bandwidth.NARROW if mode == "NFM" else Bandwidth.WIDE
6910        else:
6911            # Default behavior for VHF/UHF
6912            if mode == "AM":
6913                channel.rx_modulation = Modulation.AM
6914                channel.bandwidth = Bandwidth.WIDE
6915            else:
6916                channel.rx_modulation = Modulation.FM
6917                channel.bandwidth = Bandwidth.NARROW if mode == "NFM" else Bandwidth.WIDE
6918        if isinstance(mem.power, chirp_common.PowerLevel):
6919            key = str(mem.power).upper()
6920        elif isinstance(mem.power, str) and mem.power:
6921            key = mem.power.upper()
6922        else:
6923            key = None
6924        if key and key in _POWER_LABEL_TO_ENUM:
6925            channel.power = _POWER_LABEL_TO_ENUM[key]
6926        channel.scan_add = mem.skip != "S"

Copy a CHIRP Memory into a channel record.

An empty memory clears rx_hz, tx_hz and name only. Otherwise frequencies, name, tones, mode, power (unchanged if the label is unknown) and skip are copied. Band rules: 118-137 MHz is forced to AM, wide, with tx_enabled cleared; 18-64 MHz is forced to FM. tx_enabled is never set back to True. Learn-FHSS and the FHSS code are cleared. Scrambler (0-8) and encryption (0-3) come from the memory's extras; missing or out-of-range values become 0.

Arguments:
  • mem: The CHIRP memory.
  • channel: The record to update in place.
Private method def _update_tones_from_memory(self, mem, channel: ChannelRecord) -> None:
6928    def _update_tones_from_memory(self, mem, channel: ChannelRecord) -> None:
6929        """Translate CHIRP tone fields into the channel's TX/RX tones.
6930
6931        Uses CHIRP's ``chirp_common.split_tone_encode``, so every tone mode
6932        including ``Cross`` is honoured (``TSQL`` uses ``ctone`` for TX and
6933        RX, as in CHIRP). CHIRP's reverse polarity ``R`` is stored as the
6934        radio's ``I``. A DCS code of 0 is stored as no tone. ``mem`` is not
6935        modified.
6936
6937        Args:
6938            mem: The CHIRP ``Memory`` to read.
6939            channel: The channel record whose ``tx_tone``/``rx_tone`` are replaced.
6940        """
6941        tx_spec, rx_spec = chirp_common.split_tone_encode(mem)
6942        channel.tx_tone = _tone_from_chirp(*tx_spec)
6943        channel.rx_tone = _tone_from_chirp(*rx_spec)

Translate CHIRP tone fields into the channel's TX/RX tones.

Uses CHIRP's chirp_common.split_tone_encode, so every tone mode including Cross is honoured (TSQL uses ctone for TX and RX, as in CHIRP). CHIRP's reverse polarity R is stored as the radio's I. A DCS code of 0 is stored as no tone. mem is not modified.

Arguments:
  • mem: The CHIRP Memory to read.
  • channel: The channel record whose tx_tone/rx_tone are replaced.
Public class class RT950ProZoneRadio(RT950ProRadio):
6945class RT950ProZoneRadio(RT950ProRadio):  # pylint: disable=too-many-ancestors
6946    """One zone of the radio, shown by CHIRP as its own memory tab.
6947
6948    Memory *n* (1-99) in zone *z* is channel ``(z - 1) * 99 + n`` of the
6949    parent radio. All data lives in the parent's :class:`RadioImage`; this
6950    object only maps memory numbers and delegates everything else.
6951    """
6952
6953    # Deliberately no super().__init__(): there is no pipe or file here.
6954    def __init__(  # pylint: disable=super-init-not-called
6955            self, parent: "RT950ProRadio", zone: int) -> None:
6956        """Create the sub-device for one zone.
6957
6958        Args:
6959            parent: The radio that owns the image.
6960            zone: Zone number, 1-10.
6961        """
6962        self._parent = parent
6963        """The radio that owns the image and does all reading and writing."""
6964        self._zone = zone
6965        """Zone number, 1-10."""
6966        self._first = (zone - 1) * ZONE_SIZE
6967        """Offset added to a zone memory number (1-99) to get the parent's
6968        memory number: ``(zone - 1) * 99``."""
6969        self.VARIANT = _zone_label(  # pylint: disable=invalid-name
6970            parent._image, zone)
6971        """Tab title suffix shown by CHIRP (``"1 VHF-LOCAL"``, or ``"Zone 1"``
6972        when unnamed); fixed when the sub-device is created."""
6973        # The attributes below are normally set by CHIRP's constructor,
6974        # which is deliberately not called (see above).
6975        self.pipe = None
6976        """No serial port of its own (CHIRP attribute); the parent talks to
6977        the radio."""
6978        self._mmap = None
6979        """No memory map of its own (CHIRP attribute); see :meth:`get_mmap`."""
6980        self._memobj = None
6981        """No raw memory view of its own (CHIRP attribute)."""
6982        self._metadata = {}
6983        """Empty metadata (CHIRP attribute); CHIRP replaces it with the
6984        parent's ``_metadata[VARIANT]`` via ``link_device_metadata``."""
6985        self._memory_cache = parent._memory_cache
6986        """The parent's memory cache, shared so both views stay in step."""
6987        self.errors = []
6988        """Error list that CHIRP expects on every radio object (CHIRP attribute)."""
6989
6990    @property
6991    def _image(self):  # type: ignore[override]
6992        """Return the parent's image; this sub-device has none of its own."""
6993        return self._parent._image
6994
6995    @_image.setter
6996    def _image(self, value):
6997        """Ignore assignments; the image is owned by the parent radio.
6998
6999        Args:
7000            value: Assigned value; discarded.
7001        """
7002        del value
7003
7004    def get_features(self):  # type: ignore[override]
7005        """Return the parent's features limited to one zone (memories 1-99).
7006
7007        Returns:
7008            chirp_common.RadioFeatures: The parent's features with memory bounds
7009            1-99 and no sub-devices (static or dynamic) or settings.
7010
7011        Raises:
7012            RadioError: If CHIRP is not available.
7013        """
7014        rf = super().get_features()
7015        rf.memory_bounds = (1, ZONE_SIZE)
7016        rf.has_sub_devices = False
7017        if hasattr(rf, 'has_dynamic_subdevices'):
7018            rf.has_dynamic_subdevices = False
7019        rf.has_settings = False
7020        return rf
7021
7022    def get_sub_devices(self):  # type: ignore[override]
7023        """Return no sub-devices; a zone has no zones of its own.
7024
7025        Returns:
7026            list: An empty list.
7027        """
7028        return []
7029
7030    def get_memory(self, number: int):  # type: ignore[override]
7031        """Return memory ``number`` (1-99) of this zone.
7032
7033        Args:
7034            number: Memory number within the zone, 1-99.
7035
7036        Returns:
7037            chirp_common.Memory: A copy of the parent's memory, renumbered to
7038            ``number``.
7039
7040        Raises:
7041            RadioError: If CHIRP is not available, ``number`` is out of range
7042                or no image is loaded.
7043        """
7044        _require_chirp("get_memory")
7045        if not 1 <= number <= ZONE_SIZE:
7046            raise errors.RadioError(f"Memory {number} out of range 1-{ZONE_SIZE}")
7047        mem = self._parent.get_memory(self._first + number).dupe()
7048        mem.number = number
7049        return mem
7050
7051    def set_memory(self, mem):  # type: ignore[override]
7052        """Store ``mem`` (numbered 1-99) in this zone via the parent.
7053
7054        Args:
7055            mem: The CHIRP ``Memory`` to store; it is copied, not modified.
7056
7057        Raises:
7058            RadioError: If CHIRP is not available, the number is out of range
7059                or no image is loaded.
7060        """
7061        _require_chirp("set_memory")
7062        if not 1 <= mem.number <= ZONE_SIZE:
7063            raise errors.RadioError(f"Memory {mem.number} out of range 1-{ZONE_SIZE}")
7064        # CHIRP passes a frozen Memory: never modify it, work on a copy.
7065        glob = mem.dupe()
7066        glob.number = self._first + mem.number
7067        self._parent.set_memory(glob)
7068
7069    def get_mmap(self):  # type: ignore[override]
7070        """Return the parent's memory map.
7071
7072        Returns:
7073            memmap.MemoryMapBytes: The result of the parent's :meth:`get_mmap`.
7074        """
7075        return self._parent.get_mmap()
7076
7077    def save_mmap(self, filename):  # type: ignore[override]
7078        """Save the parent's image.
7079
7080        Args:
7081            filename: Destination ``.img`` file.
7082
7083        Returns:
7084            None: The parent's :meth:`save_mmap` returns nothing.
7085        """
7086        return self._parent.save_mmap(filename)

One zone of the radio, shown by CHIRP as its own memory tab.

Memory n (1-99) in zone z is channel (z - 1) * 99 + n of the parent radio. All data lives in the parent's RadioImage; this object only maps memory numbers and delegates everything else.

Constructor
Public constructor RT950ProZoneRadio(parent: RT950ProRadio, zone: int)
6954    def __init__(  # pylint: disable=super-init-not-called
6955            self, parent: "RT950ProRadio", zone: int) -> None:
6956        """Create the sub-device for one zone.
6957
6958        Args:
6959            parent: The radio that owns the image.
6960            zone: Zone number, 1-10.
6961        """
6962        self._parent = parent
6963        """The radio that owns the image and does all reading and writing."""
6964        self._zone = zone
6965        """Zone number, 1-10."""
6966        self._first = (zone - 1) * ZONE_SIZE
6967        """Offset added to a zone memory number (1-99) to get the parent's
6968        memory number: ``(zone - 1) * 99``."""
6969        self.VARIANT = _zone_label(  # pylint: disable=invalid-name
6970            parent._image, zone)
6971        """Tab title suffix shown by CHIRP (``"1 VHF-LOCAL"``, or ``"Zone 1"``
6972        when unnamed); fixed when the sub-device is created."""
6973        # The attributes below are normally set by CHIRP's constructor,
6974        # which is deliberately not called (see above).
6975        self.pipe = None
6976        """No serial port of its own (CHIRP attribute); the parent talks to
6977        the radio."""
6978        self._mmap = None
6979        """No memory map of its own (CHIRP attribute); see :meth:`get_mmap`."""
6980        self._memobj = None
6981        """No raw memory view of its own (CHIRP attribute)."""
6982        self._metadata = {}
6983        """Empty metadata (CHIRP attribute); CHIRP replaces it with the
6984        parent's ``_metadata[VARIANT]`` via ``link_device_metadata``."""
6985        self._memory_cache = parent._memory_cache
6986        """The parent's memory cache, shared so both views stay in step."""
6987        self.errors = []
6988        """Error list that CHIRP expects on every radio object (CHIRP attribute)."""

Create the sub-device for one zone.

Arguments:
  • parent: The radio that owns the image.
  • zone: Zone number, 1-10.
Fields
Public field VARIANT

Tab title suffix shown by CHIRP ("1 VHF-LOCAL", or "Zone 1" when unnamed); fixed when the sub-device is created.

Public field pipe

No serial port of its own (CHIRP attribute); the parent talks to the radio.

Public field errors

Error list that CHIRP expects on every radio object (CHIRP attribute).

Private field _parent

The radio that owns the image and does all reading and writing.

Private field _zone

Zone number, 1-10.

Private field _first

Offset added to a zone memory number (1-99) to get the parent's memory number: (zone - 1) * 99.

Private field _mmap

No memory map of its own (CHIRP attribute); see get_mmap().

Private field _memobj

No raw memory view of its own (CHIRP attribute).

Private field _metadata

Empty metadata (CHIRP attribute); CHIRP replaces it with the parent's _metadata[VARIANT] via link_device_metadata.

Private field _memory_cache

The parent's memory cache, shared so both views stay in step.

Properties
Private property _image
6990    @property
6991    def _image(self):  # type: ignore[override]
6992        """Return the parent's image; this sub-device has none of its own."""
6993        return self._parent._image

Parsed clone image; the single source of all channel and settings data. None until an image is downloaded or loaded.

Methods
Public method def get_features(self):
7004    def get_features(self):  # type: ignore[override]
7005        """Return the parent's features limited to one zone (memories 1-99).
7006
7007        Returns:
7008            chirp_common.RadioFeatures: The parent's features with memory bounds
7009            1-99 and no sub-devices (static or dynamic) or settings.
7010
7011        Raises:
7012            RadioError: If CHIRP is not available.
7013        """
7014        rf = super().get_features()
7015        rf.memory_bounds = (1, ZONE_SIZE)
7016        rf.has_sub_devices = False
7017        if hasattr(rf, 'has_dynamic_subdevices'):
7018            rf.has_dynamic_subdevices = False
7019        rf.has_settings = False
7020        return rf

Return the parent's features limited to one zone (memories 1-99).

Returns:

chirp_common.RadioFeatures: The parent's features with memory bounds 1-99 and no sub-devices (static or dynamic) or settings.

Raises:
  • RadioError: If CHIRP is not available.
Public method def get_sub_devices(self):
7022    def get_sub_devices(self):  # type: ignore[override]
7023        """Return no sub-devices; a zone has no zones of its own.
7024
7025        Returns:
7026            list: An empty list.
7027        """
7028        return []

Return no sub-devices; a zone has no zones of its own.

Returns:

list: An empty list.

Public method def get_memory(self, number: int):
7030    def get_memory(self, number: int):  # type: ignore[override]
7031        """Return memory ``number`` (1-99) of this zone.
7032
7033        Args:
7034            number: Memory number within the zone, 1-99.
7035
7036        Returns:
7037            chirp_common.Memory: A copy of the parent's memory, renumbered to
7038            ``number``.
7039
7040        Raises:
7041            RadioError: If CHIRP is not available, ``number`` is out of range
7042                or no image is loaded.
7043        """
7044        _require_chirp("get_memory")
7045        if not 1 <= number <= ZONE_SIZE:
7046            raise errors.RadioError(f"Memory {number} out of range 1-{ZONE_SIZE}")
7047        mem = self._parent.get_memory(self._first + number).dupe()
7048        mem.number = number
7049        return mem

Return memory number (1-99) of this zone.

Arguments:
  • number: Memory number within the zone, 1-99.
Returns:

chirp_common.Memory: A copy of the parent's memory, renumbered to number.

Raises:
  • RadioError: If CHIRP is not available, number is out of range or no image is loaded.
Public method def set_memory(self, mem):
7051    def set_memory(self, mem):  # type: ignore[override]
7052        """Store ``mem`` (numbered 1-99) in this zone via the parent.
7053
7054        Args:
7055            mem: The CHIRP ``Memory`` to store; it is copied, not modified.
7056
7057        Raises:
7058            RadioError: If CHIRP is not available, the number is out of range
7059                or no image is loaded.
7060        """
7061        _require_chirp("set_memory")
7062        if not 1 <= mem.number <= ZONE_SIZE:
7063            raise errors.RadioError(f"Memory {mem.number} out of range 1-{ZONE_SIZE}")
7064        # CHIRP passes a frozen Memory: never modify it, work on a copy.
7065        glob = mem.dupe()
7066        glob.number = self._first + mem.number
7067        self._parent.set_memory(glob)

Store mem (numbered 1-99) in this zone via the parent.

Arguments:
  • mem: The CHIRP Memory to store; it is copied, not modified.
Raises:
  • RadioError: If CHIRP is not available, the number is out of range or no image is loaded.
Public method def get_mmap(self):
7069    def get_mmap(self):  # type: ignore[override]
7070        """Return the parent's memory map.
7071
7072        Returns:
7073            memmap.MemoryMapBytes: The result of the parent's :meth:`get_mmap`.
7074        """
7075        return self._parent.get_mmap()

Return the parent's memory map.

Returns:

memmap.MemoryMapBytes: The result of the parent's get_mmap().

Public method def save_mmap(self, filename):
7077    def save_mmap(self, filename):  # type: ignore[override]
7078        """Save the parent's image.
7079
7080        Args:
7081            filename: Destination ``.img`` file.
7082
7083        Returns:
7084            None: The parent's :meth:`save_mmap` returns nothing.
7085        """
7086        return self._parent.save_mmap(filename)

Save the parent's image.

Arguments:
  • filename: Destination .img file.
Returns:

None: The parent's save_mmap() returns nothing.

Public class
@directory.register
class RT950ProDriver(RT950ProRadio):
7089@directory.register
7090class RT950ProDriver(RT950ProRadio):  # pylint: disable=too-many-ancestors
7091    """The class registered in CHIRP's driver directory.
7092
7093    :class:`RT950ProRadio` itself is not registered; it is the shared base
7094    of this class and of :class:`RT950ProZoneRadio`.
7095    """

The class registered in CHIRP's driver directory.

RT950ProRadio itself is not registered; it is the shared base of this class and of RT950ProZoneRadio.

Private function def _zone_label(image, zone: int) -> str:
5937def _zone_label(image, zone: int) -> str:
5938    """Build the memory-tab label for one zone.
5939
5940    Args:
5941        image: The parent's :class:`RadioImage`, or ``None``.
5942        zone: Zone number, 1-10.
5943
5944    Returns:
5945        str: ``"1 VHF-LOCAL"`` for a named zone, ``"Zone 1"`` otherwise.
5946    """
5947    names = ((image.zone_names if image is not None else None)
5948             or [""] * ZONE_COUNT)
5949    name = names[zone - 1]
5950    return f"{zone} {name}" if name else f"Zone {zone}"

Build the memory-tab label for one zone.

Arguments:
  • image: The parent's RadioImage, or None.
  • zone: Zone number, 1-10.
Returns:

str: "1 VHF-LOCAL" for a named zone, "Zone 1" otherwise.

Private function def _apply_zone_name(rsetting, image, index):
5953def _apply_zone_name(rsetting, image, index):
5954    """Settings callback: store an edited zone name in the image.
5955
5956    A value equal to the stored name is left as it is (also a stored name
5957    longer than ``ZONE_NAME_LENGTH``). Otherwise surrounding spaces are
5958    stripped, non-ASCII characters are dropped and the result is cut to
5959    ``ZONE_NAME_LENGTH`` (12). ``image.zone_names`` is
5960    created (ten empty names) if it is ``None``.
5961
5962    Args:
5963        rsetting: The CHIRP ``RadioSetting`` holding the new name.
5964        image: The :class:`RadioImage` to update.
5965        index: Zone index, 0-9.
5966
5967    Returns:
5968        None: Nothing; ``image.zone_names`` is updated in place.
5969    """
5970    if image.zone_names is None:
5971        image.zone_names = [""] * ZONE_COUNT
5972    value = str(rsetting.value).strip()
5973    if value == image.zone_names[index]:
5974        return
5975    image.zone_names[index] = value.encode("ascii", errors="ignore").decode()[:ZONE_NAME_LENGTH]

Settings callback: store an edited zone name in the image.

A value equal to the stored name is left as it is (also a stored name longer than ZONE_NAME_LENGTH). Otherwise surrounding spaces are stripped, non-ASCII characters are dropped and the result is cut to ZONE_NAME_LENGTH (12). image.zone_names is created (ten empty names) if it is None.

Arguments:
  • rsetting: The CHIRP RadioSetting holding the new name.
  • image: The RadioImage to update.
  • index: Zone index, 0-9.
Returns:

None: Nothing; image.zone_names is updated in place.

Private function def _build_zone_group(image):
5978def _build_zone_group(image):
5979    """Build the *Zone Names* settings group (one string per zone).
5980
5981    Each field accepts ``ZONE_NAME_LENGTH`` (12) characters, or more when the
5982    stored name is already longer (up to the 16-byte slot).
5983
5984    Args:
5985        image: The :class:`RadioImage` providing the current names.
5986
5987    Returns:
5988        RadioSettingGroup: Ten string settings wired to
5989        :func:`_apply_zone_name`.
5990    """
5991    group = RadioSettingGroup('zones', 'Zone Names')
5992    names = image.zone_names or [""] * ZONE_COUNT
5993    for index in range(ZONE_COUNT):
5994        # A name longer than ZONE_NAME_LENGTH (written by other software; the
5995        # slot holds 16 bytes) must still load, so allow its own length.
5996        maximum = max(ZONE_NAME_LENGTH, len(names[index]))
5997        value = RadioSettingValueString(0, maximum, names[index],
5998                                        autopad=False,
5999                                        charset=chirp_common.CHARSET_ASCII)
6000        setting = RadioSetting(f'zone_name_{index + 1}',
6001                               f'Zone {index + 1} name', value)
6002        setting.set_apply_callback(_apply_zone_name, image, index)
6003        group.append(setting)
6004    return group

Build the Zone Names settings group (one string per zone).

Each field accepts ZONE_NAME_LENGTH (12) characters, or more when the stored name is already longer (up to the 16-byte slot).

Arguments:
  • image: The RadioImage providing the current names.
Returns:

RadioSettingGroup: Ten string settings wired to _apply_zone_name().

Private function def _tone_to_chirp(tone: ToneSetting) -> tuple:
6007def _tone_to_chirp(tone: ToneSetting) -> tuple:
6008    """Convert a radio tone into a CHIRP tone spec for ``split_tone_decode``.
6009
6010    Args:
6011        tone: The radio tone.
6012
6013    Returns:
6014        tuple: ``(mode, value, polarity)``: ``("", None, None)`` for no tone,
6015        ``("Tone", hz, None)`` for CTCSS, ``("DTCS", code, "N" or "R")`` for
6016        DCS (the radio's inverted ``I`` becomes CHIRP's reverse ``R``).
6017    """
6018    if tone.mode is ToneMode.CTCSS and tone.ctcss_hz is not None:
6019        return ("Tone", tone.ctcss_hz, None)
6020    if tone.mode is ToneMode.DCS and tone.dcs_code is not None:
6021        polarity = "R" if (tone.dcs_polarity or "N").upper() == "I" else "N"
6022        return ("DTCS", tone.dcs_code, polarity)
6023    return ("", None, None)

Convert a radio tone into a CHIRP tone spec for split_tone_decode.

Arguments:
  • tone: The radio tone.
Returns:

tuple: (mode, value, polarity): ("", None, None) for no tone, ("Tone", hz, None) for CTCSS, ("DTCS", code, "N" or "R") for DCS (the radio's inverted I becomes CHIRP's reverse R).

Private function def _tone_from_chirp(mode: str, value, polarity) -> ToneSetting:
6026def _tone_from_chirp(mode: str, value, polarity) -> ToneSetting:
6027    """Convert one CHIRP tone spec from ``split_tone_encode`` into a radio tone.
6028
6029    Args:
6030        mode: ``"Tone"``, ``"DTCS"`` or ``""``.
6031        value: CTCSS frequency in Hz or DCS code; a DCS code of 0 or a
6032            missing value gives no tone.
6033        polarity: CHIRP DCS polarity ``"N"`` or ``"R"`` (stored as ``"I"``),
6034            or ``None``.
6035
6036    Returns:
6037        ToneSetting: The radio tone.
6038    """
6039    if mode == "Tone" and value:
6040        return ToneSetting.ctcss(float(value))
6041    if mode == "DTCS" and value:
6042        return ToneSetting.dcs(int(value), "I" if (polarity or "N").upper() == "R" else "N")
6043    return ToneSetting.off()

Convert one CHIRP tone spec from split_tone_encode into a radio tone.

Arguments:
  • mode: "Tone", "DTCS" or "".
  • value: CTCSS frequency in Hz or DCS code; a DCS code of 0 or a missing value gives no tone.
  • polarity: CHIRP DCS polarity "N" or "R" (stored as "I"), or None.
Returns:

ToneSetting: The radio tone.

Public constant VALID_BANDS: Tuple[Tuple[int, int], ...] = ((18000000, 64000000), (118000000, 137000000), (70000000, 118000000), (136000000, 174000000), (174000000, 400000000), (400000000, 480000000), (480000000, 580000000))

Frequency bands offered to CHIRP, as (low, high) in Hz.

is_split treats high as inclusive, CHIRP's validate_memory as exclusive.

Used for RadioFeatures.valid_bands and to decide when a channel is shown as split: RX and TX not inside one common band (CHIRP's chirp_common.is_split). The bands are the driver's, not the amateur bands: 136-174 MHz and 174-400 MHz are each one band, so RX 145 MHz with TX 222 MHz is split, RX 145.6 with TX 145.0 MHz is not. The bands overlap at 136-137 MHz.

Public constant MEM_FORMAT = '\nstruct {\n u8 rx_freq[4];\n u8 tx_freq[4];\n u8 rx_tone[2];\n u8 tx_tone[2];\n u8 signalling_group;\n u8 ptt_id;\n u8 scram_power;\n u8 flags;\n u8 fhss_code[4];\n char name[12];\n} channels[990];\nu8 channel_extra[1088]; // up to 0x8000\nu8 vfo[0x100];\nu8 function[0x100];\nu8 dtmf[0x200];\nu8 modulation_params[0x200];\nu8 modulation_names[0x300];\nu8 aprs[0x80];\nstruct {\n char name[12];\n u8 unused[4];\n} zone_names[10];\nu8 zone_names_pad[0x60];\n'

CHIRP bitwise layout of the clone image.

Used only for CHIRP's developer-mode Browser tab; the driver itself works on RadioImage. % formatting is used because the layout contains literal braces.

Private constant _MEMSIZE_V1 = 35200

Image size of driver versions with 990 channels but no zone names.

Private constant _LEGACY_MEMSIZE = 33152

Image size of the old 960-slot driver (channel segment 0x7800 bytes).

Private constant DRIVER_CLASS = <class 'RT950ProDriver'>

Entry point used by loaders that look for a DRIVER_CLASS name.