diff options
76 files changed, 4691 insertions, 645 deletions
@@ -1,6 +1,6 @@ Metadata-Version: 2.4 Name: chirp -Version: 20250502 +Version: 20250912 Summary: A cross-platform cross-radio programming tool Home-page: https://chirp.danplanet.com Requires-Python: >=3.10,<4 diff --git a/chirp.egg-info/PKG-INFO b/chirp.egg-info/PKG-INFO index 5bef572..bf281ef 100644 --- a/chirp.egg-info/PKG-INFO +++ b/chirp.egg-info/PKG-INFO @@ -1,6 +1,6 @@ Metadata-Version: 2.4 Name: chirp -Version: 20250502 +Version: 20250912 Summary: A cross-platform cross-radio programming tool Home-page: https://chirp.danplanet.com Requires-Python: >=3.10,<4 diff --git a/chirp.egg-info/SOURCES.txt b/chirp.egg-info/SOURCES.txt index cd03bcd..8ec7a33 100644 --- a/chirp.egg-info/SOURCES.txt +++ b/chirp.egg-info/SOURCES.txt @@ -15,7 +15,6 @@ chirp/bandplan_na.py chirp/bitwise.py chirp/bitwise_grammar.py chirp/chirp_common.py -chirp/detect.py chirp/directory.py chirp/errors.py chirp/import_logic.py @@ -142,10 +141,14 @@ chirp/drivers/mml_jc8810.py chirp/drivers/mursv1.py chirp/drivers/puxing.py chirp/drivers/puxing_px888k.py +chirp/drivers/radioddity_gm30.py chirp/drivers/radioddity_r2.py chirp/drivers/radtel_rt490.py chirp/drivers/radtel_rt620.py chirp/drivers/radtel_t18.py +chirp/drivers/retevis_h777v4.py +chirp/drivers/retevis_ra25.py +chirp/drivers/retevis_ra86.py chirp/drivers/retevis_ra87.py chirp/drivers/retevis_rb15.py chirp/drivers/retevis_rb17p.py @@ -289,6 +292,7 @@ chirp/wxui/query_sources.py chirp/wxui/radioinfo.py chirp/wxui/radiothread.py chirp/wxui/report.py +chirp/wxui/serialtrace.py chirp/wxui/settingsedit.py tests/__init__.py tests/base.py @@ -375,7 +379,9 @@ tests/images/Baofeng_UV-17.img tests/images/Baofeng_UV-17Pro.img tests/images/Baofeng_UV-17ProGPS.img tests/images/Baofeng_UV-3R.img +tests/images/Baofeng_UV-5G_Pro.img tests/images/Baofeng_UV-5R.img +tests/images/Baofeng_UV-5R_Mini.img tests/images/Baofeng_UV-6R.img tests/images/Baofeng_UV-9G.img tests/images/Baofeng_UV-B5.img @@ -433,6 +439,7 @@ tests/images/Kenwood_TH-D72_clone_mode.img tests/images/Kenwood_TH-D74_clone_mode.img tests/images/Kenwood_TH-D75.img tests/images/Kenwood_TK-272G.img +tests/images/Kenwood_TK-278.img tests/images/Kenwood_TK-280.img tests/images/Kenwood_TK-3140K.img tests/images/Kenwood_TK-3180K2.img @@ -471,6 +478,7 @@ tests/images/Quansheng_UV-K5.img tests/images/Quansheng_UV-K5_egzumer.img tests/images/Radioddity_GA-510.img tests/images/Radioddity_GA-510_V2.img +tests/images/Radioddity_GM-30.img tests/images/Radioddity_GS-5B.img tests/images/Radioddity_R2.img tests/images/Radioddity_UV-5G.img @@ -486,11 +494,14 @@ tests/images/Radtel_RT-730.img tests/images/Radtel_T18.img tests/images/Retevis_H777H_FRS.img tests/images/Retevis_H777S.img +tests/images/Retevis_H777_V4.img tests/images/Retevis_P2.img tests/images/Retevis_P62.img +tests/images/Retevis_RA25.img tests/images/Retevis_RA685.img tests/images/Retevis_RA79.img tests/images/Retevis_RA85.img +tests/images/Retevis_RA86.img tests/images/Retevis_RA87.img tests/images/Retevis_RA89.img tests/images/Retevis_RB15.img @@ -547,6 +558,7 @@ tests/images/Retevis_RT668.img tests/images/Retevis_RT68.img tests/images/Retevis_RT76.img tests/images/Retevis_RT86.img +tests/images/Retevis_RT86S.img tests/images/Retevis_RT87.img tests/images/Retevis_RT9000D_136-174.img tests/images/Retevis_RT9000D_220-260.img @@ -663,6 +675,7 @@ tests/unit/test_logger.py tests/unit/test_mappingmodel.py tests/unit/test_network_sources.py tests/unit/test_repeaterbook.py +tests/unit/test_serialtrace.py tests/unit/test_settings.py tests/unit/test_th9800.py tests/unit/test_util.py @@ -688,6 +701,7 @@ tests/unit/__pycache__/test_logger.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_mappingmodel.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_network_sources.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc +tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_settings.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_th9800.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_util.cpython-310-pytest-7.1.3.pyc @@ -696,7 +710,6 @@ tests/unit/__pycache__/test_wxui_radiothread.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_yaesu_clone.cpython-310-pytest-7.1.3.pyc tools/Makefile tools/check_commit.sh -tools/check_for_bug.sh tools/checkpatch.sh tools/cpep8.blacklist tools/cpep8.exceptions diff --git a/chirp/__init__.py b/chirp/__init__.py index 91b58cc..31b111c 100644 --- a/chirp/__init__.py +++ b/chirp/__init__.py @@ -1 +1 @@ -CHIRP_VERSION = "next-20250502" +CHIRP_VERSION = "next-20250912" diff --git a/chirp/bitwise.py b/chirp/bitwise.py index 53581bd..e595f1b 100644 --- a/chirp/bitwise.py +++ b/chirp/bitwise.py @@ -701,6 +701,10 @@ class charDataElement(DataElement): class bcdDataElement(DataElement): + def __init__(self, *a, **k): + super().__init__(*a, **k) + self._ignoremask = 0x00 + def __int__(self): tens, ones = self.get_value() return (tens * 10) + ones @@ -714,6 +718,9 @@ class bcdDataElement(DataElement): def get_bits(self, mask): return ord(self._data[self._offset]) & int(mask) + def ignore_bits(self, mask): + self._ignoremask = mask + def set_raw(self, data): if isinstance(data, int): self._data[self._offset] = data & 0xFF @@ -728,11 +735,14 @@ class bcdDataElement(DataElement): type(data)) def set_value(self, value): - self._data[self._offset] = int("%02i" % value, 16) + preserve = self._data[self._offset][0] & self._ignoremask + self._data[self._offset] = ( + int("%02i" % value, 16) & ~self._ignoremask) | preserve def _get_value(self, data): - a = (ord(data) & 0xF0) >> 4 - b = ord(data) & 0x0F + data = data[0] & ~self._ignoremask + a = (data & 0xF0) >> 4 + b = data & 0x0F return (a, b) @@ -826,12 +836,13 @@ class structDataElement(DataElement): self._generators[key] = value self._keys.append(key) + def __dir__(self): + return list(super().__dir__()) + list(self._generators.keys()) + def __getattr__(self, name): try: return self._generators[name] except KeyError: - LOG.error('Request for struct element %s not in %s' % ( - name, self._generators.keys())) raise AttributeError("No attribute %s in struct %s" % ( name, self._name)) diff --git a/chirp/cli/experttune.py b/chirp/cli/experttune.py index e256c4b..ac54338 100644 --- a/chirp/cli/experttune.py +++ b/chirp/cli/experttune.py @@ -1,4 +1,4 @@ -#!/bin/env python3 +#!/usr/bin/env python3 import argparse import contextlib diff --git a/chirp/detect.py b/chirp/detect.py deleted file mode 100644 index 9f97a31..0000000 --- a/chirp/detect.py +++ /dev/null @@ -1,127 +0,0 @@ -# Copyright 2010 Dan Smith <dsmith@danplanet.com> -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see <http://www.gnu.org/licenses/>. - -import serial -import logging - -from chirp import chirp_common, errors, directory -from chirp.drivers import ic9x_ll, icf, kenwood_live, icomciv - -LOG = logging.getLogger(__name__) - - -class DetectorRadio(chirp_common.Radio): - """Minimal radio for model detection""" - - def get_payload(self, data, raw, checksum): - return data - - -def _icom_model_data_to_rclass(md): - for _rtype, rclass in list(directory.DRV_TO_RADIO.items()): - if rclass.VENDOR != "Icom": - continue - if not hasattr(rclass, 'get_model') or not rclass.get_model(): - continue - if rclass.get_model()[:4] == md[:4]: - return rclass - - raise errors.RadioError("Unknown radio type %02x%02x%02x%02x" % - (ord(md[0]), ord(md[1]), ord(md[2]), ord(md[3]))) - - -def _detect_icom_radio(ser): - # ICOM VHF/UHF Clone-type radios @ 9600 baud - - try: - ser.baudrate = 9600 - md = icf.get_model_data(DetectorRadio(ser)) - return _icom_model_data_to_rclass(md) - except errors.RadioError as e: - LOG.error("_detect_icom_radio: %s", e) - - # ICOM IC-91/92 Live-mode radios @ 4800/38400 baud - - ser.baudrate = 4800 - try: - ic9x_ll.send_magic(ser) - return _icom_model_data_to_rclass("ic9x") - except errors.RadioError: - pass - - # ICOM CI/V Radios @ various bauds - - for rate in [9600, 4800, 19200]: - try: - ser.baudrate = rate - return icomciv.probe_model(ser) - except errors.RadioError: - pass - - ser.close() - - raise errors.RadioError("Unable to get radio model") - - -def detect_icom_radio(port): - """Detect which Icom model is connected to @port""" - if '://' in port: - ser = serial.serial_for_url(port, do_not_open=True) - ser.timeout = 0.5 - ser.open() - else: - ser = serial.Serial(port=port, timeout=0.5) - - try: - result = _detect_icom_radio(ser) - except Exception: - ser.close() - raise - - ser.close() - - LOG.info("Auto-detected %s %s on %s" % - (result.VENDOR, result.MODEL, port)) - - return result - - -def detect_kenwoodlive_radio(port): - """Detect which Kenwood model is connected to @port""" - if '://' in port: - ser = serial.serial_for_url(port, do_not_open=True) - ser.timeout = 0.5 - ser.open() - else: - ser = serial.Serial(port=port, baudrate=9600, timeout=0.5) - - r_id = kenwood_live.get_id(ser) - ser.close() - - models = {} - for rclass in list(directory.DRV_TO_RADIO.values()): - if rclass.VENDOR == "Kenwood": - models[rclass.MODEL] = rclass - - if r_id in list(models.keys()): - return models[r_id] - else: - raise errors.RadioError("Unsupported model `%s'" % r_id) - - -DETECT_FUNCTIONS = { - "Icom": detect_icom_radio, - "Kenwood": detect_kenwoodlive_radio, -} diff --git a/chirp/drivers/__init__.py b/chirp/drivers/__init__.py index 1c9d70a..e6073f5 100644 --- a/chirp/drivers/__init__.py +++ b/chirp/drivers/__init__.py @@ -160,20 +160,24 @@ from chirp.drivers import ksun_m6 from chirp.drivers import retevis_ra87 from chirp.drivers import uvk5_egzumer from chirp.drivers import tk481 -from chirp.drivers import yaesu_clone from chirp.drivers import ict10 +from chirp.drivers import radioddity_gm30 +from chirp.drivers import mml_jc8810 +from chirp.drivers import icf520 from chirp.drivers import tdh8 from chirp.drivers import tk280 +from chirp.drivers import baofeng_uv17 from chirp.drivers import uvk5 +from chirp.drivers import retevis_ra25 from chirp.drivers import radtel_rt620 from chirp.drivers import radtel_rt490 from chirp.drivers import baofeng_digital from chirp.drivers import ts790e -from chirp.drivers import baofeng_uv17 -from chirp.drivers import icf520 from chirp.drivers import icm710 from chirp.drivers import tk690 -from chirp.drivers import mml_jc8810 -from chirp.drivers import baofeng_uv17Pro from chirp.drivers import alinco_dr735t -__all__ = ['anytone', 'btech', 'anytone778uv', 'anytone_ht', 'anytone_iii', 'baofeng_common', 'baofeng_uv3r', 'baofeng_wp970i', 'bf_t1', 'bf_t8', 'boblov_x3plus', 'fake', 'fd268', 'ft1500m', 'ft1802', 'ft1d', 'ft2800', 'ft2900', 'ft4', 'ft450d', 'ft50', 'ft2d', 'ft60', 'ft70', 'ft7100', 'ft7800', 'ft8100', 'ft817', 'ft818', 'ft857', 'ft90', 'ftlx011', 'ftm3200d', 'ftm350', 'ftm7250d', 'ga510', 'generic_csv', 'generic_tpe', 'gmrsuv1', 'gmrsv2', 'h777', 'hf90', 'hg_uv98', 'alinco', 'bj9900', 'ic2100', 'hobbypcb', 'ic208', 'ic2300', 'ic2720', 'ic2200', 'ic2730', 'ic2820', 'ic9x_ll', 'ic9x', 'ic9x_icf', 'icf', 'ic9x_icf_ll', 'icomciv', 'icp7', 'icq7', 'ict8', 'icv80', 'ict70', 'ict7h', 'icv86', 'id51', 'icx90', 'icw32', 'icx8x', 'id31', 'id5100', 'id51plus', 'id800', 'id880', 'idrp', 'kg935g', 'kguv8d', 'iradio_uv_5118', 'kenwood_hmk', 'kenwood_itm', 'kenwood_live', 'kguv8e', 'kyd', 'kguv8dplus', 'kguv920pa', 'kguv980p', 'kguv9dplus', 'lt725uv', 'kyd_IP620', 'leixen', 'mursv1', 'puxing', 'ap510', 'puxing_px888k', 'radioddity_r2', 'radtel_t18', 'retevis_rb15', 'retevis_rb17p', 'retevis_rb28', 'retevis_rt1', 'retevis_rt21', 'retevis_rt22', 'retevis_rt23', 'retevis_rt26', 'retevis_rt76p', 'retevis_rt87', 'retevis_rt98', '__init__', 'bjuv55', 'rh5r_v2', 'tdxone_tdq8a', 'template', 'tg_uv2p', 'th350', 'th7800', 'th9000', 'th9800', 'th_uv3r', 'th_uv3r25', 'th_uv8000', 'th_uv88', 'th_uvf8d', 'thd72', 'thd74', 'thuv1f', 'tk270', 'tk3140', 'tk760', 'tk760g', 'tk8102', 'tk8160', 'tk8180', 'tmd710', 'tmv71', 'tmv71_ll', 'ts2000', 'ts480', 'ts590', 'ts850', 'uv5r', 'uv5x3', 'uv6r', 'uvb5', 'vgc', 'vx170', 'vx2', 'vx3', 'vx5', 'vx510', 'vx6', 'vx7', 'vx8', 'vxa700', 'wouxun', 'wouxun_common', 'kenwood_d7', 'iradio_uv_5118plus', 'ksun_m6', 'retevis_ra87', 'uvk5_egzumer', 'tk481', 'yaesu_clone', 'ict10', 'tdh8', 'tk280', 'uvk5', 'radtel_rt620', 'radtel_rt490', 'baofeng_digital', 'ts790e', 'baofeng_uv17', 'icf520', 'icm710', 'tk690', 'mml_jc8810', 'baofeng_uv17Pro', 'alinco_dr735t'] +from chirp.drivers import yaesu_clone +from chirp.drivers import retevis_h777v4 +from chirp.drivers import baofeng_uv17Pro +from chirp.drivers import retevis_ra86 +__all__ = ['anytone', 'btech', 'anytone778uv', 'anytone_ht', 'anytone_iii', 'baofeng_common', 'baofeng_uv3r', 'baofeng_wp970i', 'bf_t1', 'bf_t8', 'boblov_x3plus', 'fake', 'fd268', 'ft1500m', 'ft1802', 'ft1d', 'ft2800', 'ft2900', 'ft4', 'ft450d', 'ft50', 'ft2d', 'ft60', 'ft70', 'ft7100', 'ft7800', 'ft8100', 'ft817', 'ft818', 'ft857', 'ft90', 'ftlx011', 'ftm3200d', 'ftm350', 'ftm7250d', 'ga510', 'generic_csv', 'generic_tpe', 'gmrsuv1', 'gmrsv2', 'h777', 'hf90', 'hg_uv98', 'alinco', 'bj9900', 'ic2100', 'hobbypcb', 'ic208', 'ic2300', 'ic2720', 'ic2200', 'ic2730', 'ic2820', 'ic9x_ll', 'ic9x', 'ic9x_icf', 'icf', 'ic9x_icf_ll', 'icomciv', 'icp7', 'icq7', 'ict8', 'icv80', 'ict70', 'ict7h', 'icv86', 'id51', 'icx90', 'icw32', 'icx8x', 'id31', 'id5100', 'id51plus', 'id800', 'id880', 'idrp', 'kg935g', 'kguv8d', 'iradio_uv_5118', 'kenwood_hmk', 'kenwood_itm', 'kenwood_live', 'kguv8e', 'kyd', 'kguv8dplus', 'kguv920pa', 'kguv980p', 'kguv9dplus', 'lt725uv', 'kyd_IP620', 'leixen', 'mursv1', 'puxing', 'ap510', 'puxing_px888k', 'radioddity_r2', 'radtel_t18', 'retevis_rb15', 'retevis_rb17p', 'retevis_rb28', 'retevis_rt1', 'retevis_rt21', 'retevis_rt22', 'retevis_rt23', 'retevis_rt26', 'retevis_rt76p', 'retevis_rt87', 'retevis_rt98', '__init__', 'bjuv55', 'rh5r_v2', 'tdxone_tdq8a', 'template', 'tg_uv2p', 'th350', 'th7800', 'th9000', 'th9800', 'th_uv3r', 'th_uv3r25', 'th_uv8000', 'th_uv88', 'th_uvf8d', 'thd72', 'thd74', 'thuv1f', 'tk270', 'tk3140', 'tk760', 'tk760g', 'tk8102', 'tk8160', 'tk8180', 'tmd710', 'tmv71', 'tmv71_ll', 'ts2000', 'ts480', 'ts590', 'ts850', 'uv5r', 'uv5x3', 'uv6r', 'uvb5', 'vgc', 'vx170', 'vx2', 'vx3', 'vx5', 'vx510', 'vx6', 'vx7', 'vx8', 'vxa700', 'wouxun', 'wouxun_common', 'kenwood_d7', 'iradio_uv_5118plus', 'ksun_m6', 'retevis_ra87', 'uvk5_egzumer', 'tk481', 'ict10', 'radioddity_gm30', 'mml_jc8810', 'icf520', 'tdh8', 'tk280', 'baofeng_uv17', 'uvk5', 'retevis_ra25', 'radtel_rt620', 'radtel_rt490', 'baofeng_digital', 'ts790e', 'icm710', 'tk690', 'alinco_dr735t', 'yaesu_clone', 'retevis_h777v4', 'baofeng_uv17Pro', 'retevis_ra86'] diff --git a/chirp/drivers/baofeng_uv17.py b/chirp/drivers/baofeng_uv17.py index 48fb57f..1a04c41 100644 --- a/chirp/drivers/baofeng_uv17.py +++ b/chirp/drivers/baofeng_uv17.py @@ -22,7 +22,7 @@ from chirp.settings import RadioSettingGroup, RadioSetting, \ RadioSettings, RadioSettingValueString import struct from chirp.drivers import baofeng_common, baofeng_uv17Pro -from chirp import errors, util +from chirp import errors LOG = logging.getLogger(__name__) LIST_DTMFST = ["Off", "DT-ST", "ANI-ST", "DT+ANI"] @@ -88,15 +88,11 @@ def _download(radio): for addr in range(start_addr, start_addr + 0x1000, radio.BLOCK_SIZE): frame = radio._make_read_frame(addr, radio.BLOCK_SIZE) - # DEBUG - LOG.debug("Frame=" + util.hexprint(frame)) - + radio.pipe.log('Reading addr %04x' % addr) baofeng_common._rawsend(radio, frame) d = baofeng_common._rawrecv(radio, radio.BLOCK_SIZE + 5) - LOG.debug("Response Data= " + util.hexprint(d)) - data += d[5:] status.cur = len(data) // radio.BLOCK_SIZE @@ -133,6 +129,7 @@ def _upload(radio): data_addr = data_start_addr + addr - start_addr data = radio.get_mmap()[data_addr:data_addr + radio.BLOCK_SIZE] frame = radio._make_frame(b"W", addr, radio.BLOCK_SIZE, data) + radio.pipe.log('Sending addr %04x' % addr) baofeng_common._rawsend(radio, frame) # receiving the response diff --git a/chirp/drivers/baofeng_uv17Pro.py b/chirp/drivers/baofeng_uv17Pro.py index a2a6d5f..65b9955 100644 --- a/chirp/drivers/baofeng_uv17Pro.py +++ b/chirp/drivers/baofeng_uv17Pro.py @@ -24,7 +24,7 @@ from chirp.settings import RadioSetting, \ RadioSettingValueString, \ RadioSettings, RadioSettingGroup import struct -from chirp import errors, util +from chirp import errors LOG = logging.getLogger(__name__) @@ -145,16 +145,12 @@ def _download(radio): for addr in range(MEM_START, MEM_START + MEM_SIZE, radio.BLOCK_SIZE): frame = radio._make_read_frame(addr, radio.BLOCK_SIZE) - # DEBUG - LOG.debug("Frame=" + util.hexprint(frame)) - # Sending the read request + radio.pipe.log('Sending request for %04x' % addr) bfc._rawsend(radio, frame) - # Now we read data d = bfc._rawrecv(radio, radio.BLOCK_SIZE + 4) - LOG.debug("Response Data= " + util.hexprint(d)) if radio._uses_encr: d = _crypt(radio._encrsym, d[4:]) else: @@ -195,13 +191,9 @@ def _upload(radio): data_addr += radio.BLOCK_SIZE frame = radio._make_frame(b"W", addr, radio.BLOCK_SIZE, data) - # DEBUG - LOG.debug("Frame=" + util.hexprint(frame)) - - # Sending the read request + radio.pipe.log('Sending address %04x' % addr) bfc._rawsend(radio, frame) - # receiving the response ack = bfc._rawrecv(radio, 1) if ack != b"\x06": msg = "Bad ack writing block 0x%04x" % addr @@ -256,6 +248,8 @@ class UV17Pro(bfc.BaofengCommonHT): _has_send_id_delay = False _has_skey1_short = False _has_skey2_short = False + _has_skey_disable = False + _has_zone_linking = False _scode_offset = 0 _encrsym = 1 _has_voice = True @@ -295,6 +289,7 @@ class UV17Pro(bfc.BaofengCommonHT): VALID_BANDS = [_vhf_range, _vhf2_range, _uhf_range] PTTID_LIST = LIST_PTTID + RXDTMF_LIST = ["CTCSS/DTS", "CTCSS/DCS + DTMF"] SCODE_LIST = ["%s" % x for x in range(1, 21)] SQUELCH_LIST = ["Off"] + list("12345") SCRAMBLE_LIST = ["Off"] + ["SCR%s" % x for x in list("123")] @@ -791,7 +786,10 @@ class UV17Pro(bfc.BaofengCommonHT): 0x1D: 2, 0x2D: 3, 0x0A: 4, - 0x0C: 5} + 0x0C: 5, + 0x34: 6, + 0x08: 4, + 0x03: 5} return key_to_index.get(int(value), 0) def apply_Key1short(setting, obj): @@ -801,7 +799,10 @@ class UV17Pro(bfc.BaofengCommonHT): 'Search': 0x1D, 'Vox': 0x2D, 'TX Power': 0x0A, - 'NOAA': 0x0C} + 'NOAA': 0x0C, + 'Zone Select': 0x34, + 'Flashlight': 0x08, + 'SOS': 0x03} obj.key1short = key_to_index.get(val, 0x07) def getKey2shortIndex(value): @@ -810,7 +811,8 @@ class UV17Pro(bfc.BaofengCommonHT): 0x1D: 2, 0x2D: 3, 0x0A: 4, - 0x0C: 5} + 0x0C: 5, + 0x34: 6} return key_to_index.get(int(value), 0) def apply_Key2short(setting, obj): @@ -820,7 +822,8 @@ class UV17Pro(bfc.BaofengCommonHT): 'Search': 0x1D, 'Vox': 0x2D, 'TX Power': 0x0A, - 'NOAA': 0x0C} + 'NOAA': 0x0C, + 'Zone Select': 0x34} obj.key2short = key_to_index.get(val, 0x07) if self._has_skey1_short: @@ -841,6 +844,13 @@ class UV17Pro(bfc.BaofengCommonHT): rs.set_apply_callback(apply_Key2short, _mem.settings) basic.append(rs) + if self._has_skey_disable: + rs = RadioSetting("settings.skdisable", "Side Key Disable", + RadioSettingValueList( + self.LIST_SKEY_DISABLE, + current_index=_mem.settings.skdisable)) + basic.append(rs) + rs = RadioSetting("settings.chaworkmode", "Channel A work mode", RadioSettingValueList( LIST_WORKMODE, @@ -913,6 +923,18 @@ class UV17Pro(bfc.BaofengCommonHT): RadioSettingValueBoolean(_mem.settings.fmenable)) basic.append(rs) + if self._has_zone_linking: + for i in range(1, 11): + rs = RadioSetting(f"settings.zn{i}linkd", + f"Scan Link Zone {i}", + RadioSettingValueBoolean(getattr( + _mem.settings, f"zn{i}linkd"))) + basic.append(rs) + + rs = RadioSetting("settings.lnkzones", "Scan Zone Linking", + RadioSettingValueBoolean(_mem.settings.lnkzones)) + basic.append(rs) + def get_settings_common_workmode(self, workmode, _mem): vfoA = RadioSettingGroup("vfoA", "VFO A") @@ -1325,7 +1347,6 @@ class UV17Pro(bfc.BaofengCommonHT): mem.mode = _mem.wide and self.MODES[0] or self.MODES[1] if chirp_common.in_range(mem.freq, [self._airband]): - print('freq %i means am' % mem.freq) mem.mode = "AM" mem.extra = RadioSettingGroup("Extra", "extra") @@ -1345,7 +1366,18 @@ class UV17Pro(bfc.BaofengCommonHT): current_index=scode)) mem.extra.append(rs) - if self.MODEL in ["BF-F8HP-PRO", "K6"]: + if self.MODEL in ["BF-F8HP-PRO"]: + rs = RadioSetting("sqmode", "RX DTMF", + RadioSettingValueList( + self.RXDTMF_LIST, + current_index=_mem.sqmode)) + mem.extra.append(rs) + + rs = RadioSetting("fhss", "Encryption", + RadioSettingValueBoolean(_mem.fhss)) + mem.extra.append(rs) + + if self.MODEL in ["K6", "UV-5R Mini"]: rs = RadioSetting("sqmode", "RX DTMF", RadioSettingValueBoolean(_mem.sqmode)) mem.extra.append(rs) @@ -1354,12 +1386,12 @@ class UV17Pro(bfc.BaofengCommonHT): RadioSettingValueBoolean(_mem.fhss)) mem.extra.append(rs) - if self.MODEL == "K6": - rs = RadioSetting("scramble", "Scramble", - RadioSettingValueList( - self.SCRAMBLE_LIST, - current_index=_mem.scramble)) - mem.extra.append(rs) + if self.MODEL == "K6": + rs = RadioSetting("scramble", "Scramble", + RadioSettingValueList( + self.SCRAMBLE_LIST, + current_index=_mem.scramble)) + mem.extra.append(rs) mem.name = str(name).replace('\xFF', ' ').replace('\x00', ' ').rstrip() @@ -1533,6 +1565,11 @@ class MaxTalkerP15(BF5RM): @directory.register +class MaxTalkerMT5RM(MaxTalkerP15): + MODEL = 'MT-5RM' + + +@directory.register class BFK5Plus(BF5RM): VENDOR = "Baofeng" MODEL = "K5-Plus" @@ -1576,7 +1613,7 @@ class F8HPPro(UV17Pro): # ========== # Notice to developers: - # The BF-F8HP-PRO support in this driver is currently based upon v0.33 + # The BF-F8HP-PRO support in this driver is currently based upon v0.44 # firmware. # ========== @@ -1587,13 +1624,16 @@ class F8HPPro(UV17Pro): b"\x12\x0A\x11\x06\x04\x0E\x02\x09\x0D\x00\x00", 1)] _encrsym = 3 - STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0, 100.0] + STEPS = [2.5, 5.0, 6.25, 8.33, 10.0, 12.5, 20.0, 25.0, 50.0, 100.0] LIST_STEPS = ["2.5", "5.0", "6.25", "10.0", "12.5", "20.0", "25.0", "50.0", "100.0"] - VALID_BANDS = [UV17Pro._airband, UV17Pro._vhf_range, UV17Pro._vhf2_range, + _airband = (108000000, 136999999) + _vhf_range = (137000000, 174000000) + + VALID_BANDS = [_airband, _vhf_range, UV17Pro._vhf2_range, UV17Pro._uhf_range, UV17Pro._uhf2_range] - POWER_LEVELS = [chirp_common.PowerLevel("High", watts=8.00), + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=10.00), chirp_common.PowerLevel("Low", watts=1.00), chirp_common.PowerLevel('Mid', watts=3.00)] LIST_POWER_ON_TIME = ['3 Seconds', '5 Seconds', '10 Seconds'] @@ -1604,8 +1644,11 @@ class F8HPPro(UV17Pro): LIST_BACKLIGHT_TIMER = ["Always On", "5 sec", "10 sec", "15 sec", "20 sec", "30 sec", "60 sec"] LIST_ID_DELAY = ["%s ms" % x for x in range(100, 3100, 100)] - LIST_SKEY2_SHORT = ["FM", "Scan", "Search", "Vox", "TX Power", "NOAA"] + LIST_SKEY2_SHORT = ["FM", "Scan", "Search", "Vox", "TX Power", "NOAA", + "Zone Select"] MODES = UV17Pro.MODES + ['AM'] + SQUELCH_LIST = ["Off"] + list("12345678") + LIST_SKEY_DISABLE = ["Off", "SK Only", "PTT Only", "SK + PTT"] _has_support_for_banknames = True _vfoscan = True @@ -1615,8 +1658,10 @@ class F8HPPro(UV17Pro): _has_send_id_delay = True _has_skey1_short = True _has_skey2_short = True + _has_skey_disable = True _has_voice = False _has_when_to_send_aniid = False + _has_zone_linking = True MEM_STARTS = [0x0000, 0x9000, 0xA000, 0xD000] MEM_SIZES = [0x8040, 0x0080, 0x02C0, 0x00C0] @@ -1667,9 +1712,20 @@ class F8HPPro(UV17Pro): u8 menuquittime; u8 unknown5[2]; u8 dispani; - u8 unknown11[3]; + u8 unknown11[2]; + u8 skdisable; u8 totalarm; - u8 unknown6[2]; + u8 zn8linkd:1, + zn7linkd:1, + zn6linkd:1, + zn5linkd:1, + zn4linkd:1, + zn3linkd:1, + zn2linkd:1, + zn1linkd:1; + u8 unknown6:6, + zn10linkd:1, + zn9linkd:1; u8 ctsdcsscantype; ul16 vfoscanmin; ul16 vfoscanmax; @@ -1684,7 +1740,7 @@ class F8HPPro(UV17Pro): u8 hangup; u8 voxsw; u8 gpstimezone; - u8 unknown10; + u8 lnkzones; u8 inputdtmf; u8 gpsunits; u8 pontime; @@ -2088,3 +2144,87 @@ class BFK6(UV17Pro): rs = RadioSetting("downcode.code", "Down Code", val) rs.set_apply_callback(self.apply_code, self._memobj.downcode, 16) dtmfe.append(rs) + + +@directory.register +class UV5RMini(UV17Pro): + """Baofeng UV-5R Mini""" + VENDOR = "Baofeng" + MODEL = "UV-5R Mini" + + LIST_BEEP = ["Off", "On"] + LIST_DTMFSPEED = ["%s ms" % x for x in [50, 100, 200, 300, 400, 500]] + LIST_SKEY2_SHORT = ["FM Radio", "Scan", "Search", "VOX", "Flashlight", + "SOS"] + + MEM_STARTS = [0x0000, 0x9000, 0xA000] + MEM_SIZES = [0x8040, 0x0040, 0x01C0] + + MEM_TOTAL = 0x8240 + + _has_support_for_banknames = False + + _magic = MSTRING_UV17PROGPS + _mem_size = MEM_TOTAL + _has_voxsw = True + _has_pilot_tone = True + _has_send_id_delay = True + _has_skey1_short = True + _mem_params = { + 'mems': 999, + 'ani': 0x8080, + 'pttid': 0x80A0, + } + CHANNELS = 999 + + STEPS = [2.5, 5.0, 6.25, 8.33, 10.0, 12.5, 20.0, 25.0, 50.0] + + _uhf_rx1_range = (350000000, 390000000) + _uhf_range = (400000000, 480000000) + _uhf_rx2_range = (480000000, 520000000) + VALID_BANDS = [UV17Pro._airband, + UV17Pro._vhf_range, + _uhf_rx1_range, + _uhf_range, + _uhf_rx2_range] + MODES = UV17Pro.MODES + ['AM'] + + _end_fmt = """ + // #seekto 0x8220; + struct { + u8 unknown1[32]; + } modes; + """ + + def get_settings_pro_dtmf(self, dtmfe, _mem): + super().get_settings_pro_dtmf(dtmfe, _mem) + + rs = RadioSetting("ani.separatecode", "Separate Code", + RadioSettingValueList( + self.LIST_SEPARATE_CODE, + current_index=_mem.ani.separatecode)) + dtmfe.append(rs) + + rs = RadioSetting("ani.groupcallcode", "Group Call Code", + RadioSettingValueList( + self.LIST_GROUP_CALL_CODE, + current_index=_mem.ani.groupcallcode)) + dtmfe.append(rs) + + _codeobj = self._memobj.upcode.code + _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) + < 0x1F]) + val = RadioSettingValueString(0, 16, _code, False) + val.set_charset(DTMF_CHARS) + rs = RadioSetting("upcode.code", "Up Code", val) + rs.set_apply_callback(self.apply_code, self._memobj.upcode, 16) + dtmfe.append(rs) + + _codeobj = self._memobj.downcode.code + _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) + < 0x1F]) + val = RadioSettingValueString(0, 16, _code, False) + val.set_charset(DTMF_CHARS) + rs = RadioSetting("downcode.code", "Down Code", val) + rs.set_apply_callback(self.apply_code, self._memobj.downcode, 16) + dtmfe.append(rs) diff --git a/chirp/drivers/btech.py b/chirp/drivers/btech.py index d0cb0b1..bc9b75c 100644 --- a/chirp/drivers/btech.py +++ b/chirp/drivers/btech.py @@ -419,11 +419,11 @@ def _recv(radio, addr): # Get the full 69 bytes at a time to reduce load # 1 byte ACK + 4 bytes header + 64 bytes of data (BLOCK_SIZE) - # get the whole block - block = _rawrecv(radio, BLOCK_SIZE + 5) + # get the whole block Bug #11851 BLOCKSIZE fix for KT-8900D + block = _rawrecv(radio, radio._block_size + 5) - # basic check - if len(block) < (BLOCK_SIZE + 5): + # basic check Bug #11851 BLOCKSIZE fix for KT-8900D + if len(block) < (radio._block_size + 5): raise errors.RadioError("Short read of the block 0x%04x" % addr) # checking for the ack @@ -432,7 +432,7 @@ def _recv(radio, addr): # header validation c, a, l = struct.unpack(">BHB", block[1:5]) - if a != addr or l != BLOCK_SIZE or c != ord("X"): + if a != addr or l != radio._block_size or c != ord("X"): LOG.debug("Invalid header for block 0x%04x" % addr) LOG.debug("CMD: %s ADDR: %04x SIZE: %02x" % (c, a, l)) raise errors.RadioError("Invalid header for block 0x%04x:" % addr) @@ -542,16 +542,16 @@ def _download(radio): # put radio in program mode and identify it _do_ident(radio, status) - # reset the progress bar in the UI - status.max = MEM_SIZE // BLOCK_SIZE + # reset the progress bar in the UI Bug #11851 BLOCKSIZE fix for KT-8900D + status.max = MEM_SIZE // radio._block_size status.msg = "Cloning from radio..." status.cur = 0 radio.status_fn(status) data = b"" - for addr in range(0, MEM_SIZE, BLOCK_SIZE): + for addr in range(0, MEM_SIZE, radio._block_size): # sending the read request - _send(radio, _make_frame("S", addr, BLOCK_SIZE)) + _send(radio, _make_frame("S", addr, radio._block_size)) # read d = _recv(radio, addr) @@ -662,6 +662,7 @@ class BTechMobileCommon(chirp_common.CloneModeRadio, """BTECH's UV-5001 and alike radios""" VENDOR = "BTECH" MODEL = "" + _block_size = BLOCK_SIZE # Bug 11851 should default to BLOCK_SIZE IDENT = "" BANDS = 2 COLOR_LCD = False @@ -4091,6 +4092,7 @@ class KT8900D(BTechColor): """QYT KT8900D""" VENDOR = "QYT" MODEL = "KT8900D" + _block_size = 0x10 # Bug 11851 BLOCKSIZE fix for KT-8900D BANDS = 2 LIST_TMR = LIST_TMR15 _vhf_range = (136000000, 175000000) diff --git a/chirp/drivers/ft4.py b/chirp/drivers/ft4.py index 7fd92b6..6b463ff 100644 --- a/chirp/drivers/ft4.py +++ b/chirp/drivers/ft4.py @@ -345,13 +345,15 @@ def startcomms(radio, direction): if id_response != radio.id_str: substr0 = radio.id_str[:radio.id_str.find(b'\x00')] if id_response[:id_response.find(b'\x00')] != substr0: - msg = "ID mismatch. Expected" + util.hexprint(radio.id_str) - msg += ", Received:" + util.hexprint(id_response_mod) + msg = "ID mismatch.\nExpected:\n{}Received:\n{}".format( + util.hexprint(radio.id_str), util.hexprint(id_response_mod) + ) LOG.warning(msg) raise errors.RadioError("Incorrect ID read from radio.") else: - msg = "ID suspect. Expected" + util.hexprint(radio.id_str) - msg += ", Received:" + util.hexprint(id_response_mod) + msg = "ID suspect.\nExpected:\n{}Received:\n{}".format( + util.hexprint(radio.id_str), util.hexprint(id_response_mod) + ) LOG.warning(msg) return progressbar diff --git a/chirp/drivers/ft7800.py b/chirp/drivers/ft7800.py index 237e222..750e2c5 100644 --- a/chirp/drivers/ft7800.py +++ b/chirp/drivers/ft7800.py @@ -144,7 +144,8 @@ u8 checksum; MODES = ["FM", "AM", "NFM"] DUPLEX = ["", "", "-", "+", "split"] -STEPS = [5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0, 100.0] +STEPS = (5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0, 100.0) +STEPS_8800 = (5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0) SKIPS = ["", "S", "P", ""] CHARSET = ["%i" % int(x) for x in range(0, 10)] + \ @@ -251,7 +252,9 @@ class FTx800Radio(yaesu_clone.YaesuCloneModeRadio): """Base class for FT-7800,7900,8800,8900 radios""" BAUD_RATE = 9600 VENDOR = "Yaesu" - MODES = list(MODES) + MODES = MODES + STEPS = STEPS + _block_size = 64 POWER_LEVELS_VHF = [chirp_common.PowerLevel("Hi", watts=50), @@ -297,10 +300,10 @@ class FTx800Radio(yaesu_clone.YaesuCloneModeRadio): rf.has_bank = False rf.has_ctone = False rf.has_dtcs_polarity = False - rf.valid_modes = MODES + rf.valid_modes = self.MODES rf.valid_tmodes = self.TMODES rf.valid_duplexes = ["", "-", "+", "split"] - rf.valid_tuning_steps = STEPS + rf.valid_tuning_steps = self.STEPS rf.valid_bands = [(108000000, 520000000), (700000000, 990000000)] rf.valid_skips = ["", "S", "P"] rf.valid_power_levels = self.POWER_LEVELS_VHF @@ -385,6 +388,12 @@ class FTx800Radio(yaesu_clone.YaesuCloneModeRadio): flgidx = (mem.number - 1) % 4 _flg["skip%i" % flgidx] = SKIPS.index(mem.skip) + def _get_mem_mode(self, mem, _mem): + mem.mode = self.MODES[_mem.mode] + + def _set_mem_mode(self, mem, _mem): + _mem.mode = self.MODES.index(mem.mode) + def get_memory(self, number): _mem = self._memobj.memory[number - 1] @@ -397,10 +406,12 @@ class FTx800Radio(yaesu_clone.YaesuCloneModeRadio): mem.freq = get_freq(int(_mem.freq) * 10000) mem.rtone = chirp_common.TONES[_mem.tone] mem.tmode = self.TMODES[_mem.tmode] - mem.mode = self.MODES[_mem.mode] + + self._get_mem_mode(mem, _mem) + mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs] if self.get_features().has_tuning_step: - mem.tuning_step = STEPS[_mem.tune_step] + mem.tuning_step = self.STEPS[_mem.tune_step] mem.duplex = DUPLEX[_mem.duplex] mem.offset = self._get_mem_offset(mem, _mem) mem.name = self._get_mem_name(mem, _mem) @@ -424,10 +435,12 @@ class FTx800Radio(yaesu_clone.YaesuCloneModeRadio): set_freq(mem.freq, _mem, "freq") _mem.tone = chirp_common.TONES.index(mem.rtone) _mem.tmode = self.TMODES.index(mem.tmode) - _mem.mode = self.MODES.index(mem.mode) + + self._set_mem_mode(mem, _mem) + _mem.dtcs = chirp_common.DTCS_CODES.index(mem.dtcs) if self.get_features().has_tuning_step: - _mem.tune_step = STEPS.index(mem.tuning_step) + _mem.tune_step = self.STEPS.index(mem.tuning_step) _mem.duplex = DUPLEX.index(mem.duplex) _mem.split = mem.duplex == "split" and int(mem.offset / 10000) or 0 if mem.power: @@ -796,7 +809,8 @@ MEM_FORMAT_8800 = """ struct { u8 used:1, unknown1:1, - mode:2, + wid_nar:1, + am:1, unknown2:1, duplex:3; bbcd freq[3]; @@ -811,7 +825,7 @@ struct { u8 namevalid:1, dtcs:7; u8 name[6]; -} memory[500]; +} memory[512]; #seekto 0x%X; struct { @@ -824,7 +838,7 @@ struct { skip1:2, skip2:2, skip3:2; -} flags[250]; +} flags[256]; #seekto 0x7B48; u8 checksum; @@ -849,6 +863,7 @@ class FT8800Radio(FTx800Radio): _memstart = 0x0000 TMODES = ["", "Tone", "TSQL", "DTCS"] + STEPS = STEPS_8800 @classmethod def get_prompts(cls): @@ -880,7 +895,7 @@ class FT8800Radio(FTx800Radio): rf = FTx800Radio.get_features(self) rf.has_sub_devices = self.VARIANT == "" rf.has_bank = True - rf.memory_bounds = (1, 500) + rf.memory_bounds = (1, 512) return rf def get_sub_devices(self): @@ -940,6 +955,21 @@ class FT8800Radio(FTx800Radio): _mem.namevalid = 1 _mem.nameused = bool(mem.name.rstrip()) + def _get_mem_mode(self, mem, _mem): + if _mem.am: + mem.mode = "AM" + else: + mem.mode = "NFM" if _mem.wid_nar else "FM" + + def _set_mem_mode(self, mem, _mem): + if mem.mode == "AM": + _mem.am = True + _mem.wid_nar = False + + else: + _mem.am = False + _mem.wid_nar = mem.mode == "NFM" + class FT8800RadioLeft(FT8800Radio): """Yaesu FT-8800 Left VFO subdevice""" @@ -991,7 +1021,7 @@ u8 checksum; @directory.register -class FT8900Radio(FT8800Radio): +class FT8900Radio(FTx800Radio): """Yaesu FT-8900""" MODEL = "FT-8900" @@ -1000,17 +1030,40 @@ class FT8900Radio(FT8800Radio): _block_lengths = [8, 14784, 1] MODES = ["FM", "NFM", "AM"] + TMODES = ["", "Tone", "TSQL", "DTCS"] + STEPS = STEPS - def get_bank_model(self): - return + @classmethod + def get_prompts(cls): + rp = chirp_common.RadioPrompts() + rp.pre_download = _( + "1. Turn radio off.\n" + "2. Connect cable to DATA jack.\n" + "3. Press and hold in the \"left\" [V/M] key while turning the\n" + " radio on.\n" + "4. Rotate the \"right\" DIAL knob to select \"CLONE START\".\n" + "5. Press the [SET] key. The display will disappear\n" + " for a moment, then the \"CLONE\" notation will appear.\n" + "6. <b>After clicking OK</b>, press the \"left\" [V/M] key to\n" + " send image.\n") + rp.pre_upload = _( + "1. Turn radio off.\n" + "2. Connect cable to DATA jack.\n" + "3. Press and hold in the \"left\" [V/M] key while turning the\n" + " radio on.\n" + "4. Rotate the \"right\" DIAL knob to select \"CLONE START\".\n" + "5. Press the [SET] key. The display will disappear\n" + " for a moment, then the \"CLONE\" notation will appear.\n" + "6. Press the \"left\" [LOW] key (\"CLONE -RX-\" will appear" + " on\n" + " the display).\n") + return rp def process_mmap(self): self._memobj = bitwise.parse(MEM_FORMAT_8900, self._mmap) def get_features(self): - rf = FT8800Radio.get_features(self) - rf.has_sub_devices = False - rf.has_bank = False + rf = FTx800Radio.get_features(self) rf.valid_modes = self.MODES rf.valid_bands = [(28000000, 29700000), (50000000, 54000000), @@ -1025,19 +1078,50 @@ class FT8900Radio(FT8800Radio): def _checksums(self): return [yaesu_clone.YaesuChecksum(0x0000, 0x39C7)] + def _get_mem_offset(self, mem, _mem): + if mem.duplex == "split": + return get_freq(int(_mem.split) * 10000) + + # The offset is packed into the upper two bits of the last four + # bytes of the name (?!) + val = 0 + for i in _mem.name[2:6]: + val <<= 2 + val |= ((i & 0xC0) >> 6) + + return (val * 5) * 10000 + + def _set_mem_offset(self, mem, _mem): + if mem.duplex == "split": + set_freq(mem.offset, _mem, "split") + return + + val = int(mem.offset / 10000) // 5 + for i in reversed(list(range(2, 6))): + _mem.name[i] = (_mem.name[i] & 0x3F) | ((val & 0x03) << 6) + val >>= 2 + + def _get_mem_name(self, mem, _mem): + name = "" + if _mem.namevalid: + for i in _mem.name: + index = int(i) & 0x3F + if index < len(CHARSET): + name += CHARSET[index] + + return name.rstrip() + + def _set_mem_name(self, mem, _mem): + _mem.name = [CHARSET.index(x) for x in mem.name.ljust(6)[:6]] + _mem.namevalid = 1 + _mem.nameused = bool(mem.name.rstrip()) + def _get_mem_skip(self, mem, _mem): return SKIPS[_mem.skip] def _set_mem_skip(self, mem, _mem): _mem.skip = SKIPS.index(mem.skip) - def get_memory(self, number): - mem = super().get_memory(number) - - _mem = self._memobj.memory[number - 1] - - return mem - def set_memory(self, mem): FT8800Radio.set_memory(self, mem) diff --git a/chirp/drivers/ga510.py b/chirp/drivers/ga510.py index e6741be..7a9d24c 100644 --- a/chirp/drivers/ga510.py +++ b/chirp/drivers/ga510.py @@ -72,7 +72,7 @@ def do_download(radio): data = bytes() for addr in range(0, 0x1C40, 0x40): cmd = struct.pack('>cHB', b'R', addr, 0x40) - LOG.debug('Reading block at %04x: %r' % (addr, cmd)) + radio.pipe.log('Reading block at %04x' % addr) radio.pipe.write(cmd) block = radio.pipe.read(0x44) @@ -106,7 +106,7 @@ def do_upload(radio): # here. for addr in range(0, 0x1C20, 0x20): cmd = struct.pack('>cHB', b'W', addr, 0x20) - LOG.debug('Writing block at %04x: %r' % (addr, cmd)) + radio.pipe.log('Writing block at %04x' % addr) block = radio._mmap[addr:addr + 0x20] radio.pipe.write(cmd) radio.pipe.write(block) diff --git a/chirp/drivers/h777.py b/chirp/drivers/h777.py index c5ef877..0586fd0 100644 --- a/chirp/drivers/h777.py +++ b/chirp/drivers/h777.py @@ -98,24 +98,28 @@ TIMEOUTTIMER_LIST = ["Off", "30 seconds", "60 seconds", "90 seconds", "120 seconds", "150 seconds", "180 seconds", "210 seconds", "240 seconds", "270 seconds", "300 seconds"] +DTCS_FLAG = 0x80 +DTCS_REV_FLAG = 0x40 -def _h777_enter_programming_mode(radio): - serial = radio.pipe +def _h777_enter_programming_mode(serial, radio_cls): # increase default timeout from .25 to .5 for all serial communications serial.timeout = 0.5 try: serial.write(b"\x02") time.sleep(0.1) - serial.write(radio.PROGRAM_CMD) + serial.write(radio_cls.PROGRAM_CMD) ack = serial.read(1) - except: + except Exception as e: + LOG.warning('Failed to send program command: %s', e) raise errors.RadioError("Error communicating with radio") if not ack: - raise errors.RadioError("No response from radio") + raise errors.RadioError("No response from radio to program command") elif ack != CMD_ACK: + LOG.warning('Ack from program command was %r, expected %r', + ack, CMD_ACK) raise errors.RadioError("Radio refused to enter programming mode") try: @@ -125,37 +129,29 @@ def _h777_enter_programming_mode(radio): # version data and the last three bytes. We need to raise the # timeout so that the read doesn't finish early. ident = serial.read(8) - except: + except Exception as e: + LOG.warning('Failed to read ident: %s', e) raise errors.RadioError("Error communicating with radio") - # check if ident is OK - itis = False - for fp in radio.IDENT: - if fp in ident: - # got it! - itis = True - - break - - if itis is False: - LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident)) - raise errors.RadioError("Radio identification failed.") - - try: - serial.write(CMD_ACK) - ack = serial.read(1) - except: - raise errors.RadioError("Error communicating with radio") + if ident: + LOG.info('Radio identified with:\n%s', util.hexprint(ident)) + try: + serial.write(CMD_ACK) + ack = serial.read(1) + if ack != CMD_ACK: + raise errors.RadioError("Bad ACK after reading ident") + except: + raise errors.RadioError('No ACK after reading ident') + return ident - if ack != CMD_ACK: - raise errors.RadioError("Radio refused to enter programming mode") + raise errors.RadioError('No identification received from radio') -def _h777_exit_programming_mode(radio): - serial = radio.pipe +def _h777_exit_programming_mode(serial): try: serial.write(b"E") - except: + except Exception as e: + LOG.warning('Failed to send exit command: %s', e) raise errors.RadioError("Radio refused to exit programming mode") @@ -170,6 +166,8 @@ def _h777_read_block(radio, block_addr, block_size): serial.write(cmd) response = serial.read(4 + BLOCK_SIZE) if response[:4] != expectedresponse: + LOG.warning('Got %r expected %r' % (response[:4], + expectedresponse)) raise Exception("Error reading block %04x." % (block_addr)) block_data = response[4:] @@ -191,8 +189,7 @@ def _h777_write_block(radio, block_addr, block_size): cmd = struct.pack(">cHb", b'W', block_addr, BLOCK_SIZE) data = radio.get_mmap().get_byte_compatible()[block_addr:block_addr + 8] - LOG.debug("Writing Data:") - LOG.debug(util.hexprint(cmd + data)) + radio.pipe.log('Writing %i block at %04x' % (BLOCK_SIZE, block_addr)) try: serial.write(cmd + data) @@ -206,9 +203,26 @@ def _h777_write_block(radio, block_addr, block_size): "to radio at %04x" % block_addr) +def _h777_enter_single_programming_mode(radio): + ident = _h777_enter_programming_mode(radio.pipe, radio.__class__) + if not ident: + raise errors.RadioError('Radio did not identify') + if not any(rc_ident in ident for rc_ident in radio.IDENT): + LOG.warning('Expected %s for %s but got:\n%s', + radio.IDENT, radio.__class__.__name__, + util.hexprint(ident)) + raise errors.RadioError('Incorrect model') + + def do_download(radio): LOG.debug("download") - _h777_enter_programming_mode(radio) + + if len(radio.detected_models()) <= 1: + LOG.debug('Entering programming mode for %s', radio.__class__.__name__) + _h777_enter_single_programming_mode(radio) + else: + LOG.debug('Already in programming mode for %s', + radio.__class__.__name__) data = b"" @@ -222,13 +236,11 @@ def do_download(radio): status.cur = addr + BLOCK_SIZE radio.status_fn(status) + radio.pipe.log('Reading %i block at %04x' % (BLOCK_SIZE, addr)) block = _h777_read_block(radio, addr, BLOCK_SIZE) data += block - LOG.debug("Address: %04x" % addr) - LOG.debug(util.hexprint(block)) - - _h777_exit_programming_mode(radio) + _h777_exit_programming_mode(radio.pipe) return memmap.MemoryMapBytes(data) @@ -237,7 +249,7 @@ def do_upload(radio): status = chirp_common.Status() status.msg = "Uploading to radio" - _h777_enter_programming_mode(radio) + _h777_enter_single_programming_mode(radio) status.cur = 0 status.max = radio._memsize @@ -248,7 +260,7 @@ def do_upload(radio): radio.status_fn(status) _h777_write_block(radio, addr, BLOCK_SIZE) - _h777_exit_programming_mode(radio) + _h777_exit_programming_mode(radio.pipe) class ArcshellAR5(chirp_common.Alias): @@ -281,11 +293,6 @@ class TenwayTW325Alias(chirp_common.Alias): MODEL = 'TW-325' -class RetevisH777Alias(chirp_common.Alias): - VENDOR = 'Retevis' - MODEL = 'H777' - - @directory.register class H777Radio(chirp_common.CloneModeRadio): """HST H-777""" @@ -303,7 +310,7 @@ class H777Radio(chirp_common.CloneModeRadio): VALID_BANDS = (400000000, 490000000) MAX_VOXLEVEL = 5 ALIASES = [ArcshellAR5, ArcshellAR6, GV8SAlias, GV9SAlias, A8SAlias, - TenwayTW325Alias, RetevisH777Alias] + TenwayTW325Alias] SIDEKEYFUNCTION_LIST = ["Off", "Monitor", "Transmit Power", "Alarm"] SCANMODE_LIST = ["Carrier", "Time"] @@ -371,27 +378,31 @@ class H777Radio(chirp_common.CloneModeRadio): def get_raw_memory(self, number): return repr(self._memobj.memory[number - 1]) - def _decode_tone(self, val): - val = int(val) - if val == 16665: + def _decode_tone(self, memval): + memval[1].ignore_bits(DTCS_FLAG | DTCS_REV_FLAG) + is_dtcs = memval[1].get_bits(DTCS_FLAG) + is_rev = memval[1].get_bits(DTCS_REV_FLAG) + if memval.get_raw() == b"\xFF\xFF": return '', None, None - elif val >= 12000: - return 'DTCS', val - 12000, 'R' - elif val >= 8000: - return 'DTCS', val - 8000, 'N' + elif is_dtcs: + return 'DTCS', int(memval), 'R' if is_rev else 'N' else: - return 'Tone', val / 10.0, None + return 'Tone', int(memval) / 10.0, None def _encode_tone(self, memval, mode, value, pol): + memval[1].ignore_bits(DTCS_FLAG | DTCS_REV_FLAG) if mode == '': - memval[0].set_raw(0xFF) - memval[1].set_raw(0xFF) + memval.fill_raw(b'\xFF') elif mode == 'Tone': + memval[1].clr_bits(DTCS_FLAG | DTCS_REV_FLAG) memval.set_value(int(value * 10)) elif mode == 'DTCS': - flag = 0x80 if pol == 'N' else 0xC0 + memval[1].set_bits(DTCS_FLAG) + if pol == 'R': + memval[1].set_bits(DTCS_REV_FLAG) + else: + memval[1].clr_bits(DTCS_REV_FLAG) memval.set_value(value) - memval[1].set_bits(flag) else: raise Exception("Internal error: invalid mode `%s'" % mode) @@ -614,6 +625,37 @@ class H777Radio(chirp_common.CloneModeRadio): raise +@directory.register +class RetevisH777(H777Radio): + VENDOR = 'Retevis' + MODEL = 'H777' + ALIASES = [] + + @classmethod + def detect_from_serial(cls, pipe): + cls_to_ident = {rc: rc.IDENT for rc in cls.detected_models()} + for ident_rclass in reversed(cls.detected_models()): + ident = _h777_enter_programming_mode(pipe, ident_rclass) + for rclass, idents in cls_to_ident.items(): + if any(rc_ident in ident for rc_ident in idents): + LOG.debug('Detected %s', rclass.__name__) + return rclass + LOG.debug('Ident was %r, idents were %r', ident, idents) + + LOG.info('Did not identify radio as %s', rclass.__name__) + time.sleep(0.5) + _h777_exit_programming_mode(pipe) + time.sleep(1) + + raise errors.RadioError('Failed to identify with radio.') + + @classmethod + def match_model(cls, filedata, filename): + # This radio has always been post-metadata, so never do + # old-school detection + return False + + class H777TestCase(unittest.TestCase): def setUp(self): diff --git a/chirp/drivers/icf.py b/chirp/drivers/icf.py index cc4c9f8..bc62bd5 100644 --- a/chirp/drivers/icf.py +++ b/chirp/drivers/icf.py @@ -766,7 +766,12 @@ class IcomBankModel(chirp_common.BankModel): if index is None: return [] else: - return [self.get_mappings()[index]] + try: + return [self.get_mappings()[index]] + except IndexError: + LOG.error('Invalid bank index %i for memory %i' % ( + index, memory.number)) + return [] class IcomIndexedBankModel(IcomBankModel, @@ -944,7 +949,9 @@ class IcomCloneModeRadio(chirp_common.CloneModeRadio): nice_name = listname.split('_', 1)[0].upper() group = RadioSettingGroup('%s_list' % listname, '%s List' % nice_name) + charset = chirp_common.CHARSET_UPPER_NUMERIC + '-' for i, cs in enumerate(current): + cs = ''.join(filter(lambda c: c in charset, cs)) group.append(RadioSetting('%03i' % i, '%i' % i, RadioSettingValueString(0, 8, cs))) return group diff --git a/chirp/drivers/icf520.py b/chirp/drivers/icf520.py index 0304217..2caa5dc 100644 --- a/chirp/drivers/icf520.py +++ b/chirp/drivers/icf520.py @@ -337,8 +337,8 @@ TONES = [ DUPLEX = ["", "+", "-", "split", "off"] -# Valid values for programable keys. -# Hex numbers are used for unkown functions. +# Valid values for programmable keys. +# Hex numbers are used for unknown functions. KEY_FUNC = [ "Null", "CH Up", @@ -493,7 +493,7 @@ AUDIO_FILTER_VALUES = [ ] # Valid values for Mic Gain. -# Hex numbers are used for unkown functions. +# Hex numbers are used for unknown functions. MIC_GAIN_FUNC = [ "0x00", "1 Min", @@ -544,7 +544,7 @@ SCRAMBLER_GCODE_VALUES = [ ] # Valid values for Scrambler Synchronous Capture. -# Hex numbers are used for unkown functions. +# Hex numbers are used for unknown functions. SYN_CAPTURE_FUNC = [ "Standard", "0x01", @@ -797,7 +797,7 @@ class ICF621_2Radio(icf.IcomCloneModeRadio): memory.extra = RadioSettingGroup('extra', 'Extra') # Mask (Don't display) channel on radio. - # This is refered as Inhibit in the CS-F500 software. + # This is referred as Inhibit in the CS-F500 software. _disp_inhibit = RadioSetting( "disp_inhibit", "Mask", RadioSettingValueList( diff --git a/chirp/drivers/icomciv.py b/chirp/drivers/icomciv.py index 799cac7..af46fa9 100644 --- a/chirp/drivers/icomciv.py +++ b/chirp/drivers/icomciv.py @@ -1018,7 +1018,7 @@ class Icom7100Radio(IcomCIVRadio): self._rf.has_dtcs_polarity = False self._rf.has_dtcs = False self._rf.has_ctone = True - self._rf.has_offset = False + self._rf.has_offset = True self._rf.has_name = True self._rf.has_tuning_step = False self._rf.valid_modes = [ diff --git a/chirp/drivers/icv80.py b/chirp/drivers/icv80.py index 1564a9e..b6bcf3d 100644 --- a/chirp/drivers/icv80.py +++ b/chirp/drivers/icv80.py @@ -410,7 +410,7 @@ class ICV80Radio(icf.IcomCloneModeRadio, chirp_common.ExperimentalRadio): if mem.extd_number == "": mem.name = str(_mem.name).rstrip() mem.skip = (_skip & bit) and "S" or "" - if _mem.tx_inhibit: + if not _mem.tx_inhibit: mem.duplex = 'off' else: mem.duplex = DUPLEXES[_mem.duplex] @@ -497,6 +497,7 @@ class ICV80Radio(icf.IcomCloneModeRadio, chirp_common.ExperimentalRadio): _mem.duplex = DUPLEXES.index(mem.duplex) except ValueError: _mem.duplex = 0 + _mem.tx_inhibit = mem.duplex != 'off' power = mem.power or POWER_LEVELS[0] _mem.power = POWER_LEVELS.index(power) _mem.tuning_step = TUNING_STEPS.index(mem.tuning_step) @@ -506,7 +507,6 @@ class ICV80Radio(icf.IcomCloneModeRadio, chirp_common.ExperimentalRadio): _mem.ctone = chirp_common.TONES.index(mem.ctone) _mem.dtcs = chirp_common.DTCS_CODES.index(mem.dtcs) _mem.dtcs_polarity = DTCS_POLARITY.index(mem.dtcs_polarity) - _mem.tx_inhibit = mem.duplex == 'off' # Set used _unused &= ~bit diff --git a/chirp/drivers/id51.py b/chirp/drivers/id51.py index 0146036..0e6b09f 100644 --- a/chirp/drivers/id51.py +++ b/chirp/drivers/id51.py @@ -127,6 +127,9 @@ class ID51Radio(id31.ID31Radio): def get_features(self): rf = super(ID51Radio, self).get_features() rf.valid_bands = [(108000000, 174000000), (400000000, 479000000)] + # The ID-51 D-STAR support seems broken, so disable getting settings + # that will contain the base-class call list support. + rf.has_settings = False return rf def process_mmap(self): diff --git a/chirp/drivers/kenwood_live.py b/chirp/drivers/kenwood_live.py index 79cffe1..52475bc 100644 --- a/chirp/drivers/kenwood_live.py +++ b/chirp/drivers/kenwood_live.py @@ -1046,6 +1046,7 @@ THK2_CHARS = chirp_common.CHARSET_UPPER_NUMERIC + "-/" class THK2Radio(KenwoodLiveRadio): """Kenwood TH-K2""" MODEL = "TH-K2" + HARDWARE_FLOW = False _kenwood_valid_tones = list(KENWOOD_TONES) diff --git a/chirp/drivers/mml_jc8810.py b/chirp/drivers/mml_jc8810.py index 033ec87..1ba0a5d 100644 --- a/chirp/drivers/mml_jc8810.py +++ b/chirp/drivers/mml_jc8810.py @@ -1297,6 +1297,7 @@ class RT470Radio(JC8810base): b"\x00\x00\x00\x42\x00\x20\xF0\x04", b"\x00\x00\x00\x4A\x00\x20\xF8\x04", b"\x00\x00\x00\x3A\x00\x20\xE8\x04", # fw 1.25A + b"\x00\x00\x00\x42\x00\x20\xec\x04", # fw 1.27A ] # pcb 2 @@ -1579,6 +1580,7 @@ class RT630Radio(JC8810base): # ========== _fingerprint = [b"\x00\x00\x00\x32\x00\x20\xD8\x04", # fw 0.07 + b"\x00\x00\x00\x36\x00\x20\xDC\x04", # fw V0.09 20250703 ] POWER_LEVELS = [chirp_common.PowerLevel("H", watts=5.00), diff --git a/chirp/drivers/radioddity_gm30.py b/chirp/drivers/radioddity_gm30.py new file mode 100644 index 0000000..b08a241 --- /dev/null +++ b/chirp/drivers/radioddity_gm30.py @@ -0,0 +1,951 @@ +# Copyright 2025 Mike Iacovacci <ascendr@linuxmail.org> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import struct +import logging + +from chirp import chirp_common, directory, memmap +from chirp import bitwise, errors +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueInteger, RadioSettingValueList, \ + RadioSettingValueBoolean, RadioSettingValueString, RadioSettings + +LOG = logging.getLogger(__name__) + +MEM_FORMAT = """ +struct{ + u8 unknown02[256]; +} unknown02[16]; +struct{ + u8 bootscrmode; + u8 bsmodepad[15]; + u8 bootscreen1[10]; + u8 bs1pad[6]; + u8 bootscreen2[10]; + u8 bs2pad[6]; + u8 unused[16]; + u8 timeout; + u8 squelch; + u8 vox_level; + u8 batt_save:4, + unk_bits:2, + work_mode:1, + voice_alert:1; + u8 backlight; + u8 beep_tone:1, + auto_key_lock:1, + unk_bit_2:1, + ctcss_revert:1, + scan_type:2, + side_tone:2; + u8 unk_bit_3:1, + standby:1, + roger:1, + alarm_mode:2, + alarm_sound:1, + fm_radio:1, + unk_bit_4:1; + u8 tail_revert; + u8 tail_delay; + u8 tbst; + u8 unk_bits_5:6, + a_ch_disp:1, + b_ch_disp:1; + u8 unk_sett[30]; + u8 passw_w_ena; + u8 passw_r_ena; + u8 passw_w_val[8]; + u8 passw_r_val[8]; + u8 unk_sett_2[5]; +} settings; +struct{ + u8 unusedsettings[32]; +} unusedsettings[124]; +struct{ + u8 entry[5]; +} dtmf_list[15]; +struct{ + u8 dtmf_l_pad[5]; + u8 radio_id[5]; + u8 unk_dtmf[11]; + u8 unk_dtmf_bits:6, + press_send:1, + release_send:1; + u8 delay_time; + u8 digit_dur; + u8 inter_dur; + u8 unk_dtmf_2[28]; +} dtmf; +struct{ + u8 unkdtmf[128]; +} unuseddtmf[31]; +struct{ + u8 unk_mem[16]; +} tuning; +struct { + lbcd rx_freq[4]; + lbcd tx_freq[4]; + u8 mem_changed; + lbcd rx_tone[2]; + lbcd tx_tone[2]; + u8 unk_mem2:1, + busy_lock:1, + ptt_id:2, + unk_mem3:1, + mode:1, + power:1, + unk_mem4:1; + u8 signal:4, + unk_mem5:2, + freq_hop:1, + scan:1; + u8 step; +} vfomemory[2]; +struct { + lbcd rx_freq[4]; + lbcd tx_freq[4]; + u8 mem_changed; + lbcd rx_tone[2]; + lbcd tx_tone[2]; + u8 unk_mem2:1, + busy_lock:1, + ptt_id:2, + unk_mem3:1, + mode:1, + power:1, + unk_mem4:1; + u8 signal:4, + unk_mem5:2, + freq_hop:1, + scan:1; + u8 step; +} memory[250]; +struct{ + u8 unused_memch[16]; +} unused_mem[3]; +struct{ + u8 unknown17[256]; +} unknown17[16]; +struct{ + u8 unknown18[256]; +} unknown18[16]; +struct{ + u8 unknown19[256]; +} unknown19[16]; +struct{ + char name[6]; + u8 pad[5]; +} memnames[250]; +struct{ + u8 unknames[64]; +} unknownnames [21]; +struct{ + u8 unknown25[256]; +} unknown25[16]; +struct{ + u8 unknown26[256]; +} unknown26[16]; +""" +# radio defines these types +# query each type to retrieve +# the mem location it is stored +TYPE_MAP = [ + (0x02, "unknown02"), + (0x04, "settings"), + (0x06, "dtmf"), + (0x16, "memories"), + (0x17, "unknown17"), + (0x18, "unknown18"), + (0x19, "unknown19"), + (0x24, "chan_names"), + (0x25, "unknown25"), + (0x26, "unknown26") +] + +# we only write these data types +# back to the radio. The 3rd tuple +# being the offset in _memobj +WRITE_MAP = [ + (0x04, "settings", 0x1000), + (0x06, "dtmf", 0x2000), + (0x16, "memories", 0x3000), + (0x24, "chan_names", 0x7000) +] + + +def do_ack_ack(serial): + serial.write(b'\x06') + ack = serial.read(1) + if ack != b'\x06': + err = f"Error expected 06 ack got {ack}" + LOG.debug(err) + raise errors.RadioError(err) + + +def raw_send(serial, data, exlen): + serial.write(data) + return serial.read(exlen) + + +def do_read_cmd(serial, cmd, exlen): + echo_ack = len(cmd) + 1 # ack 0x57 + echo of cmd + resp = raw_send(serial, b'\x52' + cmd, exlen + echo_ack) + if resp[0] != 0x57: + raise errors.RadioError(f"Read CMD resp failed got {resp}") + if len(resp[echo_ack:]) != exlen: + raise errors.RadioError(f"Read CMD resp expect len={exlen} got {resp}") + do_ack_ack(serial) + return resp[echo_ack:] + + +def enter_prog(serial): + resp = raw_send(serial, b'PSEARCH', 8) + if len(resp) != 8: + err = ("Enter programming failed" + + f" Resp : {resp}") + raise errors.RadioError(err) + if resp[0] != 0x06: + raise errors.RadioError("Enter programming: " + + f"Radio Bad Ack: {resp}") + return resp[1:] + + +def exit_prog(serial): + try: + serial.write(b'\x06') + serial.write(b'\x06') + serial.write(b'\x00') + serial.close() + LOG.debug("Exited programming") + except Exception as e: + raise errors.RadioError(f"Error exiting programming {e}") + + +def check_ident(data): + if data == b'P13GMRS': + LOG.info(f"Radio is: {data}") + else: + err = (f"Ident returned unknown Radio: {data}") + LOG.debug(err) + raise errors.RadioError(err) + + +def do_sysinfo(serial): + resp = raw_send(serial, b'PASSSTA', 3) + if resp != b'\x50\x00\x00': + raise errors.RadioError(f"Expected 0x500000 got {resp}") + resp = raw_send(serial, b'SYSINFO', 1) + if resp != b'\x06': + raise errors.RadioError(f"ACK expected got {resp}") + LOG.debug(f"SYSINFO: {resp}") + + +def do_readconfig(serial): + # cmds start with 56, and expect 06 ack after recv ack + for addr, _len in [(0x00000a0d, 13), (0x00100a0d, 13), + (0x00200a0d, 13), (0x0000000a, 11)]: + cmd = struct.pack('>BL', 0x56, addr) + resp = raw_send(serial, cmd, _len) + if len(resp) != _len: + raise errors.RadioError(f"Expected (_len) Bytes got {resp}") + do_ack_ack(serial) + return True + + +def do_prog2(serial): + cmd = struct.pack('>LB', 0xffffffff, 0x0c) + serial.write(cmd) # no resp expected + resp = raw_send(serial, b'P13GMRS', 1) + if resp != b'\x06': + raise errors.RadioError(f"Error expected 06 ack got {resp}") + resp = raw_send(serial, b'\x02', 8) + if len(resp) != 8: + raise errors.RadioError(f"Error expected len 8 got {resp}") + do_ack_ack(serial) + + +def do_read_tlmap(serial): + """ The radio has defined types of config data. + Before reading or writing, we ask the radio where + The data type is stored in memory. The radio + moves memory locations possibly for durability + Build ephemeral map of type to location """ + tl_map = {m[0]: 0 for m in TYPE_MAP} + for i in range(1, 16): + addr = (i << 4 | 0x0f) + # ask the radio where each data type is in mem + cmd = struct.pack('>4B', 0xff, addr, 0x00, 0x01) + resp = do_read_cmd(serial, cmd, 1) + # mem location is for this prog session only + r_int = struct.unpack('>B', resp)[0] + if r_int in tl_map: + tl_map[r_int] = (i << 4) + return tl_map + + +def do_read_ranges(serial, loc, radio, status): + # read each data/config type from the (loc)ation + # obtained by tlmap query. each loc has 4 (pre)fix + # block numbers. Each block is 64 bytes + data = b'' + for i in range(16): + for pre in range(0x0, 0xc1, 0x40): + addr = struct.pack('>BBBB', pre, loc + i, 0x00, 0x40) + data += do_read_cmd(serial, addr, 0x40) + status.cur += 0x40 + radio.status_fn(status) + return data + + +def do_upload_block(serial, loc, offset, radio, status): + # write each config type to loc retrieved from tlmap + # 4 defined (pre)fixes/blocks per (loc)ation + # pre = 0x00 , 0x40 , 0x80, 0xc0 + # full command example [57][80][4d]0040 + # 57 = write , 80 prefix/block , 4d location to write + _mem = radio._memobj.get_raw() + for i in range(16): + for pre in range(0x0, 0xc1, 0x40): + x = offset + (i * 0x100) + pre + block = _mem[x:x + 0x40] + addr = struct.pack('>BBBBB', 0x57, pre, loc + i, 0x00, 0x40) + data = addr + block + ack = raw_send(serial, data, 1) + if ack != b'\x06': + err = f"Bad ack on write expect 0x06 got {ack}" + LOG.debug(err) + raise errors.RadioError(err) + status.cur += len(block) + radio.status_fn(status) + + +def do_download(radio): + data = b'' + try: + status = chirp_common.Status() + serial = radio.pipe + serial.flush() + ident = enter_prog(serial) + check_ident(ident) + do_sysinfo(serial) + do_readconfig(serial) + do_prog2(serial) + tl_map = do_read_tlmap(serial) + status.max = len(tl_map) * 0x1000 + status.msg = "Downloading..." + for t, loc in tl_map.items(): + if loc == 0: + raise errors.RadioError(f"TL Map failed {t} {loc}") + data += do_read_ranges(serial, loc, radio, status) + except Exception as e: + raise errors.RadioError(f"Error during download {e}") + finally: + exit_prog(serial) + return memmap.MemoryMapBytes(data) + + +def do_upload(radio): + try: + status = chirp_common.Status() + status.max = len(WRITE_MAP) * 0x1000 + serial = radio.pipe + serial.flush() + ident = enter_prog(serial) + check_ident(ident) + do_sysinfo(serial) + do_readconfig(serial) + do_prog2(serial) + tl_map = do_read_tlmap(serial) + for wt, label, offset in WRITE_MAP: + status.msg = f"Uploading: {label}..." + loc = tl_map[wt] + do_upload_block(serial, loc, offset, radio, status) + except errors.RadioError: + raise + except Exception as e: + raise errors.RadioError(f"Error during upload {e}") + finally: + exit_prog(serial) + + +@directory.register +class RadioddityGM30(chirp_common.CloneModeRadio): + """Radioddity GM-30""" + VENDOR = "Radioddity" + MODEL = "GM-30" + BAUD_RATE = 57600 + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50), + chirp_common.PowerLevel("High", watts=3.00)] + VALID_MODES = ["NFM", "FM"] + _range = [(136000000, 174000000), (400000000, 470000000)] + GMRS_RPTR = [462550000, 462575000, 462600000, 462625000, 462650000, + 462675000, 462700000, 462725000] + + VALID_TONES = chirp_common.TONES + VALID_DCS = [i for i in range( + 0, 778) if '9' not in str(i) and '8' not in str(i)] + DCS_N = 0x80 + DCS_R = 0x40 + VALID_CHARSET = chirp_common.CHARSET_ASCII + VALID_DTMF = [str(i) for i in range(0, 10)] + \ + ["A", "B", "C", "D", "*", "#"] + ASCII_NUM = [str(i) for i in range(10)] + [' '] + + VALID_STEPS = [2.5, 5.0, 6.25, 10, 12.5, 20, 25, 50] + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.has_bank = False + rf.has_tuning_step = False + rf.valid_tuning_steps = self.VALID_STEPS + rf.has_name = True + rf.valid_characters = self.VALID_CHARSET + rf.valid_name_length = 6 + rf.has_offset = True + rf.has_mode = True + rf.has_dtcs = True + rf.has_rx_dtcs = True + rf.has_dtcs_polarity = True + rf.has_ctone = True + rf.has_cross = True + rf.can_odd_split = False + rf.can_delete = True + rf.valid_modes = self.VALID_MODES + rf.valid_duplexes = ["", "-", "+", "off"] + rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] + rf.valid_cross_modes = [ + "Tone->DTCS", + "DTCS->Tone", + "->Tone", + "Tone->Tone", + "->DTCS", + "DTCS->", + "DTCS->DTCS"] + rf.valid_power_levels = self.POWER_LEVELS + rf.valid_skips = ["", "S"] + rf.valid_bands = self._range + rf.memory_bounds = (1, 250) + return rf + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def sync_in(self): + try: + data = do_download(self) + except errors.RadioError: + raise + except Exception as e: + err = f'Error during download {e}' + LOG.error(err) + raise errors.RadioError(err) + self._mmap = data + self.process_mmap() + + def sync_out(self): + try: + do_upload(self) + except Exception as e: + err = f'Error during upload {e}' + LOG.error(err) + raise errors.RadioError(err) + + def val_or_def(self, memidx, _list): + try: + return _list[memidx] + except IndexError: + return _list[0] + + def idx_or_def(self, memitem, _list): + try: + return _list.index(memitem) + except ValueError: + return 0 + + def get_str_name(self, _name): + return ''.join(filter + (lambda x: x in self.VALID_CHARSET, + str(_name))) + + def get_memory(self, number): + mem = chirp_common.Memory() + mem.number = number + _mem = self._memobj.memory[number-1] + _name = self._memobj.memnames[number-1]["name"] + str_name = self.get_str_name(_name) + mem.name = str_name.rstrip() + + if _mem.rx_freq.get_raw() == b'\xff\xff\xff\xff': + mem.empty = True + return mem + + mem.freq = int(_mem.rx_freq) * 10 + + if _mem.tx_freq.get_raw() == b'\xff\xff\xff\xff': + mem.duplex = 'off' + elif int(_mem.tx_freq) - int(_mem.rx_freq) > 0: + # '+' duplex + mem.duplex = '+' + mem.offset = (int(_mem.tx_freq) - int(_mem.rx_freq)) * 10 + elif int(_mem.tx_freq) - int(_mem.rx_freq) < 0: + # '-' duplex + mem.duplex = '-' + mem.offset = (int(_mem.rx_freq) - int(_mem.tx_freq)) * 10 + + mem.mode = self.val_or_def(_mem.mode, self.VALID_MODES) + mem.power = self.val_or_def(_mem.power, self.POWER_LEVELS) + mem.skip = "" if _mem.scan else "S" + + if 1 <= mem.number <= 7 or 15 <= mem.number <= 22: + mem.duplex = "" + mem.immutable = ['duplex', 'offset', 'empty'] + elif 8 <= mem.number <= 14: + mem.duplex = "off" + mem.immutable += ['duplex', 'offset', 'empty', 'mode', 'power'] + elif 23 <= mem.number <= 54: + mem.offset = 5 * 1000000 + mem.duplex = '+' + mem.immutable = ['duplex', 'offset', 'empty'] + else: + mem.offset = 0 + mem.duplex = "off" + mem.immutable += ['offset', 'duplex'] + if 0 < mem.number <= 30: + mem.immutable = mem.immutable + ['freq'] + + txtone = self.get_tone(_mem.tx_tone) + rxtone = self.get_tone(_mem.rx_tone) + chirp_common.split_tone_decode(mem, txtone, rxtone) + + mem.extra = RadioSettingGroup("Extra", "extra") + + rs = RadioSettingValueBoolean(_mem.busy_lock) + rset = RadioSetting("busy_lock", "Busy Lock", rs) + mem.extra.append(rset) + + rs = RadioSettingValueBoolean(_mem.freq_hop) + rset = RadioSetting("freq_hop", "Freq. Hop", rs) + mem.extra.append(rset) + + _current = _mem.signal if _mem.signal else 1 + rs = RadioSettingValueInteger(1, 15, current=_current) + rset = RadioSetting("signal", "DTMF ID", rs) + mem.extra.append(rset) + + options = ['Off', 'BOT', 'EOT', 'BOTH'] + rs = RadioSettingValueList(options, current_index=_mem.ptt_id) + rset = RadioSetting("ptt_id", "PTT ID", rs) + mem.extra.append(rset) + + return mem + + def validate_memory(self, mem): + if 31 <= mem.number <= 54: + if mem.freq not in self.GMRS_RPTR: + return [chirp_common.ValidationError( + 'Only GMRS repeater freq. permitted' + ' on channels 31 - 54')] + return super().validate_memory(mem) + + def set_memory(self, mem): + number = mem.number + _mem = self._memobj.memory[number-1] + _name = self._memobj.memnames[number-1] + newname = [str(c) for c in mem.name] + _name.name = "".join(newname).ljust(6, '\x00') + + if mem.empty: + _mem.set_raw(b'\xff' * 13 + b'\x06\x11\x00') + return + + _mem.rx_freq = mem.freq // 10 + + if mem.duplex == "+": + _mem.tx_freq = (mem.freq + mem.offset) // 10 + elif mem.duplex == "-": + _mem.tx_freq = (mem.freq - mem.offset) // 10 + elif mem.duplex == "": + _mem.tx_freq = _mem.rx_freq + elif mem.duplex == "off": + _mem.tx_freq.fill_raw(b'\xff') + + _mem.mode = self.idx_or_def(mem.mode, self.VALID_MODES) + _mem.power = self.idx_or_def(mem.power, self.POWER_LEVELS) + _mem.scan = False if mem.skip == "S" else True + + ((txmode, txval, txpol), + (rxmode, rxval, rxpol)) = chirp_common.split_tone_encode(mem) + self.set_tone(_mem.tx_tone, txmode, txval, txpol) + self.set_tone(_mem.rx_tone, rxmode, rxval, rxpol) + + # extra settings + for setting in mem.extra: + setattr(_mem, setting.get_name(), setting.value) + + def get_tone(self, _memval): + _memval[1].ignore_bits(self.DCS_N | self.DCS_R) + dcsn = _memval[1].get_bits(self.DCS_N) + dcsr = _memval[1].get_bits(self.DCS_R) + rb = _memval[1].get_raw() + if rb == b'\xff' or rb == b'\x00': + return "", 0, None + elif dcsn: + pol = "R" if dcsr else "N" + return "DTCS", int(_memval), pol + else: + return "Tone", int(_memval) / 10, None + + def set_tone(self, _memval, mode, val, pol): + # sets tones in _mem from ui edit + _memval[1].ignore_bits(self.DCS_N | self.DCS_R) + if mode == "": + _memval.set_raw(b'\xff\xff') + if mode == "Tone": + _memval[1].clr_bits(self.DCS_N | self.DCS_R) + _memval.set_value(val * 10) + if mode == "DTCS": + _memval[1].set_bits(self.DCS_N) + if pol == 'R': + _memval[1].set_bits(self.DCS_R) + else: + _memval[1].clr_bits(self.DCS_R) + _memval.set_value(val) + + def get_settings(self): + _settings = self._memobj.settings + _dtmf = self._memobj.dtmf + _dtmf_list = self._memobj.dtmf_list + + gsettings = RadioSettingGroup("gsettings", "General Settings") + group = RadioSettings(gsettings) + + _options = ["Logo", "Message", "Voltage"] + rs = RadioSettingValueList(_options, + current_index=_settings.bootscrmode) + rset = RadioSetting("settings.bootscrmode", "Boot Screen Mode", rs) + gsettings.append(rset) + + _current = "".join(chr(i) for i in _settings.bootscreen1 + if chr(i) in self.VALID_CHARSET) + rs = RadioSettingValueString(minlength=0, maxlength=10, + current=_current, + charset=self.VALID_CHARSET, + mem_pad_char=' ') + rset = RadioSetting("settings.bootscreen1", + "Boot Screen 1", rs) + gsettings.append(rset) + + _current = "".join(chr(i) for i in _settings.bootscreen2 + if chr(i) in self.VALID_CHARSET) + rs = RadioSettingValueString(minlength=0, maxlength=10, + current=_current, + charset=self.VALID_CHARSET, + mem_pad_char=' ') + rset = RadioSetting("settings.bootscreen2", + "Boot Screen 2", rs) + gsettings.append(rset) + + _options = [str(i) for i in range(0, 601, 15)] + rs = RadioSettingValueList(_options, + current_index=_settings.timeout) + rset = RadioSetting("settings.timeout", "Timeout (s)", rs) + gsettings.append(rset) + + rs = RadioSettingValueInteger(minval=0, maxval=9, + current=_settings.squelch, step=1) + rset = RadioSetting("settings.squelch", "Squelch Level", rs) + gsettings.append(rset) + + rs = RadioSettingValueInteger(minval=0, maxval=9, + current=_settings.vox_level, step=1) + rset = RadioSetting("settings.vox_level", "Vox Level", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.voice_alert, mem_vals=(0, 1)) + rset = RadioSetting("settings.voice_alert", "Voice Alert", rs) + gsettings.append(rset) + + _options = ["Freq. Mode", "Ch. Mode"] + rs = RadioSettingValueList(_options, + current_index=_settings.work_mode) + rset = RadioSetting("settings.work_mode", "Display Mode", rs) + gsettings.append(rset) + + _options = ["None", "1:1", "1:2", "1:3", "1:4"] + rs = RadioSettingValueList(_options, + current_index=_settings.batt_save) + rset = RadioSetting("settings.batt_save", "Battery Save Mode", rs) + gsettings.append(rset) + + _options = ["Bright", "1", "2", "3", "4", "5", + "6", "7", "8", "9", "10"] + rs = RadioSettingValueList(_options, + current_index=_settings.backlight) + rset = RadioSetting("settings.backlight", "Backlight", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.auto_key_lock, mem_vals=(0, 1)) + rset = RadioSetting("settings.auto_key_lock", "Auto Key Lock", rs) + gsettings.append(rset) + + _options = ["Off", "DT-ST", "ANI-ST", "DT+ANI"] + rs = RadioSettingValueList(_options, + current_index=_settings.side_tone) + rset = RadioSetting("settings.side_tone", "DTMF Side Tone", rs) + gsettings.append(rset) + + _options = ["Time", "Carrier", "Search"] + rs = RadioSettingValueList(_options, + current_index=_settings.scan_type) + rset = RadioSetting("settings.scan_type", "Scan Type", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.ctcss_revert, mem_vals=(0, 1)) + rset = RadioSetting("settings.ctcss_revert", "CTCSS Tail Revert", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.beep_tone, mem_vals=(0, 1)) + rset = RadioSetting("settings.beep_tone", "Beep Tone", rs) + gsettings.append(rset) + + _options = ["On Site", "Send Sound", "Send Code"] + rs = RadioSettingValueList(_options, + current_index=_settings.alarm_mode) + rset = RadioSetting("settings.alarm_mode", "Alarm Mode", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.fm_radio, mem_vals=(0, 1)) + rset = RadioSetting("settings.fm_radio", "FM Radio", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.roger, mem_vals=(0, 1)) + rset = RadioSetting("settings.roger", "Roger Beep", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.standby, mem_vals=(0, 1)) + rset = RadioSetting("settings.standby", "Dual Standby", rs) + gsettings.append(rset) + + _options = [str(i) for i in range(0, 1001, 100)] + rs = RadioSettingValueList(_options, + current_index=_settings.tail_revert) + rset = RadioSetting("settings.tail_revert", + "Repeater Tail Revert (ms)", rs) + gsettings.append(rset) + + # same options as tail_rvt + rs = RadioSettingValueList(_options, + current_index=_settings.tail_delay) + rset = RadioSetting("settings.tail_delay", + "Repeater Tail Delay (ms)", rs) + gsettings.append(rset) + + _options = ["1000", "1450", "1750", "2100"] + rs = RadioSettingValueList(_options, + current_index=_settings.tbst) + rset = RadioSetting("settings.tbst", "Tone Burst", rs) + gsettings.append(rset) + + _options = ["Name + Number", "Freq. + Number"] + rs = RadioSettingValueList(_options, + current_index=_settings.a_ch_disp) + rset = RadioSetting("settings.a_ch_disp", "A Channel Display Type", rs) + gsettings.append(rset) + + # same options as a_chan_disp + rs = RadioSettingValueList(_options, + current_index=_settings.b_ch_disp) + rset = RadioSetting("settings.b_ch_disp", "B Channel Display Type", rs) + gsettings.append(rset) + + # DTMF Menu + dtmf = RadioSettingGroup("dtmf", "DTMF") + group.append(dtmf) + + def _dtmf_decode(setting, pad_len): + _map = list(range(10)) + ['A', 'B', 'C', 'D', '*', '#'] + s = "" + for i in setting: + _i = int(i) + if _i < len(_map): + s += str(_map[_i]) + return s.ljust(pad_len) + + _current = _dtmf_decode(_dtmf.radio_id, 5) + rs = RadioSettingValueString( + minlength=5, maxlength=5, current=_current) + rset = RadioSetting("dtmf.radio_id", "Radio ID", rs) + dtmf.append(rset) + + rs = RadioSettingValueBoolean( + current=_dtmf.press_send, mem_vals=(0, 1)) + rset = RadioSetting("dtmf.press_send", "PTT Press Send", rs) + dtmf.append(rset) + + rs = RadioSettingValueBoolean( + current=_dtmf.release_send, mem_vals=(0, 1)) + rset = RadioSetting("dtmf.release_send", "PTT Release Send", rs) + dtmf.append(rset) + + _options = [str(i) for i in range(100, 1010, 50)] + rs = RadioSettingValueList(_options, + current_index=_dtmf.delay_time) + rset = RadioSetting("dtmf.delay_time", "Delay Time (ms)", rs) + dtmf.append(rset) + + _options = [str(i) for i in range(80, 2010, 10)] + rs = RadioSettingValueList(_options, + current_index=_dtmf.digit_dur) + rset = RadioSetting("dtmf.digit_dur", "Digit Duration (ms)", rs) + dtmf.append(rset) + + # uses same options as digit_dur + rs = RadioSettingValueList(_options, + current_index=_dtmf.inter_dur) + rset = RadioSetting( + "dtmf.inter_dur", "Digit Interval Duration (ms)", rs) + dtmf.append(rset) + + # DTMF Entries List + dtmflist = RadioSettingGroup("dtmflist", "DTMF List") + group.append(dtmflist) + for i in range(0, 15): # Entries # 1-15 + rs = RadioSettingValueString( + minlength=0, maxlength=5, + current=_dtmf_decode(_dtmf_list[i].entry, 5), + autopad=False, + charset=self.VALID_DTMF + [' ']) + rset = RadioSetting(f"dtmf_list[{i}].entry", f"Entry {i+1}", rs) + dtmflist.append(rset) + + # Password Menu + pro = RadioSettingGroup("protect", "Protect") + group.append(pro) + + def _ascii_num_filter(setting): + s = "" + for i in setting: + if chr(i) in self.ASCII_NUM: + s += str(chr(i)) + return s + + rs = RadioSettingValueBoolean( + current=_settings.passw_w_ena, mem_vals=(0, 1)) + rs.set_mutable(False) + rset = RadioSetting("settings.passw_w_ena", "Write Protect", rs) + pro.append(rset) + + _current = _ascii_num_filter(_settings.passw_w_val) + rs = RadioSettingValueString( + minlength=0, maxlength=8, current=_current, + charset=self.ASCII_NUM) + rs.set_mutable(False) + rset = RadioSetting("settings.passw_w_val", "Write Password", rs) + pro.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.passw_r_ena, mem_vals=(0, 1)) + rs.set_mutable(False) + rset = RadioSetting("settings.passw_r_ena", "Read Protect", rs) + pro.append(rset) + + _current = _ascii_num_filter(_settings.passw_r_val) + rs = RadioSettingValueString( + minlength=0, maxlength=8, current=_current, + charset=self.ASCII_NUM) + rs.set_mutable(False) + rset = RadioSetting("settings.passw_r_val", "Read Password", rs) + pro.append(rset) + + return group + + def _ff_pad__mem(self, obj, setting, element, charset, allow_space=False): + """ set_settings helper for 0xff padded elements + optional remove space chars + """ + _charset = [c for c in list(charset)] + if not allow_space: + _charset = [c for c in list(charset) if c != ' '] + _val = [0xff] * len(obj[setting]) + _i = 0 # offset for invalid chars + for i in range(len(obj[setting])): + if element.value[i] in _charset: + _val[i - _i] = ord(element.value[i]) + else: + _i += 1 + setattr(obj, setting, _val) + + def _dtmf_set__mem(self, obj, setting, element): + _dtmf_map = [str(i) for i in range(10)] + _dtmf_map += ['A', 'B', 'C', 'D', '*', '#'] + _val = [0xff] * len(obj[setting]) + _os = 0 # offset _mem setting idx for pad chars + for i in range(len(element.value)): + if element.value[i] in _dtmf_map: + _val[i - _os] = _dtmf_map.index(element.value[i]) + else: + _os += 1 + setattr(obj, setting, _val) + + def set_settings(self, settings): + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + continue + else: + try: + if "." in element.get_name(): + toks = element.get_name().split(".") + obj = self._memobj + for tok in toks[:-1]: + if '[' in tok: + t, i = tok.split("[") + i = int(i[:-1]) + obj = getattr(obj, t)[i] + else: + obj = getattr(obj, tok) + setting = toks[-1] + else: + obj = self._memobj.settings + setting = element.get_name() + + if element.has_apply_callback(): + LOG.debug("applying callback") + element.run_apply_callback() + + if element.value.get_mutable(): + if setting in ['passw_w_val', 'passw_r_val']: + self._ff_pad__mem( + obj, setting, element, self.ASCII_NUM) + elif setting in ['bootscreen1', 'bootscreen2']: + self._ff_pad__mem( + obj, setting, element, self.VALID_CHARSET, + allow_space=True) + elif setting == 'entry': + self._dtmf_set__mem( + obj, setting, element) + else: + setattr(obj, setting, element.value) + except Exception: + LOG.debug(element.get_name()) + raise diff --git a/chirp/drivers/retevis_h777v4.py b/chirp/drivers/retevis_h777v4.py new file mode 100644 index 0000000..a61998b --- /dev/null +++ b/chirp/drivers/retevis_h777v4.py @@ -0,0 +1,505 @@ +# Copyright 2025 Jim Unroe <rock.unroe@gmail.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import logging +import struct + +from chirp import ( + bitwise, + chirp_common, + directory, + errors, + memmap, + util, +) +from chirp.drivers import h777 +from chirp.settings import ( + MemSetting, + RadioSettingGroup, + RadioSettings, + RadioSettingValueBoolean, + RadioSettingValueInvertedBoolean, + RadioSettingValueInteger, + RadioSettingValueList, +) + +LOG = logging.getLogger(__name__) + +MEM_FORMAT = """ +struct { + ul32 rxfreq; // 0-3 + ul32 txfreq; // 4-7 + lbcd rx_tone[2]; // 8-9 + lbcd tx_tone[2]; // A-B + u8 unknown0:2, // C + scramb:1, // Scramble 0 = Off, 1 = On + scanadd:1, // Scan Add 0 = Scan, 1 = Skip + ishighpower:1, // Power Level 0 = Low, 1 = High + narrow:1, // Bandwidth 0 = Wide, 1 = Narrow + unknown1:1, // + bcl:1; // Busy Channel Locklut 0 = On, 1 = Off +} memory[16]; + +struct { + u8 codesw:1, // 00D0 Code Switch + scanm:1, // Scan Mode + voxs:1, // VOX Switch + roger:1, // Roger + voice:1, // Voice Annunciation + unknown_0:1, + save:1, // Battery Save + beep:1; // Beep Tone + u8 squelch; // 00D1 Squelch Level + u8 tot; // 00D2 Time-out Timer + u8 vox; // 00D3 VOX Level + u8 voxd; // 00D4 Vox Delay + u8 unknown_1; + u8 unknown_2; + u8 skey2; // 00D7 Side Key 2 (long) + u8 unknown_3[5]; // 00D8 - 00DC + u8 password[6]; // 00DD - 00E2 Password +} settings; +""" + + +CMD_ACK = b"\x06" + +DTCS = tuple(sorted(chirp_common.DTCS_CODES + (645,))) + +OFF1TO9_LIST = ["Off"] + ["%s" % x for x in range(1, 10)] +SCANM_LIST = ["Carrier", "Time"] +SKEY2_LIST = ["Off", "VOX", "Power", "Scan"] +TIMEOUTTIMER_LIST = ["Off"] + ["%s seconds" % x for x in range(30, 210, 30)] +VOICE_LIST = ["Off", "English"] +VOXD_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0"] + + +def _read_block(radio, block_addr, block_size): + serial = radio.pipe + + cmd = struct.pack(">cHb", b'R', block_addr, block_size) + expectedresponse = b"W" + cmd[1:] + LOG.debug("Reading block %04x..." % (block_addr)) + + try: + serial.write(cmd) + response = serial.read(4 + block_size) + if response[:4] != expectedresponse: + raise Exception("Error reading block %04x." % (block_addr)) + + block_data = response[4:] + except Exception: + raise errors.RadioError("Failed to read block at %04x" % block_addr) + + return block_data + + +def _write_block(radio, block_addr, block_size): + serial = radio.pipe + + cmd = struct.pack(">cHb", b'W', block_addr, block_size) + data = radio.get_mmap()[block_addr:block_addr + block_size] + + LOG.debug("Writing Data:") + LOG.debug(util.hexprint(cmd + data)) + + try: + serial.write(cmd + data) + if serial.read(1) != CMD_ACK: + raise Exception("No ACK") + except Exception: + raise errors.RadioError("Failed to send block " + "to radio at %04x" % block_addr) + + +def do_download(radio): + LOG.debug("download") + + data = b"" + + status = chirp_common.Status() + status.msg = "Cloning from radio" + + status.cur = 0 + status.max = radio._memsize + + for addr in range(0, radio._memsize, radio.BLOCK_SIZE): + status.cur = addr + radio.BLOCK_SIZE + radio.status_fn(status) + + block = _read_block(radio, addr, radio.BLOCK_SIZE) + data += block + + LOG.debug("Address: %04x" % addr) + LOG.debug(util.hexprint(block)) + + return memmap.MemoryMapBytes(data) + + +def do_upload(radio): + status = chirp_common.Status() + status.msg = "Uploading to radio" + + h777._h777_enter_single_programming_mode(radio) + + status.cur = 0 + status.max = radio._memsize + + for start_addr, end_addr in radio._ranges: + for addr in range(start_addr, end_addr, radio.BLOCK_SIZE_UP): + status.cur = addr + radio.BLOCK_SIZE_UP + radio.status_fn(status) + _write_block(radio, addr, radio.BLOCK_SIZE_UP) + + +class H777V4BaseRadio(chirp_common.CloneModeRadio): + """RETEVIS H777 V4 Base""" + VENDOR = "Retevis" + MODEL = "H777 V4 Base" + BAUD_RATE = 9600 + BLOCK_SIZE = 0x0D + BLOCK_SIZE_UP = 0x0D + + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50), + chirp_common.PowerLevel("High", watts=2.00) + ] + + PROGRAM_CMD = b"C777HAM" + _ranges = [ + (0x0000, 0x00EA), + ] + _memsize = 0x00EA + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.has_bank = False + rf.has_ctone = True + rf.has_cross = True + rf.has_rx_dtcs = True + rf.has_tuning_step = False + rf.can_odd_split = True + rf.has_name = False + rf.valid_skips = ["", "S"] + rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] + rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone", + "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"] + rf.valid_power_levels = self.POWER_LEVELS + rf.valid_duplexes = ["", "-", "+", "split", "off"] + rf.valid_modes = ["FM", "NFM"] # 25 kHz, 12.5 kHz. + rf.valid_dtcs_codes = DTCS + rf.memory_bounds = (1, 16) + rf.valid_tuning_steps = [2.5, 5., 6.25, 10., 12.5, 20., 25., 50.] + rf.valid_bands = [(400000000, 520000000)] + return rf + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def sync_in(self): + """Download from radio""" + try: + data = do_download(self) + except errors.RadioError: + # Pass through any real errors we raise + raise + except Exception: + # If anything unexpected happens, make sure we raise + # a RadioError and log the problem + LOG.exception('Unexpected error during download') + raise errors.RadioError('Unexpected error communicating ' + 'with the radio') + self._mmap = data + self.process_mmap() + + def sync_out(self): + """Upload to radio""" + try: + do_upload(self) + except errors.RadioError: + raise + except Exception: + # If anything unexpected happens, make sure we raise + # a RadioError and log the problem + LOG.exception('Unexpected error during upload') + raise errors.RadioError('Unexpected error communicating ' + 'with the radio') + + def _decode_tone(self, toneval, txrx, chnum): + pol = "N" + rawval = (toneval[1].get_bits(0xFF) << 8) | toneval[0].get_bits(0xFF) + + if toneval[0].get_bits(0xFF) == 0xFF: + mode = "" + val = 0 + elif toneval[1].get_bits(0xC0) == 0xC0: + val = int(f'{rawval & 0x1FF:o}') + if val in DTCS: + mode = "DTCS" + pol = "R" + else: + LOG.error('unknown value: CH# %i DTCS %fR %s' % ( + chnum, val, txrx)) + mode = "" + val = 0 + elif toneval[1].get_bits(0x80): + val = int(f'{rawval & 0x1FF:o}') + if val in DTCS: + mode = "DTCS" + else: + LOG.error('unknown value: CH# %i DTCS %fN %s' % ( + chnum, val, txrx)) + mode = "" + val = 0 + else: + val = int(toneval) / 10.0 + if val in chirp_common.TONES: + mode = "Tone" + else: + LOG.error('unknown value: CH# %i CTCSS %fHZ %s' % ( + chnum, val, txrx)) + mode = "" + val = 0 + + return mode, val, pol + + def _encode_tone(self, _toneval, mode, val, pol): + toneval = 0 + if mode == "Tone": + toneval = int("%i" % (val * 10), 16) + elif mode == "DTCS": + toneval = int('%i' % val, 8) + toneval |= 0x8000 + if pol == "R": + toneval |= 0x4000 + else: + toneval = 0xFFFF + + _toneval[0].set_raw(toneval & 0xFF) + _toneval[1].set_raw((toneval >> 8) & 0xFF) + + def get_raw_memory(self, number): + return repr(self._memobj.memory[number - 1]) + + def get_memory(self, number): + _mem = self._memobj.memory[number - 1] + + mem = chirp_common.Memory() + mem.number = number + + if _mem.get_raw()[:1] == b"\xFF": + mem.empty = True + return mem + + mem.freq = int(_mem.rxfreq) * 10 + + if _mem.txfreq == 0xFFFFFFFF: + # TX freq not set + mem.duplex = "off" + mem.offset = 0 + elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 25000000: + mem.duplex = "split" + mem.offset = int(_mem.txfreq) * 10 + elif int(_mem.rxfreq) == int(_mem.txfreq): + mem.duplex = "" + mem.offset = 0 + else: + mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) \ + and "-" or "+" + mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10 + + txmode, txval, txpol = self._decode_tone(_mem.tx_tone, 'TX', number) + rxmode, rxval, rxpol = self._decode_tone(_mem.rx_tone, 'RX', number) + + chirp_common.split_tone_decode(mem, + (txmode, txval, txpol), + (rxmode, rxval, rxpol)) + + if _mem.scanadd: + mem.skip = "S" + + mem.power = self.POWER_LEVELS[_mem.ishighpower] + + mem.mode = _mem.narrow and "NFM" or "FM" + + mem.extra = RadioSettingGroup("Extra", "extra") + + # BCL (Busy Channel Lockout) + rs = RadioSettingValueInvertedBoolean(not bool(_mem.bcl)) + rset = MemSetting("bcl", "BCL", rs) + rset.set_doc("Busy Channel Lockout") + mem.extra.append(rset) + + # Scramble + rs = RadioSettingValueInvertedBoolean(not bool(_mem.scramb)) + rset = MemSetting("scramb", "Scramble", rs) + rset.set_doc("Frequency inversion Scramble") + mem.extra.append(rset) + + return mem + + def set_memory(self, mem): + _mem = self._memobj.memory[mem.number - 1] + + _mem.set_raw(b"\xff" * 13) + if mem.empty: + return + + _mem.rxfreq = mem.freq / 10 + if mem.duplex == "off": + _mem.txfreq = 0xFFFFFFFF + elif mem.duplex == "split": + _mem.txfreq = mem.offset / 10 + elif mem.duplex == "+": + _mem.txfreq = (mem.freq + mem.offset) / 10 + elif mem.duplex == "-": + _mem.txfreq = (mem.freq - mem.offset) / 10 + else: + _mem.txfreq = _mem.rxfreq + + (txmode, txval, txpol), (rxmode, rxval, rxpol) = \ + chirp_common.split_tone_encode(mem) + + self._encode_tone(_mem.tx_tone, txmode, txval, txpol) + self._encode_tone(_mem.rx_tone, rxmode, rxval, rxpol) + + _mem.scanadd = mem.skip == "S" + _mem.narrow = mem.mode == "NFM" + + _mem.ishighpower = mem.power == self.POWER_LEVELS[1] + + # resetting unknowns, this have to be set by hand + _mem.unknown0 = 3 + _mem.unknown1 = 1 + + for setting in mem.extra: + setting.apply_to_memobj(_mem) + + def get_settings(self): + _settings = self._memobj.settings + basic = RadioSettingGroup("basic", "Basic Settings") + group = RadioSettings(basic) + + # Squelch + rs = RadioSettingValueInteger(0, 9, _settings.squelch) + rset = MemSetting("squelch", "Squelch", rs) + rset.set_doc("Squelch Level: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9") + basic.append(rset) + + # Time Out Timer + rs = RadioSettingValueList(TIMEOUTTIMER_LIST, + current_index=_settings.tot) + rset = MemSetting("tot", "Time-out Timer", rs) + rset.set_doc("TX Time-out Timer: Off, 30, 60, 90, 120, 150," + + " 180 seconds") + basic.append(rset) + + # Vox Level + rs = RadioSettingValueList(OFF1TO9_LIST, current_index=_settings.vox) + rset = MemSetting("vox", "VOX Level", rs) + rset.set_doc("VOX Level: Off, 1, 2, 3, 4, 5, 6, 7, 8, 9") + basic.append(rset) + + # Vox Delay + rs = RadioSettingValueList(VOXD_LIST, + current_index=_settings.voxd) + rset = MemSetting("voxd", "Vox Delay", rs) + rset.set_doc("VOX Delay: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0 seconds") + basic.append(rset) + + # Scan Mode + rs = RadioSettingValueList(SCANM_LIST, current_index=_settings.scanm) + rset = MemSetting("scanm", "Scan Mode", rs) + rset.set_doc("Scan Mode: Carrier, Time") + basic.append(rset) + + # Voice Annunciation + rs = RadioSettingValueList(VOICE_LIST, + current_index=_settings.voice) + rset = MemSetting("voice", "Voice", rs) + rset.set_doc("Voice Prompts: Off, English") + basic.append(rset) + + # Side Key 2 (long) + rs = RadioSettingValueList(SKEY2_LIST, + current_index=_settings.skey2) + rset = MemSetting("skey2", "Side Key 2", rs) + rset.set_doc("Side Key 2 (long press): Off, VOX, Power, Scan") + basic.append(rset) + + # Code Switch + rs = RadioSettingValueBoolean(_settings.codesw) + rset = MemSetting("codesw", "Code Switch", rs) + rset.set_doc("Code Switch: Off, Enabled") + basic.append(rset) + + # Battery Save + rs = RadioSettingValueBoolean(_settings.save) + rset = MemSetting("save", "Battery Save", rs) + rset.set_doc("Battery Save: Off, Enabled") + basic.append(rset) + + # Beep Tone + rs = RadioSettingValueBoolean(_settings.beep) + rset = MemSetting("beep", "Beep", rs) + rset.set_doc("Beep Prompt: Off, Enabled") + basic.append(rset) + + # VOX Switch + rs = RadioSettingValueBoolean(_settings.voxs) + rset = MemSetting("voxs", "VOX Switch", rs) + rset.set_doc("VOX Switch: Off, Enabled") + basic.append(rset) + + # Roger + rs = RadioSettingValueBoolean(_settings.roger) + rset = MemSetting("roger", "Roger", rs) + rset.set_doc("Roger: Off, Enabled") + basic.append(rset) + + return group + + def set_settings(self, settings): + others = settings.apply_to(self._memobj.settings) + if others: + LOG.error('Did not apply %s' % others) + + @classmethod + def match_model(cls, filedata, filename): + # This radio has always been post-metadata, so never do + # old-school detection + return False + + +@directory.register +@directory.detected_by(h777.RetevisH777) +class H777V4(H777V4BaseRadio): + """RETEVIS H777V4""" + VENDOR = "Retevis" + MODEL = "H777" + VARIANT = 'V4' + IDENT = [b'\x00' * 6, b'\xFF' * 6] + + # SKU #: A9294A (sold as FRS radio but supports full band TX/RX) + # Serial #: 2412R777XXXXXXX + + # SKU #: A9294C (same as SKU #: A9294A (2 pack)) + # Serial #: 2406R777XXXXXXX + + # SKU #: A9294B (sold as PMR radio but supports full band TX/RX) + # Serial #: 2412R777XXXXXXX + + # SKU #: A9294D (same as SKU #: A9294B (2 pack)) + # Serial #: 24XXR777XXXXXXX diff --git a/chirp/drivers/retevis_ra25.py b/chirp/drivers/retevis_ra25.py new file mode 100644 index 0000000..34bbb12 --- /dev/null +++ b/chirp/drivers/retevis_ra25.py @@ -0,0 +1,1165 @@ +# Copyright 2025 Mike Iacovacci <ascendr@linuxmail.org> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from chirp import chirp_common, bitwise, memmap, errors, directory +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueBoolean, RadioSettingValueList, \ + RadioSettingValueInteger, RadioSettingValueString, \ + RadioSettingValueMap, RadioSettings +import struct +import logging + +LOG = logging.getLogger(__name__) + +SERIAL_TIMEOUT = 1.0 + +MEM_FORMAT = """ +// #seekto 0x0000; +struct{ + char model[8]; + lbcd mode[1]; + char ver[4]; + u8 ri_unk[2]; + u8 ack; +} radio_info; + +struct{ + bbcd freq[4]; + bbcd tx_offset[4]; + u8 step; + u8 unk_mem:1, + nc:1, + unk_mem2:2, + compander:1, + channel_width:1, + reverse:1, + tx_off:1; + u8 unk_mem3:3, + talkaround:1, + txpower:2, + duplex:2; + u8 specdcs; + u16 scramhz; + u16 decode; + u16 encode; + u8 scrambler; + char name[8]; + u8 busychannellockout; + u8 tone_id; + u8 unk_mem4[3]; +} vfo[2]; + +struct{ + lbit bitfield[256]; +} chans_present[2]; + +struct{ + lbit bitfield[256]; +} chans_scanned[2]; + +struct { + bbcd freq[4]; + bbcd tx_offset[4]; + u8 step; + u8 unk_mem:1, + nc:1, + unk_mem2:2, + compander:1, + channel_width:1, + reverse:1, + tx_off:1; + u8 unk_mem3:3, + talkaround:1, + txpower:2, + duplex:2; + u8 specdcs; + u16 scramhz; + u16 decode; + u16 encode; + u8 scrambler; + char name[8]; + u8 busychannellockout; + u8 tone_id; + u8 unk_mem4[3]; +} memory[504]; + +struct{ + u8 dispmode; + u8 unk_fs[7]; + u8 squelch; + u8 scan_pause; + u8 unk_fs1; + u8 backlight; + u8 unk_fs2; + u8 vicedisp; + u8 unk_fs3[2]; + u8 beep:1, + alarm_off:1, + main:1, + unkfs4:4, + moni_key:1; + u8 unk_fs5; + u8 tot; + u8 unk_fs6[3]; + u8 dtmf_trans; + u8 language; + u8 tbst_freq; + u8 vox_level; + u8 vox_delay; + u8 tail_elim_type; + u8 unk_fs7:4, + setup_inhib:1, + unk_fs8:2, + init_inhib:1; + u8 unk_fs9; + u8 dcs_tail_elim; + u8 sql_tail_elim; +} func_settings; + +struct{ + u8 m[16]; +}dtmf_list[16]; + +struct{ + u8 interval_char; + u8 group_code; + u8 decoding; + u8 pretime; + u8 first_dig_tm; + u8 autoreset_tm; + u8 unk_dtmf; + u8 self_id[3]; + u8 unk_dtmf1[3]; + u8 side_tone; + u8 timelapse_enc; + u8 pttid_pause; +}dtmf_menu; + +struct{ + u8 unk_menu1[16]; +} unk_menu1; + +struct{ + u8 id[16]; +} dtmf_start; + +struct{ + u8 id[16]; +} dtmf_end; + +struct{ + u8 unk_menu2[16]; + u8 unk_menu3[16]; +} unk_menu23; + +struct{ + u8 id[16]; +} remote_stun; + +struct{ + u8 id[16]; +} remote_kill; + +struct{ + u8 unk_menu4[16]; + u8 emerg_menu[16]; +} unk_menu4; + +struct{ + u8 scanmode; + u8 prio_chan; + u8 revert_chan; + u8 lookback_a; + u8 lookback_b; + u8 dropout_delay; + u8 dwell; + u8 unk_sm; + u8 unused[8]; +} scan_menu; + +struct{ + char message[16]; +}startup_display; + +struct{ + u8 notimpl[3107]; +} notimpl; + +struct{ + u8 unk_imm[16]; + char serial_number[16]; +} immut_1; + +struct{ + char prod_date[10]; + u8 unk_imm2[22]; +} immut_2; +""" + + +# RADIO MODES +BAND_LABELS = [ + "UHF ( 400 - 490 MHz ) + VHF( 136 - 174 MHz )", + "UHF ( 400 - 490 MHz ) + VHF( 144 - 146 MHz )", + "UHF ( 430 - 440 MHz ) + VHF( 136 - 174 MHz )", + "UHF ( 430 - 440 MHz ) + VHF( 144 - 146 MHz )", + "UHF ( 430 - 440 MHz ) + VHF( 144 - 148 MHz )", + "UHF ( 400 - 438 MHz ) + VHF( 136 - 174 MHz )", + "UHF ( 420 - 450 MHz ) + VHF( 144 - 148 MHz )", + "UHF ( 400 - 470 MHz ) + VHF( 136 - 174 MHz )", + "European Version PMR", + "US GMRS", + "Australian UHF CB" +] +BAND_LIMITS = [ + [(136000000, 174000001), (400000000, 490000001)], + [(144000000, 146000001), (400000000, 490000001)], + [(136000000, 174000001), (430000000, 440000001)], + [(144000000, 146000001), (430000000, 440000001)], + [(144000000, 148000001), (430000000, 440000001)], + [(136000000, 174000001), (400000000, 438000001)], + [(144000000, 148000001), (420000000, 450000001)], + [(136000000, 174000001), (400000000, 470000001)], + [(446000000, 446200001)], + [(462550000, 467725001)], + [(476425000, 477412501)] +] + +VALID_MODES = [0, 1, 2, 3, 4, 5, 6, 7, 15, 10, 11] + +READ_MAP = [ + (0x2000, 0x2000, 0x01), + (0x12000, 0x12000, 0x01), + (0x22000, 0x22001, 0x01), + (0x32000, 0x32001, 0x01), + (0x42000, 0x420c7, 0x01), + (0x52000, 0x520c7, 0x01), + (0x62000, 0x62067, 0x01), + (0x1002000, 0x1002000, 0x01), + (0x2001000, 0x200100f, 0x01), + (0x2011000, 0x2091000, 0x10000), + (0x3001000, 0x3091000, 0x10000), + (0x4000500, 0x400057e, 0x01), + (0x4010800, 0x401087e, 0x01), + (0x5001000, 0x500101f, 0x01), + (0x5012000, 0x5012000, 0x01), + (0x5021000, 0x5021000, 0x01), + (0x6002000, 0x600200f, 0x01), + (0x6012000, 0x6012000, 0x01), + (0x6021000, 0x6021000, 0x01), + (0x6032000, 0x6032006, 0x01), + (0x8002000, 0x8002001, 0x01) +] + +WRITE_MAP = [ + (0x2000, 0x2000, 0x01, 0x0010), + (0x12000, 0x12000, 0x01, 0x30), + (0x22000, 0x22001, 0x01, 0x50), + (0x32000, 0x32001, 0x01, 0x90), + (0x42000, 0x420c7, 0x01, 0xd0), + (0x52000, 0x520c7, 0x01, 0x19d0), + (0x62000, 0x62067, 0x01, 0x32d0), + (0x1002000, 0x1002000, 0x01, 0x3fd0), + (0x2001000, 0x200100f, 0x01, 0x3ff0), + (0x2011000, 0x2021000, 0x10000, 0x40f0), + (0x2031000, 0x2041000, 0x10000, 0x4110), + (0x2071000, 0x2081000, 0x10000, 0x4150), + (0x3011000, 0x3021000, 0x10000, 0x4190), +] + + +def bcd(i): + return ((i >> 4) * 10) + (i & 0x0f) + + +def send_cmd(serial, cmd, length): + try: + resp = b'' + serial.write(cmd) + serial.flush() + resp = serial.read(length) + if len(resp) != length: + err = (f'Data send expected {length} got {len(resp)}') + LOG.error(err) + raise errors.RadioError(err) + except Exception as e: + raise errors.RadioError(f'Error sending to serial {e}') + return resp + + +def start_programming(serial): + try: + r = send_cmd(serial, b'PROGRAM', 1) + if r != b'\x06': + err = (f'Enter Programming failed ' + f'expected 0x06 got {hex(r[0])}') + LOG.error(err) + raise errors.RadioError(err) + except Exception as e: + raise errors.RadioError(f'Error Entering Program Mode {e}') + return True + + +def end_programming(serial): + try: + r = send_cmd(serial, b'END', 1) + if r != b'\x06': + LOG.error(f'Error {hex(r[0])}') + except Exception as e: + raise errors.RadioError(f"Error {e}") + + +def parse_response(r): + ck = sum(r[:-1]) % 256 + if ck != r[-1]: + err = f'Data check sum failed calc {ck} got {r[-1]}' + LOG.error(err) + return r[5:-1] + + +def get_ident(radio): + try: + bs = send_cmd(radio.pipe, b'\x02', 16) + model, mode, ver = struct.unpack('>x7ss4s3x', bs) + if ver in radio.ALLOWED_RADIO_TYPES[model]: + LOG.info(f'Model {model} Ver: {ver} is supported') + return bs + else: + err = f'ERROR: Model: {model} Ver: {ver} is not supported!' + LOG.error(err) + raise errors.RadioError(err) + except Exception as e: + raise errors.RadioError(e) + + +def get_bands(mode): + i_mode = int(mode) + bltups = list(zip(VALID_MODES, BAND_LIMITS)) + bt = next((bl[1] for bl in bltups if bl[0] == i_mode), None) + if bt is None: + err = (f"Unknown Freq. Mode {mode}") + LOG.debug(err) + raise errors.RadioError(err) + return bt + + +def sum_map(MAP): + _sum = 0 + for rt in MAP: + x, y, z = rt[0], rt[1], rt[2] + _sum += ((((y - x) // z) + 1) * ((y & 0xf000) + (y & 0x0f00) >> 8)) + return _sum + + +def do_download(radio): + try: + data = b'' + serial = radio.pipe + serial.timeout = SERIAL_TIMEOUT + status = chirp_common.Status() + status.msg = "Connecting to Radio..." + radio.status_fn(status) + r = start_programming(serial) + if not r: + raise errors.RadioError('Failed to enter programming mode') + ident_bytes = get_ident(radio) + data = ident_bytes + status.max = sum_map(READ_MAP) + status.msg = "Downloading..." + for (x, y, z) in READ_MAP: + for addr in range(x, y + 1, z): + btr = ((y & 0xf000) + (y & 0x0f00) >> 8) + cmd = struct.pack('>BL', 0x52, addr) + r = send_cmd(serial, cmd, btr + 6) + if r[0] != 0x57: + err = (f'Bad ACK expected 0x57 got {hex(r[0])}') + LOG.error(err) + raise errors.RadioError(err) + data += parse_response(r) + status.cur += btr + radio.status_fn(status) + except Exception as e: + raise errors.RadioError(f'Exception During Download: {e}') + finally: + end_programming(serial) + return memmap.MemoryMapBytes(data) + + +def write_data(serial, addr, data): + pfx = struct.pack('>BL', 0x57, addr) + data = pfx + data + chk_int = sum(data) % 256 + chk_byte = struct.pack('>B', chk_int) + cmd = data + chk_byte + r = send_cmd(serial, cmd, 1) + if r != b'\x06': + err = (f'Received bad ACK from Radio ' + f'expect 0x06 got {hex(r[0])}') + LOG.error(err) + raise errors.RadioError(err) + + +def do_upload(radio): + try: + serial = radio.pipe + serial.timeout = SERIAL_TIMEOUT + status = chirp_common.Status() + r = start_programming(serial) + if not r: + raise errors.RadioError('Failed to enter programming mode') + ident_bytes = get_ident(radio) + mode = bcd(ident_bytes[8]) + if mode != int(radio._memobj.radio_info.mode): + raise errors.RadioError('The Radio Mode does not match' + ' [Settings]->[Radio Info]->Radio Mode') + status.max = sum_map(WRITE_MAP) + status.msg = "Uploading..." + for (x, y, z, _mb) in WRITE_MAP: + i = 0 + for addr in range(x, y + 1, z): + btw = ((y & 0xf000) + (y & 0x0f00) >> 8) + si = _mb + (btw * i) + ei = _mb + (btw * (i+1)) + data = radio._mmap[si:ei] + write_data(serial, addr, data) + status.cur += btw + radio.status_fn(status) + i += 1 + except Exception as e: + raise errors.RadioError(f"Exception During Upload: {e}") + finally: + end_programming(serial) + return + + +@directory.register +class RA25UVRadio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): + """Retevis RA-25 , Anytone AT-779UV, Radioddity DB20G """ + VENDOR = "Retevis" + MODEL = "RA25" + BAUD_RATE = 115200 + ALLOWED_RADIO_TYPES = {b'RA_25UV': [b'V200']} + _file_ident = [b'RA_25UV'] + _image_size = 0x4EC3 + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5.00), + chirp_common.PowerLevel("Mid", watts=10.00), + chirp_common.PowerLevel("High", watts=25.00)] + VALID_TONES = (62.5,) + chirp_common.TONES + VALID_DCS = [i for i in range( + 0, 778) if '9' not in str(i) and '8' not in str(i)] + VALID_TUNING_STEPS = [2.5, 5.0, 6.25, 10, 12.5, 20, 25, 30, 50] + VALID_CHARSET = "".join(chr(i) + for i in range(32, 127) if chr(i) not in '\\`~') + VALID_DTMF = [str(i) for i in range(0, 10)] + ['A', 'B', + 'C', 'D', '*', '#'] + + RX_BANDS = [(136000000, 174000001), (400000000, 490000001)] + + @classmethod + def get_prompts(cls): + rp = chirp_common.RadioPrompts() + rp.experimental = \ + ('This driver is experimental, ' + 'please report issues') + return rp + + def is_tx_allowed(self, freq): + tx_bands = get_bands(self._memobj.radio_info.mode) + for bt in tx_bands: + if bt[0] <= freq <= bt[1]: + return True + return False + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.valid_tmodes = ("", "Tone", "TSQL", "DTCS", "Cross") + rf.valid_cross_modes = [ + "Tone->Tone", + "Tone->DTCS", + "DTCS->Tone", + "DTCS->", + "->Tone", + "->DTCS", + "DTCS->DTCS" + ] + rf.valid_modes = ["FM", "NFM"] + rf.valid_power_levels = self.POWER_LEVELS + rf.valid_bands = [(136000000, 174000001), (400000000, 490000001)] + rf.valid_characters = self.VALID_CHARSET + rf.valid_name_length = 8 + rf.valid_duplexes = ["", "+", "-"] + rf.valid_tuning_steps = self.VALID_TUNING_STEPS + rf.valid_tones = self.VALID_TONES + rf.has_dtcs = True + rf.has_dtcs_polarity = True + rf.valid_dtcs_codes = self.VALID_DCS + rf.has_ctone = True + rf.has_rx_dtcs = True + rf.has_cross = True + rf.has_tuning_step = True + rf.has_bank = False + rf.has_settings = True + rf.memory_bounds = (1, 502) + rf.can_odd_split = False + rf.has_offset = True + return rf + + def sync_in(self): + self._mmap = do_download(self) + self.process_mmap() + + def sync_out(self): + do_upload(self) + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def get_raw_memory(self, number): + return repr(self._memobj.memory[number - 1]) + + # Populate the UI mem from _mem + + def get_memory(self, number): + + mem = chirp_common.Memory() + mem.number = number + + if 0 < number <= 500: + _mem = self._memobj.memory[number - 1] + _mem_chans_scanned = self._memobj.chans_scanned + _mem_chans_present = self._memobj.chans_present + mem.empty = not self.get_chan_status( + _mem_chans_present, mem.number - 1) + mem.skip = '' if self.get_chan_status( + _mem_chans_scanned, mem.number - 1) else 'S' + _name = "".join(c for c in str(_mem.name) + if c in self.VALID_CHARSET) + mem.name = _name.rstrip() + + else: + _mem = self._memobj.vfo[number - 501] + mem.name = f"VFO-{number - 500}" + mem.skip = "" + mem.immutable = ["empty", "skip", "name"] + + mem.power = self.POWER_LEVELS[0] + + if mem.empty: + return mem + + mem.freq = int(_mem.freq) * 10 + + mem.power = self.POWER_LEVELS[_mem.txpower] + mem.mode = "FM" if _mem.channel_width == 0 else "NFM" + self.get_tones(_mem, mem) + self.get_duplex(_mem, mem) + mem.offset = int(_mem.tx_offset) * 10 + mem.tuning_step = self.VALID_TUNING_STEPS[_mem.step] + + if not self.is_tx_allowed(mem.freq): + _mem.tx_off = 1 + + mem.extra = RadioSettingGroup("Extra", "extra") + + rstype = RadioSettingValueBoolean(_mem.tx_off) + rs = RadioSetting("tx_off", "TX Disable", rstype) + mem.extra.append(rs) + + bcl_options = ['Off', 'Repeater', 'Busy'] + _current = _mem.busychannellockout.get_value() + rstype = RadioSettingValueList(bcl_options, current_index=_current) + rs = RadioSetting("busychannellockout", + "Busy Channel Lockout", rstype) + mem.extra.append(rs) + + rstype = RadioSettingValueBoolean(_mem.talkaround) + rs = RadioSetting("talkaround", "Talk Around", rstype) + mem.extra.append(rs) + + rstype = RadioSettingValueBoolean(_mem.reverse) + rs = RadioSetting("reverse", "Reverse", rstype) + mem.extra.append(rs) + + rstype = RadioSettingValueBoolean(_mem.compander) + rs = RadioSetting("compander", "Compander", rstype) + mem.extra.append(rs) + + rstype = RadioSettingValueBoolean(_mem.nc) + rs = RadioSetting("nc", "Noise Cancellation", rstype) + mem.extra.append(rs) + + tid_options = ['Off', 'Begin', 'End', "Both"] + _current = _mem.tone_id.get_value() + rstype = RadioSettingValueList(tid_options, current_index=_current) + rs = RadioSetting("tone_id", "DTMF PTT ID", rstype) + mem.extra.append(rs) + + return mem + + # Called when a user edits UI mem + def set_memory(self, mem): + if 0 < mem.number <= 500: + _mem = self._memobj.memory[mem.number - 1] + _mem_chans_scanned = self._memobj.chans_scanned + _mem_chans_present = self._memobj.chans_present + + if mem.empty: + self.set_chan_status(_mem_chans_present, mem.number - 1, 0) + self.set_chan_status(_mem_chans_scanned, mem.number - 1, 0) + _mem.fill_raw(b'\x00') + return + + # setup a new memory + if not self.get_chan_status(_mem_chans_present, mem.number - 1): + _mem.fill_raw(b'\x00') + self.set_chan_status(_mem_chans_present, mem.number - 1, 1) + _scan = 0 if mem.skip == 'S' else 1 + self.set_chan_status(_mem_chans_scanned, mem.number - 1, _scan) + _mem.txpower = 2 + _mem.freq = mem.freq // 10 + _mem.tx_off = 0 if self.is_tx_allowed(mem.freq) else 1 + + _mem.name = mem.name.ljust(8)[:8] + # scan when set(1) skip when off(0) + _value = 0 if mem.skip == 'S' else 1 + self.set_chan_status(_mem_chans_scanned, mem.number - 1, _value) + self.set_chan_status(_mem_chans_present, mem.number - 1, 1) + else: + _mem = self._memobj.vfo[mem.number - 501] + + _mem.freq = mem.freq // 10 + + _mem.txpower = self.POWER_LEVELS.index(mem.power) if mem.power else 0 + _mem.channel_width = 0 if mem.mode == "FM" else 1 + self.set_tones__mem(_mem, mem) + self.set_duplex__mem(_mem, mem) + _mem.tx_offset = mem.offset/10 + _mem.step = self.VALID_TUNING_STEPS.index(mem.tuning_step) + + for setting in mem.extra: + setattr(_mem, setting.get_name(), setting.value) + + if not self.is_tx_allowed(mem.freq): + _mem.tx_off = 1 + + def get_chan_status(self, _mem_field, chan_n): + if chan_n < 256: + value = _mem_field[0]['bitfield'][chan_n].get_value() + else: + value = _mem_field[1]['bitfield'][chan_n - 256].get_value() + return value + + def set_chan_status(self, _mem_field, chan_n, value): + if chan_n < 256: + _mem_field[0]['bitfield'][chan_n].set_value(value) + else: + _mem_field[1]['bitfield'][chan_n - 256].set_value(value) + + def get_duplex(self, _mem, mem): + # get duplex from _mem for ui + if _mem.duplex == 0x0: + mem.duplex = '' + elif _mem.duplex == 0x2: + mem.duplex = '-' + elif _mem.duplex == 0x3: + mem.duplex = '+' + + def set_duplex__mem(self, _mem, mem): + # sets duplex _mem from ui edit + if mem.duplex == '': + _mem.duplex = 0x0 + _mem.tx_offset = 0 + elif mem.duplex == '-': + _mem.duplex = 0x2 + elif mem.duplex == '+': + _mem.duplex = 0x3 + + def get_tones(self, _mem, mem): + # populate ui from _mem + # parse decode/rtone/rx_dtcs + if _mem.decode == 0xffff: + # off + rxtone = ("", 0, None) + elif _mem.decode >= 0x1000 and _mem.decode < 0x2000: + # ctcss tone + rxtone = ("Tone", self.VALID_TONES[_mem.decode - 0x1000], None) + elif _mem.decode >= 0x2000 and _mem.decode < 0x3000: + # DCS Normal + rxtone = ("DTCS", self.VALID_DCS[_mem.decode - 0x2000], "N") + elif _mem.decode >= 0x3000 and _mem.decode <= 0x31ff: + # DCS Inverted + rxtone = ("DTCS", self.VALID_DCS[_mem.decode - 0x3000], "R") + else: + rxtone = ("", 0, None) + # parse encode/dtcs/ctone + if _mem.encode == 0xffff: + # off + txtone = ("", 0, None) + elif _mem.encode >= 0x1000 and _mem.encode < 0x2000: + # ctcss tone + txtone = ("Tone", self.VALID_TONES[_mem.encode - 0x1000], None) + elif _mem.encode >= 0x2000 and _mem.encode < 0x3000: + # DCS Normal + txtone = ("DTCS", self.VALID_DCS[_mem.encode - 0x2000], "N") + elif _mem.encode >= 0x3000 and _mem.encode <= 0x31ff: + # DCS Inverted + txtone = ("DTCS", self.VALID_DCS[_mem.encode - 0x3000], "R") + else: + txtone = ("", 0, None) + chirp_common.split_tone_decode(mem, txtone, rxtone) + + def set_tones__mem(self, _mem, mem): + # sets tones in _mem from ui edit + ((txmode, txval, txpol), + (rxmode, rxval, rxpol)) = chirp_common.split_tone_encode(mem) + if txmode == "": + _mem.encode = 0xffff + if rxmode == "": + _mem.decode = 0xffff + if txmode == "Tone": + _mem.encode = self.VALID_TONES.index(txval) + 0x1000 + if rxmode == "Tone": + _mem.decode = self.VALID_TONES.index(rxval) + 0x1000 + if txmode == "DTCS" and txpol == "N": + _mem.encode = self.VALID_DCS.index(txval) + 0x2000 + if rxmode == "DTCS" and rxpol == "N": + _mem.decode = self.VALID_DCS.index(rxval) + 0x2000 + if txmode == "DTCS" and txpol == "R": + _mem.encode = self.VALID_DCS.index(txval) + 0x3000 + if rxmode == "DTCS" and rxpol == "R": + _mem.decode = self.VALID_DCS.index(rxval) + 0x3000 + + def get_settings(self): + + _func_settings = self._memobj.func_settings + _dtmf_menu = self._memobj.dtmf_menu + _dtmf_list = self._memobj.dtmf_list + _dtmf_start = self._memobj.dtmf_start + _dtmf_end = self._memobj.dtmf_end + _remote_kill = self._memobj.remote_kill + _remote_stun = self._memobj.remote_stun + _scan_menu = self._memobj.scan_menu + _startup_display = self._memobj.startup_display + _immut_1 = self._memobj.immut_1 + _immut_2 = self._memobj.immut_2 + _radio_info = self._memobj.radio_info + + function = RadioSettingGroup("function", "Function Setup") + group = RadioSettings(function) + + rs = RadioSettingValueInteger(minval=0, maxval=9, + current=_func_settings.squelch, step=1) + rset = RadioSetting("func_settings.squelch", "Squelch Level", rs) + function.append(rset) + + rs = RadioSettingValueInteger(minval=0, maxval=9, + current=_func_settings.vox_level, step=1) + rset = RadioSetting("func_settings.vox_level", "Vox Level", rs) + function.append(rset) + + voxdelay_options = [str(i/10) for i in range(5, 31, 1)] + rs = RadioSettingValueList( + voxdelay_options, current_index=_func_settings.vox_delay) + rset = RadioSetting("func_settings.vox_delay", "Vox Delay", rs) + function.append(rset) + + scan_pause_options = ["5", "10", "15", "SCP2"] + rs = RadioSettingValueList( + scan_pause_options, current_index=_func_settings.scan_pause) + rset = RadioSetting("func_settings.scan_pause", "Scan Pause (s)", rs) + function.append(rset) + + main_options = ["Up", "Down"] + rs = RadioSettingValueList( + main_options, current_index=_func_settings.main) + rset = RadioSetting("func_settings.main", "Main Direction", rs) + function.append(rset) + + monikey_options = ["Squelch Off Momentary", "Squelch Off"] + rs = RadioSettingValueList( + monikey_options, current_index=_func_settings.moni_key) + rset = RadioSetting("func_settings.moni_key", "[MON] Key", rs) + function.append(rset) + + rs = RadioSettingValueInteger(minval=0, maxval=30, + current=_func_settings.tot, step=1) + rset = RadioSetting("func_settings.tot", + "Time Out Timer (minutes)", rs) + function.append(rset) + + tbst_options = ["Off", "1750", "2100", "1000", "1450"] + rs = RadioSettingValueList( + tbst_options, current_index=_func_settings.tbst_freq) + rset = RadioSetting("func_settings.tbst_freq", + "TBST Frequency (Hz)", rs) + function.append(rset) + + tailelim_options = ["Off", "120 deg", "180 deg", "240 deg", "55hz"] + rs = RadioSettingValueList( + tailelim_options, current_index=_func_settings.tail_elim_type) + rset = RadioSetting("func_settings.tail_elim_type", + "Tail Eliminator Type", rs) + function.append(rset) + + dcstail_options = ["134.4", "55.0"] + rs = RadioSettingValueList( + dcstail_options, current_index=_func_settings.dcs_tail_elim) + rset = RadioSetting("func_settings.dcs_tail_elim", + "DCS Tail Elimination", rs) + function.append(rset) + + sqltail_options = ["Off", "55.2", "259.2"] + rs = RadioSettingValueList( + sqltail_options, current_index=_func_settings.sql_tail_elim) + rset = RadioSetting("func_settings.sql_tail_elim", + "Squelch Tail Elimination (Hz)", rs) + function.append(rset) + + disp_options = ["Frequency", "Channel", "Name"] + rs = RadioSettingValueList( + disp_options, current_index=_func_settings.dispmode) + rset = RadioSetting("func_settings.dispmode", "Display Mode", rs) + function.append(rset) + + vicedisp_options = ["Freq/Chan", "Battery Volt", "Off"] + rs = RadioSettingValueList( + vicedisp_options, current_index=_func_settings.vicedisp) + rset = RadioSetting("func_settings.vicedisp", "Sub-Display", rs) + function.append(rset) + + _current = "".join(c for c in str( + _startup_display.message) if c in self.VALID_CHARSET) + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=_current, + charset=self.VALID_CHARSET, + mem_pad_char=' ') + rset = RadioSetting("startup_display.message", + "Startup Display Message", rs) + function.append(rset) + + rs = RadioSettingValueInteger( + minval=1, maxval=5, current=_func_settings.backlight, step=1) + rset = RadioSetting("func_settings.backlight", "Backlight Level", rs) + function.append(rset) + + rs = RadioSettingValueBoolean( + current=_func_settings.beep, mem_vals=(0, 1)) + rset = RadioSetting("func_settings.beep", "Beep", rs) + function.append(rset) + + rs = RadioSettingValueBoolean( + current=_func_settings.alarm_off, mem_vals=(0, 1)) + rset = RadioSetting("func_settings.alarm_off", "Alarm Off", rs) + function.append(rset) + + rs = RadioSettingValueBoolean( + current=_func_settings.setup_inhib, mem_vals=(0, 1)) + rset = RadioSetting("func_settings.setup_inhib", "Setup Inhibit", rs) + function.append(rset) + + rs = RadioSettingValueBoolean( + current=_func_settings.init_inhib, mem_vals=(0, 1)) + rset = RadioSetting("func_settings.init_inhib", + "Initialization Inhibit", rs) + function.append(rset) + + lang_options = ["Simplified Chinese", "English", "Traditional Chinese"] + rs = RadioSettingValueList( + lang_options, current_index=_func_settings.language) + rset = RadioSetting("func_settings.language", "Language", rs) + function.append(rset) + + # Scan Menu + scan = RadioSettingGroup("scan", "Scan Menu") + group.append(scan) + + rs = RadioSettingValueBoolean(current=_scan_menu.scanmode) + rset = RadioSetting("scan_menu.scanmode", "Scan Mode", rs) + scan.append(rset) + + _options = ["Off", "Chan 1", "Chan 2", "Chan 1 + Chan 2"] + rs = RadioSettingValueList( + _options, current_index=_scan_menu.prio_chan) + rset = RadioSetting("scan_menu.prio_chan", "Priority Channel", rs) + scan.append(rset) + + _options = ["Selected", "Selected + Talkback", + "Prio Ch 1", "Prio Ch 2", "Last Called", + "Last Used", "Prio Ch1 + Talkback", "Prio Ch2 + Talkback"] + rs = RadioSettingValueList( + _options, current_index=_scan_menu.revert_chan) + rset = RadioSetting("scan_menu.revert_chan", "Revert Channel", rs) + scan.append(rset) + + _options = [str(i/10) for i in range(5, 51, 1)] + rs = RadioSettingValueList( + _options, current_index=_scan_menu.lookback_a) + rset = RadioSetting("scan_menu.lookback_a", "Look Back Time A (s)", rs) + scan.append(rset) + + # Uses previous options + rs = RadioSettingValueList( + _options, current_index=_scan_menu.lookback_b) + rset = RadioSetting("scan_menu.lookback_b", "Look Back Time B (s)", rs) + scan.append(rset) + + _options = [str(i/10) for i in range(1, 51, 1)] + rs = RadioSettingValueList( + _options, current_index=_scan_menu.dropout_delay) + rset = RadioSetting("scan_menu.dropout_delay", "Dropout Delay (s)", rs) + scan.append(rset) + + # Uses previous options + rs = RadioSettingValueList( + _options, current_index=_scan_menu.dwell) + rset = RadioSetting("scan_menu.dwell", "Dwell Time (s)", rs) + scan.append(rset) + + # DTMF Menu + dtmf = RadioSettingGroup("dtmf", "DTMF") + group.append(dtmf) + + def dtmf_xlate(setting): + """ Translates * and # to ascii code E / F respectively""" + s = "" + for i in setting: + if chr(i) == 'E': + s += '*' + elif chr(i) == 'F': + s += '#' + elif chr(i) in self.VALID_DTMF: + s += chr(i) + return s + + _current = ''.join(str(int(i)) for i in _dtmf_menu.self_id) + rs = RadioSettingValueString( + minlength=0, maxlength=3, current=_current) + rset = RadioSetting("dtmf_menu.self_id", "Self ID", rs) + dtmf.append(rset) + + # DTMF Transmit time is in function memory but belongs here + dtmftt_options = ["50", "100", "200", "300", "500"] + rs = RadioSettingValueList( + dtmftt_options, current_index=_func_settings.dtmf_trans) + rset = RadioSetting("func_settings.dtmf_trans", + "DTMF Transmit Time (ms)", rs) + dtmf.append(rset) + + _options_map = [('A', 10), ('B', 11), ('C', 12), + ('D', 13), ('*', 14), ('#', 15)] + rs = RadioSettingValueMap(_options_map, _dtmf_menu.interval_char) + rset = RadioSetting("dtmf_menu.interval_char", "Interval Char", rs) + dtmf.append(rset) + + _options_map = [('Off', 0), ('A', 10), ('B', 11), + ('C', 12), ('D', 13), ('*', 14), ('#', 15)] + rs = RadioSettingValueMap(_options_map, _dtmf_menu.group_code) + rset = RadioSetting("dtmf_menu.group_code", "Group Code", rs) + dtmf.append(rset) + + _options = ["None", "Beep Tone", "Beep Tone & Response"] + rs = RadioSettingValueList( + _options, current_index=_dtmf_menu.decoding) + rset = RadioSetting("dtmf_menu.decoding", "Decoding", rs) + dtmf.append(rset) + + _options = [str(i) for i in range(10, 2510, 10)] + _mem_vals = [i for i in range(1, 251)] + _options_map = list(zip(_options, _mem_vals)) + rs = RadioSettingValueMap(_options_map, _dtmf_menu.pretime) + rset = RadioSetting("dtmf_menu.pretime", "Pretime (ms)", rs) + dtmf.append(rset) + + # using same _options as pre-time + rs = RadioSettingValueMap(_options_map, _dtmf_menu.timelapse_enc) + rset = RadioSetting("dtmf_menu.timelapse_enc", + "Time Lapse After Encode (ms)", rs) + dtmf.append(rset) + + _options = [str(i) for i in range(0, 2510, 10)] + rs = RadioSettingValueList( + _options, current_index=_dtmf_menu.first_dig_tm) + rset = RadioSetting("dtmf_menu.first_dig_tm", + "First Digit Time (ms)", rs) + dtmf.append(rset) + + _options = [str(i/10) for i in range(0, 251, 1)] + rs = RadioSettingValueList( + _options, current_index=_dtmf_menu.autoreset_tm) + rset = RadioSetting("dtmf_menu.autoreset_tm", + "Auto Reset Time (ms)", rs) + dtmf.append(rset) + + rs = RadioSettingValueBoolean( + current=_dtmf_menu.side_tone, mem_vals=(0, 1)) + rset = RadioSetting("dtmf_menu.side_tone", "Side Tone", rs) + dtmf.append(rset) + + _options_map = [("Off", 0)] + [(str(i), i) for i in range(5, 76, 1)] + rs = RadioSettingValueMap(_options_map, _dtmf_menu.pttid_pause) + rset = RadioSetting("dtmf_menu.pttid_pause", + "PTT ID Pause Time (s)", rs) + dtmf.append(rset) + + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=dtmf_xlate(_dtmf_start.id), + charset=self.VALID_DTMF + [' ']) + rset = RadioSetting("dtmf_start.id", "PTT ID Starting", rs) + dtmf.append(rset) + + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=dtmf_xlate(_dtmf_end.id), + charset=self.VALID_DTMF + [' ']) + rset = RadioSetting("dtmf_end.id", "PTT ID Ending", rs) + dtmf.append(rset) + + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=dtmf_xlate(_remote_kill.id), + charset=self.VALID_DTMF + [' '],) + rset = RadioSetting("remote_kill.id", "Remote Kill", rs) + dtmf.append(rset) + + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=dtmf_xlate(_remote_stun.id), + charset=self.VALID_DTMF + [' ']) + rset = RadioSetting("remote_stun.id", "Remote Stun", rs) + dtmf.append(rset) + + # DTMF Encode List + dtmf_mem = RadioSettingGroup("dtmf_mem", "DTMF Encode List") + group.append(dtmf_mem) + + for i in range(0, 16): # M1-16 + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=dtmf_xlate(_dtmf_list[i].m), + charset=self.VALID_DTMF + [' ']) + rset = RadioSetting(f"dtmf_list[{i}].m", f"M{i+1}", rs) + dtmf_mem.append(rset) + + # Immutables Info + info_menu = RadioSettingGroup("immut_info", "Radio Info") + group.append(info_menu) + + _warning = ('To Upload to the Radio this setting must match ' + 'the Radio Mode. The Radio Mode can be changed by ' + 'holding down [V/M] during powerup. Note: Changing ' + 'the Radio Mode will set Radio memory to defaults.') + + _options_map = list(zip(BAND_LABELS, VALID_MODES)) + rs = RadioSettingValueMap(_options_map, int(_radio_info.mode)) + rset = RadioSetting("radio_info.mode", "Radio Mode", rs) + rset.set_warning(_warning) + info_menu.append(rset) + + _current = "".join(str(_radio_info.model[i]) + for i in range(1, len(_radio_info.model))) + rs = RadioSettingValueString( + minlength=1, maxlength=8, current=_current) + rs.set_mutable(False) + rset = RadioSetting("radio_info.model", "Model", rs) + info_menu.append(rset) + + _current = "".join(str(_radio_info.ver[i]) + for i in range(len(_radio_info.ver))) + rs = RadioSettingValueString( + minlength=4, maxlength=4, current=_current) + rs.set_mutable(False) + rset = RadioSetting("radio_info.ver", "Version", rs) + info_menu.append(rset) + + _current = "".join(str(_immut_1.serial_number[i]) for i in range( + len(_immut_1.serial_number))) + rs = RadioSettingValueString( + minlength=0, maxlength=16, current=_current) + rs.set_mutable(False) + rset = RadioSetting("immut_1.serial_number", "Serial Number", rs) + info_menu.append(rset) + + _current = "".join(str(_immut_2.prod_date[i]) for i in range( + len(_immut_2.prod_date)) if int(_immut_2.prod_date[i]) >= 0x20) + rs = RadioSettingValueString( + minlength=0, maxlength=10, current=_current) + rs.set_mutable(False) + rset = RadioSetting("immut_2.prod_date", "Production Date", rs) + info_menu.append(rset) + return group + + def dtmf_set__mem(self, obj, setting, element): + _val = [0] * len(obj[setting]) + _i = 0 # offset _mem setting idx for pad chars + for i in range(len(element.value)): + if element.value[i] == '*': + _val[i - _i] = ord('E') + elif element.value[i] == '#': + _val[i - _i] = ord('F') + elif element.value[i] in self.VALID_DTMF: + _val[i - _i] = ord(element.value[i]) + else: + _i += 1 + setattr(obj, setting, _val) + + def set_settings(self, settings): + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + continue + else: + try: + if "." in element.get_name(): + toks = element.get_name().split(".") + obj = self._memobj + for tok in toks[:-1]: + if '[' in tok: + t, i = tok.split("[") + i = int(i[:-1]) + obj = getattr(obj, t)[i] + else: + obj = getattr(obj, tok) + setting = toks[-1] + else: + obj = self._memobj.settings + setting = element.get_name() + + if element.has_apply_callback(): + LOG.debug("applying callback") + element.run_apply_callback() + + if element.value.get_mutable(): + if obj._name in ['dtmf_list', 'dtmf_start', 'dtmf_end', + 'remote_stun', 'remote_kill']: + self.dtmf_set__mem(obj, setting, element) + else: + setattr(obj, setting, element.value) + except Exception: + LOG.debug(element.get_name()) + raise + + @classmethod + def match_model(cls, filedata, filename): + # new drivers identified by metadata + return False + + +@directory.register +class AnyTone779UV(RA25UVRadio): + VENDOR = "AnyTone" + MODEL = "779UV" + ALLOWED_RADIO_TYPES = {b'AT779UV': [b'V200']} + + +@directory.register +class RadioddityDB20G(AnyTone779UV): + VENDOR = "Radioddity" + MODEL = "DB20-G" diff --git a/chirp/drivers/retevis_ra86.py b/chirp/drivers/retevis_ra86.py new file mode 100644 index 0000000..c0e1087 --- /dev/null +++ b/chirp/drivers/retevis_ra86.py @@ -0,0 +1,609 @@ +# Copyright 2025 Jim Unroe <rock.unroe@gmail.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import struct +import logging + +from chirp import chirp_common, directory, memmap +from chirp import bitwise, errors, util +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueInteger, RadioSettingValueList, \ + RadioSettingValueBoolean, RadioSettings + +LOG = logging.getLogger(__name__) + +MEM_FORMAT = """ +struct memory { + u32 rxfreq; // 0-3 + ul16 rxtone; // 4-5 + u32 txfreq; // 6-9 + ul16 txtone; // A-B + u8 unknown0:3, // C + scan:1, // + is_wide:1, // + unknown1:1, // + highpower:1, // + unknown2:1; // + u8 unknown3[3]; // D-F +} ; + +struct memory lochannels[14]; +struct memory chnl15; +struct memory rptr15; +struct memory chnl16; +struct memory rptr16; +struct memory chnl17; +struct memory rptr17; +struct memory chnl18; +struct memory rptr18; +struct memory chnl19; +struct memory rptr19; +struct memory chnl20; +struct memory rptr20; +struct memory chnl21; +struct memory rptr21; +struct memory chnl22; +struct memory rptr22; +struct memory hichannels[77]; + +#seekto 0x0E00; +struct { + u8 unknown00:4, vox:4; // 0E00 VOX + u8 unknown01:7, keytone:1; // 0E01 Key Tone + u8 unknown02:7, roger:1; // 0E02 Roger Beep + u8 unknown03:5, calltone:3; // 0E03 Call Tone + u8 unknown04:6, brightness:2; // 0E04 Screen Brightness + u8 unknown05:5, backlight:3; // 0E05 Backlight Duration + u8 unknown06:4, squelch:4; // 0E06 Squelch Level + u8 unknown07; // 0E07 (Reserved/Unknown) + u8 unknown08:7, repeat:1; // 0E08 Repeater + u8 unknown09:5, sleeptime:3; // 0E09 Sleep Timer + u8 unknown10:6, speakersw:2; // 0E0A Speaker Switch + u8 unknown11:6, micgain:2; // 0E0B Mic Gain + u8 unknown12:4, tot:4; // 0E0C Timeout Timer (TOT) + u8 unknown13; // 0E0D (Reserved) + u8 unknown14; // 0E0E (Reserved) + u8 unknown15; // 0E0F (Reserved) +} settings; +""" + +CMD_ACK = b"\x06" + +LIST_OFF1TO9 = ["Off"] + ["%s" % x for x in range(1, 10)] +LIST_SLEEPTIME = ["OFF", "5s", "10s", "20s", "30s", "60s"] +LIST_SPEAKERSW = ["Base", "Mic", "Dual"] +LIST_TOT = ["Off"] + ["%s" % x for x in range(15, 195, 15)] + +SPECIALS = { + "RPTR15": -8, + "RPTR16": -7, + "RPTR17": -6, + "RPTR18": -5, + "RPTR19": -4, + "RPTR20": -3, + "RPTR21": -2, + "RPTR22": -1 + } + + +def _enter_programming_mode(radio): + serial = radio.pipe + + _magic = b"\x02" + radio._magic + + try: + serial.write(_magic) + serial.read(len(_magic)) # Chew the echo + ack = serial.read(1) + except Exception: + raise errors.RadioError("Error communicating with radio") + + if not ack: + raise errors.RadioError("No response from radio") + elif ack != CMD_ACK: + raise errors.RadioError("Radio refused to enter programming mode") + + try: + serial.write(b"\x02") + serial.read(1) # Chew the echo + ident = serial.read(8) + except Exception: + raise errors.RadioError("Error communicating with radio") + + # check if ident is OK + for fp in radio._fingerprint: + if ident.startswith(fp): + break + else: + LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident)) + raise errors.RadioError("Radio identification failed.") + + try: + serial.write(CMD_ACK) + serial.read(1) # Chew the echo + ack = serial.read(1) + except Exception: + raise errors.RadioError("Error communicating with radio") + + if ack != CMD_ACK: + raise errors.RadioError("Radio refused to enter programming mode") + + +def _exit_programming_mode(radio): + serial = radio.pipe + try: + serial.write(radio.CMD_EXIT) + serial.read(1) # Chew the echo + except Exception: + raise errors.RadioError("Radio refused to exit programming mode") + + +def _read_block(radio, block_addr, block_size): + serial = radio.pipe + + cmd = struct.pack(">cHb", b'R', block_addr, block_size) + expectedresponse = b"R" + cmd[1:] + LOG.debug("Reading block %04x..." % (block_addr)) + + try: + serial.write(cmd) + serial.read(4) # Chew the echo + response = serial.read(4 + block_size) + if response[:4] != expectedresponse: + raise Exception("Error reading block %04x." % (block_addr)) + + block_data = response[4:] + + except Exception: + raise errors.RadioError("Failed to read block at %04x" % block_addr) + + return block_data + + +def _write_block(radio, block_addr, block_size): + serial = radio.pipe + + cmd = struct.pack(">cHb", b'W', block_addr, block_size) + data = radio.get_mmap()[block_addr:block_addr + block_size] + + LOG.debug("Writing Data:") + LOG.debug(util.hexprint(cmd + data)) + + try: + serial.write(cmd + data) + serial.read(4 + len(data)) # Chew the echo + serial.read(1) # Chew the echo + ack = serial.read(1) + if ack != CMD_ACK: + raise Exception("No ACK") + except Exception: + raise errors.RadioError("Failed to send block " + "to radio at %04x" % block_addr) + + +def do_download(radio): + LOG.debug("download") + _enter_programming_mode(radio) + + data = b"" + + status = chirp_common.Status() + status.msg = "Cloning from radio" + + status.cur = 0 + status.max = radio._memsize + + for addr in range(0, radio._memsize, radio.BLOCK_SIZE): + status.cur = addr + radio.BLOCK_SIZE + radio.status_fn(status) + + block = _read_block(radio, addr, radio.BLOCK_SIZE) + data += block + + LOG.debug("Address: %04x" % addr) + LOG.debug(util.hexprint(block)) + + _exit_programming_mode(radio) + + return memmap.MemoryMapBytes(data) + + +def do_upload(radio): + status = chirp_common.Status() + status.msg = "Uploading to radio" + + _enter_programming_mode(radio) + + status.cur = 0 + status.max = radio._memsize + + for start_addr, end_addr in radio._ranges: + for addr in range(start_addr, end_addr, radio.BLOCK_SIZE): + status.cur = addr + radio.BLOCK_SIZE + radio.status_fn(status) + _write_block(radio, addr, radio.BLOCK_SIZE) + + _exit_programming_mode(radio) + + +def _split(rf, f1, f2): + """Returns False if the two freqs are in the same band (no split) + or True otherwise""" + + # determine if the two freqs are in the same band + for low, high in rf.valid_bands: + if f1 >= low and f1 <= high and \ + f2 >= low and f2 <= high: + # if the two freqs are on the same Band this is not a split + return False + + # if you get here is because the freq pairs are split + return True + + +@directory.register +class RA86Radio(chirp_common.CloneModeRadio): + """RETEVIS RA86""" + VENDOR = "Retevis" + MODEL = "RA86" + BAUD_RATE = 115200 + BLOCK_SIZE = 0x10 + CMD_EXIT = b"b" + + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=20.00), + chirp_common.PowerLevel("Low", watts=0.50)] + + VALID_BANDS = [(400000000, 470000000)] + + DTCS_CODES = tuple(sorted(chirp_common.DTCS_CODES + (645,))) + + _magic = b"PROGRAM" + _fingerprint = [b"SMP558"] + _upper = 99 + + _gmrs = False + + _ranges = [ + (0x0000, 0x06B0), + (0x0E00, 0x0E10), + ] + _memsize = 0x0E10 + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.valid_special_chans = list(SPECIALS.keys()) + rf.has_settings = True + rf.valid_modes = ["FM", "NFM"] # 25 kHz, 12.5 kHz. + rf.valid_skips = ["", "S"] + rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] + rf.valid_duplexes = ["", "-", "+", "split", "off"] + rf.valid_power_levels = self.POWER_LEVELS + rf.can_odd_split = True + rf.has_rx_dtcs = True + rf.has_ctone = True + rf.has_cross = True + rf.valid_cross_modes = [ + "Tone->Tone", + "DTCS->", + "->DTCS", + "Tone->DTCS", + "DTCS->Tone", + "->Tone", + "DTCS->DTCS"] + rf.valid_dtcs_codes = self.DTCS_CODES + rf.has_tuning_step = False + rf.has_bank = False + rf.has_name = False + rf.memory_bounds = (1, self._upper) + rf.valid_bands = self.VALID_BANDS + rf.valid_tuning_steps = chirp_common.TUNING_STEPS + + return rf + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def sync_in(self): + self._mmap = do_download(self) + self.process_mmap() + + def sync_out(self): + do_upload(self) + + def decode_tone(self, val): + mode = "" + pol = "N" + if val in [0, 0xFFFF]: + xval = 0 + elif val <= 0x32: + mode = "Tone" + index = val - 1 + xval = chirp_common.TONES[index] + elif val >= 0x0033: + mode = "DTCS" + if val > 0x69 + 0x32: + index = val - 0x69 - 0x32 - 1 + pol = "R" + else: + index = val - 0x32 - 1 + xval = self.DTCS_CODES[index] + else: + LOG.warn("Bug: tone is %04x" % val) + return mode, xval, pol + + def encode_tone(self, memtone, mode, tone, pol): + if mode == "Tone": + memtone.set_value(chirp_common.TONES.index(tone) + 1) + elif mode == "TSQL": + memtone.set_value(chirp_common.TONES.index(tone) + 1) + elif mode == "DTCS": + if pol == 'R': + memtone.set_value(self.DTCS_CODES.index(tone) + 0x33 + 0x69) + else: + memtone.set_value(self.DTCS_CODES.index(tone) + 0x33) + else: + memtone.set_value(0) + + def _get_memobjs(self, number): + if isinstance(number, str): + return (getattr(self._memobj, number.lower())) + elif number < 0: + for k, v in SPECIALS.items(): + if number == v: + return (getattr(self._memobj, k.lower())) + else: + if number < 15: + return self._memobj.lochannels[number - 1] + elif 15 <= number <= 22: + return getattr(self._memobj, f"chnl{number}") + else: # number > 22 + return self._memobj.hichannels[number - 23] + + def get_memory(self, number): + _mem = self._get_memobjs(number) + + mem = chirp_common.Memory() + + if isinstance(number, str): + mem.number = SPECIALS[number] + mem.extd_number = number + else: + mem.number = number + + mem.freq = int(_mem.rxfreq) + + # We'll consider any blank (i.e. 0 MHz frequency) to be empty + if mem.freq == 0: + mem.empty = True + return mem + + if _mem.rxfreq.get_raw() == b"\xFF\xFF\xFF\xFF": + mem.freq = 0 + mem.empty = True + return mem + + if _mem.get_raw() == (b"\xFF" * 16): + LOG.debug("Initializing empty memory") + _mem.set_raw(b"\x00" * 16) + + # Freq and offset + mem.freq = int(_mem.rxfreq) + # tx freq can be blank + if _mem.txfreq.get_raw() == b"\xFF\xFF\xFF\xFF": + # TX freq not set + mem.offset = 0 + mem.duplex = "off" + else: + # TX freq set + offset = (int(_mem.txfreq)) - mem.freq + if offset != 0: + if _split(self.get_features(), mem.freq, int( + _mem.txfreq)): + mem.duplex = "split" + mem.offset = int(_mem.txfreq) + elif offset < 0: + mem.offset = abs(offset) + mem.duplex = "-" + elif offset > 0: + mem.offset = offset + mem.duplex = "+" + else: + mem.offset = 0 + + mem.mode = _mem.is_wide and "FM" or "NFM" + + if not _mem.scan: + mem.skip = "S" + + txtone = self.decode_tone(_mem.txtone) + rxtone = self.decode_tone(_mem.rxtone) + chirp_common.split_tone_decode(mem, txtone, rxtone) + + mem.power = self.POWER_LEVELS[1 - _mem.highpower] + + return mem + + def set_memory(self, mem): + # Get a low-level memory object mapped to the image + _mem = self._get_memobjs(mem.number) + + if mem.empty: + _mem.fill_raw(b"\xFF") + + return + + _mem.fill_raw(b"\x00") + + _mem.rxfreq = mem.freq + + if mem.duplex == "off": + _mem.txfreq.fill_raw(b"\xFF") + elif mem.duplex == "split": + _mem.txfreq = mem.offset + elif mem.duplex == "+": + _mem.txfreq = (mem.freq + mem.offset) + elif mem.duplex == "-": + _mem.txfreq = (mem.freq - mem.offset) + else: + _mem.txfreq = mem.freq + + ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \ + chirp_common.split_tone_encode(mem) + self.encode_tone(_mem.txtone, txmode, txtone, txpol) + self.encode_tone(_mem.rxtone, rxmode, rxtone, rxpol) + + _mem.highpower = mem.power == self.POWER_LEVELS[0] + + _mem.is_wide = mem.mode == "FM" + _mem.scan = mem.skip != "S" + + _mem.unknown0 = 0 + _mem.unknown1 = 0 + _mem.unknown2 = 0 + _mem.unknown3 = b"\x92\x1B\xC4" + + def get_settings(self): + _mem = self._memobj + basic = RadioSettingGroup("basic", "Basic Settings") + top = RadioSettings(basic) + + if _mem.settings.vox >= len(LIST_OFF1TO9): + val = 0x00 + else: + val = _mem.settings.vox + rs = RadioSetting("settings.vox", "VOX", + RadioSettingValueList( + LIST_OFF1TO9, + current_index=val)) + basic.append(rs) + + rs = RadioSetting("settings.keytone", "Key Tone", + RadioSettingValueBoolean(_mem.settings.keytone)) + basic.append(rs) + + rs = RadioSetting("settings.roger", "Roger Beep", + RadioSettingValueBoolean(_mem.settings.roger)) + basic.append(rs) + + if _mem.settings.calltone > 4: + val = 1 + else: + val = _mem.settings.calltone + 1 + rs = RadioSetting("settings.calltone", "Call Tone", + RadioSettingValueInteger(1, 5, val)) + basic.append(rs) + + if _mem.settings.brightness > 2: + val = 1 + else: + val = _mem.settings.brightness + 1 + rs = RadioSetting("settings.brightness", "Brightness", + RadioSettingValueInteger(1, 3, val)) + basic.append(rs) + + if _mem.settings.backlight > 4: + val = 2 + else: + val = _mem.settings.backlight + rs = RadioSetting("settings.backlight", "Back Light", + RadioSettingValueInteger(0, 4, val)) + basic.append(rs) + + if _mem.settings.squelch >= len(LIST_OFF1TO9): + val = 0x05 + else: + val = _mem.settings.squelch + rs = RadioSetting("settings.squelch", "Squelch", + RadioSettingValueList( + LIST_OFF1TO9, + current_index=val)) + basic.append(rs) + + if _mem.settings.tot >= len(LIST_TOT): + val = 0x0C + else: + val = _mem.settings.tot + rs = RadioSetting("settings.tot", "TOT", + RadioSettingValueList( + LIST_TOT, + current_index=val)) + basic.append(rs) + + rs = RadioSetting("settings.repeat", "Repeater", + RadioSettingValueBoolean(_mem.settings.repeat)) + basic.append(rs) + + if _mem.settings.sleeptime >= len(LIST_SLEEPTIME): + val = 0x02 + else: + val = _mem.settings.sleeptime + rs = RadioSetting("settings.sleeptime", "Sleep Time", + RadioSettingValueList( + LIST_SLEEPTIME, + current_index=val)) + basic.append(rs) + + if _mem.settings.speakersw >= len(LIST_SPEAKERSW): + val = 0x02 + else: + val = _mem.settings.speakersw + rs = RadioSetting("settings.speakersw", "Speaker Select", + RadioSettingValueList( + LIST_SPEAKERSW, + current_index=val)) + basic.append(rs) + + if _mem.settings.micgain > 2: + val = 1 + else: + val = _mem.settings.micgain + 1 + rs = RadioSetting("settings.micgain", "Mic Gain", + RadioSettingValueInteger(1, 5, val)) + basic.append(rs) + + return top + + def set_settings(self, settings): + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + continue + else: + try: + if "." in element.get_name(): + bits = element.get_name().split(".") + obj = self._memobj + for bit in bits[:-1]: + obj = getattr(obj, bit) + setting = bits[-1] + else: + obj = self._memobj.settings + setting = element.get_name() + + if element.has_apply_callback(): + LOG.debug("Using apply callback") + element.run_apply_callback() + elif setting == "brightness": + setattr(obj, setting, int(element.value) - 1) + elif setting == "calltone": + setattr(obj, setting, int(element.value) - 1) + elif setting == "micgain": + setattr(obj, setting, int(element.value) - 1) + else: + LOG.debug("Setting %s = %s" % (setting, element.value)) + setattr(obj, setting, element.value) + except Exception: + LOG.debug(element.get_name()) + raise diff --git a/chirp/drivers/retevis_rt21.py b/chirp/drivers/retevis_rt21.py index 01187ff..662a377 100644 --- a/chirp/drivers/retevis_rt21.py +++ b/chirp/drivers/retevis_rt21.py @@ -449,7 +449,7 @@ struct { """ MEM_FORMAT_RT86 = """ -#seekto 0x0000; +// #seekto 0x0000; struct { lbcd rxfreq[4]; // RX Frequency 0-3 lbcd txfreq[4]; // TX Frequency 4-7 @@ -461,7 +461,7 @@ struct { bcl:1, // Busy Lock OFF=0 ON=1 scramble_type:3; // Scramble u8 reserved[3]; // Reserved D-F -} memory[16]; +} memory[%(memcnt)d]; #seekto 0x002D; struct { @@ -484,32 +484,68 @@ struct { u8 unknown_4; // 004D u8 unknown_5[2]; // 004E-004F u8 channel_6[13]; // 0050-005C - u8 unknown_6; // 005D + u8 removectdcs; // Remove CT/DCS RT86S 005D u8 unknown_7[2]; // 005E-005F u8 channel_7[13]; // 0060-006C u8 warn; // Warn Mode 006D u8 pf1; // Key Set PF1 006E - u8 pf2; // Key Set PF2 006F + u8 pf2; // Key Set PF2 006F RT86S: Group Ch # u8 channel_8[13]; // 0070-007C u8 unknown_8; // 007D u8 tail; // QT/DQT Tail(inverted) 007E u8 tailmode; // QT/DQT Tail Mode 007F u8 channel_9[13]; // 0080-008C - u8 unknown_9[3]; // 008D-008F + u8 unknown_9; // 008D + u8 pttack; // 008E + u8 waittime; // 008F u8 channel_10[13]; // 0090-009C u8 unknown_10[3]; // 009D-009F u8 channel_11[13]; // 00A0-00AC - u8 unknown_11[2]; // 00AD-00AE - u8 chnumber; // Channel Number 00AF + u8 weather; // Weather 00AD + u8 seekfreq; // Seek Freq 00AE + u8 chnumber; // Channel Number 00AF RT86S: Talk + u8 channel_12[13]; // 00B0-00BC + u8 unknown_12; // 00BD + u8 keylock; // Key Lock 00BE + u8 wxchnumber; // WX Channel Number 00BF + u8 channel_13[13]; // 00C0-00CC + u8 backlight; // Back Light 00CD + u8 micgain; // Microphone Gain 00CE + u8 unknown_cf; // 00CF + u8 channel_14[13]; // 00D0-00DC + u8 pf_1; // Key Set PF1 00DD + u8 pf_2; // Key Set PF2 00DE + u8 menuexit; // Menu Exit Time 00DF } settings; -#seekto 0x004E; -u8 skipflags[2]; // SCAN_ADD +#seekto %(settings_offset)s; +u8 skipflags[%(bytecnt)d]; // Scan Add #seekto 0x0100; struct { u8 freqhop; // Frequency Hop } freqhops[16]; + +#seekto 0x029F; +struct { + u8 ch_number; // RT86S: Channel Number +} settings2; + +#seekto 0x031E; +struct { + u8 voxl; // Vox Level + u8 voxd; // VOX Delay +} settings3; + +#seekto 0x326; +struct { + u8 roger; // Roger +} settings4; + +#seekto 0x0330; +struct { + u8 txpower; // TX Power Level +} levels[30]; """ CMD_ACK = b"\x06" @@ -522,13 +558,18 @@ CDCSS2_LIST = ["Normal Code", "Special Code"] # RT29 UHF and RT29 VHF FREQHOP_LIST = ["Off", "Hopping 1", "Hopping 2", "Hopping 3"] FUNCTION_LIST = ["Off", "Scramble", "Compand"] GAIN_LIST = ["Standard", "Enhanced"] +GROUPCH_LIST = ["OFF"] + ["%s" % x for x in range(1, 31)] +BACKLIGHT_LIST = ["%sS" % x for x in range(1, 21)] + ["60S", "120S", "ON"] HOP_LIST = ["Mode A", "Mode B", "Mode C", "Mode D", "Mode E"] HOP86_LIST = ["Off", "Mode 1", "Mode 2", "Mode 3", "Mode 4"] +MENUEXIT_LIST = ["%sS" % x for x in range(5, 65, 5)] +MICGAIN_LIST = ["-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5"] PFKEY_LIST = ["None", "Monitor", "Lamp", "Warn", "VOX", "VOX Delay", "Key Lock", "Scan"] PFKEY28B_LIST = ["None", "Scan", "Warn", "TX Power", "Monitor"] PFKEY86_LIST = ["None", "Monitor", "Lamp", "Warn", "VOX", "VOX Delay", "Key Lock", "TX Power", "Scan"] +PFKEY86S_LIST = ["Monitor", "Warn", "Lamp"] PFKEY89_LIST = PFKEY_LIST + ["Bluetooth ON/OFF"] POT_LIST = ["Channel Type", "Volume Type"] SAVE_LIST = ["Standard", "Super"] @@ -544,7 +585,19 @@ VOICE_LIST3 = VOICE_LIST2 + ["Chinese"] VOX_LIST = ["OFF"] + ["%s" % x for x in range(1, 17)] VOXD_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0"] VOXL_LIST = ["OFF"] + ["%s" % x for x in range(1, 10)] +WAITTIME_LIST = ["OFF"] + ["%s" % x for x in range(1, 21)] WARN_LIST = ["OFF", "Native Warn", "Remote Warn"] +WX_LIST = ["WX1 162.550 MHz", + "WX2 162.400 MHz", + "WX3 162.475 MHz", + "WX4 162.425 MHz", + "WX5 162.450 MHz", + "WX6 162.500 MHz", + "WX7 162.525 MHz", + "WX8 161.650 MHz", + "WX9 161.775 MHz", + "WX10 161.750 MHz", + "WX11 162.000 MHz"] PF1_CHOICES = ["None", "Monitor", "Scan", "Scramble", "Alarm"] PF1_VALUES = [0x0F, 0x04, 0x06, 0x08, 0x0C] PF1_17A_CHOICES = ["None", "Monitor", "Scan", "Scramble"] @@ -904,6 +957,9 @@ class RT21Radio(chirp_common.CloneModeRadio): LOG.debug("Got TX %s (%i) RX %s (%i)" % (txmode, _mem.tx_tone, rxmode, _mem.rx_tone)) + def _get_pwr(self, number): + return self._memobj.levels[number - 1] + def get_memory(self, number): if self._skipflags: bitpos = (1 << ((number - 1) % 8)) @@ -925,7 +981,9 @@ class RT21Radio(chirp_common.CloneModeRadio): _mem = self._memobj.memory[number - 1] if self._reserved: - _rsvd = _mem.reserved.get_raw(asbytes=False) + _rsvd = _mem.reserved.get_raw() + if self.MODEL == "RT86S": + _rsvdpwr = _mem.highpower.get_raw() mem.freq = int(_mem.rxfreq) * 10 @@ -963,6 +1021,15 @@ class RT21Radio(chirp_common.CloneModeRadio): else: LOG.error('%s: get_mem: unhandled power level: 0x%02x' % (mem.name, _mem.txpower)) + elif self.MODEL == "RT86S": + _pwr = self._get_pwr(number) + # set the power level + if _pwr.txpower == self.TXPOWER_LOW: + mem.power = self.POWER_LEVELS[2] + elif _pwr.txpower == self.TXPOWER_MED: + mem.power = self.POWER_LEVELS[1] + elif _pwr.txpower == self.TXPOWER_HIGH: + mem.power = self.POWER_LEVELS[0] else: mem.power = self.POWER_LEVELS[1 - _mem.highpower] @@ -1188,6 +1255,9 @@ class RT21Radio(chirp_common.CloneModeRadio): LOG.debug("Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone)) + def _set_pwr(self, number): + return self._memobj.levels[number - 1] + def set_memory(self, mem): if self._skipflags: bitpos = (1 << ((mem.number - 1) % 8)) @@ -1208,7 +1278,9 @@ class RT21Radio(chirp_common.CloneModeRadio): _mem = self._memobj.memory[mem.number - 1] if self._reserved: - _rsvd = _mem.reserved.get_raw(asbytes=False) + _rsvd = _mem.reserved.get_raw() + if self.MODEL == "RT86S": + _rsvdpwr = _mem.highpower.get_raw() if self.MODEL == "RT86": _freqhops = self._memobj.freqhops[mem.number - 1] @@ -1220,15 +1292,15 @@ class RT21Radio(chirp_common.CloneModeRadio): "RT76", "RT86", ]: - _mem.set_raw("\xFF" * 13 + _rsvd) + _mem.set_raw(b"\xFF" * 13 + _rsvd) elif self.MODEL in ["RT19", "RT86", "RT619", ]: - _mem.set_raw("\xFF" * 13 + _rsvd) + _mem.set_raw(b"\xFF" * 13 + _rsvd) _freqhops.freqhop.set_raw("\x00") elif self.MODEL == "AR-63": - _mem.set_raw("\xFF" * 13 + _rsvd) + _mem.set_raw(b"\xFF" * 13 + _rsvd) else: _mem.set_raw("\xFF" * (_mem.size() // 8)) @@ -1237,9 +1309,12 @@ class RT21Radio(chirp_common.CloneModeRadio): if self.MODEL == "RB17A": _mem.set_raw("\x00" * 14 + "\xFF\xFF") elif self._reserved: - _mem.set_raw("\x00" * 13 + _rsvd) + if self.MODEL == "RT86S": + _mem.set_raw(b"\x00" * 12 + _rsvdpwr + _rsvd) + else: + _mem.set_raw(b"\x00" * 13 + _rsvd) elif self.MODEL == "AR-63": - _mem.set_raw("\x00" * 13 + _rsvd) + _mem.set_raw(b"\x00" * 13 + _rsvd) else: _mem.set_raw("\x00" * 13 + "\x30\x8F\xF8") @@ -1271,6 +1346,15 @@ class RT21Radio(chirp_common.CloneModeRadio): else: LOG.error('%s: set_mem: unhandled power level: %s' % (mem.name, mem.power)) + elif self.MODEL == "RT86S": + _pwr = self._set_pwr(mem.number) + # set the power level + if mem.power == self.POWER_LEVELS[0]: + _pwr.txpower = self.TXPOWER_HIGH + elif mem.power == self.POWER_LEVELS[1]: + _pwr.txpower = self.TXPOWER_MED + elif mem.power == self.POWER_LEVELS[2]: + _pwr.txpower = self.TXPOWER_LOW else: _mem.highpower = mem.power == self.POWER_LEVELS[0] @@ -1441,11 +1525,14 @@ class RT21Radio(chirp_common.CloneModeRadio): "RT86", "RT619", "RB89", + "RT86S", ]: if self.MODEL == "RB26" or self.MODEL == "RB23" \ - or self.MODEL == "RB89": + or self.MODEL == "RB89"or self.MODEL == "RT86S": _settings2 = self._memobj.settings2 _settings3 = self._memobj.settings3 + if self.MODEL == "RT86S": + _settings4 = self._memobj.settings4 rs = RadioSettingValueInteger(0, 9, _settings.squelch) rset = RadioSetting("squelch", "Squelch Level", rs) @@ -1500,7 +1587,7 @@ class RT21Radio(chirp_common.CloneModeRadio): basic.append(rset) if self.MODEL == "RB26" or self.MODEL == "RB23" \ - or self.MODEL == "RB89": + or self.MODEL == "RB89" or self.MODEL == "RT86S": rs = RadioSettingValueList(VOICE_LIST2, current_index=_settings.voice) rset = RadioSetting("voice", "Voice Annumciation", rs) @@ -1511,7 +1598,8 @@ class RT21Radio(chirp_common.CloneModeRadio): rset = RadioSetting("chnumberd", "Channel Number Enable", rs) basic.append(rset) - if self.MODEL == "RT86" or self.MODEL == "RB89": + if self.MODEL == "RT86" or self.MODEL == "RB89" \ + or self.MODEL == "RT86S": rs = RadioSettingValueList(SPECIAL_LIST, current_index=_settings.tailmode) rset = RadioSetting("tailmode", "QT/DQT Tail Mode", rs) @@ -1529,6 +1617,7 @@ class RT21Radio(chirp_common.CloneModeRadio): "RB26", "RT86", "RB89", + "RT86S", ]: rs = RadioSettingValueBoolean(not _settings.tail) rset = RadioSetting("tail", "QT/DQT Tail", rs) @@ -1543,10 +1632,17 @@ class RT21Radio(chirp_common.CloneModeRadio): if self.MODEL != "RT19" and self.MODEL != "RT619" and \ self.MODEL != "AR-63" and \ self.MODEL != "RT40B": - rs = RadioSettingValueList(GAIN_LIST, - current_index=_settings.gain) - rset = RadioSetting("gain", "MIC Gain", rs) - basic.append(rset) + + if self.MODEL == "RT86S": + rs = RadioSettingValueList(MICGAIN_LIST, + current_index=_settings.micgain) + rset = RadioSetting("micgain", "MIC Gain", rs) + basic.append(rset) + else: + rs = RadioSettingValueList(GAIN_LIST, + current_index=_settings.gain) + rset = RadioSetting("gain", "MIC Gain", rs) + basic.append(rset) rs = RadioSettingValueList(WARN_LIST, current_index=_settings.warn) @@ -1554,8 +1650,10 @@ class RT21Radio(chirp_common.CloneModeRadio): basic.append(rset) if self.MODEL == "RT86": - rs = RadioSettingValueInteger(1, 16, _settings.chnumber + 1) - rset = RadioSetting("settings.chnumber", "Channel Number", rs) + rs = RadioSettingValueInteger(1, self._upper, + _settings.chnumber + 1) + rset = RadioSetting("settings.chnumber", + "Channel Number", rs) basic.append(rset) rs = RadioSettingValueBoolean(_settings.vox) @@ -1572,6 +1670,23 @@ class RT21Radio(chirp_common.CloneModeRadio): rset = RadioSetting("voxd", "Vox Delay", rs) basic.append(rset) + if self.MODEL == "RT86S": + rs = RadioSettingValueInteger(1, self._upper, + _settings2.ch_number + 1) + rset = RadioSetting("settings2.ch_number", + "Channel Number", rs) + basic.append(rset) + + rs = RadioSettingValueList(VOXL_LIST, + current_index=_settings3.voxl) + rset = RadioSetting("voxl", "Vox Level", rs) + basic.append(rset) + + rs = RadioSettingValueList(VOXD_LIST, + current_index=_settings3.voxd) + rset = RadioSetting("voxd", "Vox Delay", rs) + basic.append(rset) + if self.MODEL == "RB26" or self.MODEL == "RB23" \ or self.MODEL == "RB89": rs = RadioSettingValueBoolean(_settings3.vox) @@ -1740,6 +1855,17 @@ class RT21Radio(chirp_common.CloneModeRadio): rset = RadioSetting("pf2", "PF2 Key Set", rs) basic.append(rset) + if self.MODEL == "RT86S": + rs = RadioSettingValueList(PFKEY86S_LIST, + current_index=_settings.pf_1) + rset = RadioSetting("pf_1", "PF1 Key Set", rs) + basic.append(rset) + + rs = RadioSettingValueList(PFKEY86S_LIST, + current_index=_settings.pf_2) + rset = RadioSetting("pf_2", "PF2 Key Set", rs) + basic.append(rset) + if self.MODEL == "RB28B" or self.MODEL == "RB628B": rs = RadioSettingValueInteger(0, 9, _settings.squelch) rset = RadioSetting("squelch", "Squelch Level", rs) @@ -1814,6 +1940,60 @@ class RT21Radio(chirp_common.CloneModeRadio): rset = RadioSetting("pfkey_gt", "Key Set >", rs) basic.append(rset) + if self.MODEL == "RT86S": + rs = RadioSettingValueList(BACKLIGHT_LIST, + current_index=_settings.backlight) + rset = RadioSetting("backlight", "Back Light", rs) + basic.append(rset) + + rs = RadioSettingValueList(MENUEXIT_LIST, + current_index=_settings.menuexit) + rset = RadioSetting("menuexit", "Menu Exit Time", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.weather) + rset = RadioSetting("weather", "Weather", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.seekfreq) + rset = RadioSetting("seekfreq", "Seek Freq", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.chnumber) + rset = RadioSetting("chnumber", "Talk", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings4.roger) + rset = RadioSetting("settings4.roger", "Roger", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.keylock) + rset = RadioSetting("keylock", "Key Lock", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.removectdcs) + rset = RadioSetting("removectdcs", "Remove CT/DCS", rs) + basic.append(rset) + + rs = RadioSettingValueList(WX_LIST, + current_index=_settings.wxchnumber) + rset = RadioSetting("wxchnumber", "Weather Channel", rs) + basic.append(rset) + + rs = RadioSettingValueList(GROUPCH_LIST, + current_index=_settings.pf2) + rset = RadioSetting("pf2", "Group Channel #", rs) + basic.append(rset) + + rs = RadioSettingValueList(WAITTIME_LIST, + current_index=_settings.waittime) + rset = RadioSetting("waittime", "Group Wait Time", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.pttack) + rset = RadioSetting("pttack", "Group PTT ACK", rs) + basic.append(rset) + return top def set_settings(self, settings): @@ -1838,7 +2018,7 @@ class RT21Radio(chirp_common.CloneModeRadio): element.run_apply_callback() elif setting == "channel": setattr(obj, setting, int(element.value) - 1) - elif setting == "chnumber": + elif setting == "chnumber" and self.MODEL != "RT86S": setattr(obj, setting, int(element.value) - 1) elif setting == "chnumberd": setattr(obj, setting, not int(element.value)) @@ -1848,6 +2028,8 @@ class RT21Radio(chirp_common.CloneModeRadio): setattr(obj, setting, int(element.value) - 1) elif setting == "volume": setattr(obj, setting, int(element.value) - 1) + elif setting == "ch_number": + setattr(obj, setting, int(element.value) - 1) elif element.value.get_mutable(): LOG.debug("Setting %s = %s" % (setting, element.value)) setattr(obj, setting, element.value) @@ -2034,7 +2216,8 @@ class RT29UHFRadio(RT21Radio): chirp_common.PowerLevel("Low", watts=1.00)] _magic = b"PROHRAM" - _fingerprint = [b"P3207" + b"\x13\xF8\xFF", ] # UHF model + _fingerprint = [b"P3207" + b"\x13\xF8\xFF", + b"P3207s\xF8\xFF"] # UHF model _upper = 16 _skipflags = True _reserved = False @@ -2291,7 +2474,9 @@ class RT86Radio(RT21Radio): _memsize = 0x01A0 def process_mmap(self): - self._memobj = bitwise.parse(MEM_FORMAT_RT86, self._mmap) + mem_params = {'memcnt': self._upper, 'settings_offset': '0x004E', + 'bytecnt': 2} + self._memobj = bitwise.parse(MEM_FORMAT_RT86 % mem_params, self._mmap) @directory.register @@ -2321,3 +2506,40 @@ class RB89Radio(RT21Radio): def process_mmap(self): mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0'} self._memobj = bitwise.parse(MEM_FORMAT_RB26 % mem_params, self._mmap) + + +@directory.register +class RT86SRadio(RT21Radio): + """RETEVIS RT86S""" + VENDOR = "Retevis" + MODEL = "RT86S" + BLOCK_SIZE = 0x20 + BLOCK_SIZE_UP = 0x10 + + TXPOWER_LOW = 0x00 + TXPOWER_MED = 0x01 + TXPOWER_HIGH = 0x02 + + DTCS_CODES = DTCS_EXTRA + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.00), + chirp_common.PowerLevel("Mid", watts=1.00), + chirp_common.PowerLevel("Low", watts=0.50)] + + VALID_BANDS = [(400000000, 520000000)] + + _magic = b"PHOGR" + b"\xA7\xB8" + _fingerprint = [b"P32073" + b"\x00\xFF", ] + _upper = 30 + _ack_1st_block = False + _skipflags = True + _reserved = True + + _ranges = [ + (0x0000, 0x0350), + ] + _memsize = 0x0360 + + def process_mmap(self): + mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0', + 'bytecnt': 4} + self._memobj = bitwise.parse(MEM_FORMAT_RT86 % mem_params, self._mmap) diff --git a/chirp/drivers/tdh8.py b/chirp/drivers/tdh8.py index 2fb1505..5c2916a 100644 --- a/chirp/drivers/tdh8.py +++ b/chirp/drivers/tdh8.py @@ -61,7 +61,7 @@ struct { ham:1, gmrs:1, unused14:1, - unused15:1, + dtmfst:1, pritx:1; u8 scanmode:2, unused16:1, @@ -100,7 +100,8 @@ struct { u8 ligcon; u8 voxdelay; u8 onlychmode:1, - unused:6, + breathled:3, + unused:3, alarm:1; } settings; @@ -309,7 +310,7 @@ struct { dtmfspeed:3; u8 unknown25:4, scanband:4; - u8 unknown26:8; + u8 brightness:8; u8 unknown27:8; u8 unknown28:8; u8 txled:1, @@ -696,11 +697,9 @@ struct{ SQUELCH = ['%s' % x for x in range(0, 10)] LIGHT_LIST = ["CONT", "5s", "10s", "15s", "30s"] LIGHT730_LIST = ["CONT", "10s", "20s", "30s"] -TIME_OUT_LIST = ["OFF", "60s", "120s", "180s"] MDFA_LIST = ["Frequency", "Name"] MDFB_LIST = ["Frequency", "Name"] HOP_LIST = ["A", "B", "C", "D"] -SYNC_LIST = ["ON", "OFF"] LANG_LIST = ["Chinese", "English"] SCAN_MODE_LIST = ["TO", "CO", "SE"] PRIO_LIST = ["Edit", "Busy"] @@ -711,7 +710,6 @@ LONG_KEY_LIST = ["None", "FM Radio", "Lamp", SHORT_KEY730_LIST = ["None", "Scan", "FM", "Warn", "TONE", "Weather", "Copy CH"] LONG_KEY730_LIST = SHORT_KEY730_LIST + ["Monitor"] -BUSYLOCK_LIST = ["Off", "On"] PRESS_NAME = ["stopkey1", "ssidekey1", "ssidekey2", "ltopkey2", "lsidekey3", "lsidekey4"] @@ -737,10 +735,10 @@ VFOB_NAME = ["rxfreqb", "wideb", "offsetb"] -TOT_LIST = ["OFF", "30S", "60S", "90S", "120S", "150S", "180S", "210S"] +TOT_LIST = ["Off", "30S", "60S", "90S", "120S", "150S", "180S", "210S"] ALARM_LIST = ["On site", "Alarm"] -DTMF_AUTO_RESET_LIST = ["OFF", "5S", "10S", "15S"] +DTMF_AUTO_RESET_LIST = ["Off", "5S", "10S", "15S"] DTMF_DECODING_RESPONSE_LIST = ["NULL", "RING", "REPLY", "BOTH"] DTMF_SPEED_LIST = ["80ms", "90ms", @@ -763,66 +761,41 @@ SCAN_BAND_LIST = ["All", "5.0M"] # KEY -VOX_GAIN = ["OFF", "1", "2", "3", "4", "5"] +VOX_GAIN = ["Off", "1", "2", "3", "4", "5"] VOX_DELAY = ["1.05s", "2.0s", "3.0s"] -VOX_GAIN730 = ["OFF", "1", "2", "3"] +VOX_GAIN730 = ["Off", "1", "2", "3"] VOX_DELAY730 = ["0.5s", "1.0s", "2.0s", "3.0s"] PTTID_VALUES = ["Off", "BOT", "EOT", "BOTH"] BCLOCK_VALUES = ["Off", "On"] FREQHOP_VALUES = ["Off", "On"] -SCAN_VALUES = ["Del", "Add"] # AB CHANNEL A_OFFSET = ["Off", "-", "+"] A_BAND = ["Wide", "Narrow"] -A_BUSYLOCK = ["Off", "On"] -A_SPEC_QTDQT = ["Off", "On"] A_WORKMODE = ["VFO", "VFO+CH", "CH Mode"] B_OFFSET = ["Off", "-", "+"] B_BAND = ["Wide", "Narrow"] -B_BUSYLOCK = ["Off", "On"] -B_SPEC_QTDQT = ["Off", "On"] B_WORKMODE = ["VFO", "VFO+CH", "CH Mode"] # FM -FM_WORKMODE = ["CH", "VFO"] +FM_WORKMODE = ["VFO", "CH"] FM_CHANNEL = ['%s' % x for x in range(0, 26)] # DTMF GROUPCODE = ["", "Off", "*", "#", "A", "B", "C", "D"] AB_LIST = ["A", "B"] -ALMOD_LIST = ["Site", "Tone", "Code"] BANDWIDTH_LIST = ["Wide", "Narrow"] -COLOR_LIST = ["Off", "Blue", "Orange", "Purple"] -DTMFSPEED_LIST = ["%s ms" % x for x in range(50, 2010, 10)] -DTMFST_LIST = ["OFF", "DT-ST", "ANI-ST", "DT+ANI"] -MODE_LIST = ["Channel", "Name", "Frequency"] PTTID_LIST = ["Off", "BOT", "EOT", "Both"] -PTTIDCODE_LIST = ["%s" % x for x in range(1, 16)] RTONE_LIST = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"] -RESUME_LIST = ["TO", "CO", "SE"] -ROGERRX_LIST = ["Off"] + AB_LIST -RPSTE_LIST = ["OFF"] + ["%s" % x for x in range(1, 11)] SCODE_LIST = ["%s" % x for x in range(1, 16)] -SHIFTD_LIST = ["Off", "+", "-"] -STEDELAY_LIST = ["OFF"] + ["%s ms" % x for x in range(100, 1100, 100)] STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0] STEP_LIST = [str(x) for x in STEPS] STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0] -STEP291_LIST = [str(x) for x in STEPS] -TDRAB_LIST = ["Off"] + AB_LIST -TDRCH_LIST = ["CH%s" % x for x in range(1, 129)] -TIMEOUT_LIST = ["%s sec" % x for x in range(15, 615, 15)] + \ - ["Off (if supported by radio)"] TIMEOUT730_LIST = ["Off"] + ["%s sec" % x for x in range(30, 240, 30)] -VOICE_LIST = ["Off", "English", "Chinese"] -VOX_LIST = ["OFF"] + ["%s" % x for x in range(1, 11)] -WORKMODE_LIST = ["Frequency", "Channel"] # mic MIC_GAIN_LIST = ['%s' % x for x in range(0, 10)] -MIC_GAIN_LIST_H8 = ['%s' % x for x in range(0, 33)] H8_LIST = ["TD-H8", "TD-H8-HAM", "TD-H8-GMRS"] H3_LIST = ["TD-H3", "TD-H3-HAM", "TD-H3-GMRS"] @@ -835,8 +808,7 @@ NOAA_FREQS = [162550000, 162400000, 162475000, 162425000, 162450000, HAM_GMRS_NAME = ["NOAA 1", "NOAA 2", "NOAA 3", "NOAA 4", "NOAA 5", "NOAA 6", "NOAA 7", "NOAA 8", "NOAA 9", "NOAA 10", "NOAA 11"] -ALL_MODEL = ["TD-H8", "TD-H8-HAM", "TD-H8-GMRS", "TD-H3", - "TD-H3-HAM", "TD-H3-GMRS", "RT-730"] +ALL_MODEL = H8_LIST + H3_LIST + ["RT-730"] TD_H8 = b"\x50\x56\x4F\x4A\x48\x1C\x14" TD_H3 = b"\x50\x56\x4F\x4A\x48\x5C\x14" @@ -1046,9 +1018,10 @@ class TDH8(chirp_common.CloneModeRadio): _tx_power = [chirp_common.PowerLevel("Low", watts=1.00), chirp_common.PowerLevel("Mid", watts=4.00), chirp_common.PowerLevel("High", watts=8.00)] - _ponmsg_list = ["Full", "Message", "Icon"] - _save_list = ["Off", "1:1", "1:2", "1:3", "1:4"] - _save_shortname = "Battery Save" + _ponmsg_list = ["Off", "Msg", "Icon"] + _breath_led_list = ["Off", "5S", "10S", "15S", "30S"] + _save_list = ["Off", "1:1", "1:2", "1:3", "1:4", "1:8"] + _save_shortname = "Power Save" @classmethod def detect_from_serial(cls, pipe): @@ -1472,17 +1445,14 @@ class TDH8(chirp_common.CloneModeRadio): basic.append(rs) rs = RadioSetting("sync", "SYNC", - RadioSettingValueList( - SYNC_LIST, - current_index=_settings.sync)) - + RadioSettingValueBoolean( + not _settings.sync)) basic.append(rs) rs = RadioSetting("save", self._save_shortname, RadioSettingValueList( self._save_list, current_index=_settings.save)) - basic.append(rs) rs = RadioSetting("dbrx", "Double Rx", @@ -1519,18 +1489,32 @@ class TDH8(chirp_common.CloneModeRadio): basic.append(rs) if self.MODEL != "RT-730": + if self.MODEL in H8_LIST: + # H8 uses roger-beep bool + rs = RadioSetting("rogerprompt", "Roger", + RadioSettingValueBoolean( + _settings.rogerprompt)) + basic.append(rs) + if self.MODEL in H3_LIST: # H3 uses roger-beep list rs = RadioSetting("rogerprompt", "Roger", RadioSettingValueList( self._roger_list, current_index=_settings.rogerprompt)) - else: - # H8 uses roger-beep bool - rs = RadioSetting("rogerprompt", "Roger", - RadioSettingValueBoolean( - _settings.rogerprompt)) - basic.append(rs) + basic.append(rs) + + if _settings.brightness not in range(0, 5): + LOG.warning( + "brightness out of range 1 to 5. Actual value: %X. " + "Screen may not be visible", + _settings.brightness) + + rs = RadioSetting("brightness", "Brightness", + RadioSettingValueList( + self._brightness_list, + current_index=4 - _settings.brightness)) + basic.append(rs) rs = RadioSetting("txled", "Disp Lcd(TX)", RadioSettingValueBoolean(_settings.txled)) @@ -1557,8 +1541,9 @@ class TDH8(chirp_common.CloneModeRadio): if self.MODEL in H8_LIST: rs = RadioSetting("stopkey1", "SHORT_KEY_TOP", - RadioSettingValueList(SHORT_KEY_LIST, - current_index=0)) + RadioSettingValueList( + SHORT_KEY_LIST, + current_index=_press.stopkey1)) basic.append(rs) rs = RadioSetting("ltopkey2", "LONG_KEY_TOP", @@ -1651,6 +1636,12 @@ class TDH8(chirp_common.CloneModeRadio): current_index=_settings.voxdelay)) basic.append(rs) + rs = RadioSetting("breathled", "Breath Led", + RadioSettingValueList( + self._breath_led_list, + current_index=_settings.breathled)) + basic.append(rs) + rs = RadioSetting("ponmsg", "Power-On Message", RadioSettingValueList( self._ponmsg_list, @@ -1819,8 +1810,8 @@ class TDH8(chirp_common.CloneModeRadio): cur_a_power = 0 rs = RadioSetting("lowpower", "A TX Power", RadioSettingValueList( - [str(x) for x in self._tx_power], - str(self._tx_power[cur_a_power]))) + [str(x) for x in self._tx_power], + current_index=cur_a_power)) abblock.append(rs) rs = RadioSetting("wide", "A Band", @@ -1829,14 +1820,11 @@ class TDH8(chirp_common.CloneModeRadio): abblock.append(rs) rs = RadioSetting("bcl", "A Busy Lock", - RadioSettingValueList( - A_BUSYLOCK, current_index=_vfoa.bcl)) + RadioSettingValueBoolean(_settings.ablock)) abblock.append(rs) rs = RadioSetting("specialqta", "A Special QT/DQT", - RadioSettingValueList( - A_SPEC_QTDQT, - current_index=_vfoa.specialqta)) + RadioSettingValueBoolean(_vfoa.specialqta)) abblock.append(rs) rs = RadioSetting( @@ -1888,8 +1876,8 @@ class TDH8(chirp_common.CloneModeRadio): cur_b_power = 0 rs = RadioSetting("lowpowerb", "B TX Power", RadioSettingValueList( - [str(x) for x in self._tx_power], - str(self._tx_power[cur_b_power]))) + [str(x) for x in self._tx_power], + current_index=cur_b_power)) abblock.append(rs) rs = RadioSetting("wideb", "B Band", @@ -1898,14 +1886,11 @@ class TDH8(chirp_common.CloneModeRadio): abblock.append(rs) rs = RadioSetting("bclb", "B Busy Lock", - RadioSettingValueList( - B_BUSYLOCK, current_index=_vfob.bclb)) + RadioSettingValueBoolean(_settings.bblock)) abblock.append(rs) rs = RadioSetting("specialqtb", "B Special QT/DQT", - RadioSettingValueList( - B_SPEC_QTDQT, - current_index=_vfob.specialqtb)) + RadioSettingValueBoolean(_vfob.specialqtb)) abblock.append(rs) rs = RadioSetting( @@ -1928,7 +1913,7 @@ class TDH8(chirp_common.CloneModeRadio): current_index=_settings.fmroad)) fmmode.append(rs) - rs = RadioSetting("fmrec", "Forbid Receive", + rs = RadioSetting("fmrec", "Allow Receive", RadioSettingValueBoolean(_settings.fmrec)) fmmode.append(rs) @@ -1978,9 +1963,11 @@ class TDH8(chirp_common.CloneModeRadio): gcode_val = "" else: gcode_val = gcode_val[1] - rs = RadioSetting("gcode", "Group Code", - RadioSettingValueList(GROUPCODE, - gcode_val)) + rs = RadioSetting( + "gcode", "Group Code", + RadioSettingValueList( + GROUPCODE, + current_index=GROUPCODE.index(gcode_val))) dtmf.append(rs) icode_list = self._memobj.icode.idcode @@ -2103,6 +2090,11 @@ class TDH8(chirp_common.CloneModeRadio): ecode_val = RadioSettingValueString(0, 7, used_ecode) rs = RadioSetting("ecode", "PTT ID Ending(BOT)", ecode_val) dtmf.append(rs) + if self.MODEL in H8_LIST: + rs = RadioSetting("dtmfst", "DTMF Side Tones", + RadioSettingValueBoolean(_settings.dtmfst)) + dtmf.append(rs) + # H3 if self.MODEL not in H8_LIST: # stuncode @@ -2204,7 +2196,6 @@ class TDH8(chirp_common.CloneModeRadio): elif name in PRESS_NAME: obj = _press setting = element.get_name() - elif name in VFOA_NAME: obj = _vfoa setting = element.get_name() @@ -2232,7 +2223,7 @@ class TDH8(chirp_common.CloneModeRadio): elif "scode" in name: obj = self._memobj.startcode.scode setting = element.get_name() - elif "ecode" in name: + elif "ecode" == name: obj = self._memobj.endcode.ecode setting = element.get_name() elif "group1" in name: @@ -2274,9 +2265,12 @@ class TDH8(chirp_common.CloneModeRadio): if element.has_apply_callback(): LOG.debug("Using apply callback") element.run_apply_callback() - + elif "brightness" == name: + _settings.brightness = 4 - int(element.value) + elif "sync" == name: + _settings.sync = not int(element.value) # Channel A - elif setting == "rxfreqa" and element.value.get_mutable(): + elif "rxfreqa" == setting and element.value.get_mutable(): val = int(str(element.value).replace( '.', '').ljust(8, '0')) if (val >= 13600000 and val <= 17400000) or \ @@ -2291,7 +2285,7 @@ class TDH8(chirp_common.CloneModeRadio): "or enabled in settings") raise InvalidValueError(msg) - elif setting == "ofseta" and element.value.get_mutable(): + elif "ofseta" == setting and element.value.get_mutable(): if '.' in str(element.value): val = str(element.value).replace(' ', '') if len( @@ -2325,7 +2319,7 @@ class TDH8(chirp_common.CloneModeRadio): raise InvalidValueError(msg) # B channel - elif setting == "rxfreqb" and element.value.get_mutable(): + elif "rxfreqb" == setting and element.value.get_mutable(): val = 0 val = int(str(element.value).replace( '.', '').ljust(8, '0')) @@ -2342,7 +2336,7 @@ class TDH8(chirp_common.CloneModeRadio): raise InvalidValueError(msg) # setattr(obj, setting, val) - elif setting == "ofsetb" and element.value.get_mutable(): + elif "ofsetb" == setting and element.value.get_mutable(): if '.' in str(element.value): val = str(element.value).replace(' ', '') if len(val[val.index(".") + 1:] @@ -2391,10 +2385,10 @@ class TDH8(chirp_common.CloneModeRadio): self._memobj.fmmode[num].fmblock = val self._memobj.fmusedflags[num] = bool(val) - elif setting == 'fmvfo' and element.value.get_mutable(): + elif 'fmvfo' == setting and element.value.get_mutable(): self._memobj.fmvfo = int(element.value * 10) - elif setting == 'gcode' and element.value.get_mutable(): + elif 'gcode' == setting and element.value.get_mutable(): val = str(element.value) if val == 'Off': gcode_used = 0xFF @@ -2414,7 +2408,7 @@ class TDH8(chirp_common.CloneModeRadio): gcode_used = 0x00 self._memobj.groupcode.gcode = gcode_used - elif setting == 'icode' and element.value.get_mutable(): + elif 'icode' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2427,7 +2421,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.icode.idcode = list_val - elif setting == 'scode' and element.value.get_mutable(): + elif 'scode' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2440,7 +2434,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.startcode.scode = list_val - elif setting == 'ecode' and element.value.get_mutable(): + elif 'ecode' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2453,7 +2447,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.endcode.ecode = list_val - elif setting == 'group1' and element.value.get_mutable(): + elif 'group1' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2466,7 +2460,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group1.group1 = list_val - elif setting == 'group2' and element.value.get_mutable(): + elif 'group2' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2479,7 +2473,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group2.group2 = list_val - elif setting == 'group3' and element.value.get_mutable(): + elif 'group3' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2492,7 +2486,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group3.group3 = list_val - elif setting == 'group4' and element.value.get_mutable(): + elif 'group4' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2505,7 +2499,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group4.group4 = list_val - elif setting == 'group5' and element.value.get_mutable(): + elif 'group5' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2518,7 +2512,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group5.group5 = list_val - elif setting == 'group6' and element.value.get_mutable(): + elif 'group6' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2531,7 +2525,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group6.group6 = list_val - elif setting == 'group7' and element.value.get_mutable(): + elif 'group7' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2544,7 +2538,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group7.group7 = list_val - elif setting == 'group8' and element.value.get_mutable(): + elif 'group8' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2559,7 +2553,7 @@ class TDH8(chirp_common.CloneModeRadio): elif setting == 'micgain': self._memobj.mic.micgain = ( str(element.value)) - elif setting == 'stuncode' and element.value.get_mutable(): + elif 'stuncode' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2571,7 +2565,7 @@ class TDH8(chirp_common.CloneModeRadio): list_val.append(0xFF) lenth_val += 1 self._memobj.skcode.stuncode = list_val - elif setting == 'killcode' and element.value.get_mutable(): + elif 'killcode' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2681,10 +2675,8 @@ class TDH3(TDH8): _mem_params = (0x1F2F) _tx_power = [chirp_common.PowerLevel("Low", watts=2.00), chirp_common.PowerLevel("High", watts=5.00)] - _ponmsg_list = ["Off", "Message", "Icon"] _roger_list = ["Off", "TONE1", "TONE2"] - _save_list = ["Off", "1:1", "1:2", "1:3", "1:4", "1:8"] - _save_shortname = "Power Save" + _brightness_list = ["1", "2", "3", "4", "5"] def process_mmap(self): self._memobj = bitwise.parse(MEM_FORMAT_H3, self._mmap) diff --git a/chirp/drivers/thd74.py b/chirp/drivers/thd74.py index f05df6d..ef94047 100644 --- a/chirp/drivers/thd74.py +++ b/chirp/drivers/thd74.py @@ -9,6 +9,7 @@ from chirp import chirp_common from chirp import directory from chirp import errors from chirp import memmap +from chirp import settings LOG = logging.getLogger(__name__) @@ -189,6 +190,7 @@ class THD74Radio(chirp_common.CloneModeRadio, _memsize = 0x7A300 def read_block(self, block, count=256): + self.pipe.log('Reading block %i' % block) hdr = struct.pack(">cHH", b"R", block, 0) self.pipe.write(hdr) r = self.pipe.read(5) @@ -210,6 +212,7 @@ class THD74Radio(chirp_common.CloneModeRadio, return data def write_block(self, block, map, size=256): + self.pipe.log('Writing block %i' % block) hdr = struct.pack(">cHH", b"W", block, size < 256 and size or 0) base = block * size data = map[base:base + size] @@ -423,9 +426,10 @@ class THD74Radio(chirp_common.CloneModeRadio, mem.duplex = DUPLEX[_mem.duplex] mem.tuning_step = TUNE_STEPS[_mem.tuning_step] mem.mode = MODES[_mem.mode] - mem.rtone = chirp_common.TONES[_mem.rtone] - mem.ctone = chirp_common.TONES[_mem.ctone] - mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs_code] + if mem.mode != 'DV': + mem.rtone = chirp_common.TONES[_mem.rtone] + mem.ctone = chirp_common.TONES[_mem.ctone] + mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs_code] if _mem.tone_mode: mem.tmode = 'Tone' @@ -459,6 +463,13 @@ class THD74Radio(chirp_common.CloneModeRadio, if 'Call' in mem.extd_number and mem.mode == 'DV': mem.immutable.append('mode') + mem.extra = settings.RadioSettingGroup('extra', 'Extra') + rs = settings.RadioSetting( + 'rptmode', 'DV Repeater Mode', + settings.RadioSettingValueBoolean(_mem.mode == 7)) + if mem.mode != 'DV': + rs.value.set_mutable(False) + mem.extra.append(rs) return mem def set_memory(self, mem): @@ -472,6 +483,7 @@ class THD74Radio(chirp_common.CloneModeRadio, _flg = self._memobj.flags[mem.number] _nam = self._memobj.names[mem.number + name_index_adj] + was_empty = int(_flg.used) == 0xFF _flg.used = get_used_flag(mem) if mem.empty: @@ -483,7 +495,9 @@ class THD74Radio(chirp_common.CloneModeRadio, _mem.set_raw(b'\x00' * 40) - _flg.group = 0 # FIXME + if was_empty: + # New memories go to group 0 in case it wasn't cleared on delete + _flg.group = 0 _mem.freq = mem.freq _nam.name = mem.name.ljust(16) @@ -517,6 +531,15 @@ class THD74Radio(chirp_common.CloneModeRadio, _mem.dv_rpt1call = encode_call(mem.dv_rpt1call) _mem.dv_rpt2call = encode_call(mem.dv_rpt2call) _mem.dv_code = mem.dv_code + if mem.extra and 'rptmode' in mem.extra: + rptmode = bool(mem.extra['rptmode'].value) + else: + # Pasting a DV memory from another radio means we will + # not have the extra.rptmode flag. So, assume repeater mode + # if the rpt1call has a module in the last character + rptmode = mem.dv_rpt1call.ljust(8)[7] != ' ' + if mem.mode == 'DV' and rptmode: + _mem.mode = 7 def get_raw_memory(self, number): return (repr(self._get_raw_memory(number)) + diff --git a/chirp/drivers/tk270.py b/chirp/drivers/tk270.py index 98cbb1e..c4b664f 100644 --- a/chirp/drivers/tk270.py +++ b/chirp/drivers/tk270.py @@ -48,11 +48,11 @@ struct { #seekto 0x0338; u8 scan[4]; // 4 bytes / bit LSBF for the channel -#seekto 0x033C; +// #seekto 0x033C; u8 active[4]; // 4 bytes / bit LSBF for the active cha // active = 0 -#seekto 0x0340; +// #seekto 0x0340; struct { u8 kMoni; // monitor key function u8 kScan; // scan key function @@ -95,8 +95,8 @@ struct { MEM_SIZE = 0x400 BLOCK_SIZE = 8 MEM_BLOCKS = list(range(0, (MEM_SIZE // BLOCK_SIZE))) -ACK_CMD = "\x06" -TIMEOUT = 0.05 # from 0.03 up it' s safe, we set in 0.05 for a margin +ACK_CMD = b"\x06" +TIMEOUT = 1 POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1), chirp_common.PowerLevel("High", watts=5)] @@ -146,10 +146,10 @@ def send(radio, frame): rawsend(radio, frame) -def make_frame(cmd, addr, data=""): +def make_frame(cmd, addr, data=b""): """Pack the info in the format it likes""" ts = struct.pack(">BHB", ord(cmd), addr, 8) - if data == "": + if not data: return ts else: if len(data) == 8: @@ -200,33 +200,15 @@ def open_radio(radio): raise errors.RadioError(msg) # we will try to open the radio 5 times, this is an improved mechanism - magic = "PROGRAM" - exito = False - for i in range(0, 5): - for i in range(0, len(magic)): - ack = rawrecv(radio, 1) - time.sleep(0.05) - send(radio, magic[i]) + magic = b"PROGRAM" + radio.pipe.write(magic) + handshake(radio, 'Radio did not respond to program command') - try: - handshake(radio, "Radio not entering Program mode") - exito = True - break - except: - LOG.debug("Attempt #%s, failed, trying again" % i) - pass - - # check if we had EXITO - if exito is False: - msg = "The radio did not accept program mode after five tries.\n" - msg += "Check you interface cable and power cycle your radio." - raise errors.RadioError(msg) - - rawsend(radio, "\x02") + rawsend(radio, b"\x02") ident = rawrecv(radio, 8) handshake(radio, "Comm error after ident", True) - if not (radio.TYPE in ident): + if not (radio.TYPE.encode() in ident): LOG.debug("Incorrect model ID, got %s" % util.hexprint(ident)) msg = "Incorrect model ID, got %s, it not contains %s" % \ (ident[0:5], radio.TYPE) @@ -240,11 +222,11 @@ def do_download(radio): # UI progress status = chirp_common.Status() status.cur = 0 - status.max = MEM_SIZE / BLOCK_SIZE + status.max = MEM_SIZE // BLOCK_SIZE status.msg = "Cloning from radio..." radio.status_fn(status) - data = "" + data = b"" for addr in MEM_BLOCKS: send(radio, make_frame("R", addr * BLOCK_SIZE)) data += recv(radio) @@ -257,7 +239,7 @@ def do_download(radio): status.msg = "Cloning from radio..." radio.status_fn(status) - return memmap.MemoryMap(data) + return memmap.MemoryMapBytes(data) def do_upload(radio): @@ -267,7 +249,7 @@ def do_upload(radio): # UI progress status = chirp_common.Status() status.cur = 0 - status.max = MEM_SIZE / BLOCK_SIZE + status.max = MEM_SIZE // BLOCK_SIZE status.msg = "Cloning to radio..." radio.status_fn(status) count = 0 @@ -319,7 +301,6 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa VARIANT = "" MODEL = "" _kind = "" - NEEDS_COMPAT_SERIAL = True @classmethod def get_prompts(cls): @@ -384,7 +365,13 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa def sync_in(self): """Download from radio""" - self._mmap = do_download(self) + try: + self._mmap = do_download(self) + except errors.RadioError: + raise + except Exception as e: + LOG.exception('Error downloading: %s', e) + raise errors.RadioError("Error downloading data from radio") self.process_mmap() def sync_out(self): @@ -392,13 +379,17 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa # Get the data ready for upload try: self._prep_data() - except: + except Exception as e: + LOG.exception('Failed to prepare data for upload: %s', e) raise errors.RadioError("Error processing the radio data") # do the upload try: do_upload(self) - except: + except errors.RadioError: + raise + except Exception as e: + LOG.exception('Error uploading: %s', e) raise errors.RadioError("Error uploading data to radio") def set_variant(self): @@ -446,13 +437,13 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa # fldata = "\x00\xf0\xff\xff\xff" * achs + \ # "\xff" * (5 * (self._upper - achs)) - fldata = "\xFF" * 5 * self._upper + fldata = b"\xFF" * 5 * self._upper self._fill(0x0280, fldata) def _fill(self, offset, data): """Fill an specified area of the memmap with the passed data""" for addr in range(0, len(data)): - self._mmap[offset + addr] = data[addr] + self._mmap[offset + addr] = bytes([data[addr]]) def process_mmap(self): """Process the mem map into the mem object""" @@ -494,7 +485,7 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa def decode_tone(self, val): """Parse the tone data to decode from mem, it returns: Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)""" - if val.get_raw(asbytes=False) == "\xFF\xFF": + if val.get_raw() == b"\xFF\xFF": return '', None, None val = int(val) @@ -557,11 +548,11 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa # Memory number mem.number = number - if _mem.get_raw(asbytes=False)[0] == "\xFF": + if _mem.get_raw()[0] == 0xFF: mem.empty = True # but is not enough, you have to clear the memory in the mmap # to get it ready for the sync_out process, just in case - _mem.set_raw("\xFF" * 16) + _mem.set_raw(b"\xFF" * 16) # set the channel to inactive state self.set_active(number - 1, False) return mem @@ -569,7 +560,7 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa # Freq and offset mem.freq = int(_mem.rxfreq) * 10 # tx freq can be blank - if _mem.get_raw(asbytes=False)[4] == "\xFF" or int(_mem.txen) == 255: + if _mem.get_raw()[4] == 0xFF or int(_mem.txen) == 255: # TX freq not set mem.offset = 0 mem.duplex = "off" diff --git a/chirp/drivers/tk280.py b/chirp/drivers/tk280.py index e798fca..1221cb6 100644 --- a/chirp/drivers/tk280.py +++ b/chirp/drivers/tk280.py @@ -55,6 +55,25 @@ LOG = logging.getLogger(__name__) # # + +def choose_step(step_map, freq, default=5.0): + """Choose the proper step index for a given frequency. + + @step_map should be a dict of step (in kHz) to index, in order of + preference. + @freq should be a frequency in Hz. + Returns the step index from step_map to use. + """ + try: + step = chirp_common.required_step(freq, step_map.keys()) + except errors.InvalidDataError: + step = default + LOG.warning('Frequency %s requires step not in available map, ' + 'using %s kHz by default', + chirp_common.format_freq(freq), step) + return step_map[step] + + CONVENTIONAL_DEFS = """ struct conv_settings { // x00-x01, Edit>>Model Information>>Radio Format, @@ -1658,18 +1677,8 @@ class KenwoodTKx80(chirp_common.CloneModeRadio): 5.0: 0x1, 2.5: 0x0, } - try: - _mem.rx_step = step_lookup[chirp_common.required_step( - int(_mem.rxfreq) * 10, allowed=step_lookup.keys())] - except errors.InvalidDataError: - LOG.warning('Unknown step for rx freq, defaulting to 5kHz') - _mem.rx_step = 0x1 - try: - _mem.tx_step = step_lookup[chirp_common.required_step( - int(_mem.txfreq) * 10, allowed=step_lookup.keys())] - except errors.InvalidDataError: - LOG.warning('Unknown step for tx freq, defaulting to 5kHz') - _mem.tx_step = 0x1 + _mem.rx_step = choose_step(step_lookup, int(_mem.rxfreq) * 10) + _mem.tx_step = choose_step(step_lookup, int(_mem.txfreq) * 10) ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \ chirp_common.split_tone_encode(mem) diff --git a/chirp/drivers/tk3140.py b/chirp/drivers/tk3140.py index af9e6ca..6148fa8 100644 --- a/chirp/drivers/tk3140.py +++ b/chirp/drivers/tk3140.py @@ -20,6 +20,7 @@ import struct from chirp import chirp_common from chirp import bitwise from chirp import directory +from chirp.drivers import tk280 from chirp.drivers import tk8160 from chirp.drivers import tk8180 from chirp import errors @@ -35,13 +36,11 @@ EMPTY_INDEX_ENTRY = IndexEntry(0xFF, 0xFF, 0xFF, 0xFF) def send(radio, frame): - LOG.debug("%04i P>R:\n%s" % (len(frame), util.hexprint(frame))) radio.pipe.write(frame) def recv(radio, count): buf = radio.pipe.read(count) - LOG.debug('%04i: R>P:\n%s' % (len(buf), util.hexprint(buf))) return buf @@ -143,7 +142,6 @@ def do_upload(radio): data = radio._mmap.get_packed() for block in range(0x80): if 0x54 <= block < 0x60: - LOG.debug('Skipping block 0x%02x' % block) continue addr = block * 256 chunk = data[addr:addr + 256] @@ -290,8 +288,10 @@ struct { char name[10]; lbcd rx_freq[4]; lbcd tx_freq[4]; - u8 rxsomething; - u8 txsomething; + u8 rxsomething:4, + rxstep:4; + u8 txsomething:4, + txstep:4; ul16 rxtone; ul16 txtone; u8 unknown2[5]; @@ -547,8 +547,8 @@ class KenwoodTKx140Radio(chirp_common.CloneModeRadio): _mem.memory = mem.number _mem.zone = self._zone self.sort_index() - _mem.rxsomething = 0x35 - _mem.txsomething = 0x35 + _mem.rxsomething = 0x3 + _mem.txsomething = 0x3 _mem.rx_freq = mem.freq // 10 if mem.duplex == '': @@ -564,6 +564,17 @@ class KenwoodTKx140Radio(chirp_common.CloneModeRadio): else: raise errors.RadioError('Unsupported duplex mode %r' % mem.duplex) + step_lookup = { + 6.25: 0x02, + 12.5: 0x05, + 5.0: 0x01, + 2.5: 0x00, + 10.0: 0x04, + 7.5: 0x06, # maybe? + } + _mem.rxstep = tk280.choose_step(step_lookup, int(_mem.rx_freq) * 10) + _mem.txstep = tk280.choose_step(step_lookup, int(_mem.tx_freq) * 10) + txtone, rxtone = chirp_common.split_tone_encode(mem) _mem.rxtone = tk8180.KenwoodTKx180Radio._encode_tone(*rxtone) _mem.txtone = tk8180.KenwoodTKx180Radio._encode_tone(*txtone) diff --git a/chirp/drivers/tk760g.py b/chirp/drivers/tk760g.py index 934979d..5d61c89 100644 --- a/chirp/drivers/tk760g.py +++ b/chirp/drivers/tk760g.py @@ -21,7 +21,7 @@ from chirp import chirp_common, directory, memmap, errors, util, bitwise from chirp.settings import RadioSettingGroup, RadioSetting, \ RadioSettingValueBoolean, RadioSettingValueList, \ RadioSettingValueString, RadioSettingValueInteger, \ - RadioSettings + RadioSettings, RadioSettingValueMap LOG = logging.getLogger(__name__) @@ -327,13 +327,15 @@ KEYS = { 0x5d: "AUX", 0xa1: "Channel Up/Down" # Knob for portables only } +KEY_MAP = [(v, k) for k, v in KEYS.items()] def _raw_recv(radio, amount): """Raw read from the radio device""" try: data = radio.pipe.read(amount) - except: + except Exception as e: + LOG.exception('Failed read: %s', e) raise errors.RadioError("Error reading data from radio") # DEBUG @@ -347,7 +349,8 @@ def _raw_send(radio, data): """Raw send to the radio device""" try: radio.pipe.write(data) - except: + except Exception as e: + LOG.exception('Failed write: %s', e) raise errors.RadioError("Error sending data to radio") # DEBUG @@ -418,7 +421,7 @@ def _recv(radio): raise errors.RadioError('No response from radio') elif cmd == b'Z': # Empty "zero" block - ff = _raw_recv(radio, 1) + _raw_recv(radio, 1) _handshake(radio, "after zero block") return b'\xff' * 256 elif cmd != b'W': @@ -748,7 +751,7 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, if bnumb != 255 and (bank != 255 and bank != 0): try: data[bank].append(ch) - except: + except Exception: data[bank] = list() data[bank].append(ch) data[bank].sort() @@ -1117,7 +1120,6 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, mess = self._memobj.message keys = self._memobj.keys idm = self._memobj.id - passwd = self._memobj.passwords # basic features of the radio basic = RadioSettingGroup("basic", "Basic Settings") @@ -1134,7 +1136,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, # Basic tot = RadioSetting("settings.tot", "Time Out Timer (TOT)", - RadioSettingValueList(TOT, '%i' % sett.tot)) + RadioSettingValueList( + TOT, current_index=TOT.index('%i' % sett.tot))) basic.append(tot) totalert = RadioSetting("settings.tot_alert", "TOT pre alert", @@ -1199,6 +1202,12 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, RadioSettingValueString(0, 8, ponm, False)) basic.append(pom) + offhook = RadioSetting('settings.off_hook_decode', 'Off-hook decode', + RadioSettingValueBoolean( + not sett.off_hook_decode)) + offhook.set_doc('Squelch mode active when mic is off-hook') + basic.append(offhook) + # dealer valid_chars = ",-/:[]" + chirp_common.CHARSET_ALPHANUMERIC mstr = "".join([c for c in self._VARIANT if c in valid_chars]) @@ -1250,28 +1259,28 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, # The Mobile only parameters are wrapped here if self.TYPE[0] == "M": vu = RadioSetting("keys.kVOL_UP", "VOL UP", - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kVOL_UP)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kVOL_UP))) fkeys.append(vu) vd = RadioSetting("keys.kVOL_DOWN", "VOL DOWN", - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kVOL_DOWN)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kVOL_DOWN))) fkeys.append(vd) chu = RadioSetting("keys.kCH_UP", "CH UP", - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kCH_UP)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kCH_UP))) fkeys.append(chu) chd = RadioSetting("keys.kCH_DOWN", "CH DOWN", - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kCH_DOWN)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kCH_DOWN))) fkeys.append(chd) foot = RadioSetting("keys.kFOOT", "Foot switch", - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kFOOT)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kFOOT))) fkeys.append(foot) # this is the common buttons for all @@ -1283,8 +1292,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, scn_name = "Open Circle" scn = RadioSetting("keys.kSCN", scn_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kSCN)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kSCN))) fkeys.append(scn) a_name = "A" @@ -1292,8 +1301,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, a_name = "Closed circle" a = RadioSetting("keys.kA", a_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kA)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kA))) fkeys.append(a) da_name = "D/A" @@ -1301,8 +1310,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, da_name = "< key" da = RadioSetting("keys.kDA", da_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kDA)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kDA))) fkeys.append(da) gu_name = "Triangle up" @@ -1310,8 +1319,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, gu_name = "Side 1" gu = RadioSetting("keys.kGROUP_UP", gu_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kGROUP_UP)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kGROUP_UP))) fkeys.append(gu) # Side keys on portables @@ -1320,8 +1329,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, gd_name = "> key" gd = RadioSetting("keys.kGROUP_DOWN", gd_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kGROUP_DOWN)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kGROUP_DOWN))) fkeys.append(gd) mon_name = "MON" @@ -1329,8 +1338,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, mon_name = "Side 2" mon = RadioSetting("keys.kMON", mon_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kMON)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kMON))) fkeys.append(mon) return top @@ -1364,7 +1373,7 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, # catching the "off" values as zero try: value = int(value) - except: + except ValueError: value = 0 # tot case step 15 @@ -1383,11 +1392,11 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, # Bool types + inverted if setting in ["c2t", "poweron_tone", "control_tone", "warn_tone", "battery_save", "self_prog", - "clone", "panel_test"]: + "clone", "panel_test", "off_hook_decode"]: value = bool(value) # this cases are inverted - if setting == "c2t": + if setting in ["c2t", "off_hook_decode"]: value = not value # case battery save is special @@ -1447,7 +1456,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, b = 0 mem = self._memobj.memory[loc - 1] mem.bank = b + 1 - except: + except Exception as e: + LOG.warning('Failed to set bank: %s', e) msg = "You can't have a channel without a bank, click another bank" raise errors.InvalidDataError(msg) @@ -1649,7 +1659,9 @@ class TK272G_Radios(Kenwood_Serie_60G): MODEL = "TK-272G" TYPE = b"P2720" VARIANTS = { - b"P2720\x05\xfb": (32, 136, 150, "K1"), + # NOTE: This is technically 136-150 MHz, but the radio supports + # the full range for RX at least + b"P2720\x05\xfb": (32, 136, 174, "K1"), b"P2720\x04\xfb": (32, 150, 174, "K") } diff --git a/chirp/drivers/tk8180.py b/chirp/drivers/tk8180.py index 132ce50..d644933 100644 --- a/chirp/drivers/tk8180.py +++ b/chirp/drivers/tk8180.py @@ -445,16 +445,15 @@ def do_download(radio): status.max = radio._memsize status.msg = "Cloning from radio" radio.status_fn(status) - LOG.debug('Radio address 0x%04x' % len(data)) # Addresses 0x0000-0xBF00 pulled by block number (divide by 0x100) for block in range(0, 0xBF + 1): + radio.pipe.log('Read block index %02x' % block) send(radio, make_frame('R', block)) cmd = radio.pipe.read(1) chunk = b'' if cmd == b'Z': data += bytes(b'\xff' * 256) - LOG.debug('Radio reports empty block %02x' % block) elif cmd == b'W': chunk = bytes(radio.pipe.read(256)) if len(chunk) != 256: @@ -466,7 +465,6 @@ def do_download(radio): chr(cmd))) raise errors.RadioError('Radio sent unexpected response') - LOG.debug('Read block index %02x' % block) status() chksum = radio.pipe.read(1) @@ -488,6 +486,7 @@ def do_download(radio): # Addresses 0xC000 - 0xD1F0 pulled by address for block in range(0x0100, 0x1200, 0x40): + radio.pipe.log('Read memory address %04x' % block) send(radio, make_frame('S', block, b'\x40')) x = radio.pipe.read(1) if x != b'X': @@ -495,7 +494,6 @@ def do_download(radio): chunk = radio.pipe.read(0x40) data += chunk - LOG.debug('Read memory address %04x' % block) status() radio.pipe.write(b'\x06') @@ -524,9 +522,9 @@ def do_upload(radio): addr = block * 0x100 chunk = bytes(radio._mmap[addr:addr + 0x100]) if all(byte == b'\xff' for byte in chunk): - LOG.debug('Sending zero block %i, range 0x%04x' % (block, addr)) send(radio, make_frame('Z', block, b'\xFF')) else: + radio.pipe.log('Sending block %i' % block) checksum = checksum_data(chunk) send(radio, make_frame('W', block, chunk + bytes([checksum]))) @@ -585,8 +583,8 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): def __init__(self, *a, **k): self._zones = [] chirp_common.CloneModeRadio.__init__(self, *a, **k) - _dat_header = (b'KPG89D\xFF\xFF\xFF\xFFV1.61' + self._model + - (b'\xFF' * 11) + (b'\xFF' * 32)) + self._dat_header = (b'KPG89D\xFF\xFF\xFF\xFFV1.61' + self._model + + (b'\xFF' * 11) + (b'\xFF' * 32)) def sync_in(self): try: @@ -639,7 +637,6 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): return self._model.startswith(b'P') def probe_layout(self): - start_addrs = [] tmp_format = '#seekto 0x0A00; ul16 zone_starts[128];' mem = bitwise.parse(tmp_format, self._mmap) zone_format = """struct zoneinfo { @@ -737,7 +734,6 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): dest_zoneinfo.set_raw(source_zoneinfo.get_raw(asbytes=False)) dest_zoneinfo.count = count - source_i = 0 for dest_i in range(0, min(count, old_count)): dest[dest_i].set_raw(source[dest_i].get_raw(asbytes=False)) else: @@ -998,20 +994,8 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): 5: 0x2, 2.5: 0x1, } - try: - tx_step = chirp_common.required_step(int(_mem.tx_freq) * 10, - allowed=step_lookup.keys()) - except errors.InvalidDataError: - tx_step = 5 - try: - rx_step = chirp_common.required_step(int(_mem.rx_freq) * 10, - allowed=step_lookup.keys()) - except errors.InvalidDataError: - rx_step = 5 - - # Default to 5kHz if we don't know any better - _mem.rx_step = step_lookup.get(rx_step, 0x2) - _mem.tx_step = step_lookup.get(tx_step, 0x2) + _mem.rx_step = tk280.choose_step(step_lookup, int(_mem.rx_freq) * 10) + _mem.tx_step = tk280.choose_step(step_lookup, int(_mem.tx_freq) * 10) skipbyte = self._memobj.skipflags[(mem.number - 1) // 8] if mem.skip == 'S': @@ -1464,8 +1448,6 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): return group def get_settings(self): - settings = self._memobj.settings - zones = self._get_zones() common1 = self._get_common1() common2 = self._get_common2() diff --git a/chirp/drivers/uv5r.py b/chirp/drivers/uv5r.py index 32e3949..6e67dcc 100644 --- a/chirp/drivers/uv5r.py +++ b/chirp/drivers/uv5r.py @@ -1902,6 +1902,46 @@ class BaofengUV5RGeneric(BaofengUV5R): @directory.register +class BaofengUV5GPro(BaofengUV5R): + MODEL = "UV-5G Pro" + _airband = (108000000, 136000000) + + def get_features(self): + rf = super().get_features() + rf.valid_bands = [(108000000, 174000000), + (220000000, 260000000), + (350000000, 390000000), + (400000000, 520000000)] + rf.valid_modes.append('AM') + return rf + + @classmethod + def match_model(cls, filename, filedata): + return False + + def get_memory(self, number): + mem = super().get_memory(number) + if chirp_common.in_range(mem.freq, [self._airband]): + # UV-5G Pro is AM in 108-136 MHz range + mem.mode = 'AM' + elif mem.mode == 'AM': + mem.mode = 'FM' + return mem + + def validate_memory(self, mem): + msgs = super().validate_memory(mem) + if (chirp_common.in_range(mem.freq, [self._airband]) and + not mem.mode == 'AM'): + msgs.append(chirp_common.ValidationWarning( + _('Frequency in this range requires AM mode'))) + if (not chirp_common.in_range(mem.freq, [self._airband]) and + mem.mode == 'AM'): + msgs.append(chirp_common.ValidationWarning( + _('Frequency in this range must not be AM mode'))) + return msgs + + +@directory.register class BaofengF11Radio(BaofengUV5R): VENDOR = "Baofeng" MODEL = "F-11" diff --git a/chirp/drivers/uvk5.py b/chirp/drivers/uvk5.py index a22f8dd..6706b90 100644 --- a/chirp/drivers/uvk5.py +++ b/chirp/drivers/uvk5.py @@ -295,9 +295,9 @@ FMMAX = 108.0 # bands supported by the UV-K5 BANDS = { 0: [50.0, 76.0], - 1: [108.0, 135.9999], - 2: [136.0, 199.9990], - 3: [200.0, 299.9999], + 1: [108.0, 136.9999], + 2: [137.0, 173.9999], + 3: [174.0, 349.9999], 4: [350.0, 399.9999], 5: [400.0, 469.9999], 6: [470.0, 600.0] @@ -306,9 +306,9 @@ BANDS = { # for radios with modified firmware: BANDS_NOLIMITS = { 0: [18.0, 76.0], - 1: [108.0, 135.9999], - 2: [136.0, 199.9990], - 3: [200.0, 299.9999], + 1: [108.0, 136.9999], + 2: [137.0, 173.9999], + 3: [174.0, 349.9999], 4: [350.0, 399.9999], 5: [400.0, 469.9999], 6: [470.0, 1300.0] @@ -383,8 +383,8 @@ def calculate_crc16_xmodem(data: bytes): def _send_command(serport, data: bytes): """Send a command to UV-K5 radio""" - LOG.debug("Sending command (unobfuscated) len=0x%4.4x:\n%s", - len(data), util.hexprint(data)) + serport.log("Sending command (unobfuscated) len=0x%4.4x:\n%s" % ( + len(data), util.hexprint(data))) crc = calculate_crc16_xmodem(data) data2 = data + struct.pack("<H", crc) @@ -392,8 +392,6 @@ def _send_command(serport, data: bytes): command = struct.pack(">HBB", 0xabcd, len(data), 0) + \ xorarr(data2) + \ struct.pack(">H", 0xdcba) - if DEBUG_SHOW_OBFUSCATED_COMMANDS: - LOG.debug("Sending command (obfuscated):\n%s", util.hexprint(command)) try: result = serport.write(command) except Exception as e: @@ -434,15 +432,8 @@ def _receive_reply(serport): util.hexprint(footer), len(footer)) raise errors.RadioError("Bad response footer") - if DEBUG_SHOW_OBFUSCATED_COMMANDS: - LOG.debug("Received reply (obfuscated) len=0x%4.4x:\n%s", - len(cmd), util.hexprint(cmd)) - cmd2 = xorarr(cmd) - LOG.debug("Received reply (unobfuscated) len=0x%4.4x:\n%s", - len(cmd2), util.hexprint(cmd2)) - return cmd2 @@ -480,38 +471,27 @@ def _sayhello(serport): def _readmem(serport, offset, length): - LOG.debug("Sending readmem offset=0x%4.4x len=0x%4.4x", offset, length) + serport.log("Sending readmem offset=0x%4.4x len=0x%4.4x" % ( + offset, length)) readmem = b"\x1b\x05\x08\x00" + \ struct.pack("<HBB", offset, length, 0) + \ b"\x6a\x39\x57\x64" _send_command(serport, readmem) rep = _receive_reply(serport) - if DEBUG_SHOW_MEMORY_ACTIONS: - LOG.debug("readmem Received data len=0x%4.4x:\n%s", - len(rep), util.hexprint(rep)) return rep[8:] def _writemem(serport, data, offset): - LOG.debug("Sending writemem offset=0x%4.4x len=0x%4.4x", - offset, len(data)) - - if DEBUG_SHOW_MEMORY_ACTIONS: - LOG.debug("writemem sent data offset=0x%4.4x len=0x%4.4x:\n%s", - offset, len(data), util.hexprint(data)) - dlen = len(data) writemem = b"\x1d\x05" + \ struct.pack("<BBHBB", dlen+8, 0, offset, dlen, 1) + \ b"\x6a\x39\x57\x64"+data + serport.log('Writemem at offset %04x len %04x' % (offset, dlen)) _send_command(serport, writemem) rep = _receive_reply(serport) - LOG.debug("writemem Received data: %s len=%i", - util.hexprint(rep), len(rep)) - if (rep[0] == 0x1e and rep[4] == (offset & 0xff) and rep[5] == (offset >> 8) & 0xff): @@ -737,7 +717,8 @@ class UVK5RadioBase(chirp_common.CloneModeRadio): # Return a raw representation of the memory object, which # is very helpful for development def get_raw_memory(self, number): - return repr(self._memobj.channel[number-1]) + return '\n'.join([repr(self._memobj.channel[number-1]), + repr(self._memobj.channel_attributes[number-1])]) def _find_band(self, hz): return _find_band(self._expanded_limits, hz) diff --git a/chirp/drivers/yaesu_clone.py b/chirp/drivers/yaesu_clone.py index c434ed0..83d8c8b 100644 --- a/chirp/drivers/yaesu_clone.py +++ b/chirp/drivers/yaesu_clone.py @@ -29,15 +29,12 @@ def _safe_read(pipe, count): first = True for _i in range(0, 60): buf += pipe.read(count - len(buf)) - # LOG.debug("safe_read: %i/%i\n" % (len(buf), count)) if buf: if first and buf[0] == CMD_ACK: - # LOG.debug("Chewed an ack") buf = buf[1:] # Chew an echo'd ack if using a 2-pin cable first = False if len(buf) == count: break - LOG.debug(util.hexprint(buf)) return buf @@ -55,7 +52,6 @@ def _chunk_read(pipe, count, status_fn): data += chunk if data[0] == CMD_ACK: data = data[1:] # Chew an echo'd ack if using a 2-pin cable - # LOG.debug("Chewed an ack") if time.time() - timer > 2: # It's been two seconds since we last saw data from the radio, # so it's time to give up. @@ -118,7 +114,6 @@ def _chunk_write(pipe, data, status_fn, block): chunk = data[i:i+block] pipe.write(chunk) count += len(chunk) - LOG.debug("@_chunk_write, count: %i, blocksize: %i" % (count, block)) time.sleep(delay) status = chirp_common.Status() diff --git a/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo b/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo Binary files differindex c0511d9..36570a8 100644 --- a/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/es/LC_MESSAGES/CHIRP.mo b/chirp/locale/es/LC_MESSAGES/CHIRP.mo Binary files differindex be359ff..85c8a4e 100644 --- a/chirp/locale/es/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/es/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/fr/LC_MESSAGES/CHIRP.mo b/chirp/locale/fr/LC_MESSAGES/CHIRP.mo Binary files differindex 2887273..61f4a0a 100644 --- a/chirp/locale/fr/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/fr/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/it/LC_MESSAGES/CHIRP.mo b/chirp/locale/it/LC_MESSAGES/CHIRP.mo Binary files differindex 58f1bb1..20f6fa2 100644 --- a/chirp/locale/it/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/it/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/pl/LC_MESSAGES/CHIRP.mo b/chirp/locale/pl/LC_MESSAGES/CHIRP.mo Binary files differindex 875d63f..1f23eca 100644 --- a/chirp/locale/pl/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/pl/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/ru/LC_MESSAGES/CHIRP.mo b/chirp/locale/ru/LC_MESSAGES/CHIRP.mo Binary files differindex 68a56c0..d978c35 100644 --- a/chirp/locale/ru/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/ru/LC_MESSAGES/CHIRP.mo diff --git a/chirp/settings.py b/chirp/settings.py index f400333..0b25dfb 100644 --- a/chirp/settings.py +++ b/chirp/settings.py @@ -310,12 +310,13 @@ class RadioSettingValueString(RadioSettingValue): def set_value(self, value): if len(value) < self._minlength or len(value) > self._maxlength: - raise InvalidValueError("Value must be between %i and %i chars" % - (self._minlength, self._maxlength)) + raise InvalidValueError( + "Value %r must be between %i and %i chars" % ( + value, self._minlength, self._maxlength)) for char in value: if char not in self._charset: - raise InvalidValueError("Value contains invalid " + - "character `%s'" % char) + raise InvalidValueError(("Value %r contains invalid " + "character `%s'") % (value, char)) if self._autopad: value = value.ljust(self._maxlength) RadioSettingValue.set_value(self, value) diff --git a/chirp/util.py b/chirp/util.py index 3ea5505..f07fa13 100644 --- a/chirp/util.py +++ b/chirp/util.py @@ -37,12 +37,11 @@ def int_to_byte(i): return i -def hexprint(data, addrfmt=None): +def hexprint(data, addrfmt=None, block_size=8): """Return a hexdump-like encoding of @data""" if addrfmt is None: addrfmt = '%(addr)03i' - block_size = 8 out = "" blocks = len(data) // block_size diff --git a/chirp/wxui/bugreport.py b/chirp/wxui/bugreport.py index 16e9fa3..50b449e 100644 --- a/chirp/wxui/bugreport.py +++ b/chirp/wxui/bugreport.py @@ -14,6 +14,7 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. import datetime +import gzip import logging import os import platform @@ -32,6 +33,7 @@ from chirp import logger from chirp import platform as chirp_platform from chirp.wxui import common from chirp.wxui import config +from chirp.wxui import serialtrace _ = wx.GetTranslation CONF = config.get() @@ -126,6 +128,15 @@ def prepare_report(chirpmain): manifest['files']['debug_log.txt'] = f.read() tmpf = tempfile.mktemp('.config', 'chirp') + # Grab any trace files + for tracefile in serialtrace.TRACEFILES: + if os.path.exists(tracefile): + LOG.debug('Capturing serial trace file %s', tracefile) + with open(tracefile, 'rb') as f: + manifest['files'][os.path.basename(tracefile)] = f.read() + else: + LOG.debug('Serial trace file %s does not exist', tracefile) + return manifest @@ -137,6 +148,7 @@ class BugReportContext: self.session = requests.Session() self.session.headers = { 'User-Agent': 'CHIRP/%s' % CHIRP_VERSION, + 'Referer': 'https://chirpmyradio.com/projects/chirp/issues/new', } def get_page(self, name, cls): @@ -622,7 +634,7 @@ class ResultPage(BugReportPage): elif r.status_code != 201: LOG.error('Failed to upload %s: %s %s', fn, r.status_code, r.reason) - raise Exception('Failed to upload file') + raise Exception('Failed to upload file: %s' % r.reason) return r.json()['upload']['token'] raise Exception('Failed to upload %s after multiple attempts', fn) @@ -630,19 +642,36 @@ class ResultPage(BugReportPage): if 'issue' not in manifest: self._create_bug(manifest) + for fn in list(manifest['files'].keys()): + fdata = manifest['files'][fn] + if len(fdata) > 1024 * 1024: + LOG.warning('File %s is larger than 1MB, compressing', fn) + fdata = gzip.compress(fdata) + manifest['files'].pop(fn) + fn += '.gz' + manifest['files'][fn] = fdata + + notes = '[Uploaded from CHIRP %s]\n\n' % CHIRP_VERSION tokens = [] for fn in manifest['files']: - token = self._upload_file(manifest, fn) - if fn.lower().endswith('.img'): - ct = 'application/octet-stream' - else: + try: + token = self._upload_file(manifest, fn) + except Exception as e: + LOG.error('Failed to upload file %s: %s', fn, e) + notes += '[Failed to upload file %s: %s]\n\n' % (fn, e) + continue + ext = os.path.splitext(fn)[1].lower() + if ext in ('.log', '.txt'): ct = 'text/plain' - tokens.append({'token': token, - 'filename': fn, - 'content_type': ct}) + else: + ct = 'application/octet-stream' + token_info = {'token': token, + 'filename': fn, + 'content_type': ct} + tokens.append(token_info) + LOG.debug('File tokens: %s', tokens) - notes = '[Uploaded from CHIRP %s]\n\n' % CHIRP_VERSION if not self.context.is_new: notes += manifest['desc'] r = self.context.session.put( diff --git a/chirp/wxui/clone.py b/chirp/wxui/clone.py index 2e58ed2..21bc7fc 100644 --- a/chirp/wxui/clone.py +++ b/chirp/wxui/clone.py @@ -33,6 +33,7 @@ from chirp import errors from chirp.wxui import config from chirp.wxui import common from chirp.wxui import developer +from chirp.wxui import serialtrace _ = wx.GetTranslation LOG = logging.getLogger(__name__) @@ -163,8 +164,9 @@ def open_serial(port, rclass): pipe.open() pipe.baudrate = rclass.BAUD_RATE else: - pipe = serial.Serial(baudrate=rclass.BAUD_RATE, - rtscts=rclass.HARDWARE_FLOW, timeout=0.25) + pipe = serialtrace.SerialTrace( + baudrate=rclass.BAUD_RATE, + rtscts=rclass.HARDWARE_FLOW, timeout=0.25) pipe.rts = rclass.WANTS_RTS pipe.dtr = rclass.WANTS_DTR pipe.port = port @@ -542,10 +544,19 @@ class ChirpCloneDialog(wx.Dialog): self._model.Disable() self._recent.Disable() + def enable_model_select(self): + self._vendor.Enable() + self._model.Enable() + self._recent.Enable() + def disable_running(self): self._port.Disable() self.FindWindowById(wx.ID_OK).Disable() + def enable_running(self): + self._port.Enable() + self.FindWindowById(wx.ID_OK).Enable() + def _persist_choices(self): raise NotImplementedError() @@ -682,12 +693,14 @@ class ChirpCloneDialog(wx.Dialog): common.error_proof.show_error( error, parent=self, title=_('Error communicating with radio')) + if isinstance(self, ChirpDownloadDialog): + self.enable_model_select() + self.enable_running() wx.CallAfter(safe_fail) def cancel_action(self): if isinstance(self, ChirpDownloadDialog): - self._vendor.Enable() - self._model.Enable() + self.enable_model_select() self._port.Enable() s = chirp_common.Status() s.cur = 0 diff --git a/chirp/wxui/developer.py b/chirp/wxui/developer.py index 31c4889..3d616f3 100644 --- a/chirp/wxui/developer.py +++ b/chirp/wxui/developer.py @@ -590,21 +590,35 @@ class FakeErrorOpenSerial(FakeSerial): raise Exception('Failed open') +class IsssueModuleLoadError(Exception): + pass + + class IssueModuleLoader: def __init__(self, parent): self._parent = parent report.ensure_session() self.session = report.SESSION - def get_attachments_from_issue(self, issue): + def get_attachments_from_issue(self, issue_num): r = self.session.get( - 'https://chirpmyradio.com/issues/%i.json' % issue, + 'https://chirpmyradio.com/issues/%i.json' % issue_num, params={'include': 'attachments'}) LOG.debug('Fetched attachments for issue %i (status %s)' % ( - issue, r.status_code)) + issue_num, r.status_code)) r.raise_for_status() - data = r.json()['issue']['attachments'] - return [a for a in data if + issue = r.json()['issue'] + allowed_states = ['New', 'In Progress', 'Resolved'] + valid = (issue['status']['name'] in allowed_states + and not issue['status']['is_closed']) + if not valid: + LOG.warning('Issue %i is in state %s', issue_num, issue['status']) + raise IsssueModuleLoadError( + _('Issue %i is not in a valid state to load ' + 'modules. It is highly recommended that you not ' + 'attempt to manually load modules from this ' + 'issue as it is likely to cause problems.') % issue_num) + return [a for a in issue['attachments'] if a['filename'].endswith('.py') and a.get('content_type', '').startswith('text/') and a['filesize'] < (256 * 1024)] @@ -663,6 +677,10 @@ class IssueModuleLoader: try: attachments = self.get_attachments_from_issue(issue) + except IsssueModuleLoadError as e: + LOG.exception('Failed to load module from issue %i: %s' % ( + issue, e)) + raise except Exception as e: LOG.exception('Failed to load attachments from %i: %s' % ( issue, e)) diff --git a/chirp/wxui/main.py b/chirp/wxui/main.py index ccc846f..b7380d7 100644 --- a/chirp/wxui/main.py +++ b/chirp/wxui/main.py @@ -51,6 +51,7 @@ from chirp.wxui import query_sources from chirp.wxui import radioinfo from chirp.wxui import radiothread from chirp.wxui import report +from chirp.wxui import serialtrace from chirp.wxui import settingsedit from chirp import CHIRP_VERSION @@ -1016,6 +1017,12 @@ class ChirpMain(wx.Frame): help_menu.Append(self.bug_report_item) self.bug_report_item.Enable(False) + if developer.developer_mode(): + trace_item = wx.MenuItem(help_menu, wx.NewId(), + _('Open last serial trace')) + self.Bind(wx.EVT_MENU, self._menu_last_trace, trace_item) + help_menu.Append(trace_item) + menu_bar = wx.MenuBar() menu_bar.Append(file_menu, wx.GetStockLabel(wx.ID_FILE)) menu_bar.Append(edit_menu, wx.GetStockLabel(wx.ID_EDIT)) @@ -1322,6 +1329,9 @@ class ChirpMain(wx.Frame): 'state') config._CONFIG.save() + # Clean up any trace files we left + serialtrace.purge_trace_files(0) + ALL_MAIN_WINDOWS.remove(self) self.Destroy() @@ -1718,14 +1728,15 @@ class ChirpMain(wx.Frame): else: d = clone.ChirpUploadDialog(radio, self) - d.Centre() - r = d.ShowModal() - if r != wx.ID_OK: - LOG.info('Removing un-uploaded backup %s', fn) - try: - os.remove(fn) - except Exception: - pass + with d: + d.Centre() + r = d.ShowModal() + if r != wx.ID_OK: + LOG.info('Removing un-uploaded backup %s', fn) + try: + os.remove(fn) + except Exception: + pass @common.error_proof() def _menu_reload_driver(self, event, andfile=False): @@ -1798,14 +1809,27 @@ class ChirpMain(wx.Frame): def _menu_interact_driver(self, event): LOG.warning('Going to interact with radio at the console') + radio = self.current_editorset.current_editor.radio - import code locals = {'main': self, 'radio': radio} + if self.current_editorset.radio != radio: locals['parent_radio'] = self.current_editorset.radio - code.interact(banner='Locals are: %s' % (', '.join(locals.keys())), - local=locals) + + banner = 'Locals are: %s' % (', '.join(locals.keys())) + + # Use ipython if it's installed which gives tab complete and some other + # nice features over the built in REPL. + try: + from IPython.terminal.embed import InteractiveShellEmbed + + shell = InteractiveShellEmbed() + shell(header=banner, local_ns=locals) + + except ModuleNotFoundError: + import code + code.interact(banner=banner, local=locals) @common.error_proof() def load_module(self, filename): @@ -1853,7 +1877,7 @@ class ChirpMain(wx.Frame): 'another source is akin to giving them direct ' 'access to your computer and everything on ' 'it! Proceed despite this risk?'), - 'Warning', + _('Warning'), wx.ICON_WARNING | wx.YES_NO) if r.ShowModal() != wx.ID_YES: return @@ -1889,11 +1913,10 @@ class ChirpMain(wx.Frame): border=10, flag=wx.ALIGN_CENTER) - license_link = wx.adv.HyperlinkCtrl( - d, label=_('Click here for full license text'), - url=('https://www.chirpmyradio.com/projects/chirp/repository/' - 'github/revisions/master/entry/COPYING')) - vbox.Add(license_link, border=10, flag=wx.ALL | wx.ALIGN_CENTER) + documentation_link = wx.adv.HyperlinkCtrl( + d, label=_('Click here for online documentation'), + url=('https://chirpmyradio.com/projects/chirp/wiki/Documentation')) + vbox.Add(documentation_link, border=10, flag=wx.ALL | wx.ALIGN_CENTER) licheader = """ This program is free software: you can redistribute it and/or modify @@ -1911,6 +1934,12 @@ GNU General Public License for more details.""" style=wx.TE_WORDWRAP | wx.TE_MULTILINE | wx.TE_READONLY) vbox.Add(lic, border=10, flag=wx.ALL | wx.EXPAND, proportion=1) + license_link = wx.adv.HyperlinkCtrl( + d, label=_('Click here for full license text'), + url=('https://www.chirpmyradio.com/projects/chirp/repository/' + 'github/revisions/master/entry/COPYING')) + vbox.Add(license_link, border=10, flag=wx.ALL | wx.ALIGN_CENTER) + license_approved = CONF.get_bool('agreed_to_license', 'state') if not license_approved: @@ -2011,6 +2040,14 @@ GNU General Public License for more details.""" _('Success'), wx.ICON_INFORMATION) + def _menu_last_trace(self, event): + try: + fn = serialtrace.TRACEFILES[-1] + wx.LaunchDefaultApplication(fn) + except IndexError: + common.error_proof.show_error( + _('No traces stored'), parent=self) + def _menu_auto_edits(self, event): CONF.set_bool('auto_edits', event.IsChecked(), 'state') LOG.debug('Set auto_edits=%s' % event.IsChecked()) diff --git a/chirp/wxui/memedit.py b/chirp/wxui/memedit.py index 1e6d987..bb6aabd 100644 --- a/chirp/wxui/memedit.py +++ b/chirp/wxui/memedit.py @@ -46,12 +46,13 @@ TX_WORKFLOW_ID = wx.NewId() class ChirpGridTable(wx.grid.GridStringTable): - def __init__(self, features, num_cols): + def __init__(self, features, col_defs): self._features = features + self._col_defs = col_defs num_rows = (self._features.memory_bounds[1] - self._features.memory_bounds[0] + len(self._features.valid_special_chans) + 1) - super().__init__(num_rows, num_cols) + super().__init__(num_rows, len(col_defs)) self._rowmap = {x: x for x in range(0, self.GetRowsCount())} self._rowmap_rev = {v: k for k, v in self._rowmap.items()} @@ -74,6 +75,10 @@ class ChirpGridTable(wx.grid.GridStringTable): # order. That convoluted scheme makes us always sort empty values at # the bottom instead of the top of the list, which is what a human # will want. + + def sortable_value(val): + return self._col_defs[col].get_sortable_value(val) + if col < 0: self._rowmap = {x: x for x in range(0, self.GetRowsCount())} else: @@ -81,7 +86,8 @@ class ChirpGridTable(wx.grid.GridStringTable): (asc != bool( super(ChirpGridTable, self).GetValue( realrow, col).strip()), - super(ChirpGridTable, self).GetValue(realrow, col), + sortable_value( + super(ChirpGridTable, self).GetValue(realrow, col)), realrow) for realrow in range(0, self.GetRowsCount())), reverse=not asc) @@ -163,6 +169,12 @@ class ChirpMemoryColumn(object): self._features = radio.get_features() self._doc = None + @staticmethod + def get_sortable_value(value): + """Convert a rendered value into the type/format we should use for + sorting""" + return value + @property def name(self): return self._name @@ -293,6 +305,13 @@ class ChirpFrequencyColumn(ChirpMemoryColumn): super().__init__(*a, **k) self._wants_split = set() + @staticmethod + def get_sortable_value(value): + try: + return float(value) + except ValueError: + return 0 + def value(self, memory): if self._name == 'txfreq': if memory.duplex == 'split': @@ -394,6 +413,13 @@ class ChirpVariablePowerColumn(ChirpMemoryColumn): def _digest_value(self, memory, value): return chirp_common.parse_power(value) + @staticmethod + def get_sortable_value(value): + try: + return int(chirp_common.parse_power(value)) + except ValueError: + return 0 + class ChirpChoiceEditor(wx.grid.GridCellChoiceEditor): """A locking GridCellChoiceEditor. @@ -472,6 +498,13 @@ class ChirpToneColumn(ChirpChoiceColumn): super(ChirpToneColumn, self).__init__(name, radio, tones) + @staticmethod + def get_sortable_value(value): + try: + return float(value) + except ValueError: + return 0 + @property def label(self): if self._name == 'rtone': @@ -921,7 +954,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self.bandplan = bandplan.BandPlans(CONF) self._grid = ChirpMemoryGrid(self) - self._table = ChirpGridTable(self._features, len(self._col_defs)) + self._table = ChirpGridTable(self._features, self._col_defs) # AssignTable added in wxPython 4.1, so use the older interface for # earlier version support (i.e. Ubuntu Jammy) self._grid.SetTable(self._table, takeOwnership=True, @@ -1458,6 +1491,11 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self._grid.GetRowLabelValue(row))) return + if not isinstance(memory.number, int): + LOG.error('Memory for row %i (lookup number %r) ' + 'has non-integer number field: %r', + row, number, memory.number) + if row in self._memory_errors: del self._memory_errors[row] diff --git a/chirp/wxui/serialtrace.py b/chirp/wxui/serialtrace.py new file mode 100644 index 0000000..9939195 --- /dev/null +++ b/chirp/wxui/serialtrace.py @@ -0,0 +1,129 @@ +# Copyright 2025 Dan Smith <chirp@f.danplanet.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import datetime +import logging +import os +import serial +import tempfile +import time + +from chirp import util +from chirp.wxui import config + +CONF = config.get() +LOG = logging.getLogger(__name__) +TRACEFILES = [] + + +def get_trace_entry(direction, start_ts, data): + loglines = util.hexprint(data, block_size=16).split('\n') + ts = time.monotonic() - start_ts + loglines = ['%7.3f %s %s%s' % (ts, direction, line, os.linesep) + for line in loglines if line.strip()] + if not loglines and direction == 'R' and not data: + # No data read means timeout, so denote that for clarity + loglines = ['%7.3f %s # timeout%s' % (ts, direction, os.linesep)] + return loglines + + +def purge_trace_files(keep=10): + global TRACEFILES + if keep == 0: + purge = TRACEFILES + TRACEFILES = [] + else: + purge = TRACEFILES[:-keep] + TRACEFILES = TRACEFILES[-10:] + for fn in purge: + try: + os.remove(fn) + LOG.debug('Removed old trace file %s', fn) + except FileNotFoundError: + pass + except Exception as e: + LOG.error('Failed to remove old trace file %s: %s', fn, e) + + +class SerialTrace(serial.Serial): + def __init__(self, *a, **k): + self.__tracef = None + super().__init__(*a, **k) + + def open(self): + super().open() + try: + self.__trace_start = time.monotonic() + self.__tracef = tempfile.NamedTemporaryFile(mode='w', + delete=False, + prefix='chirp-trace-', + suffix='.txt') + TRACEFILES.append(self.__tracef.name) + purge_trace_files(10) + now = datetime.datetime.now() + self.log('Serial trace %s started at %s' % (self, now.isoformat())) + LOG.info('Serial trace file created: %s' % self.__tracef.name) + except Exception as e: + LOG.error('Failed to create serial trace file: %s' % e) + self.__tracef = None + + def write(self, data): + super().write(data) + if self.__tracef: + try: + self.__tracef.writelines(get_trace_entry('W', + self.__trace_start, + data)) + except Exception as e: + LOG.error('Failed to write to serial trace file: %s' % e) + self.__tracef = None + + def read(self, size=1): + data = super().read(size) + if self.__tracef: + try: + self.__tracef.writelines(get_trace_entry('R', + self.__trace_start, + data)) + except Exception as e: + LOG.error('Failed to write to serial trace file: %s' % e) + self.__tracef = None + return data + + def close(self): + super().close() + if self.__tracef: + try: + now = datetime.datetime.now() + self.log('Trace ended at %s' % now.isoformat()) + self.__tracef.close() + LOG.info('Serial trace file closed: %s' % self.__tracef.name) + except Exception as e: + LOG.error('Failed to close serial trace file: %s' % e) + finally: + self.__tracef = None + + def log(self, message): + """Log a message to the trace file. + + Use this to annotate important events in the trace file, such as + reading a new block, etc. + """ + if self.__tracef: + try: + self.__tracef.write('# %s\n' % message) + except Exception as e: + LOG.error('Failed to write log message to trace file: %s' % e) + self.__tracef = None @@ -1,11 +1,11 @@ -from distutils.core import setup +from setuptools import setup from setuptools import find_packages setup(name='chirp', description='A cross-platform cross-radio programming tool', packages=find_packages(include=["chirp*"]), include_package_data=True, - version='20250502', + version='20250912', url='https://chirp.danplanet.com', python_requires=">=3.10,<4", install_requires=[ diff --git a/tests/__init__.py b/tests/__init__.py index b2563b8..55640b0 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -76,11 +76,12 @@ def _load_tests(loader, tests, pattern, suite=None): images = os.environ['CHIRP_TESTIMG'].split() else: images = glob.glob("tests/images/*.img") + images = [os.path.basename(img) for img in images] tests = [os.path.splitext(os.path.basename(img))[0] for img in images] base = os.path.dirname(os.path.abspath(__file__)) base = os.path.join(base, 'images') - images = glob.glob(os.path.join(base, "*")) + images = [os.path.join(base, img) for img in images] tests = {img: os.path.splitext(os.path.basename(img))[0] for img in images} if pattern == 'test*.py': diff --git a/tests/__pycache__/__init__.cpython-310.pyc b/tests/__pycache__/__init__.cpython-310.pyc Binary files differindex e5edb17..f98eee7 100644 --- a/tests/__pycache__/__init__.cpython-310.pyc +++ b/tests/__pycache__/__init__.cpython-310.pyc diff --git a/tests/__pycache__/test_clone.cpython-310-pytest-7.1.3.pyc b/tests/__pycache__/test_clone.cpython-310-pytest-7.1.3.pyc Binary files differindex e682551..4f44f20 100644 --- a/tests/__pycache__/test_clone.cpython-310-pytest-7.1.3.pyc +++ b/tests/__pycache__/test_clone.cpython-310-pytest-7.1.3.pyc diff --git a/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc b/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc Binary files differindex aaa4514..ff627da 100644 --- a/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc +++ b/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc diff --git a/tests/images/Baofeng_UV-5G_Pro.img b/tests/images/Baofeng_UV-5G_Pro.img Binary files differnew file mode 100644 index 0000000..324157f --- /dev/null +++ b/tests/images/Baofeng_UV-5G_Pro.img diff --git a/tests/images/Baofeng_UV-5R_Mini.img b/tests/images/Baofeng_UV-5R_Mini.img Binary files differnew file mode 100644 index 0000000..4f9f268 --- /dev/null +++ b/tests/images/Baofeng_UV-5R_Mini.img diff --git a/tests/images/Kenwood_TK-278.img b/tests/images/Kenwood_TK-278.img Binary files differnew file mode 100644 index 0000000..c7abbaf --- /dev/null +++ b/tests/images/Kenwood_TK-278.img diff --git a/tests/images/Radioddity_GM-30.img b/tests/images/Radioddity_GM-30.img Binary files differnew file mode 100644 index 0000000..98e810c --- /dev/null +++ b/tests/images/Radioddity_GM-30.img diff --git a/tests/images/Retevis_H777_V4.img b/tests/images/Retevis_H777_V4.img Binary files differnew file mode 100644 index 0000000..38f479a --- /dev/null +++ b/tests/images/Retevis_H777_V4.img diff --git a/tests/images/Retevis_RA25.img b/tests/images/Retevis_RA25.img Binary files differnew file mode 100644 index 0000000..723ca6e --- /dev/null +++ b/tests/images/Retevis_RA25.img diff --git a/tests/images/Retevis_RA86.img b/tests/images/Retevis_RA86.img Binary files differnew file mode 100644 index 0000000..579046a --- /dev/null +++ b/tests/images/Retevis_RA86.img diff --git a/tests/images/Retevis_RT86S.img b/tests/images/Retevis_RT86S.img Binary files differnew file mode 100644 index 0000000..b6a26dc --- /dev/null +++ b/tests/images/Retevis_RT86S.img diff --git a/tests/images/TIDRADIO_TD-H3.img b/tests/images/TIDRADIO_TD-H3.img Binary files differindex e891793..bfb305d 100644 --- a/tests/images/TIDRADIO_TD-H3.img +++ b/tests/images/TIDRADIO_TD-H3.img diff --git a/tests/py3-untested-drivers.txt b/tests/py3-untested-drivers.txt index 6d8ff38..7a8ae4b 100644 --- a/tests/py3-untested-drivers.txt +++ b/tests/py3-untested-drivers.txt @@ -17,14 +17,6 @@ KSUN_M6 KYD_IP-620 KYD_NC-630A Kenwood_ITM -Kenwood_TK-260 -Kenwood_TK-270 -Kenwood_TK-272 -Kenwood_TK-278 -Kenwood_TK-360 -Kenwood_TK-370 -Kenwood_TK-372 -Kenwood_TK-378 Kenwood_TM-D710_CloneMode Kenwood_TS-480_CloneMode Kenwood_TS-480_LiveMode diff --git a/tests/test_clone.py b/tests/test_clone.py index 1723942..cb41bfb 100644 --- a/tests/test_clone.py +++ b/tests/test_clone.py @@ -5,6 +5,7 @@ from unittest import mock from chirp import chirp_common from chirp import errors +from chirp.wxui import serialtrace from tests import base LOG = logging.getLogger(__name__) @@ -14,7 +15,7 @@ class SerialException(Exception): pass -class SerialNone: +class SerialNone(serialtrace.SerialTrace): def flush(self): pass diff --git a/tests/test_edges.py b/tests/test_edges.py index 92498ff..d41970a 100644 --- a/tests/test_edges.py +++ b/tests/test_edges.py @@ -142,6 +142,11 @@ class TestCaseEdges(base.DriverTest): # radios have empty in the immutable set. if m1.empty: m1.empty = False + + self.assertIsInstance(m1.number, int, + ('Special memory %s number %r is not an ' + 'integer') % (name, m1.number)) + try: del m1.extra except AttributeError: @@ -174,6 +179,9 @@ class TestCaseEdges(base.DriverTest): self.assertEqual('', m.extd_number, 'Non-special memory %i should not have ' 'extd_number set to %r' % (i, m.extd_number)) + self.assertIsInstance(m.number, int, + 'Memory number %r is not an integer' % + m.number) def test_get_memory_name_trailing_whitespace(self): if self.radio.MODEL == 'KG-UV8E': diff --git a/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc Binary files differindex b65e7cd..bdb9f73 100644 --- a/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc +++ b/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc diff --git a/tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc Binary files differnew file mode 100644 index 0000000..16f0c98 --- /dev/null +++ b/tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc diff --git a/tests/unit/test_bitwise.py b/tests/unit/test_bitwise.py index dc38cb6..c50c3fc 100644 --- a/tests/unit/test_bitwise.py +++ b/tests/unit/test_bitwise.py @@ -248,6 +248,22 @@ class TestBitwiseBCDTypes(BaseTest): def test_lbcd_array(self): self._test_def("lbcd foo[2];", "foo", b"\x12\x34", 3412) + def test_bbcd_array_leading_bits(self): + data = memmap.MemoryMapBytes(bytes(b"\xc7\x54")) + obj = bitwise.parse("bbcd foo[2];", data) + # This is what we interpret a leading 0xC000 as + self.assertEqual(int(obj.foo), 754 + 12000) + + # Ignore the top nibble and we expect just the bottom three + obj.foo[0].ignore_bits(0xF0) + self.assertEqual(int(obj.foo), 754) + + # If wet try to set something in the ignored nibble it should be + # ignored but preserved + obj.foo = 1754 + self.assertEqual(int(obj.foo), 754) + self.assertEqual(data[0][0], 0xC7) + class TestBitwiseCharTypes(BaseTest): def test_char(self): diff --git a/tests/unit/test_serialtrace.py b/tests/unit/test_serialtrace.py new file mode 100644 index 0000000..22e8403 --- /dev/null +++ b/tests/unit/test_serialtrace.py @@ -0,0 +1,79 @@ +import unittest +from unittest import mock + +from chirp.wxui import serialtrace + + +class TestSerialTrace(unittest.TestCase): + @mock.patch('serial.Serial.open') + def test_open(self, mock_open): + trace = serialtrace.SerialTrace() + self.assertIsNone(trace._SerialTrace__tracef) + trace.open() + self.assertIsNotNone(trace._SerialTrace__tracef) + self.assertTrue(trace._SerialTrace__tracef.name.endswith('.txt')) + mock_open.assert_called_once() + + @mock.patch('os.remove') + def test_purge_trace_files(self, mock_remove): + from chirp.wxui import serialtrace + + for i in range(15): + serialtrace.TRACEFILES.append('test_trace_%i.txt' % i) + files = serialtrace.TRACEFILES[:] + + # Purge to 10 files keeps the last 10 + serialtrace.purge_trace_files(10) + self.assertEqual(len(serialtrace.TRACEFILES), 10) + self.assertEqual(['test_trace_%i.txt' % (i + 5) for i in range(10)], + serialtrace.TRACEFILES) + + # Purge to 20 does not change anything since only 10 stored + serialtrace.purge_trace_files(20) + self.assertEqual(10, len(serialtrace.TRACEFILES)) + + # Purge to zero removes all files + serialtrace.purge_trace_files(0) + self.assertEqual(0, len(serialtrace.TRACEFILES)) + + # Make sure we ended up removing all the files + mock_remove.assert_has_calls([mock.call(fn) for fn in files], + any_order=True) + + @mock.patch('serial.Serial.open') + @mock.patch('serial.Serial.write') + @mock.patch('serial.Serial.read') + def test_log_write(self, mock_read, mock_write, mock_open): + mock_read.side_effect = [b'123', b''] + trace = serialtrace.SerialTrace() + trace.open() + fn = serialtrace.TRACEFILES[-1] + trace.write(b'foo') + trace.read(3) + trace.read(5) + trace.close() + with open(fn, 'r') as f: + content = f.read() + self.assertIn('# Serial trace', content) + self.assertIn('foo...', content) + self.assertIn('R # timeout', content) + + @mock.patch('tempfile.NamedTemporaryFile') + @mock.patch('serial.Serial.open') + @mock.patch('serial.Serial.write') + @mock.patch('serial.Serial.read') + def test_log_write_fail(self, mock_read, mock_write, mock_open, mock_tf): + mock_tf.return_value.writelines.side_effect = [ + None, Exception("Write error")] + trace = serialtrace.SerialTrace() + trace.open() + # This should generate a write failure + trace.read(3) + + # Make sure we don't interrupt further communication + trace.write(b'foo') + trace.read() + trace.write(b'bar') + + # Before we are closed, the trace file should have been abandoned + self.assertIsNone(trace._SerialTrace__tracef) diff --git a/tools/check_commit.sh b/tools/check_commit.sh index 4a6d68d..9273912 100755 --- a/tools/check_commit.sh +++ b/tools/check_commit.sh @@ -16,7 +16,7 @@ echo -e "${GREEN}Checking from $(git rev-parse --short ${BASE}):${NC}" git log --pretty=oneline --no-merges --abbrev-commit ${BASE}.. echo -git diff ${BASE}.. '*.py' | grep '^+' > added_lines +git diff ${BASE}.. -- '*.py' | grep '^+' > added_lines if grep -E '(from|import).*six' added_lines; then fail No new uses of future @@ -50,11 +50,11 @@ if grep -E "eval\(" added_lines; then fail 'Use of eval() is dangerous and not permitted!' fi -if git diff ${BASE}.. 'tools/cpep8.manifest' | tail -n +5 | grep -q '^+'; then +if git diff ${BASE}.. -- 'tools/cpep8.manifest' | tail -n +5 | grep -q '^+'; then fail 'Do not add new files to cpep8.manifest; no longer needed' fi -if git diff ${BASE}.. 'tools/cpep8.blacklist' | tail -n +5 | grep -q '^+'; then +if git diff ${BASE}.. -- 'tools/cpep8.blacklist' | tail -n +5 | grep -q '^+'; then fail 'Do not add new files to cpep8.blacklist; fix the code' fi @@ -73,12 +73,16 @@ done # fail 'New drivers should not have match_model() implemented as it is not needed' #fi +if grep -E '\Wprint\(' added_lines; then + fail 'Do not use print()' +fi + if git log ${BASE}.. --merges | grep .; then fail Please do not include merge commits in your PR fi make -C chirp/locale clean all >/dev/null 2>&1 -if git diff chirp/locale | grep '^+[^#+]' | grep -v POT-Creation; then +if git diff -- chirp/locale | grep '^+[^#+]' | grep -v POT-Creation; then fail Locale files need updating fi @@ -88,7 +92,14 @@ if echo $added_py | grep -q chirp.drivers && ! echo $added_files | grep -q tests fail All new drivers should include a test image fi -existing_drivers=$(git ls-tree --name-only $BASE chirp/drivers/) +modified_files=$(git diff --name-only --diff-filter=M ${BASE}..) +modified_img=$(echo "$modified_files" | grep 'tests.images') +modified_py=$(echo "$modified_files" | grep '\.py$') +if [ "$modified_img" -a "$modified_py" ]; then + fail "Change modifies an image and (potentially) a driver for a possible upgrade breakage" +fi + +existing_drivers=$(git ls-tree --name-only $BASE -- chirp/drivers/) limit=51 for nf in $added_py; do for of in $existing_drivers; do @@ -104,4 +115,18 @@ done rm -f added_lines license_lines +commits=$(git log --pretty=format:%h ${BASE}..) +for commit in $commits; do + git log -n1 $commit --pretty=format:%B > commit_msg + if [[ `sed -n '1p' commit_msg | wc -c` > 99 ]]; then + fail "First line of commit message of $commit must be <99 chars" + fi + if [[ `wc -l < commit_msg` > 1 ]]; then + if ! sed -n '2p' commit_msg | grep '^$'; then + fail "Second line of commit message of $commit must be blank for proper formatting in the notification emails" + fi + fi + rm -f commit_msg +done + exit $RETCODE diff --git a/tools/check_for_bug.sh b/tools/check_for_bug.sh deleted file mode 100755 index c8b042d..0000000 --- a/tools/check_for_bug.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env sh - -# This checks a given revision to make sure that it has a bug number -# in it, of the form "#123". It should be used in your pretxncommit -# hook - -hg log -r $1 --template {desc} | egrep -q "\#[0-9]+" diff --git a/tools/cpep8.manifest b/tools/cpep8.manifest index 2850863..1b499c3 100644 --- a/tools/cpep8.manifest +++ b/tools/cpep8.manifest @@ -53,8 +53,6 @@ ./chirp/drivers/th_uv88.py ./chirp/drivers/thd72.py ./chirp/drivers/tk760.py -./chirp/drivers/tk760g.py -./chirp/drivers/tk8180.py ./chirp/drivers/tmd710.py ./chirp/drivers/ts480.py ./chirp/drivers/ts590.py diff --git a/tools/fast-driver.py b/tools/fast-driver.py index 669a5e1..3f078e2 100755 --- a/tools/fast-driver.py +++ b/tools/fast-driver.py @@ -1,4 +1,4 @@ -#!/usr/bin/env Python3 +#!/usr/bin/env python3 import glob import os |
