summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--PKG-INFO2
-rw-r--r--chirp.egg-info/PKG-INFO2
-rw-r--r--chirp.egg-info/SOURCES.txt34
-rw-r--r--chirp/__init__.py2
-rw-r--r--chirp/bitwise.py13
-rw-r--r--chirp/chirp_common.py18
-rw-r--r--chirp/cli/main.py2
-rw-r--r--chirp/drivers/__init__.py25
-rw-r--r--chirp/drivers/alinco.py22
-rw-r--r--chirp/drivers/anytone_iii.py8
-rw-r--r--chirp/drivers/ar8200.py9
-rw-r--r--chirp/drivers/baofeng_digital.py4
-rw-r--r--chirp/drivers/baofeng_dm32uv.py2762
-rw-r--r--chirp/drivers/baofeng_uv17Pro.py223
-rw-r--r--chirp/drivers/boblov_x3plus.py15
-rw-r--r--chirp/drivers/btech.py6
-rw-r--r--chirp/drivers/ft1d.py44
-rw-r--r--chirp/drivers/ft2d.py47
-rw-r--r--chirp/drivers/ft4.py62
-rw-r--r--chirp/drivers/ft450d.py360
-rw-r--r--chirp/drivers/ft7100.py16
-rw-r--r--chirp/drivers/ft8000r.py635
-rw-r--r--chirp/drivers/ftm150.py1019
-rw-r--r--chirp/drivers/ftm300d.py1398
-rw-r--r--chirp/drivers/gmrsuv1.py21
-rw-r--r--chirp/drivers/gmrsv2.py4
-rw-r--r--chirp/drivers/h777.py362
-rw-r--r--chirp/drivers/ic208.py5
-rw-r--r--chirp/drivers/ic2100.py5
-rw-r--r--chirp/drivers/ic2200.py5
-rw-r--r--chirp/drivers/ic2300.py5
-rw-r--r--chirp/drivers/ic2720.py5
-rw-r--r--chirp/drivers/ic2730.py5
-rw-r--r--chirp/drivers/ic2820.py5
-rw-r--r--chirp/drivers/icp7.py20
-rw-r--r--chirp/drivers/icq7.py5
-rw-r--r--chirp/drivers/ict70.py5
-rw-r--r--chirp/drivers/ict7h.py5
-rw-r--r--chirp/drivers/ict8.py5
-rw-r--r--chirp/drivers/icx8x.py5
-rw-r--r--chirp/drivers/id31.py5
-rw-r--r--chirp/drivers/id800.py5
-rw-r--r--chirp/drivers/kenwood_itm.py16
-rw-r--r--chirp/drivers/kenwood_live.py526
-rw-r--r--chirp/drivers/kg935g.py6
-rw-r--r--chirp/drivers/kguv8e.py11
-rw-r--r--chirp/drivers/kguv920pa.py14
-rw-r--r--chirp/drivers/kguv9dplus.py13
-rw-r--r--chirp/drivers/leixen.py2
-rw-r--r--chirp/drivers/mursv1.py2
-rw-r--r--chirp/drivers/nx800.py1249
-rw-r--r--chirp/drivers/radioddity_r2.py6
-rw-r--r--chirp/drivers/radtel_rt490.py4
-rw-r--r--chirp/drivers/radtel_rt880g.py6
-rw-r--r--chirp/drivers/radtel_t18.py38
-rw-r--r--chirp/drivers/retevis_ra25.py5
-rw-r--r--chirp/drivers/retevis_rb28.py179
-rw-r--r--chirp/drivers/retevis_rt18.py190
-rw-r--r--chirp/drivers/retevis_rt21.py166
-rw-r--r--chirp/drivers/retevis_rt22.py18
-rw-r--r--chirp/drivers/retevis_rt76p.py6
-rw-r--r--chirp/drivers/retevis_rt97s.py322
-rw-r--r--chirp/drivers/rh5r_v2.py31
-rw-r--r--chirp/drivers/tg_uv2p.py10
-rw-r--r--chirp/drivers/th350.py10
-rw-r--r--chirp/drivers/th9000.py94
-rw-r--r--chirp/drivers/th9800.py6
-rw-r--r--chirp/drivers/thd72.py6
-rw-r--r--chirp/drivers/thd74.py5
-rw-r--r--chirp/drivers/tk280.py3
-rw-r--r--chirp/drivers/tk8160.py112
-rw-r--r--chirp/drivers/tk8180.py391
-rw-r--r--chirp/drivers/ts590.py5
-rw-r--r--chirp/drivers/tyt_uvl15w.py1113
-rw-r--r--chirp/drivers/uv5r.py61
-rw-r--r--chirp/drivers/uv5x3.py21
-rw-r--r--chirp/drivers/uv6r.py21
-rw-r--r--chirp/drivers/uvb5.py5
-rw-r--r--chirp/drivers/uvk5.py184
-rw-r--r--chirp/drivers/uvk5_cn.py763
-rw-r--r--chirp/drivers/vx1.py10
-rw-r--r--chirp/drivers/vx8.py17
-rw-r--r--chirp/kenwood_tone.py5
-rw-r--r--chirp/locale/it/LC_MESSAGES/CHIRP.mobin94556 -> 150447 bytes
-rw-r--r--chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mobin87412 -> 87413 bytes
-rw-r--r--chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mobin1625 -> 105485 bytes
-rw-r--r--chirp/stock_configs/FR Marine VHF Channels.csv2
-rw-r--r--chirp/wxui/__init__.py22
-rw-r--r--chirp/wxui/bankedit.py17
-rw-r--r--chirp/wxui/bugreport.py16
-rw-r--r--chirp/wxui/common.py92
-rw-r--r--chirp/wxui/main.py67
-rw-r--r--chirp/wxui/memedit.py6
-rw-r--r--chirp/wxui/radioinfo.py16
-rw-r--r--chirp/wxui/serialtrace.py10
-rw-r--r--chirp/wxui/settingsedit.py15
-rw-r--r--setup.py2
-rw-r--r--tests/__init__.py4
-rw-r--r--tests/__pycache__/test_brute_force.cpython-310-pytest-7.1.3.pycbin6686 -> 6686 bytes
-rw-r--r--tests/driver_setting_docs.yaml6
-rw-r--r--tests/driver_xfails.yaml51
-rw-r--r--tests/images/BTECH_GMRS-50X1.imgbin16384 -> 16537 bytes
-rw-r--r--tests/images/Baofeng_DM-32UV.imgbin0 -> 311449 bytes
-rw-r--r--tests/images/Baofeng_UV-5G_Pro.imgbin6665 -> 6665 bytes
-rw-r--r--tests/images/Baofeng_UV-5R.imgbin6661 -> 6657 bytes
-rw-r--r--tests/images/Boblov_X3Plus.imgbin1008 -> 1165 bytes
-rw-r--r--tests/images/Icom_IC-U82.imgbin6464 -> 6617 bytes
-rw-r--r--tests/images/Icom_ID-4100.imgbin172992 -> 173145 bytes
-rw-r--r--tests/images/Kenwood_NX-800.imgbin0 -> 168397 bytes
-rw-r--r--tests/images/Quansheng_UV-K5_losehu.imgbin0 -> 262657 bytes
-rw-r--r--tests/images/Retevis_RB48.imgbin0 -> 2233 bytes
-rw-r--r--tests/images/Retevis_RB648.imgbin0 -> 2233 bytes
-rw-r--r--tests/images/Retevis_RT18.imgbin0 -> 1161 bytes
-rw-r--r--tests/images/Retevis_RT86A.imgbin0 -> 1017 bytes
-rw-r--r--tests/images/Retevis_RT97S.imgbin0 -> 1113 bytes
-rw-r--r--tests/images/TYT_UVL-15W.imgbin0 -> 102625 bytes
-rw-r--r--tests/images/Wouxun_KG-UV9D_Plus.imgbin32768 -> 32937 bytes
-rw-r--r--tests/images/Yaesu_FT-7100M.imgbin7936 -> 8093 bytes
-rw-r--r--tests/images/Yaesu_FT-8000R.imgbin0 -> 2017 bytes
-rw-r--r--tests/images/Yaesu_FT5D_R.imgbin0 -> 131096 bytes
-rw-r--r--tests/images/Yaesu_FTM-150E.imgbin0 -> 98485 bytes
-rw-r--r--tests/images/Yaesu_FTM-300DR.imgbin0 -> 98461 bytes
-rw-r--r--tests/images/Zartek_ZA-758.imgbin0 -> 1189 bytes
-rw-r--r--tests/py3_driver_testers.txt420
-rw-r--r--tests/test_brute_force.py2
-rw-r--r--tests/test_setting_docs.py41
-rw-r--r--tests/unit/__pycache__/test_alinco_clone.cpython-310-pytest-7.1.3.pycbin6437 -> 7571 bytes
-rw-r--r--tests/unit/__pycache__/test_directory.cpython-310-pytest-7.1.3.pycbin7339 -> 8732 bytes
-rw-r--r--tests/unit/__pycache__/test_ft450d_docs.cpython-310-pytest-7.1.3.pycbin0 -> 1931 bytes
-rw-r--r--tests/unit/__pycache__/test_kenwood_tone.cpython-310-pytest-7.1.3.pycbin60864 -> 61031 bytes
-rw-r--r--tests/unit/__pycache__/test_thg71.cpython-310-pytest-7.1.3.pycbin0 -> 8127 bytes
-rw-r--r--tests/unit/__pycache__/test_wxui_radiothread.cpython-310-pytest-7.1.3.pycbin7151 -> 7121 bytes
-rw-r--r--tests/unit/__pycache__/test_yaesu_clone.cpython-310-pytest-7.1.3.pycbin7324 -> 23030 bytes
-rw-r--r--tests/unit/test_alinco_clone.py42
-rw-r--r--tests/unit/test_directory.py19
-rw-r--r--tests/unit/test_ft450d_docs.py26
-rw-r--r--tests/unit/test_ft8000r.py658
-rw-r--r--tests/unit/test_kenwood_tone.py8
-rw-r--r--tests/unit/test_thg71.py255
-rw-r--r--tests/unit/test_uvk5_cn.py1075
-rw-r--r--tests/unit/test_vx8.py69
-rw-r--r--tests/unit/test_wxui_radiothread.py17
-rw-r--r--tests/unit/test_yaesu_clone.py767
-rwxr-xr-xtools/check_commit.sh3
-rwxr-xr-xtools/checkpatch.sh72
-rwxr-xr-xtools/cpep8.py2
146 files changed, 15345 insertions, 1314 deletions
diff --git a/PKG-INFO b/PKG-INFO
index 61f065e..a61fa73 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 2.4
Name: chirp
-Version: 20260814
+Version: 20261030
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 61f065e..a61fa73 100644
--- a/chirp.egg-info/PKG-INFO
+++ b/chirp.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 2.4
Name: chirp
-Version: 20260814
+Version: 20261030
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 bdec280..1438bca 100644
--- a/chirp.egg-info/SOURCES.txt
+++ b/chirp.egg-info/SOURCES.txt
@@ -46,6 +46,7 @@ chirp/drivers/ap510.py
chirp/drivers/ar8200.py
chirp/drivers/baofeng_common.py
chirp/drivers/baofeng_digital.py
+chirp/drivers/baofeng_dm32uv.py
chirp/drivers/baofeng_uv17.py
chirp/drivers/baofeng_uv17Pro.py
chirp/drivers/baofeng_uv3r.py
@@ -71,11 +72,14 @@ chirp/drivers/ft60.py
chirp/drivers/ft70.py
chirp/drivers/ft7100.py
chirp/drivers/ft7800.py
+chirp/drivers/ft8000r.py
chirp/drivers/ft8100.py
chirp/drivers/ft817.py
chirp/drivers/ft818.py
chirp/drivers/ft857.py
chirp/drivers/ft90.py
+chirp/drivers/ftm150.py
+chirp/drivers/ftm300d.py
chirp/drivers/ftm3200d.py
chirp/drivers/ftm350.py
chirp/drivers/ftm7250d.py
@@ -142,6 +146,7 @@ chirp/drivers/leixen.py
chirp/drivers/lt725uv.py
chirp/drivers/mml_jc8810.py
chirp/drivers/mursv1.py
+chirp/drivers/nx800.py
chirp/drivers/puxing.py
chirp/drivers/puxing_px888k.py
chirp/drivers/radioddity_db40g.py
@@ -163,12 +168,14 @@ chirp/drivers/retevis_rb15.py
chirp/drivers/retevis_rb17p.py
chirp/drivers/retevis_rb28.py
chirp/drivers/retevis_rt1.py
+chirp/drivers/retevis_rt18.py
chirp/drivers/retevis_rt21.py
chirp/drivers/retevis_rt22.py
chirp/drivers/retevis_rt23.py
chirp/drivers/retevis_rt26.py
chirp/drivers/retevis_rt76p.py
chirp/drivers/retevis_rt87.py
+chirp/drivers/retevis_rt97s.py
chirp/drivers/retevis_rt98.py
chirp/drivers/rh5r_v2.py
chirp/drivers/tdh8.py
@@ -207,11 +214,13 @@ chirp/drivers/ts480.py
chirp/drivers/ts590.py
chirp/drivers/ts790e.py
chirp/drivers/ts850.py
+chirp/drivers/tyt_uvl15w.py
chirp/drivers/uv5r.py
chirp/drivers/uv5x3.py
chirp/drivers/uv6r.py
chirp/drivers/uvb5.py
chirp/drivers/uvk5.py
+chirp/drivers/uvk5_cn.py
chirp/drivers/uvk5_egzumer.py
chirp/drivers/vgc.py
chirp/drivers/vx1.py
@@ -314,11 +323,11 @@ chirp/wxui/settingsedit.py
tests/__init__.py
tests/base.py
tests/conftest.py
+tests/driver_setting_docs.yaml
tests/driver_xfails.yaml
tests/icom_clone_simulator.py
tests/model_stats.tsv
tests/py3-untested-drivers.txt
-tests/py3_driver_testers.txt
tests/test_banks.py
tests/test_brute_force.py
tests/test_clone.py
@@ -327,6 +336,7 @@ tests/test_detect.py
tests/test_drivers.py
tests/test_edges.py
tests/test_features.py
+tests/test_setting_docs.py
tests/test_settings.py
tests/xfails.txt
tests/__pycache__/__init__.cpython-310.pyc
@@ -390,6 +400,7 @@ tests/images/Baofeng_BF-T20.img
tests/images/Baofeng_BF-T20FRS.img
tests/images/Baofeng_BF-T8.img
tests/images/Baofeng_BF-V12D.img
+tests/images/Baofeng_DM-32UV.img
tests/images/Baofeng_F-11.img
tests/images/Baofeng_GM-21.img
tests/images/Baofeng_GM-5RH.img
@@ -460,6 +471,7 @@ tests/images/KSUN_M6.img
tests/images/KYD_IP-620.img
tests/images/KYD_NC-630A.img
tests/images/Kenwood_HMK.hmk
+tests/images/Kenwood_NX-800.img
tests/images/Kenwood_TH-D72_clone_mode.img
tests/images/Kenwood_TH-D74_clone_mode.img
tests/images/Kenwood_TH-D75.img
@@ -503,6 +515,7 @@ tests/images/Quansheng_TG-UV2+.img
tests/images/Quansheng_TK11.img
tests/images/Quansheng_UV-K5.img
tests/images/Quansheng_UV-K5_egzumer.img
+tests/images/Quansheng_UV-K5_losehu.img
tests/images/Radioddity_DB40-G.img
tests/images/Radioddity_GA-510.img
tests/images/Radioddity_GA-510_V2.img
@@ -563,6 +576,7 @@ tests/images/Retevis_RB27V.img
tests/images/Retevis_RB28.img
tests/images/Retevis_RB28B.img
tests/images/Retevis_RB29.img
+tests/images/Retevis_RB48.img
tests/images/Retevis_RB615.img
tests/images/Retevis_RB617.img
tests/images/Retevis_RB618.img
@@ -572,6 +586,7 @@ tests/images/Retevis_RB627B.img
tests/images/Retevis_RB628.img
tests/images/Retevis_RB628B.img
tests/images/Retevis_RB629.img
+tests/images/Retevis_RB648.img
tests/images/Retevis_RB75.img
tests/images/Retevis_RB85.img
tests/images/Retevis_RB87.img
@@ -579,6 +594,7 @@ tests/images/Retevis_RB89.img
tests/images/Retevis_RT1.img
tests/images/Retevis_RT15.img
tests/images/Retevis_RT16.img
+tests/images/Retevis_RT18.img
tests/images/Retevis_RT19.img
tests/images/Retevis_RT20.img
tests/images/Retevis_RT21.img
@@ -602,6 +618,7 @@ tests/images/Retevis_RT668.img
tests/images/Retevis_RT68.img
tests/images/Retevis_RT76.img
tests/images/Retevis_RT86.img
+tests/images/Retevis_RT86A.img
tests/images/Retevis_RT86S.img
tests/images/Retevis_RT87.img
tests/images/Retevis_RT9000D_136-174.img
@@ -609,6 +626,7 @@ tests/images/Retevis_RT9000D_220-260.img
tests/images/Retevis_RT9000D_400-490.img
tests/images/Retevis_RT9000D_66-88.img
tests/images/Retevis_RT95.img
+tests/images/Retevis_RT97S.img
tests/images/Retevis_RT98.img
tests/images/Rugged_RH5R-V2.img
tests/images/Ruyage_UV58Plus.img
@@ -631,6 +649,7 @@ tests/images/TYT_TH-UV88.img
tests/images/TYT_TH-UVF1.img
tests/images/TYT_TH-UVF8D.img
tests/images/TYT_TH9000_144.img
+tests/images/TYT_UVL-15W.img
tests/images/Talkpod_A36plus.img
tests/images/Talkpod_A36plus_8w.img
tests/images/WACCOM_MINI-8900.img
@@ -676,6 +695,7 @@ tests/images/Yaesu_FT-65R.img
tests/images/Yaesu_FT-70D.img
tests/images/Yaesu_FT-7100M.img
tests/images/Yaesu_FT-7800_7900.img
+tests/images/Yaesu_FT-8000R.img
tests/images/Yaesu_FT-8100.img
tests/images/Yaesu_FT-817.img
tests/images/Yaesu_FT-817ND.img
@@ -688,6 +708,9 @@ tests/images/Yaesu_FT-8900.img
tests/images/Yaesu_FT-90.img
tests/images/Yaesu_FT2D_R.img
tests/images/Yaesu_FT3D_R.img
+tests/images/Yaesu_FT5D_R.img
+tests/images/Yaesu_FTM-150E.img
+tests/images/Yaesu_FTM-300DR.img
tests/images/Yaesu_FTM-3200D_R.img
tests/images/Yaesu_FTM-350.img
tests/images/Yaesu_FTM-7250D_R.img
@@ -702,6 +725,7 @@ tests/images/Yaesu_VX-7.img
tests/images/Yaesu_VX-8DR.img
tests/images/Yaesu_VX-8GE.img
tests/images/Yaesu_VX-8R.img
+tests/images/Zartek_ZA-758.img
tests/unit/__init__.py
tests/unit/base.py
tests/unit/rb-united_states-oregon.json
@@ -719,6 +743,8 @@ tests/unit/test_chirp_common.py
tests/unit/test_cli.py
tests/unit/test_csv.py
tests/unit/test_directory.py
+tests/unit/test_ft450d_docs.py
+tests/unit/test_ft8000r.py
tests/unit/test_icf.py
tests/unit/test_icom_clone.py
tests/unit/test_import_logic.py
@@ -733,7 +759,10 @@ tests/unit/test_retevis_ra25.py
tests/unit/test_serialtrace.py
tests/unit/test_settings.py
tests/unit/test_th9800.py
+tests/unit/test_thg71.py
tests/unit/test_util.py
+tests/unit/test_uvk5_cn.py
+tests/unit/test_vx8.py
tests/unit/test_wxui_memquery.py
tests/unit/test_wxui_radiothread.py
tests/unit/test_yaesu_clone.py
@@ -751,6 +780,7 @@ tests/unit/__pycache__/test_cli.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_crc.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_csv.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_directory.cpython-310-pytest-7.1.3.pyc
+tests/unit/__pycache__/test_ft450d_docs.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_icf.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_icom_clone.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_import_logic.cpython-310-pytest-7.1.3.pyc
@@ -765,13 +795,13 @@ tests/unit/__pycache__/test_retevis_ra25.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_thg71.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_util.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_wxui_memquery.cpython-310-pytest-7.1.3.pyc
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/checkpatch.sh
tools/cpep8.blacklist
tools/cpep8.exceptions
tools/cpep8.manifest
diff --git a/chirp/__init__.py b/chirp/__init__.py
index 91f0eb5..6589ff7 100644
--- a/chirp/__init__.py
+++ b/chirp/__init__.py
@@ -1 +1 @@
-CHIRP_VERSION = "next-20260814"
+CHIRP_VERSION = "next-20261030"
diff --git a/chirp/bitwise.py b/chirp/bitwise.py
index a8e69ad..7aca066 100644
--- a/chirp/bitwise.py
+++ b/chirp/bitwise.py
@@ -69,6 +69,7 @@ import re
import warnings
from chirp import bitwise_grammar
+from chirp import util
LOG = logging.getLogger(__name__)
@@ -820,17 +821,27 @@ class structDataElement(DataElement):
def __repr__(self):
return self._make_repr('struct')
- def _make_repr(self, typename):
+ def _make_repr(self, typename, verbose=False):
s = typename + " {" + os.linesep
+ pos = 0
for prop in self._keys:
+ cur = self._generators[prop].get_offset()
+ if cur != pos and verbose:
+ s += os.linesep + (
+ 'Gap of %i at 0x%04x' % (cur - pos, pos)) + os.linesep
+ s += util.hexprint(self._data[pos:cur], pos) + os.linesep
s += " %15s: %s%s" % (prop, repr(self._generators[prop]),
os.linesep)
+ pos = cur + self._generators[prop].size() // 8
s += "} %s (%i bytes at 0x%04X)%s" % (self._name,
self.size() // 8,
self._offset,
os.linesep)
return s
+ def verbose_repr(self):
+ return self._make_repr('struct', verbose=True)
+
def __init__(self, *args, **kwargs):
self._generators = {}
self._keys = []
diff --git a/chirp/chirp_common.py b/chirp/chirp_common.py
index 324abdf..0a5e45d 100644
--- a/chirp/chirp_common.py
+++ b/chirp/chirp_common.py
@@ -85,7 +85,7 @@ CROSS_MODES = (
# models.
MODES = ("WFM", "FM", "NFM", "AM", "NAM", "DV", "USB", "LSB", "CW", "RTTY",
"DIG", "PKT", "NCW", "NCWR", "CWR", "P25", "Auto", "RTTYR",
- "FSK", "FSKR", "DMR", "DN")
+ "FSK", "FSKR", "DMR", "DN", "NXDN")
TONE_MODES = (
"",
@@ -1555,14 +1555,14 @@ class CloneModeRadio(FileBackedRadio, ExternalMemoryProperties,
@classmethod
def match_model(cls, filedata, filename):
"""Given contents of a stored file (@filedata), return True if
- this radio driver handles the represented model"""
-
- # Unless the radio driver does something smarter, claim
- # support if the data is the same size as our memory.
- # Ideally, each radio would perform an intelligent analysis to
- # make this determination to avoid model conflicts with
- # memories of the same size.
- return cls._memsize and len(filedata) == cls._memsize
+ this radio driver handles the represented model
+
+ NOTE: This should not be implemented by new drivers UNLESS you need
+ to recognize a non-CHIRP-native file format, such as files from the
+ OEM software or similar. Those must be registered via
+ directory.register_format() in order to be properly recognized.
+ """
+ return False
def sync_in(self):
"""Initiate a radio-to-PC clone operation"""
diff --git a/chirp/cli/main.py b/chirp/cli/main.py
index 9dd0d0b..446cf3a 100644
--- a/chirp/cli/main.py
+++ b/chirp/cli/main.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
#
# Copyright 2008 Dan Smith <dsmith@danplanet.com>
#
diff --git a/chirp/drivers/__init__.py b/chirp/drivers/__init__.py
index 59a764a..309b25b 100644
--- a/chirp/drivers/__init__.py
+++ b/chirp/drivers/__init__.py
@@ -154,40 +154,49 @@ from chirp.drivers import vx8
from chirp.drivers import __init__
from chirp.drivers import wouxun
from chirp.drivers import wouxun_common
-from chirp.drivers import baofeng_uv17Pro
+from chirp.drivers import baofeng_digital
from chirp.drivers import iradio_uv_5118plus
from chirp.drivers import retevis_ha1g
+from chirp.drivers import retevis_rt18
from chirp.drivers import ksun_m6
from chirp.drivers import tk481
from chirp.drivers import ict10
-from chirp.drivers import retevis_ra25
+from chirp.drivers import uvk5
+from chirp.drivers import uvk5_cn
from chirp.drivers import icf520
from chirp.drivers import retevis_ra86
from chirp.drivers import retevis_ra87
-from chirp.drivers import tk280
-from chirp.drivers import uvk5
from chirp.drivers import ar8200
+from chirp.drivers import retevis_rt97s
from chirp.drivers import baofeng_uv17
from chirp.drivers import yaesu_clone
from chirp.drivers import tdm11
from chirp.drivers import radtel_rt490
+from chirp.drivers import retevis_ra25
from chirp.drivers import uvk5_egzumer
+from chirp.drivers import ft8000r
from chirp.drivers import radtel_rt620
from chirp.drivers import retevis_c2
+from chirp.drivers import ftm300d
+from chirp.drivers import ftm150
from chirp.drivers import ts790e
from chirp.drivers import retevis_ha2
+from chirp.drivers import tyt_uvl15w
from chirp.drivers import icm710
-from chirp.drivers import vx1
-from chirp.drivers import baofeng_digital
from chirp.drivers import alinco_dr735t
from chirp.drivers import mml_jc8810
from chirp.drivers import tk690
from chirp.drivers import vx150
+from chirp.drivers import nx800
+from chirp.drivers import vx1
from chirp.drivers import radioddity_db40g
from chirp.drivers import radioddity_gm30
+from chirp.drivers import baofeng_dm32uv
from chirp.drivers import kenwood_d7
-from chirp.drivers import radtel_rt880g
from chirp.drivers import retevis_h777v4
+from chirp.drivers import radtel_rt880g
from chirp.drivers import iradio_common
from chirp.drivers import radtel_rt900
-__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', 'tk760g', 'ft8100', 'ft817', 'ft818', 'ft857', 'ft90', 'ft7800', 'ftm3200d', 'ftm350', 'ftm7250d', 'ga510', 'generic_csv', 'generic_tpe', 'gmrsuv1', 'gmrsv2', 'h777', 'hf90', 'hg_uv98', 'tk11', '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', 'tdh8', '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', 'alinco', 'tk8102', 'tk8160', 'tk8180', 'tmd710', 'tmv71', 'tmv71_ll', 'ts2000', 'ts480', 'ts590', 'ts850', 'uv5r', 'uv5x3', 'uv6r', 'uvb5', 'vgc', 'vx170', 'vx2', 'vx3', 'vx5', 'vx510', 'vx6', 'vx7', 'vx8', '__init__', 'wouxun', 'wouxun_common', 'baofeng_uv17Pro', 'iradio_uv_5118plus', 'retevis_ha1g', 'ksun_m6', 'tk481', 'ict10', 'retevis_ra25', 'icf520', 'retevis_ra86', 'retevis_ra87', 'tk280', 'uvk5', 'ar8200', 'baofeng_uv17', 'yaesu_clone', 'tdm11', 'radtel_rt490', 'uvk5_egzumer', 'radtel_rt620', 'retevis_c2', 'ts790e', 'retevis_ha2', 'icm710', 'vx1', 'baofeng_digital', 'alinco_dr735t', 'mml_jc8810', 'tk690', 'vx150', 'radioddity_db40g', 'radioddity_gm30', 'kenwood_d7', 'radtel_rt880g', 'retevis_h777v4', 'iradio_common', 'radtel_rt900']
+from chirp.drivers import tk280
+from chirp.drivers import baofeng_uv17Pro
+__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', 'tk760g', 'ft8100', 'ft817', 'ft818', 'ft857', 'ft90', 'ft7800', 'ftm3200d', 'ftm350', 'ftm7250d', 'ga510', 'generic_csv', 'generic_tpe', 'gmrsuv1', 'gmrsv2', 'h777', 'hf90', 'hg_uv98', 'tk11', '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', 'tdh8', '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', 'alinco', 'tk8102', 'tk8160', 'tk8180', 'tmd710', 'tmv71', 'tmv71_ll', 'ts2000', 'ts480', 'ts590', 'ts850', 'uv5r', 'uv5x3', 'uv6r', 'uvb5', 'vgc', 'vx170', 'vx2', 'vx3', 'vx5', 'vx510', 'vx6', 'vx7', 'vx8', '__init__', 'wouxun', 'wouxun_common', 'baofeng_digital', 'iradio_uv_5118plus', 'retevis_ha1g', 'retevis_rt18', 'ksun_m6', 'tk481', 'ict10', 'uvk5', 'uvk5_cn', 'icf520', 'retevis_ra86', 'retevis_ra87', 'ar8200', 'retevis_rt97s', 'baofeng_uv17', 'yaesu_clone', 'tdm11', 'radtel_rt490', 'retevis_ra25', 'uvk5_egzumer', 'ft8000r', 'radtel_rt620', 'retevis_c2', 'ftm300d', 'ftm150', 'ts790e', 'retevis_ha2', 'tyt_uvl15w', 'icm710', 'alinco_dr735t', 'mml_jc8810', 'tk690', 'vx150', 'nx800', 'vx1', 'radioddity_db40g', 'radioddity_gm30', 'baofeng_dm32uv', 'kenwood_d7', 'retevis_h777v4', 'radtel_rt880g', 'iradio_common', 'radtel_rt900', 'tk280', 'baofeng_uv17Pro']
diff --git a/chirp/drivers/alinco.py b/chirp/drivers/alinco.py
index 02809b7..ed384e5 100644
--- a/chirp/drivers/alinco.py
+++ b/chirp/drivers/alinco.py
@@ -21,7 +21,7 @@ from chirp.settings import RadioSettingValueBoolean
import time
import logging
-import codecs
+import binascii
LOG = logging.getLogger(__name__)
@@ -103,7 +103,7 @@ class AlincoStyleRadio(chirp_common.CloneModeRadio):
if b":" not in resp:
raise errors.RadioError("Unexpected response from radio")
addr, _data = resp.split(b":", 1)
- data = codecs.decode(_data, 'hex')
+ data = binascii.unhexlify(_data)
if len(data) != 16:
LOG.debug("Response was:")
@@ -132,7 +132,7 @@ class AlincoStyleRadio(chirp_common.CloneModeRadio):
self._send(b"AL~E\r\n")
self._read(20)
- return memmap.MemoryMap(data)
+ return memmap.MemoryMapBytes(data)
def _identify(self):
for _i in range(0, 3):
@@ -149,7 +149,7 @@ class AlincoStyleRadio(chirp_common.CloneModeRadio):
raise Exception("Addr 0x%04x not on 16-byte boundary" % addr)
_data = self._mmap[addr:addr+16]
- data = codecs.encode(_data, 'hex').upper()
+ data = binascii.b2a_hex(_data).upper()
cmd = b"AL~F%04XW%s\r\n" % (addr, data)
self._send(cmd)
@@ -315,10 +315,14 @@ class DRx35Radio(AlincoStyleRadio):
if not self._get_used(number) and self.MODEL != "JT220M":
mem.empty = True
return mem
- elif self.MODEL == 'JT220M':
- mem.immutable = ['empty']
mem.freq = int(_mem.freq) * 100
+ if self.MODEL == "JT220M" and mem.freq == 0:
+ mem.empty = True
+ return mem
+ elif self.MODEL == "JT220M":
+ mem.immutable = ['empty']
+
mem.rtone = self._valid_tones[_mem.rtone]
mem.ctone = self._valid_tones[_mem.ctone]
mem.duplex = DUPLEX[_mem.duplex]
@@ -543,7 +547,7 @@ class DJ175Radio(DRx35Radio):
if len(_data) == 0:
raise errors.RadioNoResponse()
- data = codecs.decode(_data, 'hex')
+ data = binascii.unhexlify(_data)
if len(data) != 16:
LOG.debug("Response was:")
@@ -651,7 +655,7 @@ class AlincoDJG7(AlincoStyleRadio):
if len(_data) == 0:
raise errors.RadioNoResponse()
- data = codecs.decode(_data, "hex")
+ data = binascii.unhexlify(_data)
if len(data) != 64:
LOG.debug("Response was:")
@@ -695,7 +699,7 @@ class AlincoDJG7(AlincoStyleRadio):
raise Exception("Addr 0x%04x not on 64-byte boundary" % addr)
_data = self._mmap[addr:addr+0x40]
- data = codecs.encode(_data, "hex").upper()
+ data = binascii.b2a_hex(_data).upper()
cmd = b"AL~F%05XW%s\r" % (addr, data)
self._send(cmd)
diff --git a/chirp/drivers/anytone_iii.py b/chirp/drivers/anytone_iii.py
index d4024a6..66c57df 100644
--- a/chirp/drivers/anytone_iii.py
+++ b/chirp/drivers/anytone_iii.py
@@ -792,6 +792,10 @@ class AnyTone5888UVIIIRadio(chirp_common.CloneModeRadio,
BAUD_RATE = 9600
_file_ident = b"588UVP"
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return cls._file_ident in filedata[0x40:0x4D]
+
_ranges = [
(0x0000, 0x8000)
]
@@ -2030,7 +2034,3 @@ class AnyTone5888UVIIIRadio(chirp_common.CloneModeRadio,
element.value.offset))
else:
setattr(_settings, name, element.value)
-
- @classmethod
- def match_model(cls, filedata, filename):
- return cls._file_ident in filedata[0x40:0x4D]
diff --git a/chirp/drivers/ar8200.py b/chirp/drivers/ar8200.py
index 44747ff..e0e9097 100644
--- a/chirp/drivers/ar8200.py
+++ b/chirp/drivers/ar8200.py
@@ -985,8 +985,9 @@ class AR8200Radio(chirp_common.LiveRadio):
if memory.mode == 'Auto':
mode = 0
elif memory.mode == 'AM':
+ ammode = memory.extra['am'] if 'am' in memory.extra else 'AM'
mode = [mode[1] for mode in self._MODES
- if mode[0] == memory.extra['am']][0]
+ if mode[0] == ammode][0]
else:
mode = [mode[1] for mode in self._MODES
if mode[0] == memory.mode][0]
@@ -1037,8 +1038,9 @@ class AR8200Radio(chirp_common.LiveRadio):
if memory.mode == 'Auto':
mode = 0
elif memory.mode == 'AM':
+ ammode = memory.extra['am'] if 'am' in memory.extra else 'AM'
mode = [mode[1] for mode in self._MODES
- if mode[0] == memory.extra['am']][0]
+ if mode[0] == ammode][0]
else:
mode = [mode[1] for mode in self._MODES
if mode[0] == memory.mode][0]
@@ -1118,8 +1120,9 @@ class AR8200Radio(chirp_common.LiveRadio):
if memory.mode == 'Auto':
mode = 0
elif memory.mode == 'AM':
+ ammode = memory.extra['am'] if 'am' in memory.extra else 'AM'
mode = [mode[1] for mode in self._MODES
- if mode[0] == memory.extra['am']][0]
+ if mode[0] == ammode][0]
else:
mode = [mode[1] for mode in self._MODES
if mode[0] == memory.mode][0]
diff --git a/chirp/drivers/baofeng_digital.py b/chirp/drivers/baofeng_digital.py
index 89614f9..0b2184e 100644
--- a/chirp/drivers/baofeng_digital.py
+++ b/chirp/drivers/baofeng_digital.py
@@ -358,7 +358,9 @@ class BaofengDigital(chirp_common.CloneModeRadio,
rs = RadioSetting("bcl", "BCL",
RadioSettingValueBoolean(bcl))
- rs.set_doc('Busy channel lockout.')
+ rs.set_doc('Prevents transmitting on a channel that is already in '
+ 'use. Pressing PTT on a busy channel sounds an alert '
+ 'tone instead of keying the transmitter.')
mem.extra.append(rs)
rs = RadioSetting("encryption_key", "Encryption key",
diff --git a/chirp/drivers/baofeng_dm32uv.py b/chirp/drivers/baofeng_dm32uv.py
new file mode 100644
index 0000000..ad9bd25
--- /dev/null
+++ b/chirp/drivers/baofeng_dm32uv.py
@@ -0,0 +1,2762 @@
+# Copyright 2026 chaffed
+#
+# 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/>.
+
+"""Baofeng DM-32UV (DMR) driver.
+
+Channels, zones (as banks), DMR lists (radio IDs, contacts, RX groups),
+scan lists and radio settings. Upload writes only the pages that differ
+from the radio (see UPLOAD_TAGS), one whole aligned 4 KB page per write,
+and reads every written page back. The layout was worked out from the
+vendor CPS (v1.60) and radio firmware and checked against a real radio
+(firmware DM32.01.01.047).
+
+The radio keeps its codeplug in 4 KB flash pages whose last byte is a tag
+naming the contents; pages move around as the radio rewrites them. The
+image this driver stores is logical: one 4 KB slot per tag in IMAGE_TAGS,
+in that order, each holding the page as read (tag byte included), or all
+0xFF if the radio has no page with that tag.
+
+The protocol has no checksums, so the driver doesn't try to recover from
+a bad link: apart from the PSEARCH handshake, any bad or missing reply
+stops the transfer, and the link must be sound. Some CH340-based
+programming cables are not: they flip bit 7 of received bytes (1 in 700
+to 1 in 50 on the tested cable), while an FTDI cable on the same radio
+read 2 MB without an error. A reply that is visibly garbled (a page tag
+or model ID with bit 7 set) stops the transfer with advice about the cable.
+"""
+
+import collections
+import functools
+import logging
+import struct
+import time
+
+from chirp import bitwise, chirp_common, directory, errors, memmap
+from chirp import kenwood_tone
+from chirp.settings import (RadioSetting, RadioSettingGroup, RadioSettings,
+ RadioSettingValueBoolean,
+ RadioSettingValueInteger, RadioSettingValueList,
+ RadioSettingValueString)
+
+LOG = logging.getLogger(__name__)
+
+PAGE = 0x1000
+# The tags the vendor CPS reads (0x12-0x41 are the channel pages).
+IMAGE_TAGS = ([0x02, 0x03, 0x04, 0x06, 0x0A, 0x0B, 0x0F, 0x10, 0x11] +
+ list(range(0x12, 0x49)) + list(range(0x5C, 0x68)))
+CH_TAG0 = 0x12
+CH_BASE = IMAGE_TAGS.index(CH_TAG0) * PAGE
+CH_SIZE, CH_PER_PAGE, CH_COUNT = 0x30, 85, 4000
+VFO_OFFSETS = (0xF9F, 0xFCF) # in the last channel page
+# Zones (tags 0x5C-0x64): the CPS zone accessors (0x482740-0x482cd0) put
+# zone z at page (z-1)//28, slot (z-1)%28 of 0x91 bytes, after a 16-byte
+# header on the first page only. At most 250 zones of 64 members.
+ZONE_TAG0 = 0x5C
+ZONE_BASE = IMAGE_TAGS.index(ZONE_TAG0) * PAGE
+ZONE_PER_PAGE, ZONE_COUNT, ZONE_MEMBERS = 28, 250, 64
+# Longest zone order text on the Settings tab: "1, 2, ..., 250".
+ZONE_ORDER_MAX = len(', '.join(str(z) for z in range(1, ZONE_COUNT + 1)))
+# Encryption key names (CPS 0x479630): tag, offset of entry 1, entry size,
+# name length, entries. Keys are chosen per channel, not edited.
+DMR_LISTS = {
+ 'privacy': (0x10, 0x301, 0x2C, 10, 32),
+ 'emergency': (0x10, 0x000, 0x14, 10, 8), # digital emergency systems
+}
+# DMR lists, from the CPS accessors (see PROTOCOL.md "DMR lists"):
+# radio IDs (tag 0x67): count at 0, entry n at 16*n = u24 LE ID + 12-char name
+RADIOID_TAG, RADIOID_MAX, RADIOID_NAME = 0x67, 250, 12
+# contacts: index page 0x0B (u16 count, counts by call type, free-slot bitmap,
+# name- and ID-sorted lists), 24-byte records on pages 0x44-0x48
+CONTACT_INDEX_TAG, CONTACT_REC_TAG0 = 0x0B, 0x44
+CONTACT_PER_PAGE, CONTACT_REC, CONTACT_MAX, CONTACT_NAME = 170, 0x18, 800, 16
+CALL_TYPES = ['Private Call', 'Group Call', 'All Call']
+# RX group lists (tag 0x0F): used-bitmap in bytes 0-3, group n at
+# 0x6D*n - 0x5C: 11-char name, 32 member IDs (u24 LE)
+RXG_TAG, RXG_MAX, RXG_NAME, RXG_MEMBERS, RXG_REC = 0x0F, 32, 11, 32, 0x6D
+# Per-channel TX contact (CPS 0x480050), outside the channel record:
+# 2 bytes per channel on tags 0x42/0x43, 12-bit contact number + digital flag
+TXC_TAGS = (0x42, 0x43)
+DMR_ID_MAX, ALL_CALL_ID = 16776415, 16777215
+# Scan lists (tag 0x11; CPS 0x483050-0x484160): byte 0 = number of lists;
+# list n at 0x39*n - 0x38: 11-char name, +0x0b member count, +0x0c CTC scan
+# mode (low nibble) / TX mode (high nibble), +0x0d..+0x17 other options
+# (kept as they are), +0x18 up to 16 u16 channel numbers. The members start
+# in the first slot (checked on the radio's own display).
+SCAN_TAG, SCAN_MAX, SCAN_REC, SCAN_NAME, SCAN_MEMBERS = 0x11, 32, 0x39, 11, 16
+# [ScanCtcDcsMode]
+SCAN_CTC_MODES = ['Not Detection CTC', 'Detection CTC Non Priority',
+ 'Detection CTC Priority', 'Detection CTC']
+SCAN_TX_MODES = ['Current Channel', 'Last Active Channel', # [ScanTxMode]
+ 'Designed Channel']
+# options of the radio's factory scan lists; bytes 3-4 = designed channel
+SCAN_DEFAULT_OPTS = bytes.fromhex('030600010000000000' '0a007f')
+
+# Some CH340 cables corrupt data from this radio (see the module docstring).
+CABLE_ADVICE = ('Some CH340-based programming cables corrupt data from '
+ 'this radio; a cable with an FTDI or CP2102 chip is '
+ 'recommended.')
+
+# The pages upload may write, in the order it writes them: lists before
+# what refers to them (contact records before their index, lists before
+# channels, zones last), so an interrupted upload leaves few dangling
+# references. One whole aligned page per W frame: the firmware erases the
+# sector on an aligned W and also erases the next sector if a W crosses
+# into it. Tags 0x02 and 0x69 look like calibration: never written.
+UPLOAD_TAGS = ([0x03, 0x04, 0x06, RADIOID_TAG] +
+ list(range(CONTACT_REC_TAG0, CONTACT_REC_TAG0 + 5)) +
+ [CONTACT_INDEX_TAG, RXG_TAG, SCAN_TAG] +
+ list(range(0x12, 0x42)) + list(TXC_TAGS) +
+ list(range(0x5C, 0x65)))
+NEVER_WRITE = (0x02, 0x69)
+
+# DTMF (tag 0x06; CPS dialog 0x421bc0, accessors 0x47bb10-0x47c920). Codes
+# are one digit per byte (0-9, A-D = 10-13, * = 14, # = 15), ended by 0xFF.
+# 0xA20 on is BDC1200 (not handled; kept as it is).
+DTMF_TAG, DTMF_CODES, DTMF_CONTACTS = 0x06, 16, 64
+DTMF_CHARS = '0123456789ABCD*#'
+CODE_CHARS = {'dtmf': DTMF_CHARS, 'digits': '0123456789',
+ 'hex': '0123456789ABCDEF'}
+# Two-tone (tag 0x03; CPS dialogs 0x45a760 system, 0x45ac30 decode,
+# 0x45ae20 encode; accessors 0x479df0-0x47a7a0). Times in 0.1 s,
+# frequencies in 0.1 Hz. Five-tone is on the same page from 0x730.
+SIGNAL_TAG, TT_ENCODE, TT_DECODE = 0x03, 32, 4
+# Five-tone (tag 0x03 from 0x730; CPS dialogs 0x4254c0 system, 0x426240
+# message codes, 0x426590 special calls). Codes are hex digits, one per
+# byte, 0xFF-terminated.
+FT_MSG, FT_SPECIAL = 8, 32
+FT_STANDARDS = ['ZVEI1', 'ZVEI2', 'ZVEI3', 'CCIR1', 'CCIR2', 'CCIR3', 'EEA',
+ 'EIA'] # [FiveTone*Standard]
+FT_SPECIAL_TYPES = (['Off', 'ANI', 'Data Transmission'], # [SpecialCallType]
+ [0xFF, 0, 1])
+FT_DELIMITERS = ['No Pause in mid', 'A', 'B', 'C', 'D', 'E', 'F']
+FT_TONE_LONG = (['%d ms' % i for i in range(30, 101, 10)], 3)
+TT_HZ = (2885, 31068) # frequency limits in 0.1 Hz (CPS 0x45a760)
+# [TwoToneDecodeFormat] and the stored codes (CPS 0x47a1f0)
+TT_DECODE_FORMATS = ['None', 'A-B', 'A-C', 'A-D', 'B-A', 'B-C', 'B-D', 'C-A',
+ 'C-B', 'C-D', 'D-A', 'D-B', 'D-C', 'Long A', 'Long B',
+ 'Long C', 'Long D']
+TT_DECODE_CODES = [0xFF, 0x01, 0x02, 0x03, 0x10, 0x12, 0x13, 0x20, 0x21,
+ 0x23, 0x30, 0x31, 0x32, 0x0F, 0x1F, 0x2F, 0x3F]
+# The page each settings struct lives on.
+STRUCT_TAGS = {'dtmf': DTMF_TAG, 'twotone': SIGNAL_TAG,
+ 'fivetone': SIGNAL_TAG}
+
+
+# The image layout: one 4 KB slot per tag in IMAGE_TAGS order (see the
+# module docstring), so every address below is fixed.
+MEM_FORMAT = """
+struct chan {
+ char name[16];
+ lbcd rxfreq[4];
+ lbcd txfreq[4];
+ u8 chtype:4, forbid_tx:1, power:2, lone_work:1;
+ u8 wide:1, auto_scan:1, scanlist:6;
+ u8 forbid_talkaround:1, tx_admit:3, unknown1a:1, aprs_rx:1, offset_dir:2;
+ u8 emerg_indicator:1, emerg_ack:1, unknown1b:1, emerg_system:5;
+ u8 squelch:4, aprs_report:2, aprs_ptt_analog:1, aprs_ptt_digital:1;
+ u8 private_confirm:1, short_data_confirm:1, tdma_direct:1, timeslot:1,
+ colorcode:4;
+ u8 privacy;
+ u8 unknown1f:1, encrypt:1, rxgroup:6;
+ u8 aprs_channel;
+ ul16 rxtone;
+ ul16 txtone;
+ u8 unknown25:2, compander:1, vox:1, unknown25b:4;
+ u8 ptt_id_display:1, rx_squelch_mode:3, signaling:3, unknown26:1;
+ u8 rx_signal:4, tx_signal:4;
+ u8 unknown28;
+ u8 step:4, ptt_id:2, unknown29:2;
+ u8 unknown2a;
+ u8 radio_id;
+ lbcd offset[4];
+};
+
+struct zone {
+ char name[16];
+ u8 count;
+ ul16 members[64];
+};
+
+// Tag 0x03, slot 0x1000: two-tone, then five-tone from +0x730.
+#seekto 0x01001;
+u8 tt_encode_count;
+#seekto 0x01030;
+struct {
+ u8 pre_carrier;
+ u8 first_tone;
+ u8 second_tone;
+ u8 long_tone;
+ u8 interval;
+ u8 unknown35;
+ u8 polite_wait;
+ ul16 freq_a;
+ ul16 freq_b;
+ ul16 freq_c;
+ ul16 freq_d;
+ u8 unknown3f:6, side_tone:1, idle_ack:1;
+ u8 auto_reset;
+ u8 dec1_format;
+ u8 dec1_call;
+ u8 dec1_unknown:7, dec1_reply:1;
+ u8 dec1_unknown2;
+ u8 dec2_format;
+ u8 dec2_call;
+ u8 dec2_unknown:7, dec2_reply:1;
+ u8 dec2_unknown2;
+ u8 dec3_format;
+ u8 dec3_call;
+ u8 dec3_unknown:7, dec3_reply:1;
+ u8 dec3_unknown2;
+ u8 dec4_format;
+ u8 dec4_call;
+ u8 dec4_unknown:7, dec4_reply:1;
+ u8 dec4_unknown2;
+} twotone;
+#seekto 0x01220;
+struct {
+ u8 name[32];
+ u8 unknown20:7, single_tone:1;
+ u8 unknown21;
+ ul16 tone1;
+ ul16 tone2;
+ u8 unknown26[2];
+} tt_encode[32];
+#seekto 0x01730;
+struct {
+ u8 self_id[5];
+ u8 decode_std;
+ u8 unknown736:4, decode_resp:4;
+ u8 unknown737[3];
+ u8 pre_carrier;
+ u8 auto_reset;
+ u8 send_delay;
+ u8 ptt_id_pause;
+ u8 first_delay;
+ u8 unknown73f:7, side_tone:1;
+ u8 unknown740[16];
+ u8 msg1_func;
+ u8 msg1_unknown:4, msg1_resp:4;
+ u8 msg1_code[12];
+ u8 msg1_pad[2];
+ u8 msg2_func;
+ u8 msg2_unknown:4, msg2_resp:4;
+ u8 msg2_code[12];
+ u8 msg2_pad[2];
+ u8 msg3_func;
+ u8 msg3_unknown:4, msg3_resp:4;
+ u8 msg3_code[12];
+ u8 msg3_pad[2];
+ u8 msg4_func;
+ u8 msg4_unknown:4, msg4_resp:4;
+ u8 msg4_code[12];
+ u8 msg4_pad[2];
+ u8 msg5_func;
+ u8 msg5_unknown:4, msg5_resp:4;
+ u8 msg5_code[12];
+ u8 msg5_pad[2];
+ u8 msg6_func;
+ u8 msg6_unknown:4, msg6_resp:4;
+ u8 msg6_code[12];
+ u8 msg6_pad[2];
+ u8 msg7_func;
+ u8 msg7_unknown:4, msg7_resp:4;
+ u8 msg7_code[12];
+ u8 msg7_pad[2];
+ u8 msg8_func;
+ u8 msg8_unknown:4, msg8_resp:4;
+ u8 msg8_code[12];
+ u8 msg8_pad[2];
+ u8 bot_id[16];
+ u8 bot_std;
+ u8 bot_long;
+ u8 unknown7e2[14];
+ u8 eot_id[16];
+ u8 eot_std;
+ u8 eot_long;
+} fivetone;
+#seekto 0x01820;
+struct {
+ u8 type;
+ u8 code[5];
+ u8 delimiter;
+ u8 standard;
+ u8 tone_long;
+ u8 unknown9[7];
+ u8 data[16];
+ u8 name[16];
+} ft_special[32];
+
+// Tag 0x04, slot 0x2000: radio settings.
+#seekto 0x02000;
+struct {
+ u8 poweron_type;
+ char line1[14];
+ char line2[14];
+ u8 unknown1d:7, allow_reset:1;
+ u8 auto_power_off;
+ u8 unknown1f;
+ u8 radio_silent:1, key_tone:1, sms_alert:1, group_call_tone:1,
+ private_call_tone:1, call_end_tone:1, talk_permit_tone:1,
+ startup_sound:1;
+ u8 voice_prompt:1, battery_low:1, tx_end_tone:2, unknown21:4;
+} set_power;
+#seekto 0x02030;
+struct {
+ u8 backlight;
+ u8 auto_backlight;
+ u8 menu_exit;
+ u8 unknown33a:3, volume_prompt:1, date_format:1, unknown33b:2,
+ time_display:1;
+ u8 call_color;
+ u8 standby_color;
+ u8 tx_backlight;
+ u8 rx_backlight;
+ u8 a_name_color;
+ u8 b_name_color;
+ u8 a_zone_color;
+ u8 b_zone_color;
+} set_display;
+#seekto 0x02040;
+struct {
+ u8 unknown40:1, gps_format:1, speed_unit:2, gps_mode:2, distance_unit:1,
+ gps_switch:1;
+ u8 time_zone;
+ u8 measure_period;
+ u8 unknown43[2];
+ u8 unknown45:5, record_type:2, record_switch:1;
+} set_gps;
+#seekto 0x02060;
+struct {
+ u8 unknown60:6, group_match:1, private_match:1;
+ u8 call_hold;
+ u8 active_wait;
+ u8 active_retries;
+ u8 pre_carrier;
+ u8 monitor_decode:1, disable_decode:1, check_decode:1, enable_decode:1,
+ alert_decode:1, data_service:2, missed_call_alert:1;
+ u8 monitor_time;
+ u8 name_format:2, unknown67a:2, send_tx_name:1, name_priority:1,
+ unknown67b:2;
+} set_dmr;
+#seekto 0x02080;
+struct {
+ u8 dual_watch:2, main_line:1, b_display:1, a_display:1, b_mode:1,
+ a_mode:1, only_channel:1;
+ u8 dual_watch_hang;
+ u8 unknown82[3];
+ u8 unknown85:4, forbid_lock:1, side_lock:1, knob_lock:1, lock_mode:1;
+ u8 lock_delay;
+ u8 key_sk1_short;
+ u8 key_sk1_long;
+ u8 key_sk2_short;
+ u8 key_sk2_long;
+ u8 key_tk_short;
+ u8 key_tk_long;
+ u8 key_p1_short;
+ u8 key_p1_long;
+ u8 key_p2_short;
+ u8 key_p2_long;
+ u8 key_p3_short;
+ u8 key_p3_long;
+ u8 long_press;
+} set_work;
+#seekto 0x020a0;
+struct {
+ u8 tot;
+ u8 tot_pre;
+ u8 vox_level;
+ u8 vox_delay;
+ u8 power_save:4, unknowna4:1, weather_alarm:1, language:1,
+ disable_leds:1;
+ u8 tbst:4, unknowna5:2, tail_mode:2;
+ u8 mic_analog;
+ u8 mic_digital;
+} set_opts;
+#seekto 0x02301;
+struct {
+ u8 send_interval;
+ u8 unknown302:7, fixed_beacon:1;
+ u8 unknown303[3];
+ char latitude[9];
+ u8 lat_hemi;
+ char longitude[9];
+ u8 lon_hemi;
+ u8 unknown31a[4];
+ ul16 report_channel[8];
+ u8 unknown32e[2];
+ u8 active_delay;
+ u8 unknown331:7, call_type:1;
+ ul24 upload_number;
+} set_aprs;
+#seekto 0x02500;
+struct {
+ u8 unknown500:6, new_zone:1, zone_list:1;
+ u8 unknown501:2, measure_period:1, radio_disable:1, radio_enable:1,
+ remote_monitor:1, radio_check:1, call_alert:1;
+ u8 display_mode:1, match_group:1, match_private:1, lang_select:1,
+ start_display:1, tx_power:1, alert_tone:1, talkaround:1;
+ u8 unknown503a:1, record:1, aprs:1, gps:1, power_save:1,
+ sub_channel_mode:1, unknown503b:2;
+ u8 unknown504:1, csv_contacts:1, manual_dial:1, functionality:1,
+ send_message:1, del_contact:1, edit_contact:1, add_contact:1;
+ u8 unknown505:4, del_log:1, sent_call:1, answered_call:1, missed_call:1;
+ u8 radio_name:1, radio_id:1, time_slot:1, color_code:1, tx_contact:1,
+ ctc_dcs:1, tx_freq:1, rx_freq:1;
+ u8 unknown507:3, channel_name:1, add_channel:1, rx_group:1,
+ tdma_direct:1, channel_type:1;
+} set_menu;
+
+// Tag 0x06, slot 0x3000: DTMF (BDC1200 from +0xA20 is not mapped).
+#seekto 0x03000;
+struct {
+ u8 code1[16];
+ u8 code2[16];
+ u8 code3[16];
+ u8 code4[16];
+ u8 code5[16];
+ u8 code6[16];
+ u8 code7[16];
+ u8 code8[16];
+ u8 code9[16];
+ u8 code10[16];
+ u8 code11[16];
+ u8 code12[16];
+ u8 code13[16];
+ u8 code14[16];
+ u8 code15[16];
+ u8 code16[16];
+ u8 pre_carrier;
+ u8 first_digit;
+ u8 duration;
+ u8 interval;
+ u8 auto_reset;
+ u8 unknown105:7, side_tone:1;
+ u8 self_id[3];
+ u8 group_code;
+ u8 interval_sign;
+ u8 auto_answer;
+ u8 ptt_id_pause;
+ u8 unknown10d;
+ u8 min_duration;
+ u8 unknown10f;
+ u8 ptt_id_up[16];
+ u8 ptt_id_down[16];
+ u8 stun_code[16];
+ u8 kill_code[16];
+} dtmf;
+#seekto 0x031ff;
+u8 dtmf_contact_count;
+struct {
+ char name[16];
+ u8 number[5];
+ u8 unknown[11];
+} dtmf_contacts[64];
+
+// Tags 0x12-0x41, slots 0x09000-0x38fff: channels. Page 0 starts with
+// the channel count; 84 channels on page 0, 85 on the others.
+#seekto 0x09000;
+ul16 ch_count;
+#seekto 0x09010;
+struct chan page0[84];
+#seekto 0x0a000;
+struct chan page1[85];
+#seekto 0x0b000;
+struct chan page2[85];
+#seekto 0x0c000;
+struct chan page3[85];
+#seekto 0x0d000;
+struct chan page4[85];
+#seekto 0x0e000;
+struct chan page5[85];
+#seekto 0x0f000;
+struct chan page6[85];
+#seekto 0x10000;
+struct chan page7[85];
+#seekto 0x11000;
+struct chan page8[85];
+#seekto 0x12000;
+struct chan page9[85];
+#seekto 0x13000;
+struct chan page10[85];
+#seekto 0x14000;
+struct chan page11[85];
+#seekto 0x15000;
+struct chan page12[85];
+#seekto 0x16000;
+struct chan page13[85];
+#seekto 0x17000;
+struct chan page14[85];
+#seekto 0x18000;
+struct chan page15[85];
+#seekto 0x19000;
+struct chan page16[85];
+#seekto 0x1a000;
+struct chan page17[85];
+#seekto 0x1b000;
+struct chan page18[85];
+#seekto 0x1c000;
+struct chan page19[85];
+#seekto 0x1d000;
+struct chan page20[85];
+#seekto 0x1e000;
+struct chan page21[85];
+#seekto 0x1f000;
+struct chan page22[85];
+#seekto 0x20000;
+struct chan page23[85];
+#seekto 0x21000;
+struct chan page24[85];
+#seekto 0x22000;
+struct chan page25[85];
+#seekto 0x23000;
+struct chan page26[85];
+#seekto 0x24000;
+struct chan page27[85];
+#seekto 0x25000;
+struct chan page28[85];
+#seekto 0x26000;
+struct chan page29[85];
+#seekto 0x27000;
+struct chan page30[85];
+#seekto 0x28000;
+struct chan page31[85];
+#seekto 0x29000;
+struct chan page32[85];
+#seekto 0x2a000;
+struct chan page33[85];
+#seekto 0x2b000;
+struct chan page34[85];
+#seekto 0x2c000;
+struct chan page35[85];
+#seekto 0x2d000;
+struct chan page36[85];
+#seekto 0x2e000;
+struct chan page37[85];
+#seekto 0x2f000;
+struct chan page38[85];
+#seekto 0x30000;
+struct chan page39[85];
+#seekto 0x31000;
+struct chan page40[85];
+#seekto 0x32000;
+struct chan page41[85];
+#seekto 0x33000;
+struct chan page42[85];
+#seekto 0x34000;
+struct chan page43[85];
+#seekto 0x35000;
+struct chan page44[85];
+#seekto 0x36000;
+struct chan page45[85];
+#seekto 0x37000;
+struct chan page46[85];
+#seekto 0x38000;
+struct chan page47[6];
+
+// VFO A and B, back to back in the last channel page.
+#seekto 0x38f9f;
+struct chan vfo0;
+struct chan vfo1;
+
+// Tags 0x5C-0x64, slots 0x40000-0x48fff: zones. Header bytes 1/3: position
+// in the zone shown on lines A/B, bytes 5/7: the zone for A/B.
+#seekto 0x40000;
+struct {
+ u8 count;
+ u8 a_pos;
+ u8 unknown2;
+ u8 b_pos;
+ u8 unknown4;
+ u8 a_zone;
+ u8 unknown6;
+ u8 b_zone;
+} zone_hdr;
+#seekto 0x40010;
+struct zone zpage0[28];
+#seekto 0x41000;
+struct zone zpage1[28];
+#seekto 0x42000;
+struct zone zpage2[28];
+#seekto 0x43000;
+struct zone zpage3[28];
+#seekto 0x44000;
+struct zone zpage4[28];
+#seekto 0x45000;
+struct zone zpage5[28];
+#seekto 0x46000;
+struct zone zpage6[28];
+#seekto 0x47000;
+struct zone zpage7[28];
+#seekto 0x48000;
+struct zone zpage8[28];
+"""
+
+# Radio settings on tag 0x04, from the CPS option dialogs (0x446770 power
+# on, 0x4388d0 tones, 0x440260 display, 0x4656a0 work mode, 0x444f60
+# options). Each entry: (struct, field, label, kind, extra). kind 'list':
+# stored value = index (+ extra[1] offset); 'bool'; 'text' (length).
+_SECONDS = ['%d s' % i for i in range(1, 31)]
+_COLORS = ['White', 'Black', 'Orange', 'Red', 'Yellow', 'Green', 'Cyan',
+ 'Blue'] # [DisplayColor]
+RADIO_SETTINGS = [
+ ('Power on', [
+ ('set_power', 'poweron_type', 'Power-on screen',
+ 'list', (['Power On Picture', 'Custom Message', 'Battery Volt'], 0)),
+ ('set_power', 'line1', 'Power-on text line 1', 'text', 14),
+ ('set_power', 'line2', 'Power-on text line 2', 'text', 14),
+ ('set_power', 'auto_power_off', 'Auto power off',
+ 'list', (['Off', '30 min', '60 min', '120 min', '240 min',
+ '480 min'], 0)),
+ ('set_power', 'allow_reset', 'Allow reset', 'bool', None),
+ ]),
+ ('Tones', [
+ ('set_power', 'key_tone', 'Key tone', 'bool', None),
+ ('set_power', 'voice_prompt', 'Voice prompt', 'bool', None),
+ ('set_power', 'startup_sound', 'Startup sound', 'bool', None),
+ ('set_power', 'battery_low', 'Battery low alert', 'bool', None),
+ ('set_power', 'talk_permit_tone', 'Talk permit tone', 'bool', None),
+ ('set_power', 'call_end_tone', 'Call end tone', 'bool', None),
+ ('set_power', 'group_call_tone', 'Group call tone', 'bool', None),
+ ('set_power', 'private_call_tone', 'Private call tone', 'bool',
+ None),
+ ('set_power', 'sms_alert', 'SMS alert', 'bool', None),
+ ('set_power', 'radio_silent', 'Radio silent', 'bool', None),
+ ('set_power', 'tx_end_tone', 'Analog TX end tone',
+ 'list', (['Off', 'Tone', 'BDC'], 0)),
+ ]),
+ ('Display', [
+ ('set_display', 'backlight', 'Backlight brightness',
+ 'list', ([str(i) for i in range(1, 7)], 0)),
+ ('set_display', 'menu_exit', 'Menu exit time',
+ 'list', (['Off'] + ['%d s' % i for i in range(5, 61, 5)], 0)),
+ ('set_display', 'tx_backlight', 'TX backlight delay',
+ 'list', (['Off'] + _SECONDS, 0)),
+ ('set_display', 'rx_backlight', 'RX backlight delay',
+ 'list', (['Always'] + _SECONDS, 0)),
+ ('set_display', 'time_display', 'Time display', 'bool', None),
+ ('set_display', 'date_format', 'Date format',
+ 'list', (['yyyy/m/d', 'd/m/yyyy'], 0)),
+ ('set_display', 'volume_prompt', 'Volume change prompt', 'bool',
+ None),
+ ('set_display', 'call_color', 'Call display colour',
+ 'list', (_COLORS, 0)),
+ ('set_display', 'standby_color', 'Standby text colour',
+ 'list', (_COLORS, 0)),
+ ('set_display', 'a_name_color', 'Channel name colour (A)',
+ 'list', (_COLORS, 0)),
+ ('set_display', 'b_name_color', 'Channel name colour (B)',
+ 'list', (_COLORS, 0)),
+ ('set_display', 'a_zone_color', 'Zone colour (A)',
+ 'list', (_COLORS, 0)),
+ ('set_display', 'b_zone_color', 'Zone colour (B)',
+ 'list', (_COLORS, 0)),
+ ]),
+ ('Work mode', [
+ ('set_work', 'only_channel', 'Only channel mode', 'bool', None),
+ ('set_work', 'dual_watch', 'Dual watch',
+ 'list', (['Single Mode', 'Double Wait', 'Single Wait'], 0)),
+ ('set_work', 'dual_watch_hang', 'Dual watch hang time',
+ 'list', (['%d ms' % i for i in range(0, 6501, 500)], 0)),
+ ]),
+ ('Options', [
+ ('set_opts', 'tot', 'TX timeout (TOT)',
+ 'list', (['Off'] + ['%d s' % i for i in range(15, 496, 5)], 0)),
+ ('set_opts', 'tot_pre', 'TOT pre-alert',
+ 'list', (['Off'] + ['%d s' % i for i in range(1, 11)], 0)),
+ ('set_opts', 'vox_level', 'VOX level',
+ 'list', ([str(i) for i in range(1, 6)], 0)),
+ ('set_opts', 'vox_delay', 'VOX delay',
+ 'list', (['%.1f s' % (i / 10) for i in range(3, 51)], 3)),
+ ('set_opts', 'language', 'Language',
+ 'list', (['Chinese', 'English'], 0)),
+ ('set_opts', 'power_save', 'Power save',
+ 'list', (['None', '1:1', '1:2', '1:4'], 0)),
+ ('set_opts', 'tail_mode', 'Tail noise reduction',
+ 'list', (['None', '120', '180', '55 Hz'], 0)),
+ ('set_opts', 'tbst', 'TBST (tone burst)',
+ 'list', (['1000 Hz', '1450 Hz', '1750 Hz', '2100 Hz'], 0)),
+ ('set_opts', 'mic_analog', 'Analog mic level',
+ 'list', ([str(i) for i in range(1, 6)], 0)),
+ ('set_opts', 'disable_leds', 'Disable all LEDs', 'bool', None),
+ ('set_opts', 'weather_alarm', 'Weather alarm', 'bool', None),
+ ]),
+]
+_KEY_FUNCS = [
+ 'None', 'Power Select', 'Volt', 'Talkaround', 'Digital Encrypt', 'Call',
+ 'VOX', 'V/M', 'Alarm', 'One Touch Call 1', 'One Touch Call 2',
+ 'One Touch Call 3', 'One Touch Call 4', 'One Touch Call 5', 'SMS',
+ 'Contacts', 'Zone Up', 'Zone Down', 'Scan', 'Record Switch',
+ 'Previous Record', 'Next Record', 'FM Radio', 'FM Search',
+ 'GPS Information', 'Monitor', 'Switch Main Channel', 'Lone Work',
+ 'Keypad Lock', 'Nuisance Channel Delete', 'TBST Send', 'APRS Send',
+ 'Channel Type', 'Display Mode', 'CTC Scan', 'CTC Setting', 'Silent Tone',
+ 'Roaming', 'Sub-PTT', 'Analog Scramble Switch', 'One Key Scan Freq',
+ 'Flashlight', 'Man Down Alarm'] # [KeyFuncData]
+_UTC = ['UTC %+d:00' % h if h else 'UTC' for h in range(-12, 14)]
+_ONOFF = (['Off', 'On'], 0)
+# Which key owns which byte comes from the CPS keys dialog (0x430760: the
+# accessor that fills each control, and 0x430600: the control's label).
+RADIO_SETTINGS.append(('Keys', [
+ ('set_work', 'lock_mode', 'Keypad lock',
+ 'list', (['Manual', 'Auto'], 0)),
+ ('set_work', 'lock_delay', 'Auto keypad lock delay',
+ 'list', (['%d s' % i for i in range(5, 61)], 0)),
+ ('set_work', 'knob_lock', 'Knob lock', 'list', _ONOFF),
+ ('set_work', 'side_lock', 'Side key lock', 'list', _ONOFF),
+ ('set_work', 'forbid_lock', 'Forbid lock key', 'list', _ONOFF),
+ ('set_work', 'long_press', 'Long press time',
+ 'list', ([str(i) for i in range(1, 6)], 0)),
+] + [('set_work', 'key_%s_%s' % (k, p), '%s %s press' % (k.upper(), p),
+ 'list', (_KEY_FUNCS, 0))
+ for k in ('sk1', 'sk2', 'tk', 'p1', 'p2', 'p3')
+ for p in ('short', 'long')]))
+RADIO_SETTINGS.append(('DMR', [
+ ('set_dmr', 'private_match', 'Private call match', 'bool', None),
+ ('set_dmr', 'group_match', 'Group call match', 'bool', None),
+ ('set_dmr', 'call_hold', 'Call hold time',
+ 'list', (['%d s' % i for i in range(1, 61)], 0)),
+ ('set_dmr', 'active_wait', 'Active wait time',
+ 'list', (['%d ms' % i for i in range(300, 4801, 30)], 1)),
+ ('set_dmr', 'active_retries', 'Active retries',
+ 'list', ([str(i) for i in range(1, 9)], 1)),
+ ('set_dmr', 'pre_carrier', 'Pre-carrier time',
+ 'list', (['%d ms' % i for i in range(120, 8641, 120)], 0)),
+ ('set_dmr', 'monitor_time', 'Remote monitor time',
+ 'list', (['%d s' % i for i in range(10, 121, 10)], 0)),
+ ('set_dmr', 'data_service', 'SMS format',
+ 'list', (['H-SMS', 'M-SMS', 'D-SMS'], 0)),
+ ('set_dmr', 'missed_call_alert', 'Missed call alert', 'bool', None),
+ ('set_dmr', 'monitor_decode', 'Remote monitor decode', 'bool', None),
+ ('set_dmr', 'disable_decode', 'Radio disable decode', 'bool', None),
+ ('set_dmr', 'check_decode', 'Radio check decode', 'bool', None),
+ ('set_dmr', 'enable_decode', 'Radio enable decode', 'bool', None),
+ ('set_dmr', 'alert_decode', 'Call alert decode', 'bool', None),
+ ('set_dmr', 'name_format', 'Name data format',
+ 'list', (['ISO 8 bit', '16 bit Unicode'], 0)),
+ ('set_dmr', 'send_tx_name', 'Send TX name', 'bool', None),
+ ('set_dmr', 'name_priority', 'Name display priority',
+ 'list', (['Contact', 'Name'], 0)),
+]))
+RADIO_SETTINGS.append(('GPS and recording', [
+ ('set_gps', 'gps_switch', 'GPS', 'bool', None),
+ ('set_gps', 'gps_mode', 'GPS mode',
+ 'list', (['GPS', 'BDS', 'GPS+BDS'], 0)),
+ ('set_gps', 'time_zone', 'Time zone', 'list', (_UTC, 0)),
+ ('set_gps', 'measure_period', 'GPS measure period',
+ 'list', (['%d s' % i for i in range(5, 256)], 0)),
+ ('set_gps', 'distance_unit', 'Distance unit',
+ 'list', (['Metric', 'Imperial'], 0)),
+ ('set_gps', 'speed_unit', 'Speed unit',
+ 'list', (['km/h', 'mph', 'knots'], 0)),
+ ('set_gps', 'gps_format', 'GPS display format',
+ 'list', (['Degrees', 'Degrees/min/sec'], 0)),
+ ('set_gps', 'record_switch', 'Recording', 'bool', None),
+ ('set_gps', 'record_type', 'Recording type',
+ 'list', (['Receive', 'Transmit', 'Receive+Transmit'], 0)),
+]))
+# APRS (CPS dialog 0x439c00, accessors 0x488580-0x488cb0). The radio
+# reports its position over DMR: to the "upload number" (a DMR ID) as a
+# private or group call, on one of 8 report channels chosen per channel.
+# Coordinates are 9 ASCII characters, e.g. "23.000000" / "118.00000"; the
+# hemisphere is separate.
+RADIO_SETTINGS.append(('APRS', [
+ ('set_aprs', 'send_interval', 'Scheduled send time',
+ 'list', (['Off'] + ['%d s' % i for i in range(30, 7201, 30)], 0)),
+ ('set_aprs', 'fixed_beacon', 'Fixed beacon (use the position below)',
+ 'bool', None),
+ ('set_aprs', 'latitude', 'Latitude (degrees)', 'coord', 90),
+ ('set_aprs', 'lat_hemi', 'Latitude N/S', 'list', (['N', 'S'], 0)),
+ ('set_aprs', 'longitude', 'Longitude (degrees)', 'coord', 180),
+ ('set_aprs', 'lon_hemi', 'Longitude E/W', 'list', (['E', 'W'], 0)),
+ ('set_aprs', 'upload_number', 'Upload number (DMR ID, 0 = none)',
+ 'int', (0, DMR_ID_MAX)),
+ ('set_aprs', 'call_type', 'Call type',
+ 'list', (['Private', 'Group'], 0)), # [AprsCallType]
+ ('set_aprs', 'active_delay', 'Repeater active delay',
+ 'list', (['Off'] + ['%d ms' % i for i in range(100, 1001, 100)], 0)),
+] + [('set_aprs', 'report_channel', 'Report channel %d' % (i + 1),
+ 'channel', i) for i in range(8)]))
+
+
+_MS = '%d ms'
+RADIO_SETTINGS.append(('DTMF', [
+ ('dtmf', 'self_id', 'Self ID code', 'digits', 3),
+ ('dtmf', 'ptt_id_up', 'PTT ID up code (BOT)', 'dtmf', 16),
+ ('dtmf', 'ptt_id_down', 'PTT ID down code (EOT)', 'dtmf', 16),
+ ('dtmf', 'stun_code', 'Stun code', 'dtmf', 16),
+ ('dtmf', 'kill_code', 'Kill code', 'dtmf', 16),
+ ('dtmf', 'group_code', 'Group code', 'list', ( # [DtmfGroupCode]
+ ['Off', 'A', 'B', 'C', 'D', '*', '#'], [0xFF] + list(range(10, 16)))),
+ ('dtmf', 'interval_sign', 'DTMF interval sign', 'list', (
+ ['A', 'B', 'C', 'D', '*', '#'], 10)), # [DtmfIntervalSign]
+ ('dtmf', 'auto_answer', 'Auto answer', 'list', ( # [DtmfAutoAck]
+ ['Off', 'Alert Tone', 'Alert Tone And Ack'], 0)),
+ ('dtmf', 'side_tone', 'Side tone', 'bool', None),
+ ('dtmf', 'pre_carrier', 'Pre-carrier time', 'list', (
+ [_MS % i for i in range(300, 5001, 50)], 15)),
+ ('dtmf', 'first_digit', 'First digit time', 'list', (
+ [_MS % i for i in range(100, 1001, 50)], 0)),
+ ('dtmf', 'duration', 'Send DTMF duration', 'list', (
+ [_MS % i for i in range(80, 2001, 10)], 0)),
+ ('dtmf', 'interval', 'Send DTMF interval', 'list', (
+ [_MS % i for i in range(80, 2001, 10)], 0)),
+ ('dtmf', 'min_duration', 'Dial code minimum duration', 'list', (
+ [_MS % i for i in range(25, 2501, 25)], 0)),
+ ('dtmf', 'auto_reset', 'Auto reset time', 'list', (
+ ['%d s' % i for i in range(1, 256)], 1)),
+ ('dtmf', 'ptt_id_pause', 'PTT ID pause time', 'list', (
+ ['Off'] + ['%d s' % i for i in range(5, 76)],
+ [0] + list(range(5, 76)))),
+] + [('dtmf', 'code%d' % i, 'DTMF code %d' % i, 'dtmf', 16)
+ for i in range(1, DTMF_CODES + 1)]))
+
+
+def _tenths(first, last, unit='s'):
+ return ['%.1f %s' % (i / 10, unit) for i in range(first, last + 1)]
+
+
+RADIO_SETTINGS.append(('Two-tone', [
+ ('twotone', 'freq_a', 'Tone A frequency (Hz)', 'hz', TT_HZ),
+ ('twotone', 'freq_b', 'Tone B frequency (Hz)', 'hz', TT_HZ),
+ ('twotone', 'freq_c', 'Tone C frequency (Hz)', 'hz', TT_HZ),
+ ('twotone', 'freq_d', 'Tone D frequency (Hz)', 'hz', TT_HZ),
+ ('twotone', 'pre_carrier', 'Pre-carrier time', 'list',
+ (_tenths(0, 50), 0)),
+ ('twotone', 'first_tone', 'First tone duration', 'list',
+ (_tenths(5, 40), 5)),
+ ('twotone', 'second_tone', 'Second tone duration', 'list',
+ (_tenths(5, 40), 5)),
+ ('twotone', 'long_tone', 'Long tone duration', 'list',
+ (_tenths(5, 100), 5)),
+ ('twotone', 'interval', 'Interval time', 'list', (_tenths(0, 20), 0)),
+ ('twotone', 'polite_wait', 'Polite wait time', 'list',
+ (_tenths(0, 50), 0)),
+ ('twotone', 'auto_reset', 'Auto reset time', 'list', (
+ ['%d s' % i for i in range(1, 256)], 1)),
+ ('twotone', 'idle_ack', 'Idle ack', 'bool', None),
+ ('twotone', 'side_tone', 'Side tone', 'bool', None),
+] + [entry for i in range(1, TT_DECODE + 1) for entry in (
+ ('twotone', 'dec%d_format' % i, 'Decode %d: format' % i, 'list',
+ (TT_DECODE_FORMATS, TT_DECODE_CODES)),
+ ('twotone', 'dec%d_call' % i, 'Decode %d: call type' % i, 'list', (
+ ['None', 'Call Alert', 'Voice Call Alert', 'Select Call'], 0)),
+ ('twotone', 'dec%d_reply' % i, 'Decode %d: reply' % i, 'bool', None))]))
+
+
+_RESPONSES = ['None', 'Alert Tone', 'Alert Tone And ACK']
+RADIO_SETTINGS.append(('Five-tone', [
+ ('fivetone', 'self_id', 'Self ID code', 'hex', 5),
+ ('fivetone', 'decode_std', 'Decode standard', 'list', (FT_STANDARDS, 0)),
+ ('fivetone', 'decode_resp', 'Decode response', 'list', (_RESPONSES, 0)),
+ ('fivetone', 'pre_carrier', 'Pre-carrier time', 'list', (
+ [_MS % i for i in range(300, 5001, 50)], 15)),
+ ('fivetone', 'auto_reset', 'Auto reset time', 'list', (
+ ['%d s' % i for i in range(1, 256)], 1)),
+ ('fivetone', 'send_delay', 'Delay time after send code', 'list', (
+ [_MS % i for i in range(10, 2551, 10)], 1)),
+ ('fivetone', 'ptt_id_pause', 'PTT ID pause time', 'list', (
+ ['Off'] + ['%d s' % i for i in range(5, 76)],
+ [0] + list(range(5, 76)))),
+ ('fivetone', 'first_delay', 'First delay time', 'list', (
+ [str(i) for i in range(10, 2551, 10)], 1)),
+ ('fivetone', 'side_tone', 'Side tone', 'bool', None),
+ ('fivetone', 'bot_id', 'PTT ID start (BOT): encode ID', 'hex', 16),
+ ('fivetone', 'bot_std', 'PTT ID start (BOT): standard', 'list',
+ (FT_STANDARDS, 0)),
+ ('fivetone', 'bot_long', 'PTT ID start (BOT): tone long', 'list',
+ FT_TONE_LONG),
+ ('fivetone', 'eot_id', 'PTT ID end (EOT): encode ID', 'hex', 16),
+ ('fivetone', 'eot_std', 'PTT ID end (EOT): standard', 'list',
+ (FT_STANDARDS, 0)),
+ ('fivetone', 'eot_long', 'PTT ID end (EOT): tone long', 'list',
+ FT_TONE_LONG),
+] + [entry for i in range(1, FT_MSG + 1) for entry in (
+ ('fivetone', 'msg%d_code' % i, 'Message code %d: code' % i, 'hex', 12),
+ ('fivetone', 'msg%d_func' % i, 'Message code %d: function' % i, 'list', (
+ ['Squelch', 'All Call', 'Emergency Alarm', 'Stun', 'Kill', 'Wake Up',
+ 'Group Call'], 0)), # [FiveToneMsgCodeFunc]
+ ('fivetone', 'msg%d_resp' % i, 'Message code %d: response' % i, 'list',
+ (_RESPONSES, 0)))]))
+
+
+def _pick(options, value):
+ return RadioSettingValueList(options, current_index=options.index(value))
+
+
+def _list_index(stored, offset):
+ """List position of a stored value; offset is added to the position,
+ or is the list of stored values."""
+ if isinstance(offset, list):
+ return offset.index(stored) if stored in offset else -1
+ return stored - offset
+
+
+def _list_stored(index, offset):
+ return offset[index] if isinstance(offset, list) else index + offset
+
+
+def _parse_hz(text, limits, label):
+ """'321.7' -> 3217 (0.1 Hz), within limits."""
+ try:
+ tenths = round(float(text) * 10)
+ except ValueError:
+ tenths = -1
+ if not limits[0] <= tenths <= limits[1]:
+ raise errors.InvalidValueError('%s must be %.1f to %.1f Hz' % (
+ label, limits[0] / 10, limits[1] / 10))
+ return tenths
+
+
+def _dtmf_text(raw, chars=DTMF_CHARS):
+ """Code bytes (digit values, 0xFF-terminated) -> text."""
+ text = ''
+ for b in raw:
+ if b >= len(chars):
+ break
+ text += chars[b]
+ return text
+
+
+def _dtmf_bytes(text, length, chars=DTMF_CHARS):
+ return bytes(chars.index(c) for c in text.upper()).ljust(length, b'\xFF')
+
+
+def _format_coord(value, limit):
+ """A coordinate as the CPS stores it (0x488750, 0x488950): 9 chars,
+ e.g. "05.500000", "23.000000", "118.00000"; at most `limit`."""
+ for decimals in (6, 5):
+ text = '%.*f' % (decimals, value)
+ if len(text) < 9:
+ text = '0' + text
+ if len(text) == 9:
+ break
+ if float(text) >= limit:
+ text = '%.*f' % (6 if limit < 100 else 5, limit)
+ return text
+
+
+def _parse_coord(raw):
+ """Stored coordinate bytes -> text as the CPS shows it, or ''."""
+ text = raw.split(b'\x00')[0].split(b'\xFF')[0].decode('latin-1')
+ try:
+ float(text)
+ except ValueError:
+ return ''
+ return text[1:] if text.startswith('0') and len(text) > 1 else text
+
+
+_MENU = [
+ ('zone_list', 'Zone list'), ('new_zone', 'New zone'),
+ ('call_alert', 'Call alert'), ('radio_check', 'Radio check'),
+ ('remote_monitor', 'Remote monitor'), ('radio_enable', 'Radio enable'),
+ ('radio_disable', 'Radio disable'), ('measure_period', 'Measure period'),
+ ('talkaround', 'Talkaround'), ('alert_tone', 'Alert tone'),
+ ('tx_power', 'TX power'), ('start_display', 'Start display'),
+ ('lang_select', 'Language'), ('match_private', 'Match private'),
+ ('match_group', 'Match group'), ('display_mode', 'Display mode'),
+ ('sub_channel_mode', 'Sub channel mode'), ('power_save', 'Power save'),
+ ('gps', 'GPS'), ('aprs', 'APRS'), ('record', 'Record'),
+ ('add_contact', 'Add contact'), ('edit_contact', 'Edit contact'),
+ ('del_contact', 'Delete contact'), ('send_message', 'Send message'),
+ ('functionality', 'Functionality'), ('manual_dial', 'Manual dial'),
+ ('csv_contacts', 'CSV contacts'), ('missed_call', 'Missed calls'),
+ ('answered_call', 'Answered calls'), ('sent_call', 'Sent calls'),
+ ('del_log', 'Delete call log'), ('rx_freq', 'RX frequency'),
+ ('tx_freq', 'TX frequency'), ('ctc_dcs', 'CTC/DCS'),
+ ('tx_contact', 'TX contact'), ('color_code', 'Color code'),
+ ('time_slot', 'Time slot'), ('radio_id', 'Radio ID'),
+ ('radio_name', 'Radio name'), ('channel_type', 'Channel type'),
+ ('tdma_direct', 'TDMA direct mode'), ('rx_group', 'RX group list'),
+ ('add_channel', 'Add channel'), ('channel_name', 'Channel name')]
+RADIO_SETTINGS.append(('Menu items', [
+ ('set_menu', f, 'Menu: %s' % label, 'bool', None) for f, label in _MENU]))
+
+# Bits of 0x80 that follow the radio's current display (A/B mode, display
+# mode, main line); upload keeps the radio's own values for these.
+WORK_STATE_MASK = 0x3E
+
+
+def zone_offset(z):
+ """(page, index) of zone z (1-250), as the CPS computes it (0x482830)."""
+ return (z - 1) // ZONE_PER_PAGE, (z - 1) % ZONE_PER_PAGE
+
+
+def channel_offset(n):
+ """(page, index) of channel n, as the CPS computes it (0x47dcc0)."""
+ if n < CH_PER_PAGE:
+ return 0, n - 1
+ return n // CH_PER_PAGE, n % CH_PER_PAGE
+
+
+CHTYPES = ['Analog', 'Digital', 'Fixed Analog', 'Fixed Digital']
+# Value lists of the channel options, from the CPS language file sections
+# (in brackets); the stored field is the index.
+LIST_EXTRAS = {
+ 'rx_squelch_mode': ('RX squelch mode', [ # [RxSquelchMode]
+ 'Carrier/CTC', 'Optional Signaling', 'CTC & Optional Signaling',
+ 'CTC | Optional Signaling']),
+ 'signaling': ('Signaling type', [ # [ChannelSignalingType]
+ 'None', 'DTMF', 'Two Tone', 'Five Tone', 'BDC1200']),
+ 'ptt_id': ('PTT ID', ['Off', 'BOT', 'EOT', 'Both']), # [ChannelPttId]
+ # [ChannelAprsReport]
+ 'aprs_report': ('APRS report (DMR)', ['Off', 'Digital']),
+ # one of the 8 report channels of the APRS settings
+ 'aprs_channel': ('APRS report channel', [str(i) for i in range(1, 9)]),
+ # which two-tone (1-8) or BDC1200 (1-4) entry, per signaling type
+ # (CPS 0x414470)
+ 'rx_signal': ('RX signaling system', ['None'] + [
+ str(i) for i in range(1, 9)]),
+ 'tx_signal': ('TX signaling system', ['None'] + [
+ str(i) for i in range(1, 9)]),
+}
+# [ChAnaTxAdmit] for analog channels, [ChDigTxAdmit] for digital ones
+TX_ADMIT = {False: ['Allow TX', 'Channel Idle', 'Match CTC', 'Non Match CTC'],
+ True: ['Always', 'Channel Idle', 'Color Code Idle']}
+BOOL_EXTRAS = [
+ ('vox', 'VOX'),
+ ('compander', 'Compander'),
+ ('ptt_id_display', 'PTT ID display'),
+ ('lone_work', 'Lone worker'),
+ ('auto_scan', 'Auto scan'),
+ ('aprs_rx', 'APRS receive'),
+ ('aprs_ptt_analog', 'Analog APRS PTT mode'),
+ ('aprs_ptt_digital', 'Digital APRS PTT mode'),
+ ('emerg_indicator', 'Emergency indicator (DMR)'),
+ ('emerg_ack', 'Emergency ACK (DMR)'),
+ ('private_confirm', 'Private call confirm (DMR)'),
+ ('short_data_confirm', 'Short data confirm (DMR)'),
+ ('tdma_direct', 'TDMA direct mode (DMR)'),
+]
+# CTCSS: tenths of a Hz in BCD (88.5 Hz = 0x0885). DCS: 0x8000 plus the
+# code in BCD, 0x4000 if inverted (D754I = 0xC754). No tone: 0xFFFF.
+TONE_MODEL = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x8000, pol_mask=0x4000, tone_init=0xFFFF, tone_flag=0x0000,
+ dcs_enc_base=16, tone_enc_base=16)
+POWER_LEVELS = [chirp_common.PowerLevel('Low', watts=1),
+ chirp_common.PowerLevel('Middle', watts=2.5),
+ chirp_common.PowerLevel('High', watts=5)]
+STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0, 50.0, 100.0]
+
+
+# --- Serial link ------------------------------------------------------------
+
+def _garbled(message):
+ """A RadioError for a visibly corrupted reply, with cable advice."""
+ return errors.RadioError(message + '. ' + CABLE_ADVICE)
+
+
+def _bad_reply(message, got, expected):
+ """A RadioError for a reply header that isn't `expected`; with cable
+ advice if only bit 7 differs, the bad cables' signature."""
+ if len(got) == len(expected) and bytes(b & 0x7F for b in got) == expected:
+ return _garbled(message)
+ return errors.RadioError(message)
+
+
+class _Link:
+ def __init__(self, pipe):
+ self.pipe = pipe
+
+ def send(self, data):
+ time.sleep(0.01)
+ self.pipe.reset_input_buffer()
+ self.pipe.write(data)
+
+ def recv(self, n, timeout=0.5):
+ self.pipe.timeout = timeout
+ return self.pipe.read(n)
+
+ def xfer(self, data, n, timeout=0.5):
+ self.send(data)
+ resp = self.recv(n, timeout)
+ if len(resp) != n:
+ raise errors.RadioError('No reply from radio to %r' % data[:7])
+ return resp
+
+ def query_v(self, cmd):
+ """A V query: the reply is 'V', the index, a length, the data."""
+ self.send(cmd)
+ hdr = self.recv(3)
+ body = self.recv(hdr[2]) if len(hdr) == 3 else b''
+ if len(hdr) != 3 or hdr[0] != 0x56 or len(body) != hdr[2]:
+ raise _bad_reply('Bad reply to radio info query %s' % cmd.hex(),
+ hdr[:1], b'V')
+ return body
+
+ def read_block(self, addr, length, timeout=5.0):
+ cmd = b'R' + struct.pack('<I', addr)[:3] + struct.pack('<H', length)
+ self.send(cmd)
+ resp = self.recv(6 + length, timeout)
+ if len(resp) != 6 + length or resp[:6] != b'W' + cmd[1:6]:
+ raise _bad_reply('Bad reply reading flash at %06x' % addr,
+ resp[:6], b'W' + cmd[1:6])
+ return resp[6:]
+
+
+MODEL_ID = b'DP570UV' # PSEARCH reply of the DM-32UV
+TESTED_FIRMWARE = ('DM32.01.01.047',)
+
+
+def _search(link):
+ """Send PSEARCH; return the model ID the radio reports.
+
+ The radio sometimes ignores the first PSEARCH or two of a session, so
+ it is sent up to 5 times, as the vendor CPS does (0x44a210)."""
+ garbled = False
+ for _attempt in range(5):
+ link.send(b'PSEARCH')
+ resp = link.recv(8)
+ if len(resp) == 8 and resp[0] == 0x06:
+ if resp[1:].isascii():
+ return resp[1:]
+ garbled = True # the model ID is ASCII text
+ if garbled:
+ raise _garbled('Garbled reply from the radio')
+ raise errors.RadioError('Radio did not respond. Is it switched on '
+ 'and connected?')
+
+
+def _check_model(model):
+ if model != MODEL_ID:
+ raise errors.RadioError(
+ 'This radio identifies as %r, not as a Baofeng DM-32UV (%r)' % (
+ model.decode('ascii', 'replace'), MODEL_ID.decode()))
+
+
+PASSWORD_SET = 0xA5
+
+
+def _identify(link, writing=False):
+ _check_model(_search(link))
+ # PASSSTA: 'P', write password flag (settings 0x439), read password
+ # flag (0x43A). The radio doesn't enforce them; the vendor CPS asks for
+ # the password. CHIRP can't ask, so the driver refuses instead.
+ resp = link.xfer(b'PASSSTA', 3)
+ if resp[0] != ord('P'):
+ raise errors.RadioError('Unexpected reply to PASSSTA')
+ if resp[2] == PASSWORD_SET:
+ raise errors.RadioError(
+ 'The radio has a read password. CHIRP cannot enter passwords; '
+ 'remove it with the vendor programming software first')
+ if writing and resp[1] == PASSWORD_SET:
+ raise errors.RadioError(
+ 'The radio has a write password. CHIRP cannot enter passwords; '
+ 'remove it with the vendor programming software first')
+ if link.xfer(b'SYSINFO', 1) != b'\x06':
+ raise errors.RadioError('Radio refused SYSINFO')
+ link.query_v(b'V\x00\x00\x40\x0D')
+ info = {}
+ for i in range(1, 17):
+ if i != 12:
+ info[i] = link.query_v(b'V\x00\x00\x00' + bytes([i]))
+ start, end = struct.unpack('<II', info[10][:8])
+ if (start | end) >> 24 or start >= end:
+ raise errors.RadioError('Unexpected codeplug range from radio')
+ firmware = info[1].decode('ascii', 'replace')
+ if firmware not in TESTED_FIRMWARE:
+ LOG.warning('DM-32UV firmware %s has not been tested with this '
+ 'driver (tested: %s)', firmware,
+ ', '.join(TESTED_FIRMWARE))
+ return firmware, start, end
+
+
+def _enter_program(link):
+ if link.xfer(b'G\x00\x00\x00\x00\x01', 0x106)[0] != ord('S'):
+ raise errors.RadioError('Unexpected reply to G')
+ link.send(b'\xFF\xFF\xFF\xFF\x0C')
+ if link.xfer(b'PROGRAM', 1) != b'\x06':
+ raise errors.RadioError('Radio refused programming mode')
+ link.xfer(b'\x02', 8)
+ if link.xfer(b'\x06', 1) != b'\x06':
+ raise errors.RadioError('Radio did not acknowledge')
+
+
+def _scan(link, start, end, radio, status):
+ """Tag of every page: ({tag: [addresses]}, [free page addresses])."""
+ pages = list(range(start, end + 1 - PAGE + 1, PAGE))
+ where = collections.defaultdict(list)
+ for i, addr in enumerate(pages):
+ tag = link.read_block(addr + PAGE - 1, 1, timeout=0.5)[0]
+ if 0x80 <= tag < 0xFF:
+ # No page tag has bit 7 set (they go up to 0x7c); a bad cable
+ # sets it, which would make a page look missing.
+ raise _garbled('Implausible page tag %02x at %06x' % (
+ tag, addr))
+ where[tag].append(addr)
+ status.cur = i
+ radio.status_fn(status)
+ return where, where.pop(0xFF, [])
+
+
+def do_download(radio):
+ link = _Link(radio.pipe)
+ firmware, start, end = _identify(link)
+ LOG.info('DM-32UV firmware %s, codeplug %06x-%06x', firmware, start, end)
+ _enter_program(link)
+
+ status = chirp_common.Status()
+ status.msg = 'Scanning flash pages'
+ status.max = (end + 1 - start) // PAGE + len(IMAGE_TAGS)
+ where, _free = _scan(link, start, end, radio, status)
+
+ status.msg = 'Cloning from radio'
+ base = status.cur + 1
+ image = bytearray(b'\xFF' * (len(IMAGE_TAGS) * PAGE))
+ for i, tag in enumerate(IMAGE_TAGS):
+ if len(where.get(tag, [])) > 1:
+ LOG.warning('Radio has %d pages with tag %02x; using the first. '
+ 'Upload will refuse until the radio has tidied up.',
+ len(where[tag]), tag)
+ if where.get(tag):
+ data = link.read_block(where[tag][0], PAGE)
+ image[i * PAGE:(i + 1) * PAGE] = data
+ status.cur = base + i
+ radio.status_fn(status)
+ radio._metadata['dm32uv_firmware'] = firmware
+ return memmap.MemoryMapBytes(bytes(image))
+
+
+def _write_page(link, addr, data, start, end):
+ """Write one whole page with W, then read it back to check it.
+
+ The protocol has no checksums and the firmware doesn't verify writes,
+ so anything other than an ACK and an exact read-back stops the upload.
+ """
+ if (len(data) != PAGE or addr % PAGE or addr < start or
+ addr + PAGE - 1 > end or data[-1] in NEVER_WRITE):
+ raise errors.RadioError('Refusing unsafe write at %06x' % addr)
+ link.send(b'W' + struct.pack('<I', addr)[:3] + struct.pack('<H', PAGE) +
+ bytes(data))
+ ack = link.recv(1, timeout=5.0)
+ if ack != b'\x06' or link.read_block(addr, PAGE) != bytes(data):
+ raise errors.RadioError(
+ 'Writing the page at %06x failed (%s). Upload again, or restore '
+ 'the backup CHIRP saved before the upload' % (
+ addr, 'no acknowledgement' if ack != b'\x06' else
+ 'it did not read back as written'))
+
+
+def _zone_record(rec):
+ """(name bytes, [members]) of a raw 0x91-byte zone record."""
+ count = min(rec[16], ZONE_MEMBERS)
+ return (rec[:16].split(b'\x00')[0].split(b'\xFF')[0],
+ [int.from_bytes(rec[17 + 2 * i:19 + 2 * i], 'little')
+ for i in range(count)])
+
+
+def _follow_display(want, current, radio_zone, zones):
+ """Zone header bytes 1-7 for the upload.
+
+ Bytes 5/7 are the zone lines A/B show and bytes 1/3 the position in it.
+ They change whenever someone browses on the radio, so the radio's own
+ values are used, moved to where that zone and channel are in the new
+ list `zones` ([(name bytes, [members])]), in case zones were reordered
+ or deleted. radio_zone(z) gives zone z as the radio has it now.
+ """
+ want = bytearray(want)
+ want[1:8] = current[1:8]
+ for pos, zone in ((1, 5), (3, 7)):
+ z, old = current[zone], None
+ if 1 <= z <= ZONE_COUNT:
+ old = radio_zone(z)
+ new = None
+ if old:
+ new = next((i for i, zn in enumerate(zones, 1) if zn == old),
+ next((i for i, zn in enumerate(zones, 1)
+ if zn[0] == old[0]), None))
+ if new is None: # deleted, or unknown to the radio
+ new = z if not old and 1 <= z <= len(zones) else 1
+ members = zones[new - 1][1] if zones else []
+ p = current[pos]
+ if old: # follow the channel, or start over
+ channel = old[1][p - 1] if 1 <= p <= len(old[1]) else None
+ p = members.index(channel) + 1 if channel in members else 1
+ if not 1 <= p <= max(len(members), 1):
+ p = 1
+ want[zone], want[pos] = new, p
+ return bytes(want)
+
+
+def do_upload(radio):
+ """Write changed channel pages back to the radio, verifying each one.
+
+ A page is written to wherever the radio keeps that tag now, or to the
+ first free page if the radio has none yet. Pages that already match the
+ image are left alone, so an unchanged image writes nothing. Returns the
+ number of pages written.
+ """
+ image = radio.get_mmap().get_packed()
+ link = _Link(radio.pipe)
+ firmware, start, end = _identify(link, writing=True)
+ LOG.info('Upload to DM-32UV firmware %s', firmware)
+ _enter_program(link)
+
+ def radio_zone(z):
+ page, index = zone_offset(z)
+ addrs = where.get(ZONE_TAG0 + page)
+ if not addrs:
+ return None
+ return _zone_record(link.read_block(
+ addrs[0] + (0x10 if page == 0 else 0) + index * 0x91, 0x91))
+ zones = [(_name_bytes(name, 16).rstrip(b'\x00'), members)
+ for name, members in radio._zone_list()]
+
+ status = chirp_common.Status()
+ status.msg = 'Scanning flash pages'
+ status.max = (end + 1 - start) // PAGE + len(UPLOAD_TAGS)
+ where, free = _scan(link, start, end, radio, status)
+ dupes = [t for t in UPLOAD_TAGS if len(where.get(t, [])) > 1]
+ if dupes:
+ raise errors.RadioError(
+ 'The radio has more than one page with tag %s; not writing' %
+ ', '.join('%02x' % t for t in dupes))
+
+ status.msg = 'Cloning to radio'
+ base = status.cur + 1
+ written = 0
+ for i, tag in enumerate(UPLOAD_TAGS):
+ slot = IMAGE_TAGS.index(tag) * PAGE
+ want = image[slot:slot + PAGE - 1] + bytes([tag])
+ # A slot is in use if it holds data, or if it came from the radio
+ # (tag byte set) and has since been emptied, e.g. all its channels
+ # deleted: then the radio's page must be emptied too.
+ if (image[slot:slot + PAGE - 1] != b'\xFF' * (PAGE - 1) or
+ image[slot + PAGE - 1] == tag and where.get(tag)):
+ if where.get(tag):
+ addr = where[tag][0]
+ current = link.read_block(addr, PAGE)
+ if tag == ZONE_TAG0:
+ want = _follow_display(want, current, radio_zone, zones)
+ elif tag == 0x04:
+ want = bytearray(want)
+ want[0x80] = (want[0x80] & ~WORK_STATE_MASK & 0xFF |
+ current[0x80] & WORK_STATE_MASK)
+ want = bytes(want)
+ if current == want:
+ addr = None
+ elif free:
+ addr = free.pop(0)
+ else:
+ raise errors.RadioError('No free page left on the radio')
+ if addr is not None:
+ _write_page(link, addr, want, start, end)
+ written += 1
+ status.cur = base + i
+ radio.status_fn(status)
+ return written
+
+
+# --- Tones ------------------------------------------------------------------
+
+def _shown(name):
+ """A name as CHIRP can show it: characters outside its charset as '?'."""
+ return ''.join(c if c in chirp_common.CHARSET_ASCII else '?'
+ for c in name)
+
+
+def _edited(value, old):
+ """The name to store for a setting that showed `old`: `old` itself,
+ byte for byte, unless the user changed it."""
+ value = str(value).strip()
+ return old if value == _shown(old).strip() else value
+
+
+def _name_bytes(name, length):
+ return name.encode('latin-1', 'replace')[:length].ljust(length, b'\x00')
+
+
+def _cached(method):
+ """Cache a lookup on the image until the driver next changes it (see
+ DM32UV._forget). Callers must not modify the result."""
+ @functools.wraps(method)
+ def wrapper(self, *args):
+ cache = self.__dict__.setdefault('_lookups', {})
+ key = (method.__name__,) + args
+ if key not in cache:
+ cache[key] = method(self, *args)
+ return cache[key]
+ return wrapper
+
+
+class DM32UVZone(chirp_common.NamedBank):
+ """A zone on the radio; its index is the zone number minus 1.
+
+ One zone after the last existing one is offered as "New zone"; adding
+ a channel to it creates it (see DM32UVZoneModel)."""
+
+ def _zone(self):
+ return self._model._radio._zone(self.index + 1)
+
+ def get_name(self):
+ name = str(self._zone().name).rstrip('\x00\xFF ')
+ if self.index + 1 > self._model._radio._zone_count() and (
+ not name or not name.isprintable()):
+ return 'New zone'
+ return name
+
+ def set_name(self, name):
+ self._zone().name = str(name)[:16].ljust(16, '\x00')
+
+
+class DM32UVZoneModel(chirp_common.MTOBankModel):
+ """The radio's zones. A channel can be in several zones; the order of
+ channels in a zone is kept, new ones are added at the end.
+
+ Zones are numbered 1..count without gaps, so the only zone that can be
+ created is count + 1: it is offered as a spare, and becomes a real zone
+ when a channel is added to it. A last zone left empty is removed."""
+
+ def __init__(self, radio):
+ super().__init__(radio, 'Zones')
+
+ def get_num_mappings(self):
+ return min(self._radio._zone_count() + 1, ZONE_COUNT)
+
+ def get_mappings(self):
+ zones = []
+ for i in range(self.get_num_mappings()):
+ zone = DM32UVZone(self, '%i' % (i + 1), 'Zone %i' % (i + 1))
+ zone.index = i
+ zones.append(zone)
+ return zones
+
+ def add_memory_to_mapping(self, memory, bank):
+ z = bank.index + 1
+ if z > self._radio._zone_count():
+ self._radio._create_zone(z)
+ members = self._radio._zone_members(z)
+ if memory.number in members:
+ return
+ if len(members) >= ZONE_MEMBERS:
+ raise errors.RadioError('Zone %s is full (%i channels)' % (
+ bank.get_name(), ZONE_MEMBERS))
+ self._radio._set_zone_members(bank.index + 1,
+ members + [memory.number])
+
+ def remove_memory_from_mapping(self, memory, bank):
+ members = self._radio._zone_members(bank.index + 1)
+ if memory.number not in members:
+ raise Exception('Memory %i is not in zone %s' % (
+ memory.number, bank.get_name()))
+ self._radio._set_zone_members(
+ bank.index + 1, [m for m in members if m != memory.number])
+ self._radio._drop_empty_last_zone()
+
+ def get_mapping_memories(self, bank):
+ return [self._radio.get_memory(n)
+ for n in self._radio._zone_members(bank.index + 1)]
+
+ def get_memory_mappings(self, memory):
+ zones = []
+ for z in self._radio._zone_index().get(memory.number, []):
+ zone = DM32UVZone(self, '%i' % z, 'Zone %i' % z)
+ zone.index = z - 1
+ zones.append(zone)
+ return zones
+
+
+@directory.register
+class DM32UV(chirp_common.CloneModeRadio):
+ """Baofeng DM-32UV"""
+ VENDOR = 'Baofeng'
+ MODEL = 'DM-32UV'
+ BAUD_RATE = 115200
+ _memsize = len(IMAGE_TAGS) * PAGE
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.experimental = (
+ 'This driver is experimental. Upload writes channels, zones, '
+ 'DMR lists, scan lists and radio settings. Passwords, encryption '
+ 'keys and the factory calibration are left as they are on the '
+ 'radio. A radio with a password set is refused.')
+ rp.pre_download = (
+ 'Switch the radio on and connect the programming cable.\n\n'
+ 'The radio returns to normal by itself a few seconds after '
+ 'the download.')
+ rp.pre_upload = (
+ 'Before the first upload, download from the radio and save the '
+ 'image as a backup.\n\n'
+ 'Upload writes only the pages that differ from the radio and '
+ 'checks each one by reading it back. It takes about a minute '
+ 'plus a few seconds per changed page.')
+ return rp
+
+ @classmethod
+ def detect_from_serial(cls, pipe):
+ """Check that the connected radio is a DM-32UV."""
+ _check_model(_search(_Link(pipe)))
+ return cls
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.memory_bounds = (1, CH_COUNT)
+ rf.has_bank = True
+ rf.has_bank_names = True
+ rf.has_ctone = True
+ rf.has_cross = True
+ rf.has_rx_dtcs = True
+ rf.has_dtcs_polarity = True
+ rf.has_settings = True
+ rf.can_odd_split = True
+ rf.valid_modes = ['FM', 'NFM', 'DMR']
+ rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
+ rf.valid_cross_modes = ['Tone->Tone', 'DTCS->', '->DTCS', 'Tone->DTCS',
+ 'DTCS->Tone', '->Tone', 'DTCS->DTCS']
+ rf.valid_duplexes = ['', '-', '+', 'split', 'off']
+ rf.valid_power_levels = POWER_LEVELS
+ rf.valid_bands = [(136000000, 174000000), (400000000, 480000000)]
+ rf.valid_tuning_steps = STEPS
+ # Frequencies are stored to 10 Hz, independent of the step.
+ rf.has_nostep_tuning = True
+ rf.valid_skips = []
+ rf.valid_name_length = 16
+ rf.valid_characters = chirp_common.CHARSET_ASCII
+ return rf
+
+ def sync_in(self):
+ try:
+ self._mmap = do_download(self)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.exception('Download failed')
+ raise errors.RadioError('Failed to download from radio: %s' % e)
+ self.process_mmap()
+
+ def sync_out(self):
+ try:
+ do_upload(self)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.exception('Upload failed')
+ raise errors.RadioError('Failed to upload to radio: %s' % e)
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+ self._forget()
+
+ def _forget(self):
+ """Drop cached lookups; called whenever the image changes."""
+ self._lookups = {}
+
+ def _chan(self, number):
+ page, index = channel_offset(number)
+ return getattr(self._memobj, 'page%d' % page)[index]
+
+ def get_bank_model(self):
+ return DM32UVZoneModel(self)
+
+ def _zone(self, z):
+ page, index = zone_offset(z)
+ return getattr(self._memobj, 'zpage%d' % page)[index]
+
+ def _zone_count(self):
+ count = int(self._memobj.zone_hdr.count)
+ return 0 if count > ZONE_COUNT else count
+
+ def _zone_members(self, z):
+ if z > self._zone_count():
+ return [] # the spare zone, or erased flash
+ zone = self._zone(z)
+ count = min(int(zone.count), ZONE_MEMBERS)
+ return [int(m) for m in zone.members[0:count]
+ if 1 <= int(m) <= CH_COUNT]
+
+ @_cached
+ def _zone_index(self):
+ """{channel: [zones it is in]}"""
+ index = collections.defaultdict(list)
+ for z in range(1, self._zone_count() + 1):
+ for m in self._zone_members(z):
+ if z not in index[m]:
+ index[m].append(z)
+ return dict(index)
+
+ def _set_zone_members(self, z, members):
+ self._forget()
+ zone = self._zone(z)
+ for i in range(ZONE_MEMBERS):
+ zone.members[i] = members[i] if i < len(members) else 0
+ zone.count = len(members)
+
+ def _create_zone(self, z):
+ """Make zone z (which must be count + 1) an empty, named zone."""
+ if z != self._zone_count() + 1 or z > ZONE_COUNT:
+ raise errors.RadioError('Zones must be created in order')
+ self._forget()
+ zone = self._zone(z)
+ name = str(zone.name).rstrip('\x00\xFF ')
+ if not name or not name.isprintable():
+ zone.name = ('Zone %i' % z).ljust(16, '\x00')
+ self._set_zone_members(z, [])
+ self._memobj.zone_hdr.count = z
+
+ def _zone_list(self):
+ """[(name, [members])] for zones 1..count."""
+ return [(str(self._zone(z).name).split('\x00')[0].split('\xFF')[0],
+ self._zone_members(z))
+ for z in range(1, self._zone_count() + 1)]
+
+ def _set_zone_list(self, zones, remap):
+ """Rewrite zones 1..len(zones); remap = {old zone: new zone} for the
+ radio's current-zone pointers (a zone not in it was deleted)."""
+ self._forget()
+ old_count = self._zone_count()
+ for z, (name, members) in enumerate(zones, 1):
+ zone = self._zone(z)
+ if str(zone.name).split('\x00')[0].split('\xFF')[0] != name:
+ zone.name.set_raw(_name_bytes(name, 16))
+ self._set_zone_members(z, members)
+ for z in range(len(zones) + 1, old_count + 1):
+ self._zone(z).name.set_raw(b'\xFF' * 16)
+ self._set_zone_members(z, [])
+ hdr = self._memobj.zone_hdr
+ hdr.count = len(zones)
+ for zone_f, pos_f in (('a_zone', 'a_pos'), ('b_zone', 'b_pos')):
+ new = remap.get(int(getattr(hdr, zone_f)))
+ if not new:
+ new = 1
+ setattr(hdr, pos_f, 1)
+ setattr(hdr, zone_f, new)
+ members = len(zones[new - 1][1]) if zones else 0
+ if not 1 <= int(getattr(hdr, pos_f)) <= max(members, 1):
+ setattr(hdr, pos_f, 1)
+
+ def _drop_empty_last_zone(self):
+ count = self._zone_count()
+ if count > 1 and not self._zone_members(count):
+ self._forget()
+ self._zone(count).name.set_raw(b'\xFF' * 16)
+ self._memobj.zone_hdr.count = count - 1
+
+ def _count(self):
+ count = int(self._memobj.ch_count)
+ return 0 if count > CH_COUNT else count
+
+ # --- raw page access (DMR lists live outside the bitwise layout) ---------
+
+ def _page(self, tag):
+ base = IMAGE_TAGS.index(tag) * PAGE
+ return base, self._mmap.get(base, PAGE)
+
+ def _put(self, tag, offset, data):
+ base = IMAGE_TAGS.index(tag) * PAGE
+ assert offset + len(data) <= PAGE - 1
+ self._forget()
+ self._mmap.set(base + offset, bytes(data))
+ self._mmap.set(base + PAGE - 1, bytes([tag])) # the page now exists
+
+ @staticmethod
+ def _text(raw):
+ text = raw.split(b'\xFF')[0].split(b'\x00')[0]
+ return text.decode('latin-1')
+
+ # --- radio IDs -----------------------------------------------------------
+
+ @_cached
+ def _radio_ids(self):
+ """[(dmr_id, name)] for radio IDs 1..count."""
+ _base, page = self._page(RADIOID_TAG)
+ count = page[0] if page[0] <= RADIOID_MAX else 0
+ return [(int.from_bytes(page[16 * n:16 * n + 3], 'little'),
+ self._text(page[16 * n + 3:16 * n + 3 + RADIOID_NAME]))
+ for n in range(1, count + 1)]
+
+ def _set_radio_ids(self, entries):
+ self._put(RADIOID_TAG, 0, bytes([len(entries)]))
+ for n in range(1, RADIOID_MAX + 1):
+ if n <= len(entries):
+ dmr_id, name = entries[n - 1]
+ rec = (dmr_id.to_bytes(3, 'little') +
+ _name_bytes(name, RADIOID_NAME) + b'\x00')
+ else:
+ rec = b'\x00' * 16
+ self._put(RADIOID_TAG, 16 * n, rec)
+
+ # --- contacts ------------------------------------------------------------
+
+ def _contact_loc(self, k):
+ return (CONTACT_REC_TAG0 + (k - 1) // CONTACT_PER_PAGE,
+ ((k - 1) % CONTACT_PER_PAGE) * CONTACT_REC)
+
+ @_cached
+ def _contacts(self):
+ """{slot: (name, dmr_id, call_type index)} for used contact slots."""
+ _base, index = self._page(CONTACT_INDEX_TAG)
+ pages = {}
+ contacts = {}
+ for k in range(1, CONTACT_MAX + 1):
+ if index[0x10 + (k - 1) // 8] >> ((k - 1) % 8) & 1:
+ continue # free slot
+ tag, off = self._contact_loc(k)
+ if tag not in pages:
+ pages[tag] = self._page(tag)[1]
+ rec = pages[tag][off:off + CONTACT_REC]
+ ctype = rec[0x16] - 3 if 3 <= rec[0x16] <= 5 else 0
+ contacts[k] = (self._text(rec[2:2 + CONTACT_NAME]),
+ int.from_bytes(rec[0x13:0x16], 'little'), ctype)
+ return contacts
+
+ def _set_contacts(self, contacts):
+ """Write {slot: (name, id, type)} and rebuild the index page the way
+ the CPS does (0x474c00): counts, free bitmap, name- and ID-sorted
+ lists of (slot | call type code << 12)."""
+ _base, index = self._page(CONTACT_INDEX_TAG)
+ index = bytearray(index if index[0x10:0x74] != b'\xFF' * 100 or
+ index[0:2] != b'\xFF\xFF' else b'\x00' * PAGE)
+ for k, (name, dmr_id, ctype) in contacts.items():
+ tag, off = self._contact_loc(k)
+ old = self._page(tag)[1][off:off + CONTACT_REC]
+ keep = old if old != b'\xFF' * CONTACT_REC else b'\x00' * 24
+ name_b = _name_bytes(name, CONTACT_NAME)
+ if self._text(keep[2:2 + CONTACT_NAME]) == name:
+ name_b = keep[2:2 + CONTACT_NAME] # keep the radio's padding
+ rec = (keep[0:2] + name_b + b'\x00' +
+ dmr_id.to_bytes(3, 'little') + bytes([ctype + 3]) +
+ keep[0x17:0x18])
+ self._put(tag, off, rec)
+ bitmap = bytearray(b'\xFF' * 100)
+ for k in contacts:
+ bitmap[(k - 1) // 8] &= ~(1 << ((k - 1) % 8)) & 0xFF
+ index[0:2] = len(contacts).to_bytes(2, 'little')
+ groups = sum(1 for c in contacts.values() if c[2] == 1)
+ index[2:4] = groups.to_bytes(2, 'little')
+ index[4] = sum(1 for c in contacts.values() if c[2] == 2)
+ index[0x10:0x74] = bitmap
+ index[0x100:PAGE - 1] = b'\xFF' * (PAGE - 1 - 0x100)
+
+ def entry(k):
+ code = (contacts[k][2] + 3) << 4
+ return bytes([k & 0xFF, (k >> 8) & 0xF | code])
+ for pos, k in enumerate(sorted(contacts, key=lambda k: (
+ contacts[k][0].encode(), k))):
+ index[0x100 + 2 * pos:0x102 + 2 * pos] = entry(k)
+ for pos, k in enumerate(sorted(contacts, key=lambda k: (
+ contacts[k][1], k))):
+ index[0x740 + 2 * pos:0x742 + 2 * pos] = entry(k)
+ self._put(CONTACT_INDEX_TAG, 0, index[:PAGE - 1])
+
+ def _txc_loc(self, n):
+ if n < 0x800:
+ return TXC_TAGS[0], 2 * (n - 1)
+ if n in (CH_COUNT + 1, CH_COUNT + 2): # VFO A, B
+ return TXC_TAGS[1], 0xFFA + 2 * (n - CH_COUNT - 1)
+ return TXC_TAGS[1], 2 * (n & 0x7FF)
+
+ def _tx_contact(self, n):
+ tag, off = self._txc_loc(n)
+ hi, lo = self._page(tag)[1][off:off + 2]
+ value = (hi >> 4) << 8 | lo
+ return 0 if value > CONTACT_MAX else value
+
+ def _set_tx_contact(self, n, contact, digital):
+ tag, off = self._txc_loc(n)
+ hi = self._page(tag)[1][off]
+ hi = 0 if hi == 0xFF else hi & 0x0E
+ self._put(tag, off, bytes([(contact >> 8) << 4 | hi | int(digital),
+ contact & 0xFF]))
+
+ # --- RX group lists ------------------------------------------------------
+
+ @_cached
+ def _rx_groups(self):
+ """{n: (name, [member IDs])} for used groups."""
+ _base, page = self._page(RXG_TAG)
+ groups = {}
+ for n in range(1, RXG_MAX + 1):
+ if page[:4] == b'\xFF' * 4 or not page[(n - 1) // 8] >> (
+ (n - 1) % 8) & 1:
+ continue
+ base = RXG_REC * n - 0x5C
+ members = [int.from_bytes(page[base + RXG_NAME + 3 * j:][:3],
+ 'little') for j in range(RXG_MEMBERS)]
+ groups[n] = (self._text(page[base:base + RXG_NAME]),
+ [m for m in members if 0 < m <= ALL_CALL_ID])
+ return groups
+
+ def _set_rx_groups(self, groups):
+ _base, page = self._page(RXG_TAG)
+ head = bytearray(page[:0x10] if page[:4] != b'\xFF' * 4
+ else b'\x00' * 0x10)
+ head[0:4] = b'\x00' * 4
+ for n in groups:
+ head[(n - 1) // 8] |= 1 << ((n - 1) % 8)
+ self._put(RXG_TAG, 0, head)
+ for n in range(1, RXG_MAX + 1):
+ base = RXG_REC * n - 0x5C
+ name, members = groups.get(n, ('', []))
+ data = _name_bytes(name, RXG_NAME)
+ for j in range(RXG_MEMBERS):
+ m = members[j] if j < len(members) else 0
+ data += m.to_bytes(3, 'little')
+ self._put(RXG_TAG, base, data)
+
+ # --- scan lists ----------------------------------------------------------
+
+ @_cached
+ def _scan_lists(self):
+ """[(name, [channels], options bytes +0x0c..+0x17)] for 1..count."""
+ _base, page = self._page(SCAN_TAG)
+ count = page[0] if page[0] <= SCAN_MAX else 0
+ lists = []
+ for n in range(1, count + 1):
+ rec = page[SCAN_REC * n - 0x38:][:SCAN_REC]
+ k = min(rec[0x0B], SCAN_MEMBERS)
+ members = [int.from_bytes(rec[0x18 + 2 * i:0x1A + 2 * i],
+ 'little') for i in range(k)]
+ lists.append((self._text(rec[:SCAN_NAME]),
+ [m for m in members if 1 <= m <= CH_COUNT],
+ rec[0x0C:0x18]))
+ return lists
+
+ def _set_scan_lists(self, lists):
+ default = lists[0][2] if lists else SCAN_DEFAULT_OPTS
+ old_count = len(self._scan_lists())
+ self._put(SCAN_TAG, 0, bytes([len(lists)]))
+ for n in range(1, SCAN_MAX + 1):
+ base = SCAN_REC * n - 0x38
+ if n > len(lists):
+ if n <= old_count: # a list that was removed
+ self._put(SCAN_TAG, base, b'\x00' * SCAN_REC)
+ continue
+ name, members, opts = lists[n - 1]
+ opts = bytearray(opts if len(opts) == 12 else default)
+ members = members[:SCAN_MEMBERS]
+ designed = int.from_bytes(opts[3:5], 'little')
+ if members and designed not in members:
+ opts[3:5] = members[0].to_bytes(2, 'little')
+ rec = (_name_bytes(name, SCAN_NAME) +
+ bytes([len(members)]) + bytes(opts) +
+ b''.join(m.to_bytes(2, 'little') for m in members) +
+ b'\x00' * (2 * (SCAN_MEMBERS - len(members))))
+ self._put(SCAN_TAG, base, rec[:SCAN_REC])
+
+ def _remove_from_scan_lists(self, number):
+ lists = self._scan_lists()
+ new = []
+ for name, members, opts in lists:
+ members = [m for m in members if m != number]
+ if not members and int.from_bytes(opts[3:5], 'little') == number:
+ # the designed channel; the factory lists use channel 1
+ opts = opts[:3] + SCAN_DEFAULT_OPTS[3:5] + opts[5:]
+ new.append((name, members, opts))
+ if new != lists:
+ self._set_scan_lists(new)
+
+ # --- Settings tab: DMR lists ---------------------------------------------
+
+ def get_settings(self):
+ dmr = RadioSettingGroup('dmr', 'DMR lists')
+ ids = RadioSettingGroup('radio_ids', 'Radio IDs')
+ entries = self._radio_ids()
+ for n in range(1, min(len(entries) + 8, RADIOID_MAX) + 1):
+ dmr_id, name = entries[n - 1] if n <= len(entries) else (0, '')
+ ids.append(RadioSetting(
+ 'rid_%d_id' % n, 'Radio ID %d: DMR ID (0 = unused)' % n,
+ RadioSettingValueInteger(0, DMR_ID_MAX,
+ min(dmr_id, DMR_ID_MAX))))
+ ids.append(RadioSetting(
+ 'rid_%d_name' % n, 'Radio ID %d: name' % n,
+ RadioSettingValueString(0, RADIOID_NAME, _shown(name),
+ autopad=False)))
+ contacts = RadioSettingGroup('contacts', 'Contacts')
+ used = self._contacts()
+ free = [k for k in range(1, CONTACT_MAX + 1) if k not in used]
+ for k in sorted(used) + free[:10]:
+ name, dmr_id, ctype = used.get(k, ('', 1, 1))
+ contacts.append(RadioSetting(
+ 'con_%d_name' % k, 'Contact %d: name (empty = unused)' % k,
+ RadioSettingValueString(0, CONTACT_NAME, _shown(name),
+ autopad=False)))
+ contacts.append(RadioSetting(
+ 'con_%d_id' % k, 'Contact %d: DMR ID' % k,
+ RadioSettingValueInteger(1, ALL_CALL_ID, max(dmr_id, 1))))
+ contacts.append(RadioSetting(
+ 'con_%d_type' % k, 'Contact %d: call type' % k,
+ RadioSettingValueList(CALL_TYPES, current_index=ctype)))
+ groups = RadioSettingGroup('rx_groups', 'RX group lists')
+ by_id = {c[1]: _shown(c[0]) for c in used.values()}
+ # CHIRP keeps showing this tree after later edits, so remember the
+ # names shown here: a member name stays valid after a rename.
+ self._shown_contact_ids = {_shown(c[0]): c[1] for c in used.values()}
+ existing = self._rx_groups()
+ spare = [n for n in range(1, RXG_MAX + 1) if n not in existing][:3]
+ for n in sorted(existing) + spare:
+ name, members = existing.get(n, ('', []))
+ groups.append(RadioSetting(
+ 'rxg_%d_name' % n, 'RX group %d: name (empty = unused)' % n,
+ RadioSettingValueString(0, RXG_NAME, _shown(name),
+ autopad=False)))
+ groups.append(RadioSetting(
+ 'rxg_%d_members' % n,
+ 'RX group %d: contacts (names or IDs, comma separated)' % n,
+ RadioSettingValueString(
+ 0, 600, ', '.join(by_id.get(m, str(m)) for m in members),
+ autopad=False, charset=chirp_common.CHARSET_ASCII)))
+ dmr.append(ids)
+ dmr.append(contacts)
+ dmr.append(groups)
+ scan = RadioSettingGroup('scan', 'Scan lists')
+ lists = self._scan_lists()
+ for n in range(1, min(len(lists) + 1, SCAN_MAX) + 1):
+ name, members, opts = lists[n - 1] if n <= len(lists) else (
+ '', [], bytes(12))
+ scan.append(RadioSetting(
+ 'scan_%d_name' % n, 'Scan list %d: name (empty = unused)' % n,
+ RadioSettingValueString(0, SCAN_NAME, _shown(name),
+ autopad=False)))
+ scan.append(RadioSetting(
+ 'scan_%d_members' % n,
+ 'Scan list %d: channels (numbers, comma separated)' % n,
+ RadioSettingValueString(0, 100, ', '.join(map(str, members)),
+ autopad=False)))
+ scan.append(RadioSetting(
+ 'scan_%d_ctc' % n, 'Scan list %d: CTC scan mode' % n,
+ RadioSettingValueList(SCAN_CTC_MODES, current_index=min(
+ opts[0] & 0xF, len(SCAN_CTC_MODES) - 1))))
+ scan.append(RadioSetting(
+ 'scan_%d_tx' % n, 'Scan list %d: scan TX mode' % n,
+ RadioSettingValueList(SCAN_TX_MODES, current_index=min(
+ opts[0] >> 4, len(SCAN_TX_MODES) - 1))))
+ zones = RadioSettingGroup('zones', 'Zones')
+ zlist = self._zone_list()
+ zones.append(RadioSetting(
+ 'zone_order', 'Zone order (zone numbers, comma separated; '
+ 'reopen the image before using the Banks tab again)',
+ RadioSettingValueString(0, ZONE_ORDER_MAX, ', '.join(
+ str(z) for z in range(1, len(zlist) + 1)), autopad=False)))
+ for z, (name, members) in enumerate(zlist, 1):
+ zones.append(RadioSetting(
+ 'zone_%d_name' % z, 'Zone %d: name' % z,
+ RadioSettingValueString(0, 16, _shown(name),
+ autopad=False)))
+ zones.append(RadioSetting(
+ 'zone_%d_members' % z,
+ 'Zone %d: channels in order (empty = delete zone)' % z,
+ RadioSettingValueString(0, 400, ', '.join(map(str, members)),
+ autopad=False)))
+ groups_out = [dmr, scan, zones]
+ if self._has_page(DTMF_TAG):
+ groups_out.append(self._dtmf_contacts_group())
+ if self._has_page(SIGNAL_TAG):
+ groups_out.append(self._tt_encode_group())
+ groups_out.append(self._ft_special_group())
+ radio = self._radio_settings()
+ if len(radio):
+ groups_out.insert(0, radio)
+ return RadioSettings(*groups_out)
+
+ def _tt_encode(self):
+ """[(name, single tone, tone 1, tone 2)] of two-tone encode
+ entries 1..count (tones in 0.1 Hz)."""
+ count = int(self._memobj.tt_encode_count)
+ count = count if 1 <= count <= TT_ENCODE else 1 # as the CPS
+ out = []
+ for e in list(self._memobj.tt_encode)[:count]:
+ raw = e.name.get_raw()
+ name = raw.decode('utf-16-le', 'replace').split('\x00')[0]
+ if raw[:2] == b'\xFF\xFF':
+ name = ''
+ out.append((name, bool(e.single_tone), int(e.tone1),
+ int(e.tone2)))
+ return out
+
+ def _tt_encode_group(self):
+ group = RadioSettingGroup('tt_encode', 'Two-tone encode')
+ entries = self._tt_encode()
+ for n in range(1, min(len(entries) + 4, TT_ENCODE) + 1):
+ name, single, t1, t2 = entries[n - 1] if n <= len(entries) \
+ else ('', False, 0, 0)
+ group.append(RadioSetting(
+ 'tte_%d_name' % n, 'Encode %d: name (empty = unused)' % n,
+ RadioSettingValueString(0, 16, _shown(name), autopad=False)))
+ group.append(RadioSetting(
+ 'tte_%d_single' % n, 'Encode %d: send' % n,
+ RadioSettingValueList(['Dual Tone', 'Single Tone'],
+ current_index=int(single))))
+ for k, tone in ((1, t1), (2, t2)):
+ group.append(RadioSetting(
+ 'tte_%d_tone%d' % (n, k), 'Encode %d: tone %d (Hz)' % (
+ n, k),
+ RadioSettingValueString(
+ 0, 7, '%.1f' % (tone / 10)
+ if TT_HZ[0] <= tone <= TT_HZ[1] else '',
+ autopad=False, charset='0123456789.')))
+ return group
+
+ def _set_tt_encode(self, values):
+ old = self._tt_encode()
+ new = list(old)
+ for n in range(1, TT_ENCODE + 1):
+ if 'tte_%d_name' % n not in values:
+ continue
+ o = old[n - 1] if n <= len(old) else ('', False, 0, 0)
+ name = _edited(values['tte_%d_name' % n], o[0])
+ tones = []
+ for k in (1, 2):
+ text = str(values['tte_%d_tone%d' % (n, k)]).strip()
+ shown = '%.1f' % (o[1 + k] / 10) \
+ if TT_HZ[0] <= o[1 + k] <= TT_HZ[1] else ''
+ tones.append(o[1 + k] if text == shown else _parse_hz(
+ text, TT_HZ, 'Two-tone encode %d, tone %d' % (n, k)))
+ single = str(values['tte_%d_single' % n]) == 'Single Tone'
+ while len(new) < n:
+ new.append(('', False, 0, 0))
+ new[n - 1] = (name, single, tones[0], tones[1])
+ while len(new) > 1 and not new[-1][0]:
+ new.pop()
+ if new == old:
+ return
+ self._forget()
+ for n, (name, single, t1, t2) in enumerate(new, 1):
+ e = self._memobj.tt_encode[n - 1]
+ if n > len(old) or old[n - 1][0] != name:
+ e.name.set_raw(
+ name.encode('utf-16-le')[:32].ljust(32, b'\x00'))
+ if n > len(old) and e.get_raw()[0x20:] == b'\xFF' * 8:
+ e.set_raw(e.get_raw()[:0x20] + b'\xFE\xFF' + b'\xFF' * 6)
+ e.single_tone = int(single)
+ e.tone1, e.tone2 = t1, t2
+ for n in range(len(new) + 1, len(old) + 1):
+ self._memobj.tt_encode[n - 1].set_raw(b'\x00' * 0x20 +
+ b'\xFF' * 8)
+ self._memobj.tt_encode_count = len(new)
+
+ def _ft_special(self):
+ """[{field: shown value}] of the 32 five-tone special calls."""
+ out = []
+ for e in self._memobj.ft_special:
+ types, stored = FT_SPECIAL_TYPES
+ t = int(e.type)
+ out.append({
+ 'type': types[stored.index(t)] if t in stored else 'Off',
+ 'code': _dtmf_text(e.code.get_raw(), CODE_CHARS['hex']),
+ 'delimiter': FT_DELIMITERS[int(e.delimiter)]
+ if int(e.delimiter) < len(FT_DELIMITERS) else
+ FT_DELIMITERS[0],
+ 'standard': FT_STANDARDS[int(e.standard)]
+ if int(e.standard) < len(FT_STANDARDS) else FT_STANDARDS[0],
+ 'tone_long': FT_TONE_LONG[0][int(e.tone_long) - 3]
+ if 3 <= int(e.tone_long) < 3 + len(FT_TONE_LONG[0])
+ else FT_TONE_LONG[0][0],
+ 'data': _dtmf_text(e.data.get_raw(), CODE_CHARS['hex']),
+ 'name': self._text(e.name.get_raw()),
+ })
+ return out
+
+ def _ft_special_group(self):
+ group = RadioSettingGroup('ft_special', 'Five-tone special calls')
+ hexchars = CODE_CHARS['hex'] + CODE_CHARS['hex'].lower()
+ calls = self._ft_special()
+ used = [n for n, c in enumerate(calls, 1) if c['type'] != 'Off']
+ spare = [n for n in range(1, FT_SPECIAL + 1) if n not in used][:3]
+ for n in used + spare:
+ c = calls[n - 1]
+ label = 'Special call %d: ' % n
+ for key, text, value in (
+ ('type', 'call type (Off = unused)', _pick(
+ FT_SPECIAL_TYPES[0], c['type'])),
+ ('name', 'name', RadioSettingValueString(
+ 0, 16, _shown(c['name']), autopad=False)),
+ ('code', 'other side code', RadioSettingValueString(
+ 0, 5, c['code'], autopad=False, charset=hexchars)),
+ ('delimiter', 'middle delimiter', _pick(
+ FT_DELIMITERS, c['delimiter'])),
+ ('standard', 'decode standard', _pick(
+ FT_STANDARDS, c['standard'])),
+ ('tone_long', 'tone long', _pick(
+ FT_TONE_LONG[0], c['tone_long'])),
+ ('data', 'data transmission', RadioSettingValueString(
+ 0, 16, c['data'], autopad=False, charset=hexchars))):
+ group.append(RadioSetting('fts_%d_%s' % (n, key),
+ label + text, value))
+ return group
+
+ def _set_ft_special(self, values):
+ calls = self._ft_special()
+ for n in range(1, FT_SPECIAL + 1):
+ if 'fts_%d_type' % n not in values:
+ continue
+ c, e = calls[n - 1], self._memobj.ft_special[n - 1]
+ new = {k: str(values['fts_%d_%s' % (n, k)]).strip()
+ for k in c}
+ if new['name'] == _shown(c['name']).strip():
+ new['name'] = c['name']
+ for k in ('code', 'data'):
+ new[k] = new[k].upper()
+ if new == c:
+ continue
+ self._forget()
+ if new['type'] != c['type']:
+ types, stored = FT_SPECIAL_TYPES
+ e.type = stored[types.index(new['type'])]
+ if new['code'] != c['code']:
+ e.code.set_raw(_dtmf_bytes(new['code'], 5, CODE_CHARS['hex']))
+ if new['data'] != c['data']:
+ e.data.set_raw(_dtmf_bytes(new['data'], 16,
+ CODE_CHARS['hex']))
+ if new['name'] != c['name']:
+ e.name.set_raw((new['name'].encode('latin-1', 'replace')[:16]
+ + b'\x00')[:16].ljust(16, b'\xFF'))
+ if new['delimiter'] != c['delimiter']:
+ e.delimiter = FT_DELIMITERS.index(new['delimiter'])
+ if new['standard'] != c['standard']:
+ e.standard = FT_STANDARDS.index(new['standard'])
+ if new['tone_long'] != c['tone_long']:
+ e.tone_long = FT_TONE_LONG[0].index(new['tone_long']) + 3
+
+ def _has_page(self, tag):
+ return self._page(tag)[1][:PAGE - 1] != b'\xFF' * (PAGE - 1)
+
+ def _dtmf_contacts(self):
+ """[(name, number)] of DTMF (analog) contacts 1..count."""
+ count = int(self._memobj.dtmf_contact_count)
+ count = count if count <= DTMF_CONTACTS else 0
+ return [(self._text(c.name.get_raw()),
+ _dtmf_text(c.number.get_raw(), '0123456789'))
+ for c in list(self._memobj.dtmf_contacts)[:count]]
+
+ def _dtmf_contacts_group(self):
+ group = RadioSettingGroup('dtmf_contacts', 'DTMF contacts')
+ contacts = self._dtmf_contacts()
+ for n in range(1, min(len(contacts) + 4, DTMF_CONTACTS) + 1):
+ name, number = contacts[n - 1] if n <= len(contacts) else ('', '')
+ group.append(RadioSetting(
+ 'dtc_%d_name' % n, 'DTMF contact %d: name' % n,
+ RadioSettingValueString(0, 16, _shown(name), autopad=False)))
+ group.append(RadioSetting(
+ 'dtc_%d_number' % n, 'DTMF contact %d: number (up to 5 '
+ 'digits)' % n,
+ RadioSettingValueString(0, 5, number, autopad=False,
+ charset='0123456789')))
+ return group
+
+ def _set_dtmf_contacts(self, values):
+ old = self._dtmf_contacts()
+ new = list(old)
+ for n in range(1, DTMF_CONTACTS + 1):
+ if 'dtc_%d_name' % n not in values:
+ continue
+ old_name = old[n - 1][0] if n <= len(old) else ''
+ name = _edited(values['dtc_%d_name' % n], old_name)
+ number = str(values['dtc_%d_number' % n]).strip()
+ while len(new) < n:
+ new.append(('', ''))
+ new[n - 1] = (name, number)
+ while new and not new[-1][0]:
+ new.pop()
+ for n, (name, number) in enumerate(new, 1):
+ if not name:
+ raise errors.InvalidValueError(
+ 'DTMF contact %d: a name is needed (only the last '
+ 'contacts can be removed)' % n)
+ if new == old:
+ return
+ self._forget()
+ for n, (name, number) in enumerate(new, 1):
+ c = self._memobj.dtmf_contacts[n - 1]
+ if n > len(old) or old[n - 1][0] != name:
+ c.name.set_raw(_name_bytes(name, 16))
+ if n > len(old) or old[n - 1][1] != number:
+ c.number.set_raw(_dtmf_bytes(number, 5, '0123456789'))
+ if n > len(old) and c.unknown.get_raw() == b'\xFF' * 11:
+ c.unknown.set_raw(b'\x00' * 11)
+ for n in range(len(new) + 1, len(old) + 1):
+ self._memobj.dtmf_contacts[n - 1].set_raw(b'\xFF' * 0x20)
+ self._memobj.dtmf_contact_count = len(new)
+
+ def _radio_settings(self):
+ top = RadioSettingGroup('radio', 'Radio settings')
+ for title, entries in RADIO_SETTINGS:
+ group = RadioSettingGroup('radio_%s' % title.lower().replace(
+ ' ', '_'), title)
+ for sname, field, label, kind, extra in entries:
+ if not self._has_page(STRUCT_TAGS.get(sname, 0x04)):
+ continue
+ obj = getattr(self._memobj, sname)
+ name = 'set_%s_%s' % (sname, field)
+ if kind == 'bool':
+ value = RadioSettingValueBoolean(bool(getattr(obj,
+ field)))
+ elif kind == 'text':
+ text = str(getattr(obj, field))
+ text = text.split('\x00')[0].split('\xFF')[0]
+ text = ''.join(c for c in text
+ if c in chirp_common.CHARSET_ASCII)
+ value = RadioSettingValueString(0, extra, text,
+ autopad=False)
+ elif kind == 'coord':
+ value = RadioSettingValueString(
+ 0, 12, _parse_coord(getattr(obj, field).get_raw()),
+ autopad=False)
+ elif kind == 'int':
+ lo, hi = extra
+ number = int(getattr(obj, field))
+ value = RadioSettingValueInteger(
+ lo, hi, number if lo <= number <= hi else lo)
+ elif kind == 'channel':
+ name = 'set_%s_%s_%d' % (sname, field, extra + 1)
+ value = self._channel_choice(
+ int(getattr(obj, field)[extra]))
+ elif kind == 'hz':
+ tenths = int(getattr(obj, field))
+ value = RadioSettingValueString(
+ 0, 7, '%.1f' % (tenths / 10)
+ if extra[0] <= tenths <= extra[1] else '',
+ autopad=False, charset='0123456789.')
+ elif kind == 'dtmf':
+ value = RadioSettingValueString(
+ 0, extra, _dtmf_text(getattr(obj, field).get_raw()),
+ autopad=False, charset=DTMF_CHARS + 'abcd')
+ elif kind in ('digits', 'hex'):
+ chars = CODE_CHARS[kind]
+ value = RadioSettingValueString(
+ 0, extra, _dtmf_text(getattr(obj, field).get_raw(),
+ chars),
+ autopad=False, charset=chars + chars.lower())
+ else:
+ options, offset = extra
+ index = _list_index(int(getattr(obj, field)), offset)
+ value = RadioSettingValueList(options, current_index=(
+ index if 0 <= index < len(options) else 0))
+ group.append(RadioSetting(name, label, value))
+ if len(group):
+ top.append(group)
+ return top
+
+ def _channel_choice(self, value):
+ """Report channel choice: the current channel, or a digital one."""
+ options = ['Current Channel'] + self._digital_channels()
+ current = 'Current Channel' if not value else '%d: %s' % (
+ value, self._channel_names().get(value, '(empty)'))
+ if current not in options:
+ options.append(current)
+ return RadioSettingValueList(options,
+ current_index=options.index(current))
+
+ @_cached
+ def _channel_names(self):
+ """{number: name} of the channels in use."""
+ names = {}
+ for n in range(1, self._count() + 1):
+ _mem = self._chan(n)
+ if _mem.rxfreq.get_raw() not in (b'\xFF' * 4, b'\x00' * 4):
+ names[n] = _shown(str(_mem.name).rstrip('\x00\xFF '))
+ return names
+
+ @_cached
+ def _digital_channels(self):
+ names = self._channel_names()
+ return ['%d: %s' % (n, names[n]) for n in names
+ if self._chan(n).chtype in (1, 3)]
+
+ @staticmethod
+ def _set_coord(field, label, limit, text):
+ """Store a coordinate typed on the Settings tab, if it changed."""
+ if text == _parse_coord(field.get_raw()):
+ return
+ if not text:
+ field.set_raw(b'\x00' * 9)
+ return
+ try:
+ value = float(text)
+ except ValueError:
+ value = -1
+ if not 0 <= value <= limit:
+ raise errors.InvalidValueError(
+ '%s must be a number from 0 to %d' % (label, limit))
+ field.set_raw(_format_coord(value, limit).encode())
+
+ def set_settings(self, settings):
+ values = {}
+
+ def walk(group):
+ for element in group:
+ if isinstance(element, RadioSetting):
+ values[element.get_name()] = element.value
+ else:
+ walk(element)
+ walk(settings)
+
+ for title, entries in RADIO_SETTINGS:
+ for sname, field, label, kind, extra in entries:
+ name = 'set_%s_%s' % (sname, field)
+ if kind == 'channel':
+ name = 'set_%s_%s_%d' % (sname, field, extra + 1)
+ if name not in values:
+ continue
+ obj = getattr(self._memobj, sname)
+ if kind == 'coord':
+ self._set_coord(getattr(obj, field), label, extra,
+ str(values[name]).strip())
+ elif kind == 'int':
+ lo, hi = extra
+ number = int(getattr(obj, field))
+ new = int(values[name])
+ if new != (number if lo <= number <= hi else lo):
+ setattr(obj, field, new)
+ elif kind == 'channel':
+ choice = str(values[name])
+ new = int(choice.split(':')[0]) if ':' in choice else 0
+ if new != int(getattr(obj, field)[extra]):
+ getattr(obj, field)[extra] = new
+ elif kind == 'bool':
+ setattr(obj, field, int(bool(values[name])))
+ elif kind == 'text':
+ text = str(values[name]).rstrip()
+ old = str(getattr(obj, field)).split('\x00')[0]
+ if text != old.split('\xFF')[0]:
+ setattr(obj, field, text[:extra].ljust(extra, '\x00'))
+ elif kind == 'hz':
+ tenths = int(getattr(obj, field))
+ text = str(values[name]).strip()
+ shown = '%.1f' % (tenths / 10) \
+ if extra[0] <= tenths <= extra[1] else ''
+ if text != shown:
+ setattr(obj, field, _parse_hz(text, extra, label))
+ elif kind in CODE_CHARS:
+ chars = CODE_CHARS[kind]
+ raw = getattr(obj, field)
+ text = str(values[name]).strip().upper()
+ if text != _dtmf_text(raw.get_raw(), chars):
+ if kind == 'digits':
+ # the CPS pads with leading zeros (0x47be70)
+ raw.set_raw(bytes(chars.index(c) for c in
+ text.rjust(extra, '0')))
+ else:
+ raw.set_raw(_dtmf_bytes(text, extra, chars))
+ else:
+ options, offset = extra
+ new = options.index(str(values[name]))
+ shown = _list_index(int(getattr(obj, field)), offset)
+ if not 0 <= shown < len(options):
+ shown = 0 # displayed as the first option
+ if new != shown: # don't rewrite what wasn't changed
+ setattr(obj, field, _list_stored(new, offset))
+
+ self._forget()
+ if self._has_page(DTMF_TAG):
+ self._set_dtmf_contacts(values)
+ if self._has_page(SIGNAL_TAG):
+ self._set_tt_encode(values)
+ self._set_ft_special(values)
+
+ # Radio IDs: keep the ones with an ID, in order; renumber channels.
+ old = self._radio_ids()
+ kept, remap = [], {}
+ for n in range(1, RADIOID_MAX + 1):
+ if 'rid_%d_id' % n not in values:
+ if n <= len(old):
+ kept.append(old[n - 1])
+ remap[n] = len(kept)
+ continue
+ dmr_id = int(values['rid_%d_id' % n])
+ old_id, old_name = old[n - 1] if n <= len(old) else (0, '')
+ if dmr_id == min(old_id, DMR_ID_MAX):
+ dmr_id = old_id # shown clamped, not changed
+ if dmr_id:
+ kept.append((dmr_id, _edited(values['rid_%d_name' % n],
+ old_name)))
+ remap[n] = len(kept)
+ if [e for e in kept] != old or any(k != v for k, v in remap.items()):
+ self._set_radio_ids(kept)
+ for number in range(1, self._count() + 1):
+ _mem = self._chan(number)
+ if int(_mem.radio_id):
+ _mem.radio_id = remap.get(int(_mem.radio_id), 0)
+
+ # Contacts: an empty name frees the slot.
+ old_contacts = self._contacts()
+ contacts = dict(old_contacts)
+ # RX group members are shown by name; accept the names shown when
+ # the settings were read and those from before this edit too (a
+ # renamed contact keeps its ID).
+ by_name = dict(getattr(self, '_shown_contact_ids', {}))
+ by_name.update({_shown(c[0]): c[1] for c in contacts.values()})
+ for k in range(1, CONTACT_MAX + 1):
+ if 'con_%d_name' % k not in values:
+ continue
+ old_name, old_id, _t = contacts.get(k, ('', 1, 0))
+ name = _edited(values['con_%d_name' % k], old_name)
+ if name:
+ ctype = CALL_TYPES.index(str(values['con_%d_type' % k]))
+ dmr_id = int(values['con_%d_id' % k])
+ if dmr_id == max(old_id, 1):
+ dmr_id = old_id # shown clamped, not changed
+ contacts[k] = (name, dmr_id, ctype)
+ else:
+ contacts.pop(k, None)
+ if contacts != old_contacts:
+ self._set_contacts(contacts)
+ for number in range(1, self._count() + 1):
+ if self._tx_contact(number) and \
+ self._tx_contact(number) not in contacts:
+ self._set_tx_contact(number, 0,
+ self._chan(number).chtype in (1, 3))
+
+ # RX groups: members by contact name or number.
+ by_name.update({_shown(c[0]): c[1] for c in contacts.values()})
+ old_groups = self._rx_groups()
+ groups = dict(old_groups)
+ for n in range(1, RXG_MAX + 1):
+ if 'rxg_%d_name' % n not in values:
+ continue
+ name = _edited(values['rxg_%d_name' % n],
+ groups.get(n, ('', []))[0])
+ if not name:
+ groups.pop(n, None)
+ continue
+ members = []
+ for item in str(values['rxg_%d_members' % n]).split(','):
+ item = item.strip()
+ if not item:
+ continue
+ if item in by_name:
+ members.append(by_name[item])
+ elif item.isdigit() and 0 < int(item) <= ALL_CALL_ID:
+ members.append(int(item))
+ else:
+ raise errors.InvalidValueError(
+ 'RX group %s: unknown contact %r' % (name, item))
+ if len(members) > RXG_MEMBERS:
+ raise errors.InvalidValueError(
+ 'RX group %s: at most %d contacts' % (name, RXG_MEMBERS))
+ groups[n] = (name, members)
+ if groups != old_groups:
+ self._set_rx_groups(groups)
+
+ # Zones: names, member order, deletion, zone order.
+ if 'zone_order' in values:
+ old = self._zone_list()
+ edited = {}
+ for z, (name, members) in enumerate(old, 1):
+ name = _edited(values.get('zone_%d_name' % z, _shown(name)),
+ name)
+ text = values.get('zone_%d_members' % z)
+ if text is not None:
+ members = []
+ for item in str(text).split(','):
+ item = item.strip()
+ if not item:
+ continue
+ if not item.isdigit() or not \
+ 1 <= int(item) <= self._count():
+ raise errors.InvalidValueError(
+ 'Zone %s: %r is not a channel in use' % (
+ name, item))
+ members.append(int(item))
+ if len(members) > ZONE_MEMBERS:
+ raise errors.InvalidValueError(
+ 'Zone %s: at most %d channels' % (
+ name, ZONE_MEMBERS))
+ if members:
+ edited[z] = (name, members)
+ order = []
+ for item in str(values['zone_order']).split(','):
+ item = item.strip()
+ if not item:
+ continue
+ if not item.isdigit() or int(item) not in range(
+ 1, len(old) + 1) or int(item) in order:
+ raise errors.InvalidValueError(
+ 'Zone order: %r is not a zone number' % item)
+ order.append(int(item))
+ order = [z for z in order if z in edited] + [
+ z for z in edited if z not in order]
+ if not order:
+ raise errors.InvalidValueError('At least one zone must remain')
+ new = [edited[z] for z in order]
+ if new != old:
+ self._set_zone_list(new, {z: i for i, z in enumerate(
+ order, 1)})
+
+ # Scan lists: an empty name removes the list; lists stay numbered
+ # 1..count, so channels pointing at a later list are renumbered.
+ old = self._scan_lists()
+ new, remap = [], {}
+ for n in range(1, SCAN_MAX + 1):
+ if 'scan_%d_name' % n not in values:
+ if n <= len(old):
+ new.append(old[n - 1])
+ remap[n] = len(new)
+ continue
+ name = _edited(values['scan_%d_name' % n],
+ old[n - 1][0] if n <= len(old) else '')
+ if not name:
+ continue
+ members = []
+ for item in str(values['scan_%d_members' % n]).split(','):
+ item = item.strip()
+ if not item:
+ continue
+ if not item.isdigit() or not 1 <= int(item) <= CH_COUNT:
+ raise errors.InvalidValueError(
+ 'Scan list %s: %r is not a channel number' % (
+ name, item))
+ members.append(int(item))
+ if len(members) > SCAN_MEMBERS:
+ raise errors.InvalidValueError(
+ 'Scan list %s: at most %d channels' % (name, SCAN_MEMBERS))
+ opts = bytearray(old[n - 1][2] if n <= len(old) else (
+ old[0][2] if old else SCAN_DEFAULT_OPTS))
+ tx_mode = SCAN_TX_MODES.index(str(values['scan_%d_tx' % n]))
+ ctc_mode = SCAN_CTC_MODES.index(str(values['scan_%d_ctc' % n]))
+ opts[0] = tx_mode << 4 | ctc_mode
+ new.append((name, members, bytes(opts)))
+ remap[n] = len(new)
+ if new != old:
+ self._set_scan_lists(new)
+ for number in range(1, self._count() + 1):
+ _mem = self._chan(number)
+ if int(_mem.scanlist):
+ _mem.scanlist = remap.get(int(_mem.scanlist), 0)
+
+ def get_raw_memory(self, number):
+ return repr(self._chan(number))
+
+ def get_memory(self, number):
+ _mem = self._chan(number)
+ mem = chirp_common.Memory()
+ mem.number = number
+ rx = _mem.rxfreq.get_raw()
+ if number > self._count() or rx in (b'\xFF' * 4, b'\x00' * 4):
+ mem.empty = True
+ return mem
+
+ mem.freq = int(_mem.rxfreq) * 10
+ if _mem.txfreq.get_raw() == b'\xFF' * 4:
+ mem.duplex = 'off'
+ else:
+ chirp_common.split_to_offset(mem, mem.freq,
+ int(_mem.txfreq) * 10)
+ mem.name = str(_mem.name).rstrip('\x00\xFF ')
+ digital = _mem.chtype in (1, 3)
+ mem.mode = 'DMR' if digital else ('FM' if _mem.wide else 'NFM')
+ mem.power = POWER_LEVELS[min(int(_mem.power), 2)]
+ if _mem.step < len(STEPS):
+ mem.tuning_step = STEPS[_mem.step]
+ if not digital:
+ TONE_MODEL.get_tone(_mem, mem)
+
+ mem.extra = self._get_extra(_mem, number)
+ return mem
+
+ @_cached
+ def _dmr_names(self, kind):
+ """{index: name} of the entries in one of the DMR_LISTS."""
+ tag, first, size, length, count = DMR_LISTS[kind]
+ _base, page = self._page(tag)
+ names = {}
+ for n in range(1, count + 1):
+ name = self._text(page[first + (n - 1) * size:][:length])
+ if name:
+ names[n] = name
+ return names
+
+ @_cached
+ def _choice_names(self, kind):
+ """({index: shown name}, name of 0) for _dmr_choice."""
+ if kind == 'radio_id':
+ names = {n: '%s (%d)' % (name, dmr_id) for n, (dmr_id, name)
+ in enumerate(self._radio_ids(), 1)}
+ none = 'Default'
+ elif kind == 'tx_contact':
+ names = {k: c[0] for k, c in self._contacts().items()}
+ none = 'None'
+ elif kind == 'rxgroup':
+ names = {n: g[0] for n, g in self._rx_groups().items()}
+ none = 'None'
+ elif kind == 'scanlist':
+ names = {n: sl[0] for n, sl in enumerate(self._scan_lists(), 1)}
+ none = 'None'
+ else:
+ names, none = self._dmr_names(kind), 'None'
+ return {n: _shown(name) for n, name in names.items()}, none
+
+ def _dmr_choice(self, kind, value):
+ """A RadioSettingValueList for a DMR list index (0 = none)."""
+ names, none = self._choice_names(kind)
+ options = [none] + ['%d: %s' % kv for kv in sorted(names.items())]
+ current = none if not value else '%d: %s' % (
+ value, names.get(value, '(unnamed)'))
+ if current not in options:
+ options.append(current)
+ return RadioSettingValueList(options,
+ current_index=options.index(current))
+
+ def _get_extra(self, _mem, number):
+ extra = RadioSettingGroup('extra', 'Extra')
+ extra.append(RadioSetting(
+ 'chtype', 'Channel type',
+ RadioSettingValueList(CHTYPES, current_index=min(
+ int(_mem.chtype), len(CHTYPES) - 1))))
+ extra.append(RadioSetting(
+ 'colorcode', 'Color code (DMR)',
+ RadioSettingValueInteger(0, 15, int(_mem.colorcode))))
+ extra.append(RadioSetting(
+ 'timeslot', 'Time slot (DMR)',
+ RadioSettingValueList(['1', '2'],
+ current_index=int(_mem.timeslot))))
+ extra.append(RadioSetting(
+ 'tx_contact', 'TX contact (DMR)',
+ self._dmr_choice('tx_contact', self._tx_contact(number))))
+ extra.append(RadioSetting(
+ 'radio_id', 'Radio ID (DMR)',
+ self._dmr_choice('radio_id', int(_mem.radio_id))))
+ extra.append(RadioSetting(
+ 'rxgroup', 'RX group list (DMR)',
+ self._dmr_choice('rxgroup', int(_mem.rxgroup))))
+ extra.append(RadioSetting(
+ 'encrypt', 'Encryption (DMR)',
+ RadioSettingValueBoolean(bool(_mem.encrypt))))
+ extra.append(RadioSetting(
+ 'privacy', 'Encryption key (DMR)',
+ self._dmr_choice('privacy', int(_mem.privacy))))
+ extra.append(RadioSetting(
+ 'scanlist', 'Scan list',
+ self._dmr_choice('scanlist', int(_mem.scanlist))))
+ extra.append(RadioSetting(
+ 'squelch', 'Squelch level',
+ RadioSettingValueInteger(0, 9, min(int(_mem.squelch), 9))))
+ extra.append(RadioSetting(
+ 'forbid_tx', 'Forbid TX',
+ RadioSettingValueBoolean(bool(_mem.forbid_tx))))
+ extra.append(RadioSetting(
+ 'forbid_talkaround', 'Forbid talkaround',
+ RadioSettingValueBoolean(bool(_mem.forbid_talkaround))))
+ admit = TX_ADMIT[_mem.chtype in (1, 3)]
+ extra.append(RadioSetting(
+ 'tx_admit', 'TX admit',
+ RadioSettingValueList(admit, current_index=min(
+ int(_mem.tx_admit), len(admit) - 1))))
+ for name, (label, options) in LIST_EXTRAS.items():
+ extra.append(RadioSetting(
+ name, label, RadioSettingValueList(options, current_index=min(
+ int(getattr(_mem, name)), len(options) - 1))))
+ extra.append(RadioSetting(
+ 'emerg_system', 'Emergency system (DMR)',
+ self._dmr_choice('emergency', int(_mem.emerg_system))))
+ for name, label in BOOL_EXTRAS:
+ extra.append(RadioSetting(
+ name, label,
+ RadioSettingValueBoolean(bool(getattr(_mem, name)))))
+ return extra
+
+ def set_memory(self, mem):
+ _mem = self._chan(mem.number)
+ if mem.empty:
+ _mem.set_raw(b'\xFF' * CH_SIZE)
+ self._update_tx_contact(mem.number, 0, False)
+ # Zones must not point at a channel that no longer exists.
+ for z in range(1, self._zone_count() + 1):
+ members = self._zone_members(z)
+ if mem.number in members:
+ self._set_zone_members(
+ z, [m for m in members if m != mem.number])
+ self._drop_empty_last_zone()
+ self._remove_from_scan_lists(mem.number)
+ if mem.number == self._count():
+ count = mem.number - 1
+ while count and self.get_memory(count).empty:
+ count -= 1
+ self._memobj.ch_count = count
+ return
+
+ if _mem.get_raw() in (b'\xFF' * CH_SIZE, b'\x00' * CH_SIZE):
+ # Defaults as on the channels the radio came with.
+ _mem.set_raw(b'\xFF' * 16 + b'\x00' * 8 + bytes.fromhex(
+ '0000000030000000' '00ffffffff000000' '0000000000000000'))
+ if mem.number > self._count():
+ # Channels skipped over become part of 1..count: make sure they
+ # are empty, not left-over template data (factory records past
+ # the count hold e.g. 400.000 MHz and would show up).
+ for gap in range(self._count() + 1, mem.number):
+ self._chan(gap).set_raw(b'\xFF' * CH_SIZE)
+ self._memobj.ch_count = mem.number
+
+ _mem.name = mem.name.ljust(16, '\x00')[:16]
+ _mem.rxfreq = mem.freq // 10
+ if mem.duplex == 'off':
+ _mem.txfreq.fill_raw(b'\xFF')
+ 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.freq // 10
+
+ digital = mem.mode == 'DMR'
+ if digital and _mem.chtype not in (1, 3):
+ _mem.chtype = 1
+ elif not digital and _mem.chtype not in (0, 2):
+ _mem.chtype = 0
+ _mem.wide = mem.mode == 'FM'
+ _mem.power = POWER_LEVELS.index(mem.power) if mem.power else 2
+ if mem.tuning_step in STEPS:
+ _mem.step = STEPS.index(mem.tuning_step)
+
+ TONE_MODEL.set_tone(mem, _mem)
+
+ tx_contact = self._tx_contact(mem.number)
+ # Values shown clamped (e.g. squelch 12 as 9) stay as they are
+ # unless the user changed them.
+ shown = {s.get_name(): str(s.value)
+ for s in self._get_extra(_mem, mem.number)}
+ for setting in mem.extra:
+ name = setting.get_name()
+ if shown.get(name) == str(setting.value):
+ continue
+ if name == 'chtype':
+ # Keep the analog/digital choice consistent with the mode.
+ value = CHTYPES.index(str(setting.value))
+ if (value in (1, 3)) == digital:
+ _mem.chtype = value
+ elif name == 'timeslot':
+ _mem.timeslot = int(str(setting.value)) - 1
+ elif name == 'tx_admit':
+ value = str(setting.value)
+ options = TX_ADMIT[_mem.chtype in (1, 3)]
+ if value not in options: # mode changed: other list
+ options = TX_ADMIT[_mem.chtype not in (1, 3)]
+ _mem.tx_admit = options.index(value)
+ elif name in LIST_EXTRAS:
+ setattr(_mem, name,
+ LIST_EXTRAS[name][1].index(str(setting.value)))
+ elif name in ('tx_contact', 'radio_id', 'rxgroup', 'privacy',
+ 'emerg_system', 'scanlist'):
+ choice = str(setting.value)
+ value = int(choice.split(':')[0]) if ':' in choice else 0
+ if name == 'tx_contact':
+ tx_contact = value
+ else:
+ setattr(_mem, name, value)
+ else:
+ setattr(_mem, name, int(setting.value))
+ self._update_tx_contact(mem.number, tx_contact, _mem.chtype in (1, 3))
+
+ def _update_tx_contact(self, number, contact, digital):
+ """Write the TX contact table only if something changes, so a page
+ the radio doesn't have isn't created for nothing."""
+ tag, off = self._txc_loc(number)
+ hi, lo = self._page(tag)[1][off:off + 2]
+ if (hi, lo) == (0xFF, 0xFF) and not contact:
+ return
+ if self._tx_contact(number) != contact or (hi & 1) != int(digital):
+ self._set_tx_contact(number, contact, digital)
diff --git a/chirp/drivers/baofeng_uv17Pro.py b/chirp/drivers/baofeng_uv17Pro.py
index 3aa5819..6321c77 100644
--- a/chirp/drivers/baofeng_uv17Pro.py
+++ b/chirp/drivers/baofeng_uv17Pro.py
@@ -569,8 +569,12 @@ class UV17Pro(bfc.BaofengCommonHT):
val.set_charset(DTMF_CHARS)
pttid = RadioSetting("pttid/%i.code" % i,
"Signal Code %i" % (i + 1), val)
- if self.MODEL == "BF-F8HP-PRO":
- pttid.set_doc("3 characters maximum")
+ doc = _("Programs DTMF code %i. A channel or VFO can select "
+ "this code as its PTT-ID and send it when PTT is "
+ "pressed, released, or both.") % (i + 1)
+ if self.MODEL in ("BF-F8HP-PRO", "UV-5R Mini", "UV-5G Mini"):
+ doc += " " + _("Use at most 3 digits.")
+ pttid.set_doc(doc)
pttid.set_apply_callback(self.apply_code, self._memobj.pttid[i], 5)
dtmfe.append(pttid)
@@ -585,6 +589,8 @@ class UV17Pro(bfc.BaofengCommonHT):
RadioSettingValueString(
0, 10, self._filterCodeName(_nameobj.name),
False, CHARSET_GB2312))
+ rs.set_doc(_("Sets the call name for DTMF code %i, up to 10 "
+ "characters long.") % (i + 1))
rs.set_apply_callback(self.apply_codename, _nameobj)
dtmfe.append(rs)
@@ -593,8 +599,13 @@ class UV17Pro(bfc.BaofengCommonHT):
val = RadioSettingValueString(0, 5, _code, False)
val.set_charset(DTMF_CHARS)
rs = RadioSetting("ani.code", "ANI Code", val)
+ doc = _("Programs the radio's numeric Automatic Number "
+ "Identification code. ANI is a DTMF PTT-ID that can "
+ "identify this radio to a dispatcher or other compatible "
+ "equipment.")
if self.MODEL == "BF-F8HP-PRO":
- rs.set_doc("3 characters maximum")
+ doc += " " + _("Use at most 3 digits.")
+ rs.set_doc(doc)
rs.set_apply_callback(self.apply_code, self._memobj.ani, 5)
dtmfe.append(rs)
@@ -606,6 +617,9 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
RadioSettingValueList(self.LIST_DTMFSPEED,
current_index=val))
+ rs.set_doc(_("Sets how long each DTMF tone is transmitted. Increase "
+ "this if the receiving system does not reliably decode "
+ "the digits."))
dtmfe.append(rs)
if _mem.ani.dtmfoff > 0xC3:
@@ -615,6 +629,9 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)",
RadioSettingValueList(self.LIST_DTMFSPEED,
current_index=val))
+ rs.set_doc(_("Sets the silent gap between transmitted DTMF tones. "
+ "Increase this if the receiving system cannot separate "
+ "adjacent digits."))
dtmfe.append(rs)
if self._has_when_to_send_aniid:
@@ -622,6 +639,9 @@ class UV17Pro(bfc.BaofengCommonHT):
"ani.aniid", "When to send ANI ID",
RadioSettingValueList(
LIST_PTTID, current_index=_mem.ani.aniid))
+ rs.set_doc(_("Controls when the ANI code is sent: BOT when PTT is "
+ "pressed, EOT when PTT is released, Both at both "
+ "times, or Off."))
dtmfe.append(rs)
if _mem.settings.hangup >= len(LIST_HANGUPTIME):
@@ -631,6 +651,8 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("settings.hangup", "Hang-up time",
RadioSettingValueList(LIST_HANGUPTIME,
current_index=val))
+ rs.set_doc(_("Sets how long the DTMF decoder remains active after a "
+ "valid code before returning to its normal state."))
dtmfe.append(rs)
def get_settings_common_basic(self, basic, _mem):
@@ -641,6 +663,13 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("settings.squelch", "Squelch",
RadioSettingValueList(
self.SQUELCH_LIST, current_index=val))
+ rs.set_doc(_("Sets how strong a received signal must be before the "
+ "speaker unmutes. 0 leaves the squelch open so you hear "
+ "noise all the time, higher values reject more weak "
+ "signals and noise. Raise this value if the speaker "
+ "keeps unmuting on interference, lower it if distant "
+ "stations are being cut off.") + " " +
+ _("Off is level 0."))
basic.append(rs)
if _mem.settings.tot >= len(self.LIST_TIMEOUT):
@@ -650,6 +679,12 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("settings.tot", "Timeout Timer",
RadioSettingValueList(
self.LIST_TIMEOUT, current_index=val))
+ rs.set_doc(_("Limits how long a single transmission may last. When "
+ "the time runs out the radio stops transmitting until "
+ "PTT is released, which prevents overheating and stops "
+ "a stuck PTT from blocking the channel for everyone "
+ "else.") + " " +
+ _("Off places no limit on the length of a transmission."))
basic.append(rs)
if _mem.settings.dualstandby >= len(self.LIST_DUAL_WATCH):
@@ -659,6 +694,9 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("settings.dualstandby", "Dual Watch",
RadioSettingValueList(
self.LIST_DUAL_WATCH, current_index=val))
+ rs.set_doc(_("Periodically checks both the A and B displayed "
+ "frequencies. When either receives a signal, the radio "
+ "stays on it until that signal disappears."))
basic.append(rs)
if _mem.settings.powerondistype >= len(self.LIST_POWERON_DISPLAY_TYPE):
@@ -669,6 +707,8 @@ class UV17Pro(bfc.BaofengCommonHT):
RadioSettingValueList(
self.LIST_POWERON_DISPLAY_TYPE,
current_index=_mem.settings.powerondistype))
+ rs.set_doc(_("Chooses the startup display, such as a logo or the "
+ "battery voltage."))
basic.append(rs)
if self._has_voice:
@@ -679,10 +719,15 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("settings.voice", "Voice Prompt",
RadioSettingValueList(
self.LIST_VOICE, current_index=val))
+ rs.set_doc(_("Selects the language of the menus and the spoken "
+ "voice prompts."))
basic.append(rs)
rs = RadioSetting("settings.voicesw", "Enable Voice",
RadioSettingValueBoolean(_mem.settings.voicesw))
+ rs.set_doc(_("Announces the channel number and other operations out "
+ "loud as you use the radio. It can be intrusive in quiet "
+ "surroundings."))
basic.append(rs)
if _mem.settings.backlight >= len(self.LIST_BACKLIGHT_TIMER):
@@ -693,10 +738,17 @@ class UV17Pro(bfc.BaofengCommonHT):
RadioSettingValueList(
self.LIST_BACKLIGHT_TIMER,
current_index=val))
+ rs.set_doc(_("Sets how many seconds the display backlight remains on "
+ "after a key press or radio activity.") + " " +
+ _("Always On keeps it lit all the time."))
basic.append(rs)
rs = RadioSetting("settings.autolock", "Key Auto Lock",
RadioSettingValueBoolean(_mem.settings.autolock))
+ rs.set_doc(_("Automatically locks the keypad to prevent accidental "
+ "changes.") + " " +
+ _("When it is off, the keypad can still be locked by "
+ "hand."))
basic.append(rs)
if _mem.settings.beep >= len(self.LIST_BEEP):
@@ -707,22 +759,33 @@ class UV17Pro(bfc.BaofengCommonHT):
RadioSettingValueList(
self.LIST_BEEP,
current_index=_mem.settings.beep))
+ rs.set_doc(_("Sounds a short confirmation tone as you operate the "
+ "radio. Turn it off when the radio has to be used "
+ "discreetly."))
basic.append(rs)
rs = RadioSetting("settings.roger", "Roger",
RadioSettingValueBoolean(_mem.settings.roger))
+ rs.set_doc(_("Sends a short tone at the end of each transmission so "
+ "other stations can hear that you released PTT."))
basic.append(rs)
rs = RadioSetting("settings.chadistype", "Channel A display type",
RadioSettingValueList(
self.LIST_MODE,
current_index=_mem.settings.chadistype))
+ rs.set_doc(_("In channel mode, chooses whether display line A shows "
+ "the memory channel number, its programmed name, or its "
+ "frequency."))
basic.append(rs)
rs = RadioSetting("settings.chbdistype", "Channel B display type",
RadioSettingValueList(
self.LIST_MODE,
current_index=_mem.settings.chbdistype))
+ rs.set_doc(_("In channel mode, chooses whether display line B shows "
+ "the memory channel number, its programmed name, or its "
+ "frequency."))
basic.append(rs)
def get_settings_pro_basic(self, basic, _mem):
@@ -734,12 +797,21 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("settings.savemode", "Save Mode",
RadioSettingValueList(self.LIST_PW_SAVEMODE,
current_index=val))
+ rs.set_doc(_("Cuts standby power consumption by switching the "
+ "receiver off and on in a repeating cycle once no signal "
+ "has been received for a few seconds. It considerably "
+ "extends battery life, at the cost of occasionally "
+ "clipping the first moment of an incoming "
+ "transmission."))
basic.append(rs)
rs = RadioSetting("settings.totalarm", "Timeout Timer Alarm",
RadioSettingValueList(
LIST_TIMEOUT_ALARM,
current_index=_mem.settings.totalarm))
+ rs.set_doc(_("Warns you the selected number of seconds before the "
+ "time-out timer ends a transmission. Off turns the "
+ "warning off."))
basic.append(rs)
if self._has_pilot_tone:
@@ -747,42 +819,68 @@ class UV17Pro(bfc.BaofengCommonHT):
RadioSettingValueList(
LIST_PILOT_TONE,
current_index=_mem.settings.tone))
+ rs.set_doc(_("Selects the tone-burst frequency sent for repeater "
+ "access."))
basic.append(rs)
rs = RadioSetting("settings.sidetone", "Side Tone",
RadioSettingValueList(
LIST_SIDE_TONE,
current_index=_mem.settings.sidetone))
+ rs.set_doc(_("Chooses which transmitted DTMF tones are also heard "
+ "through the radio speaker. Off mutes all; KB Side Tone "
+ "sounds manually keyed tones; ANI Side Tone sounds "
+ "automatic ANI/PTT-ID tones; KB + ANI Side Tone sounds "
+ "both."))
basic.append(rs)
rs = RadioSetting("settings.tailclear", "Tail Clear",
RadioSettingValueBoolean(_mem.settings.tailclear))
+ rs.set_doc(_("Transmits a special end-of-transmission signal intended "
+ "to reduce the squelch burst heard by another compatible "
+ "handheld."))
basic.append(rs)
rs = RadioSetting("settings.scanmode", "Scan Mode",
RadioSettingValueList(
LIST_SCANMODE,
current_index=_mem.settings.scanmode))
+ rs.set_doc(_("Controls what scanning does after finding a signal. "
+ "Time resumes after a preset time, Carrier resumes after "
+ "the signal disappears, and Search stops scanning on the "
+ "detected frequency or channel."))
basic.append(rs)
rs = RadioSetting("settings.alarmmode", "Alarm Mode",
RadioSettingValueList(
LIST_ALARMMODE,
current_index=_mem.settings.alarmmode))
+ rs.set_doc(_("Chooses what the emergency alarm does. Local sounds "
+ "the alarm on this radio only, Send Tone transmits a "
+ "repeating alarm tone, and Send Code transmits the "
+ "digits 119 followed by the ANI code."))
basic.append(rs)
rs = RadioSetting("settings.alarmtone", "Sound Alarm",
RadioSettingValueBoolean(_mem.settings.alarmtone))
+ rs.set_doc(_("Enables or disables the alarm sound.") + " " +
+ _("Off keeps the alarm silent on this radio's own "
+ "speaker."))
basic.append(rs)
rs = RadioSetting("settings.keylock", "Key Lock",
RadioSettingValueBoolean(_mem.settings.keylock))
+ rs.set_doc(_("Sets the current keypad-lock state.") + " " +
+ _("Hold the * key on the radio to lock or unlock the "
+ "keypad."))
basic.append(rs)
rs = RadioSetting("settings.menuquittime", "Menu Quit Timer",
RadioSettingValueList(
self.LIST_MENU_QUIT_TIME,
current_index=_mem.settings.menuquittime))
+ rs.set_doc(_("Sets how long the menu stays open without a key press "
+ "before the radio leaves it."))
basic.append(rs)
if self._has_send_id_delay:
@@ -790,12 +888,19 @@ class UV17Pro(bfc.BaofengCommonHT):
RadioSettingValueList(
self.LIST_ID_DELAY,
current_index=_mem.settings.pttdly))
+ rs.set_doc(_("Delays transmission of the automatic ANI/PTT-ID "
+ "code after PTT is pressed, allowing the receiving "
+ "path time to open before the code is sent."))
basic.append(rs)
rs = RadioSetting("settings.ctsdcsscantype", "QT Save Mode",
RadioSettingValueList(
LIST_QT_SAVEMODE,
current_index=_mem.settings.ctsdcsscantype))
+ rs.set_doc(_("Chooses where a CTCSS or DCS code found by scanning "
+ "in Frequency (VFO) mode is saved: Both saves it as "
+ "the receive and transmit code, RX only as the receive "
+ "code, and TX only as the transmit code."))
basic.append(rs)
def getKey1shortIndex(value):
@@ -843,18 +948,20 @@ class UV17Pro(bfc.BaofengCommonHT):
def get_key_index(value):
return KEY_CODE_TO_INDEX.get(int(value), 0)
+ short_doc = _("Chooses what a short press of side key %i does.")
+ long_doc = _("Chooses what a long press of side key %i does.")
KEY_SETTINGS = [
("_has_skey1_short", "settings.key1short", "Skey1 Short",
- "key1short", apply_key1short),
+ "key1short", apply_key1short, short_doc % 1),
("_has_skey1_long", "settings.key1long", "Skey1 Long",
- "key1long", apply_key1long),
+ "key1long", apply_key1long, long_doc % 1),
("_has_skey2_short", "settings.key2short", "Skey2 Short",
- "key2short", apply_key2short),
+ "key2short", apply_key2short, short_doc % 2),
("_has_skey2_long", "settings.key2long", "Skey2 Long",
- "key2long", apply_key2long),
+ "key2long", apply_key2long, long_doc % 2),
]
- for flag, path, label, attr, apply_cb in KEY_SETTINGS:
+ for flag, path, label, attr, apply_cb, doc in KEY_SETTINGS:
if getattr(self, flag):
rs = RadioSetting(
path,
@@ -865,6 +972,7 @@ class UV17Pro(bfc.BaofengCommonHT):
getattr(_mem.settings, attr))
)
)
+ rs.set_doc(doc)
rs.set_apply_callback(apply_cb, _mem.settings)
basic.append(rs)
@@ -879,39 +987,61 @@ class UV17Pro(bfc.BaofengCommonHT):
RadioSettingValueList(
LIST_WORKMODE,
current_index=_mem.settings.chaworkmode))
+ rs.set_doc(_("Selects Frequency (VFO) mode for direct tuning or "
+ "Channel (MR) mode for programmed memories on display "
+ "A."))
basic.append(rs)
rs = RadioSetting("settings.chbworkmode", "Channel B work mode",
RadioSettingValueList(
LIST_WORKMODE,
current_index=_mem.settings.chbworkmode))
+ rs.set_doc(_("Selects Frequency (VFO) mode for direct tuning or "
+ "Channel (MR) mode for programmed memories on display "
+ "B."))
basic.append(rs)
rs = RadioSetting("settings.rpttailclear", "Rpt Tail Clear",
RadioSettingValueList(
LIST_RPT_TAIL_CLEAR,
current_index=_mem.settings.rpttailclear))
+ rs.set_doc(_("Selects the squelch-tail elimination setting used for "
+ "communication through a compatible repeater. Use 0 ms "
+ "when the repeater does not support this feature."))
basic.append(rs)
rs = RadioSetting("settings.rpttaildet", "Rpt Tail Delay",
RadioSettingValueList(
LIST_RPT_TAIL_CLEAR,
current_index=_mem.settings.rpttaildet))
+ rs.set_doc(_("Sets the delay before repeater squelch-tail "
+ "elimination is applied. Match this timing to the "
+ "repeater; use 0 ms when the feature is not required."))
basic.append(rs)
rs = RadioSetting("settings.rstmenu", "Enable Menu Rst",
RadioSettingValueBoolean(_mem.settings.rstmenu))
+ rs.set_doc(_("Controls whether the radio's front-panel RESET menu is "
+ "available. This does not reset the radio by itself."))
basic.append(rs)
if self._has_voxsw:
rs = RadioSetting("settings.voxsw", "Vox Switch",
RadioSettingValueBoolean(_mem.settings.voxsw))
+ rs.set_doc(_("Voice operated transmit. The radio starts "
+ "transmitting when you speak towards the microphone, "
+ "so hands-free conversation is possible without "
+ "pressing PTT."))
basic.append(rs)
rs = RadioSetting("settings.vox", "Vox Level",
RadioSettingValueList(
LIST_VOX_LEVEL_ALT,
current_index=_mem.settings.vox))
+ rs.set_doc(_("Sets the VOX sensitivity. Too sensitive a setting "
+ "keys the transmitter on the noise around the radio, "
+ "too insensitive a setting fails to pick up your "
+ "voice."))
basic.append(rs)
else:
rs = RadioSetting("settings.vox", "Vox Level",
@@ -924,6 +1054,9 @@ class UV17Pro(bfc.BaofengCommonHT):
RadioSettingValueList(
LIST_VOX_DELAY_TIME,
current_index=_mem.settings.voxdlytime))
+ rs.set_doc(_("How long the transmitter stays keyed after you stop "
+ "speaking. A longer delay avoids dropping the "
+ "transmission during natural pauses in speech."))
basic.append(rs)
if self._has_gps:
@@ -947,10 +1080,14 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("settings.bluetooth", "Bluetooth",
RadioSettingValueBoolean(
_mem.settings.bluetooth))
+ rs.set_doc(_("Turns on Bluetooth so that the radio can be "
+ "programmed wirelessly from a phone app."))
basic.append(rs)
rs = RadioSetting("settings.fmenable", "Disable FM radio",
RadioSettingValueBoolean(_mem.settings.fmenable))
+ rs.set_doc(_("Blocks use of the broadcast FM radio receiver. When "
+ "it is off, the FM radio can be used as normal."))
basic.append(rs)
if self._has_zone_linking:
@@ -990,6 +1127,8 @@ class UV17Pro(bfc.BaofengCommonHT):
freqA.set_validate_callback(my_validate)
rs = RadioSetting("vfo.a.freq", "Frequency", freqA)
rs.set_apply_callback(apply_freq, _mem.vfo.a)
+ rs.set_doc(_("Sets the receive frequency shown on display line A in "
+ "Frequency (VFO) mode."))
vfoA.append(rs)
freqB = RadioSettingValueString(0, 10,
@@ -997,6 +1136,8 @@ class UV17Pro(bfc.BaofengCommonHT):
freqB.set_validate_callback(my_validate)
rs = RadioSetting("vfo.b.freq", "Frequency", freqB)
rs.set_apply_callback(apply_freq, _mem.vfo.b)
+ rs.set_doc(_("Sets the receive frequency shown on display line B in "
+ "Frequency (VFO) mode."))
vfoB.append(rs)
if _mem.vfo.a.sftd >= len(LIST_SHIFTS):
@@ -1006,6 +1147,10 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.a.sftd", "Shift",
RadioSettingValueList(
LIST_SHIFTS, current_index=val))
+ rs.set_doc(_("Sets VFO A's repeater shift direction. + transmits "
+ "above the receive frequency, - transmits below it, "
+ "and Off uses the same frequency for transmit and "
+ "receive."))
vfoA.append(rs)
if _mem.vfo.b.sftd >= len(LIST_SHIFTS):
@@ -1015,6 +1160,10 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.b.sftd", "Shift",
RadioSettingValueList(
LIST_SHIFTS, current_index=val))
+ rs.set_doc(_("Sets VFO B's repeater shift direction. + transmits "
+ "above the receive frequency, - transmits below it, "
+ "and Off uses the same frequency for transmit and "
+ "receive."))
vfoB.append(rs)
def convert_bytes_to_offset(bytes):
@@ -1034,6 +1183,10 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.a.offset",
"Offset (0.0-999.999)", offA)
rs.set_apply_callback(apply_offset, _mem.vfo.a)
+ rs.set_doc(_("Sets the difference in MHz between VFO A's receive "
+ "and transmit frequencies. The Shift setting "
+ "determines whether this offset is added or "
+ "subtracted."))
vfoA.append(rs)
offB = RadioSettingValueString(
@@ -1041,6 +1194,10 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.b.offset",
"Offset (0.0-999.999)", offB)
rs.set_apply_callback(apply_offset, _mem.vfo.b)
+ rs.set_doc(_("Sets the difference in MHz between VFO B's receive "
+ "and transmit frequencies. The Shift setting "
+ "determines whether this offset is added or "
+ "subtracted."))
vfoB.append(rs)
POWER_LEVELS = [str(x) for x in self.POWER_LEVELS]
@@ -1051,6 +1208,8 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.a.lowpower", "Power",
RadioSettingValueList(POWER_LEVELS,
current_index=val))
+ rs.set_doc(_("Selects VFO A's transmitter power. Use the lowest "
+ "power that provides reliable communication."))
vfoA.append(rs)
if _mem.vfo.b.lowpower >= len(POWER_LEVELS):
@@ -1060,6 +1219,8 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.b.lowpower", "Power",
RadioSettingValueList(POWER_LEVELS,
current_index=val))
+ rs.set_doc(_("Selects VFO B's transmitter power. Use the lowest "
+ "power that provides reliable communication."))
vfoB.append(rs)
if _mem.vfo.a.wide >= len(LIST_BANDWIDTH):
@@ -1069,6 +1230,9 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.a.wide", "Bandwidth",
RadioSettingValueList(LIST_BANDWIDTH,
current_index=val))
+ rs.set_doc(_("Selects wide or narrow FM for VFO A. Use Narrow where "
+ "required by the channel plan to reduce "
+ "interference to adjacent channels."))
vfoA.append(rs)
if _mem.vfo.b.wide >= len(LIST_BANDWIDTH):
@@ -1078,6 +1242,9 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.b.wide", "Bandwidth",
RadioSettingValueList(LIST_BANDWIDTH,
current_index=val))
+ rs.set_doc(_("Selects wide or narrow FM for VFO B. Use Narrow where "
+ "required by the channel plan to reduce "
+ "interference to adjacent channels."))
vfoB.append(rs)
if _mem.vfo.a.scode >= len(self.SCODE_LIST):
@@ -1087,6 +1254,9 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.a.scode", "Signal Code",
RadioSettingValueList(self.SCODE_LIST,
current_index=val))
+ rs.set_doc(_("Selects which of the %i programmed DTMF PTT-ID codes "
+ "VFO A uses. Edit the code itself under DTMF "
+ "Encode Settings.") % len(self.SCODE_LIST))
vfoA.append(rs)
if _mem.vfo.b.scode >= len(self.SCODE_LIST):
@@ -1096,6 +1266,9 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.b.scode", "Signal Code",
RadioSettingValueList(self.SCODE_LIST,
current_index=val))
+ rs.set_doc(_("Selects which of the %i programmed DTMF PTT-ID codes "
+ "VFO B uses. Edit the code itself under DTMF "
+ "Encode Settings.") % len(self.SCODE_LIST))
vfoB.append(rs)
if _mem.vfo.a.step >= len(self.STEPS):
@@ -1105,6 +1278,10 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.a.step", "Tuning Step",
RadioSettingValueList(self.LIST_STEPS,
current_index=val))
+ rs.set_doc(_("Sets how far VFO A moves for each tuning step and "
+ "while scanning in Frequency mode. Choose the "
+ "spacing used by the frequencies you intend to "
+ "tune."))
vfoA.append(rs)
if _mem.vfo.b.step >= len(self.STEPS):
@@ -1114,6 +1291,10 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("vfo.b.step", "Tuning Step",
RadioSettingValueList(self.LIST_STEPS,
current_index=val))
+ rs.set_doc(_("Sets how far VFO B moves for each tuning step and "
+ "while scanning in Frequency mode. Choose the "
+ "spacing used by the frequencies you intend to "
+ "tune."))
vfoB.append(rs)
workmode.append(vfoA)
@@ -1384,17 +1565,26 @@ class UV17Pro(bfc.BaofengCommonHT):
rs = RadioSetting("bcl", "BCL",
RadioSettingValueBoolean(_mem.bcl))
+ rs.set_doc(_("Prevents transmitting on a channel that is already in "
+ "use. Pressing PTT on a busy channel sounds an alert "
+ "tone instead of keying the transmitter."))
mem.extra.append(rs)
rs = RadioSetting("pttid", "PTT ID",
RadioSettingValueList(self.PTTID_LIST,
current_index=_mem.pttid))
+ rs.set_doc(_("Controls when this channel sends the selected DTMF "
+ "PTT-ID: BOT when PTT is pressed, EOT when PTT is "
+ "released, Both at both times, or Off."))
mem.extra.append(rs)
scode = (_mem.scode - self._scode_offset) % len(self.SCODE_LIST)
rs = RadioSetting("scode", "S-CODE",
RadioSettingValueList(self.SCODE_LIST,
current_index=scode))
+ rs.set_doc(_("Selects which of the %i programmed DTMF PTT-ID codes "
+ "this channel transmits. Edit the code itself under "
+ "DTMF Encode Settings.") % len(self.SCODE_LIST))
mem.extra.append(rs)
if self._has_scramble:
@@ -1418,10 +1608,18 @@ class UV17Pro(bfc.BaofengCommonHT):
if self.MODEL in ["K6", "UV-5R Mini"]:
rs = RadioSetting("sqmode", "RX DTMF",
RadioSettingValueBoolean(_mem.sqmode))
+ rs.set_doc(_("Selects whether the radio uses DTMF codes, "
+ "together with CTCSS or DCS, to decide when to "
+ "unmute the speaker on this channel. Off unmutes "
+ "it on the correct CTCSS or DCS alone."))
mem.extra.append(rs)
rs = RadioSetting("fhss", "FHSS",
RadioSettingValueBoolean(_mem.fhss))
+ rs.set_doc(_("Turns on the privacy function the manual calls "
+ "Encryption for this channel. Other radios can "
+ "only understand the conversation if they have it "
+ "turned on as well and use the same DCS code."))
mem.extra.append(rs)
mem.name = str(name).replace('\xFF', ' ').replace('\x00', ' ').rstrip()
@@ -2477,12 +2675,17 @@ class UV5RMini(UV17Pro):
RadioSettingValueList(
self.LIST_SEPARATE_CODE,
current_index=_mem.ani.separatecode))
+ rs.set_doc(_("Selects the special DTMF digit interpreted as a "
+ "separator by the decoder."))
dtmfe.append(rs)
rs = RadioSetting("ani.groupcallcode", "Group Call Code",
RadioSettingValueList(
self.LIST_GROUP_CALL_CODE,
current_index=_mem.ani.groupcallcode))
+ rs.set_doc(_("Selects the special DTMF digit interpreted as a "
+ "group-call wildcard by the decoder. Off assigns no "
+ "group-call digit."))
dtmfe.append(rs)
_codeobj = self._memobj.upcode.code
@@ -2491,6 +2694,8 @@ class UV5RMini(UV17Pro):
val = RadioSettingValueString(0, 16, _code, False)
val.set_charset(DTMF_CHARS)
rs = RadioSetting("upcode.code", "Up Code", val)
+ rs.set_doc(_("Programs the DTMF code sent at the beginning of a "
+ "transmission (BOT)."))
rs.set_apply_callback(self.apply_code, self._memobj.upcode, 16)
dtmfe.append(rs)
@@ -2500,6 +2705,8 @@ class UV5RMini(UV17Pro):
val = RadioSettingValueString(0, 16, _code, False)
val.set_charset(DTMF_CHARS)
rs = RadioSetting("downcode.code", "Down Code", val)
+ rs.set_doc(_("Programs the DTMF code sent at the end of a "
+ "transmission (EOT)."))
rs.set_apply_callback(self.apply_code, self._memobj.downcode, 16)
dtmfe.append(rs)
diff --git a/chirp/drivers/boblov_x3plus.py b/chirp/drivers/boblov_x3plus.py
index 6c9a6aa..c8c6373 100644
--- a/chirp/drivers/boblov_x3plus.py
+++ b/chirp/drivers/boblov_x3plus.py
@@ -108,6 +108,11 @@ class BoblovX3Plus(chirp_common.CloneModeRadio,
chirp_common.PowerLevel('High', watts=2.00)]
_memsize = 0x03F0
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (len(filedata) == cls._memsize and
+ b'P310' in filedata[0x03D0:0x03D8])
_ranges = [
(0x0000, 0x03F0),
]
@@ -123,16 +128,6 @@ class BoblovX3Plus(chirp_common.CloneModeRadio,
"download to a CHIRP Radio Images (*.img) file.\n")
return rp
- @classmethod
- def match_model(cls, filedata, filename):
- """Given contents of a stored file (@filedata), return True if
- this radio driver handles the represented model"""
-
- if len(filedata) != cls._memsize:
- return False
-
- return b'P310' in filedata[0x03D0:0x03D8]
-
def get_features(self):
"""Return a RadioFeatures object for this radio"""
diff --git a/chirp/drivers/btech.py b/chirp/drivers/btech.py
index b7dc55a..964b638 100644
--- a/chirp/drivers/btech.py
+++ b/chirp/drivers/btech.py
@@ -687,8 +687,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
POWER_LEVELS = self._power_levels
rf.valid_power_levels = POWER_LEVELS
- # normal dual bands
- rf.valid_bands = [self._vhf_range, self._uhf_range]
+ # normal dual bands. The configured ranges use whole MHz boundaries,
+ # while supported channel centers can reach 50 kHz above the limit.
+ rf.valid_bands = [self._vhf_range,
+ (self._uhf_range[0], self._uhf_range[1] + 50001)]
# 220 band
if self.BANDS == 3 or self.BANDS == 4:
diff --git a/chirp/drivers/ft1d.py b/chirp/drivers/ft1d.py
index 05ae55d..2b82ffb 100644
--- a/chirp/drivers/ft1d.py
+++ b/chirp/drivers/ft1d.py
@@ -1453,8 +1453,8 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
for index in range(0, 60):
if aprs_msg[index].flag != 255:
- astring = \
- str(aprs_msg[index].dst_callsign).partition("\xFF")[0]
+ astring = bitwise.get_string(aprs_msg[index].dst_callsign)\
+ .partition("\xFF")[0]
val = RadioSettingValueString(
0, 9, chirp_common.sanitize_string(astring) +
@@ -1465,8 +1465,8 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
"Dst Callsign %d" % index, val)
menu.append(rs)
- astring = \
- str(aprs_msg[index].path_and_body).partition("\xFF")[0]
+ astring = bitwise.get_string(aprs_msg[index].path_and_body)\
+ .partition("\xFF")[0]
val = RadioSettingValueString(
0, 66, chirp_common.sanitize_string(astring))
val.set_mutable(False)
@@ -1485,18 +1485,20 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
# There is probably a more pythonesque way to do this
scl = int(aprs_meta[index].sender_callsign[0])
dcl = int(aprs_beacon[index].dst_callsign[0])
- if scl != 255 and scl != 0: # ignore if empty send call
- callsign = str(aprs_meta[index].sender_callsign).rstrip("\xFF")
- val = RadioSettingValueString(0, 9, callsign)
+ if scl not in (255, 0): # ignore if empty send call
+ _c = chirp_common.sanitize_string(
+ bitwise.get_string(aprs_meta[index].sender_callsign))
+ val = RadioSettingValueString(0, 9, _c)
val.set_mutable(False)
rs = RadioSetting(
"aprs_beacon.src_callsign%d" % index,
"SRC Callsign %d" % index, val)
menu.append(rs)
- if dcl != 255 and dcl != 0: # ignore if empty dest call
- val = str(aprs_beacon[index].dst_callsign)
- val = RadioSettingValueString(0, 9, val.rstrip("\xFF"))
+ if dcl not in (255, 0): # ignore if empty dest call
+ val = chirp_common.sanitize_string(
+ bitwise.get_string(aprs_beacon[index].dst_callsign))
+ val = RadioSettingValueString(0, 9, val)
val.set_mutable(False)
rs = RadioSetting(
"aprs_beacon.dst_callsign%d" % index,
@@ -1520,23 +1522,21 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("aprs_beacon.time%d" % index, "Time", val)
menu.append(rs)
- if dcl != 255 and dcl != 0: # ignore if empty dest call
- path = str(aprs_beacon[index].path).replace("\x00", " ")
- path = ''.join(c for c in path
- if c in string.printable).strip()
- path = str(path).replace("\xE0", "*")
+ if dcl not in (255, 0): # ignore if empty dest call
+ path = bitwise.get_string(aprs_beacon[index].path)\
+ .replace("\x00", " ")
+ path = chirp_common.sanitize_string(str(path).strip()
+ .replace("\xE0", "*"))
val = RadioSettingValueString(0, 32, path)
val.set_mutable(False)
rs = RadioSetting(
"aprs_beacon.path%d" % index, "Digipath", val)
menu.append(rs)
- body = str(aprs_beacon[index].body).rstrip("\xFF")
- checksum = body[-2:]
- body = ''.join(s for s in body[:-2]
- if s in string.printable).translate(
- str.maketrans(
- "", "", "\x09\x0a\x0b\x0c\x0d"))
+ body = bitwise.get_string(aprs_beacon[index].body)\
+ .rstrip("\xFF")
+ # checksum = body[-2:]
+ body = chirp_common.sanitize_string(body)
try:
val = RadioSettingValueString(0, 134, body.strip())
except Exception as e:
@@ -1823,7 +1823,7 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
# MYCALL
mycall = self._memobj.my_call
- mycallstr = str(mycall.callsign).rstrip("\xff").rstrip()
+ mycallstr = bitwise.get_string(mycall.callsign).rstrip("\xff\00 ")
mycalle = RadioSettingValueString(0, 10, mycallstr, False,
charset=self._MYCALL_CHR_SET)
rs = RadioSetting('mycall.callsign',
diff --git a/chirp/drivers/ft2d.py b/chirp/drivers/ft2d.py
index aa08b26..5c1dcb3 100644
--- a/chirp/drivers/ft2d.py
+++ b/chirp/drivers/ft2d.py
@@ -154,11 +154,12 @@ class FT3D(FT2D):
MODEL = "FT3D"
VARIANT = "R"
+ _adms_ext = '.ft3d'
_model = b"AH72M"
FORMATS = [directory.register_format('FT3D ADMS-11', '*.ft3d')]
def load_mmap(self, filename):
- if filename.lower().endswith('.ft3d'):
+ if filename.lower().endswith(self._adms_ext):
with open(filename, 'rb') as f:
self._adms_header = f.read(0x18C)
if b'ADMS11, Version=1.0.0.0' not in self._adms_header:
@@ -173,9 +174,9 @@ class FT3D(FT2D):
chirp_common.CloneModeRadio.load_mmap(self, filename)
def save_mmap(self, filename):
- if filename.lower().endswith('.ft3d'):
+ if filename.lower().endswith(self._adms_ext):
if not hasattr(self, '_adms_header'):
- raise Exception('Unable to save .img to .ft3d')
+ raise Exception(f'Unable to save .img to {self._adms_ext}')
with open(filename, 'wb') as f:
f.write(self._adms_header)
f.write(self._mmap.get_packed())
@@ -183,9 +184,39 @@ class FT3D(FT2D):
else:
chirp_common.CloneModeRadio.save_mmap(self, filename)
- @classmethod
- def match_model(cls, filedata, filename):
- if filename.endswith('.ft3d'):
- return True
+
+@directory.register
+class FT5D(FT2D):
+ """Yaesu FT-5D"""
+ MODEL = "FT5D"
+ VARIANT = "R"
+
+ _adms_ext = '.ft5d'
+ _model = b"AH82M"
+ FORMATS = [directory.register_format('FT5D ADMS-14', '*.ft5d')]
+
+ def load_mmap(self, filename):
+ if filename.lower().endswith(self._adms_ext):
+ with open(filename, 'rb') as f:
+ self._adms_header = f.read(0x18C)
+ if b'ADMS14, Version=1.0.' not in self._adms_header:
+ raise errors.ImageDetectFailed(
+ 'Unsupported version found in ADMS file')
+ LOG.debug('ADMS Header:\n%s',
+ util.hexprint(self._adms_header))
+ self._mmap = memmap.MemoryMapBytes(f.read())
+ LOG.info('Loaded ADMS-14 file at offset 0x18C')
+ self.process_mmap()
+ else:
+ chirp_common.CloneModeRadio.load_mmap(self, filename)
+
+ def save_mmap(self, filename):
+ if filename.lower().endswith(self._adms_ext):
+ if not hasattr(self, '_adms_header'):
+ raise Exception(f'Unable to save .img to {self._adms_ext}')
+ with open(filename, 'wb') as f:
+ f.write(self._adms_header)
+ f.write(self._mmap.get_packed())
+ LOG.info('Wrote ADMS-14 file')
else:
- return super().match_model(filedata, filename)
+ chirp_common.CloneModeRadio.save_mmap(self, filename)
diff --git a/chirp/drivers/ft4.py b/chirp/drivers/ft4.py
index 56c276f..7a0ffcb 100644
--- a/chirp/drivers/ft4.py
+++ b/chirp/drivers/ft4.py
@@ -280,14 +280,9 @@ def sendcmd(pipe, cmd, response_len, retry=0):
if not response:
if cmd == PROGRAM_CMD:
raise errors.RadioNoResponse()
- raise errors.RadioError("No response from radio")
- if len(response) != response_len:
- raise errors.RadioError("Incomplete response from radio")
else:
response = b""
ack = pipe.read(1)
- if not ack:
- raise errors.RadioError("No response from radio")
if ack != b'\x06':
if retry < 5:
LOG.debug("retry: " + str(retry))
@@ -555,6 +550,20 @@ VALID_STEPS = [x for x in STEP_CODE if x]
US_LEGAL_STEPS = list(VALID_STEPS) # copy to pass to UI on US radios
US_LEGAL_STEPS.remove(6.25) # euro radios just use STEP_CODE
+
+def _valid_tuning_step(radio, mem):
+ """Return an explicit legal step compatible with the memory frequency."""
+ if mem.tuning_step in radio.legal_steps:
+ return mem.tuning_step
+
+ try:
+ return chirp_common.required_step(mem.freq, radio.legal_steps)
+ except errors.InvalidDataError:
+ # Preserve an otherwise-invalid frequency without exposing Auto;
+ # memory validation reports that the frequency is unsupported.
+ return radio.legal_steps[0]
+
+
# Map the radio image sql_type (0-6) to the CHIRP mem values.
# Yaesu "TSQL" and "DCS" each map to different CHIRP values depending on the
# radio values of the tx and rx tone codes. The table is a list of rows, one
@@ -685,8 +694,10 @@ DTCS_MAP = [
]
# The legal PAGER codes are the same as the CTCSS codes, but we
-# pass them to the UI as a list of strings
-EPCS_CODES = [format(flt) for flt in [0] + TONE_MAP[1:]]
+# pass them to the UI as a list of strings. The radio stores the
+# code minus one (0-49 for codes 1-50), so the list starts with the
+# first CTCSS tone.
+EPCS_CODES = [format(flt) for flt in TONE_MAP[1:]]
# allow a child class to add a param to its class
@@ -891,7 +902,7 @@ class YaesuSC35GenericRadio(chirp_common.CloneModeRadio,
["OFF"] + ["%0.1f" % (x * 0.5) for x in range(1, 24 + 1)]),
("bclo", "Busy Channel Lock-Out", ["OFF", "ON"]),
("beep", "Enable the Beeper", ["KEY+SC", "KEY", "OFF"]),
- ("bsy_led", "Busy LED", ["ON", "OFF"]),
+ ("bsy_led", "Busy LED", ["OFF", "ON"]),
("edg_beep", "Band Edge Beeper", ["OFF", "ON"]),
("vox", "VOX", ["OFF", "ON"]),
("rf_squelch", "RF Squelch Threshold",
@@ -1162,7 +1173,10 @@ class YaesuSC35GenericRadio(chirp_common.CloneModeRadio,
mem.empty = not retrieve_bit(self._memobj.enable, ndx)
mem.skip = SKIPS[retrieve_bit(self._memobj.scan, ndx)]
else:
- mem.empty = False
+ # A programmable key's channel slot is only written when the
+ # key is set to use one; otherwise it stays erased (all 0xFF).
+ mem.empty = (regtype == "prog" and
+ _mem.get_raw() == b"\xFF" * len(_mem.get_raw()))
mem.extd_number = sname
mem.immutable = ["number", "extd_number", "name", "skip"]
@@ -1307,6 +1321,20 @@ class YaesuFT4GenericRadio(YaesuSC35GenericRadio):
"w/n.dev", "wx.alert" # 45-46
]
+ def _valid_tuning_step(self, mem):
+ """Return an explicit legal step compatible with the frequency."""
+ return _valid_tuning_step(self, mem)
+
+ def get_memory(self, memref):
+ mem = super().get_memory(memref)
+ mem.tuning_step = self._valid_tuning_step(mem)
+ return mem
+
+ def set_memory(self, mem):
+ mem = mem.dupe()
+ mem.tuning_step = self._valid_tuning_step(mem)
+ return super().set_memory(mem)
+
class YaesuFT65GenericRadio(YaesuSC35GenericRadio):
"""
@@ -1334,6 +1362,22 @@ class YaesuFT65GenericRadio(YaesuSC35GenericRadio):
"vox", "wfm.rcv", "wide/nar", "wx alert", "scramble" # 35-39
]
+ def _valid_tuning_step(self, mem):
+ """Return a legal explicit step for an FT-65-family memory."""
+ if mem.tuning_step in self.legal_steps:
+ return mem.tuning_step
+ return _valid_tuning_step(self, mem)
+
+ def get_memory(self, memref):
+ mem = super().get_memory(memref)
+ mem.tuning_step = self._valid_tuning_step(mem)
+ return mem
+
+ def set_memory(self, mem):
+ mem = mem.dupe()
+ mem.tuning_step = self._valid_tuning_step(mem)
+ return super().set_memory(mem)
+
# Classes for each individual radio.
diff --git a/chirp/drivers/ft450d.py b/chirp/drivers/ft450d.py
index 2550b04..9921cc5 100644
--- a/chirp/drivers/ft450d.py
+++ b/chirp/drivers/ft450d.py
@@ -108,6 +108,12 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
CHARSET.remove("\\")
MEM_SIZE = 15017
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ if len(filedata) == cls.MEM_SIZE + 7:
+ return filedata[cls.MEM_SIZE:].startswith(cls.MODEL.encode())
+ return False
# block 9 (135 Bytes long) is to be repeated 101 times
_block_lengths = [4, 84, 135, 162, 135, 162, 151, 130, 135, 127, 189, 103]
@@ -940,47 +946,70 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("data_modes", "DATA MODE",
RadioSettingValueList(options,
current_index=vx_data))
- rs.set_doc("Extended Data Modes")
+ rs.set_doc(_("Selects the data mode a DIG channel uses. RTTY is FSK "
+ "radioteletype keyed by a terminal unit or RTTY "
+ "software, while USER-L and USER-U carry audio based "
+ "data modes such as packet on the lower or upper "
+ "sideband. N/A is for channels that are not in DIG "
+ "mode."))
mem.extra.append(rs)
rs = RadioSetting("ipo", "IPO",
RadioSettingValueBoolean(bool(_mem.ipo)))
- rs.set_doc("Bypass preamp")
+ rs.set_doc(_("Intercept point optimization. Bypasses the receiver's "
+ "RF preamplifier so that the incoming signal goes "
+ "straight to the first mixer. This gives up some "
+ "sensitivity in exchange for better handling of strong "
+ "signals and high noise levels."))
mem.extra.append(rs)
rs = RadioSetting("att", "ATT",
RadioSettingValueBoolean(bool(_mem.att)))
- rs.set_doc("10dB front end attenuator")
+ rs.set_doc(_("Reduces all incoming signals by 20 dB, for use when "
+ "extremely strong nearby stations or high noise levels "
+ "degrade reception. Between 30 kHz and 1.7 MHz the radio "
+ "always attenuates, whatever this setting."))
mem.extra.append(rs)
rs = RadioSetting("cnturon", "Contour Filter",
RadioSettingValueBoolean(_mem.cnturon))
- rs.set_doc("Contour filter on/off")
+ rs.set_doc(_("Turns on the DSP contour filter, which gently cuts or "
+ "boosts one part of the receive passband. Cutting "
+ "suppresses interference or excessive components of a "
+ "signal, boosting brings out the components that make it "
+ "easier to understand."))
mem.extra.append(rs)
options = ["Peak", "Null"]
rs = RadioSetting("cnturpk", "Contour Filter Mode",
RadioSettingValueList(options,
current_index=_mem.cnturpk))
+ rs.set_doc(_("Chooses whether the contour filter boosts (Peak) or "
+ "cuts (Null) the part of the passband it is set to."))
mem.extra.append(rs)
options = ["Low", "High"]
rs = RadioSetting("cnturgn", "Contour Filter Gain",
RadioSettingValueList(options,
current_index=_mem.cnturgn))
- rs.set_doc("Filter gain/attenuation")
+ rs.set_doc(_("Sets how strongly the contour filter boosts or cuts. "
+ "Low gives a gentle effect, High a stronger one."))
mem.extra.append(rs)
options = ["-2", "-1", "Center", "+1", "+2"]
rs = RadioSetting("cnturmd", "Contour Filter Notch",
RadioSettingValueList(options,
current_index=_mem.cnturmd))
- rs.set_doc("Filter notch offset")
+ rs.set_doc(_("Moves the part of the passband the contour filter acts "
+ "on, from -2 at the low end through Center to +2 at the "
+ "high end."))
mem.extra.append(rs)
rs = RadioSetting("notch", "Notch Filter",
RadioSettingValueBoolean(_mem.notch))
- rs.set_doc("IF bandpass filter")
+ rs.set_doc(_("Turns on the IF notch filter, a narrow and deep filter "
+ "that removes a single interfering carrier or whistle "
+ "from inside the receive passband."))
mem.extra.append(rs)
vx = 1
@@ -991,19 +1020,31 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
vx = 2
rs = RadioSetting("notch_pos", "Notch Position",
RadioSettingValueList(options, current_index=vx))
- rs.set_doc("IF bandpass filter shift")
+ rs.set_doc(_("Places the IF notch filter below the center of the "
+ "passband, at the center or above it. The exact notch "
+ "frequency is fine tuned on the radio with the DSP/SEL "
+ "knob."))
mem.extra.append(rs)
stx, options = filters_for_mode(mem.mode)
vx = getattr(_mem, stx)
rs = RadioSetting("bpfilter", "IF Bandpass Filter Width",
RadioSettingValueList(all_filters(), options[vx]))
- rs.set_doc("DSP IF bandpass Notch width (Hz)")
+ rs.set_doc(_("Sets the width of the DSP IF filter. A narrower filter "
+ "rejects interference close to the signal, a wider one "
+ "sounds more natural when the band is quiet. The widths "
+ "depend on the mode: 1.8, 2.4 or 3.0 kHz for SSB, 300 "
+ "Hz, 500 Hz or 2.4 kHz for CW, 300 Hz, 2.4 or 3.0 kHz "
+ "for DIG, 3.0, 6.0 or 9.0 kHz for AM, and 2.5 or 5.0 kHz "
+ "for FM. A width the mode does not offer is replaced "
+ "with the closest one it does."))
mem.extra.append(rs)
rs = RadioSetting("dnr_on", "DSP Noise Reduction",
RadioSettingValueBoolean(bool(_mem.dnr_on)))
- rs.set_doc("Digital noise processing")
+ rs.set_doc(_("Turns on the DSP digital noise reduction, which reduces "
+ "random background noise on the HF and 50 MHz bands. It "
+ "is especially effective on SSB."))
mem.extra.append(rs)
options = ["Off", "1", "2", "3", "4", "5", "6", "7",
@@ -1011,7 +1052,11 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("dnr_val", "DSP Noise Reduction Alg",
RadioSettingValueList(options,
current_index=_mem.dnr_val))
- rs.set_doc("Digital noise reduction algorithm number (1-11)")
+ rs.set_doc(_("Selects which of the eleven noise reduction algorithms "
+ "is used. Each one is designed for a different kind of "
+ "noise, so try them in turn to find the one that best "
+ "suppresses the noise currently heard. Off also turns "
+ "DSP Noise Reduction off."))
mem.extra.append(rs)
return mem # end get_memory
@@ -1150,16 +1195,6 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
else:
setattr(_mem, setting.get_name(), setting.value)
- @classmethod
- def match_model(cls, filedata, filename):
- """Match the opened/downloaded image to the correct version"""
- if len(filedata) == cls.MEM_SIZE + 7: # +7 bytes of model name
- rid = filedata[cls.MEM_SIZE:cls.MEM_SIZE + 7]
- if rid.startswith(cls.MODEL.encode()):
- return True
- else:
- return False
-
def _invert_me(self, setting, obj, atrb):
"""Callback: from inverted logic 1-bit booleans"""
invb = not setting.value
@@ -1216,11 +1251,19 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("ext_mnu", "Extended menu",
RadioSettingValueBoolean(_settings.ext_mnu))
- rs.set_doc("Enables access to extended settings in the radio")
+ rs.set_doc(_("Shows all 62 items of the radio's Menu Mode. When off, "
+ "the menu on the radio offers only the 16 most often "
+ "used items."))
tab.append(rs)
# Issue #8183 bugfix
rs = RadioSetting("apo", "APO time (Hrs)",
RadioSettingValueInteger(0, 12, _settings.apo))
+ rs.set_doc(_("Turns the radio off automatically once no button, knob "
+ "or microphone key has been used and nothing has been "
+ "transmitted for the selected number of hours. APO "
+ "flashes on the display and a tone sounds in the last "
+ "minute before the radio switches off. 0 disables "
+ "automatic power off."))
tab.append(rs)
options = ["%i" % i for i in range(0, 21)]
@@ -1228,62 +1271,122 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("tot", "TX 'TOT' time-out (mins)",
RadioSettingValueList(options,
current_index=_settings.tot))
+ rs.set_doc(_("Limits how long a single transmission may last. When "
+ "the time runs out the radio stops transmitting until "
+ "PTT is released, which prevents overheating and stops a "
+ "stuck PTT from blocking the channel for everyone else."))
tab.append(rs)
bx = not _settings.cat_rts # Convert from Enable=0
rs = RadioSetting("cat_rts", "CAT RTS flow control",
RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "cat_rts")
+ rs.set_doc(_("Enables the RTS line of the CAT jack. Turn it off when "
+ "the computer or cable does not provide RTS. A radio "
+ "that follows the frequency of another radio set to "
+ "F-TRANS also needs it off."))
tab.append(rs)
options = ["0", "100ms", "1000ms", "3000ms"]
rs = RadioSetting("cat_tot", "CAT Timeout",
RadioSettingValueList(options,
current_index=_settings.cat_tot))
+ rs.set_doc(_("Sets the time-out timer for computer control commands "
+ "arriving on the CAT jack. Command input that continues "
+ "for longer than this time is cut off. The radio shows "
+ "the shortest setting as 10 ms."))
tab.append(rs)
options = ["4800", "9600", "19200", "38400", "Data"]
rs = RadioSetting("catrate", "CAT rate",
RadioSettingValueList(options,
current_index=_settings.catrate))
+ rs.set_doc(_("Sets the baud rate of the CAT jack, which must match "
+ "the computer control software. Data turns the CAT jack "
+ "into an RTTY interface instead: RTTY software keys the "
+ "FSK shift through the serial data input and uses RTS as "
+ "PTT."))
tab.append(rs)
rs = RadioSetting("mem_grp", "Mem groups",
RadioSettingValueBoolean(_settings.mem_grp))
+ rs.set_doc(_("Divides the 500 regular memory channels into ten groups "
+ "of 50, numbered M-01-01 to M-10-50. Channels are then "
+ "selected and scanned one group at a time."))
tab.append(rs)
rs = RadioSetting("scn_res", "Resume scan (secs)",
RadioSettingValueInteger(0, 10, _settings.scn_res))
+ rs.set_doc(_("Sets when the scan resumes after it has paused on a "
+ "signal. 1 to 10 resumes after that many seconds, 0 "
+ "selects BUSY, which waits until the signal has gone. In "
+ "SSB, CW and SSB based data modes the scanner instead "
+ "steps slowly across a signal, giving you time to stop "
+ "it."))
tab.append(rs)
rs = RadioSetting("clk_sft", "CPU clock shift",
RadioSettingValueBoolean(_settings.clk_sft))
+ rs.set_doc(_("Shifts the frequency of the radio's CPU clock slightly. "
+ "Only use it to move an internally generated spurious "
+ "signal, or birdie, off a frequency you want to listen "
+ "on."))
tab.append(rs)
rs = RadioSetting("split", "TX/RX Frequency Split",
RadioSettingValueBoolean(_settings.split))
+ rs.set_doc(_("Turns on split frequency operation: the radio receives "
+ "on VFO-A and transmits on VFO-B, or the other way "
+ "round. The two VFOs may use different modes and even "
+ "different bands."))
tab.append(rs)
rs = RadioSetting("qspl_f", "Quick-Split freq offset (kHz)",
RadioSettingValueInteger(-20, 20, _settings.qspl_f))
+ rs.set_doc(_("Sets the offset Quick Split applies. Holding SPLIT/STEP "
+ "for a second sets the transmit VFO to the receive "
+ "frequency plus this offset, in the same mode as the "
+ "receive VFO, and turns split operation on."))
tab.append(rs)
rs = RadioSetting("emergen", "Alaska Emergency Mem 5167.5 kHz",
RadioSettingValueBoolean(_settings.emergen))
+ rs.set_doc(_("Enables transmit and receive on the Alaska emergency "
+ "channel, 5167.5 kHz, which then appears as MEM-EMG in "
+ "Memory mode. It may only be used by stations in or "
+ "within 92.6 km of Alaska, and only for emergency "
+ "communications involving the immediate protection of "
+ "life or property."))
tab.append(rs)
rs = RadioSetting("stby_beep", "PTT release 'Standby' beep",
RadioSettingValueBoolean(_settings.stby_beep))
+ rs.set_doc(_("Transmits a short beep when PTT is released, before the "
+ "radio returns to receive, to tell other stations that "
+ "your transmission has ended."))
tab.append(rs)
options = ["ATAS", "EXT ATU", "INT ATU", "INTRATU", "F-TRANS"]
rs = RadioSetting("tuner", "Antenna Tuner",
RadioSettingValueList(options,
current_index=_settings.tuner))
+ rs.set_doc(_("Selects what the TUNE button controls. ATAS is the "
+ "optional ATAS-100/-120 active-tuning antenna, EXT ATU "
+ "the optional FC-40 external tuner, and INT ATU the "
+ "built-in tuner acting on the transmit signal only, "
+ "while INTRATU puts the built-in tuner in the receive "
+ "path as well. F-TRANS instead sends this radio's "
+ "frequency to a second radio of the same model whenever "
+ "TUNE is pressed, for single operator two radio (SO2R) "
+ "operation."))
tab.append(rs)
rs = RadioSetting("rfpower", "RF power (watts)",
RadioSettingValueInteger(5, 100, _settings.rfpower))
+ rs.set_doc(_("Sets the transmit power in watts. Use the lowest power "
+ "that provides reliable communication, and a half to a "
+ "third of full power for data transmissions longer than "
+ "a few minutes."))
tab.append(rs) # End of _do_general_settings
def _do_cw_settings(self, cw): # - - - CW - - -
@@ -1292,84 +1395,141 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("cw_dly", "CW break-in delay (ms * 10)",
RadioSettingValueInteger(0, 300, _settings.cw_dly))
+ rs.set_doc(_("Sets how long the transmitter stays on after you stop "
+ "sending in semi break-in CW, in steps of 10 ms, so 25 "
+ "means 250 ms. A longer delay suits operators who pause "
+ "often while sending. The radio can also be set to FULL, "
+ "full break-in, which lets you hear between the "
+ "characters you send."))
cw.append(rs)
options = ["%i Hz" % i for i in range(400, 801, 100)]
rs = RadioSetting("cwpitch", "CW pitch",
RadioSettingValueList(options,
current_index=_settings.cwpitch))
+ rs.set_doc(_("Sets the pitch of the CW sidetone, which is also the "
+ "offset of the transmitted carrier and the center of the "
+ "CW receive filter. Tuning a station in until its tone "
+ "matches the sidetone puts you on its frequency."))
cw.append(rs)
rs = RadioSetting("cwspeed", "CW speed (wpm)",
RadioSettingValueInteger(4, 60, _settings.cwspeed))
- rs.set_doc("Cpm is Wpm * 5")
+ rs.set_doc(_("Sets the sending speed of the built-in electronic keyer "
+ "in words per minute. The radio can also show it in "
+ "characters per minute, five times the wpm value. With a "
+ "CW QSK delay of 25 ms keep it at 50 wpm or below, and "
+ "with 30 ms at 42 wpm or below, or the radio cannot "
+ "transmit."))
cw.append(rs)
options = ["1:%1.1f" % (i / 10) for i in range(25, 46, 1)]
rs = RadioSetting("cwweigt", "CW weight",
RadioSettingValueList(options,
current_index=_settings.cwweigt))
+ rs.set_doc(_("Sets the dot to dash ratio of the built-in electronic "
+ "keyer. At 1:3.0, the standard weighting, a dash lasts "
+ "three times as long as a dot."))
cw.append(rs)
options = ["15ms", "20ms", "25ms", "30ms"]
rs = RadioSetting("cw_qsk", "CW delay before TX in QSK mode",
RadioSettingValueList(options,
current_index=_settings.cw_qsk))
+ rs.set_doc(_("Sets the delay between closing the key and the carrier "
+ "being transmitted in QSK operation with the built-in "
+ "keyer. At 25 ms keep the CW speed at 50 wpm or below, "
+ "and at 30 ms at 42 wpm or below, or the radio cannot "
+ "transmit."))
cw.append(rs)
rs = RadioSetting("cwstone_sgn", "CW sidetone volume Linked",
RadioSettingValueBoolean(_settings.cwstone_sgn))
- rs.set_doc("If set; volume is relative to AF Gain knob.")
+ rs.set_doc(_("Makes the CW sidetone volume follow the AF GAIN knob, "
+ "offset by the CW sidetone linked volume. When off, the "
+ "sidetone plays at the CW sidetone fixed volume whatever "
+ "the AF GAIN setting."))
cw.append(rs)
rs = RadioSetting("cwstone_lnk", "CW sidetone linked volume",
RadioSettingValueInteger(-50, 50,
_settings.cwstone_lnk))
+ rs.set_doc(_("Sets the sidetone volume relative to the receive audio "
+ "level set by AF GAIN, when CW sidetone volume Linked is "
+ "on. 0 makes the sidetone as loud as the received audio, "
+ "negative values make it quieter and positive values "
+ "louder."))
cw.append(rs)
rs = RadioSetting("cwstone_fix", "CW sidetone fixed volume",
RadioSettingValueInteger(0, 100,
_settings.cwstone_fix))
+ rs.set_doc(_("Sets the CW sidetone volume, from 0 to 100, used when "
+ "CW sidetone volume Linked is off."))
cw.append(rs)
options = ["Numeric", "Alpha", "Mixed"]
rs = RadioSetting("cwtrain", "CW Training mode",
RadioSettingValueList(options,
current_index=_settings.cwtrain))
+ rs.set_doc(_("Selects the characters the CW training feature sends: "
+ "digits only, letters only, or both mixed. Training "
+ "plays random five character Morse groups through the "
+ "sidetone at the CW speed, without transmitting."))
cw.append(rs)
rs = RadioSetting("cw_auto", "CW key jack- auto CW mode",
RadioSettingValueBoolean(_settings.cw_auto))
- rs.set_doc("Enable for CW mode auto-set when keyer pluuged in.")
+ rs.set_doc(_("Lets the KEY jack send CW while the radio is in SSB "
+ "mode, so you can answer a station in CW without "
+ "changing mode. When off, the KEY jack only works in CW "
+ "mode."))
cw.append(rs)
options = ["Normal", "Reverse"]
rs = RadioSetting("cw_key", "CW paddle wiring",
RadioSettingValueList(options,
current_index=_settings.cw_key))
+ rs.set_doc(_("Swaps the dot and dash sides of a keyer paddle without "
+ "rewiring it, for example for a left-handed operator. "
+ "Normal sends dots from the plug tip and dashes from the "
+ "ring, Reverse the other way round."))
cw.append(rs)
rs = RadioSetting("beacon_time", "CW beacon Tx interval (secs)",
RadioSettingValueInteger(0, 255,
_settings.beacon_time))
+ rs.set_doc(_("Sets the pause in seconds between repeats of a CW "
+ "beacon message. 0 turns the repeat off, so that each "
+ "message is sent once per button press, as with a CW "
+ "message keyer."))
cw.append(rs)
tmp = self._chars2str(_beacon.t1, 40)
rs = RadioSetting("t1", "CW Beacon Line 1",
RadioSettingValueString(0, 40, tmp))
rs.set_apply_callback(self._my_str2ary, _beacon, "t1", 40)
+ rs.set_doc(_("CW beacon message 1, up to 40 characters, sent in CW "
+ "mode by the PLAY1 function of a programmable button. "
+ "The radio can send A to Z, 0 to 9, /, space and @."))
cw.append(rs)
tmp = self._chars2str(_beacon.t2, 40)
rs = RadioSetting("t2", "CW Beacon Line 2",
RadioSettingValueString(0, 40, tmp))
rs.set_apply_callback(self._my_str2ary, _beacon, "t2", 40)
+ rs.set_doc(_("CW beacon message 2, up to 40 characters, sent in CW "
+ "mode by the PLAY2 function of a programmable button. "
+ "The radio can send A to Z, 0 to 9, /, space and @."))
cw.append(rs)
tmp = self._chars2str(_beacon.t3, 40)
rs = RadioSetting("t3", "CW Beacon Line 3",
RadioSettingValueString(0, 40, tmp))
rs.set_apply_callback(self._my_str2ary, _beacon, "t3", 40)
+ rs.set_doc(_("CW beacon message 3, up to 40 characters, sent in CW "
+ "mode by the PLAY3 function of a programmable button. "
+ "The radio can send A to Z, 0 to 9, /, space and @."))
cw.append(rs) # END _do_cw_settings
def _do_panel_settings(self, pnlset): # - - - Panel settings
@@ -1379,56 +1539,86 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("amfmdial", "AM&FM Dial",
RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "amfmdial")
+ rs.set_doc(_("Lets the MAIN DIAL knob change the frequency in AM and "
+ "FM modes. When off, the MAIN DIAL does not tune in "
+ "these modes."))
pnlset.append(rs)
options = ["440 Hz", "880 Hz", "1760 Hz"]
rs = RadioSetting("beepton", "Beep frequency",
RadioSettingValueList(options,
current_index=_settings.beepton))
+ rs.set_doc(_("Sets the pitch of the beep the radio sounds to confirm "
+ "button presses."))
pnlset.append(rs)
rs = RadioSetting("beepvol_sgn", "Beep volume Linked",
RadioSettingValueBoolean(_settings.beepvol_sgn))
- rs.set_doc("If set; volume is relative to AF Gain knob.")
+ rs.set_doc(_("Makes the beep volume follow the AF GAIN knob, offset "
+ "by the Linked beep volume. When off, the beep plays at "
+ "the Fixed beep volume whatever the AF GAIN setting."))
pnlset.append(rs)
rs = RadioSetting("beepvol_lnk", "Linked beep volume",
RadioSettingValueInteger(-50, 50,
_settings.beepvol_lnk))
- rs.set_doc("Relative to AF-Gain setting.")
+ rs.set_doc(_("Sets the beep volume relative to the receive audio "
+ "level set by AF GAIN, when Beep volume Linked is on. 0 "
+ "makes the beep as loud as the received audio, negative "
+ "values make it quieter and positive values louder."))
pnlset.append(rs)
rs = RadioSetting("beepvol_fix", "Fixed beep volume",
RadioSettingValueInteger(0, 100,
_settings.beepvol_fix))
- rs.set_doc("When Linked setting is unchecked.")
+ rs.set_doc(_("Sets the beep volume, from 0 to 100, used when Beep "
+ "volume Linked is off."))
pnlset.append(rs)
rs = RadioSetting("cont", "LCD Contrast",
RadioSettingValueInteger(1, 24, _settings.cont))
- rs.set_doc("This setting does not appear to do anything...")
+ rs.set_doc(_("Sets the contrast of the display, from 1 to 24. "
+ "Changing it here has not been seen to have a visible "
+ "effect on the radio."))
pnlset.append(rs)
rs = RadioSetting("dimmer", "LCD Dimmer",
RadioSettingValueInteger(1, 8, _settings.dimmer))
+ rs.set_doc(_("Sets the brightness of the display illumination, from 1 "
+ "to 8."))
pnlset.append(rs)
options = ["RF-Gain", "Squelch"]
rs = RadioSetting("sql_rfg", "Squelch/RF-Gain",
RadioSettingValueList(options,
current_index=_settings.sql_rfg))
+ rs.set_doc(_("Chooses what the SQL/RF GAIN knob controls. RF-Gain "
+ "sets the gain of the receiver's RF and IF stages, "
+ "Squelch mutes the receiver while no signal is present. "
+ "Scanning needs Squelch, because the scanner stops on "
+ "signals strong enough to open the squelch."))
pnlset.append(rs)
options = ["Frequencies", "Panel", "All"]
rs = RadioSetting("lockmod", "Lock Mode",
RadioSettingValueList(options,
current_index=_settings.lockmod))
+ rs.set_doc(_("Selects what the LOCK button locks. Frequencies locks "
+ "the controls that change the frequency, including the "
+ "microphone UP, DWN and FAST keys. Panel locks all front "
+ "panel keys and knobs, and All locks both the front "
+ "panel and the microphone keys. POWER and LOCK always "
+ "remain usable."))
pnlset.append(rs)
options = ["Dial", "SEL"]
rs = RadioSetting("clar_btn", "CLAR button control",
RadioSettingValueList(options,
current_index=_settings.clar_btn))
+ rs.set_doc(_("Chooses which knob sets the clarifier offset after CLAR "
+ "is pressed: the MAIN DIAL or the DSP/SEL knob. The "
+ "clarifier shifts the receive frequency without changing "
+ "the transmit frequency."))
pnlset.append(rs)
if _settings.dialstp_mode == 0: # AM/FM
@@ -1438,20 +1628,32 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("dialstp", "Dial tuning step",
RadioSettingValueList(options,
current_index=_settings.dialstp))
+ rs.set_doc(_("Sets how far the frequency moves for each step of the "
+ "MAIN DIAL knob: 1, 10 or 20 Hz in SSB and CW, 100 or "
+ "200 Hz in AM and FM."))
pnlset.append(rs)
options = ["0.5secs", "1.0secs", "1.5secs", "2.0secs"]
rs = RadioSetting("keyhold", "Buttons hold-to-activate time",
RadioSettingValueList(options,
current_index=_settings.keyhold))
+ rs.set_doc(_("Sets how long a button has to be held to activate its "
+ "press and hold function. A shorter press activates the "
+ "button's normal function."))
pnlset.append(rs)
rs = RadioSetting("m_tune", "Memory tune",
RadioSettingValueBoolean(_settings.m_tune))
+ rs.set_doc(_("Allows tuning away from a recalled memory or Home "
+ "channel with the MAIN DIAL, as with a VFO. The stored "
+ "channel does not change unless you write the new "
+ "settings to it."))
pnlset.append(rs)
rs = RadioSetting("peakhold", "S-Meter display hold (1sec)",
RadioSettingValueBoolean(_settings.peakhold))
+ rs.set_doc(_("Holds the peak S-meter reading for one second, which "
+ "makes the meter easier to read."))
pnlset.append(rs)
options = ["CW Sidetone", "CW Speed", "100 kHz step", "1 MHz Step",
@@ -1459,6 +1661,10 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("seldial", "SEL dial 2nd function (push)",
RadioSettingValueList(options,
current_index=_settings.seldial))
+ rs.set_doc(_("Assigns the second function the DSP/SEL knob takes on "
+ "after it is pressed briefly: adjusting the CW sidetone "
+ "volume, the CW keyer speed, the microphone gain or the "
+ "RF power, or tuning in 100 kHz or 1 MHz steps."))
pnlset.append(rs)
# End _do_panel_settings
@@ -1468,10 +1674,19 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("pnl_cs", "C.S. Function",
RadioSettingValueList(self.FUNC_LIST,
current_index=_settings.pnl_cs))
+ rs.set_doc(_("Assigns one of the radio's functions to the front panel "
+ "C.S/VOICE button, for example MONI to listen to your "
+ "own transmission, SWR to transmit a 10 W carrier and "
+ "measure the antenna SWR, or PLAY1 to send CW beacon "
+ "message 1. Choices named after a front panel button act "
+ "like that button."))
pnlcfg.append(rs)
rs = RadioSetting("nb", "Noise blanker",
RadioSettingValueBoolean(_settings.nb))
+ rs.set_doc(_("Turns on the IF noise blanker, which reduces short "
+ "pulses of noise such as those from vehicle ignition "
+ "systems."))
pnlcfg.append(rs)
# The old FT450 uses different codes for the AGC setting, and only uses the
@@ -1489,24 +1704,41 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("agc", "AGC",
RadioSettingValueList(options,
current_index=_settings.agc))
+ rs.set_doc(_("Selects how quickly the automatic gain control lets the "
+ "receiver recover after a strong signal. Fast suits CW "
+ "and data, Slow suits SSB and AM, and Auto picks Slow "
+ "for SSB and AM and Fast for the other modes. With AGC "
+ "off the S-meter no longer moves and strong signals are "
+ "likely to distort."))
pnlcfg.append(rs)
rs = RadioSetting("keyer", "Keyer",
RadioSettingValueBoolean(_settings.keyer))
+ rs.set_doc(_("Turns on the built-in electronic CW keyer, for a keyer "
+ "paddle plugged into the KEY jack. Turn it off to use a "
+ "straight key or an external keyer."))
pnlcfg.append(rs)
rs = RadioSetting("fast", "Fast step",
RadioSettingValueBoolean(_settings.fast))
+ rs.set_doc(_("Speeds up tuning: the MAIN DIAL knob tunes ten times "
+ "faster and the DSP/SEL knob twice as fast."))
pnlcfg.append(rs)
rs = RadioSetting("lock", "Lock (per Lock Mode)",
RadioSettingValueBoolean(_settings.lock))
+ rs.set_doc(_("Locks the controls selected by Lock Mode against "
+ "accidental changes, as the LOCK button does."))
pnlcfg.append(rs)
options = ["PO", "ALC", "SWR"]
rs = RadioSetting("mtr_mode", "S-Meter mode",
RadioSettingValueList(options,
current_index=_settings.mtr_mode))
+ rs.set_doc(_("Selects what the meter shows while transmitting: PO the "
+ "average power output, ALC the relative ALC voltage, or "
+ "SWR the standing wave ratio of the antenna. While "
+ "receiving it always shows the signal strength."))
pnlcfg.append(rs)
# End _do_panel_Buttons
@@ -1515,44 +1747,67 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("vox_dly", "VOX delay (x 100 ms)",
RadioSettingValueInteger(1, 30, _settings.vox_dly))
+ rs.set_doc(_("Sets how long the transmitter stays on after you stop "
+ "speaking in VOX operation, in steps of 100 ms, so 5 "
+ "means 500 ms. A longer delay keeps short pauses in your "
+ "speech from switching the radio back to receive."))
voxdat.append(rs)
rs = RadioSetting("vox_gain", "VOX Gain",
RadioSettingValueInteger(0, 100,
_settings.vox_gain))
+ rs.set_doc(_("Sets the VOX sensitivity. Too sensitive a setting keys "
+ "the transmitter on the noise around the radio, too "
+ "insensitive a setting fails to pick up your voice. 1 is "
+ "the least sensitive setting and 100 the most."))
voxdat.append(rs)
rs = RadioSetting("dig_vox", "Digital VOX Gain",
RadioSettingValueInteger(0, 100,
_settings.dig_vox))
+ rs.set_doc(_("Sets the VOX sensitivity used in DIG mode, so that the "
+ "audio from the data equipment switches the transmitter "
+ "on without a PTT line. 0 turns VOX off in DIG mode."))
voxdat.append(rs)
rs = RadioSetting("d_disp", "User-L/U freq offset (Hz)",
RadioSettingValueInteger(-3000, 30000,
_settings.d_disp, 10))
+ rs.set_doc(_("Shifts the frequency shown on the display in the USER-L "
+ "and USER-U data modes by this many hertz. The radio "
+ "accepts -3000 to +3000 Hz."))
voxdat.append(rs)
options = ["170 Hz", "200 Hz", "425 Hz", "850 Hz"]
rs = RadioSetting("rty_sft", "RTTY FSK Freq Shift",
RadioSettingValueList(options,
current_index=_settings.rty_sft))
+ rs.set_doc(_("Sets the frequency shift between the mark and space "
+ "tones in FSK RTTY. Most amateur RTTY uses 170 Hz."))
voxdat.append(rs)
options = ["1275 Hz", "2125 Hz"]
rs = RadioSetting("rty_ton", "RTTY FSK Mark tone",
RadioSettingValueList(options,
current_index=_settings.rty_ton))
+ rs.set_doc(_("Selects the mark tone for RTTY: 2125 Hz for high tone "
+ "operation or 1275 Hz for low tone operation."))
voxdat.append(rs)
options = ["Normal", "Reverse"]
rs = RadioSetting("rtyrpol", "RTTY Mark/Space RX polarity",
RadioSettingValueList(options,
current_index=_settings.rtyrpol))
+ rs.set_doc(_("Swaps the mark and space tones when receiving RTTY. Try "
+ "Reverse if a station with a good signal cannot be "
+ "decoded."))
voxdat.append(rs)
rs = RadioSetting("rtytpol", "RTTY Mark/Space TX polarity",
RadioSettingValueList(options,
current_index=_settings.rtytpol))
+ rs.set_doc(_("Swaps the mark and space tones of your transmitted RTTY "
+ "signal."))
voxdat.append(rs)
# End _do_vox_settings
@@ -1561,120 +1816,165 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("mic_eq", "Mic Equalizer",
RadioSettingValueInteger(0, 9, _settings.mic_eq))
+ rs.set_doc(_("Selects one of ten DSP equalizer curves for your "
+ "transmitted voice. 0 is flat, 1 to 3 reduce the low, "
+ "middle or high frequencies, and 4 to 6 boost the high, "
+ "middle or low frequencies. 7 boosts the lows and "
+ "reduces the highs, 8 reduces the lows and boosts the "
+ "middle, and 9 reduces the lows and boosts the highs."))
mic.append(rs)
options = ["Low", "Normal", "High"]
rs = RadioSetting("micgain", "Mic Gain",
RadioSettingValueList(options,
current_index=_settings.micgain))
+ rs.set_doc(_("Sets the microphone gain for SSB, AM and FM. Use Low "
+ "with a microphone that has a high output, Normal with "
+ "the supplied hand microphone and High with a microphone "
+ "that has a low output. The speech processor is off at "
+ "Low and on at the other settings."))
mic.append(rs)
rs = RadioSetting("micscan", "Mic scan enabled",
RadioSettingValueBoolean(_settings.micscan))
- rs.set_doc("Enables channel scanning via mic up/down buttons.")
+ rs.set_doc(_("When on, holding the microphone UP or DWN key for about "
+ "a second starts a scan that continues after the key is "
+ "released. When off, the radio only scans while the key "
+ "is held down."))
mic.append(rs)
rs = RadioSetting("pm_dwn", "Mic Down button function",
RadioSettingValueList(self.FUNC_LIST,
current_index=_settings.pm_dwn))
+ rs.set_doc(_("Assigns one of the radio's functions to the DWN key of "
+ "the microphone. DOWN, its normal function, steps the "
+ "frequency or memory channel down."))
mic.append(rs)
rs = RadioSetting("pm_fst", "Mic Fast button function",
RadioSettingValueList(self.FUNC_LIST,
current_index=_settings.pm_fst))
+ rs.set_doc(_("Assigns one of the radio's functions to the FST key of "
+ "the microphone. FAST, its normal function, speeds up "
+ "tuning like the front panel FAST button."))
mic.append(rs)
rs = RadioSetting("pm_up", "Mic Up button function",
RadioSettingValueList(self.FUNC_LIST,
current_index=_settings.pm_up))
+ rs.set_doc(_("Assigns one of the radio's functions to the UP key of "
+ "the microphone. UP, its normal function, steps the "
+ "frequency or memory channel up."))
mic.append(rs)
# End _do_mic_settings
def _do_mymodes_settings(self, mymodes): # - - MYMODES
_settings = self._memobj.settings # Inverted Logic requires callback
+ doc = _("Includes %s in the modes the MODE buttons step through. Turn "
+ "off the modes you never use to reach the others with fewer "
+ "presses.")
bx = not _settings.mym_lsb
rs = RadioSetting("mym_lsb", "LSB", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "mym_lsb")
+ rs.set_doc(doc % "LSB")
mymodes.append(rs)
bx = not _settings.mym_usb
rs = RadioSetting("mym_usb", "USB", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "mym_usb")
+ rs.set_doc(doc % "USB")
mymodes.append(rs)
bx = not _settings.mym_cw
rs = RadioSetting("mym_cw", "CW", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "mym_cw")
+ rs.set_doc(doc % "CW")
mymodes.append(rs)
bx = not _settings.mym_am
rs = RadioSetting("mym_am", "AM", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "mym_am")
+ rs.set_doc(doc % "AM")
mymodes.append(rs)
bx = not _settings.mym_fm
rs = RadioSetting("mym_fm", "FM", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "mym_fm")
+ rs.set_doc(doc % "FM")
mymodes.append(rs)
bx = not _settings.mym_data
rs = RadioSetting("mym_data", "DATA", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "mym_data")
+ rs.set_doc(doc % "DATA")
mymodes.append(rs)
# End _do_mymodes_settings
def _do_mybands_settings(self, mybands): # - - MYBANDS Settings
_settings = self._memobj.settings # Inverted Logic requires callback
+ doc = _("Includes the %s band in the bands the BAND buttons step "
+ "through. Turn off the bands you never use to reach the "
+ "others with fewer presses.")
bx = not _settings.myb_1_8
rs = RadioSetting("myb_1_8", "1.8 MHz", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "myb_1_8")
+ rs.set_doc(doc % "1.8 MHz")
mybands.append(rs)
bx = not _settings.myb_3_5
rs = RadioSetting("myb_3_5", "3.5 MHz", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "myb_3_5")
+ rs.set_doc(doc % "3.5 MHz")
mybands.append(rs)
bx = not _settings.myb_7
rs = RadioSetting("myb_7", "7 MHz", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "myb_7")
+ rs.set_doc(doc % "7 MHz")
mybands.append(rs)
bx = not _settings.myb_10
rs = RadioSetting("myb_10", "10 MHz", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "myb_10")
+ rs.set_doc(doc % "10 MHz")
mybands.append(rs)
bx = not _settings.myb_14
rs = RadioSetting("myb_14", "14 MHz", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "myb_14")
+ rs.set_doc(doc % "14 MHz")
mybands.append(rs)
bx = not _settings.myb_18
rs = RadioSetting("myb_18", "18 MHz", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "myb_18")
+ rs.set_doc(doc % "18 MHz")
mybands.append(rs)
bx = not _settings.myb_21
rs = RadioSetting("myb_21", "21 MHz", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "myb_21")
+ rs.set_doc(doc % "21 MHz")
mybands.append(rs)
bx = not _settings.myb_24
rs = RadioSetting("myb_24", "24 MHz", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "myb_24")
+ rs.set_doc(doc % "24 MHz")
mybands.append(rs)
bx = not _settings.myb_28
rs = RadioSetting("myb_28", "28 MHz", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "myb_28")
+ rs.set_doc(doc % "28 MHz")
mybands.append(rs)
bx = not _settings.myb_50
rs = RadioSetting("myb_50", "50 MHz", RadioSettingValueBoolean(bx))
rs.set_apply_callback(self._invert_me, _settings, "myb_50")
+ rs.set_doc(doc % "50 MHz")
mybands.append(rs)
# End _do_mybands_settings
diff --git a/chirp/drivers/ft7100.py b/chirp/drivers/ft7100.py
index 0c2c5eb..97f2219 100644
--- a/chirp/drivers/ft7100.py
+++ b/chirp/drivers/ft7100.py
@@ -531,6 +531,10 @@ class FT7100Radio(YaesuCloneModeRadio):
IDBLOCK = b"Vartex Standard AH003M M-Map V04"
BAUD_RATE = 9600
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return filedata[0x1ec0:0x1ec0 + len(cls.IDBLOCK)] == cls.IDBLOCK
+
# Return information about this radio's features, including
# how many memories it has, what bands it supports, etc
def get_features(self):
@@ -542,7 +546,7 @@ class FT7100Radio(YaesuCloneModeRadio):
# This radio supports 120 + 10 + 120 + 10 = 260 memories
# These are zero based for chirpc
rf.valid_bands = [
- (108000000, 180000000), # Supports 2-meters tx
+ (108000000, 180000001), # Supports 2-meters tx
(320000000, 999990000), # Supports 70-centimeters tx
]
rf.can_odd_split = True
@@ -1120,10 +1124,6 @@ class FT7100Radio(YaesuCloneModeRadio):
return upper_uhf_limit
@classmethod
- def match_model(cls, filedata, filename):
- return filedata[0x1ec0:0x1ec0+len(cls.IDBLOCK)] == cls.IDBLOCK
-
- @classmethod
def get_prompts(cls):
rp = chirp_common.RadioPrompts()
rp.pre_download = _(
@@ -1158,7 +1158,7 @@ class FT7100RadioVHF(FT7100Radio):
rf = FT7100Radio.get_features(self)
rf.memory_bounds = (1, upper_vhf_limit)
# Normally this band supports 120 + 10 memories. 1 based for chirpw
- rf.valid_bands = [(108000000, 180000000)] # Supports 2-meters tx
+ rf.valid_bands = [(108000000, 180000001)] # Supports 2-meters tx
rf.valid_modes = MODES_VHF
rf.valid_special_chans = ['VFO', 'Home']
rf.has_sub_devices = False
@@ -1202,7 +1202,9 @@ class FT7100RadioUHF(FT7100Radio):
rf.memory_bounds = (1, upper_uhf_limit)
# Normally this band supports 120 + 10 memories. 1 based for chirpw
rf.valid_bands = [(320000000, 999990000)] # Supports 70-centimeters tx
- rf.valid_modes = MODES_UHF
+ # The radio can retain AM on UHF memories, although it ignores it.
+ # Keep it readable/valid so existing images remain round-trippable.
+ rf.valid_modes = MODES_UHF + ["AM"]
rf.valid_special_chans = ['VFO', 'Home']
rf.has_sub_devices = False
return rf
diff --git a/chirp/drivers/ft8000r.py b/chirp/drivers/ft8000r.py
new file mode 100644
index 0000000..c8b2243
--- /dev/null
+++ b/chirp/drivers/ft8000r.py
@@ -0,0 +1,635 @@
+# Copyright 2026 FT-8000 driver contributors
+#
+# 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/>.
+
+"""FT-8000 clone transport and memory editing.
+
+Validated with a physical radio and CH340 cable: 1860 bytes, 9600 8N2,
+individual byte writes with 10 ms requested gaps and cable echo. The generic
+Yaesu ACK/block transport is not applicable. Unmapped settings stay opaque.
+"""
+
+import logging
+import time
+
+from chirp import bitwise, chirp_common, directory, errors, memmap
+from chirp.settings import (MemSetting, RadioSetting, RadioSettingGroup,
+ RadioSettings, RadioSettingValueMap,
+ RadioSettingValueBoolean, RadioSettingValueList,
+ RadioSettingValueString)
+
+
+LOG = logging.getLogger(__name__)
+IMAGE_SIZE = 1860
+HEADER = bytes.fromhex('00 01 26 21 00')
+SENTINELS = {'Left': 145000000, 'Right': 433000000}
+TONES = [67.0, 69.3, 71.9, 74.4, 77.0, 79.7, 82.5, 85.4, 88.5,
+ 91.5, 94.8, 97.4, 100.0, 103.5, 107.2, 110.9, 114.8,
+ 118.8, 123.0, 127.3, 131.8, 136.5, 141.3, 146.2, 151.4,
+ 156.7, 162.2, 167.9, 173.8, 179.9, 186.2, 192.8, 203.5,
+ 210.7, 218.1, 225.7, 233.6, 241.8, 250.3]
+DUPLEXES = ['', '+', '-', 'split']
+TMODES = ['', 'Tone', 'TSQL']
+SPECIALS = ['1L', '1U', '2L', '2U', 'HOME', 'VFO']
+
+RECORD_FORMAT = """
+struct channel {
+ u8 masked:1,
+ skip:1,
+ duplex:2,
+ tx_step:2,
+ rx_step:2;
+ u8 tone_mode:2,
+ tone:6;
+ u24 freq;
+ u24 offset;
+ u8 power:2,
+ unknown1:3,
+ bell:1,
+ am:1,
+ unknown2:1;
+};
+"""
+
+MEM_FORMAT = RECORD_FORMAT + """
+struct controls {
+ u8 unknown1:3,
+ scan:1,
+ unknown2:2,
+ ars:1,
+ search:1;
+};
+struct autodial {
+ u8 count;
+ u8 digits[16];
+};
+struct band_state {
+ u8 memory_mode:1,
+ memory_tune:1,
+ home_mode:1,
+ unknown2:5;
+ u8 unknown3;
+ struct controls control;
+ u8 unknown4[3];
+ struct channel working;
+ struct channel vfo;
+ struct channel home;
+ u8 current_memory;
+ u8 unknown5[6];
+ struct autodial dtmf;
+ u8 unknown6[33];
+ u8 rf_sql;
+ u8 unknown7[4];
+};
+u8 header[5];
+#seekto 0x000B;
+struct {
+ u8 panel_lock:1,
+ key_beep:1,
+ unknown1:1,
+ same_band:1,
+ unknown2:1,
+ vhf_pair:1,
+ sub_off:1,
+ unknown3:1;
+ u8 unknown4:4,
+ dtmf_beep:1,
+ unknown5:1,
+ sub_voltmeter:1,
+ dtmf_speed:1;
+ u16 tot;
+ u8 dimmer;
+ u8 unknown6:4,
+ ibd:1,
+ ptt_lock:1,
+ unknown7:1,
+ sub_mute:1;
+ u8 mute_timeout;
+ u8 apo;
+ u8 volts_offset;
+} settings;
+#seekto 0x001B;
+struct band_state right;
+struct band_state right_saved;
+#seekto 0x011B;
+struct band_state left;
+struct band_state left_saved;
+#seekto 0x021F;
+struct channel right_memory[50];
+struct channel right_pms[4];
+#seekto 0x0409;
+struct channel left_memory[50];
+struct channel left_pms[4];
+#seekto 0x0743;
+u8 checksum;
+"""
+
+# Path, label, encoded choices, displayed choices (None = boolean).
+SETTINGS = [
+ ('settings.apo', 'Auto power off', list(range(13)),
+ ['Off'] + ['%i hour(s)' % i for i in range(1, 13)]),
+ ('settings.tot', 'Transmit timeout', [i * 60 for i in range(61)],
+ ['Off'] + ['%i minute(s)' % i for i in range(1, 61)]),
+ ('settings.dimmer', 'Display brightness', list(range(8)),
+ ['0 (darkest)', '1', '2', '3', '4', '5', '6', '7 (lightest)']),
+ ('settings.mute_timeout', 'Reduced audio timeout', list(range(60)),
+ ['%i minute(s)' % i for i in range(1, 61)]),
+ ('settings.key_beep', 'Keypad beep', [1, 0], None),
+ ('settings.dtmf_beep', 'DTMF beep', [0, 1], None),
+ ('settings.ibd', 'Intelligent band display', [0, 1], None),
+ ('settings.ptt_lock', 'PTT lock', [0, 1], None),
+ ('settings.panel_lock', 'Panel lock', [0, 1], None),
+ ('settings.dtmf_speed', 'DTMF speed', [0, 1],
+ ['Low (5 digits/second)', 'High (9 digits/second)']),
+ ('settings.sub_mute', 'Sub band mute', [0, 1], None),
+ ('settings.volts_offset', 'DC voltmeter correction',
+ [i & 0xFF for i in range(-30, 31)],
+ ['%+.3f V' % (i * 0.066) for i in range(-30, 31)])]
+
+
+def checksum(data):
+ return (sum(data[5:-1]) ^ 0xA5) & 0xFF
+
+
+def validate_image(data):
+ if len(data) != IMAGE_SIZE:
+ raise errors.RadioError('Expected 1860 bytes, received %i' % len(data))
+ if data[:5] != HEADER:
+ raise errors.RadioError(
+ 'Unrecognized FT-8000 header; this development driver currently '
+ 'supports only the hardware-verified header 00 01 26 21 00')
+ if data[-1] != checksum(data):
+ raise errors.RadioError('FT-8000 image checksum mismatch')
+
+
+def decode_frequency(raw):
+ freq = raw * 100
+ return freq + 500 if freq % 10000 in (2000, 7000) else freq
+
+
+def frequency_code(freq):
+ if freq < 280000000 and freq % 5000 == 0:
+ return 0
+ if freq % 6250 == 0:
+ return 1
+ if freq >= 280000000 and freq % 10000 == 0:
+ return 0
+ # Code 1 also covers 2.5 kHz and UHF 5 kHz endings.
+ return 1
+
+
+@directory.register
+class FT8000RRadio(chirp_common.CloneModeRadio):
+ VENDOR = 'Yaesu'
+ MODEL = 'FT-8000R'
+ BAUD_RATE = 9600
+ WANTS_DTR = False
+ WANTS_RTS = True
+ _memsize = IMAGE_SIZE
+
+ @classmethod
+ def get_prompts(cls):
+ prompts = chirp_common.RadioPrompts()
+ prompts.experimental = (
+ 'CTCSS decoding and bell require the optional FTS-22 board. '
+ 'These functions have not been verified on the test radio.')
+ prompts.pre_download = (
+ '1. Turn radio OFF. Connect the rear DATA cable.\n'
+ '2. Hold <b>F/W</b> (FIRST button below the LCD) while\n'
+ ' turning radio ON. Release when all segments blink.\n'
+ '3. <b>After clicking OK</b>, wait for download progress.\n'
+ ' Press <b>RPT</b> (THIRD button below the LCD) once.\n'
+ '4. After completion, turn OFF, then ON normally.\n'
+ ' Hold no buttons. Turn OFF before unplugging cable.\n')
+ prompts.pre_upload = (
+ '1. Turn radio OFF. Connect the rear DATA cable.\n'
+ '2. Hold <b>F/W</b> (FIRST button below the LCD) while\n'
+ ' turning radio ON. Release when all segments blink.\n'
+ '3. Press <b>REV</b> (SECOND button below the LCD) once.\n'
+ ' The display stops blinking; radio is ready to receive.\n'
+ '4. Click OK. Wait about 25-35 seconds for upload.\n'
+ ' Radio restarts on success. If needed, power OFF/ON\n'
+ ' normally without holding any buttons.\n'
+ 'If ERR appears, stop transfer and repeat from step 1.\n')
+ return prompts
+
+ def get_features(self):
+ features = chirp_common.RadioFeatures()
+ features.has_sub_devices = not bool(self.VARIANT)
+ features.memory_bounds = (1, 50)
+ features.has_bank = False
+ features.has_name = False
+ features.valid_name_length = 0
+ features.valid_characters = ''
+ features.has_settings = not bool(self.VARIANT)
+ features.has_tuning_step = False
+ features.valid_tuning_steps = [5, 10, 12.5, 15, 20, 25, 50, 100, 2.5]
+ features.has_nostep_tuning = False
+ features.has_ctone = False
+ features.has_dtcs = False
+ features.has_dtcs_polarity = False
+ features.can_delete = True
+ features.valid_tmodes = list(TMODES)
+ features.valid_tones = list(TONES)
+ features.valid_skips = ['', 'S']
+ features.valid_modes = ['FM', 'AM']
+ features.valid_duplexes = ['', '+', '-', 'split']
+ features.can_odd_split = True
+ features.valid_power_levels = self._power_levels()
+ features.valid_special_chans = list(SPECIALS)
+ features.valid_bands = ([(110000000, 280000000)]
+ if self.VARIANT == 'Left' else
+ [(280000000, 550000000),
+ (750000000, 1000000000)])
+ return features
+
+ def _power_levels(self):
+ return [chirp_common.PowerLevel('High', watts=(
+ 50 if self.VARIANT == 'Left' else 35)),
+ chirp_common.PowerLevel('Mid', watts=10),
+ chirp_common.PowerLevel('Low', watts=5)]
+
+ def get_sub_devices(self):
+ return [FT8000RLeftRadio(self._mmap), FT8000RRightRadio(self._mmap)]
+
+ def process_mmap(self):
+ validate_image(self._mmap.get_packed())
+ self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+
+ def _inactive_side(self):
+ if not self._memobj.settings.same_band:
+ return None
+ return 'right' if self._memobj.settings.vhf_pair else 'left'
+
+ def _saved_states(self):
+ # Same-band reception uses both live receivers for one band. The
+ # inactive band's state is preserved in two matching saved blocks.
+ side = self._inactive_side()
+ if side is None:
+ return []
+ other = 'left' if side == 'right' else 'right'
+ return [getattr(self._memobj, s + '_saved') for s in (side, other)]
+
+ def _working_records(self, number):
+ side = self.VARIANT.lower()
+ if side == self._inactive_side():
+ states = self._saved_states()
+ else:
+ sides = (('left', 'right')
+ if self._inactive_side() and number != 56 else (side,))
+ states = [getattr(self._memobj, s) for s in sides]
+ working = []
+ for state in states:
+ if state.memory_tune:
+ continue
+ if state.home_mode:
+ selected = 55
+ elif state.memory_mode:
+ selected = int(state.current_memory) + 1
+ else:
+ selected = 56
+ if selected == number:
+ working.append(state.working)
+ return working
+
+ def _get_record(self, number):
+ number = self._memory_number(number)
+ side = self.VARIANT.lower()
+ if 1 <= number <= 50:
+ return getattr(self._memobj, side + '_memory')[number - 1]
+ if 51 <= number <= 54:
+ return getattr(self._memobj, side + '_pms')[number - 51]
+ if number in (55, 56):
+ if side == self._inactive_side():
+ state = self._saved_states()[0]
+ else:
+ state = getattr(self._memobj, side)
+ return state.home if number == 55 else state.vfo
+ raise errors.InvalidMemoryLocation('Unknown FT-8000 memory')
+
+ @staticmethod
+ def _memory_number(number):
+ if isinstance(number, str) and number in SPECIALS:
+ return 51 + SPECIALS.index(number)
+ if not isinstance(number, int):
+ raise errors.InvalidMemoryLocation('Unknown FT-8000 memory')
+ return number
+
+ @staticmethod
+ def _memory_extra(record, empty=False):
+ extra = RadioSettingGroup('extra', 'Extra')
+ extra.append(MemSetting('bell', 'CTCSS bell (requires TSQL/FTS-22)',
+ RadioSettingValueBoolean(
+ False if empty else record.bell)))
+ extra.append(MemSetting(
+ 'masked', 'Masked (hidden on radio)',
+ RadioSettingValueBoolean(False if empty else record.masked)))
+ return extra
+
+ def get_memory(self, number):
+ record = self._get_record(number)
+ number = self._memory_number(number)
+ rx = int(record.freq) * 100
+ used = rx and (not record.masked or rx != SENTINELS[self.VARIANT])
+ if number >= 55:
+ used = bool(rx)
+ memory = chirp_common.Memory(number, empty=not bool(used))
+ memory.extra = self._memory_extra(record, empty=memory.empty)
+ if number > 50:
+ memory.extd_number = SPECIALS[number - 51]
+ if number >= 55:
+ memory.immutable = ['empty']
+ memory.extra['masked'].value.set_mutable(False)
+ if not used:
+ return memory
+ memory.freq = decode_frequency(int(record.freq))
+ memory.duplex = DUPLEXES[int(record.duplex)]
+ memory.offset = (decode_frequency(int(record.offset))
+ if memory.duplex == 'split' else
+ int(record.offset) * 100)
+ memory.mode = 'AM' if record.am else 'FM'
+ memory.tmode = {0: '', 1: 'Tone', 2: '', 3: 'TSQL'}[
+ int(record.tone_mode)]
+ if int(record.tone) < len(TONES):
+ memory.rtone = TONES[int(record.tone)]
+ else:
+ LOG.warning('Unknown FT-8000 tone index %i in %s memory %i',
+ int(record.tone), self.VARIANT, number)
+ memory.skip = 'S' if record.skip else ''
+ memory.power = self._power_levels()[
+ int(record.power) if int(record.power) < 3 else 0]
+ return memory
+
+ def _update_checksum(self):
+ self._memobj.checksum = checksum(self._mmap.get_packed())
+
+ def set_memory(self, memory):
+ record = self._get_record(memory.number)
+ existing = self.get_memory(memory.number)
+ self.check_set_memory_immutable_policy(existing, memory)
+ if memory.empty:
+ record.masked = True
+ record.freq = SENTINELS[self.VARIANT] // 100
+ self._update_checksum()
+ return
+
+ # The LCD uses a separate working record. Update only receivers whose
+ # mode and channel index select this memory, even if others match it.
+ working = self._working_records(memory.number)
+
+ tx = memory.freq
+ if memory.duplex == '+':
+ tx += memory.offset
+ elif memory.duplex == '-':
+ tx -= memory.offset
+ elif memory.duplex == 'split':
+ tx = memory.offset
+ record.freq = memory.freq // 100
+ record.offset = memory.offset // 100
+ record.duplex = DUPLEXES.index(memory.duplex)
+ record.rx_step = frequency_code(memory.freq)
+ record.tx_step = frequency_code(tx)
+ record.am = memory.mode == 'AM'
+ record.tone_mode = {'': 0, 'Tone': 1, 'TSQL': 3}[memory.tmode]
+ record.tone = TONES.index(memory.rtone)
+ record.skip = memory.skip == 'S'
+ record.power = (self._power_levels().index(memory.power)
+ if memory.power else 0)
+ record.masked = False
+ record.bell = False
+ if memory.extra:
+ for setting in memory.extra:
+ setting.apply_to_memobj(record)
+ if memory.tmode != 'TSQL':
+ record.bell = False
+ for item in working:
+ item.set_raw(record.get_raw())
+ if memory.number in (55, 56):
+ if self.VARIANT.lower() == self._inactive_side():
+ for state in self._saved_states():
+ item = state.home if memory.number == 55 else state.vfo
+ item.set_raw(record.get_raw())
+ elif memory.number == 55 and self._inactive_side():
+ for side in ('left', 'right'):
+ getattr(self._memobj, side).home.set_raw(
+ record.get_raw())
+ self._update_checksum()
+
+ def get_raw_memory(self, number):
+ return repr(self._get_record(number))
+
+ def _settings_schema(self):
+ schema = list(SETTINGS)
+ for side in ('left', 'right'):
+ label = side.title()
+ control = (side + '_saved.control'
+ if side == self._inactive_side() else side + '.control')
+ squelch = (side + '_saved.rf_sql'
+ if side == self._inactive_side() else side + '.rf_sql')
+ schema.extend([
+ (control + '.ars', label + ' auto repeater shift',
+ [0, 1], None),
+ (control + '.search', label + ' smart search',
+ [0, 1], ['One time', 'Continuous']),
+ (control + '.scan', label + ' scan resume',
+ [0, 1], ['Carrier drop', '5 seconds']),
+ (squelch, label + ' RF squelch',
+ [0, 2, 4, 6, 11], ['Off', '2 units', '4 units', '6 units',
+ 'Full scale'])])
+ return schema
+
+ def get_settings(self):
+ common = RadioSettingGroup('common', 'Radio settings')
+ for path, label, values, labels in self._settings_schema():
+ field = self._memobj
+ for part in path.split('.'):
+ field = getattr(field, part)
+ raw = int(field)
+ if raw not in values:
+ value = RadioSettingValueString(0, 64, 'Unknown: 0x%X' % raw)
+ value.set_mutable(False)
+ setting = RadioSetting(path.replace('.', '_'), label, value)
+ elif labels is None:
+ value = RadioSettingValueBoolean(
+ bool(values.index(raw)), mem_vals=values)
+ setting = MemSetting(path, label, value)
+ else:
+ value = RadioSettingValueMap(list(zip(labels, values)),
+ mem_val=raw)
+ setting = MemSetting(path, label, value)
+ common.append(setting)
+ obj = self._memobj.settings
+ mode = (0 if not obj.same_band else 1 if obj.vhf_pair else 2)
+ value = RadioSettingValueString(
+ 0, 32, ['VHF/UHF', 'VHF/VHF', 'UHF/UHF'][mode])
+ value.set_mutable(False)
+ common.append(RadioSetting('receive_mode', 'Receive mode', value))
+ sub_mode = (0 if not obj.sub_off else
+ 2 if obj.sub_voltmeter else 1)
+ common.append(RadioSetting(
+ 'sub_operation', 'Sub band operation', RadioSettingValueList(
+ ['On', 'Off', 'Voltmeter'], current_index=sub_mode)))
+ dtmf = RadioSettingGroup('dtmf', 'DTMF autodial')
+ for side in ('left', 'right'):
+ obj = (self._saved_states()[0].dtmf
+ if side == self._inactive_side() else
+ getattr(self._memobj, side).dtmf)
+ count = int(obj.count)
+ digits = [int(x) for x in obj.digits[0:min(count, 16)]]
+ if count <= 16 and all(x <= 16 for x in digits):
+ text = ''.join('0123456789ABCD*#P'[x] for x in digits)
+ value = RadioSettingValueString(0, 16, text, autopad=False)
+ value.set_charset('0123456789ABCD*#P')
+ else:
+ value = RadioSettingValueString(
+ 0, 80, 'Unknown: ' + bytes(digits).hex())
+ value.set_mutable(False)
+ dtmf.append(RadioSetting(side + '_dtmf', side.title() +
+ ' DTMF digits (P = pause)', value))
+ return RadioSettings(common, dtmf)
+
+ def set_settings(self, settings):
+ # Direct settings use MemSetting. Only multi-field/encoded settings
+ # need special handling.
+ obj = self._memobj
+ for setting in settings.apply_to(obj):
+ if not setting.changed():
+ continue
+ name = setting.get_name()
+ if name == 'sub_operation':
+ index = int(setting.value)
+ obj.settings.sub_off = bool(index)
+ obj.settings.sub_voltmeter = index == 2
+ elif name in ('left_dtmf', 'right_dtmf'):
+ digits = str(setting.value).strip().upper()
+ dtmf = (self._saved_states()[0].dtmf
+ if name == str(self._inactive_side()) + '_dtmf' else
+ getattr(obj, name[:-5]).dtmf)
+ dtmf.count = len(digits)
+ dtmf.digits = (['0123456789ABCD*#P'.index(x) for x in digits] +
+ [16] * (16 - len(digits)))
+ else:
+ raise errors.InvalidValueError('Unsupported setting: ' + name)
+ saved = self._saved_states()
+ if saved:
+ source, mirror = saved
+ for field in ('ars', 'search', 'scan'):
+ setattr(mirror.control, field, getattr(source.control, field))
+ mirror.rf_sql = source.rf_sql
+ mirror.dtmf.set_raw(source.dtmf.get_raw())
+ self._update_checksum()
+
+ def _configure_pipe(self):
+ self.pipe.bytesize = 8
+ self.pipe.parity = 'N'
+ self.pipe.stopbits = 2
+ self.pipe.xonxoff = False
+ self.pipe.dsrdtr = False
+ self.pipe.timeout = 3
+
+ def _status(self, message, count):
+ status = chirp_common.Status()
+ status.msg = message
+ status.cur = count
+ status.max = IMAGE_SIZE
+ self.status_fn(status)
+
+ def sync_in(self):
+ try:
+ self._download()
+ except errors.RadioError:
+ raise
+ except Exception as error:
+ LOG.exception('FT-8000R download failed')
+ raise errors.RadioError('Download failed: %s' % error) from error
+
+ def _download(self):
+ self._configure_pipe()
+ # Yaesu requires the operator to start the transfer. Keep the same
+ # serial timeout throughout: changing it may flush received data.
+ for attempt in range(20):
+ first = self.pipe.read(1)
+ if first:
+ break
+ else:
+ raise errors.RadioNoResponse()
+ header = first + self.pipe.read(len(HEADER) - 1)
+ # Some captures have this fixed two-byte preamble. Read its remaining
+ # bytes directly; do not scan or poll an asynchronous receive buffer.
+ prefix = b''
+ if header.startswith(b'\x00\xfc'):
+ prefix = header[:2]
+ header = header[2:] + self.pipe.read(2)
+ if header != HEADER:
+ raise errors.RadioError(
+ 'Unrecognized or incomplete FT-8000 header')
+ self._metadata['ft8000_download_prefix'] = prefix.hex()
+ data = bytearray(header)
+ self._status('Downloading from FT-8000', len(data))
+ while len(data) < IMAGE_SIZE:
+ count = min(64, IMAGE_SIZE - len(data))
+ chunk = self.pipe.read(count)
+ if len(chunk) != count:
+ raise errors.RadioError('Incomplete FT-8000 download')
+ data.extend(chunk)
+ self._status('Downloading from FT-8000', len(data))
+ validate_image(data)
+ # No per-block or final ACK: passive download is hardware-verified.
+ self._mmap = memmap.MemoryMapBytes(bytes(data))
+ self.process_mmap()
+
+ def _write_echo(self, value):
+ # CHIRP's SerialTrace wrapper currently discards Serial.write's count.
+ # In that case the required matching one-byte echo confirms the write.
+ count = self.pipe.write(value)
+ if count is not None and count != 1:
+ raise errors.RadioError('Incomplete serial write; upload stopped')
+ self.pipe.flush()
+ echo = self.pipe.read(1)
+ if not echo:
+ raise errors.RadioError('Missing cable echo; upload stopped')
+ if echo != value:
+ raise errors.RadioError('Unexpected cable echo; upload stopped')
+
+ def sync_out(self):
+ try:
+ self._upload()
+ except errors.RadioError:
+ raise
+ except Exception as error:
+ LOG.exception('FT-8000R upload failed')
+ raise errors.RadioError('Upload failed: %s' % error) from error
+
+ def _upload(self):
+ data = self._mmap.get_packed()
+ validate_image(data) # Before touching the serial port.
+ self._configure_pipe()
+ self._status('Uploading to FT-8000', 0)
+ for index, value in enumerate(data):
+ time.sleep(0.150 if index == 0 else 0.010)
+ self._write_echo(bytes([value]))
+ if index % 16 == 0 or index == IMAGE_SIZE - 1:
+ self._status('Uploading to FT-8000', index + 1)
+ time.sleep(0.150)
+ self._write_echo(b'\x06')
+ LOG.info('FT-8000 writes and echo complete; '
+ 'verify radio display/readback')
+
+
+class FT8000RLeftRadio(FT8000RRadio):
+ VARIANT = 'Left'
+
+
+class FT8000RRightRadio(FT8000RRadio):
+ VARIANT = 'Right'
diff --git a/chirp/drivers/ftm150.py b/chirp/drivers/ftm150.py
new file mode 100644
index 0000000..597e323
--- /dev/null
+++ b/chirp/drivers/ftm150.py
@@ -0,0 +1,1019 @@
+# Copyright 2026 CHIRP contributors
+#
+# 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/>.
+
+"""Yaesu FTM-150E experimental CHIRP driver.
+
+Memory map from ADMS-17 CLNFTM150nn.dat dumps (98304 bytes, ident AH086).
+
+Downloading from and uploading to the radio over a cable both work.
+Also, only the full backup (CLNFTM150nn.dat) is supported -
+setup (SYSFTM150nn.dat) and memory (MEMFTM150nn.dat) files are not supported.
+Not every feature of FTM-150/ADMS-17 is currently supported by this driver.
+"""
+
+import logging
+
+from chirp.drivers import ftm300d
+from chirp.drivers import yaesu_clone
+from chirp import bitwise
+from chirp import chirp_common
+from chirp import directory
+from chirp import errors
+from chirp.settings import RadioSetting
+from chirp.settings import RadioSettingGroup
+from chirp.settings import RadioSettings
+from chirp.settings import RadioSettingValueBoolean
+from chirp.settings import RadioSettingValueList
+from chirp.settings import RadioSettingValueString
+
+LOG = logging.getLogger(__name__)
+
+# ---------------------------------------------------------------------------
+# Clone protocol, 38400 8N1 on the DATA jack. Captured from a real
+# [58 This -> Other] transfer: the FTM-150 speaks exactly what ftm300d.py
+# already implements for the FTM-300DR, down to the skipped blocks, the
+# wrap to the name tables and the two trailer frames, so the clone code is
+# reused from there. The image has the layout of the radio's own SD backup
+# (CLNFTM150nn.dat). The radio never transmits block 0x0400, so it stays
+# zero in a cable-read image; it is zero in every SD backup seen so far,
+# too, and no known setting lives there.
+# ---------------------------------------------------------------------------
+
+# The .dat format keeps a checksum over everything before this offset, but
+# the radio transmits 0x00 there -- the clone stream carries its own
+# per-frame checksum instead. ADMS-17 fills the byte in when it writes a
+# file from a cable read and sends 0x00 again when it uploads, so do the
+# same: without it, saving a downloaded image yields a .dat whose checksum
+# does not match its contents. Nothing this driver exposes for editing
+# lives below the offset, so computing it once after the download is
+# enough.
+FILE_CHECKSUM_AT = 0x007F
+
+
+# ---------------------------------------------------------------------------
+# Frequency encoding, the same as on the FTM-300D: the 100 MHz digit and
+# the BCD digits down to 10 kHz, plus a 4-bit count of 625 Hz steps on
+# top. ftm300d.py and ftm350.py treat the latter as single 5k/2.5k/1.25k
+# (/625) flags, but together they are just binary 8/4/2/1 x 625 Hz.
+# ---------------------------------------------------------------------------
+
+YFREQ_FORMAT = """
+struct yfreq {
+ u8 fine:4,
+ hun:4;
+ bbcd khz10[2];
+};
+"""
+
+
+def decode_freq(freq):
+ """Decode a yfreq struct to Hz."""
+ return ((int(freq.hun) * 10000 + int(freq.khz10)) * 10000
+ + int(freq.fine) * 625)
+
+
+def encode_freq(freq, hz):
+ """Encode Hz into a yfreq struct."""
+ khz10, rest = divmod(hz, 10000)
+ freq.hun = khz10 // 10000 % 10
+ freq.khz10 = khz10 % 10000
+ freq.fine = rest // 625
+
+
+# ---------------------------------------------------------------------------
+# Memory map.
+#
+# `chanrecord` is the 16-byte per-channel layout shared, byte-for-byte, by
+# regular memory channels, PMS entries, and VFO/HOME band records.
+#
+# `namerecord` is the 16-byte, 0xFF-padded ASCII name shared by all of
+# those tables too.
+#
+# The FTM-300D shares this layout, but some of its fields do not apply to
+# the analog-only FTM-150 and are named unknown here on purpose:
+# - unknown3 (byte 1, 0x40) is ftm300d's "ams". The FTM-150 has no AMS,
+# yet the radio sets the bit on some records (also at 0x0091 and
+# 0x00E2), while ADMS-17 clears it everywhere when writing a .dat.
+# Meaning unknown; the driver never touches it.
+# - unknown5 (byte 11, 0x40) is ftm300d's "dn", unknown8 and unknown9
+# (bytes 14 and 15) are its "dgid_rx" and "dgid_tx". All C4FM; never
+# seen set on an FTM-150.
+# ---------------------------------------------------------------------------
+
+MEM_FORMAT = YFREQ_FORMAT + """
+struct chanrecord {
+ u8 used:1,
+ unknown0:1,
+ skip:1,
+ memref:1,
+ unknown1:2,
+ band:2;
+ u8 unused_msb:1,
+ unknown3:1,
+ narrow:1,
+ am:1,
+ duplex:4;
+ struct yfreq freq;
+ u8 tone_mode:4,
+ tune_step:4;
+ struct yfreq tx_freq;
+ u8 power:2,
+ tone:6;
+ u8 clock_shift:1,
+ dcs:7;
+ u8 unknown4:1,
+ unknown5:1,
+ unknown6:1,
+ pr_freq:5;
+ u8 unknown7;
+ u8 offset;
+ u8 unknown8;
+ u8 unknown9;
+};
+
+struct namerecord {
+ u8 text[16];
+};
+
+struct dtmfrecord {
+ u8 digits[16];
+};
+
+// 0x0000
+u8 ident[6];
+
+#seekto 0x00A1;
+u8 unit;
+
+#seekto 0x00A8;
+u8 tz_west:1,
+ tz_mag:7;
+
+#seekto 0x00CF;
+u8 pmg_selected;
+
+#seekto 0x00DF;
+u8 vfo_a_active;
+
+#seekto 0x00FB;
+u8 pmg_active;
+
+#seekto 0x0100;
+struct chanrecord vfo_a[4];
+
+#seekto 0x0150;
+struct chanrecord vfo_b[4];
+
+#seekto 0x01A0;
+struct chanrecord home_a[4];
+
+#seekto 0x01F0;
+struct chanrecord home_b[4];
+
+#seekto 0x028F;
+u8 lcd_brightness;
+
+#seekto 0x02C8;
+u8 callsign[10];
+
+// 0x02D2
+u8 pager_rx[2];
+u8 pager_tx[2];
+
+#seekto 0x0300;
+struct dtmfrecord dtmf[9];
+
+#seekto 0x03B0;
+struct namerecord home_b_names[4];
+
+#seekto 0x0480;
+struct namerecord home_a_names[4];
+
+#seekto 0x0800;
+struct chanrecord memory[999];
+
+// 0x4670
+struct chanrecord pms[100];
+
+// 0x4CB0
+u16 nameflags[999];
+
+#seekto 0x5600;
+struct chanrecord pmg[5];
+
+#seekto 0x6800;
+struct namerecord wx_names[10];
+
+// 0x68A0
+u16 wx_nameflags[10];
+
+#seekto 0x10000;
+struct namerecord names[999];
+
+// 0x13E70
+struct namerecord pms_names[100];
+"""
+
+# This is the real radio-generated (not ADMS-17-resaved) empty slot backup.
+# ADMS-17 itself writes a *different* pattern for empty channels on resave.
+EMPTY_SLOT = bytes.fromhex(
+ "01 00 01 44 00 04 00 00 00 0c 00 0f 00 0c 00 00")
+USED_PROTOTYPE = bytes.fromhex(
+ "81 00 01 46 50 00 00 00 00 0c 00 0f 00 0c 00 00")
+
+POWER_LEVELS = [
+ chirp_common.PowerLevel("Hi", watts=50),
+ chirp_common.PowerLevel("Mid", watts=25),
+ chirp_common.PowerLevel("Low", watts=5),
+]
+
+STEPS = ftm300d.STEPS
+
+# Duplex nibble: 0 simplex, 2 minus, 3 plus, 4 split.
+DUPLEX_FROM_RADIO = ftm300d.DUPLEX_FROM_RADIO
+DUPLEX_TO_RADIO = ftm300d.DUPLEX_TO_RADIO
+
+# High nibble of byte 5, in ADMS-17 terms: 0 OFF, 1 TONE, 2 TONE SQL,
+# 3 REV TONE, 4 DCS, 5 PR FREQ, 6 PAGER. CHIRP has no tmode for PR FREQ
+# (reverse tone on the User CTCSS frequency, see pr_freq) or PAGER (EPCS
+# selective call), so like ft4.py they go into the "sql_override" channel
+# extra and the grid shows tmode "" for them. The override wins over tmode
+# on write.
+TMODE_FROM_RADIO = ftm300d.TMODE_FROM_RADIO
+TMODE_TO_RADIO = ftm300d.TMODE_TO_RADIO
+EDITABLE_TMODES = ["", "Tone", "TSQL", "TSQL-R", "DTCS"]
+SQL_OVERRIDE_NONE = "(None)"
+SQL_OVERRIDE_FROM_RADIO = {5: "PR FREQ", 6: "PAGER"}
+SQL_OVERRIDE_TO_RADIO = {v: k for k, v in SQL_OVERRIDE_FROM_RADIO.items()}
+SQL_OVERRIDES = [SQL_OVERRIDE_NONE] + list(SQL_OVERRIDE_FROM_RADIO.values())
+
+# ADMS-17 "User CTCSS", 300-3000 Hz in 100 Hz steps, stored as Hz / 100 in
+# the low 5 bits of byte 11 (confirmed by controlled diff: 300 -> 3,
+# 1100 -> 11, 3000 -> 30). Every channel has it, whatever its tone mode;
+# the factory value is 1500 Hz. Bit 5 has never been seen set.
+PR_FREQS = ["%d Hz" % hz for hz in range(300, 3001, 100)]
+PR_FREQ_MIN = 3
+
+# ADMS-17 Signaling -> Pager Code: RX and TX each take two EPCS codes,
+# 1-50, stored as code - 1 (confirmed by controlled diff; factory 05/47).
+PAGER_CODES = ["%02d" % code for code in range(1, 51)]
+
+# DTMF digit encoding confirmed by controlled diff.
+DTMF_CHARSET = "0123456789*#"
+DTMF_CHAR_TO_CODE = {str(d): d for d in range(10)}
+DTMF_CHAR_TO_CODE.update({"*": 0x0E, "#": 0x0F})
+DTMF_CODE_TO_CHAR = {v: k for k, v in DTMF_CHAR_TO_CODE.items()}
+DTMF_PAD = 0xFF
+
+# WX is the ten-channel NOAA weather broadcast bank. Only the user-assignable
+# name and its flag are stored in the backup (0x6800 / 0x68A0); the
+# frequencies themselves live in firmware, which is why they are hardcoded
+# here just to label the name fields.
+#
+# UNTESTED on real hardware: the name storage is confirmed by controlled
+# diff, but only against a European FTM-150E, where the WX bank cannot
+# normally be reached -- the [P4] key ships assigned to T-CALL there, while
+# the USA FTM-150R ships with WX on P4. Nobody has yet checked that a name
+# written here shows up on a radio that can actually display the bank.
+WX_FREQS = ("162.550", "162.400", "162.475", "162.425", "162.450",
+ "162.500", "162.525", "161.650", "161.775", "163.275")
+
+
+def _decode_name(raw):
+ return ftm300d._decode_padded(raw, 0xFF)
+
+
+def _encode_name(text, length=16):
+ cleaned = "".join(
+ c if c in chirp_common.CHARSET_ASCII else " " for c in text
+ )[:length]
+ padded = cleaned.encode("ascii", "replace")
+ return padded + b"\xff" * (length - len(padded))
+
+
+def _decode_dtmf(raw):
+ buf = [int(x) for x in raw]
+ chars = []
+ for b in buf:
+ if b == DTMF_PAD:
+ break
+ chars.append(DTMF_CODE_TO_CHAR.get(b, "?"))
+ return "".join(chars)
+
+
+def _encode_dtmf(text, length=16):
+ codes = [DTMF_CHAR_TO_CODE[c] for c in text if c in DTMF_CHAR_TO_CODE]
+ codes = codes[:length]
+ return bytes(codes) + bytes([DTMF_PAD]) * (length - len(codes))
+
+
+# ---------------------------------------------------------------------------
+# Special channels: VFO A/B (4 bands each), HOME CH A/B (4 bands each, with
+# names), and PMS (50 L/U pairs). All share the exact same 16-byte
+# chanrecord layout as regular memory channels
+# ---------------------------------------------------------------------------
+
+# Order of the four records inside vfo_a/vfo_b/home_a/home_b, ascending by
+# frequency. Byte 0 of each record carries its own index, which is how this
+# order was confirmed; "OTHER" covers everything between 2 m and 70 cm.
+SPECIAL_BANDS = ("AIR", "144", "OTHER", "430")
+
+
+def _band_index(hz):
+ """Index into SPECIAL_BANDS that the radio stores for a frequency.
+
+ Edges confirmed by controlled diff on memory channels and VFO/HOME
+ records set on the radio: 136.9875 is AIR, 137.9875 and 174.0 are
+ 144, 174.1 and 399.9875 are OTHER, 400.0 and 480.0 are 430. The radio
+ does not accept exactly 137.0. (ADMS-17 disagrees on 174.0 for
+ VFO/HOME and puts it in OTHER.)
+ """
+ if hz < 137000000:
+ return 0
+ if hz <= 174000000:
+ return 1
+ if hz < 400000000:
+ return 2
+ return 3
+
+
+def _build_special_memories():
+ mapping = {}
+ idx = -1
+ for prefix in ("VFO_A", "VFO_B", "Home_A", "Home_B"):
+ for band in SPECIAL_BANDS:
+ mapping["%s_%s" % (prefix, band)] = idx
+ idx -= 1
+ for n in range(1, 51):
+ mapping["PMS_L_%02d" % n] = idx
+ idx -= 1
+ mapping["PMS_U_%02d" % n] = idx
+ idx -= 1
+ return mapping
+
+
+# ---------------------------------------------------------------------------
+# PMG (Primary Memory Group): five chanrecords at 0x5600, packed from slot 1
+# without gaps -- the radio moves the later slots up when one is deleted.
+# A slot either holds a frequency of its own, as a full record like a VFO,
+# or, with memref set, points at a memory channel: then byte 1 is 0xFF,
+# bytes 2-3 are the channel number - 1, big endian, and the band in byte 0
+# is that of the channel. Deleting a slot clears only byte 0. pmg_selected
+# is the slot selected on the radio, 0-based. All confirmed by controlled
+# diff.
+# ---------------------------------------------------------------------------
+
+PMG_EMPTY = "(Empty)"
+
+
+def _pmg_channel(raw):
+ """Memory channel number a raw PMG slot points at, or None."""
+ if not raw[0] & 0x80 or not raw[0] & 0x10:
+ return None
+ return (raw[2] << 8 | raw[3]) + 1
+
+
+def _pmg_ref(number, band):
+ """Raw PMG slot pointing at memory channel number."""
+ return bytes([0x90 | band, 0xFF, (number - 1) >> 8,
+ (number - 1) & 0xFF]) + b"\xff" * 12
+
+
+SPECIAL_MEMORIES = _build_special_memories()
+SPECIAL_MEMORIES_REV = {v: k for k, v in SPECIAL_MEMORIES.items()}
+
+
+def _special_memory_sort_key(name):
+ if name.startswith(("VFO_", "Home_")):
+ family, side, band = name.split("_")
+ family_order = 0 if family == "VFO" else 1
+ side_order = 0 if side == "A" else 1
+ return family_order, side_order, SPECIAL_BANDS.index(band), 0
+
+ band, number = name[4:].split("_")
+ side_order = 0 if band == "L" else 1
+ return 2, int(number), side_order, 0
+
+
+@directory.register
+class FTM150Radio(yaesu_clone.YaesuCloneModeRadio,
+ chirp_common.ExperimentalRadio):
+ """Yaesu FTM-150E.
+
+ Only the European FTM-150E has been tested. The USA FTM-150R probably
+ uses the same image, but that is unconfirmed, so it is not offered.
+ """
+ VENDOR = "Yaesu"
+ MODEL = "FTM-150E"
+ BAUD_RATE = 38400 # confirmed against the radio
+ NEEDS_COMPAT_SERIAL = False
+ FORMATS = [directory.register_format('Yaesu FTM-150E SD ALL', '*.dat')]
+
+ _model = b"AH086"
+ _memsize = 98304
+ # IARU Region 1 limits of the FTM-150E. Many radios are frequency-
+ # expanded (the test radio is), so validate_memory() only warns.
+ _tx_bands = [
+ (144000000, 146000000),
+ (430000000, 440000000),
+ ]
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.experimental = (
+ "This FTM-150E driver is experimental. Downloading from and\n"
+ "uploading to the radio over a cable work, as does opening and\n"
+ "saving the SD card 'ALL' backup file\n"
+ "(FTM150/BACKUP/CLNFTM150nn.dat).\n"
+ "\n"
+ "Keep an SD card 'ALL' backup before uploading.")
+ rp.pre_download = (
+ "1. Connect the cable to the DATA jack on the back of the\n"
+ " radio.\n"
+ "2. Press and hold the [F(SETUP)] key, turn the right DIAL\n"
+ " knob to select [58 This -> Other], then press the DIAL\n"
+ " knob.\n"
+ "3. <b>After clicking OK here</b>, turn the DIAL knob on the\n"
+ " radio to select [OK] and press it to start the transfer.\n")
+ rp.pre_upload = (
+ "Keep an SD card 'ALL' backup first.\n"
+ "\n"
+ "1. Connect the cable to the DATA jack on the back of the\n"
+ " radio.\n"
+ "2. Press and hold the [F(SETUP)] key, turn the right DIAL\n"
+ " knob to select [59 Other -> This], then press the DIAL\n"
+ " knob.\n"
+ "3. Turn the DIAL knob to select [OK] and press it, so the\n"
+ " radio waits for data.\n"
+ "4. Click OK here within 30 seconds.\n")
+ return rp
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_bank = False
+ rf.has_bank_names = False
+ rf.has_settings = True
+ rf.has_ctone = False
+ rf.has_dtcs = True
+ rf.has_dtcs_polarity = False
+ rf.has_cross = False
+ rf.has_rx_dtcs = False
+ rf.has_comment = False
+ rf.has_nostep_tuning = False
+ rf.can_odd_split = True
+ rf.can_delete = True
+ rf.memory_bounds = (1, 999)
+ rf.valid_special_chans = sorted(
+ SPECIAL_MEMORIES, key=_special_memory_sort_key)
+ # No "DN" -- the FTM-150 is analog only.
+ rf.valid_modes = ["FM", "NFM", "AM"]
+ rf.valid_tmodes = list(EDITABLE_TMODES)
+ rf.valid_duplexes = ["", "-", "+", "split"]
+ rf.valid_tuning_steps = list(STEPS)
+ rf.valid_skips = ["", "S"]
+ rf.valid_power_levels = POWER_LEVELS
+ rf.valid_name_length = 16
+ rf.valid_characters = chirp_common.CHARSET_ASCII
+ rf.valid_dtcs_codes = list(chirp_common.DTCS_CODES)
+ rf.valid_bands = [
+ (108000000, 174000000),
+ (174000000, 400000000),
+ # The radio accepts 480.0 itself, but nothing above it.
+ (400000000, 480000001),
+ ]
+ return rf
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+
+ def _checksums(self):
+ return [yaesu_clone.YaesuChecksum(0x0000, FILE_CHECKSUM_AT - 1)]
+
+ def sync_in(self):
+ try:
+ self._mmap = ftm300d._clone_in(self)
+ self.update_checksums()
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.exception("Failed to download from radio")
+ raise errors.RadioError(
+ "Failed to download from radio (%s)" % e)
+ self.process_mmap()
+
+ def sync_out(self):
+ # Send 0x00 in place of the file checksum, like the radio and
+ # ADMS-17 do, but leave the image itself intact.
+ checksum = self._mmap[FILE_CHECKSUM_AT]
+ self._mmap[FILE_CHECKSUM_AT] = b"\x00"
+ try:
+ ftm300d._clone_out(self)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.exception("Failed to upload to radio")
+ raise errors.RadioError(
+ "Failed to upload to radio (%s)" % e)
+ finally:
+ self._mmap[FILE_CHECKSUM_AT] = checksum
+
+ # -- settings: the small Set Mode tables so far. VFO A/B, HOME CH A/B
+ # and PMS are not here -- they are exposed as special channels in the
+ # Memories grid instead, see the "special channels" section above.
+ def get_settings(self):
+ top = RadioSettings()
+
+ top.append(self._get_status())
+
+ config = RadioSettingGroup("config", "Config")
+ top.append(config)
+ unit = int(self._memobj.unit)
+ config.append(RadioSetting(
+ "unit", "Display Units",
+ RadioSettingValueList(
+ ftm300d.UNIT_LABELS, current_index=unit if unit in (0, 1)
+ else 0)))
+ brightness = int(self._memobj.lcd_brightness)
+ config.append(RadioSetting(
+ "lcd_brightness", "LCD Brightness (raw value)",
+ RadioSettingValueString(0, 2, str(brightness))))
+
+ dtmf = RadioSettingGroup("dtmf", "DTMF Memory")
+ top.append(dtmf)
+ for i in range(9):
+ code = _decode_dtmf(self._memobj.dtmf[i].digits)
+ dtmf.append(RadioSetting(
+ "dtmf%d" % i, "Channel %d" % (i + 1),
+ RadioSettingValueString(
+ 0, 16, code, autopad=False, charset=DTMF_CHARSET)))
+
+ signaling = RadioSettingGroup("signaling", "Signaling")
+ top.append(signaling)
+ for direction in ("rx", "tx"):
+ codes = getattr(self._memobj, "pager_" + direction)
+ for i in range(2):
+ code = int(codes[i])
+ if code >= len(PAGER_CODES):
+ # Out of range values are left alone rather than shown
+ # wrong.
+ continue
+ rs = RadioSetting(
+ "pager_%s%d" % (direction, i),
+ "Pager %s Code %d" % (direction.upper(), i + 1),
+ RadioSettingValueList(PAGER_CODES, current_index=code))
+ rs.set_doc(
+ "Used by channels whose Squelch override is PAGER.")
+ signaling.append(rs)
+
+ wx = RadioSettingGroup("wx", "WX Channel Names")
+ top.append(wx)
+ for i in range(10):
+ rs = RadioSetting(
+ "wx%d" % i, "WX-CH%02d (%s MHz)" % (i + 1, WX_FREQS[i]),
+ RadioSettingValueString(
+ 0, 16, _decode_name(self._memobj.wx_names[i].text),
+ autopad=False))
+ rs.set_doc(
+ "Name only -- the frequency is fixed in firmware. The WX "
+ "bank is reachable only via a programmable key, assigned "
+ "to [P4] on the USA FTM-150R but to T-CALL on the "
+ "European FTM-150E.")
+ wx.append(rs)
+
+ top.append(self._get_pmg())
+
+ return top
+
+ # Operating state from block 0x0080, which the radio sends last and an
+ # upload restores. Read only: switching it means changing several
+ # bytes that depend on the active VFO. Confirmed by controlled diff:
+ # 0x00FB is 0x0A with PMG on and 0x00 with it off, on either VFO, and
+ # 0x00DF is 1 on VFO A (left on the display) and 0 on VFO B (right).
+ # With PMG on, the radio also sets 0x80 in byte 3 of the active VFO's
+ # block (0x00E0 A, 0x00F0 B), 0x01 in byte 4 of the other one, and
+ # clears 0x00D0 (A) or 0x00C0 (B).
+ def _get_status(self):
+ status = RadioSettingGroup("status", "Current Status")
+ pmg_active = int(self._memobj.pmg_active)
+ if pmg_active in (0x00, 0x0A):
+ rs = RadioSetting(
+ "pmg_active", "PMG active",
+ RadioSettingValueBoolean(pmg_active == 0x0A))
+ rs.value.set_mutable(False)
+ rs.set_doc("Uploading restores the state saved in this "
+ "image, whatever the radio was set to since.")
+ status.append(rs)
+ vfo_a = int(self._memobj.vfo_a_active)
+ if vfo_a in (0, 1):
+ rs = RadioSetting(
+ "vfo_a_active", "Active VFO",
+ RadioSettingValueList(
+ ["B (right)", "A (left)"], current_index=vfo_a))
+ rs.value.set_mutable(False)
+ rs.set_doc("Uploading restores the state saved in this "
+ "image, whatever the radio was set to since.")
+ status.append(rs)
+ return status
+
+ def _channel_label(self, number):
+ if int(self._memobj.memory[number - 1].used):
+ name = _decode_name(self._memobj.names[number - 1].text)
+ else:
+ name = "(empty)"
+ return ("%d %s" % (number, name)).strip()
+
+ # PMG slots are settings, as the radio treats PMG as a list of five
+ # entries. A slot holding a frequency of its own is a full channel
+ # (offset, tone, power, ...) that a settings field cannot edit fully,
+ # so it is shown and kept but cannot be created or changed here. The
+ # intended way to add that is special channels PMG_1..PMG_5 in the
+ # memory grid, like VFO and HOME, with these settings still showing
+ # what each slot holds.
+ def _get_pmg(self):
+ pmg = RadioSettingGroup("pmg", "PMG")
+ channels = [self._channel_label(i + 1)
+ for i, rec in enumerate(self._memobj.memory)
+ if int(rec.used)]
+ for i, rec in enumerate(self._memobj.pmg):
+ options = [PMG_EMPTY] + channels
+ current = PMG_EMPTY
+ number = _pmg_channel(rec.get_raw())
+ if number is not None:
+ current = self._channel_label(number)
+ if current not in options:
+ # Points at a channel deleted since; kept as is.
+ options.append(current)
+ elif int(rec.used):
+ current = "Frequency %s MHz" % chirp_common.format_freq(
+ decode_freq(rec.freq))
+ options.insert(1, current)
+ rs = RadioSetting(
+ "pmg%d" % i, "Slot %d" % (i + 1),
+ RadioSettingValueList(
+ options, current_index=options.index(current)))
+ rs.set_doc(
+ "A memory channel, or a frequency stored in the slot "
+ "itself. Frequencies can only be stored on the radio. "
+ "Emptied slots are filled by the slots after them, as on "
+ "the radio.")
+ pmg.append(rs)
+ selected = int(self._memobj.pmg_selected)
+ slots = ["Slot %d" % (i + 1) for i in range(len(self._memobj.pmg))]
+ rs = RadioSetting(
+ "pmg_selected", "Selected slot",
+ RadioSettingValueList(
+ slots, current_index=selected if selected < len(slots)
+ else 0))
+ rs.set_doc("The slot whose name the radio shows. Follows its "
+ "entry when that moves up; falls back to slot 1 when "
+ "the selected slot is emptied.")
+ pmg.append(rs)
+ return pmg
+
+ def _set_pmg(self, pmg):
+ old = [rec.get_raw() for rec in self._memobj.pmg]
+ slots = []
+ moved_to = {}
+ selected = 0
+ for element in pmg:
+ name = element.get_name()
+ value = str(element.value)
+ if name == "pmg_selected":
+ selected = int(value.split()[1]) - 1
+ continue
+ if value == PMG_EMPTY:
+ continue
+ idx = int(name[len("pmg"):])
+ moved_to[idx] = len(slots)
+ raw = old[idx]
+ if value.startswith("Frequency "):
+ slots.append(raw)
+ continue
+ number = int(value.split()[0])
+ if _pmg_channel(raw) != number:
+ raw = _pmg_ref(
+ number, int(self._memobj.memory[number - 1].band))
+ slots.append(raw)
+ for i, rec in enumerate(self._memobj.pmg):
+ if i < len(slots):
+ rec.set_raw(slots[i])
+ elif old[i][0] & 0x80:
+ rec.set_raw(b"\x00" + old[i][1:])
+ # The selection follows its slot when that moves up.
+ self._memobj.pmg_selected = moved_to.get(selected, 0)
+
+ def set_settings(self, settings):
+ for element in settings:
+ if not isinstance(element, RadioSetting):
+ if element.get_name() == "pmg":
+ self._set_pmg(element)
+ else:
+ self.set_settings(element)
+ continue
+ name = element.get_name()
+ value = str(element.value)
+ if name == "unit":
+ self._memobj.unit = ftm300d.UNIT_LABELS.index(value)
+ elif name == "lcd_brightness":
+ try:
+ self._memobj.lcd_brightness = int(value)
+ except ValueError:
+ pass
+ elif name.startswith("dtmf"):
+ idx = int(name[len("dtmf"):])
+ ftm300d._set_bytes(self._memobj.dtmf[idx].digits,
+ _encode_dtmf(value))
+ elif name.startswith(("pager_rx", "pager_tx")):
+ codes = getattr(self._memobj, name[:-1])
+ codes[int(name[-1])] = PAGER_CODES.index(value)
+ elif name.startswith("wx"):
+ idx = int(name[len("wx"):])
+ text = value.strip()
+ ftm300d._set_bytes(self._memobj.wx_names[idx].text,
+ _encode_name(text))
+ self._memobj.wx_nameflags[idx] = 0x0000 if text else 0xFFFF
+
+ # -- memory channels (1-999): logic ported from ftm300d.py
+ def get_raw_memory(self, number):
+ if isinstance(number, str):
+ arr, _names_arr, idx, _kind = self._special_target(number)
+ return repr(getattr(self._memobj, arr)[idx])
+ if number < 0:
+ return self.get_raw_memory(SPECIAL_MEMORIES_REV[number])
+ return repr(self._memobj.memory[number - 1])
+
+ def validate_memory(self, mem):
+ msgs = super().validate_memory(mem)
+ if mem.empty:
+ return msgs
+ if mem.number in SPECIAL_MEMORIES_REV:
+ name = SPECIAL_MEMORIES_REV[mem.number]
+ _arr, _names_arr, idx, kind = self._special_target(name)
+ if kind != "pms" and _band_index(mem.freq) != idx:
+ msgs.append(chirp_common.ValidationError(
+ "%s only holds %s band frequencies" % (
+ name, SPECIAL_BANDS[idx])))
+ if mem.duplex == "split":
+ tx = mem.offset
+ elif mem.duplex == "-":
+ tx = mem.freq - mem.offset
+ elif mem.duplex == "+":
+ tx = mem.freq + mem.offset
+ else:
+ tx = mem.freq
+ in_tx = any(lo <= tx < hi for lo, hi in self._tx_bands)
+ if not in_tx:
+ if mem.duplex in ("-", "+", "split"):
+ # Only a warning: an expanded radio transmits here, and a
+ # stock one refuses to on its own.
+ msgs.append(chirp_common.ValidationWarning(
+ "TX frequency is outside amateur allocations "
+ "for this model"))
+ else:
+ msgs.append(chirp_common.ValidationWarning(
+ "RX-only frequency; radio will not transmit here"))
+ return msgs
+
+ # Shared record decode/encode, used by both regular channels and
+ # every special channel (VFO/HOME/PMS) below, since they're all the
+ # same 16-byte chanrecord layout
+ def _decode_chanrecord(self, mem, _mem):
+ mem.freq = decode_freq(_mem.freq)
+ mem.duplex = DUPLEX_FROM_RADIO.get(int(_mem.duplex), "")
+ if mem.duplex == "split":
+ mem.offset = decode_freq(_mem.tx_freq)
+ else:
+ mem.offset = int(_mem.offset) * 50000
+ mem.skip = "S" if int(_mem.skip) else ""
+ try:
+ mem.power = POWER_LEVELS[int(_mem.power)]
+ except IndexError:
+ mem.power = POWER_LEVELS[0]
+ try:
+ mem.tuning_step = STEPS[int(_mem.tune_step)]
+ except IndexError:
+ mem.tuning_step = STEPS[0]
+ tone_mode = int(_mem.tone_mode)
+ mem.tmode = TMODE_FROM_RADIO.get(tone_mode, "")
+ mem.extra = RadioSettingGroup("extra", "Extra")
+ rs = RadioSetting(
+ "sql_override", "Squelch override",
+ RadioSettingValueList(
+ SQL_OVERRIDES,
+ SQL_OVERRIDE_FROM_RADIO.get(tone_mode, SQL_OVERRIDE_NONE)))
+ rs.set_doc(
+ "PR FREQ and PAGER have no CHIRP tone mode. When one is "
+ "selected here, the channel uses it on the radio regardless "
+ "of Tone Mode. PR FREQ uses the User CTCSS frequency, PAGER "
+ "the pager codes under Settings -> Signaling.")
+ mem.extra.append(rs)
+ pr_freq = int(_mem.pr_freq) - PR_FREQ_MIN
+ if 0 <= pr_freq < len(PR_FREQS):
+ # Out of range values are left alone rather than shown wrong.
+ rs = RadioSetting(
+ "pr_freq", "User CTCSS",
+ RadioSettingValueList(PR_FREQS, current_index=pr_freq))
+ rs.set_doc(
+ "Select the idle line frequency to remove signals such "
+ "as idle line signals used by private railways and "
+ "control signals of MCA radio systems. Only used when "
+ "Squelch override is PR FREQ.")
+ mem.extra.append(rs)
+ rs = RadioSetting(
+ "clock_shift", "Clock Shift",
+ RadioSettingValueBoolean(bool(int(_mem.clock_shift))))
+ rs.set_doc(
+ "Shift the CPU clock frequency on this channel, to move an "
+ "internal spurious signal (\"birdie\") away from it.")
+ mem.extra.append(rs)
+ try:
+ mem.rtone = chirp_common.TONES[int(_mem.tone)]
+ except IndexError:
+ mem.rtone = 88.5
+ mem.ctone = mem.rtone
+ try:
+ mem.dtcs = chirp_common.DTCS_CODES[int(_mem.dcs)]
+ except IndexError:
+ mem.dtcs = 23
+
+ if int(_mem.am):
+ mem.mode = "AM"
+ elif int(_mem.narrow):
+ mem.mode = "NFM"
+ else:
+ mem.mode = "FM"
+
+ def _encode_chanrecord(self, _mem, mem):
+ _mem.used = 1
+ _mem.band = _band_index(mem.freq)
+ _mem.skip = 1 if mem.skip == "S" else 0
+ encode_freq(_mem.freq, mem.freq)
+ _mem.duplex = DUPLEX_TO_RADIO.get(mem.duplex, 0)
+ if mem.duplex == "split":
+ encode_freq(_mem.tx_freq, int(mem.offset))
+ _mem.offset = 0
+ else:
+ encode_freq(_mem.tx_freq, 0)
+ _mem.offset = (
+ int(round(mem.offset / 50000.0)) if mem.offset else 0)
+
+ _mem.am = 1 if mem.mode == "AM" else 0
+ _mem.narrow = 1 if mem.mode == "NFM" else 0
+
+ try:
+ _mem.tune_step = STEPS.index(mem.tuning_step)
+ except ValueError:
+ _mem.tune_step = 0
+ _mem.tone_mode = TMODE_TO_RADIO.get(mem.tmode, 0)
+ for setting in mem.extra:
+ if setting.get_name() == "sql_override":
+ override = str(setting.value)
+ if override in SQL_OVERRIDE_TO_RADIO:
+ _mem.tone_mode = SQL_OVERRIDE_TO_RADIO[override]
+ elif setting.get_name() == "pr_freq":
+ _mem.pr_freq = (
+ PR_FREQS.index(str(setting.value)) + PR_FREQ_MIN)
+ elif setting.get_name() == "clock_shift":
+ _mem.clock_shift = 1 if setting.value else 0
+ try:
+ _mem.tone = chirp_common.TONES.index(mem.rtone)
+ except ValueError:
+ _mem.tone = chirp_common.TONES.index(88.5)
+ try:
+ _mem.dcs = chirp_common.DTCS_CODES.index(mem.dtcs)
+ except ValueError:
+ _mem.dcs = 0
+ if mem.power in POWER_LEVELS:
+ _mem.power = POWER_LEVELS.index(mem.power)
+ else:
+ _mem.power = 0
+
+ # dispatch the regular numbered channels (1-999) vs. the special
+ # channels (string name, or the negative int CHIRP stores internally)
+ def get_memory(self, number):
+ if isinstance(number, str):
+ return self._get_special(number)
+ if number < 0:
+ return self._get_special(SPECIAL_MEMORIES_REV[number])
+ return self._get_normal(number)
+
+ def set_memory(self, mem):
+ if mem.number < 0:
+ return self._set_special(mem)
+ return self._set_normal(mem)
+
+ def _get_normal(self, number):
+ mem = chirp_common.Memory()
+ mem.number = number
+ _mem = self._memobj.memory[number - 1]
+ if not int(_mem.used):
+ mem.empty = True
+ return mem
+
+ mem.empty = False
+ self._decode_chanrecord(mem, _mem)
+ mem.name = _decode_name(self._memobj.names[number - 1].text)
+ return mem
+
+ def _set_normal(self, mem):
+ _mem = self._memobj.memory[mem.number - 1]
+ name_idx = mem.number - 1
+ if mem.empty:
+ _mem.set_raw(EMPTY_SLOT)
+ ftm300d._set_bytes(self._memobj.names[name_idx].text, b"\xff" * 16)
+ self._memobj.nameflags[name_idx] = 0xFFFF
+ return
+
+ if not int(_mem.used):
+ _mem.set_raw(USED_PROTOTYPE)
+
+ self._encode_chanrecord(_mem, mem)
+
+ encoded = _encode_name(mem.name)
+ ftm300d._set_bytes(self._memobj.names[name_idx].text, encoded)
+ self._memobj.nameflags[name_idx] = (
+ 0x0000 if mem.name.strip() else 0xFFFF)
+
+ def _special_target(self, name):
+ """Return (chanrecord array attr, names array attr or None, index,
+ kind) for a special channel name. kind is 'vfo', 'home' or 'pms'."""
+ for prefix, arr, names_arr, kind in (
+ ("VFO_A", "vfo_a", None, "vfo"),
+ ("VFO_B", "vfo_b", None, "vfo"),
+ ("Home_A", "home_a", "home_a_names", "home"),
+ ("Home_B", "home_b", "home_b_names", "home")):
+ if name.startswith(prefix + "_"):
+ band = name[len(prefix) + 1:]
+ return arr, names_arr, SPECIAL_BANDS.index(band), kind
+ if name.startswith(("PMS_L_", "PMS_U_")):
+ prefix, number = name.rsplit("_", 1)
+ n = int(number) if number.isdigit() else 0
+ if 1 <= n <= 50:
+ slot = (n - 1) * 2 + (0 if prefix == "PMS_L" else 1)
+ return "pms", "pms_names", slot, "pms"
+ raise errors.InvalidMemoryLocation(
+ "Unknown FTM-150 special channel %r" % name)
+
+ def _get_special(self, name):
+ arr, names_arr, idx, kind = self._special_target(name)
+ _mem = getattr(self._memobj, arr)[idx]
+ _name_obj = (getattr(self._memobj, names_arr)[idx]
+ if names_arr else None)
+
+ mem = chirp_common.Memory()
+ mem.number = SPECIAL_MEMORIES[name]
+ mem.extd_number = name
+
+ if kind == "pms" and not int(_mem.used):
+ mem.empty = True
+ mem.immutable = ["number", "extd_number"]
+ return mem
+
+ mem.empty = False
+ self._decode_chanrecord(mem, _mem)
+ if _name_obj is not None:
+ mem.name = _decode_name(_name_obj.text)
+
+ immutable = ["number", "extd_number"]
+ if _name_obj is None:
+ # VFO A/B have no name storage at all.
+ immutable.append("name")
+ mem.immutable = immutable
+ return mem
+
+ def _set_special(self, mem):
+ name = SPECIAL_MEMORIES_REV[mem.number]
+ arr, names_arr, idx, kind = self._special_target(name)
+ _mem = getattr(self._memobj, arr)[idx]
+ _name_obj = (getattr(self._memobj, names_arr)[idx]
+ if names_arr else None)
+
+ if mem.empty:
+ if kind != "pms":
+ raise errors.RadioError(
+ "%s cannot be deleted -- VFO/HOME bands always exist "
+ "on the radio; only PMS entries can be cleared" % name)
+ _mem.set_raw(EMPTY_SLOT)
+ if _name_obj is not None:
+ ftm300d._set_bytes(_name_obj.text, b"\xff" * 16)
+ return
+
+ if kind == "pms" and not int(_mem.used):
+ _mem.set_raw(USED_PROTOTYPE)
+
+ self._encode_chanrecord(_mem, mem)
+ if _name_obj is not None:
+ ftm300d._set_bytes(_name_obj.text, _encode_name(mem.name))
diff --git a/chirp/drivers/ftm300d.py b/chirp/drivers/ftm300d.py
new file mode 100644
index 0000000..e147082
--- /dev/null
+++ b/chirp/drivers/ftm300d.py
@@ -0,0 +1,1398 @@
+# Copyright 2026 CHIRP contributors
+#
+# 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/>.
+
+"""Yaesu FTM-300DR experimental driver.
+
+Memory map from ADMS-12 CLNFTM300D.dat dumps (98304 bytes, ident AH071).
+Clone-in/out is 38400 8N1, 131-byte frames (BE address + 128 payload +
+sum%256), ACK 0x06, address wrap at 0x10000 for names.
+"""
+
+import logging
+import struct
+
+from chirp.drivers import yaesu_clone
+from chirp import bitwise
+from chirp import chirp_common
+from chirp import directory
+from chirp import errors
+from chirp import memmap
+from chirp.settings import MemSetting
+from chirp.settings import RadioSetting
+from chirp.settings import RadioSettingGroup
+from chirp.settings import RadioSettings
+from chirp.settings import RadioSettingValueBoolean
+from chirp.settings import RadioSettingValueFloat
+from chirp.settings import RadioSettingValueInteger
+from chirp.settings import RadioSettingValueList
+from chirp.settings import RadioSettingValueMap
+from chirp.settings import RadioSettingValueString
+
+LOG = logging.getLogger(__name__)
+
+FRAME_LEN = 131
+PAYLOAD_LEN = 128
+# 16-bit clone address wraps; pass 2 is file offset + 0x10000 (names).
+CLONE_PASS2 = 0x10000
+CLONE_VFO_ADDR = 0xFFFD
+CLONE_END_ADDR = 0xFFFE
+CLONE_VFO_DEST = 0x0080
+# Pass 1 skips 0x0080 (sent later as FFFD) and 0x0400 (never cloned).
+CLONE_SKIP = (0x0080, 0x0400)
+# ADMS-12 PUT (SCU-56): 768 ACKed frames. An extra leading 0x0000 in the
+# capture had no ACK (~11.5s later identical retry) — not part of the
+# protocol. GET from the radio also starts 0x0000, 0x0100, ...
+# Wire time ~34ms/frame at 38400; ACK ~36ms after OUT; next OUT ~11ms
+# after ACK. Do not copy FTM-350's 50ms post-ACK sleep. No greeting
+# byte before frame 1; PC writes first and waits for 0x06.
+
+
+def clone_addresses():
+ """Return the frozen ADMS-12 clone address list (768 frames).
+
+ Pass 1 0x0000-0xFF80 step 128 skipping 0x0080 and 0x0400, wrap to
+ file +0x10000 for names, pass 2 0x0000-0x7F80, trailer FFFD (VFO
+ at 0x80) and FFFE (end, 128 zeros, checksum 0xFD).
+ """
+ addrs = [
+ addr for addr in range(0x0000, 0x10000, PAYLOAD_LEN)
+ if addr not in CLONE_SKIP]
+ addrs.extend(range(0x0000, 0x8000, PAYLOAD_LEN))
+ addrs.append(CLONE_VFO_ADDR)
+ addrs.append(CLONE_END_ADDR)
+ return addrs
+
+
+def clone_frame(addr, payload):
+ """Build one 131-byte clone frame (BE address + 128 payload + sum%256)."""
+ if len(payload) != PAYLOAD_LEN:
+ raise ValueError("Clone payload must be %d bytes" % PAYLOAD_LEN)
+ head = struct.pack(">H", addr) + payload
+ return head + bytes([sum(head) % 256])
+
+
+def image_to_clone_frames(mmap):
+ """Serialize a 96 KiB image to the 768-frame clone stream."""
+ data = mmap.get_packed() if hasattr(mmap, "get_packed") else mmap
+ frames = []
+ bank = 0
+ prev = None
+ for addr in clone_addresses():
+ if prev is not None and prev >= 0xFF00 and addr < 0x100:
+ bank = CLONE_PASS2
+ if addr == CLONE_END_ADDR:
+ payload = b"\x00" * PAYLOAD_LEN
+ elif addr == CLONE_VFO_ADDR:
+ payload = data[CLONE_VFO_DEST:CLONE_VFO_DEST + PAYLOAD_LEN]
+ else:
+ dest = addr + bank
+ payload = data[dest:dest + PAYLOAD_LEN]
+ frames.append(clone_frame(addr, payload))
+ prev = addr
+ return frames
+
+
+def _read_clone_frame(pipe):
+ """Read one 131-byte frame. Empty means nothing has arrived yet."""
+ frame = pipe.read(FRAME_LEN)
+ if not frame:
+ return b""
+ while len(frame) < FRAME_LEN:
+ more = pipe.read(FRAME_LEN - len(frame))
+ if not more:
+ raise errors.RadioError("Timed out reading from radio")
+ frame += more
+ return frame
+
+
+def _clone_in(radio):
+ """Download the radio image over the 131-byte framed clone protocol."""
+ pipe = radio.pipe
+ if hasattr(pipe, "timeout"):
+ pipe.timeout = 1
+
+ data = memmap.MemoryMapBytes(b"\x00" * radio._memsize)
+ expected = len(clone_addresses())
+ bank = 0
+ prev_addr = None
+ frames = 0
+ attempts = 30
+ got_end = False
+
+ while not got_end:
+ if frames >= expected + 8:
+ raise errors.RadioError("Radio sent too many clone frames")
+ frame = _read_clone_frame(pipe)
+ if not frame:
+ if frames:
+ raise errors.RadioError("Timed out reading from radio")
+ attempts -= 1
+ if attempts <= 0:
+ raise errors.RadioNoResponse()
+ continue
+
+ addr, = struct.unpack(">H", frame[:2])
+ payload = frame[2:130]
+ checksum = frame[130]
+ calc = sum(frame[:130]) % 256
+ if calc != checksum:
+ LOG.debug("Calc: %02x Real: %02x addr: %04x",
+ calc, checksum, addr)
+ raise errors.RadioError("Block failed checksum")
+
+ # SCU-56 does not echo; do not chew 0x06 into the next frame.
+ pipe.write(b"\x06")
+
+ if frames == 0 and addr == 0:
+ ident = payload[:len(radio._model)]
+ if ident != radio._model:
+ raise errors.RadioError(
+ "Incorrect model ident (got %r)" % payload[:6])
+
+ if addr == CLONE_END_ADDR:
+ got_end = True
+ elif addr == CLONE_VFO_ADDR:
+ data[CLONE_VFO_DEST] = payload
+ else:
+ if (prev_addr is not None and prev_addr >= 0xFF00
+ and addr < 0x100):
+ bank = CLONE_PASS2
+ LOG.debug("Clone wrap to names at frame %d", frames)
+ dest = addr + bank
+ try:
+ data[dest] = payload
+ except IndexError:
+ raise errors.RadioError(
+ "Clone address 0x%04X maps past end of image" % addr)
+
+ prev_addr = addr
+ frames += 1
+
+ status = chirp_common.Status()
+ status.cur = frames
+ status.max = expected
+ status.msg = "Cloning from radio"
+ radio.status_fn(status)
+
+ if frames != expected:
+ LOG.warning("Expected %d clone frames, got %d", expected, frames)
+ LOG.debug("Clone-in finished after %d frames", frames)
+ return data
+
+
+def _clone_out(radio):
+ """Upload the radio image over the 131-byte framed clone protocol."""
+ pipe = radio.pipe
+ if hasattr(pipe, "timeout"):
+ pipe.timeout = 1
+
+ ident = bytes(radio.get_mmap()[0:len(radio._model)])
+ if ident != radio._model:
+ raise errors.RadioError(
+ "Incorrect model ident (got %r)" % ident)
+
+ frames = image_to_clone_frames(radio.get_mmap())
+ expected = len(frames)
+
+ for i, frame in enumerate(frames):
+ attempts = 30 if i == 0 else 1
+ while True:
+ # SCU-56 does not echo; wait for a real 0x06 from the radio.
+ pipe.write(frame)
+ ack = pipe.read(1)
+ if ack == b"\x06":
+ break
+ if ack:
+ raise errors.RadioError(
+ "Radio refused block %d (got %r)" % (i, ack))
+ attempts -= 1
+ if attempts <= 0:
+ if i == 0:
+ raise errors.RadioNoResponse()
+ raise errors.RadioError(
+ "Timed out waiting for ACK on block %d" % i)
+ LOG.debug("No ACK on frame 0, retrying (%d left)", attempts)
+
+ status = chirp_common.Status()
+ status.cur = i + 1
+ status.max = expected
+ status.msg = "Cloning to radio"
+ radio.status_fn(status)
+
+ LOG.debug("Clone-out finished after %d frames", expected)
+
+
+YFREQ_FORMAT = """
+struct yfreq {
+ u8 fine_5k:1,
+ fine_2k5:1,
+ fine_1k25:1,
+ fine_625:1,
+ hun:4;
+ u8 bcd[2];
+};
+"""
+
+MEM_FORMAT = YFREQ_FORMAT + """
+#seekto 0x0000;
+u8 ident[6];
+
+#seekto 0x0081;
+u8 unknown_81_hi:2,
+ fm_bandwidth_a:1,
+ rx_am_a:1,
+ rpt_shift_a:4;
+
+#seekto 0x0085;
+u8 vfo_tone_a:4,
+ vfo_step_a:4;
+
+#seekto 0x008C;
+u16 rpt_shift_freq_a;
+
+#seekto 0x0091;
+u8 unknown_91_hi:2,
+ fm_bandwidth_b:1,
+ rx_am_b:1,
+ rpt_shift_b:4;
+
+#seekto 0x0095;
+u8 vfo_tone_b:4,
+ vfo_step_b:4;
+
+#seekto 0x009C;
+u16 rpt_shift_freq_b;
+
+#seekto 0x009A;
+u8 clock_type_b:1,
+ unknown_9a:7;
+
+#seekto 0x00A1;
+u8 unit;
+
+#seekto 0x00A4;
+u8 apo;
+
+#seekto 0x00A8;
+u8 tz_west:1,
+ tz_mag:7;
+
+#seekto 0x00AA;
+u8 tot;
+
+#seekto 0x00AD;
+u8 display_mode;
+
+#seekto 0x00AF;
+u8 gps_datum;
+
+#seekto 0x00B5;
+u8 gps_log;
+u8 vox;
+u8 vox_delay;
+u8 recording_band;
+
+#seekto 0x00E3;
+u8 unknown_e3_hi:2,
+ rx_coverage_a:1,
+ rx_auto_a:1,
+ step_auto_a:1,
+ unknown_e3_2:1,
+ rx_auto_menu_a:1,
+ unknown_e3_lo:1;
+u8 unknown_e4_hi:5,
+ rpt_ars_a:1,
+ unknown_e4_lo:2;
+
+#seekto 0x00E5;
+u8 unknown_e5_hi:2,
+ band_scope:1,
+ unknown_e5_lo:5;
+
+#seekto 0x00E8;
+u8 display_info:1,
+ unknown_e8_hi:2,
+ standby_beep_off:1,
+ unknown_e8_3:1,
+ target_location:1,
+ digital_vw:1,
+ unknown_e8_lo:1;
+u8 unknown_e9_hi:6,
+ sub_band_mute:2;
+u8 unknown_ea_hi:2,
+ unknown_ea_5:1,
+ unknown_ea_4:1,
+ recording_mic:1,
+ unknown_ea_lo:3;
+
+#seekto 0x00EB;
+u8 location_service:1,
+ unknown_eb_6:3,
+ beep_on:1,
+ unknown_eb_lo:3;
+
+#seekto 0x00EC;
+u8 gps_device:1,
+ unknown_ec:7;
+
+#seekto 0x00EE;
+u8 ams_tx_mode;
+
+#seekto 0x00F3;
+u8 unknown_f3_hi:2,
+ rx_coverage_b:1,
+ rx_auto_b:1,
+ step_auto_b:1,
+ unknown_f3_2:1,
+ rx_auto_menu_b:1,
+ unknown_f3_lo:1;
+u8 unknown_f4_hi:5,
+ rpt_ars_b:1,
+ unknown_f4_lo:2;
+
+#seekto 0x00F9;
+u8 unknown_f9_hi:2,
+ unknown_f9_5:1,
+ time_12hr:1,
+ unknown_f9_3:1,
+ date_fmt:3;
+
+#seekto 0x00FA;
+u8 unknown_fa_hi:3,
+ beep_high:1,
+ unknown_fa_lo:4;
+
+#seekto 0x028F;
+u8 lcd_brightness;
+
+#seekto 0x02D6;
+u8 compass;
+
+#seekto 0x02DB;
+u8 digital_popup;
+
+#seekto 0x02DD;
+u8 mic_gain;
+
+#seekto 0x02C8;
+u8 callsign[10];
+
+#seekto 0x0508;
+u8 aprs_call[6];
+u8 aprs_ssid;
+
+#seekto 0x0534;
+u8 aprs_modem;
+
+#seekto 0x0800;
+struct {
+ u8 used:1,
+ unknown0:1,
+ skip:1,
+ unknown1:3,
+ uhf:1,
+ unknown2:1;
+ u8 unused_msb:1,
+ ams:1,
+ narrow:1,
+ am:1,
+ duplex:4;
+ struct yfreq freq;
+ u8 tone_mode:4,
+ tune_step:4;
+ struct yfreq tx_freq;
+ u8 power:2,
+ tone:6;
+ u8 clock_shift:1,
+ dcs:7;
+ u8 unknown4:1,
+ dn:1,
+ unknown5:2,
+ occupied:4;
+ u8 unknown6;
+ u8 offset;
+ u8 dgid_rx;
+ u8 dgid_tx;
+} memory[999];
+
+#seekto 0x4CB0;
+u16 nameflags[999];
+
+#seekto 0x10000;
+struct {
+ u8 text[16];
+} names[999];
+"""
+
+# Factory-empty slot (144.000 analog) vs ADMS-programmed prototype.
+EMPTY_SLOT = bytes.fromhex(
+ "01 00 01 44 00 00 00 00 00 00 00 03 00 00 00 00")
+USED_PROTOTYPE = bytes.fromhex(
+ "81 00 01 46 50 00 00 00 00 0c 00 0f 00 0c 00 00")
+
+POWER_LEVELS = [
+ chirp_common.PowerLevel("Hi", watts=50),
+ chirp_common.PowerLevel("Mid", watts=25),
+ chirp_common.PowerLevel("Low", watts=5),
+]
+
+STEPS = [5.0, 6.25, 8.33, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0, 100.0]
+# CONFIG 7 STEP. Nibble at 0x85/0x95 matches STEPS[]. Auto is E3/F3 bit 3
+# with nibble 0 (same as 5.0 kHz). Proven: Auto, 5.0, 6.25, 10.0, 100.0.
+# 8.33/12.5/15/20/25/50 inferred from STEPS index.
+VFO_STEP_LABELS = [
+ "AUTO",
+ "5.0 kHz",
+ "6.25 kHz",
+ "8.33 kHz",
+ "10.0 kHz",
+ "12.5 kHz",
+ "15.0 kHz",
+ "20.0 kHz",
+ "25.0 kHz",
+ "50.0 kHz",
+ "100.0 kHz",
+]
+
+
+def vfo_step_to_fields(label):
+ if label == "AUTO":
+ return 1, 0
+ return 0, VFO_STEP_LABELS.index(label) - 1
+
+
+# Duplex nibble from dumps: 0 simplex, 2 minus, 3 plus, 4 split.
+DUPLEX_FROM_RADIO = {0: "", 2: "-", 3: "+", 4: "split"}
+DUPLEX_TO_RADIO = {v: k for k, v in DUPLEX_FROM_RADIO.items()}
+
+# High nibble of byte 5. 3 is TSQL-R (ADMS REV TONE). 5/6 are PR/Pager
+# in dumps; not in CHIRP valid_tmodes yet.
+TMODE_FROM_RADIO = {0: "", 1: "Tone", 2: "TSQL", 3: "TSQL-R", 4: "DTCS"}
+TMODE_TO_RADIO = {v: k for k, v in TMODE_FROM_RADIO.items()}
+
+# CONFIG 12 UNIT at 0x00A1 (USA default INCH). CONFIG 3 TIME ZONE at
+# 0x00A8: sign-magnitude half-hours (bit7 west, low 7 bits 0-28).
+# Proven: 0x00 = UTC +/-0:00, 0x01 = +0:30, 0x81 = -0:30.
+UNIT_LABELS = ["METRIC", "INCH"]
+TZ_HALF_MIN = -28
+TZ_HALF_MAX = 28
+
+
+def timezone_from_fields(west, mag):
+ mag = int(mag)
+ if int(west):
+ return -mag
+ return mag
+
+
+def timezone_to_fields(half_hours):
+ half = max(TZ_HALF_MIN, min(TZ_HALF_MAX, int(half_hours)))
+ if half < 0:
+ return 1, -half
+ return 0, half
+
+
+def timezone_label(half_hours):
+ if half_hours == 0:
+ return "UTC \u00b10:00"
+ sign = "+" if half_hours > 0 else "-"
+ h = abs(half_hours)
+ return "UTC %s%d:%02d" % (sign, h // 2, (h % 2) * 30)
+
+
+TIMEZONE_LABELS = [
+ timezone_label(h) for h in range(TZ_HALF_MIN, TZ_HALF_MAX + 1)]
+
+# CONFIG 2 DATE&TIME FORMAT at 0x00F9: date in bits 2-0, 12-hour in bit 4.
+# Proven: MMM/DD/YYYY=2 (0x22), YYYY/MMM/DD=0 (0x20),
+# DD/MMM/YYYY=4 (0x24), YYYY/DD/MMM=1 (0x21).
+DATE_FORMAT_MAP = (
+ ("YYYY/MMM/DD", 0),
+ ("YYYY/DD/MMM", 1),
+ ("MMM/DD/YYYY", 2),
+ ("DD/MMM/YYYY", 4),
+)
+TIME_FORMAT_LABELS = ["24 HOUR", "12 HOUR"]
+# CONFIG 9 CLOCK TYPE at 0x009A bit 7. Proven A=0, B=1.
+CLOCK_TYPE_LABELS = ["A", "B"]
+
+FM_BANDWIDTH_LABELS = ["WIDE", "NARROW"]
+# MODE is per band (A=0x0081/0x00E3, B=0x0091/0x00F3). DIGITAL is global.
+# FM bandwidth = bit5 of 81/91. RX MODE Auto = bit4 of E3/F3; AM = bit4
+# of 81/91; FM = both 0. E3/F3 bit1 is "Auto listed in the radio menu"
+# (writes set it).
+RX_MODE_LABELS = ["AUTO", "FM", "AM"]
+# TX/RX DIGITAL 4 STANDBY BEEP at 0x00E8 bit4 (1=Off).
+# DIGITAL VW at 0x00E8 bit1. LOCATION SERVICE at 0x00EB bit7 (1=ON).
+STANDBY_BEEP_LABELS = ["ON", "OFF"]
+ON_Off_LABELS = ["OFF", "ON"]
+# DIGITAL POPUP at 0x02DB. Proven Off=0 .. 60sec=8, Continue=0xFF.
+# Default 10sec=5.
+DIGITAL_POPUP_MAP = (
+ ("OFF", 0),
+ ("2 SEC", 1),
+ ("4 SEC", 2),
+ ("6 SEC", 3),
+ ("8 SEC", 4),
+ ("10 SEC", 5),
+ ("20 SEC", 6),
+ ("30 SEC", 7),
+ ("60 SEC", 8),
+ ("CONTINUE", 0xFF),
+)
+# TX/RX AUDIO MIC GAIN at 0x02DD. Proven MIN=0 .. Max=4. Default NORMAL=2.
+MIC_GAIN_MAP = (
+ ("MIN", 0),
+ ("LOW", 1),
+ ("NORMAL", 2),
+ ("HIGH", 3),
+ ("MAX", 4),
+)
+# SUB BAND MUTE at 0x00E9 bits 1-0. Proven ON=0, Off=3 (global).
+SUB_BAND_MUTE_MAP = (("ON", 0), ("OFF", 3))
+# VOX at 0x00B6. Proven Off=0, LOW=1, HIGH=2.
+VOX_LABELS = ["OFF", "LOW", "HIGH"]
+# VOX DELAY at 0x00B7. Proven 1.0s=1 .. 3.0s=5. Baseline 0 inferred as 0.5s.
+VOX_DELAY_MAP = (
+ ("0.5 SEC", 0),
+ ("1.0 SEC", 1),
+ ("1.5 SEC", 2),
+ ("2.0 SEC", 3),
+ ("2.5 SEC", 4),
+ ("3.0 SEC", 5),
+)
+# RECORDING BAND at 0x00B8. Proven A=1, B=2, A+B=3.
+RECORDING_BAND_MAP = (("A", 1), ("B", 2), ("A+B", 3))
+
+# TX/RX DIGITAL AMS TX MODE at 0x00EE (global).
+# Proven: Auto=0, TX FM FIXED=1, TX DN FIXED=2.
+AMS_TX_MODE_LABELS = ["AUTO", "TX FM Fixed", "TX DN Fixed"]
+
+# CONFIG 8 BEEP: Off / LOW / HIGH as two flags.
+# Proven: enable = 0x00EB bit3, HIGH = 0x00FA bit4. Off leaves volume.
+BEEP_LABELS = ["OFF", "LOW", "HIGH"]
+
+
+def beep_from_fields(beep_on, beep_high):
+ if not int(beep_on):
+ return "OFF"
+ if int(beep_high):
+ return "HIGH"
+ return "LOW"
+
+
+def beep_to_fields(label):
+ if label == "OFF":
+ return 0, None
+ if label == "HIGH":
+ return 1, 1
+ return 1, 0
+
+
+def rx_mode_from_fields(rx_auto, rx_am):
+ if int(rx_auto):
+ return "AUTO"
+ if int(rx_am):
+ return "AM"
+ return "FM"
+
+
+def rx_mode_to_fields(label):
+ if label == "AUTO":
+ return 1, 0
+ if label == "AM":
+ return 0, 1
+ return 0, 0
+
+
+# DISPLAY 1 TARGET LOCATION at 0x00E8 bit 2. Proven Compass=0, Numeric=1.
+TARGET_LOCATION_LABELS = ["COMPASS", "NUMERIC"]
+# DISPLAY 2 COMPASS at 0x02D6. Proven North Up=0, Heading Up=1.
+COMPASS_LABELS = ["NORTH UP", "HEADING UP"]
+# DISPLAY 3 BAND SCOPE at 0x00E5 bit 5. Proven Wide=0, Narrow=1.
+BAND_SCOPE_LABELS = ["WIDE", "NARROW"]
+# GPS DATUM at 0x00AF. Proven WGS-84=0x15, Tokyo Mean=0xB2.
+GPS_DATUM_MAP = (("WGS-84", 0x15), ("TOKYO MEAN", 0xB2))
+# GPS DEVICE at 0x00EC bit 7. Proven Internal=0, External=1.
+GPS_DEVICE_LABELS = ["INTERNAL", "EXTERNAL"]
+# CONFIG 17 GPS LOG at 0x00B5.
+# Proven: Off=0, 1s=1, 2s=2, 5s=3, 10s=4, 30s=5, 60s=6. Default Off.
+GPS_LOG_MAP = (
+ ("OFF", 0),
+ ("1 SEC", 1),
+ ("2 SEC", 2),
+ ("5 SEC", 3),
+ ("10 SEC", 4),
+ ("30 SEC", 5),
+ ("60 SEC", 6),
+)
+# CONFIG 11 RX COVERAGE at 0x00E3/0x00F3 bit 5 (per band).
+# Proven: NORMAL=0, Wide=1 (factory).
+RX_COVERAGE_LABELS = ["NORMAL", "WIDE"]
+# CONFIG 14 TOT at 0x00AA. Factory 5 min.
+# Proven: Off=0, 5min=1, 10min=2, 15min=3, 20min=4, 30min=5,
+# 1min=6, 2min=7, 3min=8.
+TOT_MAP = (
+ ("OFF", 0),
+ ("1 MIN", 6),
+ ("2 MIN", 7),
+ ("3 MIN", 8),
+ ("5 MIN", 1),
+ ("10 MIN", 2),
+ ("15 MIN", 3),
+ ("20 MIN", 4),
+ ("30 MIN", 5),
+)
+# CONFIG 13 APO at 0x00A4, 0.5 hour units. Factory OFF=0.
+# Proven: OFF=0, 0.5h=1, 1.0h=2, 1.5h=3, 2.0h=4, 3.0h=6, 4.0h=8,
+# 12.0h=24. Other 0.5h steps inferred as n = hours*2.
+APO_MAP = (("OFF", 0),) + tuple(
+ ("%.1f HOUR" % (n / 2.0), n) for n in range(1, 25))
+# CONFIG RPT ARS at 0x00E4/0x00F4 bit 2 (per band). Proven ON=1, Off=0.
+# VFO RPT SHIFT is the duplex nibble of 0x81/0x91 (0=Off, 2=-, 3=+).
+# VFO SHIFT FREQ at 0x8C/0x9C, u16 BE in 50 kHz units (manual 0.00-99.95).
+# Proven: 0.75=0x000F, 1.45=0x001D, 3.10=0x003E, 5.00=0x0064,
+# 20.00=0x0190. Factory A=0.60 (0x000C), B=5.00 (0x0064).
+RPT_SHIFT_MAP = (("OFF", 0), ("-", 2), ("+", 3))
+RPT_SHIFT_FREQ_STEP = 0.05
+RPT_SHIFT_FREQ_MAX = 99.95
+RPT_SHIFT_FREQ_UNITS_MAX = 1999 # 99.95 / 0.05
+
+
+def _rpt_shift_freq_to_radio(value):
+ units = int(round(float(value) / RPT_SHIFT_FREQ_STEP))
+ if units < 0:
+ units = 0
+ if units > RPT_SHIFT_FREQ_UNITS_MAX:
+ units = RPT_SHIFT_FREQ_UNITS_MAX
+ return units
+
+
+# DISPLAY 6 DISPLAY MODE: 0x00E8 bit 7 is the info screen (0=default)
+# dual-band display). 0x00AD selects Backtrack=0, Altitude=1,
+# Timer/Clock=2, GPS Information=3 when the info screen is on.
+DISPLAY_MODE_LABELS = [
+ "DEFAULT", "BACKTRACK", "ALTITUDE", "TIMER/CLOCK", "GPS INFORMATION"]
+
+
+def display_mode_to_fields(label):
+ if label == "DEFAULT":
+ return 0, None
+ return 1, DISPLAY_MODE_LABELS.index(label) - 1
+
+
+# DISPLAY 4 LCD BRIGHTNESS at 0x028F. Proven MIN=3, MID=5, MAX=6.
+BRIGHTNESS_MAP = (("MIN", 3), ("MID", 5), ("MAX", 6))
+# F(SETUP) CALLSIGN: 10 chars at 0x02C8, 0xFF pad.
+# APRS 21 CALLSIGN: 6 chars at 0x0508, 0xCA pad (empty is all 0xCA).
+# SSID at 0x050E. Proven AAAAAA-13 -> 0x0D; empty pad 0xCA (not SSID 0).
+# APRS 4 MODEM at 0x0534. Proven Off=0, ON=1.
+# Radio CALLSIGN allows A-Z, 0-9, hyphen, and slash.
+CALLSIGN_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-/"
+APRS_CALL_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
+CALLSIGN_PAD = 0xFF
+APRS_CALL_PAD = 0xCA
+APRS_SSID_MAX = 15
+# Empty SSID is pad 0xCA, distinct from SSID 0.
+APRS_SSID_MAP = (("", APRS_CALL_PAD),) + tuple(
+ (str(i), i) for i in range(APRS_SSID_MAX + 1))
+APRS_MODEM_LABELS = ["OFF", "ON"]
+
+
+def _decode_padded(raw, pad):
+ buf = bytes(int(x) for x in raw)
+ return buf.split(bytes([pad]))[0].split(b"\x00")[0].decode(
+ "ascii", "replace").rstrip()
+
+
+def _encode_padded(text, length, pad, charset):
+ cleaned = "".join(c if c in charset else "" for c in text.upper())
+ cleaned = cleaned[:length]
+ data = cleaned.encode("ascii") + bytes([pad]) * (length - len(cleaned))
+ return data
+
+
+# Fine-step flags in the high nibble of the first freq byte.
+# Proven: 0x80 = +5 kHz, 0x20 = +1.25 kHz, together +6.25 kHz (0xA0).
+_FREQ_FINE = (
+ ("fine_5k", 5000),
+ ("fine_2k5", 2500),
+ ("fine_1k25", 1250),
+ ("fine_625", 625),
+)
+
+
+def decode_freq(freq):
+ """Decode a yfreq struct to Hz."""
+ digits = "%X%02X%02X" % (
+ int(freq.hun), int(freq.bcd[0]), int(freq.bcd[1]))
+ hz = int(digits, 10) * 10000
+ for name, add in _FREQ_FINE:
+ if int(getattr(freq, name)):
+ hz += add
+ return hz
+
+
+def encode_freq(freq, hz):
+ """Encode Hz into a yfreq struct."""
+ rem = hz % 10000
+ base = hz - rem
+ for name, add in _FREQ_FINE:
+ if rem >= add:
+ setattr(freq, name, 1)
+ rem -= add
+ else:
+ setattr(freq, name, 0)
+ khz10 = base // 10000
+ s = "%06d" % khz10
+ freq.hun = int(s[1])
+ freq.bcd[0] = (int(s[2]) << 4) | int(s[3])
+ freq.bcd[1] = (int(s[4]) << 4) | int(s[5])
+
+
+def parse_freq_bytes(raw):
+ """Parse a 3-byte freq encoding (for tests)."""
+ mmap = memmap.MemoryMapBytes(bytes(raw))
+ freq = bitwise.parse(
+ YFREQ_FORMAT + "struct yfreq freq;", mmap).freq
+ return mmap, freq
+
+
+def _set_bytes(element, data):
+ for i, value in enumerate(data):
+ element[i] = value
+
+
+@directory.register
+class FTM300Radio(yaesu_clone.YaesuCloneModeRadio,
+ chirp_common.ExperimentalRadio):
+ """Yaesu FTM-300DR (USA)."""
+ VENDOR = "Yaesu"
+ MODEL = "FTM-300DR"
+ BAUD_RATE = 38400
+ NEEDS_COMPAT_SERIAL = False
+ FORMATS = [directory.register_format('Yaesu FTM-300DR SD ALL', '*.dat')]
+
+ _model = b"AH071"
+ _memsize = 98304
+ _tx_bands = [
+ (144000000, 148000000),
+ (430000000, 450000000),
+ ]
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ # Keep these untranslated so we do not churn locale .po files.
+ rp.experimental = (
+ "The FTM-300DR driver is experimental. Memories, serial "
+ "clone, and some Config/Display/callsign settings work; "
+ "Home/PMS, most Set Mode items, and most APRS are not "
+ "mapped. "
+ "Keep a microSD ALL backup (SD CARD -> BACKUP -> WRITE TO "
+ "SD -> ALL) before uploading. The stock USB cable in the box "
+ "is not a programming cable.")
+ rp.info = (
+ "Use an SCU-56 or SCU-20 on the DATA jack at 38400 8N1. Keep "
+ "a microSD ALL backup. If clone shows ERROR, restore with "
+ "SD CARD -> READ FROM SD -> ALL.")
+ rp.pre_download = (
+ "1. Connect an SCU-56 or SCU-20 to the DATA jack "
+ "(not the stock USB firmware cable).\n"
+ "2. Press and hold [F(SETUP)], select CLONE, then "
+ "[1 This → Other].\n"
+ "3. <b>After clicking OK</b>, on the radio select OK and "
+ "press the DIAL knob.\n")
+ rp.pre_upload = (
+ "Keep a microSD ALL backup first.\n"
+ "1. Connect an SCU-56 or SCU-20 to the DATA jack "
+ "(not the stock USB firmware cable).\n"
+ "2. Press and hold [F(SETUP)], select CLONE, then "
+ "[2 Other → This].\n"
+ "3. <b>After clicking OK</b>, on the radio select OK and "
+ "press the DIAL knob.\n")
+ return rp
+
+ def _append_mode(self, parent, suffix, title):
+ group = RadioSettingGroup("band_%s" % suffix, title)
+ parent.append(group)
+ group.append(MemSetting(
+ "fm_bandwidth_%s" % suffix, "FM Bandwidth",
+ RadioSettingValueList(
+ FM_BANDWIDTH_LABELS,
+ current_index=int(
+ getattr(self._memobj, "fm_bandwidth_%s" % suffix)))))
+ rx = rx_mode_from_fields(
+ getattr(self._memobj, "rx_auto_%s" % suffix),
+ getattr(self._memobj, "rx_am_%s" % suffix))
+ group.append(RadioSetting(
+ "rx_mode_%s" % suffix, "RX Mode",
+ RadioSettingValueList(
+ RX_MODE_LABELS, current_index=RX_MODE_LABELS.index(rx))))
+
+ def _append_repeater_settings(self, parent, suffix, title):
+ group = RadioSettingGroup("repeater_%s" % suffix, title)
+ parent.append(group)
+ group.append(MemSetting(
+ "rpt_ars_%s" % suffix, "ARS",
+ RadioSettingValueList(
+ ON_Off_LABELS,
+ current_index=int(
+ getattr(self._memobj, "rpt_ars_%s" % suffix)))))
+ group.append(MemSetting(
+ "rpt_shift_%s" % suffix, "Shift",
+ RadioSettingValueMap(
+ RPT_SHIFT_MAP,
+ mem_val=int(
+ getattr(self._memobj, "rpt_shift_%s" % suffix)))))
+ units = int(getattr(self._memobj, "rpt_shift_freq_%s" % suffix))
+ mhz = round(units * RPT_SHIFT_FREQ_STEP, 2)
+ group.append(RadioSetting(
+ "rpt_shift_freq_%s" % suffix, "Shift Freq",
+ RadioSettingValueFloat(
+ 0.0, RPT_SHIFT_FREQ_MAX, mhz, RPT_SHIFT_FREQ_STEP, 2)))
+
+ def _append_step_settings(self, group, suffix, title):
+ if int(getattr(self._memobj, "step_auto_%s" % suffix)):
+ idx = 0
+ else:
+ idx = int(getattr(self._memobj, "vfo_step_%s" % suffix)) + 1
+ rs = RadioSetting(
+ "vfo_step_%s" % suffix, title,
+ RadioSettingValueList(VFO_STEP_LABELS, current_index=idx))
+ rs.set_doc(
+ "VFO mode only. In Memory mode the radio uses each "
+ "channel's Tuning Step.")
+ group.append(rs)
+
+ def _append_rx_coverage_settings(self, group, suffix, title):
+ group.append(MemSetting(
+ "rx_coverage_%s" % suffix, title,
+ RadioSettingValueList(
+ RX_COVERAGE_LABELS,
+ current_index=int(
+ getattr(self._memobj, "rx_coverage_%s" % suffix)))))
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_bank = False
+ rf.has_bank_names = False
+ rf.has_settings = True
+ rf.has_ctone = False
+ rf.has_dtcs = True
+ rf.has_dtcs_polarity = False
+ rf.has_cross = False
+ rf.has_rx_dtcs = False
+ rf.has_comment = False
+ rf.has_nostep_tuning = False
+ rf.can_odd_split = True
+ rf.can_delete = True
+ rf.memory_bounds = (1, 999)
+ rf.valid_modes = ["FM", "NFM", "AM", "DN"]
+ rf.valid_tmodes = ["", "Tone", "TSQL", "TSQL-R", "DTCS"]
+ rf.valid_duplexes = ["", "-", "+", "split"]
+ rf.valid_tuning_steps = list(STEPS)
+ rf.valid_skips = ["", "S"]
+ rf.valid_power_levels = POWER_LEVELS
+ rf.valid_name_length = 16
+ rf.valid_characters = chirp_common.CHARSET_ASCII
+ rf.valid_dtcs_codes = list(chirp_common.DTCS_CODES)
+ rf.valid_bands = [
+ (108000000, 174000000),
+ (174000000, 400000000),
+ (400000000, 480000000),
+ (480000000, 824000000),
+ (849000000, 869000000),
+ (894000000, 999990000),
+ ]
+ return rf
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+
+ def get_settings(self):
+ top = RadioSettings()
+ config = RadioSettingGroup("config", "Config")
+ top.append(config)
+
+ half = timezone_from_fields(
+ self._memobj.tz_west, self._memobj.tz_mag)
+ tz_idx = half - TZ_HALF_MIN
+ if tz_idx < 0 or tz_idx >= len(TIMEZONE_LABELS):
+ tz_idx = len(TIMEZONE_LABELS)
+ # Two bitfields; applied as leftover in set_settings().
+ config.append(RadioSetting(
+ "timezone", "Time Zone",
+ RadioSettingValueList(
+ TIMEZONE_LABELS, current_index=tz_idx)))
+
+ date_time_format = RadioSettingGroup("date_time_format",
+ "Date & Time Format")
+ config.append(date_time_format)
+ date_time_format.append(MemSetting(
+ "date_fmt", "Date Format",
+ RadioSettingValueMap(
+ DATE_FORMAT_MAP, mem_val=int(self._memobj.date_fmt))))
+ date_time_format.append(MemSetting(
+ "time_12hr", "Time Format",
+ RadioSettingValueList(
+ TIME_FORMAT_LABELS,
+ current_index=int(self._memobj.time_12hr))))
+
+ repeater = RadioSettingGroup("repeater", "Repeater")
+ config.append(repeater)
+ self._append_repeater_settings(repeater, "a", "A Band")
+ self._append_repeater_settings(repeater, "b", "B Band")
+
+ vfo_step = RadioSettingGroup("vfo_step", "Step (VFO)")
+ vfo_step.set_doc(
+ "Tuning step in VFO mode. Auto follows the band plan. "
+ "Memory mode uses each channel's Tuning Step in the "
+ "memory editor.")
+ config.append(vfo_step)
+ self._append_step_settings(vfo_step, "a", "A Band")
+ self._append_step_settings(vfo_step, "b", "B Band")
+
+ rx_coverage = RadioSettingGroup("rx_coverage", "RX Coverage")
+ config.append(rx_coverage)
+ self._append_rx_coverage_settings(rx_coverage, "a", "A Band")
+ self._append_rx_coverage_settings(rx_coverage, "b", "B Band")
+
+ beep = beep_from_fields(
+ self._memobj.beep_on, self._memobj.beep_high)
+ config.append(RadioSetting(
+ "beep", "Beep",
+ RadioSettingValueList(
+ BEEP_LABELS, current_index=BEEP_LABELS.index(beep))))
+
+ config.append(MemSetting(
+ "clock_type_b", "Clock Type",
+ RadioSettingValueList(
+ CLOCK_TYPE_LABELS,
+ current_index=int(self._memobj.clock_type_b))))
+
+ config.append(MemSetting(
+ "unit", "Display Units",
+ RadioSettingValueList(
+ UNIT_LABELS, current_index=int(self._memobj.unit))))
+
+ config.append(MemSetting(
+ "apo", "APO",
+ RadioSettingValueMap(APO_MAP, mem_val=int(self._memobj.apo))))
+
+ config.append(MemSetting(
+ "tot", "TOT",
+ RadioSettingValueMap(TOT_MAP, mem_val=int(self._memobj.tot))))
+
+ config.append(MemSetting(
+ "gps_datum", "GPS Datum",
+ RadioSettingValueMap(
+ GPS_DATUM_MAP, mem_val=int(self._memobj.gps_datum))))
+ config.append(MemSetting(
+ "gps_device", "GPS Device",
+ RadioSettingValueList(
+ GPS_DEVICE_LABELS,
+ current_index=int(self._memobj.gps_device))))
+ config.append(MemSetting(
+ "gps_log", "GPS Log",
+ RadioSettingValueMap(
+ GPS_LOG_MAP, mem_val=int(self._memobj.gps_log))))
+
+ txrx = RadioSettingGroup("txrx", "TX/RX")
+ top.append(txrx)
+
+ mode = RadioSettingGroup("mode", "Mode")
+ self._append_mode(mode, "a", "A Band")
+ self._append_mode(mode, "b", "B Band")
+ txrx.append(mode)
+
+ digital = RadioSettingGroup("digital", "Digital")
+ txrx.append(digital)
+ digital.append(MemSetting(
+ "ams_tx_mode", "AMS TX Mode",
+ RadioSettingValueList(
+ AMS_TX_MODE_LABELS,
+ current_index=int(self._memobj.ams_tx_mode))))
+ digital.append(MemSetting(
+ "digital_popup", "Digital Popup",
+ RadioSettingValueMap(
+ DIGITAL_POPUP_MAP,
+ mem_val=int(self._memobj.digital_popup))))
+ digital.append(MemSetting(
+ "location_service", "Location Service",
+ RadioSettingValueList(
+ ON_Off_LABELS,
+ current_index=int(self._memobj.location_service))))
+ digital.append(MemSetting(
+ "standby_beep_off", "Standby Beep",
+ RadioSettingValueList(
+ STANDBY_BEEP_LABELS,
+ current_index=int(self._memobj.standby_beep_off))))
+ digital.append(MemSetting(
+ "digital_vw", "Digital VW",
+ RadioSettingValueList(
+ ON_Off_LABELS,
+ current_index=int(self._memobj.digital_vw))))
+
+ audio = RadioSettingGroup("audio", "Audio")
+ txrx.append(audio)
+ audio.append(MemSetting(
+ "sub_band_mute", "Sub Band Mute",
+ RadioSettingValueMap(
+ SUB_BAND_MUTE_MAP,
+ mem_val=int(self._memobj.sub_band_mute))))
+ audio.append(MemSetting(
+ "mic_gain", "Mic Gain",
+ RadioSettingValueMap(
+ MIC_GAIN_MAP, mem_val=int(self._memobj.mic_gain))))
+
+ vox = RadioSettingGroup("vox", "VOX")
+ audio.append(vox)
+
+ vox.append(MemSetting(
+ "vox", "VOX",
+ RadioSettingValueList(
+ VOX_LABELS, current_index=int(self._memobj.vox))))
+ vox.append(MemSetting(
+ "vox_delay", "VOX Delay",
+ RadioSettingValueMap(
+ VOX_DELAY_MAP, mem_val=int(self._memobj.vox_delay))))
+
+ recording = RadioSettingGroup("recording", "Recording")
+ audio.append(recording)
+
+ recording.append(MemSetting(
+ "recording_band", "Recording Band",
+ RadioSettingValueMap(
+ RECORDING_BAND_MAP,
+ mem_val=int(self._memobj.recording_band))))
+ recording.append(MemSetting(
+ "recording_mic", "Recording Mic",
+ RadioSettingValueList(
+ ON_Off_LABELS,
+ current_index=int(self._memobj.recording_mic))))
+
+ display = RadioSettingGroup("display", "Display")
+ top.append(display)
+ display.append(MemSetting(
+ "target_location", "Target Location",
+ RadioSettingValueList(
+ TARGET_LOCATION_LABELS,
+ current_index=int(self._memobj.target_location))))
+ display.append(MemSetting(
+ "compass", "COMPASS",
+ RadioSettingValueList(
+ COMPASS_LABELS, current_index=int(self._memobj.compass))))
+ display.append(MemSetting(
+ "band_scope", "Band Scope",
+ RadioSettingValueList(
+ BAND_SCOPE_LABELS,
+ current_index=int(self._memobj.band_scope))))
+ display.append(MemSetting(
+ "lcd_brightness", "LCD Brightness",
+ RadioSettingValueMap(
+ BRIGHTNESS_MAP,
+ mem_val=int(self._memobj.lcd_brightness))))
+ if int(self._memobj.display_info):
+ dmode_idx = int(self._memobj.display_mode) + 1
+ else:
+ dmode_idx = 0
+ display.append(RadioSetting(
+ "display_mode", "Display Mode",
+ RadioSettingValueList(
+ DISPLAY_MODE_LABELS, current_index=dmode_idx)))
+
+ ident = RadioSettingGroup("callsign", "Callsign")
+ top.append(ident)
+ ident.append(RadioSetting(
+ "callsign", "Radio Callsign",
+ RadioSettingValueString(
+ 0, 10, self._decode_callsign(),
+ autopad=False, charset=CALLSIGN_CHARSET)))
+
+ aprs = RadioSettingGroup("aprs", "APRS")
+ top.append(aprs)
+ aprs.append(RadioSetting(
+ "aprs_call", "APRS Callsign",
+ RadioSettingValueString(
+ 0, 6, self._decode_aprs_call(),
+ autopad=False, charset=APRS_CALL_CHARSET)))
+ aprs.append(MemSetting(
+ "aprs_ssid", "APRS SSID",
+ RadioSettingValueMap(
+ APRS_SSID_MAP, mem_val=int(self._memobj.aprs_ssid))))
+ aprs.append(MemSetting(
+ "aprs_modem", "APRS Modem",
+ RadioSettingValueList(
+ APRS_MODEM_LABELS,
+ current_index=int(self._memobj.aprs_modem))))
+ return top
+
+ def set_settings(self, settings):
+ leftover = settings.apply_to(self._memobj)
+ for element in leftover:
+ name = element.get_name()
+ value = str(element.value)
+ if name == "timezone":
+ half = TIMEZONE_LABELS.index(value) + TZ_HALF_MIN
+ west, mag = timezone_to_fields(half)
+ self._memobj.tz_west = west
+ self._memobj.tz_mag = mag
+ elif name == "beep":
+ on, high = beep_to_fields(value)
+ self._memobj.beep_on = on
+ if high is not None:
+ self._memobj.beep_high = high
+ elif name == "display_mode":
+ info, mode = display_mode_to_fields(value)
+ self._memobj.display_info = info
+ if mode is not None:
+ self._memobj.display_mode = mode
+ elif name == "rpt_shift_freq_a":
+ self._memobj.rpt_shift_freq_a = _rpt_shift_freq_to_radio(
+ value)
+ elif name == "rpt_shift_freq_b":
+ self._memobj.rpt_shift_freq_b = _rpt_shift_freq_to_radio(
+ value)
+ elif name == "vfo_step_a":
+ auto, nibble = vfo_step_to_fields(value)
+ self._memobj.step_auto_a = auto
+ self._memobj.vfo_step_a = nibble
+ elif name == "vfo_step_b":
+ auto, nibble = vfo_step_to_fields(value)
+ self._memobj.step_auto_b = auto
+ self._memobj.vfo_step_b = nibble
+ elif name == "rx_mode_a":
+ auto, am = rx_mode_to_fields(value)
+ self._memobj.rx_auto_a = auto
+ self._memobj.rx_am_a = am
+ self._memobj.rx_auto_menu_a = 1
+ elif name == "rx_mode_b":
+ auto, am = rx_mode_to_fields(value)
+ self._memobj.rx_auto_b = auto
+ self._memobj.rx_am_b = am
+ self._memobj.rx_auto_menu_b = 1
+ elif name == "callsign":
+ self._encode_callsign(value)
+ elif name == "aprs_call":
+ self._encode_aprs_call(value)
+
+ def _decode_callsign(self):
+ return _decode_padded(self._memobj.callsign, CALLSIGN_PAD)
+
+ def _encode_callsign(self, text):
+ data = _encode_padded(text, 10, CALLSIGN_PAD, CALLSIGN_CHARSET)
+ _set_bytes(self._memobj.callsign, data)
+
+ def _decode_aprs_call(self):
+ return _decode_padded(self._memobj.aprs_call, APRS_CALL_PAD)
+
+ def _encode_aprs_call(self, text):
+ data = _encode_padded(text, 6, APRS_CALL_PAD, APRS_CALL_CHARSET)
+ _set_bytes(self._memobj.aprs_call, data)
+
+ def sync_in(self):
+ try:
+ self._mmap = _clone_in(self)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.exception("Failed to read: %s", e)
+ raise errors.RadioError(
+ "Failed to download from radio (%s)" % e)
+ self.process_mmap()
+
+ def sync_out(self):
+ try:
+ _clone_out(self)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.exception("Failed to write: %s", e)
+ raise errors.RadioError(
+ "Failed to upload to radio (%s)" % e)
+
+ def get_raw_memory(self, number):
+ return repr(self._memobj.memory[number - 1])
+
+ def validate_memory(self, mem):
+ msgs = super().validate_memory(mem)
+ if mem.empty:
+ return msgs
+ if mem.duplex == "split":
+ tx = mem.offset
+ elif mem.duplex == "-":
+ tx = mem.freq - mem.offset
+ elif mem.duplex == "+":
+ tx = mem.freq + mem.offset
+ else:
+ tx = mem.freq
+ in_tx = any(lo <= tx < hi for lo, hi in self._tx_bands)
+ if not in_tx:
+ if mem.duplex in ("-", "+", "split"):
+ msgs.append(chirp_common.ValidationError(
+ "TX frequency is outside amateur allocations "
+ "for this model"))
+ else:
+ msgs.append(chirp_common.ValidationWarning(
+ "RX-only frequency; radio will not transmit here"))
+ return msgs
+
+ def _decode_name(self, number):
+ raw = bytes(int(x) for x in self._memobj.names[number - 1].text)
+ return raw.split(b"\xff")[0].split(b"\x00")[0].decode(
+ "ascii", "replace").rstrip()
+
+ def _encode_name(self, name):
+ cleaned = "".join(
+ c if c in chirp_common.CHARSET_ASCII else " "
+ for c in name)[:16]
+ padded = cleaned.encode("ascii", "replace")
+ return padded + b"\xff" * (16 - len(padded))
+
+ def _get_extra(self, mem, _mem):
+ extra = RadioSettingGroup("Extra", "extra")
+ extra.append(MemSetting(
+ "ams", "AMS mode",
+ RadioSettingValueBoolean(bool(int(_mem.ams)))))
+ extra.append(MemSetting(
+ "dgid_rx", "RX DG-ID",
+ RadioSettingValueInteger(0, 99, int(_mem.dgid_rx))))
+ extra.append(MemSetting(
+ "dgid_tx", "TX DG-ID",
+ RadioSettingValueInteger(0, 99, int(_mem.dgid_tx))))
+ extra.append(MemSetting(
+ "clock_shift", "Clock Shift",
+ RadioSettingValueBoolean(bool(int(_mem.clock_shift)))))
+ mem.extra = extra
+
+ def _apply_extra(self, mem, _mem):
+ for setting in mem.extra:
+ setting.apply_to_memobj(_mem)
+ # AMS extra maps to _mem.ams; DN-only is the inverse bit.
+ # Analog modes must not leave either digital flag set.
+ if mem.mode == "DN":
+ _mem.dn = 0 if int(_mem.ams) else 1
+ else:
+ _mem.ams = 0
+ _mem.dn = 0
+
+ def get_memory(self, number):
+ mem = chirp_common.Memory()
+ mem.number = number
+ _mem = self._memobj.memory[number - 1]
+ if not int(_mem.used):
+ mem.empty = True
+ return mem
+
+ mem.empty = False
+ mem.freq = decode_freq(_mem.freq)
+ mem.duplex = DUPLEX_FROM_RADIO.get(int(_mem.duplex), "")
+ if mem.duplex == "split":
+ mem.offset = decode_freq(_mem.tx_freq)
+ else:
+ mem.offset = int(_mem.offset) * 50000
+ mem.name = self._decode_name(number)
+ mem.skip = "S" if int(_mem.skip) else ""
+ try:
+ mem.power = POWER_LEVELS[int(_mem.power)]
+ except IndexError:
+ mem.power = POWER_LEVELS[0]
+ try:
+ mem.tuning_step = STEPS[int(_mem.tune_step)]
+ except IndexError:
+ mem.tuning_step = STEPS[0]
+ mem.tmode = TMODE_FROM_RADIO.get(int(_mem.tone_mode), "")
+ try:
+ mem.rtone = chirp_common.TONES[int(_mem.tone)]
+ except IndexError:
+ mem.rtone = 88.5
+ mem.ctone = mem.rtone
+ try:
+ mem.dtcs = chirp_common.DTCS_CODES[int(_mem.dcs)]
+ except IndexError:
+ mem.dtcs = 23
+
+ if int(_mem.am):
+ mem.mode = "AM"
+ elif int(_mem.narrow):
+ mem.mode = "NFM"
+ elif int(_mem.ams) or int(_mem.dn):
+ mem.mode = "DN"
+ else:
+ mem.mode = "FM"
+
+ self._get_extra(mem, _mem)
+ return mem
+
+ def set_memory(self, mem):
+ _mem = self._memobj.memory[mem.number - 1]
+ name_idx = mem.number - 1
+ if mem.empty:
+ _mem.set_raw(EMPTY_SLOT)
+ _set_bytes(self._memobj.names[name_idx].text, b"\xff" * 16)
+ self._memobj.nameflags[name_idx] = 0xFFFF
+ return
+
+ if not int(_mem.used):
+ _mem.set_raw(USED_PROTOTYPE)
+
+ _mem.used = 1
+ _mem.unknown2 = 1
+ _mem.occupied = 0xF
+ _mem.uhf = 1 if mem.freq >= 400000000 else 0
+ _mem.skip = 1 if mem.skip == "S" else 0
+ encode_freq(_mem.freq, mem.freq)
+ _mem.duplex = DUPLEX_TO_RADIO.get(mem.duplex, 0)
+ if mem.duplex == "split":
+ encode_freq(_mem.tx_freq, int(mem.offset))
+ _mem.offset = 0
+ else:
+ encode_freq(_mem.tx_freq, 0)
+ _mem.offset = int(round(mem.offset / 50000.0)) if mem.offset else 0
+
+ _mem.am = 1 if mem.mode == "AM" else 0
+ _mem.narrow = 1 if mem.mode == "NFM" else 0
+ if mem.mode != "DN":
+ _mem.ams = 0
+ _mem.dn = 0
+
+ try:
+ _mem.tune_step = STEPS.index(mem.tuning_step)
+ except ValueError:
+ _mem.tune_step = 0
+ _mem.tone_mode = TMODE_TO_RADIO.get(mem.tmode, 0)
+ try:
+ _mem.tone = chirp_common.TONES.index(mem.rtone)
+ except ValueError:
+ _mem.tone = chirp_common.TONES.index(88.5)
+ try:
+ _mem.dcs = chirp_common.DTCS_CODES.index(mem.dtcs)
+ except ValueError:
+ _mem.dcs = 0
+ if mem.power in POWER_LEVELS:
+ _mem.power = POWER_LEVELS.index(mem.power)
+ else:
+ _mem.power = 0
+
+ encoded = self._encode_name(mem.name)
+ _set_bytes(self._memobj.names[name_idx].text, encoded)
+ self._memobj.nameflags[name_idx] = (
+ 0x0000 if mem.name.strip() else 0xFFFF)
+
+ self._apply_extra(mem, _mem)
+ if mem.mode == "DN" and not int(_mem.ams) and not int(_mem.dn):
+ _mem.ams = 1
+ _mem.dn = 0
diff --git a/chirp/drivers/gmrsuv1.py b/chirp/drivers/gmrsuv1.py
index 20f3f47..966043c 100644
--- a/chirp/drivers/gmrsuv1.py
+++ b/chirp/drivers/gmrsuv1.py
@@ -112,6 +112,10 @@ class GMRSV1(bfc.BaofengCommonHT):
(0x1FC0, 0x1FD0)]
_send_block_size = 0x10
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return len(filedata) == 0x2008 and model_match(cls, filedata)
+
MODES = ["NFM", "FM"]
VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
"!@#$%^&*()+-=[]:\";'<>?,./"
@@ -1073,20 +1077,3 @@ class GMRSV1(bfc.BaofengCommonHT):
service.append(rs)
return top
-
- @classmethod
- def match_model(cls, filedata, filename):
- match_size = False
- match_model = False
-
- # testing the file data size
- if len(filedata) == 0x2008:
- match_size = True
-
- # testing the firmware model fingerprint
- match_model = model_match(cls, filedata)
-
- if match_size and match_model:
- return True
- else:
- return False
diff --git a/chirp/drivers/gmrsv2.py b/chirp/drivers/gmrsv2.py
index 0e7b486..820bd36 100644
--- a/chirp/drivers/gmrsv2.py
+++ b/chirp/drivers/gmrsv2.py
@@ -521,13 +521,13 @@ class GMRSV2base(bfc.BaofengCommonHT):
if mem.freq in bandplan_na.ALL_MURS_FREQS:
if mem.freq in bandplan_na.MURS_NFM:
# Narrow only MURS channels (limit mode)
- mem.duplex == ''
+ mem.duplex = ''
mem.offset = 0
mem.mode = "NFM"
immutable = ["duplex", "offset", "mode"]
if mem.freq in bandplan_na.MURS_FM:
# Narrow or wide MURS channels
- mem.duplex == ''
+ mem.duplex = ''
mem.offset = 0
immutable = ["duplex", "offset"]
else:
diff --git a/chirp/drivers/h777.py b/chirp/drivers/h777.py
index 699fb54..0d76901 100644
--- a/chirp/drivers/h777.py
+++ b/chirp/drivers/h777.py
@@ -23,7 +23,8 @@ from chirp import chirp_common, directory, memmap
from chirp import bitwise, errors, util
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueInteger, RadioSettingValueList, \
- RadioSettingValueBoolean, RadioSettings
+ RadioSettingValueBoolean, RadioSettingValueMap, \
+ RadioSettingValueString, RadioSettings
LOG = logging.getLogger(__name__)
@@ -227,6 +228,8 @@ def do_download(radio):
LOG.debug('Already in programming mode for %s',
radio.__class__.__name__)
+ radio._pre_download()
+
data = b""
status = chirp_common.Status()
@@ -338,6 +341,10 @@ class H777Radio(chirp_common.CloneModeRadio):
_has_scanmodes = True
_has_scramble = True
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return cls._memsize and len(filedata) == cls._memsize
+
def get_features(self):
rf = chirp_common.RadioFeatures()
rf.has_settings = True
@@ -390,7 +397,15 @@ class H777Radio(chirp_common.CloneModeRadio):
elif is_dtcs:
return 'DTCS', int(memval), 'R' if is_rev else 'N'
else:
- return 'Tone', int(memval) / 10.0, None
+ tone = int(memval) / 10.0
+ valid_tones = self.get_features().valid_tones
+ if tone not in valid_tones:
+ closest = min(valid_tones, key=lambda value: abs(value - tone))
+ LOG.error(
+ "Radio reports unsupported tone %.1f Hz; using %.1f Hz",
+ tone, closest)
+ tone = closest
+ return 'Tone', tone, None
def _encode_tone(self, memval, mode, value, pol):
memval[1].ignore_bits(DTCS_FLAG | DTCS_REV_FLAG)
@@ -450,8 +465,8 @@ class H777Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("bcl", "Busy Channel Lockout",
RadioSettingValueBoolean(not _mem.bcl))
rs.set_doc('Prevents transmitting on a channel that is already in '
- 'use. Pressing PTT while the channel is busy emits an '
- 'alert tone and inhibits the transmitter')
+ 'use. Pressing PTT on a busy channel sounds an alert '
+ 'tone instead of keying the transmitter.')
mem.extra.append(rs)
if self._has_scramble:
rs = RadioSetting("beatshift", "Beat Shift(scramble)",
@@ -491,9 +506,12 @@ class H777Radio(chirp_common.CloneModeRadio):
_mem.skip = mem.skip == "S"
for setting in mem.extra:
- # NOTE: Only two settings right now, both are inverted
+ # All channel extras are stored inverted
setattr(_mem, setting.get_name(), not int(setting.value))
+ self._clear_unknown_bits(_mem)
+
+ def _clear_unknown_bits(self, _mem):
# When set to one, official programming software (BF-480) shows always
# "WFM", even if we choose "NFM". Therefore, for compatibility
# purposes, we will set these to zero.
@@ -501,6 +519,10 @@ class H777Radio(chirp_common.CloneModeRadio):
_mem.unknown2 = 0
_mem.unknown3 = 0
+ def _pre_download(self):
+ """Called in programming mode, before the memory is read"""
+ pass
+
def get_settings(self):
_settings = self._memobj.settings
basic = RadioSettingGroup("basic", "Basic Settings")
@@ -511,14 +533,17 @@ class H777Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("voiceprompt", "Voice prompt",
RadioSettingValueBoolean(_settings.voiceprompt))
- rs.set_doc('Announces channel changes and operations by voice')
+ rs.set_doc('Announces the channel number and other operations out '
+ 'loud as you use the radio. It can be intrusive in quiet '
+ 'surroundings.')
basic.append(rs)
rs = RadioSetting("voicelanguage", "Voice language",
RadioSettingValueList(
VOICE_LIST,
current_index=_settings.voicelanguage))
- rs.set_doc('Language used for the voice prompts (Chinese or English)')
+ rs.set_doc('Selects the language the spoken voice prompts use. It '
+ 'has no effect unless Voice prompts are enabled.')
basic.append(rs)
rs = RadioSetting("scan", "Scan",
@@ -540,17 +565,17 @@ class H777Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("vox", "VOX",
RadioSettingValueBoolean(_settings.vox))
- rs.set_doc('Voice Operated Transmit keys the transmitter when you '
- 'speak into the microphone, eliminating the need to '
- 'press PTT')
+ rs.set_doc('Voice operated transmit. The radio starts transmitting '
+ 'when you speak towards the microphone, so hands-free '
+ 'conversation is possible without pressing PTT.')
basic.append(rs)
rs = RadioSetting("voxlevel", "VOX level",
RadioSettingValueInteger(
1, self.MAX_VOXLEVEL, _settings.voxlevel + 1))
- rs.set_doc('VOX gain sensitivity. If set too sensitive the radio '
- 'keys up on background noise; if not sensitive enough it '
- 'will not pick up your voice')
+ rs.set_doc('Sets the VOX sensitivity. Too sensitive a setting keys '
+ 'the transmitter on the noise around the radio, too '
+ 'insensitive a setting fails to pick up your voice.')
basic.append(rs)
rs = RadioSetting("voxinhibitonrx", "Inhibit VOX on receive",
@@ -590,24 +615,30 @@ class H777Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("settings2.beep", "Beep",
RadioSettingValueBoolean(
self._memobj.settings2.beep))
- rs.set_doc('When enabled, the radio emits a short tone when you '
- 'select a channel that has nothing programmed')
+ rs.set_doc('Sounds a short confirmation tone as you operate the '
+ 'radio. Turn it off when the radio has to be used '
+ 'discreetly.')
basic.append(rs)
rs = RadioSetting("settings2.batterysaver", "Battery saver",
RadioSettingValueBoolean(
self._memobj.settings2.batterysaver))
- rs.set_doc('Reduces battery power used when no signal is being '
- 'received. Activates automatically about 10 seconds '
- 'after the last received signal or operation')
+ rs.set_doc('Cuts standby power consumption by switching the receiver '
+ 'off and on in a repeating cycle once no signal has been '
+ 'received for a few seconds. It considerably extends '
+ 'battery life, at the cost of occasionally clipping the '
+ 'first moment of an incoming transmission.')
basic.append(rs)
rs = RadioSetting("settings2.squelchlevel", "Squelch level",
RadioSettingValueInteger(
0, 9, self._memobj.settings2.squelchlevel))
- rs.set_doc('Mutes the speaker when no signal is present so that you '
- 'only hear sound when a signal is received. Higher '
- 'levels require a stronger signal to unmute')
+ rs.set_doc('Sets how strong a received signal must be before the '
+ 'speaker unmutes. 0 leaves the squelch open so you hear '
+ 'noise all the time, higher values reject more weak '
+ 'signals and noise. Raise this value if the speaker keeps '
+ 'unmuting on interference, lower it if distant stations '
+ 'are being cut off.')
basic.append(rs)
if self._has_sidekey:
@@ -623,9 +654,10 @@ class H777Radio(chirp_common.CloneModeRadio):
RadioSettingValueList(
TIMEOUTTIMER_LIST,
current_index=self._memobj.settings2.timeouttimer))
- rs.set_doc('Limits the maximum length of a single transmission to '
- 'prevent overheating the radio. An alert sounds when the '
- 'limit is reached')
+ rs.set_doc('Limits how long a single transmission may last. When '
+ 'the time runs out the radio stops transmitting until '
+ 'PTT is released, which prevents overheating and stops a '
+ 'stuck PTT from blocking the channel for everyone else.')
basic.append(rs)
return top
@@ -960,3 +992,285 @@ class MAVERICKRA425Radio(BF1904Radio):
def match_model(cls, filedata, filename):
# This model is only ever matched via metadata
return False
+
+
+ZA758_MEM_FORMAT = """
+#seekto 0x0010;
+struct {
+ lbcd rxfreq[4];
+ lbcd txfreq[4];
+ lbcd rxtone[2];
+ lbcd txtone[2];
+ u8 pttid:1,
+ compander:1,
+ scramble:1,
+ skip:1,
+ highpower:1,
+ narrow:1,
+ unknown1:1,
+ bcl:1;
+ u8 unknown2[3];
+} memory[16];
+
+#seekto 0x03A0;
+u8 bot_code[15];
+
+#seekto 0x03C0;
+struct {
+ u8 unknown0:1,
+ scanmode:1,
+ pttid:2,
+ voice:2,
+ batterysaver:1,
+ beep:1;
+ u8 squelch;
+ u8 sk1short;
+ u8 tot;
+ u8 vox;
+ u8 sk2short;
+ u8 priority;
+ u8 voxdelay;
+ u8 sk1long;
+ u8 sk2long;
+} settings;
+
+#seekto 0x03E0;
+u8 eot_code[15];
+"""
+
+ZA758_SIDEKEY_LIST = ["Off", "Monitor Momentary", "High/Low Power", "Scan",
+ "VOX", "Talkaround", "Reverse", "Show Power",
+ "Show Battery", "Call Ring", "Emergency Alarm",
+ "Channel Announce", "PTT ID", "Squelch Level",
+ "Compander", "Scrambler"]
+# The factory software does not offer these functions on a short press
+ZA758_SHORTPRESS_EXCLUDE = (2, 5, 6, 7)
+ZA758_VOICE_LIST = ["Off", "Chinese", "English"]
+ZA758_PTTID_LIST = ["Off", "Begin of TX", "End of TX", "Both"]
+ZA758_VOX_LIST = ["Off"] + ["%i" % x for x in range(1, 10)]
+ZA758_VOXDELAY_LIST = ["%.1f seconds" % (x / 10) for x in range(5, 31, 5)]
+ZA758_DTMF_CHARS = "0123456789ABCD"
+# Flags byte for a new channel: busy lock, scramble, compander and PTT ID
+# off; narrow, low power. Scan add is then set from the memory, so a new
+# scanned channel matches the factory channels (0xE7).
+ZA758_NEW_FLAGS = 0xF7
+
+
+@directory.register
+class ZartekZA758Radio(H777Radio):
+ """Zartek ZA-758"""
+ VENDOR = "Zartek"
+ MODEL = "ZA-758"
+ PROGRAM_CMD = b"LROGRAM"
+ IDENT = [b"SMP558\x00\x00"]
+ ALIASES = []
+
+ # Low is the 500 mW licence-free limit the radio ships with.
+ # TODO: High has not been measured; 2 W is the rating of the ZA-748.
+ POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
+ chirp_common.PowerLevel("High", watts=2.00)]
+ VALID_BANDS = (400000000, 470000000)
+
+ # Do not upload the unmapped 0x0110-0x039F and 0x03F0-0x03FF or the
+ # model fingerprint at 0x03D0
+ _ranges = [
+ (0x0000, 0x0110),
+ (0x03A0, 0x03D0),
+ (0x03E0, 0x03F0),
+ ]
+ _memsize = 0x0400
+ _has_scramble = False
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ # This model is only ever matched via metadata
+ return False
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(ZA758_MEM_FORMAT, self._mmap)
+
+ def _pre_download(self):
+ # Before reading, the factory software requests the 6-byte read
+ # password and acknowledges it. The password is only checked by
+ # the software, so it is not compared here.
+ try:
+ self.pipe.write(b"\x05")
+ password = self.pipe.read(6)
+ if len(password) != 6:
+ raise errors.RadioError(
+ "Radio did not send its password block")
+ self.pipe.write(CMD_ACK)
+ ack = self.pipe.read(1)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.warning('Failed to read password block: %s', e)
+ raise errors.RadioError("Error communicating with radio")
+ if ack != CMD_ACK:
+ raise errors.RadioError("No ACK after reading password block")
+
+ def _clear_unknown_bits(self, _mem):
+ # Bits the BF-888 clears hold scramble, compander and PTT ID here
+ pass
+
+ def get_memory(self, number):
+ mem = super().get_memory(number)
+ if mem.empty:
+ return mem
+
+ _mem = self._memobj.memory[number - 1]
+ rs = RadioSetting("scramble", "Scramble",
+ RadioSettingValueBoolean(not _mem.scramble))
+ rs.set_doc('Inverts the audio so only radios with scramble enabled '
+ 'on the same channel can understand it.')
+ mem.extra.append(rs)
+ rs = RadioSetting("compander", "Compander",
+ RadioSettingValueBoolean(not _mem.compander))
+ rs.set_doc('Compresses audio on transmit and expands it on receive '
+ 'to reduce noise. Radios on the channel should match.')
+ mem.extra.append(rs)
+ rs = RadioSetting("pttid", "PTT ID",
+ RadioSettingValueBoolean(not _mem.pttid))
+ rs.set_doc('Sends the PTT ID DTMF codes on this channel, at the '
+ 'times chosen by the PTT ID setting.')
+ mem.extra.append(rs)
+ return mem
+
+ def set_memory(self, mem):
+ _mem = self._memobj.memory[mem.number - 1]
+ if (not mem.empty and
+ _mem.rxfreq.get_raw() in (b"\xFF" * 4, b"\x00" * 4)):
+ # A blank channel's flags are not usable defaults; erased ones
+ # are all set, which means high power
+ _mem.set_raw(b"\xFF" * 12 + bytes([ZA758_NEW_FLAGS]) +
+ b"\xFF" * 3)
+ super().set_memory(mem)
+
+ def _get_dtmf_code(self, code):
+ # Digits are stored one per byte; the first non-digit ends the code
+ digits = ""
+ for value in code:
+ if int(value) >= len(ZA758_DTMF_CHARS):
+ break
+ digits += ZA758_DTMF_CHARS[int(value)]
+ return digits
+
+ def get_settings(self):
+ _settings = self._memobj.settings
+ basic = RadioSettingGroup("basic", "Basic Settings")
+ keys = RadioSettingGroup("keys", "Side Keys")
+ dtmf = RadioSettingGroup("dtmf", "PTT ID")
+ top = RadioSettings(basic, keys, dtmf)
+
+ rs = RadioSetting("squelch", "Squelch level",
+ RadioSettingValueInteger(
+ 0, 9, int(_settings.squelch)))
+ rs.set_doc('Signal strength needed to open the speaker. Higher '
+ 'levels block weak signals and noise; 0 leaves the '
+ 'squelch open.')
+ basic.append(rs)
+
+ rs = RadioSetting("tot", "Time-out timer",
+ RadioSettingValueList(
+ TIMEOUTTIMER_LIST,
+ current_index=int(_settings.tot)))
+ rs.set_doc('Limits how long one transmission can last. When the '
+ 'time runs out the radio stops transmitting until PTT '
+ 'is released.')
+ basic.append(rs)
+
+ rs = RadioSetting("vox", "VOX level",
+ RadioSettingValueList(
+ ZA758_VOX_LIST,
+ current_index=int(_settings.vox)))
+ rs.set_doc('Voice-operated transmit. 9 is the most sensitive and '
+ '1 needs the loudest voice to start transmitting.')
+ basic.append(rs)
+
+ rs = RadioSetting("voxdelay", "VOX delay",
+ RadioSettingValueList(
+ ZA758_VOXDELAY_LIST,
+ current_index=int(_settings.voxdelay)))
+ rs.set_doc('How long the radio keeps transmitting after you stop '
+ 'speaking in VOX mode.')
+ basic.append(rs)
+
+ rs = RadioSetting("voice", "Voice announcement",
+ RadioSettingValueList(
+ ZA758_VOICE_LIST,
+ current_index=int(_settings.voice)))
+ rs.set_doc('Announces the channel number and battery level out '
+ 'loud in the chosen language.')
+ basic.append(rs)
+
+ rs = RadioSetting("beep", "Beep tone",
+ RadioSettingValueBoolean(_settings.beep))
+ rs.set_doc('Sounds a beep when keys are pressed.')
+ basic.append(rs)
+
+ rs = RadioSetting("batterysaver", "Battery saver",
+ RadioSettingValueBoolean(_settings.batterysaver))
+ rs.set_doc('Periodically turns the receiver off while the channel '
+ 'is quiet to extend battery life.')
+ basic.append(rs)
+
+ rs = RadioSetting("scanmode", "Scan mode",
+ RadioSettingValueList(
+ self.SCANMODE_LIST,
+ current_index=_settings.scanmode))
+ rs.set_doc('Carrier resumes scanning when the signal stops; Time '
+ 'resumes after a few seconds even if it continues.')
+ basic.append(rs)
+
+ rs = RadioSetting("priority", "Priority channel",
+ RadioSettingValueMap(
+ [("Off", 0xFF)] +
+ [("%i" % (x + 1), x) for x in range(16)],
+ int(_settings.priority)))
+ rs.set_doc('Channel that is checked more often while scanning.')
+ basic.append(rs)
+
+ short_keys = [(name, i) for i, name in enumerate(ZA758_SIDEKEY_LIST)
+ if i not in ZA758_SHORTPRESS_EXCLUDE]
+ long_keys = [(name, i) for i, name in enumerate(ZA758_SIDEKEY_LIST)]
+ for name, label, options in (
+ ("sk1short", "Side key 1 (short press)", short_keys),
+ ("sk1long", "Side key 1 (long press)", long_keys),
+ ("sk2short", "Side key 2 (short press)", short_keys),
+ ("sk2long", "Side key 2 (long press)", long_keys)):
+ rs = RadioSetting(name, label,
+ RadioSettingValueMap(
+ options, int(getattr(_settings, name))))
+ rs.set_doc('Function of the side key.')
+ keys.append(rs)
+
+ rs = RadioSetting("pttid", "PTT ID",
+ RadioSettingValueList(
+ ZA758_PTTID_LIST,
+ current_index=_settings.pttid))
+ rs.set_doc('When to send the DTMF ID codes on channels that have '
+ 'PTT ID enabled.')
+ dtmf.append(rs)
+
+ def apply_code(setting, obj, name):
+ # The code is shown only up to its first non-digit byte, so
+ # leave it alone unless it was edited
+ if not setting.changed():
+ return
+ value = str(setting.value).strip()
+ code = [ZA758_DTMF_CHARS.index(c) for c in value]
+ setattr(obj, name, code + [0xFF] * (15 - len(code)))
+
+ for name, label in (("bot_code", "Begin of TX code"),
+ ("eot_code", "End of TX code")):
+ rs = RadioSetting(name, label,
+ RadioSettingValueString(
+ 0, 15,
+ self._get_dtmf_code(
+ getattr(self._memobj, name)),
+ False, ZA758_DTMF_CHARS))
+ rs.set_doc('DTMF digits (0-9, A-D) sent as this radio\'s ID.')
+ rs.set_apply_callback(apply_code, self._memobj, name)
+ dtmf.append(rs)
+
+ return top
diff --git a/chirp/drivers/ic208.py b/chirp/drivers/ic208.py
index c7b088a..61dda85 100644
--- a/chirp/drivers/ic208.py
+++ b/chirp/drivers/ic208.py
@@ -138,6 +138,11 @@ class IC208Radio(icf.IcomCloneModeRadio):
_ranges = [(0x0000, 0x2600, 32)]
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
def get_features(self):
rf = chirp_common.RadioFeatures()
rf.memory_bounds = (1, 500)
diff --git a/chirp/drivers/ic2100.py b/chirp/drivers/ic2100.py
index 40297b4..adf3a48 100644
--- a/chirp/drivers/ic2100.py
+++ b/chirp/drivers/ic2100.py
@@ -173,6 +173,11 @@ class IC2100Radio(icf.IcomCloneModeRadio):
_ranges = [(0x0000, 0x07E0, 32)]
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
def get_features(self):
rf = chirp_common.RadioFeatures()
rf.memory_bounds = (1, 100)
diff --git a/chirp/drivers/ic2200.py b/chirp/drivers/ic2200.py
index 07453fb..4668abf 100644
--- a/chirp/drivers/ic2200.py
+++ b/chirp/drivers/ic2200.py
@@ -111,6 +111,11 @@ class IC2200Radio(icf.IcomCloneModeRadio, chirp_common.IcomDstarSupport):
_endframe = "Icom Inc\x2eD8"
_can_hispeed = True
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
_memories = []
_ranges = [(0x0000, 0x1340, 32),
diff --git a/chirp/drivers/ic2300.py b/chirp/drivers/ic2300.py
index bd3a93e..bd52904 100644
--- a/chirp/drivers/ic2300.py
+++ b/chirp/drivers/ic2300.py
@@ -128,6 +128,11 @@ class IC2300Radio(icf.IcomCloneModeRadio):
_can_hispeed = True
_ranges = [(0x0000, 0x18a0, 32)] # upload entire memory for now
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
def get_features(self):
rf = chirp_common.RadioFeatures()
rf.memory_bounds = (0, 199)
diff --git a/chirp/drivers/ic2720.py b/chirp/drivers/ic2720.py
index 5e147d9..e7a1d22 100644
--- a/chirp/drivers/ic2720.py
+++ b/chirp/drivers/ic2720.py
@@ -77,6 +77,11 @@ class IC2720Radio(icf.IcomCloneModeRadio):
_ranges = [(0x0000, 0x1400, 32)]
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
def _get_bank(self, loc):
_bank = self._memobj.banks[loc / 2]
if loc % 2:
diff --git a/chirp/drivers/ic2730.py b/chirp/drivers/ic2730.py
index d901464..5735a0c 100644
--- a/chirp/drivers/ic2730.py
+++ b/chirp/drivers/ic2730.py
@@ -287,6 +287,11 @@ class IC2730Radio(icf.IcomCloneModeRadio):
_raw_frames = True
_highbit_flip = True
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
_icf_data: dict[str, typing.Any] = {
'MapRev': 1,
'EtcData': 0, # This might be wrong
diff --git a/chirp/drivers/ic2820.py b/chirp/drivers/ic2820.py
index c3cd23d..e9da424 100644
--- a/chirp/drivers/ic2820.py
+++ b/chirp/drivers/ic2820.py
@@ -141,6 +141,11 @@ class IC2820Radio(icf.IcomCloneModeRadio, chirp_common.IcomDstarSupport):
_bank_class = IC2820Bank
_can_hispeed = True
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
MYCALL_LIMIT = (1, 7)
URCALL_LIMIT = (1, 61)
RPTCALL_LIMIT = (1, 61)
diff --git a/chirp/drivers/icp7.py b/chirp/drivers/icp7.py
index 2874191..170b136 100644
--- a/chirp/drivers/icp7.py
+++ b/chirp/drivers/icp7.py
@@ -15,6 +15,7 @@
from chirp.drivers import icf
from chirp import chirp_common, directory, bitwise
+from chirp import errors
# memory number:
# 000 - 999 regular memory channels (supported, others not)
@@ -100,6 +101,11 @@ class ICP7Radio(icf.IcomCloneModeRadio):
_bank_class = ICP7Bank
_can_hispeed = True
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
def _get_bank(self, loc):
_bank = self._memobj.banks[loc]
if _bank.bank != 0xff:
@@ -166,6 +172,8 @@ class ICP7Radio(icf.IcomCloneModeRadio):
mem.tmode = TMODES[_mem.tmode]
mem.duplex = DUPLEX[_mem.duplex]
mem.tuning_step = TUNING_STEPS[_mem.tuning_step]
+ if mem.tuning_step == 0:
+ mem.tuning_step = self._valid_tuning_step(mem)
mem.rtone = chirp_common.TONES[_mem.rtone]
mem.ctone = chirp_common.TONES[_mem.ctone]
mem.mode = MODES[_mem.mode]
@@ -180,6 +188,13 @@ class ICP7Radio(icf.IcomCloneModeRadio):
return mem
+ def _valid_tuning_step(self, mem):
+ try:
+ return chirp_common.required_step(
+ mem.freq, self.get_features().valid_tuning_steps)
+ except errors.InvalidDataError:
+ return self.get_features().valid_tuning_steps[0]
+
def set_memory(self, mem):
bit = 1 << (mem.number % 8)
byte = int(mem.number / 8)
@@ -222,7 +237,10 @@ class ICP7Radio(icf.IcomCloneModeRadio):
_mem.tmode = TMODES.index(mem.tmode)
_mem.duplex = DUPLEX.index(mem.duplex)
_mem.train_tone = 228 # Train SQL Tone (x10 Hz)
- _mem.tuning_step = TUNING_STEPS.index(mem.tuning_step)
+ tuning_step = mem.tuning_step
+ if tuning_step == 0:
+ tuning_step = self._valid_tuning_step(mem)
+ _mem.tuning_step = TUNING_STEPS.index(tuning_step)
_mem.rtone = chirp_common.TONES.index(mem.rtone)
_mem.ctone = chirp_common.TONES.index(mem.ctone)
_mem.unknown0 = 0 # unknown (always zero)
diff --git a/chirp/drivers/icq7.py b/chirp/drivers/icq7.py
index a5fdce3..0a53250 100644
--- a/chirp/drivers/icq7.py
+++ b/chirp/drivers/icq7.py
@@ -107,6 +107,11 @@ class ICQ7Radio(icf.IcomCloneModeRadio):
_ranges = [(0x0000, 0x07C0, 16)]
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
def get_features(self):
rf = chirp_common.RadioFeatures()
rf.has_settings = True
diff --git a/chirp/drivers/ict70.py b/chirp/drivers/ict70.py
index f05eb21..44a7409 100644
--- a/chirp/drivers/ict70.py
+++ b/chirp/drivers/ict70.py
@@ -93,6 +93,11 @@ class ICT70Radio(icf.IcomCloneModeRadio):
_ranges = [(0x0000, 0x19E0, 32)]
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
_num_banks = 26
_bank_class = ICT70Bank
diff --git a/chirp/drivers/ict7h.py b/chirp/drivers/ict7h.py
index 9a28646..30346dd 100644
--- a/chirp/drivers/ict7h.py
+++ b/chirp/drivers/ict7h.py
@@ -55,6 +55,11 @@ class ICT7HRadio(icf.IcomCloneModeRadio):
_ranges = [(0x0000, _memsize, 16)]
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
def get_features(self):
rf = chirp_common.RadioFeatures()
rf.memory_bounds = (1, 60)
diff --git a/chirp/drivers/ict8.py b/chirp/drivers/ict8.py
index cc6dbbb..6331ca3 100644
--- a/chirp/drivers/ict8.py
+++ b/chirp/drivers/ict8.py
@@ -70,6 +70,11 @@ class ICT8ARadio(icf.IcomCloneModeRadio):
_ranges = [(0x0000, 0x07B0, 16)]
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
def get_features(self):
rf = chirp_common.RadioFeatures()
rf.valid_tmodes = TMODES
diff --git a/chirp/drivers/icx8x.py b/chirp/drivers/icx8x.py
index 04f07fd..a7a5c9b 100644
--- a/chirp/drivers/icx8x.py
+++ b/chirp/drivers/icx8x.py
@@ -95,6 +95,11 @@ class ICx8xRadio(icf.IcomCloneModeRadio, chirp_common.IcomDstarSupport):
_can_hispeed = False
_double_ident = True
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
_memories = []
_ranges = [(0x0000, 0x1340, 32),
diff --git a/chirp/drivers/id31.py b/chirp/drivers/id31.py
index 1a36045..f3cd9e0 100644
--- a/chirp/drivers/id31.py
+++ b/chirp/drivers/id31.py
@@ -177,6 +177,11 @@ class ID31Radio(icf.IcomCloneModeRadio, chirp_common.IcomDstarSupport):
_ranges = [(0x00000, 0x15500, 32)]
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
MODES = {0: "FM", 1: "NFM", 5: "DV"}
def _get_bank(self, loc):
diff --git a/chirp/drivers/id800.py b/chirp/drivers/id800.py
index c2c5700..e946a48 100644
--- a/chirp/drivers/id800.py
+++ b/chirp/drivers/id800.py
@@ -165,6 +165,11 @@ class ID800v2Radio(icf.IcomCloneModeRadio, chirp_common.IcomDstarSupport):
_memories = []
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (super().match_model(filedata, filename) or
+ (cls._memsize and len(filedata) == cls._memsize))
+
_ranges = [(0x0020, 0x2B18, 32),
(0x2B18, 0x2B20, 8),
(0x2B20, 0x2BE0, 32),
diff --git a/chirp/drivers/kenwood_itm.py b/chirp/drivers/kenwood_itm.py
index 5544f49..1a7fcec 100644
--- a/chirp/drivers/kenwood_itm.py
+++ b/chirp/drivers/kenwood_itm.py
@@ -18,6 +18,7 @@ import csv
import logging
from chirp import chirp_common, errors, directory
+from chirp import kenwood_tone
from chirp.drivers import generic_csv
LOG = logging.getLogger(__name__)
@@ -63,17 +64,12 @@ class ITMRadio(generic_csv.CSVRadio):
return mem
def _clean_tmode(self, headers, line, mem):
- rtone = eval(generic_csv.get_datum_by_header(headers, line, "TXSIG"))
- ctone = eval(generic_csv.get_datum_by_header(headers, line, "RXSIG"))
-
- if rtone:
- mem.tmode = "Tone"
- if ctone:
- mem.tmode = "TSQL"
-
- mem.rtone = rtone or 88.5
- mem.ctone = ctone or mem.rtone
+ txtone = kenwood_tone.parse_qtdqt(
+ generic_csv.get_datum_by_header(headers, line, "TXSIG"))
+ rxtone = kenwood_tone.parse_qtdqt(
+ generic_csv.get_datum_by_header(headers, line, "RXSIG"))
+ chirp_common.split_tone_decode(mem, txtone, rxtone)
return mem
def load(self, filename=None):
diff --git a/chirp/drivers/kenwood_live.py b/chirp/drivers/kenwood_live.py
index 772253b..7bb0de8 100644
--- a/chirp/drivers/kenwood_live.py
+++ b/chirp/drivers/kenwood_live.py
@@ -410,6 +410,8 @@ class TMV7Radio(KenwoodOldLiveRadio):
rf.valid_tuning_steps = STEPS
rf.has_sub_devices = True
rf.memory_bounds = (1, self._upper)
+ rf.valid_bands = [(144000000, 148000000),
+ (420000000, 450000000)]
return rf
def _make_mem_spec(self, mem):
@@ -502,7 +504,7 @@ class TMG707Radio(TMV7Radio):
MODEL = "TM-G707"
def get_features(self):
- rf = TMV7Radio.get_features(self)
+ rf = super().get_features()
rf.has_sub_devices = False
rf.memory_bounds = (1, 180)
rf.valid_bands = [(118000000, 174000000),
@@ -511,59 +513,453 @@ class TMG707Radio(TMV7Radio):
return rf
-THG71_STEPS = [5, 6.25, 10, 12.5, 15, 20, 25, 30, 50, 100]
+THG71_STEPS = [5.0, 6.25, 10.0, 12.5, 15.0, 20.0, 25.0, 30.0, 50.0, 100.0]
+THG71_TONES = tuple(x for x in chirp_common.OLD_TONES if x != 69.3)
+THG71_SPECIALS = ["CALL-V", "CALL-U", "Pr"] + \
+ ["L%i" % i for i in range(10)] + \
+ ["U%i" % i for i in range(10)]
+THG71_POWER_LEVELS = ["High", "Low", "Economic Low"]
+THG71_POWER_MAP = {0: "High", 2: "Low", 3: "Economic Low"}
+THG71_POWER_MAP_REV = {"High": 0, "Low": 2, "Economic Low": 3}
+
+
+def _thg71_code_to_tone(code_str):
+ if not code_str or not code_str.isdigit():
+ return 88.5
+ idx = int(code_str) - 1
+ if 0 <= idx < len(chirp_common.OLD_TONES):
+ t = chirp_common.OLD_TONES[idx]
+ if t != 69.3:
+ return t
+ return 88.5
+
+
+def _thg71_tone_to_code(tone):
+ if tone not in chirp_common.OLD_TONES or tone == 69.3:
+ tone = 88.5
+ idx = chirp_common.OLD_TONES.index(tone)
+ return "%02i" % (idx + 1)
@directory.register
-class THG71Radio(TMV7Radio):
+class THG71Radio(KenwoodOldLiveRadio):
"""Kenwood TH-G71"""
MODEL = "TH-G71"
+ HARDWARE_FLOW = False
+
+ _upper = 199
+ _kenwood_split = True
+ _kenwood_valid_tones = list(chirp_common.OLD_TONES)
def get_features(self):
- rf = TMV7Radio.get_features(self)
+ rf = chirp_common.RadioFeatures()
rf.has_tuning_step = True
+ rf.has_bank = False
+ rf.has_dtcs = False
+ rf.has_dtcs_polarity = False
+ rf.has_mode = False
+ rf.has_ctone = True
+ rf.has_settings = True
+ rf.has_sub_devices = False
+ rf.can_odd_split = True
+ rf.valid_modes = ["FM"]
+ rf.valid_tmodes = ["", "Tone", "TSQL"]
+ rf.valid_duplexes = ["", "+", "-", "split"]
+ rf.valid_skips = ["", "S"]
rf.valid_tuning_steps = list(THG71_STEPS)
+ rf.valid_tones = THG71_TONES
rf.valid_name_length = 6
- rf.has_sub_devices = False
+ rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + "-/ "
+ rf.memory_bounds = (0, 199)
+ rf.valid_special_chans = list(THG71_SPECIALS)
rf.valid_bands = [(118000000, 174000000),
(320000000, 470000000),
- (800000000, 945000000)]
+ (800000000, 949000000)]
return rf
- def _make_mem_spec(self, mem):
- spec = (
- "%011i" % mem.freq,
- "%X" % THG71_STEPS.index(mem.tuning_step),
- "%i" % util.get_dict_rev(DUPLEX, mem.duplex),
- "0",
- "%i" % (mem.tmode == "Tone"),
- "%i" % (mem.tmode == "TSQL"),
- "0",
- "%02i" % (self._kenwood_valid_tones.index(mem.rtone) + 1),
- "000",
- "%02i" % (self._kenwood_valid_tones.index(mem.ctone) + 1),
- "%09i" % mem.offset,
- "%i" % ((mem.skip == "S") and 1 or 0))
- return spec
+ def _cmd_get_memory(self, number):
+ chan = ("%03i" % number) if isinstance(number, int) else str(number)
+ return "MR", "0,0,%s" % chan
+
+ def _cmd_get_memory_name(self, number):
+ chan = ("%03i" % number) if isinstance(number, int) else str(number)
+ return "MNA", "0,%s" % chan
+
+ def _cmd_get_split(self, number):
+ chan = ("%03i" % number) if isinstance(number, int) else str(number)
+ return "MR", "0,1,%s" % chan
+
+ def _cmd_set_memory(self, number, spec):
+ chan = ("%03i" % number) if isinstance(number, int) else str(number)
+ if spec:
+ return "MW", "0,0,%s,%s" % (chan, spec)
+ return "MW", "0,0,%s" % chan
+
+ def _cmd_set_memory_name(self, number, name):
+ chan = ("%03i" % number) if isinstance(number, int) else str(number)
+ return "MNA", "0,%s,%s" % (chan, name)
+
+ def _cmd_set_split(self, number, spec):
+ chan = ("%03i" % number) if isinstance(number, int) else str(number)
+ return "MW", "0,1,%s,%s" % (chan, spec)
def _parse_mem_spec(self, spec):
mem = chirp_common.Memory()
- mem.number = int(spec[2])
+ chan_str = spec[2]
+ if chan_str.isdigit():
+ mem.number = int(chan_str)
+ else:
+ mem.number = 0
+ mem.extd_number = chan_str
mem.freq = int(spec[3])
- mem.tuning_step = THG71_STEPS[int(spec[4], 16)]
- mem.duplex = DUPLEX[int(spec[5])]
- if int(spec[7]):
+ step_idx = int(spec[4], 16) if spec[4] else 0
+ if 0 <= step_idx < len(THG71_STEPS):
+ mem.tuning_step = THG71_STEPS[step_idx]
+ else:
+ mem.tuning_step = THG71_STEPS[0]
+ shift_idx = int(spec[5]) if spec[5] else 0
+ mem.duplex = DUPLEX.get(shift_idx, "")
+ if len(spec) > 7 and int(spec[7]):
mem.tmode = "Tone"
- elif int(spec[8]):
+ elif len(spec) > 8 and int(spec[8]):
mem.tmode = "TSQL"
- mem.rtone = self._kenwood_valid_tones[int(spec[10]) - 1]
- mem.ctone = self._kenwood_valid_tones[int(spec[12]) - 1]
- if spec[13]:
+ else:
+ mem.tmode = ""
+ mem.rtone = _thg71_code_to_tone(spec[10]) if len(spec) > 10 else 88.5
+ mem.ctone = _thg71_code_to_tone(spec[12]) if len(spec) > 12 else 88.5
+ if len(spec) > 13 and spec[13] and spec[13].isdigit():
mem.offset = int(spec[13])
else:
mem.offset = 0
+ if len(spec) > 14 and spec[14] == "1":
+ mem.skip = "S"
+ else:
+ mem.skip = ""
return mem
+ def _parse_call_spec(self, band, spec):
+ mem = chirp_common.Memory()
+ mem.number = 0
+ mem.extd_number = "CALL-V" if band == 0 else "CALL-U"
+ mem.freq = int(spec[2])
+ step_idx = int(spec[3], 16) if spec[3] else 0
+ if 0 <= step_idx < len(THG71_STEPS):
+ mem.tuning_step = THG71_STEPS[step_idx]
+ else:
+ mem.tuning_step = THG71_STEPS[0]
+ shift_idx = int(spec[4]) if spec[4] else 0
+ mem.duplex = DUPLEX.get(shift_idx, "")
+ if len(spec) > 6 and int(spec[6]):
+ mem.tmode = "Tone"
+ elif len(spec) > 7 and int(spec[7]):
+ mem.tmode = "TSQL"
+ else:
+ mem.tmode = ""
+ mem.rtone = _thg71_code_to_tone(spec[9]) if len(spec) > 9 else 88.5
+ mem.ctone = _thg71_code_to_tone(spec[11]) if len(spec) > 11 else 88.5
+ if len(spec) > 12 and spec[12] and spec[12].isdigit():
+ mem.offset = int(spec[12])
+ else:
+ mem.offset = 0
+ mem.skip = ""
+ return mem
+
+ def _make_mem_spec(self, mem, is_call=False):
+ if mem.tuning_step in THG71_STEPS:
+ step_idx = THG71_STEPS.index(mem.tuning_step)
+ else:
+ step_idx = 0
+ if mem.duplex in ["", "+", "-"]:
+ duplex_code = util.get_dict_rev(DUPLEX, mem.duplex)
+ offset = mem.offset
+ elif mem.duplex == "split":
+ duplex_code = 0
+ offset = 0
+ else:
+ duplex_code = 0
+ offset = 0
+
+ spec = [
+ "%011i" % mem.freq,
+ "%X" % step_idx,
+ "%i" % duplex_code,
+ "0",
+ "%i" % (mem.tmode == "Tone"),
+ "%i" % (mem.tmode == "TSQL"),
+ "",
+ _thg71_tone_to_code(mem.rtone),
+ "",
+ _thg71_tone_to_code(mem.ctone),
+ "%09i" % offset,
+ ]
+ if not is_call:
+ spec.append("%i" % (1 if mem.skip == "S" else 0))
+ return tuple(spec)
+
+ def _parse_split_spec(self, mem, spec):
+ mem.duplex = "split"
+ mem.offset = int(spec[3])
+
+ def _make_split_spec(self, mem):
+ if mem.tuning_step in THG71_STEPS:
+ step_idx = THG71_STEPS.index(mem.tuning_step)
+ else:
+ step_idx = 0
+ return ("%011i" % mem.offset, "%X" % step_idx)
+
+ def get_memory(self, number):
+ if isinstance(number, str):
+ if number not in THG71_SPECIALS:
+ raise errors.InvalidMemoryLocation(
+ "Special channel %s is not valid" % number)
+ mem_key = number
+ else:
+ if number < 0 or number > self._upper:
+ raise errors.InvalidMemoryLocation(
+ "Number must be between 0 and %i" % self._upper)
+ mem_key = number
+
+ if mem_key in self._memcache and not NOCACHE:
+ return self._memcache[mem_key]
+
+ is_call = False
+ call_band = 0
+ if mem_key == "CALL-V":
+ cmd = ("CR", "0,0")
+ is_call = True
+ call_band = 0
+ elif mem_key == "CALL-U":
+ cmd = ("CR", "1,0")
+ is_call = True
+ call_band = 1
+ else:
+ cmd = self._cmd_get_memory(mem_key)
+
+ result = self.command(self.pipe, *cmd)
+ if result in ["N", "E"] or result == "?" or not result:
+ mem = chirp_common.Memory()
+ if isinstance(mem_key, int):
+ mem.number = mem_key
+ else:
+ mem.number = 0
+ mem.extd_number = mem_key
+ mem.empty = True
+ self._memcache[mem_key] = mem
+ return mem
+ elif " " not in result:
+ LOG.error("Not sure what to do with this: %r" % result)
+ raise errors.RadioError("Unexpected result returned from radio")
+
+ value = result.split(" ", 1)[1]
+ spec = value.split(",")
+
+ if is_call:
+ mem = self._parse_call_spec(call_band, spec)
+ else:
+ mem = self._parse_mem_spec(spec)
+
+ self._memcache[mem_key] = mem
+
+ if not is_call and self._has_name:
+ result = self.command(self.pipe,
+ *self._cmd_get_memory_name(mem_key))
+ if " " in result:
+ value = result.split(" ", 1)[1]
+ parts = value.split(",")
+ if len(parts) >= 3:
+ mem.name = parts[2].rstrip()
+ elif len(parts) == 2:
+ mem.name = parts[1].rstrip()
+
+ if mem.duplex == "" and mem.offset == 0:
+ if is_call:
+ split_cmd = ("CR", "%i,1" % call_band)
+ result = self.command(self.pipe, *split_cmd)
+ if not iserr(result) and " " in result:
+ value = result.split(" ", 1)[1]
+ parts = value.split(",")
+ if len(parts) >= 3:
+ mem.duplex = "split"
+ mem.offset = int(parts[2])
+ else:
+ result = self.command(self.pipe,
+ *self._cmd_get_split(mem_key))
+ if not iserr(result) and " " in result:
+ value = result.split(" ", 1)[1]
+ self._parse_split_spec(mem, value.split(","))
+
+ return mem
+
+ def set_memory(self, memory):
+ mem_key = memory.extd_number if memory.extd_number else memory.number
+ if isinstance(mem_key, str):
+ if mem_key not in THG71_SPECIALS:
+ raise errors.InvalidMemoryLocation(
+ "Special channel %s is not valid" % mem_key)
+ else:
+ if mem_key < 0 or mem_key > self._upper:
+ raise errors.InvalidMemoryLocation(
+ "Number must be between 0 and %i" % self._upper)
+
+ if memory.tmode == "Tone" and memory.rtone not in THG71_TONES:
+ raise errors.UnsupportedToneError("This radio does not support "
+ "tone %.1fHz" % memory.rtone)
+ if memory.tmode == "TSQL" and memory.ctone not in THG71_TONES:
+ raise errors.UnsupportedToneError("This radio does not support "
+ "tone %.1fHz" % memory.ctone)
+
+ if memory.empty:
+ self.erase_memory(mem_key)
+ return
+
+ is_call = False
+ call_band = 0
+ if mem_key == "CALL-V":
+ is_call = True
+ call_band = 0
+ elif mem_key == "CALL-U":
+ is_call = True
+ call_band = 1
+
+ spec = self._make_mem_spec(memory, is_call=is_call)
+ spec_str = ",".join(spec)
+ self._memcache.pop(mem_key, None)
+
+ if is_call:
+ r1 = self.command(self.pipe, "CW",
+ "%i,0,%s" % (call_band, spec_str))
+ else:
+ r1 = self.command(self.pipe,
+ *self._cmd_set_memory(mem_key, spec_str))
+
+ if iserr(r1):
+ raise errors.InvalidDataError("Radio refused channel %s" % mem_key)
+
+ if not is_call and self._has_name:
+ time.sleep(0.05)
+ clean_name = memory.name.upper()[:6]
+ r2 = self.command(self.pipe,
+ *self._cmd_set_memory_name(mem_key, clean_name))
+ if iserr(r2):
+ raise errors.InvalidDataError("Radio refused name %s: %r" %
+ (mem_key, clean_name))
+
+ if memory.duplex == "split":
+ time.sleep(0.05)
+ if is_call:
+ if memory.tuning_step in THG71_STEPS:
+ step_idx = THG71_STEPS.index(memory.tuning_step)
+ else:
+ step_idx = 0
+ split_spec = "%011i,%X" % (memory.offset, step_idx)
+ result = self.command(self.pipe, "CW",
+ "%i,1,%s" % (call_band, split_spec))
+ else:
+ split_spec = ",".join(self._make_split_spec(memory))
+ result = self.command(self.pipe,
+ *self._cmd_set_split(mem_key,
+ split_spec))
+ if iserr(result):
+ raise errors.InvalidDataError("Radio refused split on %s" %
+ mem_key)
+
+ def erase_memory(self, number):
+ if number in ["CALL-V", "CALL-U"]:
+ return
+ resp = self.command(self.pipe, *self._cmd_set_memory(number, ""))
+ if iserr(resp):
+ raise errors.RadioError("Radio refused delete of %s" % number)
+ self._memcache.pop(number, None)
+
+ def get_settings(self):
+ basic = RadioSettingGroup("basic", "Basic Settings")
+ dtmf = RadioSettingGroup("dtmf", "DTMF Memories")
+ top = RadioSettings(basic, dtmf)
+
+ # VHF Transmit Power
+ curr = "High"
+ try:
+ resp = self.command(self.pipe, "PC", "0")
+ if not iserr(resp) and " " in resp:
+ val = int(resp.split(" ")[1].split(",")[1])
+ curr = THG71_POWER_MAP.get(val, "High")
+ except Exception:
+ pass
+ rs = RadioSetting("pc_vhf", "VHF Transmit Power",
+ RadioSettingValueList(
+ THG71_POWER_LEVELS,
+ current_index=THG71_POWER_LEVELS.index(curr)))
+ basic.append(rs)
+
+ # UHF Transmit Power
+ curr = "High"
+ try:
+ resp = self.command(self.pipe, "PC", "1")
+ if not iserr(resp) and " " in resp:
+ val = int(resp.split(" ")[1].split(",")[1])
+ curr = THG71_POWER_MAP.get(val, "High")
+ except Exception:
+ pass
+ rs = RadioSetting("pc_uhf", "UHF Transmit Power",
+ RadioSettingValueList(
+ THG71_POWER_LEVELS,
+ current_index=THG71_POWER_LEVELS.index(curr)))
+ basic.append(rs)
+
+ # Squelch Level (0-5)
+ val = 2
+ try:
+ resp = self.command(self.pipe, "SQ", "0")
+ if not iserr(resp) and " " in resp:
+ val = int(resp.split(" ")[1].split(",")[1])
+ except Exception:
+ pass
+ rs = RadioSetting("squelch", "Squelch Level",
+ RadioSettingValueInteger(0, 5, val))
+ basic.append(rs)
+
+ # DTMF Memories (DM 00 to DM 09)
+ dtmf_charset = "0123456789ABCD*#"
+ for i in range(10):
+ dtmf_val = ""
+ try:
+ resp = self.command(self.pipe, "DM", "%02i" % i)
+ if not iserr(resp) and " " in resp:
+ parts = resp.split(" ", 1)[1].split(",")
+ if len(parts) > 1:
+ dtmf_val = parts[1].replace("E", "*").replace("F", "#")
+ except Exception:
+ pass
+ rs = RadioSetting("dm_%02i" % i, "DTMF Memory %i" % i,
+ RadioSettingValueString(0, 16, dtmf_val,
+ autopad=False,
+ charset=dtmf_charset))
+ dtmf.append(rs)
+
+ return top
+
+ def set_settings(self, settings):
+ for element in settings:
+ if not isinstance(element, RadioSetting):
+ self.set_settings(element)
+ continue
+ if not element.changed():
+ continue
+ name = element.get_name()
+ if name == "pc_vhf":
+ code = THG71_POWER_MAP_REV.get(str(element.value), 0)
+ self.command(self.pipe, "PC", "0,%i" % code)
+ elif name == "pc_uhf":
+ code = THG71_POWER_MAP_REV.get(str(element.value), 0)
+ self.command(self.pipe, "PC", "1,%i" % code)
+ elif name == "squelch":
+ self.command(self.pipe, "SQ", "0,%02i" % int(element.value))
+ elif name.startswith("dm_"):
+ idx = int(name.split("_")[1])
+ raw = str(element.value).upper().replace("*", "E")
+ raw = raw.replace("#", "F")
+ self.command(self.pipe, "DM", "%02i,%s" % (idx, raw))
+
THF6A_STEPS = [5.0, 6.25, 8.33, 9.0, 10.0, 12.5, 15.0, 20.0, 25.0, 30.0, 50.0,
100.0]
@@ -1051,9 +1447,59 @@ class THK2Radio(KenwoodLiveRadio):
"""Kenwood TH-K2"""
MODEL = "TH-K2"
HARDWARE_FLOW = False
+ _probe_memory = 99
_kenwood_valid_tones = list(KENWOOD_TONES)
+ def __init__(self, *a, **k):
+ self._has_name = True
+ super().__init__(*a, **k)
+ if self.pipe:
+ self._probe_layout()
+
+ def _probe_layout(self):
+ """Determine if the radio is in 100+alpha or 200 channel mode"""
+ rf = self.get_features()
+ wasempty = None
+ try:
+ LOG.debug('Getting memory %i', self._probe_memory)
+ m = self.get_memory(self._probe_memory)
+ wasempty = m.empty
+ if wasempty:
+ m.freq = rf.valid_bands[0][0]
+ m.empty = False
+ LOG.debug('Memory %i was empty using %s to probe',
+ self._probe_memory, m)
+ else:
+ LOG.debug('Memory %i was set: %s', self._probe_memory, m)
+ # This either sets the probe memory over itself, or creates one
+ # at the lower limit frequency. Note that in order for this to
+ # work, we need _has_name=True here so that we can detect if we
+ # failed to set the memory (because 199 is out of range) or the
+ # memory name (because 199 is in range, but names are not
+ # supported).
+ self.set_memory(m)
+ LOG.error('Unexpectedly successful at setting probe memory %s', m)
+ except errors.InvalidDataError as e:
+ LOG.debug('Probe response was %s', e)
+ if 'name' in str(e):
+ # Radio is configured for max channels, refused the name
+ self._has_name = False
+ LOG.info('Radio determined to be in max-channel mode')
+ else:
+ # Radio is configured for alpha channels, as it refused the
+ # whole thing
+ self._has_name = True
+ LOG.info('Radio determined to be in channel+alpha mode')
+ finally:
+ if wasempty:
+ LOG.debug('Erasing probe memory %s', m)
+ # This needs to do the raw command because of the memory
+ # caching in set_memory()
+ self.command(self.pipe, *self._cmd_set_memory(
+ self._probe_memory, ""))
+ LOG.debug('Done probing layout')
+
def get_features(self):
rf = chirp_common.RadioFeatures()
rf.can_odd_split = False
@@ -1068,7 +1514,7 @@ class THK2Radio(KenwoodLiveRadio):
rf.valid_bands = [(136000000, 173990000)]
rf.valid_skips = ["", "S"]
rf.valid_tuning_steps = [5.0]
- rf.memory_bounds = (0, 49)
+ rf.memory_bounds = (0, 49 if self._has_name else 99)
return rf
def _cmd_get_memory(self, number):
@@ -1139,6 +1585,7 @@ TM271_STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 15.0, 20.0, 25.0, 30.0, 50.0, 100.0]
class TM271Radio(THK2Radio):
"""Kenwood TM-271"""
MODEL = "TM-271"
+ _probe_memory = 199
def get_features(self):
rf = chirp_common.RadioFeatures()
@@ -1146,6 +1593,7 @@ class TM271Radio(THK2Radio):
rf.has_dtcs_polarity = False
rf.has_bank = False
rf.has_tuning_step = False
+ rf.has_name = self._has_name
rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS"]
rf.valid_modes = THK2_MODES
rf.valid_duplexes = THK2_DUPLEX
@@ -1154,7 +1602,7 @@ class TM271Radio(THK2Radio):
rf.valid_bands = [(137000000, 173990000)]
rf.valid_skips = ["", "S"]
rf.valid_tuning_steps = list(TM271_STEPS)
- rf.memory_bounds = (0, 99)
+ rf.memory_bounds = (0, 99 if self._has_name else 199)
return rf
def _cmd_get_memory(self, number):
@@ -1178,25 +1626,13 @@ class TM281Radio(TM271Radio):
@directory.register
-class TM471Radio(THK2Radio):
+class TM471Radio(TM271Radio):
"""Kenwood TM-471"""
MODEL = "TM-471"
def get_features(self):
- rf = chirp_common.RadioFeatures()
- rf.can_odd_split = False
- rf.has_dtcs_polarity = False
- rf.has_bank = False
- rf.has_tuning_step = False
- rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS"]
- rf.valid_modes = THK2_MODES
- rf.valid_duplexes = THK2_DUPLEX
- rf.valid_characters = THK2_CHARS
- rf.valid_name_length = 6
+ rf = super().get_features()
rf.valid_bands = [(444000000, 479990000)]
- rf.valid_skips = ["", "S"]
- rf.valid_tuning_steps = [5.0]
- rf.memory_bounds = (0, 99)
return rf
def _cmd_get_memory(self, number):
diff --git a/chirp/drivers/kg935g.py b/chirp/drivers/kg935g.py
index 20a35ef..b6f20bd 100644
--- a/chirp/drivers/kg935g.py
+++ b/chirp/drivers/kg935g.py
@@ -1625,7 +1625,11 @@ class KG935GRadio(chirp_common.CloneModeRadio,
mem.freq = int(_mem.rxfreq) * 10
- if _mem.txfreq == 0xFFFFFFFF:
+ tx_disabled = (
+ _mem.txfreq == 0xFFFFFFFF or
+ (self.MODEL in ("KG-XS20G", "KG-XS20G Plus", "KG-XS20H") and
+ int(_mem.txfreq) == 0))
+ if tx_disabled:
# TX freq not set
mem.duplex = "off"
mem.offset = 0
diff --git a/chirp/drivers/kguv8e.py b/chirp/drivers/kguv8e.py
index cda0378..e022400 100644
--- a/chirp/drivers/kguv8e.py
+++ b/chirp/drivers/kguv8e.py
@@ -314,6 +314,12 @@ class KGUV8ERadio(chirp_common.CloneModeRadio,
_model = b"KG-UV8D-A"
_file_ident = b"kguv8e" # lowercase
BAUD_RATE = 19200
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ ident = (b'kg' + filedata[0x426:0x430].replace(b'(', b'').replace(
+ b')', b'').lower())
+ return cls._file_ident in ident
POWER_LEVELS = [chirp_common.PowerLevel("L", watts=1),
chirp_common.PowerLevel("H", watts=5)]
_record_start = 0x7B
@@ -381,11 +387,6 @@ class KGUV8ERadio(chirp_common.CloneModeRadio,
# 35:38 VHF tx lower limit
# 39:42 VHF tx upper limit
- @classmethod
- def match_model(cls, filedata, filename):
- id = cls._file_ident
- return cls._file_ident in b'kg' + filedata[0x426:0x430].replace(b'(', b'').replace(b')', b'').lower()
-
def _identify(self):
"""Do the identification dance"""
for _i in range(0, 10):
diff --git a/chirp/drivers/kguv920pa.py b/chirp/drivers/kguv920pa.py
index 4211a6d..42ec8b6 100644
--- a/chirp/drivers/kguv920pa.py
+++ b/chirp/drivers/kguv920pa.py
@@ -433,6 +433,10 @@ class KGUV920PARadio(chirp_common.CloneModeRadio,
_model = "KG-UV920Rr" # what the radio responds to CMD_ID with
_file_ident = b"KGUV920PA"
BAUD_RATE = 19200
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return cls._file_ident in filedata[0x400:0x408]
POWER_LEVELS = [chirp_common.PowerLevel("L", watts=5),
chirp_common.PowerLevel("M", watts=20),
chirp_common.PowerLevel("H", watts=50)]
@@ -455,7 +459,7 @@ class KGUV920PARadio(chirp_common.CloneModeRadio,
# add the chars to the packet
_packet += payload
# calculate and add the checksum to the packet
- _packet += bytes([checksum.checksum_8bit(_packet[1:])])
+ _packet += bytes([checksum.checksum_8bit(_packet[1:], 16)])
LOG.debug("Sent:\n%s" % util.hexprint(_packet))
self.pipe.write(_packet)
@@ -468,8 +472,8 @@ class KGUV920PARadio(chirp_common.CloneModeRadio,
raise errors.RadioError('Radio sent short header')
_length = _header[3]
_packet = self.pipe.read(_length)
- _cs = checksum.checksum_8bit(_header[1:])
- _cs += checksum.checksum_8bit(_packet)
+ _cs = checksum.checksum_8bit(_header[1:], 16)
+ _cs += checksum.checksum_8bit(_packet, 16)
_cs %= 16
try:
_rcs = self.pipe.read(1)[0]
@@ -480,10 +484,6 @@ class KGUV920PARadio(chirp_common.CloneModeRadio,
LOG.error("_rcs=%x", _rcs)
return (_rcs != _cs, _packet)
- @classmethod
- def match_model(cls, filedata, filename):
- return cls._file_ident in filedata[0x400:0x408]
-
def _identify(self):
"""
Offset
diff --git a/chirp/drivers/kguv9dplus.py b/chirp/drivers/kguv9dplus.py
index 630dff8..0945388 100644
--- a/chirp/drivers/kguv9dplus.py
+++ b/chirp/drivers/kguv9dplus.py
@@ -1093,6 +1093,10 @@ class KGUV9DPlusRadio(chirp_common.CloneModeRadio,
_rev = b"00" # default rev for the radio I know about...
_file_ident = b"kg-uv9d"
BAUD_RATE = 19200
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return cls._file_ident in filedata[0x51:0x59].lower()
POWER_LEVELS = [chirp_common.PowerLevel("L", watts=1),
chirp_common.PowerLevel("M", watts=2),
chirp_common.PowerLevel("H", watts=5)]
@@ -1148,15 +1152,6 @@ class KGUV9DPlusRadio(chirp_common.CloneModeRadio,
packet = _pkt_encode(cmd, payload)
self.pipe.write(packet)
- @classmethod
- def match_model(cls, filedata, filename):
- """Look for bits in the file image and see if it looks
- like ours...
- TODO: there is a bunch of rubbish between 0x50 and 0x160
- that is still a known unknown
- """
- return cls._file_ident in filedata[0x51:0x59].lower()
-
def _identify(self):
""" Identify the radio
The ident block identifies the radio and its capabilities.
diff --git a/chirp/drivers/leixen.py b/chirp/drivers/leixen.py
index 9135946..48e4ae0 100644
--- a/chirp/drivers/leixen.py
+++ b/chirp/drivers/leixen.py
@@ -417,7 +417,7 @@ class LeixenVV898Radio(chirp_common.CloneModeRadio):
rf.valid_duplexes = ["", "-", "+", "split", "off"]
rf.valid_skips = ["", "S"]
rf.valid_tuning_steps = _STEP_LIST
- rf.valid_bands = [(136000000, 174000000),
+ rf.valid_bands = [(136000000, 174000001),
(400000000, 480000000)]
rf.valid_tones = TONES
rf.valid_dtcs_codes = DTCS_CODES
diff --git a/chirp/drivers/mursv1.py b/chirp/drivers/mursv1.py
index 9fc8d43..8eccafe 100644
--- a/chirp/drivers/mursv1.py
+++ b/chirp/drivers/mursv1.py
@@ -465,7 +465,7 @@ class MURSV1(baofeng_common.BaofengCommonHT):
if mem.number >= 1 and mem.number <= 15:
MURS_FREQ = MURS_FREQS[mem.number - 1]
mem.freq = MURS_FREQ
- mem.duplex == ''
+ mem.duplex = ''
mem.offset = 0
immutable = ["empty", "freq", "duplex", "offset"]
if mem.freq in bandplan_na.MURS_NFM:
diff --git a/chirp/drivers/nx800.py b/chirp/drivers/nx800.py
new file mode 100644
index 0000000..383b648
--- /dev/null
+++ b/chirp/drivers/nx800.py
@@ -0,0 +1,1249 @@
+# Copyright 2026 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 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 time
+
+from chirp import bitwise, util
+from chirp import checksum
+from chirp import chirp_common
+from chirp import directory
+from chirp import errors
+from chirp import memmap
+from chirp import settings
+from chirp.drivers import tk280
+from chirp.drivers import tk8180
+
+
+LOG = logging.getLogger(__name__)
+
+
+POWER_LEVELS = [chirp_common.PowerLevel('Low', watts=5),
+ chirp_common.PowerLevel('High', watts=50)]
+
+CHANNEL_TYPES = ['Analog', 'NXDN', 'Mixed']
+DISPLAY_FORMAT_VALUES = {
+ 'CH/GID Name': 0xFF,
+ 'Zone-CH/GID Number': 0x30,
+}
+SUBLCD_VALUES = {
+ 'None': 0xFF,
+ 'Zone Number': 0x30,
+ 'CH/GID Number': 0x31,
+ 'OST List Number': 0x32,
+ 'Site Number': 0x33,
+}
+TONE_VOLUME_VALUES = [('Off', 0x00), ('Selectable', 0x30), ('Current', 0xFF)]
+TONE_VOLUME_VALUES += [('%i' % i, i) for i in range(1, 32)]
+TIMED_POWER_OFF_VALUES = ['%ih%02dm' % divmod(i * 10, 60)
+ for i in range(0, 49)]
+NX800_R_BLOCK_COUNT = 0x276
+NX800_S_BLOCKS = [
+ 0x0000,
+ 0x0100, 0x0200, 0x0300, 0x0400, 0x0500, 0x0600, 0x0700,
+ 0x0800, 0x0900, 0x0A00, 0x0B00, 0x0C00, 0x0D00, 0x0E00,
+ 0x0F00, 0x1000, 0x1100,
+ 0x8300, 0x8600, 0x8700, 0x8800, 0x8900, 0x8A00,
+ 0x2D00, 0x2E00, 0x2F00,
+]
+NX800_S_BASE = 0x27600
+NX800_X_BLOCKS = [
+ 0x0000,
+ 0x0100, 0x0200, 0x0300, 0x0400, 0x0500, 0x0600, 0x0700,
+ 0x0800, 0x0900, 0x0A00, 0x0B00, 0x0C00, 0x0D00, 0x0E00,
+ 0x0F00, 0x1000, 0x1100,
+ 0x2D00, 0x2E00, 0x2F00,
+]
+MODE_ANALOG = 0xFD
+MODE_NXDN = 0xF8
+MODE_MIXED_DIGITAL_PREF = 0xFA
+MODE_MIXED_ANALOG_PREF = 0xFE
+MODE_MIXED = (MODE_MIXED_DIGITAL_PREF, MODE_MIXED_ANALOG_PREF)
+
+
+def _sanitize_ran(value):
+ value = int(value)
+ if value < 1:
+ return 1
+ if value > 63:
+ return 63
+ return value
+
+
+def _xor_wire(data, key):
+ return bytes([b ^ key for b in data])
+
+
+def _send_xor(radio, data):
+ radio.pipe.write(_xor_wire(data, radio._wire_xor_key))
+
+
+def _read_xor(radio, count):
+ data = radio.pipe.read(count)
+ if len(data) != count:
+ raise errors.RadioError('Short read from radio')
+ return _xor_wire(data, radio._wire_xor_key)
+
+
+def _exchange_xor_ack(radio):
+ _send_xor(radio, b'\x06')
+ if _read_xor(radio, 1) != b'\x06':
+ raise errors.RadioError('Post-block exchange failed')
+
+
+def do_ident(radio):
+ radio.pipe.baudrate = 9600
+ radio.pipe.stopbits = 2
+ radio.pipe.timeout = 1
+
+ radio.pipe.write(b'PROGRAM')
+ ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
+ if ack != b'\x16':
+ raise errors.RadioError('Radio refused hi-speed program mode')
+
+ radio.pipe.baudrate = 19200
+ ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
+ if ack != b'\x06':
+ raise errors.RadioError('Radio refused program mode')
+
+ radio.pipe.write(b'\x02')
+ ident = radio.pipe.read(48)
+ if len(ident) != 48:
+ raise errors.RadioError('Radio did not return ident')
+ if ident[:8] != radio._model:
+ LOG.warning('Radio model mismatch:\n%s' % util.hexprint(ident))
+ raise errors.RadioError('Unsupported radio model %r' % ident)
+
+ # This can be anything. We choose it to be 0x00 so that the rest of the
+ # communication happens in the clear for easier debugging of traces.
+ # The OEM software seems to pick a random value for each session,
+ # obfuscating the traces. Setting this differently would achieve the
+ # same result here, but there is no reason for us to do that.
+ radio._wire_xor_key = 0x00
+
+ # We tell the radio what the key is by sending it XOR'd with magic
+ # value 0xB2, followed by cleartext ACK (0x06). The radio will then
+ # ack in the clear and all future communications will be XOR'd.
+ radio.pipe.write(bytes([radio._wire_xor_key ^ 0xB2, 0x06]))
+ if radio.pipe.read(1) != b'\x06':
+ raise errors.RadioError('Radio refused obfuscated mode')
+
+ # Initial exchange observed before first R/S requests.
+ _send_xor(radio, b'P')
+ _read_xor(radio, 12)
+ _exchange_xor_ack(radio)
+
+ # Optional model string read seen in OEM trace.
+ _send_xor(radio, b'URK')
+ _read_xor(radio, 34)
+ _exchange_xor_ack(radio)
+
+
+def do_download(radio):
+ do_ident(radio)
+
+ data = bytearray(b'\xFF' * radio._memsize)
+ read_count = 0
+
+ def status():
+ st = chirp_common.Status()
+ st.cur = read_count
+ st.max = radio._memsize
+ st.msg = 'Cloning from radio'
+ radio.status_fn(st)
+
+ for block in range(0, NX800_R_BLOCK_COUNT):
+ _send_xor(radio, tk8180.make_frame('R', block))
+ cmd = _read_xor(radio, 1)
+ chunk = b''
+ addr = block * 0x100
+ if cmd == b'Z':
+ read_count += 0x100
+ elif cmd == b'W':
+ chunk = _read_xor(radio, 256)
+ data[addr:addr + 0x100] = chunk
+ read_count += 0x100
+ else:
+ raise errors.RadioError('Unexpected response %r for block %02x' %
+ (cmd, block))
+
+ chksum = _read_xor(radio, 1)
+ calc = checksum.checksum_8bit(chunk)
+ if chunk and calc != chksum[0]:
+ raise errors.RadioError('Checksum failure while reading block')
+
+ _exchange_xor_ack(radio)
+ status()
+
+ s_index = {addr: idx for idx, addr in enumerate(NX800_S_BLOCKS)}
+ for block in NX800_S_BLOCKS:
+ _send_xor(radio, tk8180.make_frame('S', block, b'\x00'))
+ cmd = _read_xor(radio, 1)
+ if cmd != b'X':
+ raise errors.RadioError('Radio did not send block for %04x' %
+ block)
+ chunk = _read_xor(radio, 256)
+ soff = NX800_S_BASE + (s_index[block] * 0x100)
+ data[soff:soff + 0x100] = chunk
+ read_count += 0x100
+
+ _exchange_xor_ack(radio)
+ status()
+
+ _send_xor(radio, b'E')
+ if _read_xor(radio, 1) != b'\x06':
+ raise errors.RadioError('Radio failed to acknowledge completion')
+
+ return bytes(data)
+
+
+def do_upload(radio):
+ do_ident(radio)
+
+ progress = 0
+
+ def status(cur):
+ st = chirp_common.Status()
+ st.cur = cur
+ st.max = radio._memsize
+ st.msg = 'Cloning to radio'
+ radio.status_fn(st)
+
+ mmap = radio._mmap.get_packed()
+
+ for block in range(0, NX800_R_BLOCK_COUNT):
+ addr = block * 0x100
+ chunk = mmap[addr:addr + 0x100]
+ if len(chunk) != 0x100:
+ raise errors.RadioError('Invalid memory map while uploading')
+
+ if all(byte == 0xFF for byte in chunk):
+ _send_xor(radio, tk8180.make_frame('Z', block, b'\xFF'))
+ else:
+ cs = checksum.checksum_8bit(chunk)
+ _send_xor(radio, tk8180.make_frame(
+ 'W', block, chunk + bytes([cs])))
+
+ if _read_xor(radio, 1) != b'\x06':
+ raise errors.RadioError('Radio refused data block %04x' % block)
+ progress += 0x100
+ status(progress)
+
+ for i, addr in enumerate(NX800_X_BLOCKS):
+ src = NX800_S_BASE + (i * 0x100)
+ chunk = mmap[src:src + 0x100]
+ if len(chunk) != 0x100:
+ raise errors.RadioError('Invalid memory map while uploading')
+
+ _send_xor(radio, tk8180.make_frame('X', addr, b'\x00' + chunk))
+
+ if _read_xor(radio, 1) != b'\x06':
+ raise errors.RadioError('Radio refused data block %04x' % addr)
+ progress += 0x100
+ status(progress)
+
+ _send_xor(radio, b'E')
+ if _read_xor(radio, 1) != b'\x06':
+ raise errors.RadioError('Radio failed to acknowledge completion')
+
+
+def _best_effort_reset(radio):
+ try:
+ radio.pipe.baudrate = 9600
+ radio.pipe.write(b'E')
+ time.sleep(0.3)
+ radio.pipe.baudrate = 19200
+ radio.pipe.write(b'E')
+ except Exception:
+ LOG.exception('Unable to send reset sequence')
+
+
+BASE_MEM_FORMAT = """
+// No idea why, but if this is set to 0xFF KPG won't open it (but radio
+// does not seem to care). Error is something about the missing/mismatched
+// "system key", even for purely analog radios. Not sure when this would
+// get unset or need to be reset, but enumerate it here for easy
+// identification at least.
+#seekto 0x0031;
+u8 systemkey;
+
+struct memory {
+ u8 number;
+ u8 unknown01_03[3];
+ ul32 rx_freq;
+ ul32 tx_freq;
+ ul16 rx_tone;
+ ul16 tx_tone;
+ u8 ran_dec;
+ u8 unknown12;
+ u8 ran_enc;
+ u8 unknown14;
+ char name[14];
+ u8 unknown22_3c[26];
+ u8 tx_upper_f:5,
+ analog_tx:1,
+ mixed:1,
+ analog_rx:1;
+ u8 modeunknown:5,
+ highpower:1,
+ modeunknown2:2;
+ u8 unknown3e_1:4,
+ unknown3e_2:4;
+ u8 unknown3f_1:3, // always 0b111
+ digital_narrow:1,
+ unknown3f_2:2, // always 0b11 on nx, 0b00 on analog
+ analog_wide:1,
+ unknown3f_3:1; // always 1
+};
+
+#seekto 0x5D00;
+ul16 zone_starts[128];
+
+struct zoneinfo {
+ u8 number;
+ u8 zonetype;
+ ul16 flagoffset;
+ u8 count;
+ u8 unknown06;
+ char name[14];
+ u8 unknown15_18[4];
+ ul16 tot_timeout;
+ ul16 tot_prealert;
+ ul16 tot_rekey;
+ ul16 tot_reset;
+ u8 unknown21_2c[12];
+ u8 unknown2d;
+ u8 unknown2e_2f[2];
+ u8 unknown30_3f[17];
+};
+
+#seekto 0x201;
+u8 sublcd;
+
+#seekto 0x220;
+char pon_msgtext[14];
+
+#seekto 0x22E;
+u8 pon_msgtype;
+
+#seekto 0x232;
+u8 low_volume_level;
+
+#seekto 0x233;
+u8 high_volume_level;
+
+#seekto 0x234;
+u8 tone_volume_offset;
+
+#seekto 0x235;
+u8 poweron_tone;
+
+#seekto 0x236;
+u8 control_tone;
+
+#seekto 0x237;
+u8 warning_tone;
+
+#seekto 0x238;
+u8 alert_tone;
+
+#seekto 0x239;
+u8 sidetone;
+
+#seekto 0x23A;
+u8 locator_tone;
+
+#seekto 0x23C;
+u8 timed_power_off;
+
+#seekto 0x23B;
+u8 ignition_mode;
+
+#seekto 0x26C;
+struct {
+ u8 ignition_sense:1,
+ unknown26d_0:2,
+ signal_strength_indicator:1,
+ power_switch_memory:1,
+ unknown26d_1:2,
+ off_hook_decode:1;
+} conv_settings;
+
+#seekto 0x26E;
+struct {
+ u8 unknown26f_0:3,
+ clone:1,
+ firmware_programming:1,
+ firmware_version_information:1,
+ panel_tuning:1,
+ panel_test:1;
+} panel_settings;
+
+#seekto 0x269;
+struct {
+ u8 unknown270_0:5,
+ zone_name_display:1,
+ unknown270_1:2;
+} conv_settings2;
+
+#seekto 0x28D;
+struct {
+ u8 unknown28e_0:6,
+ tone_off:1,
+ ost_memory:1;
+} settings;
+
+#seekto 0x2FF;
+struct {
+ u8 unknown00;
+ char name[14];
+ u8 unknown0f_10[2];
+ ul16 rxtone;
+ ul16 txtone;
+ u8 unknown15_1f[11];
+} ost_tones[40];
+
+#seekto 0x27A00;
+u8 squelch;
+
+#seekto 0x27A02;
+u8 display_format;
+
+#seekto 0x27A05;
+u8 clock_display;
+
+#seekto 0x27B00;
+lbit skipflags[512];
+"""
+
+
+class KenwoodNXx00Radio(tk8180.ZoneMemoryMixin, tk8180.KenwoodOSTMixin,
+ chirp_common.CloneModeRadio):
+ """Kenwood NX-x00 file-format bootstrap."""
+
+ VENDOR = 'Kenwood'
+ MODEL = 'NX-x00'
+ BAUD_RATE = 9600
+ FORMATS = [directory.register_format('Kenwood KPG-111D', '*.dat')]
+
+ _dat_size = 0x40
+ _dat_variant = None
+ _default_dat_key = 0x00
+ _memsize = 0x29100
+ _system_start = 0x5E00
+ _max_per_zone = 250
+ _zone_header_size = 0x40
+ _memory_size = 0x40
+ OST_NAME_LENGTH = 14
+
+ def _compute_zone_layout(self, zone_sizes):
+ zones = []
+ addr = self._system_start
+ for count in zone_sizes:
+ zones.append((addr, count))
+ addr += self._zone_header_size + (count * self._memory_size)
+ return zones
+
+ def _set_zone_flagoffset(self, zoneinfo, scan_index):
+ zoneinfo.flagoffset = scan_index
+
+ def __init__(self, *a, **k):
+ self._wire_xor_key = 0x00
+ self._zones = []
+ self._channel_map = []
+ self._zone = None
+ super().__init__(*a, **k)
+ dat_variant = self._dat_variant
+ if dat_variant is None:
+ dat_variant = 0x06
+ self._dat_header = (b'KPG111D\xFF\xFF\xFFV2.00\xFF' + self._model +
+ b'\xFF\xFF\x00' + bytes([dat_variant]) +
+ b'\xFF\xFF\xFF\xFFD' + (b'\xFF' * 31))
+
+ @staticmethod
+ def _xor_payload(payload, key):
+ return bytes([byte ^ key for byte in payload])
+
+ @classmethod
+ def _get_dat_xor_key(cls, payload):
+ if not payload:
+ raise errors.RadioError('DAT file is empty')
+ return payload[0] ^ 0xFF
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ if filename.lower().endswith('.dat'):
+ if len(filedata) < cls._dat_size + cls._memsize:
+ return False
+ if not filedata.startswith(b'KPG111D'):
+ return False
+ if filedata[0x10:0x18] != cls._model:
+ return False
+ if cls._dat_variant is None:
+ return True
+ return filedata[0x1B] == cls._dat_variant
+ return False
+
+ def sync_in(self):
+ try:
+ data = do_download(self)
+ self._mmap = memmap.MemoryMapBytes(data)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.exception('General failure')
+ raise errors.RadioError('Failed to download from radio: %s' % e)
+ finally:
+ _best_effort_reset(self)
+ self.process_mmap()
+
+ def sync_out(self):
+ try:
+ do_upload(self)
+ except errors.RadioError:
+ _best_effort_reset(self)
+ raise
+ except Exception as e:
+ _best_effort_reset(self)
+ LOG.exception('General failure')
+ raise errors.RadioError('Failed to upload to radio: %s' % e)
+ finally:
+ _best_effort_reset(self)
+
+ def load_mmap(self, filename):
+ if filename.lower().endswith('.dat'):
+ with open(filename, 'rb') as f:
+ self._dat_header = f.read(self._dat_size)
+ obfuscated = f.read()
+ if len(obfuscated) == self._memsize + 1:
+ dat_xor_key = self._get_dat_xor_key(obfuscated)
+ payload = self._xor_payload(obfuscated[1:], dat_xor_key)
+ elif len(obfuscated) == self._memsize:
+ dat_xor_key = obfuscated[-1] ^ 0xFF
+ payload = self._xor_payload(obfuscated, dat_xor_key)
+ else:
+ raise errors.RadioError(
+ 'Unexpected DAT payload size %i' % len(obfuscated))
+ self._mmap = memmap.MemoryMapBytes(payload)
+ self.process_mmap()
+ LOG.info('Loaded DAT file with xor key 0x%02X',
+ dat_xor_key)
+ else:
+ super().load_mmap(filename)
+
+ def save_mmap(self, filename):
+ if filename.lower().endswith('.dat'):
+ # Per above, we choose a key of 0x00 so we end up with no
+ # obfuscation in the DAT file for easier debugging. If we set
+ # this to something non-zero we would obfuscate the file in the
+ # same way OEM does.
+ key = self._default_dat_key
+ payload = self._mmap.get_packed()
+ if len(payload) != self._memsize:
+ raise errors.RadioError(
+ 'Invalid memory size %i' % len(payload))
+ obfuscated = bytes([0xFF ^ key]) + self._xor_payload(payload, key)
+ with open(filename, 'wb') as f:
+ f.write(self._dat_header)
+ f.write(obfuscated)
+ LOG.info('Wrote DAT file with xor key 0x%02X', key)
+ else:
+ super().save_mmap(filename)
+
+ def process_mmap(self):
+ self._zones = self.probe_layout()
+ self._memobj = bitwise.parse(
+ self._build_mem_format_from_zone_sizes(
+ [x[1] for x in self._zones]),
+ self._mmap)
+ self._channel_map = []
+ for zoneindex, (_addr, count) in enumerate(self._zones):
+ for chanindex in range(count):
+ self._channel_map.append((zoneindex, chanindex))
+
+ def _build_mem_format_from_zone_sizes(self, zone_sizes):
+ mem_format = BASE_MEM_FORMAT
+ for index, (addr, count) in enumerate(self._compute_zone_layout(
+ zone_sizes)):
+ mem_format += tk8180.SYSTEM_MEM_FORMAT % {
+ 'addr': addr,
+ 'count': max(count, 1),
+ 'index': index,
+ }
+ return mem_format
+
+ def probe_layout(self):
+ static = bitwise.parse(BASE_MEM_FORMAT, self._mmap)
+
+ zone_addresses = []
+ for i in range(0, 128):
+ addr = int(static.zone_starts[i])
+ if addr == 0xFFFF:
+ break
+ zone_addresses.append(addr)
+
+ probe_format = BASE_MEM_FORMAT
+ for i, addr in enumerate(zone_addresses):
+ probe_format += '#seekto 0x%x; struct zoneinfo zone%i;' % (addr, i)
+
+ probe = bitwise.parse(probe_format, self._mmap)
+ zones = []
+ for i, addr in enumerate(zone_addresses):
+ zone = getattr(probe, 'zone%i' % i)
+ if int(zone.zonetype) != 0x31:
+ LOG.warning(
+ 'Unsupported non-conventional zone %i type %02x at 0x%04x',
+ i, int(zone.zonetype), addr)
+ raise errors.RadioError('Unsupported non-conventional zone')
+ zones.append((addr, int(zone.count)))
+
+ LOG.debug('Zones: %s', zones)
+ return zones
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_bank = False
+ rf.has_tuning_step = False
+ rf.has_settings = self._zone is None
+ if self._zone is None:
+ rf.memory_bounds = (1, max(1, len(self._channel_map)))
+ rf.has_sub_devices = True
+ rf.has_dynamic_subdevices = True
+ else:
+ rf.memory_bounds = (1, self._max_per_zone)
+ rf.has_sub_devices = False
+ rf.has_dynamic_subdevices = False
+ rf.can_odd_split = True
+ rf.valid_modes = ['FM', 'NFM', 'NXDN']
+ rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
+ rf.valid_cross_modes = ['Tone->Tone', 'DTCS->', '->DTCS',
+ 'Tone->DTCS', 'DTCS->Tone', '->Tone',
+ 'DTCS->DTCS']
+ rf.has_ctone = True
+ rf.has_cross = True
+ rf.has_rx_dtcs = True
+ rf.valid_duplexes = ['', '-', '+', 'split', 'off']
+ rf.valid_skips = ['', 'S']
+ rf.valid_name_length = 14
+ rf.valid_bands = self.VALID_BANDS
+ rf.valid_power_levels = POWER_LEVELS
+ rf.valid_characters = chirp_common.CHARSET_ASCII
+ rf.valid_tuning_steps = [5.0, 12.5, 6.25]
+ return rf
+
+ def _resolve_channel(self, number):
+ if self._zone is None:
+ if number < 1 or number > len(self._channel_map):
+ return None
+ return self._channel_map[number - 1]
+
+ if number < 1 or number > self._max_per_zone:
+ return None
+ chanindex = self._get_zone_channel_index(self._zone, number)
+ if chanindex is None:
+ return None
+ return self._zone, chanindex
+
+ def _get_zone_channel_index(self, zoneindex, number):
+ zone = getattr(self._memobj, 'zone%i' % zoneindex)
+ count = self._zones[zoneindex][1]
+ for i in range(count):
+ if int(zone.memories[i].number) == number:
+ return i
+ return None
+
+ def _init_new_zoneinfo(self, dest_zoneinfo, zone_number, count,
+ old_memobj):
+ if self._zones:
+ z0info = getattr(old_memobj, 'zone0').zoneinfo
+ dest_zoneinfo.set_raw(z0info.get_raw())
+ else:
+ dest_zoneinfo.set_raw(b'\xFF' * 0x40)
+ dest_zoneinfo.number = zone_number + 1
+ dest_zoneinfo.zonetype = 0x31
+ dest_zoneinfo.count = count
+ dest_zoneinfo.name = (' %i' % (zone_number + 1)).ljust(14, '\x00')
+
+ def expand_mmap(self, zone_sizes):
+ super().expand_mmap(zone_sizes)
+
+ def get_raw_memory(self, number):
+ resolved = self._resolve_channel(number)
+ if resolved is None:
+ raise errors.RadioError('Invalid memory %s' % number)
+ zoneindex, chanindex = resolved
+ zone = getattr(self._memobj, 'zone%i' % zoneindex)
+ return repr(zone.memories[chanindex])
+
+ def get_memory(self, number):
+ mem = chirp_common.Memory()
+ mem.number = number
+
+ resolved = self._resolve_channel(number)
+ if resolved is None:
+ mem.empty = True
+ return mem
+
+ zoneindex, chanindex = resolved
+ zobj = getattr(self._memobj, 'zone%i' % zoneindex)
+ zone = zobj.zoneinfo
+ _mem = zobj.memories[chanindex]
+
+ if int(_mem.number) == 0xFF or int(_mem.rx_freq) in (0, 0xFFFFFFFF):
+ mem.empty = True
+ return mem
+
+ mem.freq = int(_mem.rx_freq)
+ mem.name = str(_mem.name).rstrip('\x00').rstrip()
+
+ chirp_common.split_tone_decode(
+ mem,
+ tk8180.KenwoodTKx180Radio._decode_tone(int(_mem.tx_tone)),
+ tk8180.KenwoodTKx180Radio._decode_tone(int(_mem.rx_tone)))
+
+ tx = int(_mem.tx_freq)
+ if tx == 0xFFFFFFFF:
+ mem.duplex = 'off'
+ mem.offset = 0
+ else:
+ offset = tx - mem.freq
+ if offset == 0:
+ mem.duplex = ''
+ mem.offset = 0
+ elif abs(offset) < 10000000:
+ mem.duplex = offset < 0 and '-' or '+'
+ mem.offset = abs(offset)
+ else:
+ mem.duplex = 'split'
+ mem.offset = tx
+
+ verynarrow = not _mem.digital_narrow
+ if _mem.mixed:
+ channel_type = 'Mixed'
+ if _mem.analog_tx:
+ mem.mode = 'FM' if _mem.analog_wide else 'NFM'
+ else:
+ mem.mode = 'NXDN'
+ elif _mem.analog_rx:
+ # Analog only
+ channel_type = 'Analog'
+ mem.mode = 'FM' if _mem.analog_wide else 'NFM'
+ else:
+ # Digital only
+ channel_type = 'NXDN'
+ mem.mode = 'NXDN'
+
+ ran_dec = _sanitize_ran(int(_mem.ran_dec))
+ ran_enc = _sanitize_ran(int(_mem.ran_enc))
+
+ mem.extra = settings.RadioSettingGroup('extra', 'Extra')
+ val = settings.RadioSettingValueList(
+ CHANNEL_TYPES,
+ current_index=CHANNEL_TYPES.index(channel_type))
+ mem.extra.append(settings.RadioSetting('channel_type',
+ 'Channel Type', val))
+
+ val = settings.RadioSettingValueBoolean(_mem.analog_wide)
+ val.set_mutable(channel_type == 'Mixed' and mem.mode == 'NXDN')
+ mem.extra.append(settings.RadioSetting('analog_wide',
+ 'Analog Wide', val))
+
+ val = settings.RadioSettingValueBoolean(verynarrow)
+ val.set_mutable(channel_type != 'Analog')
+ mem.extra.append(settings.RadioSetting('verynarrow',
+ 'NXDN Very Narrow', val))
+
+ val = settings.RadioSettingValueInteger(1, 63, ran_dec)
+ val.set_mutable(channel_type != 'Analog')
+ mem.extra.append(settings.RadioSetting('ran_dec',
+ 'RAN Dec', val))
+
+ val = settings.RadioSettingValueInteger(1, 63, ran_enc)
+ val.set_mutable(channel_type != 'Analog')
+ mem.extra.append(settings.RadioSetting('ran_enc',
+ 'RAN Enc', val))
+
+ mem.power = POWER_LEVELS[int(_mem.highpower)]
+
+ scan_index = int(zone.flagoffset) + chanindex - 1
+ if 0 <= scan_index < len(self._memobj.skipflags):
+ mem.skip = 'S' if bool(self._memobj.skipflags[scan_index]) else ''
+ else:
+ mem.skip = ''
+
+ return mem
+
+ def set_memory(self, mem):
+ resolved = self._resolve_channel(mem.number)
+ if resolved is None:
+ if mem.empty:
+ return
+ if self._zone is None:
+ raise errors.RadioError('Only discovered channels are '
+ 'writable')
+
+ if mem.number > self._max_per_zone:
+ raise errors.RadioError('Maximum channels per zone is %i' %
+ self._max_per_zone)
+
+ parent = getattr(self, '_parent', self)
+ zoneindex = self._zone
+ new_sizes = [x[1] for x in parent._zones]
+ new_sizes[zoneindex] = new_sizes[zoneindex] + 1
+ parent.expand_mmap(new_sizes)
+
+ zobj = getattr(self._memobj, 'zone%i' % zoneindex)
+ _mem = zobj.memories[parent._zones[zoneindex][1] - 1]
+ _mem.number = mem.number
+ self.shuffle_zone()
+
+ chanindex = parent._get_zone_channel_index(zoneindex, mem.number)
+ if chanindex is None:
+ raise errors.RadioError('Failed to allocate memory')
+ _mem = zobj.memories[chanindex]
+
+ zone = zobj.zoneinfo
+ else:
+ zoneindex, chanindex = resolved
+ zobj = getattr(self._memobj, 'zone%i' % zoneindex)
+ zone = zobj.zoneinfo
+ _mem = zobj.memories[chanindex]
+
+ if mem.empty:
+ parent = getattr(self, '_parent', self)
+ _mem.number = 0xFF
+ self.shuffle_zone()
+ new_sizes = [x[1] for x in parent._zones]
+ new_sizes[zoneindex] = new_sizes[zoneindex] - 1
+ parent.expand_mmap(new_sizes)
+ return
+
+ _mem.number = mem.number
+ _mem.rx_freq = mem.freq
+ txtone, rxtone = chirp_common.split_tone_encode(mem)
+ _mem.tx_tone = tk8180.KenwoodTKx180Radio._encode_tone(*txtone)
+ _mem.rx_tone = tk8180.KenwoodTKx180Radio._encode_tone(*rxtone)
+ _mem.name = mem.name[:14].ljust(14)
+ _mem.highpower = mem.power == POWER_LEVELS[1]
+
+ # Default in case we don't have mem.extra:
+ channel_type = 'NXDN' if mem.mode == 'NXDN' else 'Analog'
+ verynarrow = False
+ analog_wide = mem.mode == 'FM'
+ ran_dec = ran_enc = 0
+
+ for setting in mem.extra or []:
+ if setting.get_name() == 'channel_type':
+ value = str(setting.value)
+ if value in CHANNEL_TYPES:
+ channel_type = value
+ else:
+ try:
+ channel_type = CHANNEL_TYPES[int(setting.value)]
+ except (TypeError, ValueError, IndexError):
+ pass
+ elif setting.get_name() == 'verynarrow':
+ verynarrow = bool(int(setting.value))
+ elif (setting.get_name() == 'analog_wide' and
+ channel_type == 'Mixed' and
+ mem.mode == 'NXDN'):
+ analog_wide = bool(int(setting.value))
+ elif setting.get_name() == 'ran_dec':
+ ran_dec = _sanitize_ran(setting.value)
+ elif setting.get_name() == 'ran_enc':
+ ran_enc = _sanitize_ran(setting.value)
+
+ _mem.analog_rx = channel_type == 'Analog'
+ _mem.mixed = channel_type == 'Mixed'
+ _mem.analog_tx = mem.mode != 'NXDN'
+ _mem.digital_narrow = not verynarrow
+ _mem.analog_wide = analog_wide
+ _mem.unknown3f_2 = 0x3 if channel_type == 'NXDN' else 0
+ _mem.unknown3f_1 = 0x0 if channel_type == 'NXDN' else 0x7
+
+ if channel_type != 'Analog':
+ _mem.ran_dec = ran_dec
+ _mem.ran_enc = ran_enc
+ else:
+ _mem.ran_dec = 0xFF
+ _mem.ran_enc = 0xFF
+
+ if mem.duplex == '':
+ _mem.tx_freq = mem.freq
+ elif mem.duplex == 'split':
+ _mem.tx_freq = mem.offset
+ elif mem.duplex == 'off':
+ _mem.tx_freq = 0xFFFFFFFF
+ elif mem.duplex == '-':
+ _mem.tx_freq = mem.freq - mem.offset
+ elif mem.duplex == '+':
+ _mem.tx_freq = mem.freq + mem.offset
+ else:
+ raise errors.RadioError('Unsupported duplex mode %r' % mem.duplex)
+
+ scan_index = int(zone.flagoffset) + chanindex - 1
+ if 0 <= scan_index < len(self._memobj.skipflags):
+ self._memobj.skipflags[scan_index] = int(mem.skip == 'S')
+
+ def get_sub_devices(self):
+ zones = []
+ to_copy = ('VENDOR', 'MODEL', 'VALID_BANDS', '_model')
+ for i, _ in enumerate(self._zones):
+ zone = getattr(self._memobj, 'zone%i' % i)
+ zone_cls = tk280.TKx80SubdevMeta.make_subdev(
+ self, KenwoodNXx00RadioZone, i, to_copy,
+ VARIANT='Zone %s' % (
+ str(zone.zoneinfo.name).rstrip('\x00').rstrip()))
+ zones.append(zone_cls(self, i))
+ return zones
+
+ def _get_zones(self):
+ zones = settings.RadioSettingGroup('zones', 'Zones')
+
+ zone_count = settings.RadioSetting(
+ '_zonecount',
+ 'Number of Zones',
+ settings.RadioSettingValueInteger(1, 128, len(self._zones)))
+ zone_count.set_doc('Number of zones in the radio. Reducing this '
+ 'number will DELETE memories in affected zones!')
+ zone_count.set_volatile(True)
+ zones.append(zone_count)
+
+ for i in range(len(self._zones)):
+ zone = settings.RadioSettingSubGroup('zone%i' % i,
+ 'Zone %i' % (i + 1))
+ _zone = getattr(self._memobj, 'zone%i' % i).zoneinfo
+
+ _name = str(_zone.name).rstrip('\x00')
+ name = settings.MemSetting(
+ 'zone%i.zoneinfo.name' % i,
+ 'Name',
+ settings.RadioSettingValueString(0, 14, _name,
+ mem_pad_char='\x00'))
+ zone.append(name)
+
+ def apply_timer(setting, key, zone_number):
+ val = int(setting.value)
+ if key == 'tot_timeout':
+ if val < 15:
+ val = 15
+ elif val > 1200:
+ val = 1200
+ val = (val // 15) * 15
+ elif val == 0:
+ val = 0xFFFF
+ _zone = getattr(self._memobj,
+ 'zone%i' % zone_number).zoneinfo
+ setattr(_zone, key, val)
+
+ def collapse_timer(val):
+ val = int(val)
+ if val == 0xFFFF:
+ val = 0
+ return val
+
+ timeout = settings.RadioSetting(
+ 'z%itot_timeout' % i,
+ 'Time-out Timer',
+ settings.RadioSettingValueInteger(
+ 15, 1200,
+ max(15, min(1200, int(_zone.tot_timeout))), 15))
+ timeout.set_apply_callback(apply_timer, 'tot_timeout', i)
+ zone.append(timeout)
+
+ prealert = settings.RadioSetting(
+ 'z%itot_prealert' % i,
+ 'TOT Pre-Alert',
+ settings.RadioSettingValueInteger(
+ 0, 10, collapse_timer(_zone.tot_prealert)))
+ prealert.set_apply_callback(apply_timer, 'tot_prealert', i)
+ zone.append(prealert)
+
+ rekey = settings.RadioSetting(
+ 'z%itot_rekey' % i,
+ 'TOT Re-Key Time',
+ settings.RadioSettingValueInteger(
+ 0, 60, collapse_timer(_zone.tot_rekey)))
+ rekey.set_apply_callback(apply_timer, 'tot_rekey', i)
+ zone.append(rekey)
+
+ reset = settings.RadioSetting(
+ 'z%itot_reset' % i,
+ 'TOT Reset Time',
+ settings.RadioSettingValueInteger(
+ 0, 15, collapse_timer(_zone.tot_reset)))
+ reset.set_apply_callback(apply_timer, 'tot_reset', i)
+ zone.append(reset)
+
+ zones.append(zone)
+
+ return zones
+
+ def _get_ost(self):
+ ostgroup = super()._get_ost()
+
+ for key, name in (('ost_memory', 'OST Status Memory'),
+ ('tone_off', 'Tone Off')):
+ ostgroup.append(settings.MemSetting(
+ 'settings.%s' % key, name,
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(getattr(self._memobj.settings, key)))))
+
+ # RadioSettingGroup only supports appending, so move the
+ # settings we added to the front of the group, ahead of the
+ # individual OSTs appended by the parent.
+ for i, key in enumerate(('ost_memory', 'tone_off')):
+ name = 'settings_%s' % key
+ ostgroup.keys().remove(name)
+ ostgroup.keys().insert(i, name)
+
+ return ostgroup
+
+ def _get_conventional(self):
+ conv = settings.RadioSettingGroup('conv', 'Conventional')
+
+ conv.append(settings.MemSetting(
+ 'conv_settings.power_switch_memory',
+ 'Power Switch Status Memory',
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(self._memobj.conv_settings.power_switch_memory))))
+
+ conv.append(settings.MemSetting(
+ 'conv_settings.ignition_sense', 'Ignition Sense',
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(self._memobj.conv_settings.ignition_sense))))
+
+ conv.append(settings.MemSetting(
+ 'conv_settings.signal_strength_indicator',
+ 'Signal Strength Indicator',
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(
+ self._memobj.conv_settings.signal_strength_indicator))))
+
+ conv.append(settings.MemSetting(
+ 'conv_settings2.zone_name_display', 'Zone Name Display',
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(self._memobj.conv_settings2.zone_name_display))))
+
+ conv.append(settings.MemSetting(
+ 'panel_settings.panel_test', 'Panel Test',
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(self._memobj.panel_settings.panel_test))))
+
+ conv.append(settings.MemSetting(
+ 'panel_settings.panel_tuning', 'Panel Tuning',
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(self._memobj.panel_settings.panel_tuning))))
+
+ conv.append(settings.MemSetting(
+ 'panel_settings.clone', 'Clone',
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(self._memobj.panel_settings.clone))))
+
+ conv.append(settings.MemSetting(
+ 'panel_settings.firmware_programming',
+ 'Firmware Programming',
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(self._memobj.panel_settings.firmware_programming))))
+
+ conv.append(settings.MemSetting(
+ 'panel_settings.firmware_version_information',
+ 'Firmware Version Information',
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(
+ self._memobj.panel_settings.firmware_version_information)
+ )))
+
+ conv.append(settings.MemSetting(
+ 'conv_settings.off_hook_decode', 'Off-hook Decode',
+ settings.RadioSettingValueInvertedBoolean(
+ not bool(self._memobj.conv_settings.off_hook_decode))))
+
+ conv.append(settings.MemSetting(
+ 'squelch', 'Squelch Level',
+ settings.RadioSettingValueInteger(0, 9,
+ int(self._memobj.squelch))))
+
+ conv.append(settings.MemSetting(
+ 'display_format', 'Display Format',
+ settings.RadioSettingValueMap(
+ DISPLAY_FORMAT_VALUES.items(),
+ int(self._memobj.display_format))))
+
+ conv.append(settings.MemSetting(
+ 'sublcd', 'Sub-LCD Display',
+ settings.RadioSettingValueMap(SUBLCD_VALUES.items(),
+ int(self._memobj.sublcd))))
+
+ conv.append(settings.MemSetting(
+ 'clock_display', 'Clock Display',
+ settings.RadioSettingValueBoolean(
+ bool(self._memobj.clock_display == 0),
+ mem_vals=(0xFF, 0x00))))
+
+ conv.append(settings.MemSetting(
+ 'low_volume_level', 'Low Volume Level (Fixed Volume)',
+ settings.RadioSettingValueInteger(
+ 0, 30,
+ int(self._memobj.low_volume_level))))
+
+ conv.append(settings.MemSetting(
+ 'high_volume_level', 'High Volume Level (Fixed Volume)',
+ settings.RadioSettingValueInteger(
+ 1, 31,
+ int(self._memobj.high_volume_level))))
+
+ conv.append(settings.MemSetting(
+ 'pon_msgtype', 'Power-on Message Type',
+ settings.RadioSettingValueMap(
+ [('Off', 0xFF), ('Text', 0x30), ('Clock', 0x31),
+ ('FleetSync ID', 0x32), ('NXDN Unit ID', 0x33),
+ ('NXDN Unit ID Name', 0x34)],
+ int(self._memobj.pon_msgtype))))
+
+ conv.append(settings.MemSetting(
+ 'pon_msgtext', 'Power-on Message Text',
+ settings.RadioSettingValueString(
+ 0, 14, str(self._memobj.pon_msgtext).rstrip('\x00'))))
+
+ _tvo = int(self._memobj.tone_volume_offset)
+ if _tvo & 0x80:
+ _tvo = _tvo - 0x100
+ conv.append(settings.MemSetting(
+ 'tone_volume_offset', 'Tone Volume Offset',
+ settings.RadioSettingValueInteger(-5, 5, _tvo)))
+
+ conv.append(settings.MemSetting(
+ 'poweron_tone', 'Power-on Tone',
+ settings.RadioSettingValueMap(
+ TONE_VOLUME_VALUES,
+ int(self._memobj.poweron_tone))))
+
+ conv.append(settings.MemSetting(
+ 'control_tone', 'Control Tone',
+ settings.RadioSettingValueMap(
+ TONE_VOLUME_VALUES,
+ int(self._memobj.control_tone))))
+
+ conv.append(settings.MemSetting(
+ 'warning_tone', 'Warning Tone',
+ settings.RadioSettingValueMap(
+ TONE_VOLUME_VALUES,
+ int(self._memobj.warning_tone))))
+
+ conv.append(settings.MemSetting(
+ 'alert_tone', 'Alert Tone',
+ settings.RadioSettingValueMap(
+ TONE_VOLUME_VALUES,
+ int(self._memobj.alert_tone))))
+
+ conv.append(settings.MemSetting(
+ 'sidetone', 'Sidetone',
+ settings.RadioSettingValueMap(
+ TONE_VOLUME_VALUES,
+ int(self._memobj.sidetone))))
+
+ conv.append(settings.MemSetting(
+ 'locator_tone', 'Locator Tone',
+ settings.RadioSettingValueMap(
+ TONE_VOLUME_VALUES,
+ int(self._memobj.locator_tone))))
+
+ conv.append(settings.MemSetting(
+ 'ignition_mode', 'Ignition Sense Type',
+ settings.RadioSettingValueMap(
+ [('Ignition and Switch', 0x30), ('Ignition Only', 0x31)],
+ int(self._memobj.ignition_mode))))
+
+ conv.append(settings.MemSetting(
+ 'timed_power_off', 'Timed Power Off',
+ settings.RadioSettingValueList(
+ TIMED_POWER_OFF_VALUES,
+ current_index=int(self._memobj.timed_power_off))))
+
+ return conv
+
+ def get_settings(self):
+ return settings.RadioSettings(self._get_zones(), self._get_ost(),
+ self._get_conventional())
+
+ def set_settings(self, settings_obj):
+ for element in settings_obj.apply_to(self._memobj):
+ if not element.changed():
+ continue
+ if element.get_name() == '_zonecount':
+ new_zone_count = int(element.value)
+ zone_sizes = [x[1] for x in self._zones[:new_zone_count]]
+ if len(self._zones) > new_zone_count:
+ self.expand_mmap(zone_sizes[:new_zone_count])
+ elif len(self._zones) < new_zone_count:
+ self.expand_mmap(zone_sizes +
+ ([0] * (new_zone_count -
+ len(self._zones))))
+ elif element.has_apply_callback():
+ element.run_apply_callback()
+
+
+class KenwoodNXx00RadioZone:
+ _zone = None
+
+ def __init__(self, parent, zone=0):
+ if isinstance(parent, KenwoodNXx00Radio):
+ self._parent = parent
+ else:
+ LOG.warning('Parent was not actually our parent, expect failure')
+ self._zone = zone
+
+ @property
+ def _zones(self):
+ return self._parent._zones
+
+ @property
+ def _memobj(self):
+ return self._parent._memobj
+
+ @property
+ def _mmap(self):
+ return self._parent._mmap
+
+ def load_mmap(self, filename):
+ self._parent.load_mmap(filename)
+
+ def save_mmap(self, filename):
+ self._parent.save_mmap(filename)
+
+ def get_sub_devices(self):
+ return []
+
+
+# Need a test to confirm
+# @directory.register
+class KenwoodNX700Radio(KenwoodNXx00Radio):
+ MODEL = 'NX-700'
+ VALID_BANDS = [(136000000, 174000000)]
+ _dat_variant = 0x04
+ _model = b'MNX 0700'
+
+
+@directory.register
+class KenwoodNX800Radio(KenwoodNXx00Radio):
+ MODEL = 'NX-800'
+ VALID_BANDS = [(400000000, 520000000)]
+ _dat_variant = 0x06
+ _model = b'MNX 0800'
diff --git a/chirp/drivers/radioddity_r2.py b/chirp/drivers/radioddity_r2.py
index 0845ac6..1e19943 100644
--- a/chirp/drivers/radioddity_r2.py
+++ b/chirp/drivers/radioddity_r2.py
@@ -667,12 +667,6 @@ class RadioddityR2(chirp_common.CloneModeRadio):
LOG.debug(element.get_name())
raise
- @classmethod
- def match_model(cls, filedata, filename):
- # This radio has always been post-metadata, so never do
- # old-school detection
- return False
-
@directory.register
class RetevisRT24(RadioddityR2):
diff --git a/chirp/drivers/radtel_rt490.py b/chirp/drivers/radtel_rt490.py
index 6353b86..d489158 100644
--- a/chirp/drivers/radtel_rt490.py
+++ b/chirp/drivers/radtel_rt490.py
@@ -481,10 +481,6 @@ class RT490Radio(chirp_common.CloneModeRadio):
_mem_params = (_upper-1)
_frs = _murs = _pmr = _gmrs = True
- @classmethod
- def match_model(cls, filedata, filename):
- return False
-
def set_settings(self, settings):
for element in settings:
if not isinstance(element, RadioSetting):
diff --git a/chirp/drivers/radtel_rt880g.py b/chirp/drivers/radtel_rt880g.py
index cd38fad..91e78d9 100644
--- a/chirp/drivers/radtel_rt880g.py
+++ b/chirp/drivers/radtel_rt880g.py
@@ -2307,9 +2307,3 @@ class RT880G(chirp_common.CloneModeRadio):
except Exception as e:
LOG.debug(element.get_name(), e)
raise
-
- @classmethod
- def match_model(cls, filedata, filename):
- # This radio has always been post-metadata, so never do
- # old-school detection
- return False
diff --git a/chirp/drivers/radtel_t18.py b/chirp/drivers/radtel_t18.py
index 396f650..9ee106b 100644
--- a/chirp/drivers/radtel_t18.py
+++ b/chirp/drivers/radtel_t18.py
@@ -364,7 +364,7 @@ def _t18_write_block(radio, block_addr, block_size):
def do_download(radio):
LOG.debug("download")
- _t18_enter_programming_mode(radio)
+ radio._enter_programming_mode()
data = b""
@@ -393,7 +393,7 @@ def do_upload(radio):
status = chirp_common.Status()
status.msg = "Uploading to radio"
- _t18_enter_programming_mode(radio)
+ radio._enter_programming_mode()
status.cur = 0
status.max = radio._memsize
@@ -483,6 +483,9 @@ class T18Radio(chirp_common.CloneModeRadio):
def process_mmap(self):
self._memobj = bitwise.parse(MEM_FORMAT % self._mem_params, self._mmap)
+ def _enter_programming_mode(self):
+ _t18_enter_programming_mode(self)
+
def sync_in(self):
self._mmap = do_download(self)
self.process_mmap()
@@ -564,9 +567,9 @@ class T18Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("bcl", "Busy Channel Lockout",
RadioSettingValueBoolean(not _mem.bcl))
rs.set_doc(
- "Prevents transmitting on this channel while another station is "
- "already using it. Pressing PTT on a busy channel sounds an "
- "alert tone instead of keying the transmitter.")
+ "Prevents transmitting on a channel that is already in use. "
+ "Pressing PTT on a busy channel sounds an alert tone instead of "
+ "keying the transmitter.")
mem.extra.append(rs)
if self.MODEL != "RB18" and self.MODEL != "RB618" and \
self.MODEL != "FRS-B1" and self.MODEL != "BF-V8A" and \
@@ -738,7 +741,7 @@ class T18Radio(chirp_common.CloneModeRadio):
"Sets how strong a received signal must be before the speaker "
"unmutes. 0 leaves the squelch open so you hear noise all the "
"time, higher values reject more weak signals and noise. Raise "
- "this value if the radio keeps opening on interference, lower "
+ "this value if the speaker keeps unmuting on interference, lower "
"it if distant stations are being cut off.")
basic.append(rs)
@@ -796,8 +799,8 @@ class T18Radio(chirp_common.CloneModeRadio):
RadioSettingValueBoolean(_settings2.voicesw))
rs.set_doc(
"Announces the channel number and other operations out loud "
- "as you use the radio. Useful on a radio without a display, "
- "but it can be intrusive in quiet surroundings.")
+ "as you use the radio. It can be intrusive in quiet "
+ "surroundings.")
basic.append(rs)
elif self.MODEL == "RT15":
rs = RadioSetting("voiceprompt", "Voice prompts",
@@ -816,10 +819,11 @@ class T18Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("batterysaver", "Battery saver",
RadioSettingValueBoolean(_settings.batterysaver))
rs.set_doc(
- "Cuts standby power consumption by dozing the receiver once no "
- "signal has been received for a few seconds. It considerably "
- "extends battery life, at the cost of occasionally clipping the "
- "first moment of an incoming transmission.")
+ "Cuts standby power consumption by switching the receiver off and "
+ "on in a repeating cycle once no signal has been received for a "
+ "few seconds. It considerably extends battery life, at the cost "
+ "of occasionally clipping the first moment of an incoming "
+ "transmission.")
basic.append(rs)
if self.MODEL not in ["RB29",
@@ -1085,10 +1089,9 @@ class T18Radio(chirp_common.CloneModeRadio):
RadioSettingValueInteger(
1, 5, _settings2.voxgain))
rs.set_doc(
- "Sets the VOX sensitivity, on a scale of 1 to 5. Too "
- "sensitive a setting keys the transmitter on the noise "
- "around the radio, too insensitive a setting fails to pick "
- "up your voice. Only has an effect when VOX is enabled.")
+ "Sets the VOX sensitivity. Too sensitive a setting keys the "
+ "transmitter on the noise around the radio, too insensitive "
+ "a setting fails to pick up your voice.")
basic.append(rs)
if self.MODEL == "RB29" or self.MODEL == "RB629":
@@ -1552,7 +1555,8 @@ class RT15Radio(T18Radio):
_magic = b"KAOGRAM"
_fingerprint = [b"\x06\x00\x00\x00\x00\x00\x00\x00",
- b"\x06\x03\xE8\x08\xFF\xFF\xFF\xFF"]
+ b"\x06\x03\xE8\x08\xFF\xFF\xFF\xFF",
+ b"\x06MP558\xFF\xFF"]
_upper = 16
_mem_params = (_upper # number of channels
)
diff --git a/chirp/drivers/retevis_ra25.py b/chirp/drivers/retevis_ra25.py
index 8d8c93a..a26d702 100644
--- a/chirp/drivers/retevis_ra25.py
+++ b/chirp/drivers/retevis_ra25.py
@@ -1181,11 +1181,6 @@ class RA25UVRadio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
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):
diff --git a/chirp/drivers/retevis_rb28.py b/chirp/drivers/retevis_rb28.py
index 4e13023..c837142 100644
--- a/chirp/drivers/retevis_rb28.py
+++ b/chirp/drivers/retevis_rb28.py
@@ -1,4 +1,4 @@
-# Copyright 2023 Jim Unroe <rock.unroe@gmail.com>
+# Copyright 2026 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
@@ -79,7 +79,7 @@ struct {
u8 tone; // Tone 006E
u8 chnumber; // Channel 006F
u8 channel_8[13]; // 0070-007C
- u8 unknown_7d; // 007D
+ u8 vibrate; // 007D
u8 scan; // Scan 007E
u8 backlight; // Back Light 007F
u8 channel_9[13]; // 0080-008C
@@ -87,7 +87,7 @@ struct {
u8 wxwarn; // Weather Warn 008E
u8 roger; // End Tone 008F
u8 channel_10[13]; // 0090-009C
- u8 unknown_9d; // 009D
+ u8 keylock48; // Key Lock 009D
u8 keylock; // Key Lock 009E
u8 unknown_9f; // 009F
u8 channel_11[13]; // 00A0-00AC
@@ -140,17 +140,23 @@ VOICE_LIST = ["Off", "English"]
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)]
-PMR_TONES = tuple(
- set(chirp_common.TONES) - set([69.3, 159.8, 165.5, 171.3, 177.3,
- 183.5, 189.9, 196.6, 199.5, 206.5,
- 229.1, 254.1]))
-
-PMR_DTCS_CODES = tuple(
- set(chirp_common.DTCS_CODES) - set([36, 53, 122, 145, 212,
- 225, 246, 252, 255, 266,
- 274, 325, 332, 356, 446,
- 452, 454, 455, 462, 523,
- 526]))
+# Sort to preserve chirp_common ordering because these tuples are used for
+# positional tone/DTCS index mapping when decoding the radio image.
+PMR_TONES = tuple(sorted(
+ set(chirp_common.TONES) - set([
+ 69.3, 159.8, 165.5, 171.3, 177.3,
+ 183.5, 189.9, 196.6, 199.5, 206.5,
+ 229.1, 254.1
+ ])
+))
+
+PMR_DTCS_CODES = tuple(sorted(
+ set(chirp_common.DTCS_CODES) - set([
+ 36, 53, 122, 145, 212, 225, 246, 252, 255,
+ 266, 274, 325, 332, 356, 446, 452, 454, 455,
+ 462, 523, 526
+ ])
+))
def _enter_programming_mode(radio):
@@ -321,6 +327,14 @@ class RB28Radio(chirp_common.CloneModeRadio):
_ack_1st_block = False
_reserved = True
_frs = True
+ _pmr = False
+ _duplexes = ["", "off"]
+ _has_volume = True
+ _has_autokeylock = True
+ _has_pfkey = True
+ _has_wxchnumber = True
+ _has_vibrate = False
+ _has_keylock48 = False
_ranges = [
(0x0000, 0x0160),
@@ -343,7 +357,7 @@ class RB28Radio(chirp_common.CloneModeRadio):
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 = ["", "off"]
+ rf.valid_duplexes = self._duplexes
rf.valid_modes = ["FM", "NFM"] # 25 kHz, 12.5 kHz.
rf.valid_tones = self.TONES
rf.valid_dtcs_codes = self.DTCS_CODES
@@ -412,7 +426,10 @@ class RB28Radio(chirp_common.CloneModeRadio):
mem.empty = True
return mem
- if int(_mem.rxfreq) == int(_mem.txfreq):
+ if _mem.txfreq.get_raw() == b"\xFF\xFF\xFF\xFF":
+ mem.duplex = "off"
+ mem.offset = 0
+ elif int(_mem.rxfreq) == int(_mem.txfreq):
mem.duplex = ""
mem.offset = 0
else:
@@ -464,8 +481,9 @@ class RB28Radio(chirp_common.CloneModeRadio):
mem.extra.append(rset)
_obj = self._memobj.bclo
- key = "chnl_%i" % (mem.number)
- rs = RadioSettingValueBoolean(getattr(_obj, "chnl_%i" % (mem.number)))
+ key = "bclo"
+ rs = RadioSettingValueBoolean(
+ getattr(_obj, "chnl_%i" % mem.number))
rset = RadioSetting(key, "Busy Channel Lockout", rs)
mem.extra.append(rset)
@@ -575,8 +593,9 @@ class RB28Radio(chirp_common.CloneModeRadio):
_mem.highpower = mem.power == self.POWER_LEVELS[0]
for setting in mem.extra:
- if setting.get_name().startswith("chnl_"):
- setattr(self._memobj.bclo, setting.get_name(), setting.value)
+ if setting.get_name() == "bclo":
+ setattr(self._memobj.bclo,
+ "chnl_%i" % mem.number, setting.value)
else:
setattr(_mem, setting.get_name(), setting.value)
@@ -609,9 +628,10 @@ class RB28Radio(chirp_common.CloneModeRadio):
rset = RadioSetting("backlight", "Back Light", rs)
basic.append(rset)
- rs = RadioSettingValueInteger(0, 9, _settings.volume)
- rset = RadioSetting("volume", "Volume", rs)
- basic.append(rset)
+ if self._has_volume:
+ rs = RadioSettingValueInteger(0, 9, _settings.volume)
+ rset = RadioSetting("volume", "Volume", rs)
+ basic.append(rset)
rs = RadioSettingValueInteger(0, 10, _settings.tone)
rset = RadioSetting("tone", "Tone", rs)
@@ -621,14 +641,15 @@ class RB28Radio(chirp_common.CloneModeRadio):
rset = RadioSetting("chnumber", "Channel Number", rs)
basic.append(rset)
- if self.MODEL == "RB28":
+ if self._has_wxchnumber:
rs = RadioSettingValueInteger(1, 11, _settings.wxchnumber + 1)
rset = RadioSetting("wxchnumber", "Weather Channel Number", rs)
basic.append(rset)
- rs = RadioSettingValueBoolean(_settings.autokeylock)
- rset = RadioSetting("autokeylock", "Auto Key Lock", rs)
- basic.append(rset)
+ if self._has_autokeylock:
+ rs = RadioSettingValueBoolean(_settings.autokeylock)
+ rset = RadioSetting("autokeylock", "Auto Key Lock", rs)
+ basic.append(rset)
rs = RadioSettingValueBoolean(_settings.save)
rset = RadioSetting("save", "Battery Save", rs)
@@ -638,6 +659,11 @@ class RB28Radio(chirp_common.CloneModeRadio):
rset = RadioSetting("roger", "End Tone", rs)
basic.append(rset)
+ if self._has_vibrate:
+ rs = RadioSettingValueBoolean(_settings.vibrate)
+ rset = RadioSetting("vibrate", "Vibrate", rs)
+ basic.append(rset)
+
rs = RadioSettingValueBoolean(_settings.beep)
rset = RadioSetting("beep", "Beep", rs)
basic.append(rset)
@@ -651,9 +677,14 @@ class RB28Radio(chirp_common.CloneModeRadio):
rset = RadioSetting("wxwarn", "Weather Warn", rs)
basic.append(rset)
- rs = RadioSettingValueBoolean(_settings.keylock)
- rset = RadioSetting("keylock", "Key Lock", rs)
- basic.append(rset)
+ if self._has_keylock48:
+ rs = RadioSettingValueBoolean(_settings.keylock48)
+ rset = RadioSetting("keylock48", "Key Lock", rs)
+ basic.append(rset)
+ else:
+ rs = RadioSettingValueBoolean(_settings.keylock)
+ rset = RadioSetting("keylock", "Key Lock", rs)
+ basic.append(rset)
rs = RadioSettingValueList(VOXL_LIST,
current_index=_settings.voxl)
@@ -665,15 +696,16 @@ class RB28Radio(chirp_common.CloneModeRadio):
rset = RadioSetting("voxd", "Vox Delay", rs)
basic.append(rset)
- rs = RadioSettingValueList(self.PFKEY_LIST,
- current_index=_settings.pfkey_lt)
- rset = RadioSetting("pfkey_lt", "Key Set < Long", rs)
- basic.append(rset)
+ if self._has_pfkey:
+ rs = RadioSettingValueList(self.PFKEY_LIST,
+ current_index=_settings.pfkey_lt)
+ rset = RadioSetting("pfkey_lt", "Key Set < Long", rs)
+ basic.append(rset)
- rs = RadioSettingValueList(self.PFKEY_LIST,
- current_index=_settings.pfkey_gt)
- rset = RadioSetting("pfkey_gt", "Key Set > Long", rs)
- basic.append(rset)
+ rs = RadioSettingValueList(self.PFKEY_LIST,
+ current_index=_settings.pfkey_gt)
+ rset = RadioSetting("pfkey_gt", "Key Set > Long", rs)
+ basic.append(rset)
return top
@@ -710,12 +742,6 @@ class RB28Radio(chirp_common.CloneModeRadio):
LOG.debug(element.get_name())
raise
- @classmethod
- def match_model(cls, filedata, filename):
- # Radios that have always been post-metadata, so never do
- # old-school detection
- return False
-
@directory.register
class RB628Radio(RB28Radio):
@@ -734,3 +760,68 @@ class RB628Radio(RB28Radio):
)
_frs = False
_pmr = True
+ _has_wxchnumber = False
+
+
+@directory.register
+class RB48Radio(RB28Radio):
+ """RETEVIS RB48"""
+ VENDOR = "Retevis"
+ MODEL = "RB48"
+
+ POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.00),
+ chirp_common.PowerLevel("Low", watts=0.50)]
+
+ VALID_BANDS = [(400000000, 520000000)]
+
+ _magic = b"PHOGR[" + b"\x17"
+ _fingerprint = [b"P32073" + b"\x02\xFF", ]
+ _upper = 22
+ _mem_params = (_upper, # number of channels
+ )
+ _frs = False # Sold as FRS radio but supports full band TX/RX
+ _duplexes = ["", "+", "-", "split"]
+ _has_volume = False
+ _has_autokeylock = False
+ _has_pfkey = False
+ _has_wxchnumber = True
+ _has_vibrate = True
+ _has_keylock48 = True
+
+ _ranges = [
+ (0x0000, 0x0160),
+ ]
+ _memsize = 0x0800
+
+
+@directory.register
+class RB648Radio(RB28Radio):
+ """RETEVIS RB648"""
+ VENDOR = "Retevis"
+ MODEL = "RB648"
+
+ POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.00),
+ chirp_common.PowerLevel("Low", watts=0.50)]
+
+ VALID_BANDS = [(400000000, 520000000)]
+
+ _magic = b"PHOGRQp"
+ _fingerprint = [b"P32073" + b"\x02\xFF", ]
+ _upper = 16
+ _mem_params = (_upper, # number of channels
+ )
+
+ _frs = False
+ _pmr = False # Sold as PMR radio but supports full band TX/RX
+ _duplexes = ["", "+", "-", "split"]
+ _has_volume = False
+ _has_autokeylock = False
+ _has_pfkey = False
+ _has_wxchnumber = False
+ _has_vibrate = True
+ _has_keylock48 = True
+
+ _ranges = [
+ (0x0000, 0x0160),
+ ]
+ _memsize = 0x0800
diff --git a/chirp/drivers/retevis_rt18.py b/chirp/drivers/retevis_rt18.py
new file mode 100644
index 0000000..448fb08
--- /dev/null
+++ b/chirp/drivers/retevis_rt18.py
@@ -0,0 +1,190 @@
+# Copyright 2026
+#
+# EXPERIMENTAL / reverse-engineered driver for the Retevis RT18.
+#
+# The clone protocol and 16-channel memory layout were derived from
+# passive USB capture analysis (Wireshark + USBPcap) of the vendor's
+# Windows CPS talking to a real RT18 over its programming cable. Treat
+# with caution:
+#
+# * Channel memory (frequency, tones, power, narrow/wide, scan add,
+# busy lock, scramble, compander, spec code) is expected to read
+# correctly -- the block-read protocol and the 16-channel/16-byte
+# layout at 0x0010-0x0110 were directly confirmed against captured
+# traffic. Reprogramming squelch tone/DCS code, wide/narrowband,
+# and squelch level was tested end-to-end on a real unit (CHIRP
+# write, then read back with the vendor CPS) and matched.
+# * The rest of the "Other"/settings screen (timeout timer, VOX,
+# beep, scan mode, battery save, etc.) is INHERITED UNCHANGED from
+# the Radtel T18 base class and has NOT been individually tested
+# on a real RT18 yet -- the exact offsets may differ. Don't trust
+# those specific values until confirmed.
+# * The 6-digit programming password (separate "Password" settings
+# group below) IS confirmed against a real "set password" capture
+# (rt18_write_password_to_radio.pcapng) and was also tested
+# end-to-end on a real unit (CHIRP write, then read back with the
+# vendor CPS) -- see _PASSWORD_ADDR.
+# * ALWAYS do a "read from radio" and save the image before ever
+# attempting a write, so there is a known-good backup.
+#
+# 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 time
+
+from chirp import chirp_common, directory, errors
+from chirp.drivers import radtel_t18 as t18
+from chirp.settings import RadioSetting, RadioSettingGroup, \
+ RadioSettingValueString
+
+# Offset/length of the 6-digit programming password inside the memory
+# image, confirmed against rt18_write_password_to_radio.pcapng: writing
+# a full image with the password set to "123456" sends a block-write of
+# `01 02 03 04 05 06 00 ff` at address 0x03B0 -- one raw byte per digit
+# (not ASCII), followed by 2 bytes that stay `00 ff` whether or not a
+# password is set (unknown/reserved). All-0xFF digits means "no
+# password", matching what the extra 0x05 handshake step reads back.
+_PASSWORD_ADDR = 0x03B0
+_PASSWORD_LEN = 6
+_PASSWORD_BLANK = b"\xff" * _PASSWORD_LEN
+
+
+@directory.register
+class RT18Radio(t18.T18Radio):
+ """Retevis RT18"""
+
+ VENDOR = "Retevis"
+ MODEL = "RT18"
+
+ BLOCK_SIZE = 0x08
+ CMD_EXIT = b"b"
+ # Confirmed by capture: no per-block ACK after a block *read*
+ # (unlike most other T18 siblings, which do ACK_BLOCK = True).
+ ACK_BLOCK = False
+
+ # Handshake magic, captured verbatim from a real "Read from radio"
+ # session: b"\x02" + this string.
+ _magic = b"JSOGRAP"
+
+ # NOTE: unlike most T18 siblings (which check for a text string like
+ # b"SMP558..."), the 8-byte ident this radio returns does not look
+ # like a text fingerprint. Originally captured as:
+ # 06 03 e8 08 ff ff ff ff
+ # ...but a real unit (see git history) responded instead with
+ # 06 00 00 00 00 00 00 00
+ # confirming this is NOT a fixed brand string -- only the leading
+ # 0x06 (which is just CMD_ACK, echoed as the first byte of the
+ # ident reply) is consistent; the remaining bytes vary with radio
+ # state (e.g. programmed vs. blank). So only match on that.
+ _fingerprint = [b"\x06"]
+
+ _upper = 16
+ _mem_params = _upper
+ _frs = _frs16 = _murs = _pmr = _gmrs = False
+ _echo = False
+ _reserved = False
+
+ _ranges = [
+ (0x0000, 0x03F0),
+ ]
+ _memsize = 0x03F0
+
+ VALID_BANDS = [(400000000, 470000000)]
+
+ POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
+ chirp_common.PowerLevel("High", watts=2.00)]
+
+ # 6 raw digit bytes read via the extra 0x05 step during handshake,
+ # or b"\xff\xff\xff\xff\xff\xff" when no password is set. This is
+ # also mirrored at 0x03B0 inside the main memory image -- writing
+ # a full image back (as do_upload always does) rewrites it too.
+ _password = b""
+
+ def _enter_programming_mode(self):
+ """Identical handshake to the Radtel T18 family (magic + ident
+ + ack), plus one extra step this RT18 firmware does before the
+ normal block read/write loop: a single 0x05 command that
+ returns a 6-byte "password" block (raw digit bytes, or 0xFF x6
+ when no password is set), acknowledged the same way as a
+ channel block."""
+ # Both captures (read and write sessions) show the vendor CPS
+ # asserting DTR then RTS on the cable, then waiting ~120-130ms
+ # before writing the magic string -- CHIRP's generic serial-open
+ # asserts both lines but writes the magic immediately, which can
+ # race the radio's cable/UART chip if the port was very recently
+ # opened/closed (observed as an intermittent "No response from
+ # radio" on repeated clone attempts). Mirror the vendor's delay.
+ time.sleep(0.15)
+ t18.T18Radio._enter_programming_mode(self)
+
+ serial = self.pipe
+ try:
+ self.pipe.log("RT18 password step")
+ serial.write(b"\x05")
+ if self._echo:
+ serial.read(1) # Chew the echo
+ self._password = serial.read(6)
+ serial.write(t18.CMD_ACK)
+ if self._echo:
+ serial.read(1) # Chew the echo
+ ack = serial.read(1)
+ except Exception:
+ raise errors.RadioError(
+ "Error communicating with radio (password step)")
+
+ if ack != t18.CMD_ACK:
+ raise errors.RadioError("Bad ACK after password step")
+
+ def _rt18_get_password(self):
+ raw = self._mmap.get(_PASSWORD_ADDR, _PASSWORD_LEN)
+ if raw == _PASSWORD_BLANK:
+ return ""
+ return "".join(str(b) for b in raw if b != 0xFF)
+
+ def _rt18_apply_password(self, setting):
+ digits = [int(c) for c in str(setting.value).strip()]
+ raw = bytes(digits) + _PASSWORD_BLANK[len(digits):]
+ self._mmap.set(_PASSWORD_ADDR, raw)
+
+ def get_settings(self):
+ top = t18.T18Radio.get_settings(self)
+
+ # The vendor CPS for the RT18 has no "Voice prompts" control --
+ # unlike its T18 siblings, this radio doesn't seem to have voice
+ # prompts at all. Drop the setting the base class adds
+ # unconditionally so we don't expose a non-existent feature.
+ basic = top[0]
+ if "voiceprompt" in basic:
+ del basic[basic["voiceprompt"]]
+
+ password = RadioSettingGroup("password", "Password")
+ top.append(password)
+
+ rs = RadioSetting(
+ "rt18_password", "Programming password (blank = disabled)",
+ RadioSettingValueString(0, _PASSWORD_LEN,
+ self._rt18_get_password(),
+ autopad=False,
+ charset="0123456789"))
+ rs.set_doc(
+ "Password required (on the radio's vendor CPS) to "
+ "enter programming mode. 1-6 digits, or blank to disable "
+ "password protection. Change this field and upload to set a "
+ "new password, or clear it and upload to remove password "
+ "protection entirely. Confirmed via passive USB capture of a "
+ "real 'set password' session; not confirmed to actually gate "
+ "anything on the radio side beyond what was observed.")
+ rs.set_apply_callback(self._rt18_apply_password)
+ password.append(rs)
+
+ return top
diff --git a/chirp/drivers/retevis_rt21.py b/chirp/drivers/retevis_rt21.py
index f0c05b1..dfb5289 100644
--- a/chirp/drivers/retevis_rt21.py
+++ b/chirp/drivers/retevis_rt21.py
@@ -557,6 +557,43 @@ struct {
} levels[30];
"""
+MEM_FORMAT_RT86A = MEM_FORMAT_RT86 + """
+#seekto 0x00BD;
+struct {
+ u8 micgain; // MIC Gain
+ u8 txprompt; // TX Prompt Tone
+ u8 removectdcs; // Remove CT/DCS
+} rt86a_keys;
+
+#seekto 0x00CD;
+struct {
+ u8 pf1_short; // PF1 Short Press
+ u8 pf1_long; // PF1 Long Press
+ u8 pf2_short; // PF2 Short Press
+} rt86a_pf;
+
+#seekto 0x00DD;
+struct {
+ u8 pf2_long; // PF2 Long Press
+ u8 groupcall; // Group Call Channel
+ u8 reverttime; // Group Call Revert Time
+} rt86a_group;
+
+#seekto 0x00ED;
+struct {
+ u8 pttrevert; // Group Call PTT Revert
+ u8 txendtone; // TX End Tone
+ u8 wirelesscopy; // Wireless Copy
+} rt86a_flags;
+
+#seekto 0x033D;
+struct {
+ u8 vox; // VOX Function
+ u8 voxl; // VOX Level
+ u8 voxd; // VOX Delay
+} rt86a;
+"""
+
CMD_ACK = b"\x06"
ALARM_LIST = ["Local Alarm", "Remote Alarm"]
@@ -618,6 +655,11 @@ PFKEY_CHOICES = ["None", "Monitor", "Scan", "Scramble", "VOX", "Alarm"]
PFKEY_VALUES = [0x0F, 0x04, 0x06, 0x08, 0x09, 0x0A]
TOPKEY_CHOICES = ["None", "Alarming"]
TOPKEY_VALUES = [0xFF, 0x0C]
+RT86A_PFKEY_SHORT_LIST = ["None", "Monitor", "Scan", "Warn",
+ "Power Change", "VOX", "Channel Lock"]
+RT86A_PFKEY_LONG_LIST = RT86A_PFKEY_SHORT_LIST + ["Group Call", "Transmit"]
+RT86A_WARN_LIST = ["Off", "Local Alarm", "Remote Alarm"]
+RT86A_REVERT_LIST = ["%d seconds" % x for x in range(15, 615, 15)]
GMRS_FREQS1 = [462562500, 462587500, 462612500, 462637500, 462662500,
462687500, 462712500]
@@ -2621,3 +2663,127 @@ class RT86SRadio(RT21Radio):
mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0',
'bytecnt': 4}
self._memobj = bitwise.parse(MEM_FORMAT_RT86 % mem_params, self._mmap)
+
+
+@directory.register
+class RT86ARadio(RT86SRadio):
+ """RETEVIS RT86A"""
+ VENDOR = "Retevis"
+ MODEL = "RT86A"
+
+ # The RT86A shares the RT86S memory layout but uses a distinct
+ # programming magic and identification string.
+ _magic = b"PHOGR6" + b"\x83"
+ _fingerprint = [b"P32073" + b"\x02\xFF", ]
+
+ def process_mmap(self):
+ mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0',
+ 'bytecnt': 4}
+ self._memobj = bitwise.parse(MEM_FORMAT_RT86A % mem_params,
+ self._mmap)
+
+ def get_settings(self):
+ _settings = self._memobj.settings
+ _keys = self._memobj.rt86a_keys
+ _pf = self._memobj.rt86a_pf
+ _group = self._memobj.rt86a_group
+ _flags = self._memobj.rt86a_flags
+ _rt86a = self._memobj.rt86a
+
+ top = RadioSettings()
+ basic = RadioSettingGroup("basic", "Basic Settings")
+ top.append(basic)
+
+ rs = RadioSettingValueInteger(0, 9, _settings.squelch)
+ basic.append(RadioSetting("squelch", "Squelch Level", rs))
+
+ rs = RadioSettingValueList(TIMEOUTTIMER_LIST,
+ current_index=_settings.tot)
+ basic.append(RadioSetting("tot", "Time-out Timer", rs))
+
+ rs = RadioSettingValueList(VOICE_LIST2,
+ current_index=_settings.voice)
+ basic.append(RadioSetting("voice", "Voice Prompts", rs))
+
+ rs = RadioSettingValueBoolean(_settings.save)
+ basic.append(RadioSetting("save", "Battery Save", rs))
+
+ rs = RadioSettingValueBoolean(_settings.beep)
+ basic.append(RadioSetting("beep", "Beep", rs))
+
+ rs = RadioSettingValueList(SAVE_LIST,
+ current_index=_settings.savem)
+ basic.append(RadioSetting("savem", "Battery Save Mode", rs))
+
+ rs = RadioSettingValueList(RT86A_WARN_LIST,
+ current_index=_settings.warn)
+ basic.append(RadioSetting("warn", "Warn Mode", rs))
+
+ rs = RadioSettingValueList(MICGAIN_LIST,
+ current_index=_keys.micgain)
+ basic.append(RadioSetting("rt86a_keys.micgain", "MIC Gain", rs))
+
+ rs = RadioSettingValueList(SPECIAL_LIST,
+ current_index=_settings.tailmode)
+ basic.append(RadioSetting("tailmode", "QT/DQT Tail Mode", rs))
+
+ rs = RadioSettingValueBoolean(not _settings.tail)
+ basic.append(RadioSetting("tail", "QT/DQT Tail", rs))
+
+ rs = RadioSettingValueBoolean(_keys.txprompt)
+ basic.append(RadioSetting("rt86a_keys.txprompt",
+ "TX Prompt Tone", rs))
+
+ rs = RadioSettingValueBoolean(_keys.removectdcs)
+ basic.append(RadioSetting("rt86a_keys.removectdcs",
+ "Remove CT/DCS", rs))
+
+ rs = RadioSettingValueBoolean(_flags.txendtone)
+ basic.append(RadioSetting("rt86a_flags.txendtone",
+ "TX End Tone", rs))
+
+ rs = RadioSettingValueBoolean(_flags.wirelesscopy)
+ basic.append(RadioSetting("rt86a_flags.wirelesscopy",
+ "Wireless Copy", rs))
+
+ rs = RadioSettingValueBoolean(_rt86a.vox)
+ basic.append(RadioSetting("rt86a.vox", "VOX Function", rs))
+
+ rs = RadioSettingValueList(VOXL_LIST,
+ current_index=_rt86a.voxl)
+ basic.append(RadioSetting("rt86a.voxl", "VOX Level", rs))
+
+ rs = RadioSettingValueList(VOXD_LIST,
+ current_index=_rt86a.voxd)
+ basic.append(RadioSetting("rt86a.voxd", "VOX Delay", rs))
+
+ rs = RadioSettingValueList(GROUPCH_LIST,
+ current_index=_group.groupcall)
+ basic.append(RadioSetting("rt86a_group.groupcall",
+ "Group Call Channel", rs))
+
+ rs = RadioSettingValueList(RT86A_REVERT_LIST,
+ current_index=_group.reverttime)
+ basic.append(RadioSetting("rt86a_group.reverttime",
+ "Group Call Revert Time", rs))
+
+ rs = RadioSettingValueBoolean(_flags.pttrevert)
+ basic.append(RadioSetting("rt86a_flags.pttrevert",
+ "Group Call PTT Revert", rs))
+
+ for name, label, value in [
+ ("rt86a_pf.pf1_short", "PF1 Short Press", _pf.pf1_short),
+ ("rt86a_pf.pf1_long", "PF1 Long Press", _pf.pf1_long),
+ ("rt86a_pf.pf2_short", "PF2 Short Press", _pf.pf2_short),
+ ("rt86a_group.pf2_long", "PF2 Long Press",
+ _group.pf2_long)]:
+ if name.endswith("_short"):
+ options = RT86A_PFKEY_SHORT_LIST
+ else:
+ options = RT86A_PFKEY_LONG_LIST
+ if value >= len(options):
+ value = 0
+ rs = RadioSettingValueList(options, current_index=value)
+ basic.append(RadioSetting(name, label, rs))
+
+ return top
diff --git a/chirp/drivers/retevis_rt22.py b/chirp/drivers/retevis_rt22.py
index 7930a81..ac340e3 100644
--- a/chirp/drivers/retevis_rt22.py
+++ b/chirp/drivers/retevis_rt22.py
@@ -519,7 +519,7 @@ class RT22Radio(chirp_common.CloneModeRadio):
"Sets how strong a received signal must be before the speaker "
"unmutes. 0 leaves the squelch open so you hear noise all the "
"time, higher values reject more weak signals and noise. Raise "
- "this value if the radio keeps opening on interference, lower "
+ "this value if the speaker keeps unmuting on interference, lower "
"it if distant stations are being cut off.")
basic.append(rs)
@@ -538,9 +538,8 @@ class RT22Radio(chirp_common.CloneModeRadio):
RadioSettingValueList(
VOICE_LIST, current_index=_settings.voice))
rs.set_doc(
- "Announces the channel number out loud in the selected language "
- "each time you change channel. Useful on a radio without a "
- "display. Off silences the announcements.")
+ "Selects the language for spoken radio-operation prompts, or "
+ "disables those prompts.")
basic.append(rs)
rs = RadioSetting("pf2key", "PF2 Key",
@@ -568,7 +567,7 @@ class RT22Radio(chirp_common.CloneModeRadio):
rs.set_doc(
"Sets the VOX sensitivity. Too sensitive a setting keys the "
"transmitter on the noise around the radio, too insensitive a "
- "setting fails to pick up your voice. OFF disables VOX.")
+ "setting fails to pick up your voice.")
basic.append(rs)
rs = RadioSetting("voxdelay", "VOX Delay Time (Old | New)",
@@ -584,10 +583,11 @@ class RT22Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("save", "Battery Save",
RadioSettingValueBoolean(_settings.save))
rs.set_doc(
- "Cuts standby power consumption by dozing the receiver once no "
- "signal has been received for a few seconds. It considerably "
- "extends battery life, at the cost of occasionally clipping the "
- "first moment of an incoming transmission.")
+ "Cuts standby power consumption by switching the receiver off and "
+ "on in a repeating cycle once no signal has been received for a "
+ "few seconds. It considerably extends battery life, at the cost "
+ "of occasionally clipping the first moment of an incoming "
+ "transmission.")
basic.append(rs)
rs = RadioSetting("beep", "Beep",
diff --git a/chirp/drivers/retevis_rt76p.py b/chirp/drivers/retevis_rt76p.py
index db928af..8818044 100644
--- a/chirp/drivers/retevis_rt76p.py
+++ b/chirp/drivers/retevis_rt76p.py
@@ -980,9 +980,3 @@ class RT76PRadio(chirp_common.CloneModeRadio):
except Exception:
LOG.debug(element.get_name())
raise
-
- @classmethod
- def match_model(cls, filedata, filename):
- # This radio has always been post-metadata, so never do
- # old-school detection
- return False
diff --git a/chirp/drivers/retevis_rt97s.py b/chirp/drivers/retevis_rt97s.py
new file mode 100644
index 0000000..349cf40
--- /dev/null
+++ b/chirp/drivers/retevis_rt97s.py
@@ -0,0 +1,322 @@
+# Copyright 2026
+#
+# 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 struct
+import logging
+
+from chirp import bitwise, checksum, chirp_common, directory, errors, memmap
+from chirp import kenwood_tone
+from chirp.settings import MemSetting, RadioSettingGroup, RadioSettings
+from chirp.settings import RadioSettingValueBoolean, RadioSettingValueList
+
+LOG = logging.getLogger(__name__)
+
+MEM_FORMAT = """
+#seekto 0x0010;
+struct {
+ lbcd rxfreq[4];
+ lbcd txfreq[4];
+ ul16 rxtone;
+ ul16 txtone;
+ u8 unknown12;
+ u8 unknown13;
+ u8 unknown_hi:3,
+ highpower:1,
+ narrow:1,
+ unknown_lo:3;
+ u8 unknown15;
+} memory[16];
+
+#seekto 0x0330;
+struct {
+ u8 unknown0_hi:7,
+ tail:1;
+ u8 opt_bit7:1,
+ transit:1,
+ opt_bit5:1,
+ keylock:1,
+ opt_lo:4;
+ u8 unknown1;
+ u8 unknown2;
+ u8 squelch;
+ u8 unknown3;
+ u8 relay;
+} settings;
+"""
+
+MEM_SIZE = 0x03C0
+BLOCK_SIZE = 0x10
+# The factory program reads 0x0000-0x03C0 and writes every block except
+# 0x0350-0x0370, which is a calibration curve it leaves on the radio.
+WRITE_RANGES = [(0x0000, 0x0350), (0x0380, 0x03C0)]
+CMD_ACK = b"\x06"
+# Low power level is inferred from Internet sources
+POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5.00),
+ chirp_common.PowerLevel("High", watts=10.00)]
+# Repeater receive is the 467 MHz input. Duplex is minus, so the
+# 462 MHz transmit frequencies are 5 MHz below these.
+OFFSET = 5000000
+RX_FREQS = [467550000, 467575000, 467600000, 467625000,
+ 467650000, 467675000, 467700000, 467725000]
+TX_FREQS = [freq - OFFSET for freq in RX_FREQS]
+SQUELCH_CHOICES = ["%i" % i for i in range(10)]
+RELAY_CHOICES = ["%i" % i for i in range(10)]
+
+
+def _read_exact(pipe, count):
+ data = b""
+ while len(data) < count:
+ chunk = pipe.read(count - len(data))
+ if not chunk:
+ break
+ data += chunk
+ return data
+
+
+def _enter_programming_mode(radio):
+ pipe = radio.pipe
+ pipe.timeout = 2
+ pipe.write(b"PROGRAM")
+ ack = _read_exact(pipe, 1)
+ if not ack:
+ raise errors.RadioNoResponse()
+ if ack != CMD_ACK:
+ raise errors.RadioError("Radio refused to enter programming mode")
+
+ pipe.write(b"\x02")
+ ident = _read_exact(pipe, 8)
+ if len(ident) != 8:
+ raise errors.RadioNoResponse()
+ if not ident.startswith(b"P3118"):
+ raise errors.RadioError(
+ "Radio identification failed: %r" % ident)
+
+ pipe.write(CMD_ACK)
+ ack = _read_exact(pipe, 1)
+ if ack != CMD_ACK:
+ raise errors.RadioError("Radio refused to enter programming mode")
+
+ pipe.write(b"\x07")
+ ack = _read_exact(pipe, 1)
+ if ack != b"\x4e":
+ raise errors.RadioError("Radio refused to enter programming mode")
+ return ident
+
+
+def _exit_programming_mode(radio):
+ radio.pipe.write(b"E")
+
+
+def _read_block(radio, addr):
+ cmd = struct.pack(">cHB", b"R", addr, BLOCK_SIZE)
+ radio.pipe.write(cmd)
+ response = _read_exact(radio.pipe, 4 + BLOCK_SIZE + 1)
+ expected = struct.pack(">cHB", b"W", addr, BLOCK_SIZE)
+ if len(response) != 4 + BLOCK_SIZE + 1 or response[:4] != expected:
+ raise errors.RadioError("No block at %04x" % addr)
+ data = response[4:4 + BLOCK_SIZE]
+ if checksum.checksum_8bit(data) != response[-1]:
+ raise errors.RadioError("Bad checksum at %04x" % addr)
+ return data
+
+
+def _write_block(radio, addr):
+ data = radio.get_mmap()[addr:addr + BLOCK_SIZE]
+ cmd = struct.pack(">cHB", b"W", addr, BLOCK_SIZE)
+ radio.pipe.write(cmd + data + bytes([checksum.checksum_8bit(data)]))
+ ack = _read_exact(radio.pipe, 1)
+ if ack != CMD_ACK:
+ raise errors.RadioError("Radio refused block at %04x" % addr)
+
+
+def do_download(radio):
+ _enter_programming_mode(radio)
+ data = b""
+ status = chirp_common.Status()
+ status.msg = "Cloning from radio"
+ status.max = MEM_SIZE
+ for addr in range(0, MEM_SIZE, BLOCK_SIZE):
+ status.cur = addr + BLOCK_SIZE
+ radio.status_fn(status)
+ data += _read_block(radio, addr)
+ _exit_programming_mode(radio)
+ return memmap.MemoryMapBytes(data)
+
+
+def do_upload(radio):
+ _enter_programming_mode(radio)
+ status = chirp_common.Status()
+ status.msg = "Cloning to radio"
+ blocks = []
+ for start, end in WRITE_RANGES:
+ blocks.extend(range(start, end, BLOCK_SIZE))
+ status.max = len(blocks)
+ for i, addr in enumerate(blocks, start=1):
+ status.cur = i
+ radio.status_fn(status)
+ _write_block(radio, addr)
+ _exit_programming_mode(radio)
+
+
+@directory.register
+class RT97SRadio(chirp_common.CloneModeRadio):
+ """Retevis RT97S"""
+ VENDOR = "Retevis"
+ MODEL = "RT97S"
+ BAUD_RATE = 9600
+ # CTCSS is BCD of Hz*10. DCS is BCD with 0x8000 set and 0x4000 for
+ # reverse. An unused tone is 0xFFFF.
+ _tone_model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x8000, pol_mask=0x4000, tone_init=0xFFFF,
+ tone_flag=0x0000, dcs_enc_base=16, tone_enc_base=16)
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_settings = True
+ rf.has_bank = False
+ rf.has_name = False
+ rf.has_tuning_step = False
+ rf.has_nostep_tuning = True
+ rf.has_rx_dtcs = True
+ rf.has_ctone = True
+ rf.has_cross = True
+ rf.can_odd_split = False
+ rf.valid_modes = ["FM", "NFM"]
+ rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
+ rf.valid_cross_modes = ["Tone->Tone", "DTCS->", "->DTCS",
+ "Tone->DTCS", "DTCS->Tone", "->Tone",
+ "DTCS->DTCS"]
+ rf.valid_duplexes = ["-"]
+ rf.valid_skips = []
+ rf.valid_power_levels = POWER_LEVELS
+ rf.valid_bands = [(TX_FREQS[0], TX_FREQS[-1] + 25000),
+ (RX_FREQS[0], RX_FREQS[-1] + 25000)]
+ rf.memory_bounds = (1, 16)
+ return rf
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.info = _(
+ "Channel frequencies are from the repeater's point of view. "
+ "The receive frequency is the 467 MHz input. Duplex is minus "
+ "and the offset is 5 MHz, so the repeater transmits on the "
+ "462 MHz output. A station using this repeater listens on "
+ "the repeater output and transmits on the input.")
+ return rp
+
+ def sync_in(self):
+ try:
+ self._mmap = do_download(self)
+ except errors.RadioError:
+ raise
+ except Exception as exc:
+ raise errors.RadioError(str(exc))
+ self.process_mmap()
+
+ def sync_out(self):
+ try:
+ do_upload(self)
+ except errors.RadioError:
+ raise
+ except Exception as exc:
+ raise errors.RadioError(str(exc))
+
+ 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])
+
+ def get_memory(self, number):
+ _mem = self._memobj.memory[number - 1]
+ mem = chirp_common.Memory()
+ mem.number = number
+ if _mem.get_raw() == b"\xff" * 16:
+ mem.empty = True
+ return mem
+
+ mem.freq = int(_mem.rxfreq) * 10
+ mem.duplex = "-"
+ mem.offset = mem.freq - int(_mem.txfreq) * 10
+ mem.immutable = ["duplex", "offset"]
+ mem.mode = "NFM" if _mem.narrow else "FM"
+ mem.power = POWER_LEVELS[1 if _mem.highpower else 0]
+ self._tone_model.get_tone(_mem, mem)
+ return mem
+
+ def set_memory(self, mem):
+ _mem = self._memobj.memory[mem.number - 1]
+ if mem.empty:
+ _mem.fill_raw(b"\xFF")
+ return
+
+ if _mem.get_raw() == b"\xff" * 16:
+ _mem.fill_raw(b"\x00")
+
+ _mem.rxfreq = mem.freq // 10
+ _mem.txfreq = (mem.freq - mem.offset) // 10
+
+ self._tone_model.set_tone(mem, _mem)
+ _mem.narrow = mem.mode == "NFM"
+ if mem.power is not None:
+ _mem.highpower = mem.power == POWER_LEVELS[1]
+
+ def validate_memory(self, mem):
+ msgs = super().validate_memory(mem)
+ if mem.empty:
+ return msgs
+ if mem.freq not in RX_FREQS:
+ msgs.append(chirp_common.ValidationError(
+ "Receive frequency must be a GMRS repeater input, "
+ "467.550 through 467.725 MHz"))
+ if mem.offset != OFFSET:
+ msgs.append(chirp_common.ValidationWarning(
+ "GMRS repeater offset must be 5.000 MHz below the "
+ "receive frequency"))
+ return msgs
+
+ def get_settings(self):
+ _settings = self._memobj.settings
+ group = RadioSettingGroup("basic", "Repeater")
+
+ group.append(MemSetting(
+ "settings.squelch", "Squelch Level",
+ RadioSettingValueList(SQUELCH_CHOICES,
+ current_index=int(_settings.squelch))))
+
+ group.append(MemSetting(
+ "settings.relay", "Relay Delay",
+ RadioSettingValueList(RELAY_CHOICES,
+ current_index=int(_settings.relay))))
+
+ transit = MemSetting(
+ "settings.transit", "Transit Function",
+ RadioSettingValueBoolean(_settings.transit))
+ transit.set_warning(
+ _("Disabling Transit Function disables repeating. "
+ "The repeater will not repeat until this setting is enabled."),
+ safe_value=True)
+ group.append(transit)
+ group.append(MemSetting(
+ "settings.keylock", "Key Lock",
+ RadioSettingValueBoolean(_settings.keylock)))
+ group.append(MemSetting(
+ "settings.tail", "Tail Tone Eliminate",
+ RadioSettingValueBoolean(_settings.tail)))
+ return RadioSettings(group)
+
+ def set_settings(self, settings):
+ settings.apply_to(self._memobj)
diff --git a/chirp/drivers/rh5r_v2.py b/chirp/drivers/rh5r_v2.py
index 2f9155c..a08ca7e 100644
--- a/chirp/drivers/rh5r_v2.py
+++ b/chirp/drivers/rh5r_v2.py
@@ -136,7 +136,7 @@ class TYTTHUVF8_V2(chirp_common.CloneModeRadio):
rf.has_rx_dtcs = True
rf.has_settings = False
rf.can_odd_split = False
- rf.valid_duplexes = ['', '-', '+']
+ rf.valid_duplexes = ['', '-', '+', 'off']
rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + "-"
rf.valid_bands = [(136000000, 174000000),
@@ -236,16 +236,20 @@ class TYTTHUVF8_V2(chirp_common.CloneModeRadio):
return mem
mem.freq = int(_mem.rx_freq) * 10
- offset = (int(_mem.tx_freq) - int(_mem.rx_freq)) * 10
- if not offset:
+ if int(_mem.tx_freq) == 0:
mem.offset = 0
- mem.duplex = ''
- elif offset < 0:
- mem.offset = abs(offset)
- mem.duplex = '-'
+ mem.duplex = 'off'
else:
- mem.offset = offset
- mem.duplex = '+'
+ offset = (int(_mem.tx_freq) - int(_mem.rx_freq)) * 10
+ if not offset:
+ mem.offset = 0
+ mem.duplex = ''
+ elif offset < 0:
+ mem.offset = abs(offset)
+ mem.duplex = '-'
+ else:
+ mem.offset = offset
+ mem.duplex = '+'
txmode, txval, txpol = self._decode_tone(_mem.tx_tone)
rxmode, rxval, rxpol = self._decode_tone(_mem.rx_tone)
@@ -270,13 +274,18 @@ class TYTTHUVF8_V2(chirp_common.CloneModeRadio):
_mem.set_raw(b'\x00' * 16)
_mem.rx_freq = mem.freq / 10
- if mem.duplex == '-':
+ if mem.duplex == 'off':
+ tx_freq = 0
+ elif mem.duplex == '-':
mult = -1
+ tx_freq = mem.freq + (mem.offset * mult)
elif not mem.duplex:
mult = 0
+ tx_freq = mem.freq + (mem.offset * mult)
else:
mult = 1
- _mem.tx_freq = (mem.freq + (mem.offset * mult)) / 10
+ tx_freq = mem.freq + (mem.offset * mult)
+ _mem.tx_freq = tx_freq / 10
(txmode, txval, txpol), (rxmode, rxval, rxpol) = \
chirp_common.split_tone_encode(mem)
diff --git a/chirp/drivers/tg_uv2p.py b/chirp/drivers/tg_uv2p.py
index bafeb8c..7cea881 100644
--- a/chirp/drivers/tg_uv2p.py
+++ b/chirp/drivers/tg_uv2p.py
@@ -223,6 +223,11 @@ class QuanshengTGUV2P(chirp_common.CloneModeRadio,
_memsize = 0x2000
@classmethod
+ def match_model(cls, filedata, filename):
+ return (filedata.startswith(b"TG-UV2+ Radio Program Data") and
+ len(filedata) == cls._memsize + 0x30)
+
+ @classmethod
def get_prompts(cls):
rp = chirp_common.RadioPrompts()
rp.experimental = \
@@ -781,8 +786,3 @@ class QuanshengTGUV2P(chirp_common.CloneModeRadio,
except Exception:
LOG.debug(element.get_name())
raise
-
- @classmethod
- def match_model(cls, filedata, filename):
- return (filedata.startswith(b"TG-UV2+ Radio Program Data") and
- len(filedata) == (cls._memsize + 0x30))
diff --git a/chirp/drivers/th350.py b/chirp/drivers/th350.py
index 271d633..38b694d 100644
--- a/chirp/drivers/th350.py
+++ b/chirp/drivers/th350.py
@@ -254,6 +254,11 @@ class Th350Radio(BaofengUVB5):
VENDOR = "TYT"
MODEL = "TH-350"
BAUD_RATE = 9600
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (filedata.startswith(b"TRI350 Radio Program data") and
+ len(filedata) == cls._memsize + 0x30)
SPECIALS = {
"VFO1": -3,
"VFO2": -2,
@@ -391,11 +396,6 @@ class Th350Radio(BaofengUVB5):
return (self._memobj.channels[number - 1],
self._memobj.names[number - 1].name)
- @classmethod
- def match_model(cls, filedata, filename):
- return (filedata.startswith(b"TRI350 Radio Program data") and
- len(filedata) == (cls._memsize + 0x30))
-
# US version has channel names that are 8 characters long
diff --git a/chirp/drivers/th9000.py b/chirp/drivers/th9000.py
index 65b0525..344f8d6 100644
--- a/chirp/drivers/th9000.py
+++ b/chirp/drivers/th9000.py
@@ -447,29 +447,34 @@ def _read(radio, length):
return data
-def _ident(radio):
- radio.pipe.timeout = 1
- exito = False
- for i in range(0, 5):
- _echo_write(radio, b"PROGRAM")
- response = radio.pipe.read(3)
-
- if response == b"QX\06":
- exito = True
- break
-
- # check if we had EXITO
- if exito is False:
- if not response:
- raise errors.RadioNoResponse()
- 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)
+def _enter_program(radio):
+ """Return the interrogate that got QX+ACK.
+ PROGRA: is the TH-9000D Plus command. PROGRAM is the original.
+ Plus must be tried first: a rejected PROGRAM still enters program mode.
+ """
+ radio.pipe.timeout = 1
+ response = b""
+ for cmd in (b"PROGRA:", b"PROGRAM"):
+ for i in range(0, 5):
+ _echo_write(radio, cmd)
+ response = radio.pipe.read(3)
+ LOG.debug("%s reply: %s" % (cmd, util.hexprint(response)))
+ if response == b"QX\x06":
+ return cmd
+ if not response:
+ raise errors.RadioNoResponse()
+ 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)
+
+
+def _confirm_ident(radio):
_echo_write(radio, b"\x02")
response = radio.pipe.read(16)
LOG.debug(util.hexprint(response))
- if response[1:8] != b"TH-9000":
+ # Original ident is TH-9000. Plus ident is ITH-9000.
+ if b"TH-9000" not in response:
LOG.error("Looking for:\n%s" % util.hexprint("TH-9000"))
LOG.error("Response was:\n%s" % util.hexprint(response))
raise errors.RadioError("Unsupported model")
@@ -522,9 +527,11 @@ def _finish(radio):
raise errors.RadioError("Radio did not finish cleanly")
-def do_download(radio):
-
- _ident(radio)
+def do_download(radio, ident=True):
+ # Detection already entered program mode before sync_in().
+ if ident:
+ _enter_program(radio)
+ _confirm_ident(radio)
_memobj = None
data = b""
@@ -546,7 +553,8 @@ def do_download(radio):
def do_upload(radio):
- _ident(radio)
+ _enter_program(radio)
+ _confirm_ident(radio)
for start, end in radio._ranges:
for addr in range(start, end, 0x10):
@@ -606,9 +614,21 @@ class Th9000Radio(chirp_common.CloneModeRadio,
rf.valid_tuning_steps = TUNING_STEPS
return rf
+ _plus_class = None
+
+ @classmethod
+ def detect_from_serial(cls, pipe):
+ """Interrogate before sync_in(). Plus answers PROGRA:, not PROGRAM."""
+ radio = cls(pipe)
+ cmd = _enter_program(radio)
+ if cmd == b"PROGRA:" and cls._plus_class:
+ return cls._plus_class
+ return cls
+
# Do a download of the radio from the serial port
def sync_in(self):
- self._mmap = do_download(self)
+ # detect_from_serial() already entered program mode on this pipe.
+ self._mmap = do_download(self, ident=False)
self.process_mmap()
# Do an upload of the radio to the serial port
@@ -1081,6 +1101,32 @@ class Th9000440Radio(Th9000220Radio):
return match_orig_model(cls, filedata, filename)
+@directory.detected_by(Th9000220Radio)
+class Th9000220PlusRadio(Th9000220Radio):
+ """TYT TH-9000D Plus 220"""
+ MODEL = "TH9000_220"
+ VARIANT = "Plus"
+
+
+@directory.detected_by(Th9000144Radio)
+class Th9000144PlusRadio(Th9000144Radio):
+ """TYT TH-9000D Plus 144"""
+ MODEL = "TH9000_144"
+ VARIANT = "Plus"
+
+
+@directory.detected_by(Th9000440Radio)
+class Th9000440PlusRadio(Th9000440Radio):
+ """TYT TH-9000D Plus 440"""
+ MODEL = "TH9000_440"
+ VARIANT = "Plus"
+
+
+Th9000220Radio._plus_class = Th9000220PlusRadio
+Th9000144Radio._plus_class = Th9000144PlusRadio
+Th9000440Radio._plus_class = Th9000440PlusRadio
+
+
@directory.register
class Lt580VHFRadio(Th9000144Radio):
"""Luiton LT-580 VHF"""
diff --git a/chirp/drivers/th9800.py b/chirp/drivers/th9800.py
index b22ab21..3f378c6 100644
--- a/chirp/drivers/th9800.py
+++ b/chirp/drivers/th9800.py
@@ -1252,12 +1252,6 @@ class RetevisMA1Radio(TYTTH9800Base, chirp_common.CloneModeRadio,
PNLKEY_VALUES = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x12]
@classmethod
- def match_model(cls, filedata, filename):
- # This radio has always been post-metadata, so never do
- # old-school detection
- return False
-
- @classmethod
def get_prompts(cls):
rp = chirp_common.RadioPrompts()
rp.experimental = (
diff --git a/chirp/drivers/thd72.py b/chirp/drivers/thd72.py
index 3fec893..8717b44 100644
--- a/chirp/drivers/thd72.py
+++ b/chirp/drivers/thd72.py
@@ -771,7 +771,5 @@ class THD72Radio(chirp_common.CloneModeRadio):
@classmethod
def match_model(cls, filedata, filename):
- if filename.endswith('.mc4'):
- return True
- else:
- return super(THD72Radio, cls).match_model(filedata, filename)
+ return (filename.endswith('.mc4') or
+ (cls._memsize and len(filedata) == cls._memsize))
diff --git a/chirp/drivers/thd74.py b/chirp/drivers/thd74.py
index fd39a55..2ab46e8 100644
--- a/chirp/drivers/thd74.py
+++ b/chirp/drivers/thd74.py
@@ -557,10 +557,7 @@ class THD74Radio(chirp_common.CloneModeRadio,
@classmethod
def match_model(cls, filedata, filename):
- if filename.endswith('.d74'):
- return True
- else:
- return chirp_common.CloneModeRadio.match_model(filedata, filename)
+ return filename.endswith('.d74')
@directory.register
diff --git a/chirp/drivers/tk280.py b/chirp/drivers/tk280.py
index 68f1bcd..a744d3c 100644
--- a/chirp/drivers/tk280.py
+++ b/chirp/drivers/tk280.py
@@ -15,6 +15,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import collections
+import abc
import itertools
import logging
import struct
@@ -776,7 +777,7 @@ def do_upload(radio):
radio.status_fn(status)
-class TKx80SubdevMeta(type):
+class TKx80SubdevMeta(abc.ABCMeta):
"""Metaclass for generating subdevice subclasses"""
def __new__(cls, name, bases, dct):
return super(TKx80SubdevMeta, cls).__new__(cls, name, bases, dct)
diff --git a/chirp/drivers/tk8160.py b/chirp/drivers/tk8160.py
index fb314aa..126abe2 100644
--- a/chirp/drivers/tk8160.py
+++ b/chirp/drivers/tk8160.py
@@ -73,10 +73,10 @@ struct {
unknown2_01:1,
wide:1;
u8 beatshift:1,
- unknown2_1:1,
+ scrambler:1,
highpower:1,
scanadd:1,
- unknown2_2:4;
+ scramblercode:4; // code - 1
u8 unknown2_3:6,
pttid:2; // 0:off 1:BOT 2:EOT 3:Both
char name[8];
@@ -103,7 +103,7 @@ struct {
// 28=volup 2A=None 15=2-tone 8=AUX 16=Call1 17=Call2 13=ChDn 12=ChUp
// 0B=DisplayCh 09=HornAlert 03=KeyLock 14=Brightness 02=Monitor 25=MonMom
-// 0C=OST 19=PA 1A=SquelchLevel 05=Scan 06=ScanAdd 0A=Scrambler 18=Selcall
+// 0C=OST 19=PA 1A=SquelchLevel 05=Scan 06=ScanAdd 0A=Scrambler 1B=Selcall
// 27=SendGPS 04=TA 28=VolUp 29=VolDn 00=ZoneUp 24=SqlOff 26=SqlOffMom
// 1C=Status 1D=SelCall+Status 01=ZoneDn
#seekto 0x1820;
@@ -145,10 +145,10 @@ _KEYS = [
'2-Tone',
'Call 1',
'Call 2',
- 'Selcall',
+ '?', # 18
'Public Address',
'Squelch Level',
- '?',
+ 'Selcall', # 1B
'Status',
'Selcall+Status',
'?', # 1E
@@ -216,6 +216,17 @@ KEY_NAMES = {
POWER_LEVELS = [chirp_common.PowerLevel('Low', watts=25),
chirp_common.PowerLevel('High', watts=50)]
+BCL_OPTIONS = ['Off', 'Carrier', 'QT/DQT', 'Optional Signaling']
+PTTID_OPTIONS = ['Off', 'BOT', 'EOT', 'Both']
+OPTSIG_OPTIONS = ['Off', 'DTMF', '2-Tone 1', '2-Tone 2', '2-Tone 3',
+ 'FleetSync']
+
+# The ranges KPG writes, in the same frames. It does not write 0x0000-0x001F,
+# which the radio maintains itself, or 0x1740-0x17DF, which holds the radio's
+# model, serial number and what look like alignment values, so an image read
+# from one radio does not overwrite another radio's identity.
+UPLOAD_RANGES = [(0x0020, 0x1740), (0x17E0, 0x3120)]
+
def ends_program(fn):
@functools.wraps(fn)
@@ -290,15 +301,17 @@ def do_upload(radio):
radio.status_fn(status)
LOG.debug('Radio address 0x%04x' % addr)
- for addr in range(0, 0x30E0, 0x40):
- block = data[addr:addr + 0x40]
- hdr = struct.pack('>cHB', b'W', addr, 0x40)
- radio.pipe.write(hdr + block)
- ack = radio.pipe.read(1)
- if ack != b'\x06':
- LOG.error('Expected ack, got %r' % ack)
- raise errors.RadioError('Radio did not ACK block')
- status(addr)
+ for start, end in UPLOAD_RANGES:
+ for addr in range(start, end, 0x40):
+ length = min(0x40, end - addr)
+ block = data[addr:addr + length]
+ hdr = struct.pack('>cHB', b'W', addr, length)
+ radio.pipe.write(hdr + block)
+ ack = radio.pipe.read(1)
+ if ack != b'\x06':
+ LOG.error('Expected ack, got %r' % ack)
+ raise errors.RadioError('Radio did not ACK block')
+ status(addr)
class TKx160Radio(chirp_common.CloneModeRadio):
@@ -308,6 +321,7 @@ class TKx160Radio(chirp_common.CloneModeRadio):
_channels = 128
_power_levels = POWER_LEVELS
_has_zones = True
+ _has_memory_extras = True
_mem_format = mem_format
def sync_in(self):
@@ -554,8 +568,50 @@ class TKx160Radio(chirp_common.CloneModeRadio):
m.mode = 'FM' if _mem.wide else 'NFM'
m.skip = '' if _mem.scanadd else 'S'
+ if self._has_memory_extras:
+ m.extra = self._get_memory_extras(_mem)
+
return m
+ @staticmethod
+ def _get_memory_extras(_mem):
+ optsig = int(_mem.optsig)
+ if optsig >= len(OPTSIG_OPTIONS):
+ LOG.warning('Unknown optional signaling %i, showing Off', optsig)
+ optsig = 0
+
+ extra = settings.RadioSettingGroup('extra', 'Extra')
+ extra.append(settings.MemSetting(
+ 'bcl', 'Busy Channel Lockout',
+ settings.RadioSettingValueList(BCL_OPTIONS,
+ current_index=int(_mem.bcl))))
+ extra.append(settings.MemSetting(
+ 'beatshift', 'Beat Shift',
+ settings.RadioSettingValueBoolean(bool(_mem.beatshift))))
+ extra.append(settings.MemSetting(
+ 'pttid', 'PTT ID',
+ settings.RadioSettingValueList(PTTID_OPTIONS,
+ current_index=int(_mem.pttid))))
+ extra.append(settings.MemSetting(
+ 'pttidmute', 'PTT ID Mute',
+ settings.RadioSettingValueBoolean(bool(_mem.pttidmute))))
+ extra.append(settings.MemSetting(
+ 'compander', 'Compander',
+ settings.RadioSettingValueBoolean(bool(_mem.compander))))
+ extra.append(settings.MemSetting(
+ 'optsig', 'Optional Signaling',
+ settings.RadioSettingValueList(OPTSIG_OPTIONS,
+ current_index=optsig)))
+ extra.append(settings.MemSetting(
+ 'scrambler', 'Scrambler',
+ settings.RadioSettingValueBoolean(bool(_mem.scrambler))))
+ extra.append(settings.MemSetting(
+ 'scramblercode', 'Scrambler Code',
+ settings.RadioSettingValueList(
+ [str(c) for c in range(1, 17)],
+ current_index=int(_mem.scramblercode))))
+ return extra
+
def set_memory(self, mem):
_index_entry, slot = self.check_index(mem.number)
if mem.empty:
@@ -563,7 +619,8 @@ class TKx160Radio(chirp_common.CloneModeRadio):
self._memobj.memories[slot].set_raw(b'\xFF' * 32)
self.delete_from_index(mem.number)
return
- elif slot is None:
+ is_new = slot is None
+ if is_new:
slot = self.next_slot(mem.number)
_mem = self._memobj.memories[slot]
@@ -595,21 +652,24 @@ class TKx160Radio(chirp_common.CloneModeRadio):
_mem.scanadd = mem.skip == ''
_mem.name = mem.name[:8].ljust(8)
- # Set the flags we don't support
- _mem.bcl = 0
- _mem.beatshift = 0
- _mem.pttid = 0
- _mem.compander = 0
- _mem.pttidmute = 0
- _mem.optsig = 0
+ extras = mem.extra if self._has_memory_extras else []
+ if is_new and not extras:
+ # Defaults for the flags in extra, for a new memory only, so that
+ # editing a memory does not undo settings made in KPG
+ _mem.bcl = 0
+ _mem.beatshift = 0
+ _mem.pttid = 0
+ _mem.compander = 0
+ _mem.pttidmute = 0
+ _mem.optsig = 0
+ _mem.scrambler = 0
+ _mem.scramblercode = 0
# Set the unknowns
_mem.unknown1[0] = 0x02
_mem.unknown1[1] = 0x02
_mem.unknown2_0 = 0x0F
_mem.unknown2_01 = 0x00
- _mem.unknown2_1 = 0x00
- _mem.unknown2_2 = 0x00
_mem.unknown2_3 = 0x00
_mem.unknown3_0 = 0x00
_mem.unknown3_1 = 0x00
@@ -617,6 +677,9 @@ class TKx160Radio(chirp_common.CloneModeRadio):
_mem.unknown5[0] = 0xFF
_mem.unknown5[1] = 0xFF
+ for setting in extras:
+ setting.apply_to_memobj(_mem)
+
@staticmethod
def make_key_group(keysobj, keynames, keyvals):
keyvals_by_label = {v: k for k, v in keyvals.items()}
@@ -748,6 +811,7 @@ class TK7162Radio(TKx160Radio):
_channels = 16
_power_levels = _POWER_LEVELS_7162
_has_zones = False
+ _has_memory_extras = False
_mem_format = mem_format_7162
def get_settings(self) -> settings.RadioSettings:
diff --git a/chirp/drivers/tk8180.py b/chirp/drivers/tk8180.py
index ff71a7f..0805a23 100644
--- a/chirp/drivers/tk8180.py
+++ b/chirp/drivers/tk8180.py
@@ -14,6 +14,7 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import enum
+import abc
import struct
import time
import logging
@@ -222,6 +223,9 @@ struct {
} zone%(index)i;
"""
+
+ZONE_LAYOUT_MEM_FORMAT = HEADER_FORMAT
+
STARTUP_MODES = ['Text', 'Clock']
VOLUMES = OrderedDict([(str(x), x) for x in range(0, 30)])
@@ -380,6 +384,195 @@ POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5),
chirp_common.PowerLevel("High", watts=50)]
+class ZoneMemoryMixin(abc.ABC):
+
+ @property
+ def raw_zone(self):
+ return getattr(self._memobj, 'zone%i' % self._zone)
+
+ @property
+ def raw_zoneinfo(self):
+ return self.raw_zone.zoneinfo
+
+ @property
+ def raw_memories(self):
+ return self.raw_zone.memories
+
+ @staticmethod
+ def _get_skipflag(memobj, flagoffset, index):
+ """Return the skip flag of memory index in a zone, or None"""
+ bit = int(flagoffset) + index - 1
+ if 0 <= bit < len(memobj.skipflags):
+ return int(memobj.skipflags[bit])
+ return None
+
+ @staticmethod
+ def _set_skipflag(memobj, flagoffset, index, skip):
+ """Set the skip flag of memory index in a zone"""
+ bit = int(flagoffset) + index - 1
+ if skip is not None and 0 <= bit < len(memobj.skipflags):
+ memobj.skipflags[bit] = skip
+
+ def shuffle_zone(self):
+ """Sort the memories in the zone according to logical channel number"""
+ raw_memories = self.raw_memories
+ memories = [(i, raw_memories[i].number)
+ for i in range(0, self.raw_zoneinfo.count)]
+ current = memories[:]
+ memories.sort(key=lambda t: t[1])
+ if current == memories:
+ LOG.debug('Shuffle not required')
+ return
+ flagoffset = self.raw_zoneinfo.flagoffset
+ raw_data = [raw_memories[i].get_raw()
+ for i, _n in memories]
+ # The skip flags are indexed by position, so move them too
+ skip_data = [self._get_skipflag(self._memobj, flagoffset, i)
+ for i, _n in memories]
+ for i, raw_mem in enumerate(raw_data):
+ raw_memories[i].set_raw(raw_mem)
+ for i, skip in enumerate(skip_data):
+ self._set_skipflag(self._memobj, flagoffset, i, skip)
+
+ @abc.abstractmethod
+ def _compute_zone_layout(self, zone_sizes):
+ pass
+
+ @abc.abstractmethod
+ def _set_zone_flagoffset(self, zoneinfo, scan_index):
+ pass
+
+ @abc.abstractmethod
+ def _init_new_zoneinfo(self, dest_zoneinfo, zone_number, count,
+ old_memobj):
+ pass
+
+ @abc.abstractmethod
+ def _build_mem_format_from_zone_sizes(self, zone_sizes):
+ pass
+
+ def expand_mmap(self, zone_sizes):
+ old_zones = self._zones
+ old_memobj = self._memobj
+
+ self._mmap = memmap.MemoryMapBytes(bytes(self._mmap.get_packed()))
+
+ self._zones = self._compute_zone_layout(zone_sizes)
+ self._memobj = bitwise.parse(
+ self._build_mem_format_from_zone_sizes(zone_sizes), self._mmap)
+
+ for index in range(0, 128):
+ try:
+ self._memobj.zone_starts[index] = self._zones[index][0]
+ except IndexError:
+ self._memobj.zone_starts[index] = 0xFFFF
+
+ scan_index = 1
+ for zone_number, count in enumerate(zone_sizes):
+ dest_zone = getattr(self._memobj, 'zone%i' % zone_number)
+ dest = dest_zone.memories
+ dest_zoneinfo = dest_zone.zoneinfo
+
+ if zone_number < len(old_zones):
+ _, old_count = old_zones[zone_number]
+ source_zone = getattr(old_memobj, 'zone%i' % zone_number)
+ source = source_zone.memories
+ source_zoneinfo = source_zone.zoneinfo
+
+ dest_zoneinfo.set_raw(source_zoneinfo.get_raw())
+ dest_zoneinfo.count = count
+
+ for i in range(0, min(count, old_count)):
+ dest[i].set_raw(source[i].get_raw())
+ # The zone may start at a new flag offset, so move each
+ # memory's skip flag with it
+ skip = self._get_skipflag(old_memobj,
+ source_zoneinfo.flagoffset, i)
+ self._set_skipflag(self._memobj, scan_index, i, skip)
+ else:
+ self._init_new_zoneinfo(dest_zoneinfo, zone_number,
+ count, old_memobj)
+
+ self._set_zone_flagoffset(dest_zoneinfo, scan_index)
+ scan_index += count
+
+ self.process_mmap()
+
+
+class KenwoodOSTMixin:
+ OST_NAME_LENGTH = 12
+
+ def _get_ost_name_path(self, index):
+ return 'ost_tones[%i].name' % index
+
+ def _get_ost_name(self, _ost):
+ return str(_ost.name).rstrip('\x00')
+
+ @staticmethod
+ def _select_tone_value(tones, raw_tone, index, which):
+ if raw_tone == 0xFFFF:
+ return 'Off'
+
+ cur = round(int(raw_tone) / 10.0, 1)
+ if cur not in tones:
+ LOG.debug('Non-standard OST %s tone %i %s', which, index, cur)
+ tones.append(cur)
+ tones.sort()
+ return str(cur)
+
+ def _get_ost(self, parent=None):
+ tones = chirp_common.TONES[:]
+
+ def apply_tone(setting, index, which):
+ if str(setting.value) == 'Off':
+ val = 0xFFFF
+ else:
+ val = int(float(str(setting.value)) * 10)
+ setattr(self._memobj.ost_tones[index], '%stone' % which, val)
+
+ def _tones():
+ return ['Off'] + [str(x) for x in tones]
+
+ ostgroup = RadioSettingGroup('ost', 'OST')
+ ostgroup.set_doc('Operator Selectable Tone')
+
+ for i in range(0, 40):
+ _ost = self._memobj.ost_tones[i]
+ ost = RadioSettingSubGroup('ost%i' % i,
+ 'OST %i' % (i + 1))
+
+ cur = self._get_ost_name(_ost)
+ name = MemSetting(self._get_ost_name_path(i), 'Name',
+ RadioSettingValueString(
+ 0, self.OST_NAME_LENGTH, cur,
+ mem_pad_char='\x00'))
+ ost.append(name)
+
+ cur = self._select_tone_value(tones, _ost.rxtone, i, 'rx')
+ tone_values = _tones()
+ rx = RadioSetting('rxtone%i' % i, 'RX Tone',
+ RadioSettingValueList(
+ tone_values,
+ current_index=tone_values.index(cur)))
+ rx.set_apply_callback(apply_tone, i, 'rx')
+ ost.append(rx)
+
+ cur = self._select_tone_value(tones, _ost.txtone, i, 'tx')
+ tone_values = _tones()
+ tx = RadioSetting('txtone%i' % i, 'TX Tone',
+ RadioSettingValueList(
+ tone_values,
+ current_index=tone_values.index(cur)))
+ tx.set_apply_callback(apply_tone, i, 'tx')
+ ost.append(tx)
+
+ ostgroup.append(ost)
+
+ if parent is not None:
+ parent.append(ostgroup)
+ return ostgroup
+
+
ButtonDisposition = enum.Enum('ButtonDisposition',
['PRIMARY', 'SECONDARY', 'HOLD'])
@@ -541,8 +734,8 @@ def do_download(radio):
raise errors.RadioError('Radio did not send block')
data += chunk
else:
- LOG.error('Radio sent %r (%02x), expected W(0x57)' % (cmd,
- chr(cmd)))
+ LOG.error('Radio sent %r (%s), expected W(0x57)' % (
+ cmd, cmd.hex()))
raise errors.RadioError('Radio sent unexpected response')
status()
@@ -645,7 +838,8 @@ def reset(self):
LOG.error('Unable to send reset sequence')
-class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
+class KenwoodTKx180Radio(ZoneMemoryMixin, KenwoodOSTMixin,
+ chirp_common.CloneModeRadio):
"""Kenwood TK-x180"""
VENDOR = 'Kenwood'
MODEL = 'TK-x180'
@@ -653,8 +847,44 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
FORMATS = [directory.register_format('Kenwood KPG-89D', '*.dat')]
_system_start = 0x0B00
+ _zone_header_size = 0x20
+ _memory_size = 0x30
_memsize = 0xD100
+ def _compute_zone_layout(self, zone_sizes):
+ zones = []
+ addr = self._system_start
+ for count in zone_sizes:
+ zones.append((addr, count))
+ addr += self._zone_header_size + (count * self._memory_size)
+ return zones
+
+ def _set_zone_flagoffset(self, zoneinfo, scan_index):
+ zoneinfo.flagoffset = scan_index
+
+ def _build_mem_format_from_zone_sizes(self, zone_sizes):
+ mem_format = ZONE_LAYOUT_MEM_FORMAT
+ for index, (addr, count) in enumerate(self._compute_zone_layout(
+ zone_sizes)):
+ mem_format += SYSTEM_MEM_FORMAT % {
+ 'addr': addr,
+ 'count': max(count, 1),
+ 'index': index}
+ return mem_format
+
+ def _init_new_zoneinfo(self, dest_zoneinfo, zone_number, count,
+ old_memobj):
+ dest_zoneinfo.number = zone_number + 1
+ dest_zoneinfo.zonetype = 0x31
+ dest_zoneinfo.count = count
+ dest_zoneinfo.name = ('Zone %i' % (zone_number + 1)).ljust(12)
+
+ z0info = getattr(old_memobj, 'zone0').zoneinfo
+ dest_zoneinfo.timeout = z0info.timeout
+ dest_zoneinfo.tot_alert = z0info.tot_alert
+ dest_zoneinfo.tot_rekey = z0info.tot_rekey
+ dest_zoneinfo.tot_reset = z0info.tot_reset
+
@property
def is_mobile(self):
"""True if this is a mobile transceiver"""
@@ -782,90 +1012,7 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
self._memobj = bitwise.parse(mem_format, self._mmap)
def expand_mmap(self, zone_sizes):
- """Remap memory into zones of the specified sizes, copying things
- around to keep the contents, as appropriate."""
- old_zones = self._zones
- old_memobj = self._memobj
-
- self._mmap = memmap.MemoryMapBytes(bytes(self._mmap.get_packed()))
-
- new_format = HEADER_FORMAT
- addr = self._system_start
- self._zones = []
- for index, count in enumerate(zone_sizes):
- new_format += SYSTEM_MEM_FORMAT % {
- 'addr': addr,
- 'count': max(count, 1), # Never allow array of zero
- 'index': index}
- self._zones.append((addr, count))
- addr += 0x20 + (count * 0x30)
-
- self._memobj = bitwise.parse(new_format, self._mmap)
-
- # Set all known zone addresses and clear the rest
- for index in range(0, 128):
- try:
- self._memobj.zone_starts[index] = self._zones[index][0]
- except IndexError:
- self._memobj.zone_starts[index] = 0xFFFF
-
- scan_index = 1
- for zone_number, count in enumerate(zone_sizes):
- dest_zone = getattr(self._memobj, 'zone%i' % zone_number)
- dest = dest_zone.memories
- dest_zoneinfo = dest_zone.zoneinfo
-
- if zone_number < len(old_zones):
- LOG.debug('Copying existing zone %i' % zone_number)
- _, old_count = old_zones[zone_number]
- source_zone = getattr(old_memobj, 'zone%i' % zone_number)
- source = source_zone.memories
- source_zoneinfo = source_zone.zoneinfo
-
- if old_count != count:
- LOG.debug('Zone %i going from %i to %i' % (zone_number,
- old_count,
- count))
-
- # Copy the zone record from the source, but then update
- # the count
- dest_zoneinfo.set_raw(source_zoneinfo.get_raw())
- dest_zoneinfo.count = count
-
- for dest_i in range(0, min(count, old_count)):
- dest[dest_i].set_raw(source[dest_i].get_raw())
- else:
- LOG.debug('New zone %i' % zone_number)
- dest_zone.zoneinfo.number = zone_number + 1
- dest_zone.zoneinfo.zonetype = 0x31
- dest_zone.zoneinfo.count = count
- dest_zone.zoneinfo.name = (
- 'Zone %i' % (zone_number + 1)).ljust(12)
-
- # Copy the settings we care about from the first zone
- z0info = self._memobj.zone0.zoneinfo
- dest_zone.zoneinfo.timeout = z0info.timeout
- dest_zone.zoneinfo.tot_alert = z0info.tot_alert
- dest_zone.zoneinfo.tot_rekey = z0info.tot_rekey
- dest_zone.zoneinfo.tot_reset = z0info.tot_reset
- dest_zone.zoneinfo.flagoffset = scan_index
- scan_index += count
-
- def shuffle_zone(self):
- """Sort the memories in the zone according to logical channel number"""
- # FIXME: Move this to the zone
- raw_memories = self.raw_memories
- memories = [(i, raw_memories[i].number)
- for i in range(0, self.raw_zoneinfo.count)]
- current = memories[:]
- memories.sort(key=lambda t: t[1])
- if current == memories:
- LOG.debug('Shuffle not required')
- return
- raw_data = [raw_memories[i].get_raw()
- for i, n in memories]
- for i, raw_mem in enumerate(raw_data):
- raw_memories[i].set_raw(raw_mem)
+ return super().expand_mmap(zone_sizes)
@classmethod
def get_prompts(cls):
@@ -910,18 +1057,6 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
return rf
@property
- def raw_zone(self):
- return getattr(self._memobj, 'zone%i' % self._zone)
-
- @property
- def raw_zoneinfo(self):
- return self.raw_zone.zoneinfo
-
- @property
- def raw_memories(self):
- return self.raw_zone.memories
-
- @property
def max_mem(self):
return self.raw_memories[self.raw_zoneinfo.count].number
@@ -1446,64 +1581,6 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
return zones
- def _get_ost(self, parent):
- tones = chirp_common.TONES[:]
-
- def apply_tone(setting, index, which):
- if str(setting.value) == 'Off':
- val = 0xFFFF
- else:
- val = int(float(str(setting.value)) * 10)
- setattr(self._memobj.ost_tones[index], '%stone' % which, val)
-
- def _tones():
- return ['Off'] + [str(x) for x in tones]
-
- ostgroup = RadioSettingGroup('ost', 'OST')
- ostgroup.set_doc('Operator Selectable Tone')
- parent.append(ostgroup)
-
- for i in range(0, 40):
- _ost = self._memobj.ost_tones[i]
- ost = RadioSettingSubGroup('ost%i' % i,
- 'OST %i' % (i + 1))
-
- cur = str(_ost.name).rstrip('\x00')
- name = MemSetting('ost_tones[%i].name' % i, 'Name',
- RadioSettingValueString(0, 12, cur,
- mem_pad_char='\x00'))
- ost.append(name)
-
- if _ost.rxtone == 0xFFFF:
- cur = 'Off'
- else:
- cur = round(int(_ost.rxtone) / 10.0, 1)
- if cur not in tones:
- LOG.debug('Non-standard OST rx tone %i %s' % (i, cur))
- tones.append(cur)
- tones.sort()
- rx = RadioSetting('rxtone%i' % i, 'RX Tone',
- RadioSettingValueList(_tones(),
- str(cur)))
- rx.set_apply_callback(apply_tone, i, 'rx')
- ost.append(rx)
-
- if _ost.txtone == 0xFFFF:
- cur = 'Off'
- else:
- cur = round(int(_ost.txtone) / 10.0, 1)
- if cur not in tones:
- LOG.debug('Non-standard OST tx tone %i %s' % (i, cur))
- tones.append(cur)
- tones.sort()
- tx = RadioSetting('txtone%i' % i, 'TX Tone',
- RadioSettingValueList(_tones(),
- str(cur)))
- tx.set_apply_callback(apply_tone, i, 'tx')
- ost.append(tx)
-
- ostgroup.append(ost)
-
def _get_keys(self):
if self.is_mobile:
model_functions = BUTTON_FUNCTIONS | MOBILE_BUTTON_FUNCTIONS
diff --git a/chirp/drivers/ts590.py b/chirp/drivers/ts590.py
index 204c497..3a7ea8d 100644
--- a/chirp/drivers/ts590.py
+++ b/chirp/drivers/ts590.py
@@ -1647,11 +1647,6 @@ class TS590Radio(chirp_common.CloneModeRadio):
LOG.debug(element.get_name())
raise
- @classmethod
- def match_model(cls, fdata, fyle):
- """ Included to prevent 'File > New' error """
- return False
-
@directory.register
class TS590SRadio(TS590Radio):
diff --git a/chirp/drivers/tyt_uvl15w.py b/chirp/drivers/tyt_uvl15w.py
new file mode 100644
index 0000000..f3d59f3
--- /dev/null
+++ b/chirp/drivers/tyt_uvl15w.py
@@ -0,0 +1,1113 @@
+# Copyright 2026
+#
+# 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/>.
+
+"""TYT UVL-15W
+
+Based on TYT's "UVL-15W communications protocol V3.0" and "UVL-15W data
+storage instructions V1.0" documents.
+
+The radio talks over USB CDC (or Bluetooth) using framed binary packets:
+
+ request: FE.. FE EE EF <cmd> <escaped data> <escaped lrc> FD
+ response: FE.. FE EF EE <cmd> <escaped data> <escaped lrc> FD
+
+Data and LRC bytes are sent as (byte + 0x80); results above 0xF9 are sent
+as FF followed by the low nibble, so FA..FF never appear inside a frame.
+The LRC is the two's complement of the 8-bit sum of the raw data.
+
+The clone image is the radio's whole read/write window of its SPI flash,
+0x8000-0x21000. Offsets in MEM_FORMAT are relative to 0x8000.
+"""
+
+import logging
+import struct
+
+from chirp import bitwise, chirp_common, directory, errors, memmap
+from chirp.settings import MemSetting, RadioSetting, RadioSettingGroup
+from chirp.settings import RadioSettings, RadioSettingValueBoolean
+from chirp.settings import RadioSettingValueInteger, RadioSettingValueList
+from chirp.settings import RadioSettingValueString
+
+LOG = logging.getLogger(__name__)
+
+MODEL_ID = b"UVL-15W"
+FLASH_START = 0x8000
+FLASH_END = 0x21000
+MEM_SIZE = FLASH_END - FLASH_START
+READ_BLOCK = 0x800
+WRITE_BLOCK = 0x200
+RETRIES = 3
+
+CMD_INFO = 0xE0
+CMD_INFO_RESP = 0xE1
+CMD_READ_START = 0xE2
+CMD_WRITE_START = 0xE3
+CMD_WRITE = 0xE4
+CMD_FINISH = 0xE5
+CMD_READ = 0xE6
+CMD_ERROR = 0xEE
+
+NUM_CHANNELS = 1000
+GROUP_SLOTS = 128
+VFOS = ["VFO A", "VFO B"]
+WX_CHANNELS = ["WX%i" % i for i in range(1, 11)]
+SPECIALS = VFOS + WX_CHANNELS
+
+MEM_FORMAT = """
+struct channel {
+ u32 rxfreq;
+ u32 txfreq;
+ char name[24];
+ u32 offset;
+ u8 step:4,
+ reverse:2,
+ duplex:2;
+ u8 bcl:2,
+ rxonly:1,
+ power:2,
+ mode:3;
+ u8 txtone_type:3,
+ sql_type:3,
+ unknown26:2;
+ u8 unknown27:1,
+ compander:2,
+ dcs_pol:2,
+ rxtone_type:3;
+ u8 txtone;
+ u8 rxtone;
+ u8 sig_type;
+ u8 sig_index;
+ u8 scramble;
+ u8 pttid;
+ u8 aprs_rx;
+ u8 reserved;
+};
+
+#seekto 0x0000;
+struct channel memory[1000];
+
+#seekto 0xBB80;
+struct channel vfo[2];
+
+#seekto 0xBC40;
+struct channel temp[2];
+
+#seekto 0xBCA0;
+struct channel wx[10];
+
+#seekto 0xD000;
+lbit valid[1024];
+
+#seekto 0xD080;
+u8 scanflags[256];
+
+#seekto 0xD300;
+struct {
+ u8 unknown0[7];
+ u8 a_mode;
+ u8 b_mode;
+ u8 unknown09;
+ u16 a_channel;
+ u16 b_channel;
+} status;
+
+#seekto 0xD400;
+struct {
+ u8 language;
+ u8 unknown01[4];
+ u8 unknown05:5,
+ show_zone:1,
+ show_name:1,
+ show_freq:1;
+ u8 menu_exit;
+ u8 backlight;
+ u8 auto_dim;
+ u8 auto_dim_delay;
+ u8 rx_wake;
+ u8 tx_wake;
+ u8 ai_denoise;
+ u8 vox;
+ u8 vox_level;
+ u8 vox_delay;
+ u8 unknown10[10];
+ u8 key_beep;
+ u8 low_bat_beep;
+ u8 unknown1c;
+ u8 unknown1d:6,
+ roger_end:1,
+ roger_start:1;
+ u8 mic_gain;
+ u8 power_on_beep;
+ u8 unknown20[5];
+ u8 theme;
+ u8 unknown26[4];
+ u8 tot_beep;
+ u8 bat_display;
+ u8 rx_led;
+ u8 rssi;
+ u8 standby_led;
+ u8 unknown2f;
+ u8 dual_mode;
+ u8 cross_mode;
+ u8 squelch;
+ u8 tot;
+ u8 tx_channel;
+ u8 hang_time;
+ u8 tail_ctcss;
+ u8 tail_dcs;
+ u8 tail_carrier;
+ u8 tail_time;
+ u8 tbst_time;
+ u8 tbst_freq;
+ u8 tbst_sidetone;
+ u8 scan_mode;
+ u8 mr_scan_type;
+ u8 cross_monitor;
+ u8 unknown40[32];
+ u8 boot_logo;
+ u8 boot_fw;
+ u8 boot_msg_on;
+ u8 boot_voltage;
+ char boot_msg[50];
+ u8 unknown96[26];
+ u8 save_mode;
+ u8 save_delay;
+} settings;
+"""
+
+# Zone and scan list areas. Each zone or scan list has an ordered list of
+# up to 128 channels (0-based, FFFF for unused), and each channel has an
+# inverted bitmap of the zones and scan lists it belongs to.
+# On layout 2 the channel lists are big-endian and the bitmaps
+# little-endian (seen on a radio). TYT's document says the layout 1 lists
+# are little-endian.
+# Layout 1 (firmware 3.03.x) is from TYT's storage document; layout 2
+# (firmware 3.09.x) was found by setting zones in TYT's V3.09.21 software.
+GROUP_FORMATS = {
+ 1: """
+#seekto 0x10000;
+struct {
+ ul16 slot[128];
+} zone_members[16];
+
+#seekto 0x11000;
+struct {
+ ul16 slot[128];
+} scan_members[16];
+
+#seekto 0x12000;
+ul16 ch_zones[1000];
+
+#seekto 0x12800;
+ul16 ch_scans[1000];
+
+#seekto 0x13000;
+struct {
+ u8 name[24];
+} zone_names[16];
+
+#seekto 0x13400;
+struct {
+ u8 name[24];
+} scan_names[16];
+""",
+ 2: """
+#seekto 0x10000;
+struct {
+ u16 slot[128];
+} zone_members[32];
+
+#seekto 0x12000;
+struct {
+ u16 slot[128];
+} scan_members[32];
+
+#seekto 0x14000;
+ul32 ch_zones[1000];
+
+#seekto 0x15000;
+ul32 ch_scans[1000];
+
+#seekto 0x16000;
+struct {
+ u8 name[24];
+} zone_names[32];
+
+#seekto 0x16500;
+struct {
+ u8 name[24];
+} scan_names[32];
+""",
+}
+GROUP_COUNTS = {1: 16, 2: 32}
+
+
+POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1.00),
+ chirp_common.PowerLevel("Mid", watts=5.00),
+ chirp_common.PowerLevel("High", watts=15.00)]
+MODES = ["FM", "NFM", "AM", "NAM"]
+STEPS = [2.5, 3.125, 5.0, 6.25, 8.33, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0,
+ 100.0]
+DUPLEXES = ["", "-", "+", "split"]
+TONES = [67.0, 69.3, 71.9, 74.4, 77.0, 79.7, 82.5, 85.4, 88.5, 91.5,
+ 94.8, 97.4, 100.0, 103.5, 107.2, 110.9, 114.8, 118.8, 123.0, 127.3,
+ 131.8, 136.5, 141.3, 146.2, 151.4, 156.7, 159.8, 162.2, 165.5, 167.9,
+ 171.3, 173.8, 177.3, 179.9, 183.5, 186.2, 189.9, 192.8, 196.6, 199.5,
+ 203.5, 206.5, 210.7, 218.1, 225.7, 229.1, 233.6, 241.8, 250.3, 254.1]
+DTCS_CODES = [
+ 23, 25, 26, 31, 32, 36, 43, 47, 51, 53, 54, 65, 71, 72, 73, 74,
+ 114, 115, 116, 122, 125, 131, 132, 134, 143, 145, 152, 155, 156, 162,
+ 165, 172, 174, 205, 212, 223, 225, 226, 243, 244, 245, 246, 251, 252,
+ 255, 261, 263, 265, 266, 271, 274, 306, 311, 315, 325, 331, 332, 343,
+ 346, 351, 356, 364, 365, 371, 411, 412, 413, 423, 431, 432, 445, 446,
+ 452, 454, 455, 462, 464, 465, 466, 503, 506, 516, 523, 526, 532, 546,
+ 565, 606, 612, 624, 627, 631, 632, 654, 662, 664, 703, 712, 723, 731,
+ 732, 734, 743, 754]
+# dcs_pol field: 0=TX N/RX N, 1=TX N/RX R, 2=TX R/RX N, 3=TX R/RX R
+DCS_POLARITY = ["NN", "NR", "RN", "RR"]
+# rxtone_type field: 0=off 1=CTCSS 2=DCS 3=CTCSS (reverse) 4=DCS (reverse)
+SQL_CARRIER = 0
+SQL_TONE = 1
+# Squelch types that use the tone decoder: tone, tone and signal, tone or
+# signal. Type 2 (optional signalling only) ignores the decode tone.
+SQL_WITH_TONE = (1, 3, 4)
+BCL = ["Off", "Repeater", "Carrier"]
+SCRAMBLE = ["Off", "2700", "2800", "2900", "3000", "3100", "3200", "3300",
+ "3400"]
+COMPANDER = ["Off", "TX", "RX", "TX/RX"]
+PTTID = ["Off"] + ["%i" % i for i in range(8)]
+APRS_RX = ["Off", "On", "On (mute)"]
+REVERSE = ["Off", "Talkaround", "Reverse"]
+SKIP_VALUES = ["", "S", "P"]
+
+LANGUAGES = ["Simplified Chinese", "Traditional Chinese", "English",
+ "Turkish"]
+LEVELS9 = ["%i" % i for i in range(1, 10)]
+OFF_ON = ["Off", "On"]
+TOT = ["Off"] + ["%i min" % i for i in range(1, 11)] + [
+ "15 min", "20 min", "25 min", "30 min"]
+MENU_EXIT = ["Off"] + ["%i s" % i for i in range(5, 16)] + [
+ "%i s" % i for i in range(20, 60, 5)] + [
+ "%i min" % i for i in range(1, 11)]
+AUTO_DIM = ["Off", "Auto off"] + ["Dim level %i" % i for i in range(1, 9)]
+DUAL_MODES = ["Single", "Dual watch, single TX", "Dual RX, single TX",
+ "Cross-band repeat"]
+WORK_MODES = ["Memory", "Frequency", "Call", "Weather"]
+SCAN_MODES = ["Carrier", "Time", "Search"]
+TBST_FREQS = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"]
+THEMES = ["White", "Black"]
+BAT_DISPLAY = ["Icon", "Voltage", "Icon and voltage"]
+RSSI = ["Off", "dBm", "S-meter/dBm"]
+MIC_GAIN = ["Low", "Medium", "High"] + ["%i" % i for i in range(32)]
+SAVE_DELAY = ["%i s" % i for i in range(3, 11)] + [
+ "%i s" % i for i in range(12, 21, 2)] + [
+ "%i s" % i for i in range(25, 61, 5)] + [
+ "%i s" % i for i in range(70, 121, 10)] + [
+ "%i s" % i for i in range(150, 301, 30)]
+
+
+def _escape(data):
+ out = bytearray()
+ for byte in data:
+ temp = (byte + 0x80) & 0xFF
+ if temp > 0xF9:
+ out += bytes([0xFF, temp & 0x0F])
+ else:
+ out.append(temp)
+ return bytes(out)
+
+
+def _unescape(data):
+ out = bytearray()
+ i = 0
+ while i < len(data):
+ if data[i] == 0xFF:
+ if i + 1 >= len(data):
+ raise errors.RadioError("Truncated escape in response")
+ out.append((0xF0 + data[i + 1] + 0x80) & 0xFF)
+ i += 2
+ else:
+ out.append((data[i] + 0x80) & 0xFF)
+ i += 1
+ return bytes(out)
+
+
+def _lrc(data):
+ return (0x100 - (sum(data) & 0xFF)) & 0xFF
+
+
+def _make_frame(cmd, data=b""):
+ return (b"\xFE\xFE\xEE\xEF" + bytes([cmd]) +
+ _escape(data + bytes([_lrc(data)])) + b"\xFD")
+
+
+def _parse_frame(frame):
+ """Return (cmd, data) from a response frame ending in FD"""
+ frame = frame.lstrip(b"\xFE")
+ if len(frame) < 5 or frame[:2] != b"\xEF\xEE" or frame[-1] != 0xFD:
+ raise errors.RadioError("Malformed response from radio")
+ cmd = frame[2]
+ payload = _unescape(frame[3:-1])
+ if not payload or sum(payload) & 0xFF:
+ raise errors.RadioError("Bad checksum in response from radio")
+ return cmd, payload[:-1]
+
+
+def _recv_frame(radio):
+ pipe = radio.pipe
+ frame = b""
+ # Worst case is a read block with every byte escaped, plus framing
+ for _i in range(2 * (READ_BLOCK + 8) + 64):
+ byte = pipe.read(1)
+ if not byte:
+ if not frame:
+ raise errors.RadioNoResponse()
+ raise errors.RadioError("Timeout waiting for radio response")
+ if not frame and byte != b"\xFE":
+ # Discard noise before the preamble
+ continue
+ frame += byte
+ if byte == b"\xFD":
+ return _parse_frame(frame)
+ raise errors.RadioError("Radio sent an overlong or garbled response")
+
+
+def _command(radio, cmd, data=b"", expect=None):
+ for attempt in range(RETRIES):
+ radio.pipe.write(_make_frame(cmd, data))
+ try:
+ rcmd, rdata = _recv_frame(radio)
+ except errors.RadioNoResponse:
+ raise
+ except errors.RadioError as e:
+ LOG.warning("Command %02X attempt %i failed: %s",
+ cmd, attempt + 1, e)
+ continue
+ if rcmd == CMD_ERROR:
+ msg = rdata.decode("ascii", "replace")
+ LOG.warning("Radio error for command %02X: %s", cmd, msg)
+ if "Lrc" in msg or "Frame" in msg:
+ continue
+ raise errors.RadioError("Radio reported error: %s" % msg)
+ if expect is not None and rcmd != expect:
+ raise errors.RadioError(
+ "Unexpected response %02X to command %02X" % (rcmd, cmd))
+ return rdata
+ raise errors.RadioError("Radio did not accept command %02X" % cmd)
+
+
+def _identify(radio):
+ radio.pipe.timeout = 2
+ info = _command(radio, CMD_INFO, MODEL_ID, expect=CMD_INFO_RESP)
+ LOG.debug("Radio info: %r", info)
+ if not info.startswith(MODEL_ID):
+ raise errors.RadioError("Radio is not a UVL-15W: %r" % info[:16])
+ return info
+
+
+def _check_password(info, offset, op):
+ if len(info) > offset and info[offset]:
+ raise errors.RadioError(
+ "The radio has a %s password set. Remove it from the radio "
+ "before using CHIRP." % op)
+
+
+def _range_data():
+ # The end address is inclusive. TYT's older software sent 0x21000 here,
+ # which can make the radio erase the flash sector after the data area,
+ # where the menu icons live; their V3.09.21 software sends 0x20FFF.
+ return struct.pack(">II", FLASH_START, FLASH_END - 1)
+
+
+def _expect_text(data, text):
+ if text not in data:
+ raise errors.RadioError("Radio refused: %r" % data)
+
+
+def _finish(radio, text):
+ try:
+ _command(radio, CMD_FINISH, text)
+ except errors.RadioError as e:
+ # The radio reboots after this; a missed reply does no harm
+ LOG.warning("No reply to finish command: %s", e)
+
+
+def do_download(radio):
+ info = _identify(radio)
+ _check_password(info, 10, "read")
+ radio.metadata = {"uvl15w_version":
+ info[12:20].decode("ascii", "replace").strip("\x00")}
+ _expect_text(_command(radio, CMD_READ_START, _range_data()),
+ b"READ START OK")
+
+ status = chirp_common.Status()
+ status.msg = "Cloning from radio"
+ status.max = MEM_SIZE
+ data = b""
+ radio.pipe.timeout = 5
+ for addr in range(FLASH_START, FLASH_END, READ_BLOCK):
+ size = min(READ_BLOCK, FLASH_END - addr)
+ req = struct.pack(">IH", addr, size)
+ resp = _command(radio, CMD_READ, req, expect=CMD_WRITE)
+ if resp[:6] != req or len(resp) != 6 + size:
+ raise errors.RadioError("Bad block from radio at %06x" % addr)
+ data += resp[6:]
+ status.cur = len(data)
+ radio.status_fn(status)
+
+ _finish(radio, b"Read Complete")
+ return memmap.MemoryMapBytes(data)
+
+
+def do_upload(radio):
+ info = _identify(radio)
+ _check_password(info, 11, "write")
+ radio._prepare_upload()
+ _expect_text(_command(radio, CMD_WRITE_START, _range_data()),
+ b"WRITE START OK")
+
+ status = chirp_common.Status()
+ status.msg = "Cloning to radio"
+ status.max = MEM_SIZE
+ mmap = radio.get_mmap().get_byte_compatible()
+ radio.pipe.timeout = 5
+ for offset in range(0, MEM_SIZE, WRITE_BLOCK):
+ addr = FLASH_START + offset
+ block = mmap[offset:offset + WRITE_BLOCK]
+ hdr = struct.pack(">IH", addr, len(block))
+ resp = _command(radio, CMD_WRITE, hdr + block)
+ if not resp.startswith(b"WF OK") or resp[5:11] != hdr:
+ raise errors.RadioError("Radio refused block at %06x" % addr)
+ status.cur = offset + len(block)
+ radio.status_fn(status)
+
+ _finish(radio, b"Write Complete")
+
+
+def _decode_name(raw):
+ raw = bytes(raw).split(b"\x00")[0]
+ if raw[:1] == b"\xFF":
+ return ""
+ return raw.decode("utf-8", "replace")
+
+
+class UVL15WZone(chirp_common.NamedBank):
+ def get_name(self):
+ name = _decode_name(
+ self._model._radio._memobj.zone_names[self.index].name)
+ return name if name.isprintable() and name else "Zone %i" % (
+ self.index)
+
+ def set_name(self, name):
+ raw = name.rstrip().encode("utf-8")[:24]
+ self._model._radio._memobj.zone_names[self.index].name = \
+ raw.ljust(24, b"\x00")
+
+
+class UVL15WZoneModel(chirp_common.MTOBankModel):
+ """Zones. Each channel has an inverted bitmap of the zones it belongs
+ to, and each zone has an ordered list of its channels; both are kept
+ in step here, as the factory software does."""
+
+ def __init__(self, radio):
+ super().__init__(radio, "Zones")
+
+ def _zone(self, index):
+ zone = UVL15WZone(self, "%i" % (index + 1), "Zone %i" % (index + 1))
+ zone.index = index
+ return zone
+
+ def get_num_mappings(self):
+ return GROUP_COUNTS[self._radio._layout()]
+
+ def get_mappings(self):
+ return [self._zone(i) for i in range(self.get_num_mappings())]
+
+ def add_memory_to_mapping(self, memory, zone):
+ self._radio._group_add("zone", self._ch(memory), zone.index)
+
+ def remove_memory_from_mapping(self, memory, zone):
+ ch = self._ch(memory)
+ if zone.index not in self._radio._channel_groups("zone", ch):
+ raise errors.RadioError("Memory %i is not in zone %s" % (
+ memory.number, zone.get_name()))
+ self._radio._group_remove("zone", ch, zone.index)
+
+ def get_mapping_memories(self, zone):
+ return [self._radio.get_memory(ch + self._radio.FIRST_CHANNEL)
+ for ch in self._radio._group_list("zone", zone.index)]
+
+ def get_memory_mappings(self, memory):
+ return [self._zone(z) for z in
+ self._radio._channel_groups("zone", self._ch(memory))]
+
+ def _ch(self, memory):
+ return memory.number - self._radio.FIRST_CHANNEL
+
+
+@directory.register
+class UVL15WRadio(chirp_common.CloneModeRadio):
+ """TYT UVL-15W"""
+ VENDOR = "TYT"
+ MODEL = "UVL-15W"
+ BAUD_RATE = 115200
+ NEEDS_COMPAT_SERIAL = False
+
+ # The radio and TYT's software number channels from 0
+ FIRST_CHANNEL = 0
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.experimental = _(
+ "This driver is built from TYT's published protocol and memory "
+ "layout and has not yet been tested widely. Save a copy of a "
+ "fresh download from your radio before uploading. The radio "
+ "restarts at the end of every download and upload.")
+ return rp
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ # Zones and settings are only mapped for known layouts
+ known = self._layout() in GROUP_COUNTS
+ rf.has_settings = known
+ rf.has_bank = known
+ rf.has_bank_names = known
+ rf.has_name = True
+ rf.has_tuning_step = True
+ rf.has_rx_dtcs = True
+ rf.has_ctone = True
+ rf.has_cross = True
+ rf.has_dtcs_polarity = True
+ rf.can_odd_split = True
+ rf.valid_name_length = 16
+ rf.valid_characters = chirp_common.CHARSET_ASCII
+ rf.valid_modes = list(MODES)
+ rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
+ rf.valid_cross_modes = ["Tone->Tone", "DTCS->", "->DTCS",
+ "Tone->DTCS", "DTCS->Tone", "->Tone",
+ "DTCS->DTCS"]
+ rf.valid_tones = list(TONES)
+ rf.valid_dtcs_codes = list(DTCS_CODES)
+ rf.valid_duplexes = ["", "-", "+", "split", "off"]
+ rf.valid_skips = list(SKIP_VALUES)
+ rf.valid_tuning_steps = list(STEPS)
+ rf.valid_power_levels = POWER_LEVELS
+ rf.valid_bands = [(108000000, 174000000), (400000000, 520000000)]
+ rf.memory_bounds = (self.FIRST_CHANNEL,
+ self.FIRST_CHANNEL + NUM_CHANNELS - 1)
+ rf.valid_special_chans = list(SPECIALS)
+ return rf
+
+ def sync_in(self):
+ try:
+ self._mmap = do_download(self)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.exception("Download failed")
+ raise errors.RadioError("Failed to download: %s" % e)
+ self.process_mmap()
+
+ def sync_out(self):
+ # The image holds the radio's whole data area, including parts we
+ # do not understand, so only write back an image read from a radio
+ if "uvl15w_version" not in self.metadata:
+ raise errors.RadioError(
+ "This image was not downloaded from a UVL-15W. Download "
+ "from your radio first, then copy channels into that image "
+ "and upload it.")
+ try:
+ do_upload(self)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.exception("Upload failed")
+ raise errors.RadioError("Failed to upload: %s" % e)
+
+ def _prepare_upload(self):
+ # The factory software mirrors VFO A/B to Temp A/B on every upload
+ self._memobj.temp[0].set_raw(self._memobj.vfo[0].get_raw())
+ self._memobj.temp[1].set_raw(self._memobj.vfo[1].get_raw())
+
+ def process_mmap(self):
+ self._layout_version = self._detect_layout()
+ if self._layout_version == 0:
+ raise errors.RadioError(
+ "This image's data layout is not one CHIRP knows")
+ self._memobj = bitwise.parse(
+ MEM_FORMAT + GROUP_FORMATS.get(self._layout_version, ""),
+ self._mmap)
+
+ def _layout(self):
+ if self._mmap is None:
+ return 1
+ return self._layout_version
+
+ def _detect_layout(self):
+ """Return the data layout version, 0 if unknown.
+
+ Firmware 3.03.x stores "EDG1" version 1 at 0x1BB00, matching TYT's
+ storage document. Firmware 3.09.x moved the zone and scan list
+ areas and stores "EDG1" version 2 at 0x1EB00."""
+ data = self._mmap.get_byte_compatible()
+ if data[0x13B00:0x13B05] == b"EDG1\x01":
+ return 1
+ if data[0x16B00:0x16B05] == b"EDG1\x02":
+ return 2
+ if data[0x13B00:0x13B05] == b"\xFF" * 5:
+ # Never-written block, as on a factory-fresh image
+ return 1
+ return 0
+
+ def _resolve(self, number):
+ """Return (channel index or None for a special, record, number)"""
+ if isinstance(number, str):
+ special = SPECIALS.index(number)
+ else:
+ special = number - self.FIRST_CHANNEL - NUM_CHANNELS
+ if special >= len(VFOS):
+ return (None, self._memobj.wx[special - len(VFOS)],
+ self.FIRST_CHANNEL + NUM_CHANNELS + special)
+ if special >= 0:
+ return (None, self._memobj.vfo[special],
+ self.FIRST_CHANNEL + NUM_CHANNELS + special)
+ ch = number - self.FIRST_CHANNEL
+ return ch, self._memobj.memory[ch], number
+
+ def get_raw_memory(self, number):
+ return repr(self._resolve(number)[1])
+
+ def get_bank_model(self):
+ if self._layout() not in GROUP_COUNTS:
+ return None
+ return UVL15WZoneModel(self)
+
+ # Zone and scan list membership helpers. kind is "zone" or "scan";
+ # ch and group are 0-based.
+
+ def _groups(self, kind):
+ return (getattr(self._memobj, "%s_members" % kind),
+ getattr(self._memobj, "ch_%ss" % kind))
+
+ def _channel_groups(self, kind, ch):
+ bits = ~int(self._groups(kind)[1][ch])
+ return [g for g in range(GROUP_COUNTS[self._layout()])
+ if bits & (1 << g)]
+
+ def _group_list(self, kind, group):
+ slots = self._groups(kind)[0][group].slot
+ return [int(s) for s in slots if int(s) < NUM_CHANNELS]
+
+ def _set_group_list(self, kind, group, channels):
+ slots = self._groups(kind)[0][group].slot
+ for i in range(GROUP_SLOTS):
+ slots[i] = channels[i] if i < len(channels) else 0xFFFF
+
+ def _group_add(self, kind, ch, group):
+ members = self._group_list(kind, group)
+ if ch not in members:
+ if len(members) >= GROUP_SLOTS:
+ raise errors.RadioError("%s %i is full" % (
+ kind.title(), group + 1))
+ self._set_group_list(kind, group, members + [ch])
+ bitmaps = self._groups(kind)[1]
+ bitmaps[ch] = int(bitmaps[ch]) & ~(1 << group)
+
+ def _group_remove(self, kind, ch, group):
+ self._set_group_list(
+ kind, group,
+ [c for c in self._group_list(kind, group) if c != ch])
+ bitmaps = self._groups(kind)[1]
+ bitmaps[ch] = int(bitmaps[ch]) | (1 << group)
+
+ def _clear_groups(self, ch):
+ if self._layout() not in GROUP_COUNTS:
+ return
+ for kind in ("zone", "scan"):
+ for group in self._channel_groups(kind, ch):
+ self._group_remove(kind, ch, group)
+
+ def _get_skip(self, ch):
+ return (int(self._memobj.scanflags[ch // 4]) >> (2 * (ch % 4))) & 3
+
+ def _set_skip(self, ch, value):
+ shift = 2 * (ch % 4)
+ flags = int(self._memobj.scanflags[ch // 4]) & ~(3 << shift)
+ self._memobj.scanflags[ch // 4] = flags | (value << shift)
+
+ def _get_tone(self, kind, index, pol):
+ if kind in (1, 3) and index < len(TONES):
+ return "Tone", TONES[index], None
+ if kind in (2, 4) and index < len(DTCS_CODES):
+ return "DTCS", DTCS_CODES[index], pol
+ return "", None, None
+
+ def get_memory(self, number):
+ ch, _mem, number = self._resolve(number)
+ mem = chirp_common.Memory()
+ mem.number = number
+ if ch is None:
+ mem.extd_number = SPECIALS[number - self.FIRST_CHANNEL -
+ NUM_CHANNELS]
+ if mem.extd_number in WX_CHANNELS:
+ # Receive-only weather channels with fixed names
+ mem.name = _decode_name(_mem.name.get_raw()).rstrip()
+ mem.immutable = ["name", "skip", "empty"]
+ elif not self._memobj.valid[ch]:
+ mem.empty = True
+ return mem
+
+ mem.freq = int(_mem.rxfreq)
+ if ch is not None:
+ mem.name = _decode_name(_mem.name.get_raw()).rstrip()
+ txfreq = int(_mem.txfreq)
+ duplex = int(_mem.duplex)
+ if _mem.rxonly:
+ mem.duplex = "off"
+ elif duplex in (1, 2):
+ mem.duplex = DUPLEXES[duplex]
+ mem.offset = int(_mem.offset)
+ elif duplex == 3 or txfreq != mem.freq:
+ chirp_common.split_to_offset(mem, mem.freq, txfreq)
+
+ mem.mode = MODES[_mem.mode] if _mem.mode < len(MODES) else "FM"
+ mem.power = POWER_LEVELS[min(int(_mem.power), 2)]
+ if _mem.step < len(STEPS):
+ mem.tuning_step = STEPS[_mem.step]
+
+ pol = DCS_POLARITY[_mem.dcs_pol]
+ txtone = self._get_tone(_mem.txtone_type, _mem.txtone, pol[0])
+ rxtone = ("", None, None)
+ if _mem.sql_type in SQL_WITH_TONE:
+ rxtone = self._get_tone(_mem.rxtone_type, _mem.rxtone, pol[1])
+ chirp_common.split_tone_decode(mem, txtone, rxtone)
+
+ if ch is not None:
+ skip = self._get_skip(ch)
+ mem.skip = SKIP_VALUES[skip] if skip < len(SKIP_VALUES) else ""
+
+ mem.extra = RadioSettingGroup("extra", "Extra")
+ mem.extra.append(MemSetting(
+ "bcl", "Busy channel lockout",
+ RadioSettingValueList(BCL, current_index=min(int(_mem.bcl), 2))))
+ mem.extra.append(MemSetting(
+ "reverse", "Talkaround/reverse",
+ RadioSettingValueList(REVERSE,
+ current_index=min(int(_mem.reverse), 2))))
+ mem.extra.append(MemSetting(
+ "compander", "Compander",
+ RadioSettingValueList(COMPANDER,
+ current_index=int(_mem.compander))))
+ mem.extra.append(MemSetting(
+ "scramble", "Scrambler",
+ RadioSettingValueList(SCRAMBLE,
+ current_index=min(int(_mem.scramble), 8))))
+ pttid = int(_mem.pttid) & 0x0F
+ mem.extra.append(RadioSetting(
+ "pttid", "PTT ID",
+ RadioSettingValueList(PTTID, current_index=min(pttid, 8))))
+ aprs = int(_mem.aprs_rx) & 0x03
+ mem.extra.append(RadioSetting(
+ "aprs_rx", "APRS receive",
+ RadioSettingValueList(APRS_RX, current_index=min(aprs, 2))))
+ if ch is not None and self._layout() in GROUP_COUNTS:
+ # One scan list per channel here; a channel the factory
+ # software put in several lists shows the first of them.
+ lists = self._channel_groups("scan", ch)
+ mem.extra.append(RadioSetting(
+ "scanlist", "Scan list",
+ RadioSettingValueList(
+ self._scan_list_choices(),
+ current_index=lists[0] + 1 if lists else 0)))
+ return mem
+
+ def _scan_list_choices(self):
+ choices = ["None"]
+ for i in range(GROUP_COUNTS[self._layout()]):
+ name = _decode_name(self._memobj.scan_names[i].name)
+ if not name.isprintable():
+ name = ""
+ choices.append(("%i: %s" % (i, name)).rstrip(": "))
+ return choices
+
+ def _set_scan_list(self, ch, index):
+ lists = self._channel_groups("scan", ch)
+ current = lists[0] + 1 if lists else 0
+ if index == current:
+ return
+ for group in lists:
+ self._group_remove("scan", ch, group)
+ if index:
+ self._group_add("scan", ch, index - 1)
+
+ def _set_tone(self, mode, value, pol):
+ if mode == "Tone":
+ return 1, TONES.index(value)
+ if mode == "DTCS":
+ return 2, DTCS_CODES.index(value)
+ return 0, 0
+
+ def set_memory(self, mem):
+ ch, _mem, number = self._resolve(mem.extd_number or mem.number)
+ if ch is None:
+ pass
+ elif mem.empty:
+ self._memobj.valid[ch] = False
+ _mem.fill_raw(b"\x00")
+ # Unused channels have both scan bits set
+ self._set_skip(ch, 3)
+ self._clear_groups(ch)
+ return
+
+ elif not self._memobj.valid[ch]:
+ _mem.fill_raw(b"\x00")
+ self._clear_groups(ch)
+ _mem.step = STEPS.index(12.5)
+ _mem.power = 2
+ # The radio keeps a default 600 kHz offset on simplex channels
+ _mem.offset = 600000
+ if ch is not None:
+ self._memobj.valid[ch] = True
+ _mem.name = mem.name.ljust(24, "\x00")[:24]
+
+ _mem.rxfreq = mem.freq
+ _mem.rxonly = mem.duplex == "off"
+ if mem.duplex in ("+", "-"):
+ _mem.duplex = DUPLEXES.index(mem.duplex)
+ _mem.offset = mem.offset
+ if mem.duplex == "+":
+ _mem.txfreq = mem.freq + mem.offset
+ else:
+ _mem.txfreq = mem.freq - mem.offset
+ elif mem.duplex == "split":
+ _mem.duplex = 3
+ _mem.txfreq = mem.offset
+ _mem.offset = abs(mem.offset - mem.freq)
+ else:
+ _mem.duplex = 0
+ _mem.txfreq = mem.freq
+
+ _mem.mode = MODES.index(mem.mode)
+ if mem.power in POWER_LEVELS:
+ _mem.power = POWER_LEVELS.index(mem.power)
+ else:
+ _mem.power = 2
+ if mem.tuning_step in STEPS:
+ _mem.step = STEPS.index(mem.tuning_step)
+
+ (txmode, txval, txpol), (rxmode, rxval, rxpol) = \
+ chirp_common.split_tone_encode(mem)
+ _mem.txtone_type, _mem.txtone = self._set_tone(txmode, txval, txpol)
+ _mem.rxtone_type, _mem.rxtone = self._set_tone(rxmode, rxval, rxpol)
+ _mem.dcs_pol = DCS_POLARITY.index(
+ "%s%s" % (txpol or "N", rxpol or "N"))
+ # The radio's per-channel SQL control has to be on Tone for it to
+ # send the encode tone as well as to decode (seen on a radio)
+ if (txmode or rxmode) and _mem.sql_type not in SQL_WITH_TONE:
+ _mem.sql_type = SQL_TONE
+ elif not (txmode or rxmode) and _mem.sql_type in SQL_WITH_TONE:
+ _mem.sql_type = SQL_CARRIER
+
+ if ch is not None:
+ self._set_skip(ch, SKIP_VALUES.index(mem.skip or ""))
+
+ for setting in mem.extra or []:
+ if not self._own_extra(setting):
+ # Copied from another radio's memory; not ours to apply
+ continue
+ if setting.get_name() == "pttid":
+ _mem.pttid = (int(_mem.pttid) & 0xF0) | int(setting.value)
+ elif setting.get_name() == "aprs_rx":
+ _mem.aprs_rx = (int(_mem.aprs_rx) & 0xFC) | int(
+ setting.value)
+ elif setting.get_name() == "scanlist":
+ if ch is not None:
+ self._set_scan_list(ch, int(setting.value))
+ else:
+ setting.apply_to_memobj(_mem)
+
+ @staticmethod
+ def _own_extra(setting):
+ options = {"bcl": BCL, "reverse": REVERSE, "compander": COMPANDER,
+ "scramble": SCRAMBLE, "pttid": PTTID, "aprs_rx": APRS_RX}
+ name = setting.get_name()
+ if not isinstance(setting.value, RadioSettingValueList):
+ return False
+ if name == "scanlist":
+ return True
+ return options.get(name) == setting.value.get_options()
+
+ def validate_memory(self, mem):
+ msgs = super().validate_memory(mem)
+ if mem.empty or mem.duplex == "off":
+ return msgs
+ txfreq = mem.freq
+ if mem.duplex == "+":
+ txfreq += mem.offset
+ elif mem.duplex == "-":
+ txfreq -= mem.offset
+ elif mem.duplex == "split":
+ txfreq = mem.offset
+ if not (136000000 <= txfreq < 174000000 or
+ 400000000 <= txfreq < 480000000):
+ msgs.append(chirp_common.ValidationWarning(
+ _("Transmit frequency is outside the radio's transmit "
+ "bands and may be refused by the radio")))
+ return msgs
+
+ def _add(self, group, setting):
+ if setting is not None:
+ group.append(setting)
+
+ # A value outside the documented choices means this firmware uses the
+ # byte differently, so leave it alone rather than offer to change it.
+
+ def _list(self, path, name, choices, obj):
+ current = int(obj)
+ if current >= len(choices):
+ LOG.debug("Skipping %s: unexpected value %i", path, current)
+ return None
+ return MemSetting(path, name,
+ RadioSettingValueList(choices,
+ current_index=current))
+
+ def _bool(self, path, name, obj):
+ if int(obj) > 1:
+ LOG.debug("Skipping %s: unexpected value %i", path, int(obj))
+ return None
+ return MemSetting(path, name, RadioSettingValueBoolean(int(obj)))
+
+ def get_settings(self):
+ _s = self._memobj.settings
+ _st = self._memobj.status
+
+ func = RadioSettingGroup("func", "Function")
+ self._add(func, self._list(
+ "settings.dual_mode", "Dual mode", DUAL_MODES, _s.dual_mode))
+ self._add(func, self._list(
+ "status.a_mode", "Side A mode", WORK_MODES, _st.a_mode))
+ self._add(func, self._list(
+ "status.b_mode", "Side B mode", WORK_MODES, _st.b_mode))
+ for side in "ab":
+ current = int(getattr(_st, "%s_channel" % side))
+ if current < NUM_CHANNELS:
+ func.append(RadioSetting(
+ "%s_channel" % side,
+ "Side %s memory channel" % side.upper(),
+ RadioSettingValueInteger(
+ self.FIRST_CHANNEL,
+ self.FIRST_CHANNEL + NUM_CHANNELS - 1,
+ current + self.FIRST_CHANNEL)))
+ self._add(func, self._list(
+ "settings.squelch", "Squelch level", LEVELS9, _s.squelch))
+ self._add(func, self._list(
+ "settings.tot", "Transmit timeout", TOT, _s.tot))
+ self._add(func, self._list(
+ "settings.scan_mode", "Scan resume", SCAN_MODES, _s.scan_mode))
+ self._add(func, self._list(
+ "settings.tbst_freq", "Tone burst frequency", TBST_FREQS,
+ _s.tbst_freq))
+ self._add(func, self._bool(
+ "settings.save_mode", "Battery save", _s.save_mode))
+ self._add(func, self._list(
+ "settings.save_delay", "Battery save delay", SAVE_DELAY,
+ _s.save_delay))
+
+ disp = RadioSettingGroup("display", "Display")
+ self._add(disp, self._list(
+ "settings.language", "Language", LANGUAGES, _s.language))
+ self._add(disp, self._list(
+ "settings.theme", "Theme", THEMES, _s.theme))
+ self._add(disp, self._list(
+ "settings.backlight", "Backlight level", LEVELS9, _s.backlight))
+ self._add(disp, self._list(
+ "settings.auto_dim", "Auto dim", AUTO_DIM, _s.auto_dim))
+ self._add(disp, self._list(
+ "settings.menu_exit", "Menu auto exit", MENU_EXIT, _s.menu_exit))
+ self._add(disp, self._bool(
+ "settings.show_freq", "Show channel frequency", _s.show_freq))
+ self._add(disp, self._bool(
+ "settings.show_name", "Show channel name", _s.show_name))
+ self._add(disp, self._bool(
+ "settings.show_zone", "Show zone name", _s.show_zone))
+ self._add(disp, self._list(
+ "settings.bat_display", "Battery display", BAT_DISPLAY,
+ _s.bat_display))
+ self._add(disp, self._list(
+ "settings.rssi", "Signal strength", RSSI, _s.rssi))
+ self._add(disp, self._bool(
+ "settings.boot_logo", "Show boot logo", _s.boot_logo))
+ self._add(disp, self._bool(
+ "settings.boot_msg_on", "Show boot message", _s.boot_msg_on))
+ msg = _decode_name(_s.boot_msg.get_raw())
+ if not msg.isprintable():
+ msg = ""
+ disp.append(RadioSetting(
+ "boot_msg", "Boot message",
+ RadioSettingValueString(0, 50, msg, autopad=False,
+ charset=chirp_common.CHARSET_ASCII)))
+
+ audio = RadioSettingGroup("audio", "Audio")
+ self._add(audio, self._bool(
+ "settings.key_beep", "Key beep", _s.key_beep))
+ self._add(audio, self._bool(
+ "settings.low_bat_beep", "Low battery beep", _s.low_bat_beep))
+ self._add(audio, self._bool(
+ "settings.power_on_beep", "Power on beep", _s.power_on_beep))
+ self._add(audio, self._bool(
+ "settings.tot_beep", "Timeout beep", _s.tot_beep))
+ self._add(audio, self._bool(
+ "settings.roger_start", "Talk start beep", _s.roger_start))
+ self._add(audio, self._bool(
+ "settings.roger_end", "Talk end beep", _s.roger_end))
+ self._add(audio, self._list(
+ "settings.mic_gain", "Mic gain", MIC_GAIN, _s.mic_gain))
+ self._add(audio, self._bool(
+ "settings.vox", "VOX", _s.vox))
+ self._add(audio, self._bool(
+ "settings.ai_denoise", "AI noise reduction", _s.ai_denoise))
+
+ groups = [func, disp, audio]
+ if self._layout() in GROUP_COUNTS:
+ for kind, title in (("zone", "Zones"), ("scan", "Scan lists")):
+ group = RadioSettingGroup(kind, title)
+ names = getattr(self._memobj, "%s_names" % kind)
+ for i in range(GROUP_COUNTS[self._layout()]):
+ name = _decode_name(names[i].name)
+ if not name.isprintable():
+ name = ""
+ group.append(RadioSetting(
+ "%s_name_%i" % (kind, i), "%s %i name" % (
+ "Zone" if kind == "zone" else "Scan list", i),
+ RadioSettingValueString(
+ 0, 24, name, autopad=False,
+ charset=chirp_common.CHARSET_ASCII)))
+ groups.append(group)
+ return RadioSettings(*groups)
+
+ def set_settings(self, settings):
+ for element in settings.apply_to(self._memobj):
+ if element.get_name() in ("a_channel", "b_channel"):
+ setattr(self._memobj.status, element.get_name(),
+ int(element.value) - self.FIRST_CHANNEL)
+ elif element.get_name() == "boot_msg":
+ raw = str(element.value).encode("ascii")[:50]
+ self._memobj.settings.boot_msg = raw.ljust(50, b"\x00")
+ elif element.get_name()[4:10] == "_name_":
+ kind, i = element.get_name().split("_name_")
+ names = getattr(self._memobj, "%s_names" % kind)
+ raw = str(element.value).rstrip().encode("ascii")[:24]
+ names[int(i)].name = raw.ljust(24, b"\x00")
diff --git a/chirp/drivers/uv5r.py b/chirp/drivers/uv5r.py
index d4a5b24..a647ff9 100644
--- a/chirp/drivers/uv5r.py
+++ b/chirp/drivers/uv5r.py
@@ -921,7 +921,7 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
raw_tx = b""
for i in range(0, 4):
raw_tx += _mem.txfreq[i].get_raw()
- return raw_tx == b"\xFF\xFF\xFF\xFF"
+ return raw_tx in (b"\xFF\xFF\xFF\xFF", b"\x00\x00\x00\x00")
def _get_mem(self, number):
return self._memobj.memory[number]
@@ -1028,9 +1028,9 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("bcl", "BCL",
RadioSettingValueBoolean(_mem.bcl))
rs.set_doc(
- "Busy Channel Lockout. Prevents transmitting on this channel "
- "while the radio is receiving a signal, even when a different "
- "CTCSS tone or DCS code keeps that signal muted.")
+ "Prevents transmitting on a channel that is already in use. "
+ "Pressing PTT on a busy channel sounds an alert tone instead of "
+ "keying the transmitter.")
mem.extra.append(rs)
rs = RadioSetting("pttid", "PTT ID",
@@ -1213,28 +1213,30 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
RadioSettingValueInteger(0, 9, _settings.squelch))
rs.set_doc(
"Sets how strong a received signal must be before the speaker "
- "unmutes. 0 leaves the squelch open; higher values reject more "
- "weak signals and noise. The manual recommends 5 as a starting "
- "point.")
+ "unmutes. 0 leaves the squelch open so you hear noise all the "
+ "time, higher values reject more weak signals and noise. Raise "
+ "this value if the speaker keeps unmuting on interference, lower "
+ "it if distant stations are being cut off.")
basic.append(rs)
rs = RadioSetting("save", "Battery Saver",
RadioSettingValueList(
SAVE_LIST, current_index=_settings.save))
rs.set_doc(
- "Reduces standby battery use by periodically putting the "
- "receiver to sleep. Higher ratios save more power, but may "
- "delay reception of the beginning of a transmission.")
+ "Cuts standby power consumption by switching the receiver off and "
+ "on in a repeating cycle once no signal has been received for a "
+ "few seconds. It considerably extends battery life, at the cost "
+ "of occasionally clipping the first moment of an incoming "
+ "transmission.")
basic.append(rs)
rs = RadioSetting("vox", "VOX Sensitivity",
RadioSettingValueList(
VOX_LIST, current_index=_settings.vox))
rs.set_doc(
- "Allows voice-operated transmission without pressing PTT. "
- "Lower numbered levels are more sensitive; choose a level that "
- "responds to speech without being triggered by background "
- "noise, or select OFF to disable VOX.")
+ "Sets the VOX sensitivity. Too sensitive a setting keys the "
+ "transmitter on the noise around the radio, too insensitive a "
+ "setting fails to pick up your voice.")
advanced.append(rs)
if self.MODEL == "UV-6":
@@ -1244,9 +1246,9 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("autolk", "Vox",
RadioSettingValueBoolean(_settings.autolk))
rs.set_doc(
- "Enables voice-operated transmission. When "
- "enabled, speaking into the microphone can start "
- "transmission without pressing PTT.")
+ "Voice operated transmit. The radio starts transmitting "
+ "when you speak towards the microphone, so hands-free "
+ "conversation is possible without pressing PTT.")
advanced.append(rs)
if self.MODEL != "UV-6":
@@ -1286,9 +1288,8 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
RadioSettingValueList(
TDRAB_LIST, current_index=_settings.tdrab))
rs.set_doc(
- "Selects A or B as the transmit side while Dual Watch is "
- "enabled. Off leaves transmit selection under the radio's "
- "normal Dual Watch behavior.")
+ "Selects which side has transmit priority while Dual Watch "
+ "is enabled.")
advanced.append(rs)
if self.MODEL == "UV-6":
@@ -1313,16 +1314,18 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("beep", "Beep",
RadioSettingValueBoolean(_settings.beep))
rs.set_doc(
- "Enables the audible confirmation beep for keypad presses.")
+ "Sounds a short confirmation tone as you operate the radio. "
+ "Turn it off when the radio has to be used discreetly.")
basic.append(rs)
rs = RadioSetting("timeout", "Timeout Timer",
RadioSettingValueList(
TIMEOUT_LIST, current_index=_settings.timeout))
rs.set_doc(
- "Limits the length of one continuous transmission. When the "
- "selected time expires, the radio stops transmitting to help "
- "prevent overheating and an accidentally stuck transmitter.")
+ "Limits how long a single transmission may last. When the time "
+ "runs out the radio stops transmitting until PTT is released, "
+ "which prevents overheating and stops a stuck PTT from blocking "
+ "the channel for everyone else.")
basic.append(rs)
if ((self._is_orig() and self._my_version() < 251) or
@@ -1330,7 +1333,9 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("voice", "Voice",
RadioSettingValueBoolean(_settings.voice))
rs.set_doc(
- "Enables or disables spoken prompts for radio operations.")
+ "Announces the channel number and other operations out loud "
+ "as you use the radio. It can be intrusive in quiet "
+ "surroundings.")
advanced.append(rs)
else:
rs = RadioSetting("voice", "Voice",
@@ -1372,9 +1377,9 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("bcl", "Busy Channel Lockout",
RadioSettingValueBoolean(_settings.bcl))
rs.set_doc(
- "Prevents transmitting while the radio is receiving a signal. "
- "This helps avoid interrupting other users whose signal is "
- "muted by your selected CTCSS tone or DCS code.")
+ "Prevents transmitting on a channel that is already in use. "
+ "Pressing PTT on a busy channel sounds an alert tone instead of "
+ "keying the transmitter.")
advanced.append(rs)
if self.MODEL != "UV-6":
diff --git a/chirp/drivers/uv5x3.py b/chirp/drivers/uv5x3.py
index 1e1a98d..2c67e2b 100644
--- a/chirp/drivers/uv5x3.py
+++ b/chirp/drivers/uv5x3.py
@@ -120,6 +120,10 @@ class UV5X3(bfc.BaofengCommonHT):
(0x1FE0, 0x2000)]
_send_block_size = 0x10
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return len(filedata) == 0x200E and model_match(cls, filedata)
+
MODES = ["FM", "NFM"]
VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
"!@#$%^&*()+-=[]:\";'<>?,./"
@@ -1328,23 +1332,6 @@ class UV5X3(bfc.BaofengCommonHT):
return top
- @classmethod
- def match_model(cls, filedata, filename):
- match_size = False
- match_model = False
-
- # testing the file data size
- if len(filedata) == 0x200E:
- match_size = True
-
- # testing the firmware model fingerprint
- match_model = model_match(cls, filedata)
-
- if match_size and match_model:
- return True
- else:
- return False
-
@directory.register
class MTCUV5R3Radio(UV5X3):
diff --git a/chirp/drivers/uv6r.py b/chirp/drivers/uv6r.py
index 748f9c8..06c446e 100644
--- a/chirp/drivers/uv6r.py
+++ b/chirp/drivers/uv6r.py
@@ -109,6 +109,10 @@ class UV6R(bfc.BaofengCommonHT):
(0x1FE0, 0x1FF0)]
_send_block_size = 0x10
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return len(filedata) in (0x2008, 0x2010) and model_match(cls, filedata)
+
MODES = ["FM", "NFM"]
VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
"!@#$%^&*()+-=[]:\";'<>?,./"
@@ -842,20 +846,3 @@ class UV6R(bfc.BaofengCommonHT):
service.append(rs)
return top
-
- @classmethod
- def match_model(cls, filedata, filename):
- match_size = False
- match_model = False
-
- # testing the file data size
- if len(filedata) in (0x2008, 0x2010):
- match_size = True
-
- # testing the firmware model fingerprint
- match_model = model_match(cls, filedata)
-
- if match_size and match_model:
- return True
- else:
- return False
diff --git a/chirp/drivers/uvb5.py b/chirp/drivers/uvb5.py
index 8733f62..b9b33d1 100644
--- a/chirp/drivers/uvb5.py
+++ b/chirp/drivers/uvb5.py
@@ -488,6 +488,11 @@ class BaofengUVB5(chirp_common.CloneModeRadio,
_mem.scanadd = mem.skip == ""
_mem.highpower = mem.power == POWER_LEVELS[1]
+ _mem.bcl = 0
+ _mem.revfreq = 0
+ _mem.compander = 0
+ _mem.pttid = 0
+
if _nam:
for i in range(0, self.NAME_LENGTH):
try:
diff --git a/chirp/drivers/uvk5.py b/chirp/drivers/uvk5.py
index f0d9fbb..4a76edc 100644
--- a/chirp/drivers/uvk5.py
+++ b/chirp/drivers/uvk5.py
@@ -47,9 +47,13 @@ DEBUG_SHOW_OBFUSCATED_COMMANDS = False
# might be useful for someone debugging some obscure memory issue
DEBUG_SHOW_MEMORY_ACTIONS = False
-MEM_FORMAT = """
-#seekto 0x0000;
-struct {
+# Shared structure definitions. These are parsed together with the layout in
+# MEM_FORMAT below, but they can also be parsed on their own by a driver that
+# only needs a subset of the map; bitwise supports named struct definitions
+# used later as types. Keep every struct that a sibling driver shares here so
+# that the layouts cannot drift apart.
+MEM_DEFS = """
+struct memory {
ul32 freq;
ul32 offset;
u8 rxcode;
@@ -88,16 +92,27 @@ struct {
u8 step;
u8 scrambler;
-} channel[214];
+};
-#seekto 0xd60;
-struct {
+struct channel_attributes {
u8 is_scanlist1:1,
is_scanlist2:1,
compander:2,
is_free:1,
band:3;
-} channel_attributes[200];
+};
+
+struct channelname {
+char name[16];
+};
+"""
+
+MEM_FORMAT = MEM_DEFS + """
+#seekto 0x0000;
+struct memory channel[214];
+
+#seekto 0xd60;
+struct channel_attributes channel_attributes[200];
#seekto 0xe40;
ul16 fmfreq[20];
@@ -194,9 +209,7 @@ u8 enscramble;
} lock;
#seekto 0xf50;
-struct {
-char name[16];
-} channelname[200];
+struct channelname channelname[200];
#seekto 0x1c00;
struct {
@@ -491,15 +504,33 @@ def _resetradio(serport):
_send_command(serport, resetpacket)
+def _legal_airband_freq(freq):
+ """Return the airband channel that @freq corresponds to.
+
+ These radios store any multiple of their smallest step, so an airband
+ channel can end up holding a frequency that is not an airband channel at
+ all - 121.745MHz sits between two 25kHz channels, for example. CHIRP
+ models the airband as 25kHz and 8.33kHz channels, so hand back the channel
+ the stored value belongs to rather than a frequency that fails the shared
+ validation.
+ """
+ if not chirp_common.is_airband(freq):
+ return freq
+ try:
+ chirp_common.fix_rounded_step(freq)
+ except errors.InvalidDataError:
+ # Not one of the three sub-channels of this 25kHz block: take the
+ # nearest channel, including the base of the following block
+ base = freq // 25000 * 25000
+ channels = [base + (25000 // 3) * index for index in range(4)]
+ return min(channels, key=lambda hz: (abs(hz - freq), hz))
+ return freq
+
+
def do_download(radio):
"""download eeprom from radio"""
serport = radio.pipe
serport.timeout = 0.5
- status = chirp_common.Status()
- status.cur = 0
- status.max = MEM_SIZE
- status.msg = "Downloading from radio"
- radio.status_fn(status)
eeprom = b""
f = _sayhello(serport)
@@ -512,18 +543,28 @@ def do_download(radio):
radio.metadata = {'uvk5_firmware': f}
+ # The size is asked for after the handshake on purpose: a subclass may
+ # decide it from the firmware that just answered, which is what makes
+ # "no image loaded yet" work for radios bigger than the stock EEPROM.
+ size = radio.mem_size
+ radio._check_download_size(size)
+ status = chirp_common.Status()
+ status.cur = 0
+ status.max = size
+ status.msg = "Downloading from radio"
+ radio.status_fn(status)
+
+ block = radio.read_block
addr = 0
- while addr < MEM_SIZE:
- data = _readmem(serport, addr, MEM_BLOCK)
+ while addr < size:
+ data = radio._read_mem_block(serport, addr, block)
+ if not data or len(data) != block:
+ raise errors.RadioError("Memory download incomplete")
+ eeprom += data
+ addr += block
status.cur = addr
radio.status_fn(status)
- if data and len(data) == MEM_BLOCK:
- eeprom += data
- addr += MEM_BLOCK
- else:
- raise errors.RadioError("Memory download incomplete")
-
return memmap.MemoryMapBytes(eeprom)
@@ -536,13 +577,13 @@ def do_upload(radio):
status.msg = "Uploading to radio"
if radio._upload_calibration:
- status.max = MEM_SIZE - radio._cal_start
+ status.max = radio.mem_size - radio._cal_start
start_addr = radio._cal_start
- stop_addr = MEM_SIZE
+ stop_addr = radio.mem_size
else:
- status.max = PROG_SIZE
+ status.max = radio.prog_size
start_addr = 0
- stop_addr = PROG_SIZE
+ stop_addr = radio.prog_size
radio.status_fn(status)
@@ -555,14 +596,18 @@ def do_upload(radio):
'Firmware version is not supported by this driver')
LOG.info('Uploading image from firmware %r to radio with %r',
radio.metadata.get('uvk5_firmware', 'unknown'), f)
+
+ image = radio.get_mmap()
+ radio._check_upload_image(len(image), f)
+ block = radio.write_block
addr = start_addr
while addr < stop_addr:
- dat = radio.get_mmap()[addr:addr+MEM_BLOCK]
- _writemem(serport, dat, addr)
+ dat = image[addr:addr+block]
+ radio._write_mem_block(serport, dat, addr)
status.cur = addr - start_addr
radio.status_fn(status)
if dat:
- addr += MEM_BLOCK
+ addr += block
else:
raise errors.RadioError("Memory upload incomplete")
status.msg = "Uploaded OK"
@@ -602,6 +647,42 @@ class UVK5RadioBase(chirp_common.CloneModeRadio):
_langs = ["Chinese", "English"]
_backlight = ["Off"] + ['%is' % (i + 1) for i in range(5)]
+ # Clone geometry. The module level constants above are the stock
+ # defaults; a subclass whose EEPROM is larger, or that needs a different
+ # block size for reads than for writes, overrides these instead of
+ # replacing do_download() / do_upload() with a copy of the whole loop.
+ mem_size = MEM_SIZE
+ prog_size = PROG_SIZE
+ read_block = MEM_BLOCK
+ write_block = MEM_BLOCK
+
+ # Encoding of the name field. Stock radios store bytes that decode as
+ # latin-1; a driver for firmware that stores Chinese text overrides this.
+ NAME_ENCODING = 'latin-1'
+
+ def _check_download_size(self, size):
+ """Hook: raise RadioError if @size bytes may not be read."""
+
+ def _check_upload_image(self, image_size, firmware):
+ """Hook: raise RadioError if this image may not be written."""
+
+ def _read_mem_block(self, serport, offset, length):
+ """Hook: transport used by do_download(); some firmware differs."""
+ return _readmem(serport, offset, length)
+
+ def _write_mem_block(self, serport, data, offset):
+ """Hook: transport used by do_upload(); some firmware differs."""
+ return _writemem(serport, data, offset)
+
+ def _decode_name(self, raw):
+ """Decode a name field that ends at NUL or 0xFF."""
+ end = len(raw)
+ for index, byte in enumerate(raw):
+ if byte in (0x00, 0xFF):
+ end = index
+ break
+ return raw[:end].decode(self.NAME_ENCODING, 'replace').rstrip()
+
@classmethod
def k5_approve_firmware(cls, firmware):
# All subclasses must implement this
@@ -903,15 +984,14 @@ class UVK5RadioBase(chirp_common.CloneModeRadio):
if number > 199:
mem.immutable = ["name", "scanlists"]
else:
- _mem2 = self._memobj.channelname[number]
- for char in _mem2.name:
- if str(char) == "\xFF" or str(char) == "\x00":
- break
- mem.name += str(char)
- mem.name = mem.name.rstrip()
+ # The name field is bytes, not text: read it raw so that a
+ # driver with a different encoding can decode it itself, and so
+ # that no str is ever assigned to the char array.
+ mem.name = self._decode_name(
+ self._memobj.channelname[number].get_raw())
# Convert your low-level frequency to Hertz
- mem.freq = int(_mem.freq)*10
+ mem.freq = _legal_airband_freq(int(_mem.freq)*10)
mem.offset = int(_mem.offset)*10
if (mem.offset == 0):
@@ -1893,7 +1973,7 @@ class UVK5RadioBase(chirp_common.CloneModeRadio):
return mem
# clean the channel memory, restore some bits if it was used before
- if _mem.get_raw(asbytes=False)[0] == "\xff":
+ if _mem.get_raw()[0] == 0xff:
# this was an empty memory
_mem.set_raw(b"\x00" * 16)
else:
@@ -1944,9 +2024,14 @@ class UVK5RadioBase(chirp_common.CloneModeRadio):
# channels >200 are the 14 VFO chanells and don't have names
if number < 200:
- _mem2 = self._memobj.channelname[number]
- tag = mem.name.ljust(10) + "\x00"*6
- _mem2.name = tag # Store the alpha tag
+ # Byte-native, so that no str is assigned to the char array and
+ # a subclass with a different name encoding can rewrite it after
+ # calling super(). This is byte for byte what the previous
+ # str-based version produced: latin-1 bytes, space padded to 10,
+ # then six NULs.
+ tag = mem.name.encode('latin-1')
+ tag = tag[:10].ljust(10, b' ') + b'\x00' * 6
+ self._memobj.channelname[number].set_raw(tag)
# tone data
self._set_tone(mem, _mem)
@@ -1986,18 +2071,9 @@ class UVK5RadioBase(chirp_common.CloneModeRadio):
_mem.scrambler & 0xf0) | SCRAMBLER_LIST.index(svalue)
if number < 200 and sname == "scanlists":
- if svalue == "1":
- _mem4.channel_attributes[number].is_scanlist1 = 1
- _mem4.channel_attributes[number].is_scanlist2 = 0
- elif svalue == "2":
- _mem4.channel_attributes[number].is_scanlist1 = 0
- _mem4.channel_attributes[number].is_scanlist2 = 1
- elif svalue == "1+2":
- _mem4.channel_attributes[number].is_scanlist1 = 1
- _mem4.channel_attributes[number].is_scanlist2 = 1
- else:
- _mem4.channel_attributes[number].is_scanlist1 = 0
- _mem4.channel_attributes[number].is_scanlist2 = 0
+ _attr = _mem4.channel_attributes[number]
+ _attr.is_scanlist1 = '1' in svalue
+ _attr.is_scanlist2 = '2' in svalue
return mem
@@ -2009,7 +2085,7 @@ class UVK5Radio(UVK5RadioBase):
approved_prefixes = (
# These are the original OEM firmware versions
'k5_2.01.', 'app_2.01.', '2.01.', '3.00.',
- '4.00.', 'k5_4.00.', '5.00.', '7.00.',
+ '4.00.', 'k5_4.00.', '5.00.', '7.00.', '7.01.',
# This "oneofeeleven" prefix really covers a wide range of
# firmwares that are user-built, but people report them working
# fine with the base driver.
diff --git a/chirp/drivers/uvk5_cn.py b/chirp/drivers/uvk5_cn.py
new file mode 100644
index 0000000..5c2b2de
--- /dev/null
+++ b/chirp/drivers/uvk5_cn.py
@@ -0,0 +1,763 @@
+# Quansheng UV-K5 / UV-K6 driver for Chinese third-party firmware
+# with GB2312 channel names (LOSEHU / LTS / UVE expanded builds)
+#
+# Copyright 2026 赵昕 BG8ADW
+#
+# Based on the Quansheng UV-K5 driver:
+# Quansheng UV-K5 driver (c) 2023 Jacek Lipkowski <sq5bpf@lipkowski.org>
+# based on template.py Copyright 2012 Dan Smith <dsmith@danplanet.com>
+#
+# and on the reversed protocol and memory notes of the k5web project (MIT
+# licensed): k5web/src/utils/serial.js,
+# k5web/src/components/navbar/index.vue,
+# k5web/src/views/list/search-table/index.vue
+#
+# 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/>.
+
+"""Quansheng UV-K5/UV-K6 running expanded Chinese third-party firmware.
+
+This covers the builds that store channel names as GB2312 and that need the
+split-address EEPROM commands (0x2B read / 0x38 write): the LOSEHU expanded
+builds, LTS, and UVE. Everything else is inherited from ``uvk5.py``.
+
+WHAT CHANGES RELATIVE TO THE BASE DRIVER
+----------------------------------------
+The channel record, the channel attribute bytes and the name array are at
+the same offsets with the same layout as the stock radio - verified against
+the firmware's own write path (``settings.c:691-711``) and against k5web's
+``readChannel``/``writeChannel`` - so ``MEM_FORMAT`` here is
+``uvk5.MEM_DEFS`` plus only the three arrays this driver models. The deltas
+are:
+
+* an alternate EEPROM command pair with a split 32 bit address, and a
+ different command geometry (0x40 byte writes, computed header size);
+* GB2312 channel names, and the firmware's own editor limit for them;
+* a larger EEPROM, sized per profile, and a refusal to touch the
+ multi-bootloader region that sits above 0x40000 on these builds.
+
+THE COMMAND TIMESTAMP
+---------------------
+The firmware remembers the four byte timestamp of the hello command and
+silently drops any later command that carries a different one - no reply, no
+error, indistinguishable from a dead radio:
+
+ app/uart.c:243 CMD_0514 (hello): Timestamp = pCmd->Timestamp;
+ app/uart.c:264 CMD_051B: if (pCmd->Timestamp != Timestamp) return;
+ app/uart.c:298 CMD_051D: same
+ app/uart.c:584 CMD_052B: same
+ app/uart.c:613 CMD_0538: same
+
+``uvk5._sayhello()`` sends ``6a 39 57 64`` (``uvk5.py:436``) and upstream's
+own commands send the same bytes (``uvk5.py:464,474``), so this driver sends
+exactly those bytes too (``TIMESTAMP`` below) and the unit tests assert that
+the hello packet and both command bodies agree. k5web sends ``FF FF FF FF``
+for both its handshake and its commands and is equally self consistent;
+mixing the two makes every read and write after the handshake fail silently.
+
+CHANNEL NAMES
+-------------
+These builds store names as plain GB2312 double byte characters - first byte
+>= 0xA1, glyph looked up by classic GB2312 code order
+(``ui/helper.c:246-253``) - which the capture confirms on real hardware.
+The field is 16 bytes but the radio's own menu only edits
+``MAX_EDIT_INDEX`` of them, 13 for these builds (``font.h:28``), so that is
+``valid_name_length``. A name that does not fit the field at all is
+rejected; a name that fits the field but is longer than the editor limit is
+kept as it is (real radios carry them) and is left byte for byte alone if
+the user only edits something else on that channel.
+
+EEPROM SIZE AND WRITE SAFETY
+----------------------------
+The size comes from, in order: the loaded image, the profile default, and
+the user's "EEPROM size" setting. The default for every profile this driver
+claims is 0x40000: a live scan of the reference radio (stride 0x8000 over
+0..0x100000) shows user data at 0x00000-0x02FFF including the pinyin area at
+0x20000, mostly erased bytes at 0x030000-0x03FFFF, and the multi-bootloader
+from 0x040000 ("_BL002" at 0x40008), with the space aliasing with a period
+of 0x80000 above that.
+
+The 0x040000-0x07FFFF region is the multi-bootloader that some of these
+builds install, and a stray write into it can leave the radio unbootable in
+a way CHIRP cannot repair - the one place where the Chinese firmware is
+strictly more dangerous than an OEM UV-K5. So nothing at or above
+``DATA_LIMIT`` is ever read or written, an image that extends into it is
+refused, and a normal upload only writes ``PROG_SIZE`` (0x1d00) bytes at
+all, which means the fonts, the welcome text, the FM broadcast presets, the
+pinyin blobs and the bootloader region are preserved by never being written.
+
+VERIFICATION STATUS
+-------------------
+Verified against a real radio (LOSEHU131HS, 2026-10-13, Prolific PL2303GS
+on COM9): the hello handshake and its version string, both EEPROM read
+command pairs including 0x2B addressing past 0x10000 where the stock 0x1B
+command wraps at 0xFFFF, the channel record fields, the channel attribute
+bytes and the GB2312 name encoding (channel 1 of the capture reads
+435.5875 MHz simplex with the name "私有频点"), the write command 0x38 at a
+low address and at 0x01E1E8 (the 32 bit path), a whole-image write and
+read-back that differed in 0 bytes, and determinism across dump sessions.
+
+NOT verified on a real radio: CHIRP's own clone path end to end, and the
+region above PROG_SIZE, which this driver never writes. Other builds in this
+family are handled by the follow-up work noted in the pull request rather
+than by guessing here; radios this driver does not claim are offered as
+read-only images.
+"""
+
+import logging
+import re
+import struct
+
+from chirp import chirp_common, directory, bitwise, errors
+from chirp.drivers import uvk5
+from chirp.settings import RadioSetting, RadioSettingGroup, \
+ RadioSettingValueBoolean, RadioSettingValueList, \
+ RadioSettingValueString, RadioSettings
+
+LOG = logging.getLogger(__name__)
+
+# Only the three arrays this driver models, built on the definitions shared
+# with the base driver so that the channel record, the attributes and the
+# name array cannot drift apart from it.
+MEM_FORMAT = uvk5.MEM_DEFS + """
+#seekto 0x0000;
+struct memory channel[214];
+
+#seekto 0xd60;
+struct channel_attributes channel_attributes[200];
+
+#seekto 0xf50;
+struct channelname channelname[200];
+"""
+
+# The firmware stores the hello command's timestamp and drops any later
+# command that carries a different one (see the module docstring). These are
+# the same four bytes uvk5._sayhello() sends, so the handshake and our
+# commands always agree.
+TIMESTAMP = b'\x6a\x39\x57\x64'
+
+# Highest EEPROM address this driver will ever read or write. 0x040000 and
+# above is the multi-bootloader on these builds (see the module docstring).
+DATA_LIMIT = 0x40000
+
+# Size of the channel name field on disk, and how many bytes of it the
+# radio's own menu will store (font.h:28, ENABLE_CHINESE_FULL == 4).
+NAME_LENGTH = 16
+NAME_BYTES = 13
+
+# EEPROM sizes offered by k5web (serial.js check_eeprom, card/index.vue).
+EEPROM_SIZES = (0x2000, 0x10000, 0x20000, 0x40000, 0x80000)
+EEPROM_SIZE_LABELS = (
+ '0x2000 (8 KiB)',
+ '0x10000 (64 KiB)',
+ '0x20000 (128 KiB)',
+ '0x40000 (256 KiB)',
+ '0x80000 (512 KiB)',
+)
+EEPROM_SIZE_CHOICES = dict(zip(EEPROM_SIZE_LABELS, EEPROM_SIZES))
+
+# Ordered firmware regular expression -> profile name -> EEPROM size in
+# bytes, transcribed from k5web navbar/index.vue:230-254 (which matches with
+# RegExp.test(), i.e. an unanchored search, and keeps the first match).
+#
+# Only the profiles that this driver implements are listed here. The rest of
+# k5web's table - the stock 0x1B/0x1D builds (losehu117, losehu118, lts) and
+# the font-mapped builds (losehu117k, ltsk and the LTS sub-font builds) - is
+# deliberately left out: they take different code paths that no capture here
+# exercises, so they fall through to the read-only fallback below. See the
+# follow-up work noted in the pull request.
+#
+# The version string comes from the radio's hello reply (command 0x0514,
+# reply 0x0515, offset 4, up to 16 ASCII bytes: app/uart.c:76,206-220) and is
+# the build's PACKED_FILE_SUFFIX (version.h:27, version.c:22, Makefile:309) -
+# NOT the ``*OEFW-<author>`` flash header that fw-pack.py inserts at 0x2000,
+# which must never be allowlisted.
+#
+# Sizes: every profile here is an expanded build, and a live scan of the
+# reference radio shows user data ending before 0x40000 with the
+# multi-bootloader starting there, so 0x40000 is the sensible default.
+CN_PROFILES = (
+ (r'L_BL[0-9][0-9][0-9]', 'losehubl', 0x40000),
+ (r'LOSEHU.*D', 'losehud', 0x40000),
+ (r'UVE.*', 'losehu124h', 0x40000),
+ (r'LOSEHU13[0-9].*HS', 'losehu124h', 0x40000),
+ (r'LOSEHU13[0-9].*H', 'losehu124h', 0x40000),
+ (r'LOSEHU13[0-9].*KS', 'losehu120k', 0x40000),
+ (r'LOSEHU13[0-9].*K', 'losehu120k', 0x40000),
+ (r'LOSEHU12[4-9].*HS', 'losehu124h', 0x40000),
+ (r'LOSEHU12[4-9].*H', 'losehu124h', 0x40000),
+ (r'LOSEHU12[0-3].*H', 'losehu118h', 0x40000),
+ (r'LOSEHU12[0-9].*KS', 'losehu120k', 0x40000),
+ (r'LOSEHU12[0-9].*K', 'losehu120k', 0x40000),
+ (r'LOSEHU11[8-9].*H', 'losehu118h', 0x40000),
+ (r'LOSEHU11[8-9].*K', 'losehu118k', 0x40000),
+ # Any other LOSEHU1xx build: recognised, but not claimed, so it comes up
+ # as a read-only image instead of being driven on a guess.
+ (r'LOSEHU1[0-9][0-9].*', 'todo', 0x2000),
+ # The UV-K1 is a different radio, handled by uvk5.UVK1Radio.
+ (r'7\..*', 'k1', 0x2000),
+ (r'.*', 'todo', 0x2000),
+)
+
+# Tuning steps offered by these firmwares; the channel record stores the
+# index into this list in a whole byte. Transcribed from k5web
+# search-table/index.vue (stepOption); 24 entries, which is also
+# STEP_N_ELEM in the firmware (frequencies.h:45-73).
+CN_STEPS = (2.50, 5.00, 6.25, 10.00, 12.50, 25.00, 8.33, 0.01, 0.05, 0.10,
+ 0.25, 0.50, 1.00, 1.25, 9.00, 15.00, 20.00, 30.00, 50.00, 100.00,
+ 125.00, 200.00, 250.00, 500.00)
+
+# Band edges used by k5web to pick the band byte it stores in the channel
+# attributes (search-table/index.vue freqRange, and the reduce/indexOf pair
+# on write): the index of the highest edge below the RX frequency. These are
+# the firmware's own boundaries (frequencies.c:37-44).
+CN_BAND_EDGES = (50.0, 108.0, 136.0, 174.0, 350.0, 400.0, 470.0)
+
+# Wide coverage of the "limits removed" firmwares, half open [lo, hi) to
+# match RadioFeatures.validate_memory().
+CN_BANDS = (
+ (18000000, 108000000),
+ (108000000, 137000000),
+ (137000000, 174000000),
+ (174000000, 350000000),
+ (350000000, 400000000),
+ (400000000, 470000000),
+ (470000000, 1300000000),
+)
+
+_GB2312_CHARSET = None
+
+
+def gb2312_charset():
+ """Return every character a GB2312 channel name field can hold."""
+ global _GB2312_CHARSET
+ if _GB2312_CHARSET is None:
+ chars = set(chirp_common.CHARSET_ASCII)
+ for lead in range(0x81, 0xFF):
+ for trail in range(0x40, 0xFF):
+ try:
+ chars.add(bytes([lead, trail]).decode('gb2312'))
+ except UnicodeDecodeError:
+ continue
+ _GB2312_CHARSET = ''.join(sorted(chars))
+ return _GB2312_CHARSET
+
+
+def cn_profile(firmware):
+ """Return the k5web profile name for @firmware.
+
+ k5web uses ``new RegExp(pattern).test(version)`` and keeps the first
+ match, i.e. an unanchored search over an ordered table.
+ """
+ for pattern, profile, _size in CN_PROFILES:
+ if re.search(pattern, firmware):
+ return profile
+ return 'todo'
+
+
+def profile_mem_size(firmware):
+ """Return the default EEPROM size for @firmware, in bytes."""
+ for pattern, _profile, size in CN_PROFILES:
+ if re.search(pattern, firmware):
+ return size
+ return 0x2000
+
+
+def _encode_char(char):
+ try:
+ return char.encode('gb2312')
+ except UnicodeEncodeError:
+ return b'?'
+
+
+def encode_name_prefix(name, limit=NAME_BYTES):
+ """Encode as many characters of @name as fit in @limit bytes.
+
+ A two byte character is never cut in half.
+ """
+ out = bytearray()
+ for char in name:
+ encoded = _encode_char(char)
+ if len(out) + len(encoded) > limit:
+ break
+ out += encoded
+ return bytes(out)
+
+
+def encode_name(name, limit=NAME_BYTES):
+ """Encode @name into exactly NAME_LENGTH bytes, NUL padded."""
+ return encode_name_prefix(name, limit).ljust(NAME_LENGTH, b'\x00')
+
+
+def name_fits(name, limit=NAME_LENGTH):
+ """True if every character of @name fits in @limit bytes."""
+ return len(b''.join(_encode_char(char) for char in name)) <= limit
+
+
+def decode_name(raw):
+ """Decode a NAME_LENGTH byte GB2312 channel name field.
+
+ Mirrors k5web serial.js uint8ArrayToString() and the firmware's own
+ convention (``settings.c:414-417``: NUL terminated, trailing spaces
+ trimmed by the caller): the name ends at 0x00 or 0xFF; a byte >= 0x80
+ starts a two byte character, and if the field ends in the middle of one -
+ or the pair is not valid GB2312 - the rest of the name is still decoded
+ instead of being dropped.
+ """
+ out = []
+ index = 0
+ raw = bytes(raw)
+ while index < len(raw):
+ byte = raw[index]
+ if byte in (0x00, 0xFF):
+ break
+ if byte < 0x80:
+ out.append(chr(byte))
+ index += 1
+ continue
+ if index + 1 >= len(raw) or raw[index + 1] in (0x00, 0xFF):
+ # The field ends in the middle of a two byte character
+ break
+ try:
+ out.append(bytes(raw[index:index + 2]).decode('gb2312'))
+ except UnicodeDecodeError:
+ out.append('?')
+ index += 2
+ return ''.join(out)
+
+
+def readmem_command(offset, length):
+ """Build the alternate EEPROM read command (0x2B) for @offset.
+
+ Layout from k5web serial.js:1458 and the firmware's CMD_052B
+ (``app/uart.c:578-604``), including the timestamp rule above.
+ """
+ return b'\x2b\x05\x08\x00' + \
+ struct.pack('<HBB', (offset >> 16) & 0xffff, length, 0) + \
+ TIMESTAMP + \
+ struct.pack('<H', offset & 0xffff)
+
+
+def writemem_command(offset, data):
+ """Build the alternate EEPROM write command (0x38) for @offset.
+
+ Layout per the firmware's own CMD_0538 (``app/uart.c:614-649``): ID,
+ header size, address bits 16-31, size, bAllowPassword, timestamp, then
+ the data whose first two bytes are address bits 0-15. The header size
+ counts everything after the four byte header, so it is 10 + len(data);
+ k5web hardcodes 0x1c there (``serial.js:1552``) and the firmware
+ tolerates that, but the computed value is what the firmware documents.
+ """
+ return b'\x38\x05' + \
+ struct.pack('<H', 10 + len(data)) + \
+ struct.pack('<HBB', (offset >> 16) & 0xffff, len(data) + 2, 0) + \
+ TIMESTAMP + \
+ struct.pack('<H', offset & 0xffff) + data
+
+
+def _readmem(serport, offset, length):
+ """Read @length bytes at @offset with the alternate command."""
+ if offset < 0 or offset + length > DATA_LIMIT:
+ raise errors.RadioError(
+ _('Refusing to read 0x%4.4x..0x%4.4x: this driver only reads '
+ 'below 0x%4.4x') % (offset, offset + length - 1, DATA_LIMIT))
+ serport.log('Sending readmem (cn) offset=0x%4.4x len=0x%4.4x' % (
+ offset, length))
+ uvk5._send_command(serport, readmem_command(offset, length))
+ rep = uvk5._receive_reply(serport)
+ if len(rep) < 8 + length:
+ LOG.warning('Short readmem reply: got %i bytes, wanted %i',
+ len(rep), 8 + length)
+ raise errors.RadioError('Short response to readmem')
+ # The firmware does not appear to validate the request's size field (the
+ # reference radio answers with 0x08 and with 0x0A alike), so the reply's
+ # size byte is only reported, never asserted on.
+ if rep[6] != length:
+ LOG.debug('readmem reply size is 0x%2.2x, wanted 0x%2.2x',
+ rep[6], length)
+ return rep[8:8 + length]
+
+
+def _writemem(serport, data, offset):
+ """Write @data at @offset with the alternate command.
+
+ Anything at or above DATA_LIMIT is the multi-bootloader region and is
+ refused outright: a stray write there can leave the radio unbootable.
+ """
+ if offset < 0 or offset + len(data) > DATA_LIMIT:
+ raise errors.RadioError(
+ _('Refusing to write 0x%4.4x..0x%4.4x: 0x%4.4x is the start of '
+ 'the multi-bootloader on this firmware and writing there can '
+ 'destroy the radio') % (offset, offset + len(data) - 1,
+ DATA_LIMIT))
+ serport.log('Writemem (cn) at offset %04x len %04x' % (offset, len(data)))
+ uvk5._send_command(serport, writemem_command(offset, data))
+ rep = uvk5._receive_reply(serport)
+ if rep and rep[0] == 0x1e:
+ return True
+ LOG.warning('Bad data from writemem (cn)')
+ raise errors.RadioError('Bad response to writemem')
+
+
+def _find_band_cn(hz):
+ """Return the band byte k5web stores for @hz, or False if out of range."""
+ if not CN_BANDS[0][0] <= hz < CN_BANDS[-1][1]:
+ return False
+ mhz = hz / 1000000.0
+ band = 0
+ for index, edge in enumerate(CN_BAND_EDGES):
+ if edge < mhz:
+ band = index
+ return band
+
+
+@directory.register
+@directory.detected_by(uvk5.UVK5Radio)
+class UVK5LoseHuRadio(uvk5.UVK5RadioBase):
+ """Quansheng UV-K5/K6 with expanded Chinese firmware"""
+
+ VENDOR = "Quansheng"
+ MODEL = "UV-K5"
+ VARIANT = "losehu"
+ BAUD_RATE = 38400
+
+ # Reads use 0x80, the largest reply the firmware's reply structure can
+ # carry (``app/uart.c:100-108``). Writes use 0x40: the firmware's
+ # receive buffer would take 0x80 (``app/uart.c:24,172``) but 0x40 is
+ # what k5web uses on every write path (``serial.js:1534``) and what has
+ # been exercised on hardware. 0x1d00 is a multiple of 0x40, so there is
+ # never a short final chunk.
+ #
+ # PROG_SIZE stops before the calibration area at 0x1E00
+ # (settings.c:314,319,323,332,333,352; the AES key is at 0x0F30,
+ # settings.c:294-297), which is unique per radio; everything this driver
+ # maps lives below 0x1D00 anyway.
+ MEM_BLOCK = 0x80
+ WRITE_BLOCK = 0x40
+ PROG_SIZE = 0x1d00
+ DEFAULT_MEM_SIZE = 0x2000
+
+ # Clone geometry that uvk5.do_download()/do_upload() pick up from the
+ # radio class instead of the module constants, so the clone loop does not
+ # have to be copied here.
+ read_block = MEM_BLOCK
+ write_block = WRITE_BLOCK
+ prog_size = PROG_SIZE
+
+ @property
+ def mem_size(self):
+ """How much EEPROM the clone loops should cover."""
+ return self.eeprom_size
+
+ # Profiles this class answers for. The rest of k5web's table stays out
+ # of this class on purpose (see CN_PROFILES).
+ _CN_PROFILES = frozenset((
+ 'losehubl', 'losehu118h', 'losehu118k', 'losehu120k', 'losehu124h',
+ 'losehud'))
+
+ _steps = CN_STEPS
+ _expanded_limits = True
+
+ def __init__(self, pipe):
+ # Must be set before super().__init__(), which loads an image and
+ # calls process_mmap() when we are constructed from a filename.
+ self._eeprom_size = None
+ super().__init__(pipe)
+
+ @classmethod
+ def k5_approve_firmware(cls, firmware):
+ return cn_profile(firmware) in cls._CN_PROFILES
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.experimental = _(
+ 'This is an experimental driver for Quansheng UV-K5/UV-K6 radios '
+ 'running expanded Chinese third-party firmware (LOSEHU, LTS, '
+ 'UVE), which store channel names as GB2312 and use the split '
+ 'address EEPROM commands.\n\n'
+ 'It has been verified against one such radio, a LOSEHU131HS '
+ 'build: downloading, uploading and a whole-image read-back were '
+ 'checked there. Other builds in this family may behave '
+ 'differently, and a wrong write can harm your radio. Use at your '
+ 'own risk, and keep the image you download before changing '
+ 'anything: it can be used to restore the radio.\n\n'
+ '- Writing at or above 0x40000 would overwrite the '
+ 'multi-bootloader that some of these builds install there, so '
+ 'this driver never writes that high and refuses an image that '
+ 'extends into it.\n'
+ '- The default EEPROM size is derived from the reported firmware '
+ 'version and is only a guess; check the "EEPROM size" setting '
+ 'against your radio before uploading.\n'
+ '- Settings (keys, DTMF, MDC, scan lists, boot logo, satellite '
+ 'data, calibration) are not supported.')
+ rp.pre_download = _(
+ '1. Turn the radio on.\n'
+ '2. Connect the cable to the mic/speaker connector.\n'
+ '3. Make sure the connector is firmly seated.\n'
+ '4. Click OK to download the image from the device.\n\n'
+ 'It may not work if you turn the radio on with the cable '
+ 'already attached.')
+ rp.pre_upload = _(
+ '1. Turn the radio on.\n'
+ '2. Connect the cable to the mic/speaker connector.\n'
+ '3. Make sure the connector is firmly seated.\n'
+ '4. Click OK to upload the image to the device.\n\n'
+ 'It may not work if you turn the radio on with the cable '
+ 'already attached.')
+ return rp
+
+ @property
+ def eeprom_size(self):
+ """Size of the EEPROM image in bytes.
+
+ A loaded image is authoritative. Otherwise the profile of the
+ firmware on the radio decides, and the user can override it with the
+ "EEPROM size" setting.
+ """
+ if self._eeprom_size:
+ return self._eeprom_size
+ return profile_mem_size(self.metadata.get('uvk5_firmware', ''))
+
+ def _get_valid_bands(self):
+ if self._expanded_limits:
+ return CN_BANDS
+ return tuple((int(lo * 1000000), int(hi * 1000000))
+ for lo, hi in uvk5.BANDS.values())
+
+ def _find_band(self, hz):
+ if self._expanded_limits:
+ return _find_band_cn(hz)
+ return uvk5._find_band(False, hz)
+
+ def _get_specials(self):
+ # The stock driver exposes 14 VFO channels above channel 200, modelled
+ # as 16 byte records. These firmwares store them as 32 byte records
+ # at 0x0C80 (``settings.c:681-682``), which no capture here
+ # exercises, so they are not offered.
+ return {}
+
+ def get_features(self):
+ rf = super().get_features()
+ rf.valid_special_chans = []
+ rf.valid_name_length = NAME_BYTES
+ rf.valid_characters = gb2312_charset()
+ rf.valid_tuning_steps = list(self._steps)
+ rf.valid_bands = self._get_valid_bands()
+ return rf
+
+ def process_mmap(self):
+ self._check_firmware_at_load()
+ self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+ # The image tells us how much EEPROM was actually read
+ self._eeprom_size = len(self._mmap)
+
+ def _check_download_size(self, size):
+ if size > DATA_LIMIT:
+ raise errors.RadioError(
+ _('The EEPROM size is set to 0x%(size)x bytes, but this '
+ 'driver only reads below 0x%(limit)x; 0x%(limit)x and '
+ 'above is the multi-bootloader on these firmwares. '
+ 'Correct the "EEPROM size" setting.') % {
+ 'size': size, 'limit': DATA_LIMIT})
+
+ def _check_upload_image(self, image_size, firmware):
+ if self.eeprom_size > DATA_LIMIT:
+ raise errors.RadioError(
+ _('The EEPROM size is set to 0x%(size)x bytes, but this '
+ 'driver only writes below 0x%(limit)x; 0x%(limit)x and '
+ 'above is the multi-bootloader on these firmwares. '
+ 'Correct the "EEPROM size" setting.') % {
+ 'size': self.eeprom_size, 'limit': DATA_LIMIT})
+ if image_size > DATA_LIMIT:
+ raise errors.RadioError(
+ _('Image is %(image)i bytes, but this driver only writes '
+ 'below 0x%(limit)x; 0x%(limit)x and above is the '
+ 'multi-bootloader on these firmwares and writing there '
+ 'can destroy the radio. Use an image that stops before '
+ 'it.') % {'image': image_size, 'limit': DATA_LIMIT})
+ if image_size != self.eeprom_size:
+ image_fw = self.metadata.get('uvk5_firmware', '')
+ raise errors.RadioError(
+ _('Image is %(image)i bytes from firmware %(image_fw)r '
+ '(profile %(image_profile)s). The radio reports firmware '
+ '%(radio_fw)r (profile %(radio_profile)s), which suggests '
+ '%(default)i bytes, and the EEPROM size setting is %(size)i '
+ 'bytes.\nLoad an image of the right size, or set the EEPROM '
+ 'size to the real size.') % {
+ 'image': image_size,
+ 'image_fw': image_fw,
+ 'image_profile': cn_profile(image_fw),
+ 'radio_fw': firmware,
+ 'radio_profile': cn_profile(firmware),
+ 'default': profile_mem_size(firmware),
+ 'size': self.eeprom_size})
+
+ def _read_mem_block(self, serport, offset, length):
+ # These builds answer the alternate 0x2B read command, which carries
+ # the handshake timestamp, instead of the stock 0x1B one
+ return _readmem(serport, offset, length)
+
+ def _write_mem_block(self, serport, data, offset):
+ return _writemem(serport, data, offset)
+
+ def _get_tone(self, mem, _mem):
+ """Read the tone settings, tolerating a partially written record.
+
+ uvk5's _get_tone indexes TMODES with the raw nibble (uvk5.py:770-773)
+ and raises IndexError for a tone type between 4 and 15. Radios only
+ ever write 0..3 (``dcs.h:22-30``), but an interrupted write or a
+ hand-made image can leave 0xFF there, and crashing while loading an
+ image is worse than losing the tone, so the range is checked first.
+ """
+ if int(_mem.rxcodeflag) > 3 or int(_mem.txcodeflag) > 3:
+ mem.tmode = ''
+ return
+ return super()._get_tone(mem, _mem)
+
+ def _decode_name(self, raw):
+ # The base class decodes names as latin-1; these builds store GB2312,
+ # and the field can also end in the middle of a two byte character, so
+ # decode_name() walks it rather than handing it to a plain codec.
+ return decode_name(raw).rstrip()
+
+ def _store_name(self, number, name, original):
+ """Store @name in the name field of channel @number.
+
+ @original is the field as it was before the base class wrote its
+ placeholder. If the name we can decode is unchanged, those bytes are
+ put back exactly as they were, so that a name this driver cannot
+ represent - or an unused name slot - is never rewritten just because
+ the user changed something else on that channel.
+ """
+ if original != b'\xff' * NAME_LENGTH and \
+ decode_name(original).rstrip() == name.rstrip():
+ self._memobj.channelname[number].set_raw(original)
+ return
+ self._memobj.channelname[number].set_raw(encode_name(name))
+
+ def _already_empty(self, number):
+ """True if channel @number is already in an "empty" spelling.
+
+ The radio leaves an untouched channel's record, name and attribute at
+ 0xFF, while CHIRP writes 0x00/0x0F when it clears one; both mean
+ "empty". Recognising the former lets a round trip leave the bytes
+ alone instead of respelling them.
+ """
+ record = bytes(self._memobj.channel[number].get_raw())
+ name = bytes(self._memobj.channelname[number].get_raw())
+ if record not in (b'\xff' * NAME_LENGTH, b'\x00' * NAME_LENGTH):
+ return False
+ if name not in (b'\xff' * NAME_LENGTH, b'\x00' * NAME_LENGTH):
+ return False
+ return bool(int(self._memobj.channel_attributes[number].is_free))
+
+ def set_memory(self, mem):
+ if mem.empty or not isinstance(mem.number, int) or mem.number > 200:
+ if mem.empty and isinstance(mem.number, int) and \
+ mem.number <= 200 and self._already_empty(mem.number - 1):
+ # Nothing to do: the bytes already say "empty"
+ return mem
+ return super().set_memory(mem)
+
+ number = mem.number - 1
+ original = bytes(self._memobj.channelname[number].get_raw())
+
+ # The base class writes the name through a str, which cannot hold a
+ # GB2312 name, so hand it a placeholder and write the real bytes
+ # afterwards.
+ proxy = mem.dupe()
+ proxy.name = ''
+ super().set_memory(proxy)
+ self._store_name(number, mem.name, original)
+ return mem
+
+ def validate_memory(self, mem):
+ msgs = super().validate_memory(mem)
+
+ if mem.empty or not isinstance(mem.number, int):
+ return msgs
+
+ # A name that does not fit the field cannot be stored at all. A name
+ # that fits the field but is longer than the radio's own editor limit
+ # is not reported: real radios carry them and this driver preserves
+ # them byte for byte (see _store_name).
+ if not name_fits(mem.name, NAME_LENGTH):
+ msgs.append(chirp_common.ValidationError(
+ _('The name needs more than the %i bytes this name field '
+ 'holds') % NAME_LENGTH))
+
+ return msgs
+
+ def get_settings(self):
+ roinfo = RadioSettingGroup('roinfo', _('Driver information'))
+ top = RadioSettings(roinfo)
+
+ firmware = self.metadata.get('uvk5_firmware', 'UNKNOWN')
+ # Fixed width and no autopad, so that the value shown is exactly the
+ # firmware string (uvk5 pads this to 128 characters).
+ val = RadioSettingValueString(len(firmware), len(firmware), firmware,
+ False)
+ val.set_mutable(False)
+ roinfo.append(RadioSetting('fw_ver', _('Firmware version'), val))
+
+ size = self.eeprom_size
+ if size in EEPROM_SIZES:
+ index = EEPROM_SIZES.index(size)
+ else:
+ index = 0
+ rs = RadioSetting('eeprom_size', _('EEPROM size'),
+ RadioSettingValueList(EEPROM_SIZE_LABELS,
+ current_index=index))
+ rs.set_doc(_(
+ 'The profile %(profile)s suggests %(default)i bytes; this is '
+ 'only a guess and the radio is the authority. A loaded image '
+ 'sets this automatically, and anything at or above '
+ '0x%(limit)x is refused because that is the multi-bootloader '
+ 'region.') % {
+ 'profile': cn_profile(
+ self.metadata.get('uvk5_firmware', '')),
+ 'default': profile_mem_size(
+ self.metadata.get('uvk5_firmware', '')),
+ 'limit': DATA_LIMIT})
+ roinfo.append(rs)
+
+ val = RadioSettingValueBoolean(self._expanded_limits)
+ rs = RadioSetting('nolimits',
+ _('Limits disabled for modified firmware'), val)
+ rs.set_warning(_(
+ 'This should only be enabled if you are using modified firmware '
+ 'that supports wider frequency coverage. Enabling this will '
+ 'cause CHIRP not to enforce OEM restrictions and may lead to '
+ 'undefined or unregulated behavior. Use at your own risk!'),
+ safe_value=False)
+ roinfo.append(rs)
+
+ return top
+
+ def set_settings(self, settings):
+ for element in settings:
+ if not isinstance(element, RadioSetting):
+ self.set_settings(element)
+ continue
+
+ name = element.get_name()
+
+ if name == 'eeprom_size':
+ size = EEPROM_SIZE_CHOICES.get(str(element.value))
+ if size:
+ self._eeprom_size = size
+
+ elif name == 'nolimits':
+ LOG.warning('User expanded band limits')
+ self._expanded_limits = bool(element.value)
diff --git a/chirp/drivers/vx1.py b/chirp/drivers/vx1.py
index 71bb74e..1ff504a 100644
--- a/chirp/drivers/vx1.py
+++ b/chirp/drivers/vx1.py
@@ -382,6 +382,11 @@ class VX1Radio(yaesu_clone.YaesuCloneModeRadio):
_model = b""
_memsize = 4818
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (len(filedata) == cls._memsize and
+ filedata[0xE6:0xEB] == b"YAESU")
_block_lengths = [4818]
_block_size = 32
@@ -413,11 +418,6 @@ class VX1Radio(yaesu_clone.YaesuCloneModeRadio):
"to upload.\n")
return rp
- @classmethod
- def match_model(cls, filedata, filename):
- return (len(filedata) == cls._memsize and
- filedata[0xE6:0xEB] == b"YAESU")
-
def sync_out(self):
# 9600 8N1 baud for 4818 bytes = 5.02 seconds
diff --git a/chirp/drivers/vx8.py b/chirp/drivers/vx8.py
index 9717ca4..b8c7e4b 100644
--- a/chirp/drivers/vx8.py
+++ b/chirp/drivers/vx8.py
@@ -17,7 +17,7 @@ import re
import logging
from chirp.drivers import yaesu_clone
-from chirp import chirp_common, directory, bitwise
+from chirp import chirp_common, directory, bitwise, errors
from chirp.settings import RadioSettingGroup, RadioSetting, RadioSettings
from chirp.settings import RadioSettingValueInteger, RadioSettingValueString
from chirp.settings import RadioSettingValueList, RadioSettingValueBoolean
@@ -655,8 +655,19 @@ class VX8Radio(yaesu_clone.YaesuCloneModeRadio):
mem.tmode = TMODES[_mem.tone_mode]
mem.duplex = DUPLEX[_mem.duplex]
if mem.duplex == "split":
- mem.offset = chirp_common.fix_rounded_step(mem.offset)
- mem.mode = MODES[_mem.mode]
+ try:
+ mem.offset = chirp_common.fix_rounded_step(mem.offset)
+ except errors.InvalidDataError:
+ # The radio may store a split offset that does not align to
+ # any step we can correct for (i.e. one entered from the
+ # keypad that the radio itself rounded to 1kHz resolution).
+ # Pass the raw value through so the memory is still loadable.
+ pass
+ # A mode of 3 is the radio's "AUTO" RX mode, which is what gets
+ # stored for memories programmed from the keypad. It resolves to
+ # NFM (i.e. FM) everywhere except the broadcast and air bands, so
+ # coerce it to FM since we have no way to represent it.
+ mem.mode = MODES[_mem.mode] if _mem.mode < len(MODES) else MODES[0]
mem.dtcs = chirp_common.DTCS_CODES[_mem.dcs]
mem.tuning_step = STEPS[_mem.tune_step]
mem.power = POWER_LEVELS[3 - _mem.power]
diff --git a/chirp/kenwood_tone.py b/chirp/kenwood_tone.py
index 8f0d40a..0806deb 100644
--- a/chirp/kenwood_tone.py
+++ b/chirp/kenwood_tone.py
@@ -217,6 +217,8 @@ def parse_qtdqt(selcall):
try:
val = int(selcall[1:4])
pol = selcall[4]
+ if pol == 'I':
+ pol = 'R'
return 'DTCS', val, pol
except (ValueError, IndexError):
raise ValueError(
@@ -244,6 +246,9 @@ def format_qtdqt(mode, val, pol):
:returns: A selcall string like '103.5' or 'D023N'
"""
if mode == 'DTCS':
+ pol = pol.upper()
+ if pol == 'R':
+ pol = 'I'
return 'D%03.3i%s' % (val, pol)
elif mode == 'Tone':
return '%3.1f' % val
diff --git a/chirp/locale/it/LC_MESSAGES/CHIRP.mo b/chirp/locale/it/LC_MESSAGES/CHIRP.mo
index 7c5fc6f..d382839 100644
--- a/chirp/locale/it/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/it/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mo b/chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mo
index 69cda04..fd2aef9 100644
--- a/chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mo b/chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mo
index 32029c7..1d1ab8d 100644
--- a/chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/stock_configs/FR Marine VHF Channels.csv b/chirp/stock_configs/FR Marine VHF Channels.csv
index da8bac7..719fe9c 100644
--- a/chirp/stock_configs/FR Marine VHF Channels.csv
+++ b/chirp/stock_configs/FR Marine VHF Channels.csv
@@ -56,3 +56,5 @@ Location,Name,Frequency,Duplex,Offset,Tone,rToneFreq,cToneFreq,DtcsCode,DtcsPola
55,SEA 86,161.925000,-,4.600000,,88.5,88.5,023,NN,FM,5.00,,,,,
56,SEA 87,157.375000,,0.000000,,88.5,88.5,023,NN,FM,5.00,,,,,
57,SEA 88,157.425000,,0.000000,,88.5,88.5,023,NN,FM,5.00,,,,,
+58,AIS 1,161.975000,,0.000000,,88.5,88.5,023,NN,FM,5.00,,,,,
+59,AIS 2,162.025000,,0.000000,,88.5,88.5,023,NN,FM,5.00,,,,,
diff --git a/chirp/wxui/__init__.py b/chirp/wxui/__init__.py
index bdb5319..e316b03 100644
--- a/chirp/wxui/__init__.py
+++ b/chirp/wxui/__init__.py
@@ -40,7 +40,7 @@ def maybe_install_desktop(args, parent):
icon_path = str(p)
# If asked not to do this, always bail
- if args.no_install_desktop_app:
+ if args.install_desktop_app is False:
return
# Already exists, don't prompt user
@@ -49,8 +49,8 @@ def maybe_install_desktop(args, parent):
return
# If already asked and not explicitly opted-in, stop nagging
- if (CONF.get_bool('offered_desktop', 'state') and not
- args.install_desktop_app):
+ if (CONF.get_bool('offered_desktop', 'state') and
+ args.install_desktop_app is not True):
LOG.debug('Desktop file missing but user previously offered')
return
@@ -113,15 +113,15 @@ def chirpmain():
'other profile data'))
if sys.platform == 'linux':
desktop = parser.add_mutually_exclusive_group()
- parser.add_argument('--compat-linux-gdk-backend', action='store_true',
+ parser.add_argument('--compat-linux-gdk-backend',
+ action=argparse.BooleanOptionalAction,
+ default=True,
help='Force GDK_BACKEND=x11 for compatibility')
- desktop.add_argument('--install-desktop-app', action='store_true',
- default=False,
- help=('Install a desktop icon even if it was '
- 'previously refused'))
- desktop.add_argument('--no-install-desktop-app', action='store_true',
- default=False,
- help='Do not prompt to install a desktop icon')
+ desktop.add_argument('--install-desktop-app',
+ action=argparse.BooleanOptionalAction,
+ default=None,
+ help=('Install a desktop icon (even if it was '
+ 'previously refused)'))
logger.add_arguments(parser)
args = parser.parse_args()
logger.handle_options(args)
diff --git a/chirp/wxui/bankedit.py b/chirp/wxui/bankedit.py
index 68d03b7..6e3bbba 100644
--- a/chirp/wxui/bankedit.py
+++ b/chirp/wxui/bankedit.py
@@ -13,6 +13,7 @@
# 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 platform
import wx
@@ -24,6 +25,7 @@ from chirp.wxui import config
from chirp.wxui import memedit
CONF = config.get()
+LOG = logging.getLogger(__name__)
if platform.system() == 'Linux':
@@ -140,7 +142,14 @@ class ChirpBankEdit(common.ChirpEditor):
lower, upper = self._features.memory_bounds
for i in range(lower, upper + 1):
- mem = self._radio.get_memory(i)
+ try:
+ mem = self._radio.get_memory(i)
+ except Exception as e:
+ # Leave this memory out of the cache and blank in the grid
+ # so that one unloadable memory does not prevent the rest
+ # of the bank editor from working.
+ LOG.error('Failed to load memory %i: %s', i, e)
+ continue
self._refresh_memory(mem)
wx.CallAfter(self._grid.AutoSizeColumns, setAsMin=True)
@@ -248,7 +257,11 @@ class ChirpBankEdit(common.ChirpEditor):
wx.PostEvent(self, common.EditorChanged(self.GetId()))
def _change_memory_mapping(self, number, bank, present):
- mem = self._memory_cache[number]
+ try:
+ mem = self._memory_cache[number]
+ except KeyError:
+ raise Exception(_('Memory %i could not be loaded, so its bank '
+ 'membership cannot be changed') % number)
bank = self._bank_indexes[self._bank_index_order[bank]]
if present:
self._bankmodel.add_memory_to_mapping(mem, bank)
diff --git a/chirp/wxui/bugreport.py b/chirp/wxui/bugreport.py
index 5ed1508..f99a394 100644
--- a/chirp/wxui/bugreport.py
+++ b/chirp/wxui/bugreport.py
@@ -41,6 +41,7 @@ _ = wx.GetTranslation
CONF = config.get()
BASE = (CONF.get('baseurl', 'chirpmyradio') or
'https://data.chirpmyradio.com/redmine')
+USER_BASE = 'https://chirpmyradio.com'
LOG = logging.getLogger(__name__)
ReportThreadEvent, EVT_REPORT_THREAD = wx.lib.newevent.NewCommandEvent()
@@ -252,8 +253,8 @@ class GetCreds(BugReportPage):
def _build(self, vbox):
vbox.Add(
wx.adv.HyperlinkCtrl(
- self, label=BASE + '/account/register',
- url=BASE + '/account/register'),
+ self, label=USER_BASE + '/account/register',
+ url=USER_BASE + '/account/register'),
0, border=20, flag=wx.ALIGN_CENTER)
panel = wx.Panel(self)
@@ -418,9 +419,10 @@ class NewBugInfo(BugReportPage):
wx.adv.HyperlinkCtrl(
panel,
label=_('searched for duplicate issues'),
- url=BASE + ('/projects/chirp/search?utf8=%E2%9C%93&'
- 'q=&scope=&all_words=&all_words=1&titles_only=&'
- 'issues=1&attachments=0&options=0&commit=Search')),
+ url=USER_BASE + (
+ '/projects/chirp/search?utf8=%E2%9C%93&'
+ 'q=&scope=&all_words=&all_words=1&titles_only=&'
+ 'issues=1&attachments=0&options=0&commit=Search')),
0)
hbox.AddStretchSpacer(1)
@@ -591,7 +593,7 @@ class ResultPage(BugReportPage):
style=wx.TE_CENTER)
vbox.Add(self.result, 0, border=20, flag=wx.EXPAND | wx.ALL)
- self.issuelink = wx.adv.HyperlinkCtrl(self, url=BASE)
+ self.issuelink = wx.adv.HyperlinkCtrl(self, url=USER_BASE)
self.issuelink.Hide()
vbox.Add(self.issuelink, 0, border=20, flag=wx.EXPAND | wx.ALL)
@@ -731,7 +733,7 @@ class ResultPage(BugReportPage):
self.result.SetLabel(
_('Successfully sent bug report:'))
self.FindWindowById(wx.ID_BACKWARD).Enable(False)
- link = BASE + '/issues/%s' % self.context.bugnum
+ link = USER_BASE + '/issues/%s' % self.context.bugnum
self.issuelink.SetLabel(link)
self.issuelink.SetURL(link)
self.issuelink.Show()
diff --git a/chirp/wxui/common.py b/chirp/wxui/common.py
index 2d78322..b6c3aa4 100644
--- a/chirp/wxui/common.py
+++ b/chirp/wxui/common.py
@@ -40,6 +40,26 @@ from chirp.wxui import radiothread
LOG = logging.getLogger(__name__)
CONF = config.get()
+
+def pg_action_edit():
+ # wxPython >= 4.3 replaced the PG_ACTION_* integer constants with
+ # the PGKeyboardAction enum. Look this up lazily (i.e. not at
+ # module import time) since by the time a settings grid is
+ # actually built, something will have already imported
+ # wx.propgrid for real; doing it ourselves at import time with an
+ # explicit `import wx.propgrid` breaks tests that stub out `wx`
+ # wholesale with a Mock.
+ if hasattr(wx.propgrid, 'PG_ACTION_EDIT'):
+ return wx.propgrid.PG_ACTION_EDIT
+ return wx.propgrid.PGKeyboardAction.Edit
+
+
+def pg_action_next_property():
+ if hasattr(wx.propgrid, 'PG_ACTION_NEXT_PROPERTY'):
+ return wx.propgrid.PG_ACTION_NEXT_PROPERTY
+ return wx.propgrid.PGKeyboardAction.NextProperty
+
+
CHIRP_DATA_MEMORY = wx.DataFormat('x-chirp/memory-channel')
EditorChanged, EVT_EDITOR_CHANGED = wx.lib.newevent.NewCommandEvent()
StatusMessage, EVT_STATUS_MESSAGE = wx.lib.newevent.NewCommandEvent()
@@ -202,9 +222,20 @@ class ChirpEditor(wx.Panel):
LOG.error('Wait dialog already in progress!')
return
- self.wait_dialog = wx.ProgressDialog(_('Please wait'), message, 100,
- parent=self)
- wx.CallAfter(self.wait_dialog.Show)
+ dlg = self.wait_dialog = wx.ProgressDialog(_('Please wait'), message,
+ 100, parent=self)
+
+ def _show():
+ # stop_wait_dialog() now destroys the dialog synchronously
+ # (see its docstring) instead of via wx.CallAfter(), which
+ # this Show() predates -- for a job that finishes very
+ # quickly, stop_wait_dialog() can run, and Destroy() this
+ # very dialog, before this queued call fires. Guard against
+ # showing (or touching at all) an already-destroyed dialog.
+ if self.wait_dialog is dlg:
+ dlg.Show()
+
+ wx.CallAfter(_show)
def bump_wait_dialog(self, value=None, message=None):
if value:
@@ -212,13 +243,50 @@ class ChirpEditor(wx.Panel):
else:
wx.CallAfter(self.wait_dialog.Pulse, message)
- def stop_wait_dialog(self):
- def cb():
- if self.wait_dialog:
- self.wait_dialog.Destroy()
- self.wait_dialog = None
-
- wx.CallAfter(cb)
+ def stop_wait_dialog(self, then=None):
+ """Destroy the wait dialog now, optionally running a callback
+ after, both *synchronously* -- deliberately not via
+ wx.CallAfter().
+
+ This matters a lot on MSW: wx.ProgressDialog leaves MSW's focus
+ state unsettled for a moment after being destroyed, and any
+ SetFocus() -- ours or one wx issues internally, e.g.
+ wx.Treebook.AddPage() implicitly focusing the first page it
+ adds -- issued while the dialog is still alive (even just
+ hidden, not yet Destroy()ed) can fail outright, logged as
+ 'SetFocus' failed with error 0x00000057. This is a real,
+ never-fixed-upstream wxWidgets bug -- see
+ https://github.com/wxWidgets/wxWidgets/issues/24290, whose
+ title is literally "SetFocus when selecting a notebook page
+ while Progress is active".
+
+ This used to destroy the dialog via wx.CallAfter(), which
+ happened to give callers like settingsedit.py's _initialize()
+ enough separation in practice under wxWidgets 3.2 (wxPython
+ <4.3): building the settings Treebook right after calling this
+ landed in a *later* turn of the event loop than the dialog's
+ destruction, by the time it actually ran. Starting with
+ wxPython 4.3 (wxWidgets 3.3), wx.CallAfter() instead runs once
+ "the current and pending event handlers have completed", so
+ the caller's very next line -- e.g. building Treebook pages --
+ can now run *before* this dialog is actually destroyed,
+ recreating exactly the upstream race. Destroying synchronously
+ here, then letting `then` (if given) run only after an actual
+ wx.CallLater() tick, fixes this at the source instead of
+ depending on that ordering happenstance.
+
+ Callers that build new UI right after calling this (as
+ settingsedit.py does) should also add a wx.SafeYield() of
+ their own between this call and that UI construction, so MSW
+ gets a real turn to process the dialog's teardown before
+ anything -- including wx's own internal AddPage() focus calls
+ -- tries to move focus again.
+ """
+ if self.wait_dialog:
+ self.wait_dialog.Destroy()
+ self.wait_dialog = None
+ if then is not None:
+ wx.CallLater(50, then)
def status_message(self, message):
wx.PostEvent(self, StatusMessage(self.GetId(), message=message))
@@ -403,8 +471,8 @@ class ChirpSettingGrid(wx.Panel):
self.pg.DedicateKey(wx.WXK_RETURN)
self.pg.DedicateKey(wx.WXK_UP)
self.pg.DedicateKey(wx.WXK_DOWN)
- self.pg.AddActionTrigger(wx.propgrid.PG_ACTION_EDIT, wx.WXK_RETURN)
- self.pg.AddActionTrigger(wx.propgrid.PG_ACTION_NEXT_PROPERTY,
+ self.pg.AddActionTrigger(pg_action_edit(), wx.WXK_RETURN)
+ self.pg.AddActionTrigger(pg_action_next_property(),
wx.WXK_RETURN)
sizer = wx.BoxSizer(wx.VERTICAL)
diff --git a/chirp/wxui/main.py b/chirp/wxui/main.py
index 4baa07a..ad3ea74 100644
--- a/chirp/wxui/main.py
+++ b/chirp/wxui/main.py
@@ -233,6 +233,7 @@ class ChirpEditorSet(wx.Panel):
if editor.GetId() != event.GetId():
LOG.debug('refreshing %s' % editor)
editor.refresh()
+ event.Skip()
def _editor_changed(self, event):
self._modified = True
@@ -1707,15 +1708,30 @@ class ChirpMain(wx.Frame):
self.enable_bugreport()
with clone.ChirpDownloadDialog(self) as d:
d.Centre()
- if d.ShowModal() == wx.ID_OK:
- radio = d._radio
- self._make_backup(radio, 'download')
- report.report_model(radio, 'download')
- if isinstance(radio, chirp_common.LiveRadio):
- editorset = ChirpLiveEditorSet(radio, None, self._editors)
- else:
- editorset = ChirpEditorSet(radio, None, self._editors)
- self.add_editorset(editorset)
+ ok = d.ShowModal() == wx.ID_OK
+ radio = d._radio if ok else None
+ # `d` is destroyed by the `with` block above, *before* we build
+ # any new UI here. ChirpEditorSet immediately moves keyboard
+ # focus to its first grid (memedit.py's self._grid.SetFocus()),
+ # and on MSW under wxWidgets 3.3+ (wxPython 4.3+) a SetFocus()
+ # issued while this dialog is only hidden (ShowModal()
+ # returned, but not yet Destroy()ed) can fail outright rather
+ # than just log harmlessly -- see
+ # https://github.com/wxWidgets/wxWidgets/issues/24290, whose
+ # title is literally this: "SetFocus when selecting a notebook
+ # page while Progress is active". wx.SafeYield() gives MSW a
+ # chance to actually process the dialog's teardown before we
+ # touch focus again.
+ wx.SafeYield()
+ if not ok:
+ return
+ self._make_backup(radio, 'download')
+ report.report_model(radio, 'download')
+ if isinstance(radio, chirp_common.LiveRadio):
+ editorset = ChirpLiveEditorSet(radio, None, self._editors)
+ else:
+ editorset = ChirpEditorSet(radio, None, self._editors)
+ self.add_editorset(editorset)
def _menu_upload(self, event):
radio = self.current_editorset.radio
@@ -1972,7 +1988,9 @@ GNU General Public License for more details."""
self.Close()
def _menu_developer(self, menuitem, event):
- developer.developer_mode(menuitem.IsChecked())
+ wx.CallAfter(self._menu_developer_deferred, menuitem)
+
+ def _menu_developer_deferred(self, menuitem):
state = menuitem.IsChecked() and _('enabled') or _('disabled')
if menuitem.IsChecked():
msg = _(
@@ -1984,14 +2002,18 @@ GNU General Public License for more details."""
'warned! Proceed anyway?')
d = wx.MessageDialog(self, msg, _('Danger Ahead'),
style=wx.ICON_WARNING | wx.YES_NO)
- if d.ShowModal() != wx.ID_YES:
- menuitem.Check(False)
- return
+ try:
+ if d.ShowModal() != wx.ID_YES:
+ menuitem.Check(False)
+ return
+ finally:
+ d.Destroy()
wx.MessageBox(_('Developer state is now %s. '
'CHIRP must be restarted to take effect') % state,
_('Restart Required'), wx.OK)
LOG.info('User set developer mode to %s', menuitem.IsChecked())
+ developer.developer_mode(menuitem.IsChecked())
def _menu_reporting(self, menuitem, event):
if not menuitem.IsChecked():
@@ -2085,13 +2107,18 @@ GNU General Public License for more details."""
@common.error_proof()
def _do_network_query(self, query_cls):
self.enable_bugreport()
- d = query_cls(self, title=_('Query %s') % query_cls.NAME)
- r = d.ShowModal()
- if r == wx.ID_OK:
- report.report_model(d.result_radio, 'query')
- editorset = ChirpEditorSet(d.result_radio,
- None, self._editors)
- self.add_editorset(editorset)
+ with query_cls(self, title=_('Query %s') % query_cls.NAME) as d:
+ ok = d.ShowModal() == wx.ID_OK
+ result_radio = d.result_radio if ok else None
+ # See the matching comment in _menu_download(): `d` needs to be
+ # actually destroyed (not just hidden) before ChirpEditorSet
+ # moves focus to its first grid, or SetFocus() can fail on MSW.
+ wx.SafeYield()
+ if not ok:
+ return
+ report.report_model(result_radio, 'query')
+ editorset = ChirpEditorSet(result_radio, None, self._editors)
+ self.add_editorset(editorset)
def _menu_query_rr(self, event):
self._do_network_query(query_sources.RRQueryDialog)
diff --git a/chirp/wxui/memedit.py b/chirp/wxui/memedit.py
index 9b59e95..faaa427 100644
--- a/chirp/wxui/memedit.py
+++ b/chirp/wxui/memedit.py
@@ -1072,7 +1072,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
# After we do another thing, the items in the redo queue are no longer
# valid
self._redo_queue = []
- self._update_menu()
+ wx.CallAfter(self._update_menu)
def _undo(self, event):
"""Undo the latest change."""
@@ -2918,8 +2918,8 @@ class ChirpMemPropDialog(wx.Dialog):
self._pg.DedicateKey(wx.WXK_RETURN)
self._pg.DedicateKey(wx.WXK_UP)
self._pg.DedicateKey(wx.WXK_DOWN)
- self._pg.AddActionTrigger(wx.propgrid.PG_ACTION_EDIT, wx.WXK_RETURN)
- self._pg.AddActionTrigger(wx.propgrid.PG_ACTION_NEXT_PROPERTY,
+ self._pg.AddActionTrigger(common.pg_action_edit(), wx.WXK_RETURN)
+ self._pg.AddActionTrigger(common.pg_action_next_property(),
wx.WXK_RETURN)
self._tabs.InsertPage(0, self._pg, _('Values'))
diff --git a/chirp/wxui/radioinfo.py b/chirp/wxui/radioinfo.py
index e2142c5..90c05c3 100644
--- a/chirp/wxui/radioinfo.py
+++ b/chirp/wxui/radioinfo.py
@@ -22,6 +22,16 @@ from chirp.wxui import accessibility
from chirp.wxui import common
+def _enable_scrolling(pg):
+ # PropertyGrid.EnableScrolling() is inherited from wxScrolled, which
+ # wxPropertyGrid did not derive from until wxWidgets 3.1.5 (i.e.
+ # wxPython 4.1.0). The Linux AppImage ships 4.0.7, where the grid is
+ # a plain wxControl plus a wxScrollHelper and manages its own
+ # scrollbars, so there is no such method to call.
+ if hasattr(pg, 'EnableScrolling'):
+ pg.EnableScrolling(True, True)
+
+
class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor):
def __init__(self, radio, *a, **k):
super(ChirpRadioInfo, self).__init__(*a, **k)
@@ -61,7 +71,7 @@ class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor):
def _add_driver(self):
pg = wx.propgrid.PropertyGrid(
self, style=wx.propgrid.PG_SPLITTER_AUTO_CENTER)
- pg.EnableScrolling(True, True)
+ _enable_scrolling(pg)
accessibility.enable_propgrid_a11y(pg, _('Radio Info: Driver'))
self._group_control.AddPage(pg, _('Driver'))
@@ -88,7 +98,7 @@ class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor):
pg = wx.propgrid.PropertyGrid(
self, style=wx.propgrid.PG_SPLITTER_AUTO_CENTER)
- pg.EnableScrolling(True, True)
+ _enable_scrolling(pg)
accessibility.enable_propgrid_a11y(pg, _('Radio Info: Icom'))
self._group_control.AddPage(pg, 'Icom')
@@ -116,7 +126,7 @@ class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor):
pg = wx.propgrid.PropertyGrid(
self, style=wx.propgrid.PG_SPLITTER_AUTO_CENTER)
- pg.EnableScrolling(True, True)
+ _enable_scrolling(pg)
accessibility.enable_propgrid_a11y(pg, _('Radio Info: Image Metadata'))
self._group_control.AddPage(pg, 'Image Metadata')
# Don't show the icom fields which are displayed elsewhere, and
diff --git a/chirp/wxui/serialtrace.py b/chirp/wxui/serialtrace.py
index cb4cf59..f50485f 100644
--- a/chirp/wxui/serialtrace.py
+++ b/chirp/wxui/serialtrace.py
@@ -116,11 +116,21 @@ class SerialTrace(serial.Serial):
def last_write(self):
return self.__last_write
+ @property
+ def trace_dir(self):
+ # If CHIRP_DEBUG is set and ./traces exists, use that for trace files
+ # for easier access
+ if os.getenv('CHIRP_DEBUG') and os.path.isdir('traces'):
+ return os.path.abspath('traces')
+ else:
+ return None
+
def open(self):
super().open()
try:
self.__trace_start = time.monotonic()
self.__tracef = tempfile.NamedTemporaryFile(mode='w',
+ dir=self.trace_dir,
delete=False,
prefix='chirp-trace-',
suffix='.txt')
diff --git a/chirp/wxui/settingsedit.py b/chirp/wxui/settingsedit.py
index 225dd5f..c923e89 100644
--- a/chirp/wxui/settingsedit.py
+++ b/chirp/wxui/settingsedit.py
@@ -57,7 +57,15 @@ class ChirpSettingsEdit(common.ChirpEditor):
event.Skip()
def _initialize(self, job):
+ # Close the wait dialog and let MSW settle *before* building
+ # any Treebook pages below: wx.Treebook.AddPage() implicitly
+ # focuses the first page it adds (like wx.Notebook does), and
+ # if the "Getting settings" dialog is still alive at that
+ # moment, that focus call can fail outright -- see the long
+ # comment on ChirpEditor.stop_wait_dialog() for why.
self.stop_wait_dialog()
+ wx.SafeYield()
+
with common.error_proof(Exception):
if isinstance(job.result, Exception):
raise job.result
@@ -67,9 +75,10 @@ class ChirpSettingsEdit(common.ChirpEditor):
self._group_control.SetSelection(self._restore_selection)
self._restore_selection = None
- # Focus the selector after it loads
- tc = self._group_control.GetTreeCtrl()
- wx.CallAfter(tc.SetFocus)
+ # Belt and suspenders: explicitly (re)focus the selector
+ # too, once more via a real timer tick rather than a second
+ # wx.CallAfter() (same reasoning as stop_wait_dialog()).
+ wx.CallLater(50, self._group_control.GetTreeCtrl().SetFocus)
def selected(self):
if not self._initialized:
diff --git a/setup.py b/setup.py
index 74e0546..2e00509 100644
--- a/setup.py
+++ b/setup.py
@@ -5,7 +5,7 @@ setup(name='chirp',
description='A cross-platform cross-radio programming tool',
packages=find_packages(include=["chirp*"]),
include_package_data=True,
- version='20260814',
+ version='20261030',
url='https://chirp.danplanet.com',
python_requires=">=3.10,<4",
install_requires=[
diff --git a/tests/__init__.py b/tests/__init__.py
index 55640b0..8ef8741 100644
--- a/tests/__init__.py
+++ b/tests/__init__.py
@@ -17,6 +17,7 @@ from tests import test_copy_all
from tests import test_detect
from tests import test_edges
from tests import test_features
+from tests import test_setting_docs
from tests import test_settings
LOG = logging.getLogger('testadapter')
@@ -96,7 +97,8 @@ def _load_tests(loader, tests, pattern, suite=None):
test_clone.TestCaseClone,
test_settings.TestCaseSettings,
test_features.TestCaseFeatures,
- test_copy_all.TestCaseCopyAll)
+ test_copy_all.TestCaseCopyAll,
+ test_setting_docs.TestCaseSettingDocs)
# Load our list of dynamic XFAIL tests
with open('tests/driver_xfails.yaml') as xflist:
diff --git a/tests/__pycache__/test_brute_force.cpython-310-pytest-7.1.3.pyc b/tests/__pycache__/test_brute_force.cpython-310-pytest-7.1.3.pyc
index 4f6f2ab..2596075 100644
--- a/tests/__pycache__/test_brute_force.cpython-310-pytest-7.1.3.pyc
+++ b/tests/__pycache__/test_brute_force.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/driver_setting_docs.yaml b/tests/driver_setting_docs.yaml
new file mode 100644
index 0000000..9f45667
--- /dev/null
+++ b/tests/driver_setting_docs.yaml
@@ -0,0 +1,6 @@
+# Radios whose settings, including the per-memory ones in the first
+# non-empty memory, must all carry a description (set_doc()).
+# TestCaseSettingDocs skips every radio not listed here. Entries are
+# radio class IDs, as in driver_xfails.yaml; keep them sorted.
+- Baofeng_UV-5G_Mini
+- Baofeng_UV-5R_Mini
diff --git a/tests/driver_xfails.yaml b/tests/driver_xfails.yaml
index a60b646..a2b464a 100644
--- a/tests/driver_xfails.yaml
+++ b/tests/driver_xfails.yaml
@@ -1,7 +1,3 @@
-Anysecu_UV-A37:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Broken name stored in memory 202?
Talkpod_A36plus:
- class: TestCaseBruteForce
test: test_validate_all
@@ -9,63 +5,80 @@ Talkpod_A36plus:
- class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
-BTECH_GMRS-20V2:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Improper application of the duplex policy
-BTECH_GMRS-50V2:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Improper application of the duplex policy
-Abbree_AR-730:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Broken name stored in memory 256?
-Yaesu_FT-90:
+Wouxun_KG-UVD1P:
- class: TestCaseBruteForce
test: test_validate_all
- reason: Memory 7 stored with high power but unable to be set?
-Wouxun_KG-UVD1P:
+ reason: Bad channel stored in image or code is wrong
- class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
Puxing_PX-2R:
- class: TestCaseBruteForce
+ test: test_validate_all
+ reason: Bad channel stored in image or code is wrong
+ - class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
Radtel_RT-470X_BT:
- class: TestCaseBruteForce
+ test: test_validate_all
+ reason: Bad channel stored in image or code is wrong
+ - class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
BTECH_UV-25X4_G2:
- class: TestCaseBruteForce
+ test: test_validate_all
+ reason: Bad channel stored in image or code is wrong
+ - class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
Abbree_AR-63:
- class: TestCaseBruteForce
+ test: test_validate_all
+ reason: Bad channel stored in image or code is wrong
+ - class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
Feidaxin_FD-288B:
- class: TestCaseBruteForce
+ test: test_validate_all
+ reason: Bad channel stored in image or code is wrong
+ - class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
Wouxun_KG-UV8E:
- class: TestCaseBruteForce
+ test: test_validate_all
+ reason: Bad channel stored in image or code is wrong
+ - class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
Boblov_X3Plus:
- class: TestCaseBruteForce
+ test: test_validate_all
+ reason: Bad channel stored in image or code is wrong
+ - class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
QYT_KT7900D:
- class: TestCaseBruteForce
+ test: test_validate_all
+ reason: Bad channel stored in image or code is wrong
+ - class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
BTECH_UV-25X4:
- class: TestCaseBruteForce
+ test: test_validate_all
+ reason: Bad channel stored in image or code is wrong
+ - class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
Baojie_BJ-9900_Left:
- class: TestCaseBruteForce
+ test: test_validate_all
+ reason: Bad channel stored in image or code is wrong
+ - class: TestCaseBruteForce
test: test_validate_all_steps
reason: Bad channel stored in image or code is wrong
diff --git a/tests/images/BTECH_GMRS-50X1.img b/tests/images/BTECH_GMRS-50X1.img
index e84780f..5125a8d 100644
--- a/tests/images/BTECH_GMRS-50X1.img
+++ b/tests/images/BTECH_GMRS-50X1.img
Binary files differ
diff --git a/tests/images/Baofeng_DM-32UV.img b/tests/images/Baofeng_DM-32UV.img
new file mode 100644
index 0000000..9cd5be1
--- /dev/null
+++ b/tests/images/Baofeng_DM-32UV.img
Binary files differ
diff --git a/tests/images/Baofeng_UV-5G_Pro.img b/tests/images/Baofeng_UV-5G_Pro.img
index 324157f..4823769 100644
--- a/tests/images/Baofeng_UV-5G_Pro.img
+++ b/tests/images/Baofeng_UV-5G_Pro.img
Binary files differ
diff --git a/tests/images/Baofeng_UV-5R.img b/tests/images/Baofeng_UV-5R.img
index 773c32b..7d9934a 100644
--- a/tests/images/Baofeng_UV-5R.img
+++ b/tests/images/Baofeng_UV-5R.img
Binary files differ
diff --git a/tests/images/Boblov_X3Plus.img b/tests/images/Boblov_X3Plus.img
index 07331e4..b08c235 100644
--- a/tests/images/Boblov_X3Plus.img
+++ b/tests/images/Boblov_X3Plus.img
Binary files differ
diff --git a/tests/images/Icom_IC-U82.img b/tests/images/Icom_IC-U82.img
index 5a1c0a4..e57930a 100644
--- a/tests/images/Icom_IC-U82.img
+++ b/tests/images/Icom_IC-U82.img
Binary files differ
diff --git a/tests/images/Icom_ID-4100.img b/tests/images/Icom_ID-4100.img
index 1305f49..5f01e3f 100644
--- a/tests/images/Icom_ID-4100.img
+++ b/tests/images/Icom_ID-4100.img
Binary files differ
diff --git a/tests/images/Kenwood_NX-800.img b/tests/images/Kenwood_NX-800.img
new file mode 100644
index 0000000..d92f401
--- /dev/null
+++ b/tests/images/Kenwood_NX-800.img
Binary files differ
diff --git a/tests/images/Quansheng_UV-K5_losehu.img b/tests/images/Quansheng_UV-K5_losehu.img
new file mode 100644
index 0000000..1556960
--- /dev/null
+++ b/tests/images/Quansheng_UV-K5_losehu.img
Binary files differ
diff --git a/tests/images/Retevis_RB48.img b/tests/images/Retevis_RB48.img
new file mode 100644
index 0000000..e32b0b7
--- /dev/null
+++ b/tests/images/Retevis_RB48.img
Binary files differ
diff --git a/tests/images/Retevis_RB648.img b/tests/images/Retevis_RB648.img
new file mode 100644
index 0000000..9d0fa34
--- /dev/null
+++ b/tests/images/Retevis_RB648.img
Binary files differ
diff --git a/tests/images/Retevis_RT18.img b/tests/images/Retevis_RT18.img
new file mode 100644
index 0000000..201ec90
--- /dev/null
+++ b/tests/images/Retevis_RT18.img
Binary files differ
diff --git a/tests/images/Retevis_RT86A.img b/tests/images/Retevis_RT86A.img
new file mode 100644
index 0000000..81f0053
--- /dev/null
+++ b/tests/images/Retevis_RT86A.img
Binary files differ
diff --git a/tests/images/Retevis_RT97S.img b/tests/images/Retevis_RT97S.img
new file mode 100644
index 0000000..4fabdf3
--- /dev/null
+++ b/tests/images/Retevis_RT97S.img
Binary files differ
diff --git a/tests/images/TYT_UVL-15W.img b/tests/images/TYT_UVL-15W.img
new file mode 100644
index 0000000..305a2dc
--- /dev/null
+++ b/tests/images/TYT_UVL-15W.img
Binary files differ
diff --git a/tests/images/Wouxun_KG-UV9D_Plus.img b/tests/images/Wouxun_KG-UV9D_Plus.img
index 410e498..dccf395 100644
--- a/tests/images/Wouxun_KG-UV9D_Plus.img
+++ b/tests/images/Wouxun_KG-UV9D_Plus.img
Binary files differ
diff --git a/tests/images/Yaesu_FT-7100M.img b/tests/images/Yaesu_FT-7100M.img
index 30e18ce..727a906 100644
--- a/tests/images/Yaesu_FT-7100M.img
+++ b/tests/images/Yaesu_FT-7100M.img
Binary files differ
diff --git a/tests/images/Yaesu_FT-8000R.img b/tests/images/Yaesu_FT-8000R.img
new file mode 100644
index 0000000..c7dcb99
--- /dev/null
+++ b/tests/images/Yaesu_FT-8000R.img
Binary files differ
diff --git a/tests/images/Yaesu_FT5D_R.img b/tests/images/Yaesu_FT5D_R.img
new file mode 100644
index 0000000..2841039
--- /dev/null
+++ b/tests/images/Yaesu_FT5D_R.img
Binary files differ
diff --git a/tests/images/Yaesu_FTM-150E.img b/tests/images/Yaesu_FTM-150E.img
new file mode 100644
index 0000000..90f5fa3
--- /dev/null
+++ b/tests/images/Yaesu_FTM-150E.img
Binary files differ
diff --git a/tests/images/Yaesu_FTM-300DR.img b/tests/images/Yaesu_FTM-300DR.img
new file mode 100644
index 0000000..bfcdc27
--- /dev/null
+++ b/tests/images/Yaesu_FTM-300DR.img
Binary files differ
diff --git a/tests/images/Zartek_ZA-758.img b/tests/images/Zartek_ZA-758.img
new file mode 100644
index 0000000..23f9a4c
--- /dev/null
+++ b/tests/images/Zartek_ZA-758.img
Binary files differ
diff --git a/tests/py3_driver_testers.txt b/tests/py3_driver_testers.txt
deleted file mode 100644
index 53bee81..0000000
--- a/tests/py3_driver_testers.txt
+++ /dev/null
@@ -1,420 +0,0 @@
-# Format is:
-# Driver_ID,Tester,Test Date
-# Tester is preferred as a github id, but obfuscated email or name is
-# acceptable. If a driver is literally identical to another, use
-# +DRIVER_KEY to mark it as implied-tested.
-# If the driver is tested with an in-tree image (or is a live driver) and the
-# clone routines are shared in common with other things that are tested, use
-# *MODULE_NAME to mark it as "probably works because of common code in
-# $module". If a user reported it as working in a chirp website issue, use
-# the form #BUGNUMBER.
-Abbree_AR-518,@KC9HI,16-Dec-2022
-Abbree_AR-63,@KC9HI,30-Nov-2022
-Abbree_AR-730,@KC9HI,17-Aug-2023
-Abbree_AR-869,+Radtel_RT-490,11-Nov-2023
-Abbree_AR-F5,@KC9HI,09-Aug-2023
-Alinco_DJ175,+Alinco_DR235T,12-Dec-2022
-Alinco_DJ596,+Alinco_DR235T,12-Dec-2022
-Alinco_DJ-G7EG,@HB9UF,09-Dec-2022
-Alinco_DJ-G7T,#10567,09-May-2023
-Alinco_DR03T,+Alinco_DR235T,12-Dec-2022
-Alinco_DR06T,+Alinco_DR235T,12-Dec-2022
-Alinco_DR135T,+Alinco_DR235T,12-Dec-2022
-Alinco_DR235T,@kk7ds,12-Dec-2022
-Alinco_DR435T,+Alinco_DR235T,12-Dec-2022
-Alinco_DR735T,@jacobcalvert,03-April-2024
-Anysecu_UV-A37,@KC9HI,5-Jun-2023
-Anysecu_WP-9900,@KC9HI,11-Nov-2022
-Anysecu_AC-580,+Radioddity_GS-5B,17-Mar-2023
-AnyTone_778UV,+Retevis_RT95,13-Nov-2022
-AnyTone_778UV_VOX,+Retevis_RT95,13-Nov-2022
-AnyTone_5888UV,@kk7ds,9-Dec-2022
-AnyTone_5888UVIII,@bschuler42,9-Jan-2023
-AnyTone_OBLTR-8R,@KC9HI,17-Dec-2022
-AnyTone_TERMN-8R,@KC9HI,17-Dec-2022
-BTECH_FRS-A1,@KC9HI,30-Nov-2022
-BTECH_FRS-B1,@KC9HI,28-Nov-2022
-BTECH_GMRS-20V2,@KC9HI,13-Nov-2022
-BTECH_GMRS-50V2,@KC9HI,15-Feb-2023
-BTECH_GMRS-50X1,@KC9HI,13-Nov-2022
-BTECH_GMRS-V1,@KC9HI,10-Dec-2022
-BTECH_GMRS-V2,@KC9HI,10-Dec-2022
-BTECH_MURS-V1,@KC9HI,10-Dec-2022
-BTECH_MURS-V2,@KC9HI,2-Mar-2023
-BTECH_UV-2501,@KC9HI,11-Nov-2022
-BTECH_UV-2501+220,@KC9HI,11-Nov-2022
-BTECH_UV-25X2,@KC9HI,11-Nov-2022
-BTECH_UV-25X2_G2,@KC9HI,23-Apr-2023
-BTECH_UV-25X4,@KC9HI,10-Nov-2022
-BTECH_UV-25X4_G2,@KC9HI,23-Apr-2023
-BTECH_UV-5001,@KC9HI,11-Nov-2022
-BTECH_UV-50X2,@KC9HI,11-Nov-2022
-BTECH_UV-50X2_G2,@KC9HI,30-Nov-2022
-BTECH_UV-50X3,@KC9HI,10-Dec-2022
-BTECH_UV-5X3,@KC9HI,9-Dec-2022
-Baofeng_5RM,@vdwel,7-Dec-2023
-Baofeng_5RX,@KC9HI,16-Jan-2024
-Baofeng_BF-1901,@cetinajero,3-Jul-2023
-Baofeng_BF-1904,@cetinajero,3-Jul-2023
-Baofeng_BF-1909,@KC9HI,10-May-2024
-Baofeng_BF-888,@kk7ds,13-Feb-2019
-Baofeng_BF-A58,@KC9HI,3-Dec-2022
-Baofeng_BF-A58S,@KC9HI,3-Dec-2022
-Baofeng_BF-F8HP,@KC9HI,18-Nov-2022
-Baofeng_BF-M4,@cetinajero,8-May-2023
-Baofeng_BF-T1,@KC9HI,10-Dec-2022
-Baofeng_BF-T20,@KC9HI,15-Dec-2023
-Baofeng_BF-T20FRS,@KC9HI,17-Dec-2023
-Baofeng_BF-T8,@KC9HI,30-Nov-2022
-Baofeng_BF-V8A,@KC9HI,28-Nov-2022
-Baofeng_F-11,+Baofeng_UV-5R,18-Nov-2022
-Baofeng_GM-5RH,@KC9HI,21-Mar-2024
-Baofeng_GT-3WP,@KC9HI,3-Dec-2022
-Baofeng_GT-5R,@KC9HI,18-Nov-2022
-Baofeng_UV-3R,@yarda,26-Sep-2022
-Baofeng_UV-5R,@lekv,23-Oct-2022
-Baofeng_UV-6,+Baofeng_UV-5R,18-Nov-2022
-Baofeng_UV-6R,@KC9HI,10-Dec-2022
-Baofeng_UV-82,@KC9HI,18-Nov-2022
-Baofeng_UV-82HP,@KC9HI,18-Nov-2022
-Baofeng_UV-82WP,@KC9HI,3-Dec-2022
-Baofeng_UV-9G,@KC9HI,3-Dec-2022
-Baofeng_UV-9R,@KC9HI,3-Dec-2022
-Baofeng_UV-13Pro,@vdwel,21-Feb-2024
-Baofeng_UV-17,@vdwel,27-Nov-2023
-Baofeng_UV-17Pro,@vdwel,27-Nov-2023
-Baofeng_UV-17ProGPS,@vdwel,27-Nov-2023
-Baofeng_UV-25,+Baofeng_UV-17Pro,2-Jun-2024
-Baofeng_UV-B5,@KC9HI,18-Nov-2022
-Baofeng_UV-S9X3,@KC9HI,22-Aug-2023
-Baofeng_W31E,@KC9HI,14-Aug-2023
-Baojie_BJ-218,+LUITON_LT-725UV,16-Feb-2023
-Baojie_BJ-318,@KC9HI,2-Jan-2023
-Boristone_8RS,+Radtel_RT-490,11-Nov-2023
-Cignus_XTR-5,+Radioddity_GS-5B,17-Mar-2023
-CRT_Micron_UV,+Retevis_RT95,13-Nov-2022
-CRT_Micron_UV_V2,+Retevis_RT95,13-Nov-2022
-Explorer_QRZ-1,+TYT_TH-UV88,5-Dec-2022
-Generic_CSV,@kk7ds,4-Dec-2022
-HamGeek_HG-590,+Radtel_RT-490,11-Nov-2023
-Hiroyasu_HI-8811,@KC9HI,4-Jun-2023
-HobbyPCB_RS-UV3,@kk7ds,9-Dec-2022
-Icom_IC-208H,*icf,12-Dec-2022
-Icom_IC-2100H,*icf,12-Dec-2022
-Icom_IC-2200H,@kk7ds,24-Oct-2022
-Icom_IC-2300H,#10264,13-Jan-2022
-Icom_IC-2720H,*icf,12-Dec-2022
-Icom_IC-2730A,#10261,17-Dec-2022
-Icom_IC-2820H,@kk7ds,22-Oct-2022
-Icom_IC-7000,#10510,10-Apr-2023
-Icom_IC-7100,Mike W,16-Feb-2023
-Icom_IC-7200,@kk7ds,22-Oct-2022
-Icom_IC-7300,@kk7ds,22-Oct-2022
-Icom_IC-746,#10346,3-Feb-2023
-Icom_IC-7610,@kk7ds,24-Oct-2022
-Icom_IC-91_92AD,@kk7ds,23-Nov-2022
-Icom_IC-910,@mfncooper,1-Oct-2021
-Icom_ID-31A,@kk7ds,1-Dec-2022
-Icom_ID-51,+Icom_ID-31A,1-Dec-2022
-Icom_ID-51_Plus,+Icom_ID-31A,1-Dec-2022
-Icom_ID-51_Plus2,+Icom_ID-31A,17-Dec-2022
-Icom_ID-4100,@n8sqt,18-Dec-2022
-Icom_ID-5100,@kk7ds,17-Dec-2022
-Icom_ID-800H_v2,@kk7ds,22-Oct-2022
-Icom_ID-80H,*icf,22-Oct-2022
-Icom_ID-880H,@kk7ds,22-Oct-2022
-Icom_IC-E90,*icf,12-Dec-2022
-Icom_IC-P7,*icf,12-Dec-2022
-Icom_IC-T70,*icf,12-Dec-2022
-Icom_IC-T7H,#10752,30-Jul-2023
-Icom_IC-T8A,*icf,12-Dec-2022
-Icom_IC-Q7A,@KC9HI,20-Nov-2022
-Icom_IC-U82,+Icom_IC-V82,25-Jan-2023
-Icom_IC-V80,@kk7ds,16-Feb-2023
-Icom_IC-V82,@kk7ds,25-Jan-2023
-Icom_IC-V86,*icf,12-Dec-2022
-Icom_IC-W32A,#10238,12-Dec-2022
-Icom_IC-W32E,*icf,12-Dec-2022
-Intek_KT-980HP,+Baofeng_BF-F8HP,18-Nov-2022
-Intek_HR-2040,+AnyTone_5888UV,9-Dec-2022
-Jetstream_JT220M,+Alinco_DR235T,12-Dec-2022
-Jetstream_JT270M,+Jetstream_JT270M,13-Dec-2022
-Jetstream_JT270MH,@kk7ds,13-Dec-2022
-Jianpai_8800_Plus,+Radtel_RT-490,11-Nov-2023
-JJCC_JC-8629,+Radtel_RT-490,11-Nov-2023
-Kenwood_HMK,+Generic_CSV,4-Dec-2022
-Kenwood_TH-D7,*kenwood_live,12-Dec-2022
-Kenwood_TH-D7G,*kenwood_live,12-Dec-2022
-Kenwood_TH-D72_clone_mode,@kk7ds,28-Nov-2022
-Kenwood_TH-D72_live_mode,@kk7ds,21-Oct-2022
-Kenwood_TH-D74_clone_mode,@kk7ds,30-Nov-2022
-Kenwood_TH-D74_live_mode,@kk7ds,20-Oct-2022
-Kenwood_TH-D75,#11122,114-Feb-2024
-Kenwood_TH-F6,@KC9HI,30-Nov-2022
-Kenwood_TH-F7,@sv1,19-Oct-2022
-Kenwood_TH-G71,*kenwood_live,12-Dec-2022
-Kenwood_TH-K2,*kenwood_live,12-Dec-2022
-Kenwood_TM-271,+Kenwood_TM-281,23-Oct-2022
-Kenwood_TM-281,@kk7ds,23-Oct-2022
-Kenwood_TM-471,*kenwood_live,12-Dec-2022
-Kenwood_TM-D700,@kk7ds,20-Oct-2022
-Kenwood_TM-D710,*kenwood_live,22-Oct-2022
-Kenwood_TM-D710G,@kk7ds,22-Oct-2022
-Kenwood_TM-D710G_CloneMode,@kk7ds,22-Oct-2022
-Kenwood_TM-G707,*kenwood_live,12-Dec-2022
-Kenwood_TM-V7,*kenwood_live,12-Dec-2022
-Kenwood_TM-V71,@kk7ds,21-Oct-2022
-Kenwood_TK-2140K,+Kenwood_TK-3140K,2-Feb-2023
-Kenwood_TK-2180,@kk7ds,4-Dec-2022
-Kenwood_TK-3140K,@kk7ds,2-Feb-2023
-Kenwood_TK-3140K2,+Kenwood_TK-3140K,2-Feb-2023
-Kenwood_TK-3140K3,+Kenwood_TK-3140K,2-Feb-2023
-Kenwood_TK-3180K,@kk7ds,4-Dec-2022
-Kenwood_TK-3180K2,+Kenwood_TK-3180K,4-Dec-2022
-Kenwood_TK-7102,@kk7ds,15-Feb-2019
-Kenwood_TK-7108,@kk7ds,15-Feb-2019
-Kenwood_TK-7180,@kk7ds,18-Oct-2022
-Kenwood_TK-7180E,+Kenwood_TK-7180,18-Oct-2022
-Kenwood_TK-8102,@kk7ds,15-Feb-2019
-Kenwood_TK-8108,@kk7ds,15-Feb-2019
-Kenwood_TK-7160K,@kk7ds,27-Jan-2023
-Kenwood_TK-7160M,+Kenwood_TK-7160K,27-Jan-2023
-Kenwood_TK-8160K,+Kenwood_TK-7160K,27-Jan-2023
-Kenwood_TK-8160M,+Kenwood_TK-7160K,27-Jan-2023
-Kenwood_TK-8180,@kk7ds,18-Oct-2022
-Kenwood_TK-8180E,+Kenwood_TK-8180,18-Dec-2022
-Kenwood_TK-762G,@kk7ds,5-Dec-2022
-Kenwood_TK-868G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-862G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-860G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-768G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-760G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-388G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-378G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-372G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-370G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-360G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-278G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-272G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-270G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-260G,+Kenwood_TK-762G,5-Dec-2022
-Kenwood_TK-760,@kk7ds,5-Dec-2022
-Kenwood_TK-762,+Kenwood_TK-760,5-Dec-2022
-Kenwood_TK-768,+Kenwood_TK-760,5-Dec-2022
-Kenwood_TK-860,+Kenwood_TK-760,5-Dec-2022
-Kenwood_TK-862,+Kenwood_TK-760,5-Dec-2022
-Kenwood_TK-868,+Kenwood_TK-760,5-Dec-2022
-Kenwood_TS-2000,ZS6CRW,10-Jan-2022
-Lanchonlh_HG-UV98,#11179,23-Feb-2024
-Leixen_VV-898,+Jetstream_JT270MH,13-Dec-2022
-Leixen_VV-898S,@READ10,19-Dec-2022
-Leixen_VV-898S_Dual_Bank,#4069,10-Feb-2024
-Leixen_VV-898E_Dual_Bank,+Leixen_VV-898S_Dual_Bank,10-Feb-2024
-LUITON_LT-316,+Retevis_RT22,9-Dec-2022
-LUITON_LT-580_UHF,@KC9HI,8-Dec-2022
-LUITON_LT-580_VHF,@KC9HI,8-Dec-2022
-LUITON_LT-588UV,@KC9HI,11-Nov-2022
-LUITON_LT-725UV,@KC9HI,11-Dec-2022
-Maverick_RA-100,@cetinajero,7-Jul-2023
-Maverick_RA-425,@cetinajero,7-Jul-2023
-MMLradio_JC-8629,@KC9HI,11-Nov-2023
-MTC_UV-5R-3,+BTECH_UV-5X3,9-Dec-2022
-Midland_DBR2500,+Retevis_RT95,13-Nov-2022
-Polmar_DB-50M,+AnyTone_5888UV,9-Dec-2022
-Powerwerx_DB-750X,+AnyTone_5888UV,9-Dec-2022
-Puxing_PX-888K,#10544,09-May-2023
-Q-MAC_HF-90_v300_or_earlier,@fthain,9-Mar-2023
-Q-MAC_HF-90_v301_or_later,@fthain,9-Mar-2023
-Quansheng_TG-UV2+,#10398,26-Feb-2023
-Quansheng_UV-K5,@sq5bpf,29-May-2023
-Quansheng_UV-K5_egzumer,@egzumer,23-Jan-2024
-QYT_KT-8R,@KC9HI,11-Nov-2022
-QYT_KT-UV980,+WACCOM_MINI-8900,11-Nov-2022
-QYT_KT-WP12,+Anysecu_WP-9900,11-Nov-2022
-QYT_KT5800,+BTECH_UV-25X2,11-Nov-2022
-QYT_KT7900D,+BTECH_UV-25X4,11-Nov-2022
-QYT_KT8900,+LUITON_LT-588UV,11-Nov-2022
-QYT_KT8900D,+BTECH_UV-25X2,11-Nov-2022
-QYT_KT8900R,+BTECH_UV-2501+220,11-Nov-2022
-QYT_KT980PLUS,+BTECH_UV-25X2,11-Nov-2022
-Radioddity_DB25-G,@KC9HI,11-Nov-2022
-Radioddity_GA-2S,@KC9HI,4-Dec-2022
-Radioddity_GA-510,@kk7ds,21-Oct-2022
-Radioddity_GS-5B,@lunapiercook,5-Mar-2023
-Radioddity_R2,@KC9HI,17-Dec-2022
-Radioddity_UV-5G,@KC9HI,18-Nov-2022
-Radioddity_UV-5RX3,@KC9HI,18-Nov-2022
-Radioddity_UV-82X3,@KC9HI,18-Nov-2022
-Radtel_RT-470,@KC9HI,2-Apr-2023
-Radtel_RT-470L,@KC9HI,5-May-2023
-Radtel_RT-470X,@KC9HI,10-Aug-2023
-Radtel_RT-490,@KC9HI,11-Nov-2023
-Radtel_RT-495,@KC9HI,14-Jun-2024
-Radtel_RT-630,@KC9HI,14-Jun-2024
-Radtel_RT-730,@KC9HI,11-May-2024
-Radtel_T18,@KC9HI,28-Nov-2022
-Retevis_H777H_FRS,@KC9HI,12-Jan-2025
-Retevis_H777H_PMR,@KC9HI,12-Jan-2025
-Retevis_H777S,@KC9HI,22-Dec-2022
-Retevis_H777_Plus,@KC9HI,4-Dec-2022
-Retevis_P2,@KC9HI,15-Jun-2024
-Retevis_P62,@KC9HI,15-Jun-2024
-Retevis_RA685,@KC9HI,19-Nov-2022
-Retevis_RA79,@KC9HI,27-Oct-2023
-Retevis_RA85,@KC9HI,19-Nov-2022
-Retevis_RA87,@KC9HI,16-May-2024
-Retevis_RA89,@KC9HI,23-Nov-2023
-Retevis_RB15,@KC9HI,18-Dec-2022
-Retevis_RB17,@KC9HI,28-Nov-2022
-Retevis_RB17A,@KC9HI,30-Nov-2022
-Retevis_RB17P,@KC9HI,18-Dec-2022
-Retevis_RB17V,@KC9HI,28-Nov-2022
-Retevis_RB18,@KC9HI,28-Nov-2022
-Retevis_RB19,@KC9HI,28-Nov-2022
-Retevis_RB19P,@KC9HI,28-Nov-2022
-Retevis_RB23,@KC9HI,30-Nov-2022
-Retevis_RB26,@KC9HI,30-Nov-2022
-Retevis_RB27,@KC9HI,30-Nov-2022
-Retevis_RB27B,@KC9HI,30-Nov-2022
-Retevis_RB28,@KC9HI,9-Feb-2023
-Retevis_RB28B,@KC9HI,27-Jan-2023
-Retevis_RB27V,@KC9HI,30-Nov-2022
-Retevis_RB29,@KC9HI,24-Dec-2022
-Retevis_RB615,@KC9HI,18-Dec-2022
-Retevis_RB617,@KC9HI,28-Nov-2022
-Retevis_RB618,@KC9HI,28-Nov-2022
-Retevis_RB619,@KC9HI,28-Nov-2022
-Retevis_RB627B,@KC9HI,30-Nov-2022
-Retevis_RB628,@KC9HI,10-Feb-2023
-Retevis_RB628B,@KC9HI,28-Jan-2023
-Retevis_RB629,@KC9HI,24-Dec-2022
-Retevis_RB75,@KC9HI,28-Nov-2022
-Retevis_RB85,@KC9HI,28-Nov-2022
-Retevis_RB87,@KC9HI,10-Mar-2023
-Retevis_RB89,@KC9HI,6-Aug-2024
-Retevis_RT15,@KC9HI,18-Feb-2023
-Retevis_RT16,@KC9HI,30-Nov-2022
-Retevis_RT19,@KC9HI,30-Nov-2022
-Retevis_RT20,@k9ps-paul,7-Sep-2023
-Retevis_RT21,@KC9HI,30-Nov-2022
-Retevis_RT21V,@KC9HI,24-Jul-2023
-Retevis_RT22,@KC9HI,9-Dec-2022
-Retevis_RT23,@KC9HI,17-Dec-2022
-Retevis_RT22FRS,@KC9HI,9-Dec-2022
-Retevis_RT22S,@KC9HI,28-Nov-2022
-Retevis_RT24,@KC9HI,22-Dec-2022
-Retevis_RT24V,@KC9HI,27-Aug-2023
-Retevis_RT26,@KC9HI,17-Dec-2022
-Retevis_RT29_UHF,@KC9HI,30-Nov-2022
-Retevis_RT29_VHF,@KC9HI,30-Nov-2022
-Retevis_RT40B,@KC9HI,30-Nov-2022
-Retevis_RT47,@KC9HI,28-Nov-2022
-Retevis_RT47V,@KC9HI,28-Nov-2022
-Retevis_RT1,@KC9HI,11-Dec-2022
-Retevis_RT6,@KC9HI,3-Dec-2022
-Retevis_RT619,@KC9HI,30-Nov-2022
-Retevis_RT622,@KC9HI,9-Dec-2022
-Retevis_RT647,@KC9HI,28-Nov-2022
-Retevis_RT668,@KC9HI,28-Nov-2022
-Retevis_RT68,@KC9HI,28-Nov-2022
-Retevis_RT76,@KC9HI,30-Nov-2022
-Retevis_RT76P,@KC9HI,17-Dec-2022
-Retevis_RT85,@KC9HI,5-Dec-2022
-Retevis_RT86,@KC9HI,17-Feb-2023
-Retevis_RT87,@KC9HI,17-Dec-2022
-Retevis_RT95,@KC9HI,13-Nov-2022
-Retevis_RT95_VOX,+Retevis_RT95,13-Nov-2022
-Retevis_RT98,@KC9HI,14-Dec-2022
-Retevis_RT9000D_136-174,@KC9HI,8-Dec-2022
-Retevis_RT9000D_220-260,@KC9HI,8-Dec-2022
-Retevis_RT9000D_400-490,@KC9HI,8-Dec-2022
-Retevis_RT9000D_66-88,@KC9HI,8-Dec-2022
-Ruyage_UV58Plus,@KC9HI,18-Mar-2023
-SenhaiX_8800,+Radioddity_GS-5B,17-Mar-2023
-Socotran_FB-8629,+Radtel_RT-490,11-Nov-2023
-Socotran_JC-8629,+Radtel_RT-490,11-Nov-2023
-Talkpod_A36plus,@KC9HI,12-Jun-2023
-Talkpod_A36plus_8w,@KC9HI,16-Feb-2024
-TDXone_TD-Q8A,@KC9HI,18-Dec-2022
-TIDRADIO_TD-H6,@kk7ds,21-Oct-2022
-TIDRADIO_TD-H8,@Sandmann34,7-Feb-2023
-TIDRADIO_TD-H8-GMRS,@Sandmann34,7-Feb-2023
-TIDRADIO_TD-H8-HAM,@Sandmann34,7-Feb-2023
-TID_TD-M8,+Retevis_RT22,9-Dec-2022
-TID_TD-UV68,@Sandmann34,7-Feb-2023
-TIDRADIO_TD-H3,@songjunbiao,1-Dec-2023
-TIDRADIO_TD-H3-GMRS,@songjunbiao,1-Dec-2023
-TIDRADIO_TD-H3-HAM,@songjunbiao,1-Dec-2023
-TYT_TH-UVF1,@kk7ds,13-Dec-2022
-TYT_TH-UVF8D,@MELERIX,2-Feb-2023
-TYT_TH-UV8000,@KC9HI,6-Jan-2023
-TYT_TH-UV88,@KC9HI,5-Dec-2022
-TYT_TH-7800,#10585,4-Jul-2023
-TYT_TH9000_144,+Retevis_RT9000D_136-174,8-Dec-2022
-TYT_TH9000_220,+Retevis_RT9000D_220-260,8-Dec-2022
-TYT_TH9000_440,+Retevis_RT9000D_400-490,8-Dec-2022
-TYT_TH-9800,#10755,30-Jul-2023
-WACCOM_MINI-8900,@KC9HI,11-Nov-2022
-WLN_KD-C1,+Retevis_RT22,9-Dec-2022
-Wouxun_KG-1000G,@mrtjr1,23-jan-2023
-Wouxun_KG-1000G_Plus,@mrtjr1,23-jan-2023
-Wouxun_KG-816,+Wouxun_KG-UV6,11-Dec-2022
-Wouxun_KG-818,+Wouxun_KG-UV6,11-Dec-2022
-Wouxun_KG-UV6,@KC9HI,11-Dec-2022
-Wouxun_KG-UVD1P,+Wouxun_KG-UV6,11-Dec-2022
-Wouxun_KG-UV8D,Unit tested; needs confirm,24-Dec-2022
-Wouxun_KG-UV8D_Plus,Unit tested; needs confirm,2-Jan-2022
-Wouxun_KG-UV8H,@mrtjr1,27-Mar-2023
-Wouxun_KG-UV8E,W5EGL,2-Jan-2022
-Wouxun_KG-UV9D_Plus,@samwich,10-Jan-2023
-Wouxun_KG-UV920P-A,@KC9HI,22-Dec-2022
-Wouxun_KG-UV980P,@mrtjr1,23-jan-2023
-Wouxun_KG-UV9PX,@mrtjr1,20-Jan-2022
-Wouxun_KG-UV9GX,@mrtjr1,27-Mar-2023
-Wouxun_KG-UV9G_Pro,@mrtjr1,25-Apr-2023
-Wouxun_KG-UV9K,@mrtjr1,14-Apr-2023
-Wouxun_KG-935G,@mrtjr1,4-Jan-2022
-Wouxun_KG-935G_Plus,@mrtjr1,7-Feb-2023
-Wouxun_KG-935H,@mrtjr1,14-Mar-2025
-Yaesu_FT-1500M,@f3sty,05-Dec-2022
-Yaesu_FT-2800M,#10616,05-Jun-2023
-Yaesu_FT-2900R_1900R,#10274,14-Jan-2023
-Yaesu_FT-2900R_1900RTXMod_Opened_Xmit,+Yaesu_FT-2900R_1900R,14-Jan-2023
-Yaesu_FT-1D_R,+Yaesu_FT3D_R,30-Dec-2022
-Yaesu_FT2D_R,+Yaesu_FT3D_R,30-Dec-2022
-Yaesu_FT2D_Rv2,+Yaesu_FT3D_R,30-Dec-2022
-Yaesu_FT3D_R,@kk7ds,30-Dec-2022
-Yaesu_FT-450,@WCurlew,03-Nov-2023
-Yaesu_FT-450D,@Old-Phart,01-Jun-2023
-Yaesu_FT-4XE,Unit tested; needs confirm,24-Dec-2022
-Yaesu_FT-4XR,+Yaesu_FT-4XE,24-Dec-2022
-Yaesu_FT-4VR,+Yaesu_FT-4XE,24-Dec-2022
-Yaesu_FT-65R,#10266,13-Jan-2022
-Yaesu_FT-65E,@kwirk,27-Jan-2023
-Yaesu_FT-25R,+Yaesu_FT-4XE,24-Dec-2022
-Yaesu_FT-50,#10824,5-Sep-2023
-Yaesu_FT-60,N0EYE,9-Jan-2023
-Yaesu_FT-70D,@n8sqt,05-Dec-2022
-Yaesu_FT-7800_7900,@kk7ds,24-Oct-2022
-Yaesu_FT-8100,#10904,19-Oct-2023
-Yaesu_FT-8800,@kk7ds,24-Oct-2022
-Yaesu_FT-8900,#10753,30-Jul-2023
-Yaesu_FT-817,@kk7ds,14-Feb-2019
-Yaesu_FT-817ND,+Yaesu_FT-817,14-Feb-2019
-Yaesu_FT-817ND_US,+Yaesu_FT-817,14-Feb-2019
-Yaesu_FT-818,@thomasrussellmurphy,4-Feb-2023
-Yaesu_FT-818ND_US,+Yaesu_FT-817,14-Feb-2019
-Yaesu_FT-857_897,+Yaesu_FT-817,14-Feb-2019
-Yaesu_FT-857_897_US,+Yaesu_FT-817,14-Feb-2019
-Yaesu_FT-90,#10386,22-Feb-2023
-Yaesu_FTM-350,@kk7ds,4-Dec-2022
-Yaesu_VX-2,@thomasrussellmurphy,20-Jan-2023
-Yaesu_VX-3,@kk7ds,15-Feb-2019
-Yaesu_VX-5,*yaesu_clone,12-Dec-2022
-Yaesu_VX-6,@dominickpastore,10-Dec-2022
-Yaesu_VX-7,@kk7ds,15-Feb-2019
-Yaesu_VX-8R,+Yaesu_VX-8DR,15-Feb-2019
-Yaesu_VX-8DR,@kk7ds,15-Feb-2019
-Yaesu_VX-8GE,+Yaesu_VX-8DR,15-Feb-2019
-Yedro_YC-M04VUS,+Retevis_RT95,13-Nov-2022
-Zastone_ZT-X6,+Retevis_RT22,9-Dec-2022
diff --git a/tests/test_brute_force.py b/tests/test_brute_force.py
index 0114868..10a4936 100644
--- a/tests/test_brute_force.py
+++ b/tests/test_brute_force.py
@@ -199,7 +199,7 @@ class TestCaseBruteForce(base.DriverTest):
m1 = self.radio.get_memory(i)
if m1.empty:
continue
- errs, warns = chirp_common.split_validation_msgs(
+ warns, errs = chirp_common.split_validation_msgs(
self.radio.validate_memory(m1))
self.assertEqual([], errs,
('Radio has validation errors for memory %i '
diff --git a/tests/test_setting_docs.py b/tests/test_setting_docs.py
new file mode 100644
index 0000000..6fb3789
--- /dev/null
+++ b/tests/test_setting_docs.py
@@ -0,0 +1,41 @@
+import os
+
+import yaml
+
+from chirp import directory
+from chirp import settings
+from tests import base
+
+with open(os.path.join(os.path.dirname(__file__),
+ 'driver_setting_docs.yaml')) as f:
+ DOCUMENTED = yaml.load(f, Loader=yaml.SafeLoader) or []
+
+
+class TestCaseSettingDocs(base.DriverTest):
+ def setUp(self):
+ # Most radios are not listed, so skip them before loading the image
+ if (self.SUB_DEVICE is None and
+ directory.radio_class_id(self.RADIO_CLASS) not in DOCUMENTED):
+ self.skipTest('Not listed in driver_setting_docs.yaml')
+ super().setUp()
+
+ def test_settings_have_docs(self):
+ if directory.radio_class_id(self.radio.__class__) not in DOCUMENTED:
+ self.skipTest('Not listed in driver_setting_docs.yaml')
+
+ all_settings = []
+ if self.rf.has_settings:
+ all_settings.extend(self.radio.get_settings().walk())
+ for i in range(*self.rf.memory_bounds):
+ mem = self.radio.get_memory(i)
+ if not mem.empty:
+ extra = mem.extra
+ if isinstance(extra, settings.RadioSettingGroup):
+ extra = extra.walk()
+ all_settings.extend(extra)
+ break
+
+ missing = [setting.get_name() for setting in all_settings
+ if not setting.__doc__]
+ self.assertEqual([], missing,
+ 'Settings without a description')
diff --git a/tests/unit/__pycache__/test_alinco_clone.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_alinco_clone.cpython-310-pytest-7.1.3.pyc
index 47581de..84d6e46 100644
--- a/tests/unit/__pycache__/test_alinco_clone.cpython-310-pytest-7.1.3.pyc
+++ b/tests/unit/__pycache__/test_alinco_clone.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_directory.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_directory.cpython-310-pytest-7.1.3.pyc
index 23d774d..bd37c26 100644
--- a/tests/unit/__pycache__/test_directory.cpython-310-pytest-7.1.3.pyc
+++ b/tests/unit/__pycache__/test_directory.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_ft450d_docs.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_ft450d_docs.cpython-310-pytest-7.1.3.pyc
new file mode 100644
index 0000000..ec0002d
--- /dev/null
+++ b/tests/unit/__pycache__/test_ft450d_docs.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_kenwood_tone.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_kenwood_tone.cpython-310-pytest-7.1.3.pyc
index ba7d6fe..10eaf8d 100644
--- a/tests/unit/__pycache__/test_kenwood_tone.cpython-310-pytest-7.1.3.pyc
+++ b/tests/unit/__pycache__/test_kenwood_tone.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_thg71.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_thg71.cpython-310-pytest-7.1.3.pyc
new file mode 100644
index 0000000..cb249cc
--- /dev/null
+++ b/tests/unit/__pycache__/test_thg71.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_wxui_radiothread.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_wxui_radiothread.cpython-310-pytest-7.1.3.pyc
index 26c1c5d..dd688fb 100644
--- a/tests/unit/__pycache__/test_wxui_radiothread.cpython-310-pytest-7.1.3.pyc
+++ b/tests/unit/__pycache__/test_wxui_radiothread.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_yaesu_clone.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_yaesu_clone.cpython-310-pytest-7.1.3.pyc
index 79c5233..2abfeb7 100644
--- a/tests/unit/__pycache__/test_yaesu_clone.cpython-310-pytest-7.1.3.pyc
+++ b/tests/unit/__pycache__/test_yaesu_clone.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/test_alinco_clone.py b/tests/unit/test_alinco_clone.py
index c5e28ca..5aaf872 100644
--- a/tests/unit/test_alinco_clone.py
+++ b/tests/unit/test_alinco_clone.py
@@ -145,7 +145,9 @@ class AlincoCloneTest(unittest.TestCase):
radio = rclass(pipe)
radio.sync_in()
if not radio.NEEDS_COMPAT_SERIAL:
- self.assertIsInstance(radio._mmap, memmap.MemoryMapBytes)
+ # Note that MemoryMap (the str-based compat class) is a subclass
+ # of MemoryMapBytes, so this must compare the type exactly.
+ self.assertEqual(type(radio._mmap), memmap.MemoryMapBytes)
def _test_alinco_upload(self, rclass, image):
pipe = FakeAlincoSerial(image)
@@ -157,15 +159,42 @@ class AlincoCloneTest(unittest.TestCase):
self.assertEqual(ref_image[0x200:rclass._memsize],
pipe.image.get_packed()[0x200:rclass._memsize])
+ def _test_alinco_roundtrip(self, rclass, image):
+ # Read from the radio and then write the same thing straight back,
+ # which is what actually happens in the field (#12611)
+ pipe = FakeAlincoSerial(image)
+ radio = rclass(None)
+ radio.pipe = pipe
+ with mock.patch('time.sleep'):
+ radio.sync_in()
+ pipe.zero()
+ with mock.patch('time.sleep'):
+ radio.sync_out()
+ ref_image = open(image, 'rb').read()
+ self.assertEqual(ref_image[0x200:rclass._memsize],
+ pipe.image.get_packed()[0x200:rclass._memsize])
+
def _test_alinco(self, rclass):
ident = directory.radio_class_id(rclass)
image = os.path.join(os.path.dirname(__file__),
'..', 'images',
'%s.img' % ident)
with mock.patch('time.sleep'):
+ # The round-trip goes first, as it is the flow that actually
+ # broke in the field (#12611)
+ self._test_alinco_roundtrip(rclass, image)
self._test_alinco_upload(rclass, image)
self._test_alinco_download(rclass, image)
+ def _test_roundtrip(self, rclass):
+ """Run only the read-then-write-back test for @rclass"""
+ ident = directory.radio_class_id(rclass)
+ image = os.path.join(os.path.dirname(__file__),
+ '..', 'images',
+ '%s.img' % ident)
+ with mock.patch('time.sleep'):
+ self._test_alinco_roundtrip(rclass, image)
+
def test_djg7(self):
self._test_alinco(alinco.AlincoDJG7EG)
@@ -180,6 +209,17 @@ class AlincoCloneTest(unittest.TestCase):
# specifically
self._test_alinco(alinco.DJ175Radio)
+ def test_dj175_roundtrip(self):
+ # Uploading after a download used to fail with
+ # "encoding with 'hex' codec failed (TypeError: a bytes-like
+ # object is required, not 'str')" (#12611). This is kept as its
+ # own test so that the actual failure is reported, rather than
+ # tripping over the mmap type check in _test_alinco_download().
+ self._test_roundtrip(alinco.DJ175Radio)
+
+ def test_dr235_roundtrip(self):
+ self._test_roundtrip(alinco.DR235Radio)
+
def test_all_alinco_identify(self):
# Make sure all the alinco models have bytes for their _model
# and can identify properly
diff --git a/tests/unit/test_directory.py b/tests/unit/test_directory.py
index e9f1697..9b39c45 100644
--- a/tests/unit/test_directory.py
+++ b/tests/unit/test_directory.py
@@ -80,6 +80,25 @@ class TestDirectory(base.BaseTest):
self.assertEqual('A', radio.VARIANT)
+class TestImageDetection(base.BaseTest):
+ def test_clone_mode_radio_requires_metadata(self):
+ class NewRadio(chirp_common.CloneModeRadio):
+ _memsize = 16
+
+ self.assertFalse(NewRadio.match_model(b'0' * 16, 'test.img'))
+
+ def test_legacy_image_detect_matches_memory_size(self):
+ class OldRadio(chirp_common.CloneModeRadio):
+ _memsize = 16
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return cls._memsize and len(filedata) == cls._memsize
+
+ self.assertTrue(OldRadio.match_model(b'0' * 16, 'test.img'))
+ self.assertFalse(OldRadio.match_model(b'0' * 15, 'test.img'))
+
+
class TestDetectBruteForce(base.BaseTest):
def test_detect_all(self):
# Attempt a brute-force detection of all test images.
diff --git a/tests/unit/test_ft450d_docs.py b/tests/unit/test_ft450d_docs.py
new file mode 100644
index 0000000..266c1a0
--- /dev/null
+++ b/tests/unit/test_ft450d_docs.py
@@ -0,0 +1,26 @@
+import os
+
+from chirp.drivers import ft450d
+from tests.unit import base # noqa
+
+
+def test_ft450_models_all_settings_have_docs():
+ images = os.path.join(os.path.dirname(__file__), "..", "images")
+ models = (
+ (ft450d.FT450DRadio, "Yaesu_FT-450D.img"),
+ (ft450d.FT450Radio, "Yaesu_FT-450.img"),
+ )
+
+ for radio_cls, image in models:
+ radio = radio_cls(os.path.join(images, image))
+ radio.get_features()
+ settings = list(radio.get_settings().walk())
+ settings.extend(radio.get_memory(1).extra.walk())
+
+ missing = [setting.get_name() for setting in settings
+ if not setting.__doc__]
+ att = next(setting for setting in settings
+ if setting.get_name() == "att")
+
+ assert not missing, radio_cls.MODEL
+ assert "20 dB" in att.__doc__
diff --git a/tests/unit/test_ft8000r.py b/tests/unit/test_ft8000r.py
new file mode 100644
index 0000000..9119e77
--- /dev/null
+++ b/tests/unit/test_ft8000r.py
@@ -0,0 +1,658 @@
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+import unittest
+from unittest import mock
+
+from chirp import chirp_common, directory, errors, memmap
+from chirp.drivers import ft8000r
+from chirp.settings import MemSetting
+
+
+FIXTURE = Path(__file__).parents[1] / 'images' / 'Yaesu_FT-8000R.img'
+
+
+class Clock:
+ now = 0.0
+
+ def monotonic(self):
+ return self.now
+
+ def sleep(self, seconds):
+ self.now += seconds
+
+
+class Port:
+ def __init__(self, clock, data=b'', echo=True, short=False, corrupt=False):
+ self.clock = clock
+ self.pending = bytearray(data)
+ self.echo = echo
+ self.short = short
+ self.corrupt = corrupt
+ self.writes = []
+ self.reads = []
+ self.timeout = 1
+
+ @property
+ def in_waiting(self):
+ return len(self.pending)
+
+ def read(self, count):
+ self.reads.append((count, self.timeout))
+ if len(self.pending) < count:
+ self.clock.sleep(self.timeout)
+ # Match serial.read(): collect count bytes or return short on timeout.
+ result = bytes(self.pending[:count])
+ del self.pending[:count]
+ return result
+
+ def write(self, data):
+ self.writes.append(data)
+ if self.short:
+ return 0
+ if self.echo:
+ self.pending.extend(bytes([data[0] ^ 1]) if self.corrupt else data)
+ return len(data)
+
+ def flush(self):
+ pass
+
+
+class TestFT8000R(unittest.TestCase):
+ def setUp(self):
+ self.radio = ft8000r.FT8000RRadio(str(FIXTURE))
+ self.data = self.radio.get_mmap().get_packed()
+ self.left, self.right = self.radio.get_sub_devices()
+ self.clock = Clock()
+ self.time = mock.patch.object(ft8000r, 'time', SimpleNamespace(
+ monotonic=self.clock.monotonic, sleep=self.clock.sleep))
+ self.time.start()
+ self.addCleanup(self.time.stop)
+ self.status = []
+ self.radio.status_fn = self.status.append
+
+ def test_hardware_fixture_and_subdevices(self):
+ self.assertEqual(self.data[-1], 0x88)
+ self.assertTrue(self.radio.get_features().has_sub_devices)
+ self.assertFalse(self.left.get_features().has_sub_devices)
+ self.assertEqual(self.left.get_features().memory_bounds, (1, 50))
+ self.assertEqual(self.left.get_memory(1).freq, 146440000)
+ self.assertEqual(self.right.get_memory(1).freq, 439800000)
+ self.assertEqual(self.left.get_memory(13).mode, 'AM')
+ self.assertEqual(self.left.get_memory(4).duplex, '+')
+ self.assertEqual(self.left.get_memory(4).offset, 600000)
+ self.assertEqual(self.right.get_memory(1).duplex, '-')
+ self.assertEqual(self.right.get_memory(1).offset, 5000000)
+ self.assertEqual(sum(not self.left.get_memory(i).empty
+ for i in range(1, 51)), 13)
+ self.assertEqual(sum(not self.right.get_memory(i).empty
+ for i in range(1, 51)), 3)
+
+ def test_noop_roundtrip_is_byte_identical(self):
+ for child in (self.left, self.right):
+ for number in range(1, 51):
+ memory = child.get_memory(number)
+ if not memory.empty:
+ child.set_memory(memory)
+ self.assertEqual(self.radio.get_mmap().get_packed(), self.data)
+
+ def test_two_frequency_edits_and_working_records_share_parent_map(self):
+ shared = self.radio.get_mmap()
+ for child, freq in [(self.left, 146420000), (self.right, 439780000)]:
+ memory = child.get_memory(1)
+ memory.freq = freq
+ child.set_memory(memory)
+ changed = shared.get_packed()
+ self.assertIs(self.left.get_mmap(), shared)
+ self.assertIs(self.right.get_mmap(), shared)
+ self.assertEqual(changed[0x409:0x412], bytes.fromhex(
+ '00 08 16 57 88 00 17 70 00'))
+ self.assertEqual(changed[0x21F:0x228], bytes.fromhex(
+ '20 4c 43 1a e8 00 c3 50 00'))
+ self.assertEqual(changed[0x121:0x12A], changed[0x409:0x412])
+ self.assertEqual(changed[0x21:0x2A], changed[0x21F:0x228])
+ allowed = {0x21, 0x24, 0x25, 0x124, 0x125, 0x21F, 0x222,
+ 0x223, 0x40C, 0x40D, 0x743}
+ self.assertEqual({i for i, (a, b) in enumerate(zip(self.data, changed))
+ if a != b}, allowed)
+ ft8000r.validate_image(changed)
+
+ def test_selected_memory_replaces_working_front_panel_changes(self):
+ data = bytearray(self.data)
+ data[0x122] ^= 1
+ data[-1] = ft8000r.checksum(data)
+ self.radio = ft8000r.FT8000RRadio(memmap.MemoryMapBytes(bytes(data)))
+ left = self.radio.get_sub_devices()[0]
+ memory = left.get_memory(1)
+ memory.freq = 146420000
+ left.set_memory(memory)
+ self.assertEqual(left.get_mmap()[0x121:0x12A],
+ left.get_mmap()[0x409:0x412])
+
+ def test_duplicate_memories_can_be_edited(self):
+ data = bytearray(self.data)
+ data[0x412:0x41B] = data[0x409:0x412]
+ data[-1] = ft8000r.checksum(data)
+ left = ft8000r.FT8000RLeftRadio(memmap.MemoryMapBytes(bytes(data)))
+ memory = left.get_memory(1)
+ memory.freq = 146420000
+ left.set_memory(memory)
+ self.assertEqual(left.get_memory(1).freq, 146420000)
+ self.assertEqual(left.get_memory(2).freq, 146440000)
+ self.assertEqual(int(left._memobj.left.working.freq) * 100, 146420000)
+ left.set_memory(left.get_memory(1))
+
+ def test_selection_distinguishes_identical_records(self):
+ for mode, index, number, updates in (
+ (0x80, 0, 1, True), (0x80, 0, 2, False),
+ (0x80, 0, 55, False), (0x80, 1, 1, False),
+ (0x80, 1, 2, True), (0x00, 0, 1, False),
+ (0x00, 0, 55, False), (0x20, 0, 1, False),
+ (0x20, 0, 55, True), (0xC0, 0, 1, False),
+ (0x00, 0, 56, True), (0x80, 0, 56, False),
+ (0x20, 0, 56, False), (0xC0, 0, 56, False)):
+ with self.subTest(mode=mode, index=index, number=number):
+ data = bytearray(self.data)
+ for address in (0x121, 0x12A, 0x133, 0x412):
+ data[address:address + 9] = data[0x409:0x412]
+ data[0x11B] = mode
+ data[0x13C] = index
+ data[-1] = ft8000r.checksum(data)
+ left = ft8000r.FT8000RLeftRadio(
+ memmap.MemoryMapBytes(bytes(data)))
+ memory = left.get_memory(number)
+ memory.freq += 5000
+ left.set_memory(memory)
+ self.assertEqual(int(left._memobj.left.working.freq) * 100,
+ 146445000 if updates else 146440000)
+ ft8000r.validate_image(left.get_mmap().get_packed())
+
+ def test_unsupported_edits_do_not_mutate_image(self):
+ for field, value in [('tmode', 'DTCS'), ('freq', 439800000)]:
+ memory = self.left.get_memory(1)
+ setattr(memory, field, value)
+ self.assertTrue(any(isinstance(m, chirp_common.ValidationError)
+ for m in self.left.validate_memory(memory)))
+ for freq in (146441001, 146441000):
+ memory = self.left.get_memory(1)
+ memory.freq = freq
+ self.assertTrue(any(isinstance(m, chirp_common.ValidationError)
+ for m in self.left.validate_memory(memory)))
+ self.assertEqual(self.radio.get_mmap().get_packed(), self.data)
+
+ def test_tone_power_and_skip_from_vendor_record(self):
+ memory = self.right.get_memory(1)
+ self.assertEqual(memory.tmode, 'Tone')
+ self.assertEqual(memory.rtone, 100.0)
+ self.assertEqual(str(memory.power), 'High')
+ self.assertEqual(memory.skip, '')
+ self.assertFalse(self.right.get_features().has_dtcs)
+ self.assertEqual(len(self.right.get_features().valid_tones), 39)
+
+ def test_validation_rejects_unsupported_grid_before_import(self):
+ memory = self.right.get_memory(1)
+ memory.freq = 433006000
+ messages = self.right.validate_memory(memory)
+ self.assertTrue(any(isinstance(m, chirp_common.ValidationError)
+ for m in messages))
+ self.assertEqual(self.right.filter_name('Unsupported name'), '')
+
+ def test_uhf_five_khz_ending_matches_vendor_grid_code(self):
+ memory = self.right.get_memory('HOME')
+ memory.freq = 433005000
+ self.right.set_memory(memory)
+ raw = self.right.get_mmap()[0x33:0x3C]
+ self.assertEqual(raw[0] & 3, 1)
+ self.assertEqual(raw[2:5], (4330050).to_bytes(3, 'big'))
+ self.assertEqual(self.right.get_memory('HOME').freq, 433005000)
+
+ def test_factory_home_duplicate_does_not_block_regular_memory_edit(self):
+ data = bytearray(self.data)
+ data[0x133:0x13C] = data[0x409:0x412]
+ data[-1] = ft8000r.checksum(data)
+ left = ft8000r.FT8000RLeftRadio(memmap.MemoryMapBytes(bytes(data)))
+ memory = left.get_memory(1)
+ memory.freq = 146460000
+ left.set_memory(memory)
+ self.assertEqual(left.get_memory(1).freq, 146460000)
+ self.assertEqual(int(left._memobj.left.working.freq) * 100, 146460000)
+ self.assertEqual(left.get_memory('HOME').freq, 146440000)
+
+ def test_new_memory_all_fields_literal_vendor_encoding(self):
+ memory = self.left.get_memory(50)
+ memory.empty = False
+ memory.freq = 146520000
+ memory.duplex = '-'
+ memory.offset = 600000
+ memory.tmode = 'TSQL'
+ memory.rtone = 123.0
+ memory.mode = 'AM'
+ memory.skip = 'S'
+ memory.power = self.left.get_features().valid_power_levels[2]
+ old = self.radio.get_mmap().get_packed()
+ self.left.set_memory(memory)
+ offset = 0x409 + 49 * 9
+ raw = self.radio.get_mmap()[offset:offset + 9]
+ self.assertEqual(raw, bytes.fromhex('60 d2 16 5b 70 00 17 70 82'))
+ actual = self.left.get_memory(50)
+ for field in ('freq', 'duplex', 'offset', 'tmode', 'rtone',
+ 'mode', 'skip', 'power', 'empty'):
+ self.assertEqual(getattr(actual, field), getattr(memory, field))
+ self.assertEqual(self.radio.get_mmap()[0x121:0x12A], old[0x121:0x12A])
+ self.left.set_memory(actual)
+ ft8000r.validate_image(self.radio.get_mmap().get_packed())
+ actual.empty = True
+ self.left.set_memory(actual)
+ self.assertTrue(self.left.get_memory(50).empty)
+ ft8000r.validate_image(self.radio.get_mmap().get_packed())
+
+ def test_offset_split_and_working_copy_sync(self):
+ memory = self.right.get_memory(1)
+ memory.duplex = 'split'
+ memory.offset = 434812500
+ self.right.set_memory(memory)
+ data = self.radio.get_mmap().get_packed()
+ self.assertEqual(data[0x21F] & 0x3F, 0x35)
+ self.assertEqual(ft8000r.decode_frequency(int.from_bytes(
+ data[0x224:0x227], 'big')),
+ 434812500)
+ self.assertEqual(data[0x21:0x2A], data[0x21F:0x228])
+ self.assertEqual(self.right.get_memory(1).offset, 434812500)
+
+ def test_full_write_repairs_invalid_fields_preserving_unknown_bits(self):
+ data = bytearray(self.data)
+ # Unknown tone index/mode, bell/unknown flags and reserved power code.
+ data[0x40A] = 0xBF
+ data[0x411] = 0xFD
+ data[-1] = ft8000r.checksum(data)
+ left = ft8000r.FT8000RLeftRadio(memmap.MemoryMapBytes(bytes(data)))
+ memory = left.get_memory(1)
+ left.set_memory(memory)
+ self.assertEqual(left.get_mmap()[0x40A], b'\x08')
+ self.assertEqual(left.get_mmap()[0x411], b'\x39')
+ memory.skip = 'S'
+ left.set_memory(memory)
+ self.assertEqual(left.get_mmap()[0x40A], b'\x08')
+ self.assertEqual(left.get_mmap()[0x411], b'\x39')
+ self.assertEqual(left.get_mmap()[0x409], bytes([data[0x409] | 0x40]))
+ self.assertNotIn('rtone', memory.immutable)
+ memory.rtone = 100.0
+ left.set_memory(memory)
+ self.assertEqual(left.get_memory(1).rtone, 100.0)
+ self.assertEqual(left.get_mmap()[0x40A], b'\x0c')
+
+ def test_symbolic_record_and_direct_settings(self):
+ record = self.right._get_record(1)
+ self.assertEqual(int(record.freq), 4398000)
+ self.assertEqual(int(record.duplex), 2)
+ self.assertEqual(self.right.get_raw_memory(1), repr(record))
+ self.assertIsInstance(self.right.get_memory(1).extra['bell'],
+ MemSetting)
+ self.assertIsInstance(self.radio.get_settings()[0][
+ 'settings_tot'], MemSetting)
+
+ def test_memory_write_sets_all_fields_without_parsing_again(self):
+ memory = self.left.get_memory(1)
+ record = self.left._get_record(1)
+ record.tx_step = 3
+ record.tone = 0
+ record.skip = True
+ with mock.patch.object(ft8000r.bitwise, 'parse',
+ side_effect=AssertionError('Repeated parse')):
+ self.left.set_memory(memory)
+ self.assertEqual(int(record.tx_step), 0)
+ self.assertEqual(int(record.tone), ft8000r.TONES.index(memory.rtone))
+ self.assertFalse(record.skip)
+ ft8000r.validate_image(self.radio.get_mmap().get_packed())
+
+ def _same_band_radio(self, vhf_pair):
+ # Hardware captures confirmed unchanged memory banks, a copy of the
+ # active state on both receivers, and two saved inactive-band states.
+ data = bytearray(self.data)
+ active, inactive = ((0x11B, 0x1B) if vhf_pair else (0x1B, 0x11B))
+ saved = bytes(data[inactive:inactive + 0x5F])
+ data[0x7A:0xD9] = saved
+ data[0x17A:0x1D9] = saved
+ data[inactive:inactive + 0x5F] = data[active:active + 0x5F]
+ data[0xB] = (data[0xB] & ~0x14) | 0x10 | (4 if vhf_pair else 0)
+ data[-1] = ft8000r.checksum(data)
+ return ft8000r.FT8000RRadio(memmap.MemoryMapBytes(bytes(data)))
+
+ def test_same_band_images_keep_native_memory_and_special_channels(self):
+ for vhf_pair in (True, False):
+ radio = self._same_band_radio(vhf_pair)
+ for actual, original in zip(radio.get_sub_devices(),
+ (self.left, self.right)):
+ for number in range(1, 57):
+ a = actual.get_memory(number)
+ b = original.get_memory(number)
+ for field in ('empty', 'freq', 'duplex', 'offset',
+ 'rtone'):
+ self.assertEqual(getattr(a, field), getattr(b, field))
+ data = radio.get_mmap().get_packed()
+ radio.set_settings(radio.get_settings())
+ self.assertEqual(radio.get_mmap().get_packed(), data)
+
+ def test_same_band_memory_edits_update_matching_live_or_saved_copies(self):
+ for vhf_pair in (True, False):
+ for side in (0, 1):
+ radio = self._same_band_radio(vhf_pair)
+ device = radio.get_sub_devices()[side]
+ before = radio.get_mmap().get_packed()
+ memory = device.get_memory(1)
+ memory.freq += 5000
+ device.set_memory(memory)
+ data = radio.get_mmap().get_packed()
+ offset = 0x409 if side == 0 else 0x21F
+ expected = data[offset:offset + 9]
+ active = side == (0 if vhf_pair else 1)
+ copies = (0x21, 0x121) if active else (0x80, 0x180)
+ preserved = (0x80, 0x180) if active else (0x21, 0x121)
+ for address in copies:
+ self.assertEqual(data[address:address + 9], expected)
+ for address in preserved:
+ self.assertEqual(data[address:address + 9],
+ before[address:address + 9])
+ ft8000r.validate_image(data)
+
+ def test_same_band_receivers_have_independent_selections(self):
+ for vhf_pair, address in ((True, 0x1B), (False, 0x11B)):
+ radio = self._same_band_radio(vhf_pair)
+ data = bytearray(radio.get_mmap().get_packed())
+ data[address + 33] = 1
+ data[-1] = ft8000r.checksum(data)
+ radio = ft8000r.FT8000RRadio(memmap.MemoryMapBytes(bytes(data)))
+ device = radio.get_sub_devices()[0 if vhf_pair else 1]
+ memory = device.get_memory(1)
+ memory.freq += 5000
+ device.set_memory(memory)
+ self.assertEqual(radio.get_mmap()[address + 6:address + 15],
+ bytes(data[address + 6:address + 15]))
+ own = 0x121 if vhf_pair else 0x21
+ self.assertNotEqual(radio.get_mmap()[own:own + 9],
+ bytes(data[own:own + 9]))
+
+ def test_same_band_vfo_edit_preserves_other_receiver(self):
+ for vhf_pair in (True, False):
+ radio = self._same_band_radio(vhf_pair)
+ data = bytearray(radio.get_mmap().get_packed())
+ data[0x1B] &= ~0xA0
+ data[0x11B] &= ~0xA0
+ data[-1] = ft8000r.checksum(data)
+ radio = ft8000r.FT8000RRadio(memmap.MemoryMapBytes(bytes(data)))
+ device = radio.get_sub_devices()[0 if vhf_pair else 1]
+ memory = device.get_memory('VFO')
+ memory.freq += 5000
+ device.set_memory(memory)
+ other = 0x21 if vhf_pair else 0x121
+ self.assertEqual(radio.get_mmap()[other:other + 9],
+ bytes(data[other:other + 9]))
+
+ def test_same_band_inactive_settings_edit_both_saved_states(self):
+ for vhf_pair in (True, False):
+ radio = self._same_band_radio(vhf_pair)
+ before = radio.get_mmap().get_packed()
+ side = 'right' if vhf_pair else 'left'
+ settings = radio.get_settings()
+ settings[0][side + '_saved_rf_sql'].value = 'Full scale'
+ settings[1][side + '_dtmf'].value = '12#P'
+ radio.set_settings(settings)
+ data = radio.get_mmap().get_packed()
+ for base in (0x7A, 0x17A):
+ self.assertEqual(data[base + 0x5A], 11)
+ self.assertEqual(data[base + 0x28:base + 0x2D],
+ bytes.fromhex('04 01 02 0f 10'))
+ for base in (0x1B, 0x11B):
+ self.assertEqual(data[base:base + 0x5F],
+ before[base:base + 0x5F])
+ ft8000r.validate_image(data)
+
+ def test_deleting_active_memory_preserves_live_vfo(self):
+ memory = self.left.get_memory(1)
+ memory.empty = True
+ self.left.set_memory(memory)
+ self.assertTrue(self.left.get_memory(1).empty)
+ self.assertEqual(self.radio.get_mmap()[0x121:0x12A],
+ self.data[0x121:0x12A])
+
+ def test_special_memories_addresses_and_noop(self):
+ for child, addresses in [
+ (self.left, [0x5CB, 0x5D4, 0x5DD, 0x5E6, 0x133, 0x12A]),
+ (self.right, [0x3E1, 0x3EA, 0x3F3, 0x3FC, 0x33, 0x2A])]:
+ locations = zip(ft8000r.SPECIALS, addresses)
+ for i, (name, address) in enumerate(locations):
+ self.assertEqual(child._get_record(name).get_offset(), address)
+ memory = child.get_memory(name)
+ self.assertEqual(memory.number, 51 + i)
+ self.assertEqual(memory.extd_number, name)
+ child.set_memory(memory)
+ self.assertEqual(self.radio.get_mmap().get_packed(), self.data)
+ vfo = self.left.get_memory('VFO')
+ vfo.freq = 146460000
+ self.left.set_memory(vfo)
+ self.assertEqual(self.left.get_memory('VFO').freq, 146460000)
+ self.assertEqual(self.left.get_memory(1).freq, 146440000)
+
+ def test_bell_and_mask_only_change_known_bits(self):
+ memory = self.right.get_memory(1)
+ memory.tmode = 'TSQL'
+ memory.extra['bell'].value = True
+ memory.extra['masked'].value = True
+ self.right.set_memory(memory)
+ raw = self.radio.get_mmap().get_packed()[0x21F:0x228]
+ self.assertEqual(raw, bytes.fromhex('a5 cc 43 1b b0 00 c3 50 04'))
+ actual = self.right.get_memory(1)
+ self.assertFalse(actual.empty)
+ self.assertTrue(bool(actual.extra['bell'].value))
+ self.assertTrue(bool(actual.extra['masked'].value))
+ actual.tmode = 'Tone'
+ self.right.set_memory(actual)
+ self.assertFalse(bool(self.right.get_memory(1).extra['bell'].value))
+
+ def test_all_tones_and_power_choices(self):
+ for child in (self.left, self.right):
+ for mode in ft8000r.TMODES:
+ for tone in ft8000r.TONES:
+ memory = child.get_memory(2)
+ memory.tmode = mode
+ memory.rtone = tone
+ child.set_memory(memory)
+ actual = child.get_memory(2)
+ self.assertEqual((actual.tmode, actual.rtone),
+ (mode, tone))
+ for power in child.get_features().valid_power_levels:
+ memory = child.get_memory(2)
+ memory.power = power
+ child.set_memory(memory)
+ self.assertEqual(child.get_memory(2).power, power)
+
+ def test_settings_noop_preserves_unknown_and_noncanonical_values(self):
+ for original in (self.data, bytes([0xFF]) * 1860):
+ data = bytearray(original)
+ data[:5] = ft8000r.HEADER
+ data[-1] = ft8000r.checksum(data)
+ radio = ft8000r.FT8000RRadio(memmap.MemoryMapBytes(bytes(data)))
+ settings = radio.get_settings()
+ radio.set_settings(settings)
+ self.assertEqual(radio.get_mmap().get_packed(), bytes(data))
+
+ def test_settings_change_exact_bits_and_dtmf_encoding(self):
+ settings = self.radio.get_settings()
+ common, dtmf = settings
+ common['settings_key_beep'].value = False
+ common['settings_tot'].value = '5 minute(s)'
+ common['right_rf_sql'].value = 'Full scale'
+ common['right_control_scan'].value = '5 seconds'
+ common['settings_volts_offset'].value = '-0.066 V'
+ dtmf['left_dtmf'].value = '12ABCD*#P0'
+ self.radio.set_settings(settings)
+ data = self.radio.get_mmap().get_packed()
+ self.assertEqual(data[0xB], self.data[0xB] | 0x40)
+ self.assertEqual(data[0xD:0xF], b'\x01\x2c')
+ self.assertEqual(data[0x75], 11)
+ self.assertEqual(data[0x1D], self.data[0x1D] | 0x10)
+ self.assertEqual(data[0x13], 0xFF)
+ self.assertEqual(data[0x143:0x154], bytes.fromhex(
+ '0a 01 02 0a 0b 0c 0d 0e 0f 10 00 10 10 10 10 10 10'))
+ after = self.radio.get_settings()
+ self.assertEqual(str(after[1]['left_dtmf'].value), '12ABCD*#P0')
+ self.assertEqual(str(after[0]['settings_tot'].value), '5 minute(s)')
+ allowed = {0xB, 0xD, 0xE, 0x13, 0x75, 0x1D, 0x743}
+ allowed.update(range(0x143, 0x154))
+ self.assertTrue({i for i, (a, b) in enumerate(zip(self.data, data))
+ if a != b} <= allowed)
+ ft8000r.validate_image(data)
+
+ def test_subband_operation_does_not_change_receive_mode(self):
+ for index in (1, 2, 0):
+ settings = self.radio.get_settings()
+ settings[0]['sub_operation'].value = index
+ self.radio.set_settings(settings)
+ data = self.radio.get_mmap().get_packed()
+ self.assertEqual(data[0xB] & ~2, self.data[0xB] & ~2)
+ self.assertEqual(data[0xC] & ~2, self.data[0xC] & ~2)
+ self.assertEqual(int(self.radio.get_settings()[0][
+ 'sub_operation'].value), index)
+
+ def test_save_and_reopen_with_chirp_metadata(self):
+ with tempfile.TemporaryDirectory() as temp:
+ path = str(Path(temp) / 'radio.img')
+ self.radio.save(path)
+ loaded = directory.get_radio_by_image(path)
+ self.assertIsInstance(loaded, ft8000r.FT8000RRadio)
+ self.assertEqual(loaded.MODEL, 'FT-8000R')
+ self.assertEqual(loaded.get_mmap().get_packed(), self.data)
+ # No loose raw-image autodetection by checksum/size alone.
+ self.assertFalse(ft8000r.FT8000RRadio.match_model(
+ self.data, 'unknown.img'))
+
+ def test_unreleased_development_model_is_not_registered(self):
+ class EarlyFT8000(ft8000r.FT8000RRadio):
+ MODEL = 'FT-8000'
+
+ with tempfile.TemporaryDirectory() as temp:
+ path = str(Path(temp) / 'legacy.img')
+ radio = EarlyFT8000(memmap.MemoryMapBytes(self.data))
+ radio.save(path)
+ with self.assertRaises(errors.ImageMetadataInvalidModel):
+ directory.get_radio_by_image(path)
+
+ def test_download_blocking_with_observed_fixed_preamble(self):
+ port = Port(self.clock, data=b'\x00\xfc' + self.data)
+ radio = ft8000r.FT8000RRadio(port)
+ radio.status_fn = self.status.append
+ radio.sync_in()
+ self.assertEqual(radio.get_mmap().get_packed(), self.data)
+ self.assertEqual(radio.metadata['ft8000_download_prefix'], '00fc')
+ self.assertEqual(port.writes, [])
+ self.assertEqual(port.stopbits, 2)
+ self.assertEqual(port.reads[:3], [(1, 3), (4, 3), (2, 3)])
+ self.assertFalse(hasattr(port, 'dtr'))
+ self.assertFalse(hasattr(port, 'rts'))
+ self.assertFalse(hasattr(port, 'write_timeout'))
+ self.assertEqual(self.status[-1].cur, 1860)
+
+ def test_download_requests_exact_blocks_with_serial_timeouts(self):
+ port = Port(self.clock, data=self.data)
+ radio = ft8000r.FT8000RRadio(port)
+ radio.status_fn = self.status.append
+ radio.sync_in()
+ self.assertEqual(port.reads[:2], [(1, 3), (4, 3)])
+ self.assertTrue(all(timeout == 3 for count, timeout in port.reads[1:]))
+ self.assertEqual(sum(count for count, timeout in port.reads), 1860)
+ self.assertEqual(radio.get_mmap().get_packed(), self.data)
+ self.assertEqual(port.writes, [])
+
+ def test_download_waits_for_operator_without_changing_timeout(self):
+ class DelayedPort(Port):
+ attempts = 0
+
+ def read(self, count):
+ self.attempts += 1
+ if self.attempts <= 2:
+ self.reads.append((count, self.timeout))
+ self.clock.sleep(self.timeout)
+ return b''
+ return super().read(count)
+
+ port = DelayedPort(self.clock, data=self.data)
+ radio = ft8000r.FT8000RRadio(port)
+ radio.status_fn = self.status.append
+ radio.sync_in()
+ self.assertEqual(port.reads[:4], [(1, 3), (1, 3), (1, 3), (4, 3)])
+ self.assertEqual(radio.get_mmap().get_packed(), self.data)
+ self.assertEqual(self.clock.now, 6)
+
+ def test_short_header_or_block_stops_without_polling(self):
+ for data, expected_reads in [(b'\x00', 2), (self.data[:30], 3),
+ (b'garbage' + self.data, 2)]:
+ with self.subTest(size=len(data)):
+ port = Port(self.clock, data=data)
+ radio = ft8000r.FT8000RRadio(port)
+ radio.status_fn = self.status.append
+ with self.assertRaises(errors.RadioError):
+ radio.sync_in()
+ self.assertEqual(len(port.reads), expected_reads)
+ self.assertIsNone(radio.get_mmap())
+
+ def test_corrupt_or_partial_download_not_installed(self):
+ corrupt = bytearray(self.data)
+ corrupt[-1] ^= 1
+ for data in (bytes(corrupt), self.data[:100], b'', b'X' * 100):
+ with self.subTest(size=len(data)):
+ port = Port(self.clock, data=data)
+ radio = ft8000r.FT8000RRadio(port)
+ radio.status_fn = self.status.append
+ with self.assertRaises(errors.RadioError):
+ radio.sync_in()
+ self.assertIsNone(radio.get_mmap())
+ self.assertEqual(port.writes, [])
+
+ def test_upload_exact_one_byte_writes_echo_and_completion(self):
+ port = Port(self.clock)
+ self.radio.set_pipe(port)
+ self.radio.sync_out()
+ self.assertEqual(b''.join(port.writes), self.data + b'\x06')
+ self.assertTrue(all(len(chunk) == 1 for chunk in port.writes))
+ self.assertGreaterEqual(self.clock.now, 18.8)
+ self.assertEqual(port.in_waiting, 0)
+ self.assertEqual(port.stopbits, 2)
+ self.assertFalse(self.radio.WANTS_DTR)
+ self.assertTrue(self.radio.WANTS_RTS)
+
+ def test_upload_bad_echo_or_short_write_stops_at_first_byte(self):
+ for options in ({'echo': False}, {'corrupt': True}, {'short': True}):
+ with self.subTest(options=options):
+ port = Port(self.clock, **options)
+ self.radio.set_pipe(port)
+ with self.assertRaises(errors.RadioError):
+ self.radio.sync_out()
+ self.assertEqual(port.writes, [self.data[:1]])
+
+ def test_chirp_serialtrace_style_missing_write_count_requires_echo(self):
+ class TracePort(Port):
+ def write(self, data):
+ super().write(data)
+ # Same return behavior as wxui.serialtrace.SerialTrace.
+ return None
+ for echo in (True, False):
+ port = TracePort(self.clock, echo=echo)
+ self.radio.set_pipe(port)
+ if echo:
+ self.radio.sync_out()
+ self.assertEqual(b''.join(port.writes), self.data + b'\x06')
+ else:
+ with self.assertRaises(errors.RadioError):
+ self.radio.sync_out()
+ self.assertEqual(port.writes, [self.data[:1]])
+
+ def test_invalid_image_never_sends_and_unexpected_echo_stops_upload(self):
+ port = Port(self.clock, data=b'\x06')
+ self.radio.set_pipe(port)
+ with self.assertRaises(errors.RadioError):
+ self.radio.sync_out()
+ self.assertEqual(port.writes, [self.data[:1]])
+ self.radio.get_mmap()[1859] = self.data[-1] ^ 1
+ self.radio.pipe = None
+ with self.assertRaisesRegex(errors.RadioError, 'checksum'):
+ self.radio.sync_out()
diff --git a/tests/unit/test_kenwood_tone.py b/tests/unit/test_kenwood_tone.py
index a45657e..9496f8c 100644
--- a/tests/unit/test_kenwood_tone.py
+++ b/tests/unit/test_kenwood_tone.py
@@ -2085,6 +2085,12 @@ class TestParseQtdqt(base.BaseTest):
self.assertEqual(val, 32)
self.assertEqual(pol, "R")
+ def test_parse_dcs_inverse(self):
+ mode, val, pol = kenwood_tone.parse_qtdqt("D032I")
+ self.assertEqual(mode, "DTCS")
+ self.assertEqual(val, 32)
+ self.assertEqual(pol, "R")
+
def test_parse_dcs_lowercase(self):
mode, val, pol = kenwood_tone.parse_qtdqt("d023n")
self.assertEqual(mode, "DTCS")
@@ -2114,7 +2120,7 @@ class TestFormatQtdqt(base.BaseTest):
def test_format_dcs_reverse(self):
result = kenwood_tone.format_qtdqt("DTCS", 32, "R")
- self.assertEqual(result, "D032R")
+ self.assertEqual(result, "D032I")
def test_format_tone(self):
result = kenwood_tone.format_qtdqt("Tone", 103.5, "")
diff --git a/tests/unit/test_thg71.py b/tests/unit/test_thg71.py
new file mode 100644
index 0000000..3eed2a8
--- /dev/null
+++ b/tests/unit/test_thg71.py
@@ -0,0 +1,255 @@
+from tests.unit import base
+from chirp import chirp_common, errors
+from chirp.drivers import kenwood_live
+
+
+class TestTHG71(base.BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.radio = kenwood_live.THG71Radio(None)
+
+ def test_features(self):
+ rf = self.radio.get_features()
+ self.assertEqual(rf.memory_bounds, (0, 199))
+ self.assertEqual(rf.valid_modes, ["FM"])
+ self.assertEqual(rf.valid_tmodes, ["", "Tone", "TSQL"])
+ self.assertEqual(rf.valid_duplexes, ["", "+", "-", "split"])
+ self.assertEqual(rf.valid_skips, ["", "S"])
+ self.assertEqual(rf.valid_name_length, 6)
+ self.assertTrue(rf.has_tuning_step)
+ self.assertTrue(rf.can_odd_split)
+ self.assertTrue(rf.has_settings)
+ self.assertFalse(rf.has_sub_devices)
+ self.assertFalse(rf.has_dtcs)
+ self.assertFalse(rf.has_bank)
+
+ # Tone checks
+ self.assertEqual(len(rf.valid_tones), 38)
+ self.assertNotIn(69.3, rf.valid_tones)
+ self.assertIn(67.0, rf.valid_tones)
+ self.assertIn(71.9, rf.valid_tones)
+ self.assertIn(250.3, rf.valid_tones)
+
+ # Steps check
+ self.assertEqual(len(rf.valid_tuning_steps), 10)
+ self.assertEqual(rf.valid_tuning_steps[0], 5.0)
+ self.assertEqual(rf.valid_tuning_steps[9], 100.0)
+
+ # Special channels check
+ self.assertIn("CALL-V", rf.valid_special_chans)
+ self.assertIn("CALL-U", rf.valid_special_chans)
+ self.assertIn("Pr", rf.valid_special_chans)
+ self.assertIn("L0", rf.valid_special_chans)
+ self.assertIn("U0", rf.valid_special_chans)
+ self.assertIn("L9", rf.valid_special_chans)
+ self.assertIn("U9", rf.valid_special_chans)
+
+ # Bands check
+ self.assertEqual(len(rf.valid_bands), 3)
+ self.assertEqual(rf.valid_bands[0], (118000000, 174000000))
+ self.assertEqual(rf.valid_bands[1], (320000000, 470000000))
+ self.assertEqual(rf.valid_bands[2], (800000000, 949000000))
+
+ def test_tone_codes(self):
+ # Test code to tone conversion
+ self.assertEqual(kenwood_live._thg71_code_to_tone("01"), 67.0)
+ self.assertEqual(kenwood_live._thg71_code_to_tone("03"), 71.9)
+ self.assertEqual(kenwood_live._thg71_code_to_tone("09"), 88.5)
+ self.assertEqual(kenwood_live._thg71_code_to_tone("27"), 162.2)
+ self.assertEqual(kenwood_live._thg71_code_to_tone("39"), 250.3)
+ # Invalid code 02 should fall back
+ self.assertEqual(kenwood_live._thg71_code_to_tone("02"), 88.5)
+
+ # Test tone to code conversion
+ self.assertEqual(kenwood_live._thg71_tone_to_code(67.0), "01")
+ self.assertEqual(kenwood_live._thg71_tone_to_code(71.9), "03")
+ self.assertEqual(kenwood_live._thg71_tone_to_code(88.5), "09")
+ self.assertEqual(kenwood_live._thg71_tone_to_code(162.2), "27")
+ self.assertEqual(kenwood_live._thg71_tone_to_code(250.3), "39")
+ self.assertEqual(kenwood_live._thg71_tone_to_code(69.3), "09")
+
+ def test_parse_mr_spec(self):
+ # MR 0,0,000,00146980000,0,2,0,1,0,,27,,09,000600000,0
+ spec = ["0", "0", "000", "00146980000", "0", "2", "0", "1", "0", "",
+ "27", "", "09", "000600000", "0"]
+ mem = self.radio._parse_mem_spec(spec)
+ self.assertEqual(mem.number, 0)
+ self.assertEqual(mem.freq, 146980000)
+ self.assertEqual(mem.tuning_step, 5.0)
+ self.assertEqual(mem.duplex, "-")
+ self.assertEqual(mem.tmode, "Tone")
+ self.assertEqual(mem.rtone, 162.2)
+ self.assertEqual(mem.ctone, 88.5)
+ self.assertEqual(mem.offset, 600000)
+ self.assertEqual(mem.skip, "")
+
+ def test_parse_mr_spec_with_skip(self):
+ # MR 0,0,005,00146520000,0,0,0,0,0,,09,,09,000000000,1
+ spec = ["0", "0", "005", "00146520000", "0", "0", "0", "0", "0", "",
+ "09", "", "09", "000000000", "1"]
+ mem = self.radio._parse_mem_spec(spec)
+ self.assertEqual(mem.number, 5)
+ self.assertEqual(mem.freq, 146520000)
+ self.assertEqual(mem.duplex, "")
+ self.assertEqual(mem.skip, "S")
+
+ def test_parse_call_spec(self):
+ # CR 1,0,00446000000,6,0,0,0,0,,09,,09,005000000
+ spec = ["1", "0", "00446000000", "6", "0", "0", "0", "0", "",
+ "09", "", "09", "005000000"]
+ mem = self.radio._parse_call_spec(1, spec)
+ self.assertEqual(mem.extd_number, "CALL-U")
+ self.assertEqual(mem.freq, 446000000)
+ self.assertEqual(mem.tuning_step, 25.0)
+ self.assertEqual(mem.duplex, "")
+ self.assertEqual(mem.offset, 5000000)
+
+ def test_make_mr_spec(self):
+ mem = chirp_common.Memory()
+ mem.number = 0
+ mem.freq = 146980000
+ mem.tuning_step = 5.0
+ mem.duplex = "-"
+ mem.tmode = "Tone"
+ mem.rtone = 162.2
+ mem.ctone = 88.5
+ mem.offset = 600000
+ mem.skip = ""
+
+ spec = self.radio._make_mem_spec(mem)
+ spec_str = ",".join(spec)
+ self.assertEqual(
+ spec_str,
+ "00146980000,0,2,0,1,0,,27,,09,000600000,0"
+ )
+
+ def test_make_split_spec(self):
+ mem = chirp_common.Memory()
+ mem.number = 0
+ mem.freq = 146400000
+ mem.tuning_step = 25.0
+ mem.duplex = "split"
+ mem.offset = 445000000
+
+ split_spec = self.radio._make_split_spec(mem)
+ self.assertEqual(split_spec, ("00445000000", "6"))
+
+ def test_unsupported_tone(self):
+ mem = chirp_common.Memory()
+ mem.number = 1
+ mem.freq = 146520000
+ mem.tmode = "Tone"
+ mem.rtone = 69.3
+ with self.assertRaises(errors.UnsupportedToneError):
+ self.radio.set_memory(mem)
+
+ mem.tmode = "TSQL"
+ mem.rtone = 88.5
+ mem.ctone = 69.3
+ with self.assertRaises(errors.UnsupportedToneError):
+ self.radio.set_memory(mem)
+
+ def test_mock_get_memory_regular_and_split(self):
+ def fake_command(ser, cmd, *args):
+ if cmd == "MR" and args[0] == "0,0,000":
+ # Split RX
+ return "MR 0,0,000,00146400000,0,0,0,0,0,,27,,09,,0"
+ elif cmd == "MR" and args[0] == "0,1,000":
+ # Split TX
+ return "MR 0,1,000,00445000000,6"
+ elif cmd == "MNA" and args[0] == "0,000":
+ return "MNA 0,000,SPLIT1"
+ elif cmd == "MR" and args[0] == "0,0,001":
+ return "MR 0,0,001,00146980000,0,2,0,1,0,,27,,09,000600000,0"
+ elif cmd == "MR" and args[0] == "0,1,001":
+ return "N"
+ elif cmd == "MNA" and args[0] == "0,001":
+ return "MNA 0,001,RPT1"
+ elif cmd == "MR" and args[0] == "0,0,002":
+ return "N"
+ return "?"
+
+ self.radio.command = fake_command
+
+ # Test split channel 0
+ mem0 = self.radio.get_memory(0)
+ self.assertEqual(mem0.number, 0)
+ self.assertEqual(mem0.freq, 146400000)
+ self.assertEqual(mem0.duplex, "split")
+ self.assertEqual(mem0.offset, 445000000)
+ self.assertEqual(mem0.name, "SPLIT1")
+
+ # Test regular channel 1
+ mem1 = self.radio.get_memory(1)
+ self.assertEqual(mem1.number, 1)
+ self.assertEqual(mem1.freq, 146980000)
+ self.assertEqual(mem1.duplex, "-")
+ self.assertEqual(mem1.offset, 600000)
+ self.assertEqual(mem1.tmode, "Tone")
+ self.assertEqual(mem1.rtone, 162.2)
+ self.assertEqual(mem1.name, "RPT1")
+
+ # Test empty channel 2
+ mem2 = self.radio.get_memory(2)
+ self.assertTrue(mem2.empty)
+
+ def test_mock_get_and_set_call_channel(self):
+ sent_commands = []
+
+ def fake_command(ser, cmd, *args):
+ sent_commands.append((cmd, args))
+ if cmd == "CR" and args[0] == "0,0":
+ return "CR 0,0,00147405000,0,0,0,0,0,,27,,09,000600000"
+ elif cmd == "CR" and args[0] == "0,1":
+ return "N"
+ elif cmd == "CW":
+ return "CW"
+ return "N"
+
+ self.radio.command = fake_command
+
+ mem = self.radio.get_memory("CALL-V")
+ self.assertEqual(mem.extd_number, "CALL-V")
+ self.assertEqual(mem.freq, 147405000)
+ self.assertEqual(mem.offset, 600000)
+
+ mem.freq = 146520000
+ mem.offset = 0
+ self.radio.set_memory(mem)
+ self.assertIn(("CW", ("0,0,00146520000,0,0,0,0,0,,27,,09,000000000",)),
+ sent_commands)
+
+ def test_mock_get_and_set_settings(self):
+ sent_commands = []
+
+ def fake_command(ser, cmd, *args):
+ sent_commands.append((cmd, args))
+ if cmd == "PC" and args[0] == "0":
+ return "PC 0,2" # Low power VHF
+ elif cmd == "PC" and args[0] == "1":
+ return "PC 1,0" # High power UHF
+ elif cmd == "SQ" and args[0] == "0":
+ return "SQ 0,03"
+ elif cmd == "DM" and args[0] == "00":
+ return "DM 00,E5558881234" # *5558881234
+ elif cmd == "DM":
+ return "DM %s" % args[0]
+ return cmd
+
+ self.radio.command = fake_command
+
+ settings = self.radio.get_settings()
+ self.assertEqual(str(settings["basic"]["pc_vhf"].value), "Low")
+ self.assertEqual(str(settings["basic"]["pc_uhf"].value), "High")
+ self.assertEqual(int(settings["basic"]["squelch"].value), 3)
+ self.assertEqual(str(settings["dtmf"]["dm_00"].value), "*5558881234")
+
+ # Change settings and apply
+ settings["basic"]["pc_vhf"].value = "Economic Low"
+ settings["basic"]["squelch"].value = 5
+ settings["dtmf"]["dm_00"].value = "*123#456"
+ self.radio.set_settings(settings)
+
+ self.assertIn(("PC", ("0,3",)), sent_commands)
+ self.assertIn(("SQ", ("0,05",)), sent_commands)
+ self.assertIn(("DM", ("00,E123F456",)), sent_commands)
diff --git a/tests/unit/test_uvk5_cn.py b/tests/unit/test_uvk5_cn.py
new file mode 100644
index 0000000..e20ebd8
--- /dev/null
+++ b/tests/unit/test_uvk5_cn.py
@@ -0,0 +1,1075 @@
+# Copyright 2026 赵昕 BG8ADW
+#
+# 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/>.
+
+"""Unit tests for the Chinese firmware UV-K5 driver (chirp.drivers.uvk5_cn).
+
+These tests need no radio and no serial port. The image in
+tests/images/Quansheng_UV-K5_losehu.img is a REAL 256 KiB capture from a
+UV-K5 running a LOSEHU131HS build (2026-10-13, Prolific PL2303GS on COM9);
+only the CHIRP metadata trailer was added to it.
+
+The driver uses the gettext builtin ``_``, which the GUI installs and the
+driver test suite sets up in tests/test_drivers.py; do the same here.
+"""
+
+import os
+import struct
+import unittest
+from unittest import mock
+
+from chirp import bitwise, chirp_common, directory, errors, memmap
+from chirp.drivers import uvk5, uvk5_cn
+
+__builtins__['_'] = lambda s: s
+
+IMAGES = os.path.join(os.path.dirname(__file__), '..', 'images')
+IMAGE = os.path.join(IMAGES, 'Quansheng_UV-K5_losehu.img')
+OEM_IMAGE = os.path.join(IMAGES, 'Quansheng_UV-K5.img')
+
+# The real radio this image came from
+FIRMWARE = 'LOSEHU131HS'
+EEPROM_SIZE = 0x40000
+# First unused channel in the capture (its record and name slot are all 0xFF)
+FIRST_EMPTY = 98
+# Channel 1 of the capture: GB2312 "private frequency", 435.5875 MHz simplex
+CH1_NAME = '\u79c1\u6709\u9891\u70b9'
+CH1_FREQ = 435587500
+
+
+class FakeSerial:
+ """Minimal clone of the serial object the framing layer needs."""
+
+ def __init__(self, response=b'', fail_after=None):
+ self.written = []
+ self.buffer = bytearray(response)
+ self.timeout = None
+ self.fail_after = fail_after
+ self.reads = 0
+
+ def log(self, message):
+ pass
+
+ def write(self, data):
+ if not isinstance(data, bytes):
+ raise TypeError('driver wrote non-bytes to the serial port')
+ self.written.append(data)
+
+ def read(self, size=None):
+ self.reads += 1
+ if self.fail_after is not None and self.reads > self.fail_after:
+ raise errors.RadioError('fake serial stopped answering')
+ data = bytes(self.buffer[:size])
+ del self.buffer[:size]
+ return data
+
+
+def make_reply(payload):
+ """Wrap @payload in the radio's reply frame."""
+ # _receive_reply() does not verify the CRC that follows the payload
+ return (b'\xab\xcd' + struct.pack('>BB', len(payload), 0) +
+ uvk5.xorarr(payload + b'\x12\x34') + b'\xdc\xba')
+
+
+def unframe(frame):
+ """Undo the framing of a command the driver sent and return its payload."""
+ assert frame[:2] == b'\xab\xcd', 'bad magic'
+ assert frame[-2:] == b'\xdc\xba', 'bad footer'
+ length = frame[2]
+ body = frame[4:-2]
+ assert len(body) == length + 2, 'bad obfuscated length'
+ return uvk5.xorarr(body)[:length]
+
+
+def padded(data):
+ return bytes(data).ljust(uvk5_cn.NAME_LENGTH, b'\x00')
+
+
+def attr_byte(radio, index):
+ """Recompose the channel attribute byte for @index."""
+ attr = radio._memobj.channel_attributes[index]
+ return ((int(attr.is_scanlist1) << 7) |
+ (int(attr.is_scanlist2) << 6) |
+ (int(attr.compander) << 4) |
+ (int(attr.is_free) << 3) |
+ int(attr.band))
+
+
+def split_msgs(msgs):
+ return chirp_common.split_validation_msgs(msgs)
+
+
+def image_payload(path):
+ with open(path, 'rb') as image_file:
+ data = image_file.read()
+ payload, metadata = chirp_common.CloneModeRadio._strip_metadata(data)
+ return payload, metadata
+
+
+class TestMemFormat(unittest.TestCase):
+ """MEM_FORMAT must be built from the shared definitions, not a copy."""
+
+ def test_built_from_the_base_definitions(self):
+ self.assertTrue(uvk5_cn.MEM_FORMAT.startswith(uvk5.MEM_DEFS))
+ self.assertTrue(uvk5.MEM_FORMAT.startswith(uvk5.MEM_DEFS))
+ # The struct bodies live in exactly one place
+ self.assertEqual(1, uvk5.MEM_DEFS.count('struct memory {'))
+ layout = uvk5_cn.MEM_FORMAT[len(uvk5.MEM_DEFS):]
+ self.assertNotIn('ul32 freq', layout)
+ self.assertIn('struct memory channel[214];', layout)
+ self.assertIn('struct channel_attributes channel_attributes[200];',
+ layout)
+ self.assertIn('struct channelname channelname[200];', layout)
+
+ def test_parses_the_real_image_identically_to_the_base(self):
+ """Our subset must place everything exactly where uvk5 does."""
+ payload, _metadata = image_payload(IMAGE)
+ ours = bitwise.parse(uvk5_cn.MEM_FORMAT,
+ memmap.MemoryMapBytes(payload))
+ base = bitwise.parse(uvk5.MEM_FORMAT,
+ memmap.MemoryMapBytes(payload))
+ for number in range(200):
+ self.assertEqual(bytes(base.channel[number].get_raw()),
+ bytes(ours.channel[number].get_raw()),
+ 'channel record %i' % (number + 1))
+ self.assertEqual(bytes(base.channelname[number].get_raw()),
+ bytes(ours.channelname[number].get_raw()),
+ 'channel name %i' % (number + 1))
+ self.assertEqual(
+ bytes(base.channel_attributes[number].get_raw()),
+ bytes(ours.channel_attributes[number].get_raw()),
+ 'channel attributes %i' % (number + 1))
+
+
+class TestTimestamp(unittest.TestCase):
+ """Every command must carry the hello packet's timestamp.
+
+ The firmware stores the four byte timestamp of the hello command and
+ silently drops any later command that carries a different one - no
+ reply, no error, indistinguishable from a dead radio:
+ ``app/uart.c:243`` stores it, ``app/uart.c:264`` (CMD_051B), ``:298``
+ (CMD_051D), ``:584`` (CMD_052B) and ``:613`` (CMD_0538) all return
+ early on a mismatch.
+ """
+
+ def hello_timestamp(self):
+ """Run the real uvk5._sayhello() and decode what it sent."""
+ payload = bytes([0x15, 0x05, 0x24, 0x00]) + \
+ b'k5_2.01.23\x00' + b'\x00' * 14
+ serport = FakeSerial(make_reply(payload))
+ self.assertEqual('k5_2.01.23', uvk5._sayhello(serport))
+ hello = unframe(serport.written[0])
+ self.assertEqual(b'\x14\x05\x04\x00', hello[:4])
+ return hello[4:8]
+
+ def test_hello_timestamp_matches_our_commands(self):
+ timestamp = self.hello_timestamp()
+ self.assertEqual(timestamp, uvk5_cn.TIMESTAMP)
+ self.assertEqual(timestamp,
+ uvk5_cn.readmem_command(0x2024, 0x80)[8:12])
+ self.assertEqual(timestamp,
+ uvk5_cn.writemem_command(0x2000, b'\x00' * 8)[8:12])
+
+ def test_base_commands_use_the_same_timestamp(self):
+ """The commands inherited from uvk5 must agree as well."""
+ timestamp = self.hello_timestamp()
+ data = bytes(range(8))
+ reply = make_reply(bytes([0x1c, 0x05, 0x0a, 0x00, 0x00, 0x00,
+ 0x08, 0x00]) + data)
+ serport = FakeSerial(reply)
+ self.assertEqual(data, uvk5._readmem(serport, 0x0000, 0x08))
+ self.assertEqual(timestamp, unframe(serport.written[0])[8:12])
+
+ serport = FakeSerial(make_reply(bytes([0x1e, 0x05, 0x00, 0x00,
+ 0x00, 0x00])))
+ self.assertTrue(uvk5._writemem(serport, data, 0x0000))
+ self.assertEqual(timestamp, unframe(serport.written[0])[8:12])
+
+
+class TestCommandSyntax(unittest.TestCase):
+ """Byte exact checks of the command bodies.
+
+ The expected bytes are written out by hand from k5web
+ src/utils/serial.js eeprom_read (line 1458) and eeprom_write (line 1552)
+ and from the firmware's own CMD_0538 (app/uart.c:614-649), so that a
+ change in the driver cannot silently change the protocol.
+ """
+
+ def test_read_command_low_address(self):
+ expected = bytes([
+ 0x2b, 0x05, 0x08, 0x00,
+ 0x00, 0x00, # address bits 16..31
+ 0x80, # size
+ 0x00,
+ ]) + uvk5_cn.TIMESTAMP + bytes([
+ 0x24, 0x20, # address bits 0..15 = 0x2024
+ ])
+ self.assertEqual(expected, uvk5_cn.readmem_command(0x2024, 0x80))
+
+ def test_read_command_high_address(self):
+ expected = bytes([
+ 0x2b, 0x05, 0x08, 0x00,
+ 0x01, 0x00, # address bits 16..31 = 0x0001
+ 0x80,
+ 0x00,
+ ]) + uvk5_cn.TIMESTAMP + bytes([
+ 0xf8, 0xff, # address bits 0..15 = 0xFFF8
+ ])
+ self.assertEqual(expected,
+ uvk5_cn.readmem_command(0x01fff8, 0x80))
+
+ def test_write_command(self):
+ data = bytes(range(0x10))
+ expected = bytes([
+ 0x38, 0x05,
+ 0x1a, 0x00, # header size = 10 + len(data) = 0x1a
+ 0x00, 0x00, # address bits 16..31
+ 0x10 + 2, # size + the two address bytes
+ 0x00,
+ ]) + uvk5_cn.TIMESTAMP + bytes([
+ 0x00, 0x20, # address bits 0..15 = 0x2000
+ ]) + data
+ self.assertEqual(expected, uvk5_cn.writemem_command(0x2000, data))
+
+ def test_write_header_size_matches_the_firmware_formula(self):
+ # app/uart.c:614-649 counts everything after the four byte header:
+ # two high address bytes, size, bAllowPassword, four timestamp
+ # bytes, two low address bytes and the payload
+ for length in (8, 0x10, 0x40, 0x80):
+ command = uvk5_cn.writemem_command(0x1234, b'\x00' * length)
+ self.assertEqual(10 + length,
+ struct.unpack('<H', command[2:4])[0], length)
+ self.assertEqual(length + 2, command[6], length)
+ # payload must be a whole number of the firmware's write units
+ self.assertEqual(0, length % 8, length)
+
+ def test_write_geometry(self):
+ cls = uvk5_cn.UVK5LoseHuRadio
+ self.assertEqual(0x80, cls.MEM_BLOCK) # reply structure limit
+ self.assertEqual(0x40, cls.WRITE_BLOCK) # k5web verified size
+ self.assertEqual(0, cls.WRITE_BLOCK % 8) # firmware write unit
+ self.assertEqual(0, cls.PROG_SIZE % cls.WRITE_BLOCK)
+ self.assertEqual(0x1d00, cls.PROG_SIZE)
+
+ def test_writemem_sends_exactly_that_frame(self):
+ data = bytes(range(0x40))
+ serport = FakeSerial(make_reply(bytes([0x1e, 0x05])))
+ self.assertTrue(uvk5_cn._writemem(serport, data, 0x2000))
+ self.assertEqual(1, len(serport.written))
+ self.assertEqual(uvk5_cn.writemem_command(0x2000, data),
+ unframe(serport.written[0]))
+
+ def test_readmem_sends_exactly_that_frame(self):
+ data = bytes(range(0x80))
+ payload = bytes([0x1c, 0x05, 0x0a, 0x00, 0x24, 0x20, 0x80, 0x00])
+ serport = FakeSerial(make_reply(payload + data))
+ self.assertEqual(data, uvk5_cn._readmem(serport, 0x2024, 0x80))
+ self.assertEqual(1, len(serport.written))
+ self.assertEqual(uvk5_cn.readmem_command(0x2024, 0x80),
+ unframe(serport.written[0]))
+
+ def test_writemem_rejects_bad_reply(self):
+ serport = FakeSerial(make_reply(bytes([0x00, 0x05])))
+ with self.assertRaises(errors.RadioError):
+ uvk5_cn._writemem(serport, b'\x00' * 8, 0x0000)
+
+ def test_readmem_rejects_short_reply(self):
+ serport = FakeSerial(make_reply(bytes([0x1c, 0x05, 0x0a, 0x00])))
+ with self.assertRaises(errors.RadioError):
+ uvk5_cn._readmem(serport, 0x0000, 0x80)
+
+
+class TestNameCodec(unittest.TestCase):
+
+ def test_ascii_round_trip(self):
+ self.assertEqual(padded(b'CALL'), uvk5_cn.encode_name('CALL'))
+ self.assertEqual('CALL', uvk5_cn.decode_name(padded(b'CALL')))
+
+ def test_real_radio_gb2312_name(self):
+ """The name of channel 1 of the real capture."""
+ raw = b'\xcb\xbd\xd3\xd0\xc6\xb5\xb5\xe3' + b'\x00' * 8
+ self.assertEqual(CH1_NAME, uvk5_cn.decode_name(raw))
+ self.assertEqual(raw, uvk5_cn.encode_name(CH1_NAME))
+ self.assertTrue(uvk5_cn.name_fits(CH1_NAME, uvk5_cn.NAME_BYTES))
+
+ def test_gb2312_round_trip(self):
+ name = '\u4e2d\u7ee7' # "repeater"
+ self.assertEqual(padded(b'\xd6\xd0\xbc\xcc'),
+ uvk5_cn.encode_name(name))
+ self.assertEqual(name, uvk5_cn.decode_name(
+ uvk5_cn.encode_name(name)))
+
+ def test_empty_name_all_ff(self):
+ self.assertEqual('', uvk5_cn.decode_name(b'\xff' * 16))
+
+ def test_empty_name_all_nul(self):
+ self.assertEqual('', uvk5_cn.decode_name(b'\x00' * 16))
+ self.assertEqual(padded(b''), uvk5_cn.encode_name(''))
+
+ def test_name_stops_at_ff(self):
+ self.assertEqual('AB', uvk5_cn.decode_name(b'AB' + b'\xff' * 14))
+
+ def test_field_ends_mid_character(self):
+ """The whole name must not be lost when the field is cut short."""
+ raw = b'AB\xd6\xd0\xb9' + b'\x00' * 11
+ self.assertEqual('AB\u4e2d', uvk5_cn.decode_name(raw))
+
+ def test_field_ends_on_dangling_lead_byte(self):
+ raw = b'A' * 15 + b'\xd6'
+ self.assertEqual('A' * 15, uvk5_cn.decode_name(raw))
+
+ def test_dangling_lead_byte_then_ff(self):
+ raw = b'AB\xd6\xff' + b'\x00' * 12
+ self.assertEqual('AB', uvk5_cn.decode_name(raw))
+
+ def test_invalid_gb2312_pair(self):
+ raw = b'A\x80\x40B' + b'\x00' * 12 # 0x80 is not a GB2312 lead
+ self.assertEqual('A?B', uvk5_cn.decode_name(raw))
+
+ def test_name_longer_than_field_is_truncated_on_char_boundary(self):
+ name = '\u4e2d' * 9 # 18 bytes
+ self.assertFalse(uvk5_cn.name_fits(name))
+ encoded = uvk5_cn.encode_name(name, uvk5_cn.NAME_LENGTH)
+ self.assertEqual(16, len(encoded))
+ self.assertEqual('\u4e2d' * 8, uvk5_cn.decode_name(encoded))
+
+ def test_name_is_encoded_within_the_editor_limit(self):
+ # The default limit is the firmware's 13 bytes (font.h:28)
+ self.assertEqual(13, uvk5_cn.NAME_BYTES)
+ self.assertEqual(b'X' * 13 + b'\x00' * 3,
+ uvk5_cn.encode_name('X' * 16))
+ self.assertTrue(uvk5_cn.name_fits('X' * 13, 13))
+ self.assertFalse(uvk5_cn.name_fits('X' * 14, 13))
+ # Five two byte characters fit in 10 bytes, six do not
+ self.assertTrue(uvk5_cn.name_fits('\u4e2d' * 5, 10))
+ self.assertFalse(uvk5_cn.name_fits('\u4e2d' * 6, 10))
+
+ def test_unencodable_character_becomes_question_mark(self):
+ self.assertEqual(padded(b'?'), uvk5_cn.encode_name('\u20ac'))
+
+ def test_gb2312_charset_is_usable(self):
+ charset = uvk5_cn.gb2312_charset()
+ self.assertIn('A', charset)
+ self.assertIn('\u4e2d', charset)
+ self.assertNotIn('\x00', charset)
+
+
+class TestFirmwareProfiles(unittest.TestCase):
+ """The profile table must follow k5web navbar/index.vue:230-254."""
+
+ def test_retained_profiles(self):
+ cases = {
+ 'LOSEHU131HS': 'losehu124h', # the reference radio
+ 'LOSEHU133HS': 'losehu124h',
+ 'LOSEHU133H': 'losehu124h',
+ 'LOSEHU133K': 'losehu120k',
+ 'LOSEHU126K': 'losehu120k',
+ 'LOSEHU126H': 'losehu124h',
+ 'LOSEHU122H': 'losehu118h',
+ 'LOSEHU118K': 'losehu118k',
+ 'LOSEHU118H': 'losehu118h',
+ 'L_BL001': 'losehubl',
+ 'LOSEHUD': 'losehud',
+ 'UVE5-1.2.3': 'losehu124h',
+ }
+ for firmware, profile in cases.items():
+ self.assertEqual(profile, uvk5_cn.cn_profile(firmware), firmware)
+ self.assertTrue(
+ uvk5_cn.UVK5LoseHuRadio.k5_approve_firmware(firmware),
+ firmware)
+
+ def test_deferred_builds_are_not_claimed(self):
+ """The other code paths are deliberately left to the follow-up PR.
+
+ The stock-command builds (losehu117/118/lts), the font-mapped ones
+ (losehu117k/ltsk) and the LTS sub-font builds each take a path that
+ no capture here exercises, so they must come up as the read-only
+ fallback rather than be driven on a guess.
+ """
+ for firmware in ('LOSEHU116', 'LOSEHU117P6', 'LOSEHU118',
+ 'LOSEHU133', 'LOSEHU116K', 'LOSEHU117K',
+ 'LOSEHU117P6K', 'LOSEHU13PK', 'font1', 'font2',
+ 'font3', 'LOSEHU140'):
+ self.assertEqual('todo', uvk5_cn.cn_profile(firmware), firmware)
+ self.assertFalse(
+ uvk5_cn.UVK5LoseHuRadio.k5_approve_firmware(firmware),
+ firmware)
+
+ def test_oem_and_foreign_firmware_are_not_claimed(self):
+ for firmware in ('k5_2.01.26', 'app_2.01.17', 'EGZUMER v1',
+ '7.03.01', '1o11', '*OEFW-LOSEHU', 'OSFW-bd90ca3'):
+ self.assertFalse(
+ uvk5_cn.UVK5LoseHuRadio.k5_approve_firmware(firmware),
+ firmware)
+
+ def test_oefw_flash_header_is_never_approved(self):
+ """0x2000 holds '*OEFW-<author>' (fw-pack.py:28); it is not the
+ version string and must never be allowlisted."""
+ for firmware in ('*OEFW-LOSEHU', '*OEFW-'):
+ self.assertFalse(uvk5.UVK5Radio.k5_approve_firmware(firmware))
+ self.assertEqual('todo', uvk5_cn.cn_profile(firmware))
+
+ def test_k1_goes_to_the_upstream_uvk1_driver(self):
+ self.assertEqual('k1', uvk5_cn.cn_profile('7.03.01'))
+ self.assertTrue(uvk5.UVK1Radio.k5_approve_firmware('7.03.01'))
+
+ def test_eeprom_size_from_profile(self):
+ # A live scan of the reference radio shows user data ending before
+ # 0x40000 with the multi-bootloader starting there, so every claimed
+ # profile defaults to 0x40000.
+ for firmware in (FIRMWARE, 'LOSEHU133HS', 'LOSEHU126K', 'LOSEHU118H',
+ 'LOSEHU118K', 'LOSEHUD', 'L_BL001', 'UVE5'):
+ self.assertEqual(0x40000, uvk5_cn.profile_mem_size(firmware),
+ firmware)
+ # Anything not claimed keeps the smallest image
+ self.assertEqual(0x2000, uvk5_cn.profile_mem_size('LOSEHU116'))
+ self.assertEqual(0x2000, uvk5_cn.profile_mem_size('unknown'))
+
+ def test_data_limit_is_the_bootloader_boundary(self):
+ self.assertEqual(0x40000, uvk5_cn.DATA_LIMIT)
+ self.assertLess(uvk5_cn.UVK5LoseHuRadio.PROG_SIZE,
+ uvk5_cn.DATA_LIMIT)
+
+
+class TestDetection(unittest.TestCase):
+ """Serial detection must pick the right class, and fall back safely."""
+
+ def _detect(self, firmware):
+ with mock.patch.object(uvk5, '_sayhello', return_value=firmware):
+ return uvk5.UVK5Radio.detect_from_serial(object())
+
+ def test_claimed_firmware_uses_our_class(self):
+ for firmware in ('LOSEHU131HS', 'LOSEHU133K', 'LOSEHU126H',
+ 'LOSEHU118K', 'LOSEHUD', 'L_BL001', 'UVE5'):
+ self.assertIs(uvk5_cn.UVK5LoseHuRadio, self._detect(firmware),
+ firmware)
+
+ def test_deferred_and_unknown_firmware_is_read_only(self):
+ for firmware in ('LOSEHU116', 'LOSEHU117P6K', 'LOSEHU133',
+ 'some new firmware'):
+ self.assertIs(uvk5.UVK5RestrictedRadio, self._detect(firmware),
+ firmware)
+
+ def test_oem_firmware_still_uses_the_stock_driver(self):
+ with mock.patch.object(uvk5, '_sayhello',
+ return_value='k5_2.01.23'):
+ self.assertIs(uvk5.UVK5Radio,
+ uvk5.UVK5Radio.detect_from_serial(object()))
+
+ def test_registry_lookup(self):
+ self.assertIs(uvk5_cn.UVK5LoseHuRadio,
+ directory.get_radio('Quansheng_UV-K5_losehu'))
+ self.assertIs(uvk5.UVK5Radio,
+ directory.get_radio('Quansheng_UV-K5'))
+
+ def test_class_does_not_own_detected_models(self):
+ """tests/test_clone.py requires detect_from_serial() to be usable."""
+ cls = uvk5_cn.UVK5LoseHuRadio
+ self.assertFalse(hasattr(cls, 'DETECTED_MODELS_%s' % cls.__name__))
+ with self.assertRaises(NotImplementedError):
+ cls.detect_from_serial(object())
+
+
+class TestPrompts(unittest.TestCase):
+
+ def test_prompts(self):
+ prompts = uvk5_cn.UVK5LoseHuRadio.get_prompts()
+ for name in ('experimental', 'pre_download', 'pre_upload'):
+ self.assertIsInstance(getattr(prompts, name), str)
+ text = prompts.experimental
+ # The verification status and the dangerous region must be stated
+ self.assertIn('LOSEHU131HS', text)
+ self.assertIn('verified', text)
+ self.assertIn('0x40000', text)
+ self.assertIn('multi-bootloader', text)
+ # ... and it must not claim to be untested
+ self.assertNotIn('not been tested', text)
+
+ def test_prompts_available_on_the_class_and_an_instance(self):
+ self.assertIsInstance(uvk5_cn.UVK5LoseHuRadio.get_prompts(),
+ chirp_common.RadioPrompts)
+ radio = uvk5_cn.UVK5LoseHuRadio(None)
+ self.assertIsInstance(radio.get_prompts(),
+ chirp_common.RadioPrompts)
+
+
+class TestRealImage(unittest.TestCase):
+ """Exercise the driver against the real LOSEHU131HS capture."""
+
+ def setUp(self):
+ self.radio = directory.get_radio_by_image(IMAGE)
+ self.radio.status_fn = lambda status: True
+
+ def test_detected_as_losehu_variant(self):
+ self.assertIsInstance(self.radio, uvk5_cn.UVK5LoseHuRadio)
+ self.assertEqual('losehu', self.radio.VARIANT)
+
+ def test_image_metadata(self):
+ metadata = self.radio.metadata
+ self.assertEqual(FIRMWARE, metadata['uvk5_firmware'])
+ self.assertIn('REAL capture', metadata['image_note'])
+ self.assertEqual('Quansheng', metadata['vendor'])
+ self.assertEqual('UV-K5', metadata['model'])
+ self.assertEqual('losehu', metadata['variant'])
+
+ def test_eeprom_size_comes_from_the_image(self):
+ self.assertEqual(EEPROM_SIZE, self.radio.eeprom_size)
+ # ... and agrees with what the profile suggests, so a fresh download
+ # from the same radio would read the same amount
+ self.assertEqual(EEPROM_SIZE, uvk5_cn.profile_mem_size(FIRMWARE))
+ self.assertEqual(0x40000, len(self.radio._mmap))
+
+ def test_channel_one_is_the_regression_anchor(self):
+ mem = self.radio.get_memory(1)
+ self.assertFalse(mem.empty)
+ self.assertEqual(CH1_FREQ, mem.freq)
+ self.assertEqual(CH1_NAME, mem.name)
+ self.assertEqual('', mem.duplex) # simplex
+ self.assertEqual(0, mem.offset)
+ self.assertEqual('FM', mem.mode)
+ self.assertEqual('High', str(mem.power))
+ self.assertEqual(2.5, mem.tuning_step)
+
+ def test_other_real_channels(self):
+ mem = self.radio.get_memory(3)
+ self.assertEqual(439587500, mem.freq)
+ self.assertEqual('-', mem.duplex)
+ self.assertEqual(8000000, mem.offset)
+ self.assertEqual('TSQL', mem.tmode)
+
+ mem = self.radio.get_memory(50)
+ self.assertEqual(439925000, mem.freq)
+ self.assertEqual(8012500, mem.offset)
+ self.assertEqual('Tone', mem.tmode)
+ self.assertEqual(71.9, mem.rtone)
+
+ mem = self.radio.get_memory(97)
+ self.assertEqual(132600000, mem.freq)
+ self.assertEqual('Low', str(mem.power))
+ self.assertEqual('\u822a\u7a7a\u9891\u70b9', mem.name)
+
+ def test_band_bytes_match_the_real_image(self):
+ # The capture's attribute area starts 05 05 05 05 05 05 05 02 01
+ for index in range(7):
+ self.assertEqual(0x05, attr_byte(self.radio, index),
+ 'channel %i' % (index + 1))
+ self.assertEqual(0x02, attr_byte(self.radio, 7))
+ self.assertEqual(0x01, attr_byte(self.radio, 8))
+ # Unused channels are marked 0xFF on disk
+ self.assertEqual(0xff, attr_byte(self.radio, FIRST_EMPTY - 1))
+
+ def test_non_empty_and_empty_channels(self):
+ nonempty = [n for n in range(1, 201)
+ if not self.radio.get_memory(n).empty]
+ self.assertEqual(list(range(1, FIRST_EMPTY)), nonempty)
+ self.assertEqual(97, len(nonempty))
+ for number in (FIRST_EMPTY, 150, 200):
+ mem = self.radio.get_memory(number)
+ self.assertTrue(mem.empty, number)
+ self.assertEqual('', mem.name)
+ self.assertEqual(6, len(mem.extra))
+
+ def test_special_channels_are_not_offered(self):
+ rf = self.radio.get_features()
+ self.assertEqual([], rf.valid_special_chans)
+ self.assertEqual((1, 200), rf.memory_bounds)
+ self.assertEqual({}, self.radio._get_specials())
+
+ def test_features(self):
+ rf = self.radio.get_features()
+ self.assertTrue(rf.has_settings)
+ self.assertEqual(13, rf.valid_name_length)
+ self.assertIn('\u4e2d', rf.valid_characters)
+ self.assertEqual(24, len(rf.valid_tuning_steps))
+ self.assertIn(8.33, rf.valid_tuning_steps)
+ self.assertEqual((1, 200), rf.memory_bounds)
+ self.assertEqual(18000000, rf.valid_bands[0][0])
+ self.assertEqual(1300000000, rf.valid_bands[-1][1])
+
+ def test_round_trip_changes_nothing_but_the_invalid_airband_channel(self):
+ """Reading and writing every channel must not change one byte.
+
+ This is the strongest cheap proof that the driver's delta over the
+ base class is a no-op for real data: the channel records, the
+ attributes (including the 0xFF "empty" spelling) and the names.
+
+ Channel 91 is the single exception and only on the first pass: it
+ holds 121.745MHz, which is not an airband channel, so the read path
+ reports the channel that rounds to and writing it back corrects the
+ radio. Nothing else may move, and the correction must be stable.
+ """
+ payload, _metadata = image_payload(IMAGE)
+ self.assertEqual(payload, bytes(self.radio._mmap.get_packed()))
+
+ records = {number:
+ bytes(self.radio._memobj.channel[number - 1].get_raw())
+ for number in range(1, 201)}
+
+ for number in range(1, 201):
+ self.radio.set_memory(self.radio.get_memory(number))
+
+ changed = [number for number in range(1, 201)
+ if bytes(self.radio._memobj.channel[number - 1].get_raw())
+ != records[number]]
+ self.assertEqual([91], changed)
+
+ corrected = bytes(self.radio._mmap.get_packed())
+ differing = [index for index in range(len(payload))
+ if payload[index] != corrected[index]]
+ self.assertTrue(differing)
+ self.assertLessEqual(len(differing), 4,
+ 'more than one frequency field changed')
+
+ # The correction is stable: a second pass changes nothing
+ for number in range(1, 201):
+ self.radio.set_memory(self.radio.get_memory(number))
+ self.assertEqual(corrected, bytes(self.radio._mmap.get_packed()))
+
+ def test_long_name_round_trips_without_being_shortened(self):
+ mem = self.radio.get_memory(19)
+ self.assertEqual('\u5e94\u6025\u901a\u4fe1\u7fbd\u6797\u5927\u961f',
+ mem.name)
+ self.radio.set_memory(mem)
+ self.assertEqual(mem.name, self.radio.get_memory(19).name)
+ raw = bytes(self.radio._memobj.channelname[18].get_raw())
+ self.assertEqual(16, len(raw.rstrip(b'\x00')))
+
+ def test_unrepresentable_name_bytes_are_preserved(self):
+ """Name bytes we cannot reproduce must not be rewritten."""
+ field = self.radio._memobj.channelname[0] # real channel 1
+ raw = b'A\x80\x40B' + b'\x00' * 12
+ field.set_raw(raw)
+
+ mem = self.radio.get_memory(1)
+ self.assertFalse(mem.empty)
+ self.assertEqual('A?B', mem.name)
+ mem.freq = 145500000 # change something else entirely
+ self.radio.set_memory(mem)
+ self.assertEqual(raw, bytes(field.get_raw()))
+
+ # Bytes after the terminator are just as protected
+ trailing = b'AB' + b'\x00' + b'\xd6\xd0' + b'\x00' * 11
+ field.set_raw(trailing)
+ mem = self.radio.get_memory(1)
+ self.assertEqual('AB', mem.name)
+ mem.freq = 145500000
+ self.radio.set_memory(mem)
+ self.assertEqual(trailing, bytes(field.get_raw()))
+
+ # But when the user really changes the name, it is written
+ mem.name = 'NEW'
+ self.radio.set_memory(mem)
+ self.assertEqual(uvk5_cn.encode_name('NEW'), bytes(field.get_raw()))
+
+ def test_set_memory_round_trip_gb2312(self):
+ number = FIRST_EMPTY
+ mem = self.radio.get_memory(number)
+ mem.empty = False
+ mem.freq = 439000000
+ mem.name = '\u4e2d\u7ee7\u53f0'
+ self.radio.set_memory(mem)
+ new = self.radio.get_memory(number)
+ self.assertFalse(new.empty)
+ self.assertEqual(439000000, new.freq)
+ self.assertEqual('\u4e2d\u7ee7\u53f0', new.name)
+ raw = self.radio._memobj.channelname[number - 1].get_raw()
+ self.assertEqual('\u4e2d\u7ee7\u53f0'.encode('gb2312'),
+ bytes(raw[:6]))
+ self.assertEqual(b'\x00' * 10, bytes(raw[6:]))
+
+ def test_set_memory_round_trip_ascii(self):
+ number = FIRST_EMPTY + 1
+ mem = self.radio.get_memory(number)
+ mem.empty = False
+ mem.freq = 435000000
+ mem.name = 'TEST'
+ self.radio.set_memory(mem)
+ new = self.radio.get_memory(number)
+ self.assertEqual(435000000, new.freq)
+ self.assertEqual('TEST', new.name)
+
+ def test_delete_and_rewrite(self):
+ number = FIRST_EMPTY + 2
+ mem = self.radio.get_memory(number)
+ mem.empty = False
+ mem.freq = 145500000
+ mem.name = 'GONE'
+ self.radio.set_memory(mem)
+ self.assertFalse(self.radio.get_memory(number).empty)
+
+ mem.empty = True
+ self.radio.set_memory(mem)
+ self.assertTrue(self.radio.get_memory(number).empty)
+ self.assertEqual(b'\xff' * 16,
+ bytes(self.radio._memobj.channel[number - 1]
+ .get_raw()))
+
+ def test_already_empty_channel_is_left_alone(self):
+ """An untouched empty channel keeps its 0xFF spelling."""
+ index = FIRST_EMPTY - 1
+ before = bytes(self.radio._memobj.channel_attributes[index].get_raw())
+ self.radio.set_memory(self.radio.get_memory(FIRST_EMPTY))
+ self.assertEqual(
+ before,
+ bytes(self.radio._memobj.channel_attributes[index].get_raw()))
+
+ def test_tuning_step_round_trip_for_every_offered_step(self):
+ number = FIRST_EMPTY + 3
+ mem = self.radio.get_memory(number)
+ mem.empty = False
+ mem.freq = 145000000
+ for step in self.radio.get_features().valid_tuning_steps:
+ mem.tuning_step = step
+ self.radio.set_memory(mem)
+ self.assertEqual(step, self.radio.get_memory(number).tuning_step)
+
+ def test_set_memory_does_not_modify_input(self):
+ mem = chirp_common.FrozenMemory(self.radio.get_memory(1))
+ self.radio.set_memory(mem) # must not raise
+ self.assertEqual(CH1_NAME, self.radio.get_memory(1).name)
+
+ def test_get_memory_has_no_trailing_whitespace(self):
+ number = FIRST_EMPTY + 4
+ mem = self.radio.get_memory(number)
+ mem.empty = False
+ mem.freq = 145000000
+ mem.name = 'PAD '
+ self.radio.set_memory(mem)
+ self.assertEqual('PAD', self.radio.get_memory(number).name)
+
+ def test_validate_memory_accepts_every_real_channel(self):
+ """No channel of the capture may produce a message of any kind.
+
+ CHIRP's sample image test asserts that validate_memory() is clean for
+ every channel of the image. Channel 91 of this capture holds
+ 121.745MHz, which is not an airband channel at all - it sits in the gap
+ between the 25 kHz channels - even though the radio stored it. The
+ read path therefore reports the channel that value rounds to, and this
+ checks that the result validates.
+ """
+ warnings = 0
+ errors_seen = []
+ for number in range(1, 201):
+ mem = self.radio.get_memory(number)
+ if mem.empty:
+ continue
+ warns, errs = split_msgs(self.radio.validate_memory(mem))
+ warnings += len(warns)
+ if errs:
+ errors_seen.append((number, str(errs[0])))
+
+ self.assertEqual(0, warnings)
+ self.assertEqual([], errors_seen)
+
+ # The gap frequency is reported as the channel it rounds to, and that
+ # channel must satisfy CHIRP's airband policy
+ airband = self.radio.get_memory(91)
+ self.assertNotEqual(121745000, airband.freq)
+ chirp_common.fix_rounded_step(airband.freq)
+
+ def test_validate_memory_rejects_name_wider_than_the_field(self):
+ mem = self.radio.get_memory(1)
+ mem.name = '\u4e2d' * 9 # 18 bytes > 16
+ warns, errs = split_msgs(self.radio.validate_memory(mem))
+ self.assertEqual(1, len(errs))
+ self.assertIn('16 bytes', str(errs[0]))
+
+ def test_validate_memory_is_silent_about_the_editor_limit(self):
+ """A name past the radio's editor limit but inside the field is
+ accepted without a message: the field holds it and this driver keeps
+ it byte for byte."""
+ mem = self.radio.get_memory(1)
+ mem.name = '\u4e2d' * 7 # 14 bytes: field ok
+ self.assertFalse(uvk5_cn.name_fits(mem.name, uvk5_cn.NAME_BYTES))
+ self.assertTrue(uvk5_cn.name_fits(mem.name, uvk5_cn.NAME_LENGTH))
+ warns, errs = split_msgs(self.radio.validate_memory(mem))
+ self.assertEqual([], warns)
+ self.assertEqual([], errs)
+
+ def test_settings_round_trip(self):
+ settings = self.radio.get_settings()
+ before = {}
+ for group in settings:
+ for setting in group:
+ before[setting.get_name()] = setting.value.get_value()
+ self.assertEqual(FIRMWARE, before['fw_ver'])
+ self.assertEqual('0x40000 (256 KiB)', before['eeprom_size'])
+ self.assertTrue(before['nolimits'])
+
+ self.radio.set_settings(settings)
+
+ after = {}
+ for group in self.radio.get_settings():
+ for setting in group:
+ after[setting.get_name()] = setting.value.get_value()
+ self.assertEqual(before, after)
+
+ def test_eeprom_size_setting(self):
+ self.assertEqual(0x40000, self.radio.eeprom_size)
+ settings = self.radio.get_settings()
+ for group in settings:
+ for setting in group:
+ if setting.get_name() == 'eeprom_size':
+ setting.value.set_value('0x10000 (64 KiB)')
+ self.radio.set_settings(settings)
+ self.assertEqual(0x10000, self.radio.eeprom_size)
+
+ def test_bitwise_parses_the_image_without_errors(self):
+ with mock.patch.object(bitwise.LOG, 'error') as mock_error:
+ self.radio.process_mmap()
+ self.assertFalse(mock_error.called,
+ [x[0][0] for x in mock_error.call_args_list])
+
+ def test_a_corrupt_tone_nibble_does_not_crash_get_memory(self):
+ """uvk5's _get_tone indexes TMODES with the raw nibble.
+
+ Radios only write tone types 0..3 (dcs.h:22-30), but a partially
+ written record can hold 0xFF there, which would raise IndexError
+ while loading an image.
+ """
+ image = bytearray(b'\xFF' * 0x2000)
+ image[0x00:0x04] = struct.pack('<L', 435587500 // 10)
+ image[0x0d60] = 0x05
+ radio = uvk5_cn.UVK5LoseHuRadio(None)
+ radio.metadata = {'uvk5_firmware': FIRMWARE}
+ radio._mmap = memmap.MemoryMapBytes(bytes(image))
+ radio._eeprom_size = 0x2000
+ radio.process_mmap()
+ mem = radio.get_memory(1) # must not raise
+ self.assertFalse(mem.empty)
+ self.assertEqual('', mem.tmode)
+ self.assertEqual(435587500, mem.freq)
+
+
+class TestWriteSafety(unittest.TestCase):
+ """Nothing at or above DATA_LIMIT may ever be written.
+
+ 0x040000-0x07FFFF holds the multi-bootloader on these builds ("_BL002"
+ at 0x40008); a stray write there can leave the radio unbootable in a way
+ CHIRP cannot repair.
+ """
+
+ def test_writemem_refuses_the_bootloader_region(self):
+ serport = FakeSerial(make_reply(bytes([0x1e, 0x05])))
+ with self.assertRaises(errors.RadioError) as caught:
+ uvk5_cn._writemem(serport, b'\x00' * 16, 0x40000)
+ message = str(caught.exception)
+ self.assertIn('0x40000', message)
+ self.assertIn('multi-bootloader', message)
+ self.assertEqual([], serport.written)
+
+ def test_writemem_refuses_a_block_that_crosses_the_limit(self):
+ serport = FakeSerial(make_reply(bytes([0x1e, 0x05])))
+ with self.assertRaises(errors.RadioError):
+ uvk5_cn._writemem(serport, b'\x00' * 0x40, 0x3ffd0)
+ self.assertEqual([], serport.written)
+
+ def test_writemem_allows_the_last_block_below_the_limit(self):
+ serport = FakeSerial(make_reply(bytes([0x1e, 0x05])))
+ self.assertTrue(uvk5_cn._writemem(serport, b'\x00' * 0x40, 0x3ffc0))
+
+ def test_readmem_refuses_the_bootloader_region(self):
+ serport = FakeSerial()
+ with self.assertRaises(errors.RadioError):
+ uvk5_cn._readmem(serport, 0x40000, 0x80)
+ self.assertEqual([], serport.written)
+
+ def test_upload_refuses_an_image_that_reaches_the_bootloader(self):
+ radio = uvk5_cn.UVK5LoseHuRadio(None)
+ radio.status_fn = lambda status: True
+ radio.pipe = FakeSerial()
+ radio._mmap = memmap.MemoryMapBytes(bytes(0x80000))
+ radio._eeprom_size = 0x2000 # so the *image* length trips the guard
+ with mock.patch.object(uvk5, '_sayhello', return_value=FIRMWARE):
+ with self.assertRaises(errors.RadioError) as caught:
+ uvk5.do_upload(radio)
+ message = str(caught.exception)
+ self.assertIn('524288', message)
+ self.assertIn('0x40000', message)
+ self.assertIn('multi-bootloader', message)
+
+ def test_upload_refuses_a_size_past_the_limit(self):
+ radio = uvk5_cn.UVK5LoseHuRadio(None)
+ radio.status_fn = lambda status: True
+ radio.pipe = FakeSerial()
+ radio._mmap = memmap.MemoryMapBytes(bytes(0x2000))
+ radio._eeprom_size = 0x80000
+ with mock.patch.object(uvk5, '_sayhello', return_value=FIRMWARE):
+ with self.assertRaises(errors.RadioError) as caught:
+ uvk5.do_upload(radio)
+ self.assertIn('0x40000', str(caught.exception))
+
+ def test_download_refuses_a_size_past_the_limit(self):
+ radio = uvk5_cn.UVK5LoseHuRadio(None)
+ radio.status_fn = lambda status: True
+ radio.pipe = FakeSerial()
+ radio._eeprom_size = 0x80000
+ with mock.patch.object(uvk5, '_sayhello', return_value=FIRMWARE):
+ with self.assertRaises(errors.RadioError) as caught:
+ uvk5.do_download(radio)
+ self.assertIn('0x40000', str(caught.exception))
+
+ def test_real_image_is_inside_the_limit(self):
+ payload, metadata = image_payload(IMAGE)
+ self.assertEqual(0x40000, len(payload))
+ self.assertLessEqual(len(payload), uvk5_cn.DATA_LIMIT)
+ self.assertEqual(FIRMWARE, metadata['uvk5_firmware'])
+
+
+class TestOemNamePath(unittest.TestCase):
+ """The byte-native name handling in the base class must not change the
+ bytes the OEM driver writes."""
+
+ def test_oem_image_name_round_trip_is_byte_identical(self):
+ radio = directory.get_radio_by_image(OEM_IMAGE)
+ before = bytes(radio._mmap.get_packed())
+ names = {}
+ for number in range(1, 201):
+ mem = radio.get_memory(number)
+ if mem.empty:
+ continue
+ names[number] = bytes(radio._memobj.channelname[number - 1]
+ .get_raw())
+ radio.set_memory(mem)
+ after = bytes(radio._mmap.get_packed())
+ for number, raw in names.items():
+ self.assertEqual(raw, bytes(radio._memobj.channelname[number - 1]
+ .get_raw()), 'name %i' % number)
+ diffs = [i for i in range(len(before)) if before[i] != after[i]]
+ self.assertEqual([], diffs)
+
+ def test_oem_name_read_stops_at_nul_and_ff(self):
+ radio = directory.get_radio_by_image(OEM_IMAGE)
+ field = radio._memobj.channelname[0]
+ field.set_raw(b'AB' + b'\x00' * 14)
+ self.assertEqual('AB', radio.get_memory(1).name)
+ field.set_raw(b'CD' + b'\xff' * 14)
+ self.assertEqual('CD', radio.get_memory(1).name)
+
+ def test_oem_name_write_is_space_padded(self):
+ radio = directory.get_radio_by_image(OEM_IMAGE)
+ mem = radio.get_memory(1)
+ mem.name = 'XYZ'
+ radio.set_memory(mem)
+ self.assertEqual(b'XYZ' + b' ' * 7 + b'\x00' * 6,
+ bytes(radio._memobj.channelname[0].get_raw()))
+
+
+@unittest.skipIf(not os.path.exists(IMAGE), 'test image missing')
+class TestCloneWithFakeSerial(unittest.TestCase):
+ """Download and upload over a fake serial port."""
+
+ READ_DATA = bytes(range(0x80))
+
+ def setUp(self):
+ self.radio = uvk5_cn.UVK5LoseHuRadio(None)
+ self.radio.status_fn = lambda status: True
+
+ def _read_reply(self, data):
+ payload = bytes([0x1c, 0x05, 0x0a, 0x00, 0x00, 0x00,
+ len(data), 0x00]) + data
+ return make_reply(payload)
+
+ def _download(self, response=b'', fail_after=None, size=None):
+ serport = FakeSerial(response, fail_after=fail_after)
+ self.radio.pipe = serport
+ if size is not None:
+ self.radio._eeprom_size = size
+ with mock.patch.object(uvk5, '_sayhello', return_value=FIRMWARE):
+ mmap = uvk5.do_download(self.radio)
+ return serport, mmap
+
+ def test_download_reads_the_requested_size(self):
+ size = 0x2000
+ response = self._read_reply(self.READ_DATA) * (size // 0x80)
+ serport, mmap = self._download(response, size=size)
+ self.assertEqual(size, len(mmap.get_packed()))
+ self.assertEqual(size // 0x80, len(serport.written))
+ for index, frame in enumerate(serport.written):
+ payload = unframe(frame)
+ self.assertEqual(0x2b, payload[0])
+ self.assertEqual(uvk5_cn.TIMESTAMP, payload[8:12])
+ self.assertEqual(struct.pack('<H', (index * 0x80) & 0xffff),
+ payload[12:14])
+ self.assertEqual(FIRMWARE, self.radio.metadata['uvk5_firmware'])
+ self.assertEqual(self.READ_DATA * (size // 0x80), mmap.get_packed())
+
+ def test_download_raises_when_profile_over_estimates(self):
+ # A profile that over-estimates the EEPROM must fail loudly rather
+ # than hand the user a short image that they might upload back
+ response = self._read_reply(self.READ_DATA) * 64 # exactly 0x2000
+ with self.assertRaises(errors.RadioError):
+ self._download(response)
+
+ def test_download_fails_if_no_usable_image(self):
+ with self.assertRaises(errors.RadioError):
+ self._download(b'', fail_after=0, size=0x2000)
+
+ def test_download_rejects_unsupported_firmware(self):
+ self.radio.pipe = FakeSerial()
+ with mock.patch.object(uvk5, '_sayhello', return_value='BOGUS'):
+ with self.assertRaises(errors.RadioError):
+ uvk5.do_download(self.radio)
+
+ def test_upload_writes_prog_size_and_resets(self):
+ self.radio._mmap = memmap.MemoryMapBytes(bytes(range(0x100)) * 0x20)
+ self.radio._eeprom_size = 0x2000
+ nwrites = 0x1d00 // 0x40
+ serport = FakeSerial(make_reply(bytes([0x1e, 0x05])) * nwrites)
+ self.radio.pipe = serport
+ with mock.patch.object(uvk5, '_sayhello', return_value=FIRMWARE):
+ self.assertTrue(uvk5.do_upload(self.radio))
+ self.assertEqual(nwrites + 1, len(serport.written))
+ for index, frame in enumerate(serport.written[:-1]):
+ payload = unframe(frame)
+ self.assertEqual(0x38, payload[0])
+ self.assertEqual(10 + 0x40,
+ struct.unpack('<H', payload[2:4])[0])
+ self.assertEqual(0x40 + 2, payload[6])
+ self.assertEqual(uvk5_cn.TIMESTAMP, payload[8:12])
+ self.assertEqual(struct.pack('<H', (index * 0x40) & 0xffff),
+ payload[12:14])
+ self.assertEqual(0x40, len(payload) - 14)
+ self.assertEqual(b'\xdd\x05\x00\x00',
+ unframe(serport.written[-1]))
+
+ def test_upload_refuses_mismatched_image(self):
+ self.radio._mmap = memmap.MemoryMapBytes(bytes(0x2000))
+ self.radio._eeprom_size = 0x40000
+ self.radio.pipe = FakeSerial(make_reply(bytes([0x1e, 0x05])))
+ with mock.patch.object(uvk5, '_sayhello', return_value=FIRMWARE):
+ with self.assertRaises(errors.RadioError) as caught:
+ uvk5.do_upload(self.radio)
+ message = str(caught.exception)
+ self.assertIn('8192', message) # loaded image length
+ self.assertIn('todo', message) # its profile
+ self.assertIn('losehu124h', message) # radio profile
+ self.assertIn('262144', message) # profile default
+ self.assertIn('EEPROM size', message)
+
+ def test_upload_rejects_unsupported_firmware(self):
+ self.radio._mmap = memmap.MemoryMapBytes(bytes(0x2000))
+ self.radio.pipe = FakeSerial()
+ with mock.patch.object(uvk5, '_sayhello', return_value='BOGUS'):
+ with self.assertRaises(errors.RadioError):
+ uvk5.do_upload(self.radio)
+
+ def test_sync_in_with_silent_serial_raises_radio_error(self):
+ self.radio.pipe = FakeSerial()
+ with self.assertRaises(errors.RadioError):
+ self.radio.sync_in()
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/tests/unit/test_vx8.py b/tests/unit/test_vx8.py
new file mode 100644
index 0000000..3c5a713
--- /dev/null
+++ b/tests/unit/test_vx8.py
@@ -0,0 +1,69 @@
+from pathlib import Path
+import unittest
+
+from chirp import memmap
+from chirp.drivers import vx8
+
+
+FIXTURE = Path(__file__).parents[1] / 'images' / 'Yaesu_VX-8GE.img'
+
+FLAG_BASE = 0x2C4A
+MEMORY_BASE = 0x328A
+MEMORY_SIZE = 32
+
+# Values observed in a real-world VX-8GE image for channels programmed
+# from the radio's keypad, which CHIRP could not previously load: the
+# radio's "AUTO" RX mode is stored as mode bits == 3, which is out of
+# range for the driver's MODES list, and a keypad-entered split
+# transmit frequency is rounded to the 1kHz resolution of the offset
+# field, leaving it unaligned to any tuning step.
+FLAG_USED_VALID = 0x03
+MODE_AUTO = 0xC0 # mode (3) | duplex (0) | tune step (0)
+MODE_AUTO_SPLIT = 0xF0 # mode (3) | duplex (3, split) | tune step (0)
+FREQ_4625625 = b'\x46\x25\x62' # 462.5625 MHz, as stored by the radio
+OFFSET_5000K = b'\x00\x50\x00' # 5 MHz
+OFFSET_159007 = b'\x15\x90\x07' # 159.007 MHz, not aligned to any step
+NAME_KEYPAD = b'\x14\x0e\x22\x19\x0a\x0d' # "KEYPAD" in the VX-8 charset
+
+
+class TestVX8(unittest.TestCase):
+ def setUp(self):
+ self.radio = vx8.VX8GERadio(str(FIXTURE))
+ self.data = self.radio.get_mmap().get_packed()
+ self.number = self.radio.get_features().memory_bounds[1]
+
+ def _radio_with_keypad_memory(self, mode_byte, offset_bytes):
+ data = bytearray(self.data)
+ number = self.number
+ data[FLAG_BASE + number - 1] = FLAG_USED_VALID
+ base = MEMORY_BASE + (number - 1) * MEMORY_SIZE
+ data[base] = 0x00
+ data[base + 1] = mode_byte
+ data[base + 2:base + 5] = FREQ_4625625
+ data[base + 5] = 0xC0 # power | tone mode
+ data[base + 6:base + 8] = b'\x00\x00' # charset bits
+ data[base + 8:base + 24] = NAME_KEYPAD + b'\xFF' * 10
+ data[base + 24:base + 27] = offset_bytes
+ data[base + 27:base + 32] = b'\x00\x00\x00\x00\x00'
+ return vx8.VX8GERadio(memmap.MemoryMapBytes(bytes(data)))
+
+ def test_all_memories_load(self):
+ for number in range(*self.radio.get_features().memory_bounds):
+ self.radio.get_memory(number)
+
+ def test_auto_mode_coerced_to_fm(self):
+ radio = self._radio_with_keypad_memory(MODE_AUTO, OFFSET_5000K)
+ mem = radio.get_memory(self.number)
+ self.assertFalse(mem.empty)
+ self.assertEqual(mem.mode, 'FM')
+ self.assertEqual(mem.freq, 462562500)
+ self.assertEqual(mem.name, 'KEYPAD')
+
+ def test_uncorrectable_split_offset_loads(self):
+ radio = self._radio_with_keypad_memory(MODE_AUTO_SPLIT,
+ OFFSET_159007)
+ mem = radio.get_memory(self.number)
+ self.assertFalse(mem.empty)
+ self.assertEqual(mem.mode, 'FM')
+ self.assertEqual(mem.duplex, 'split')
+ self.assertEqual(mem.offset, 159007000)
diff --git a/tests/unit/test_wxui_radiothread.py b/tests/unit/test_wxui_radiothread.py
index 18d08b5..bd8fc37 100644
--- a/tests/unit/test_wxui_radiothread.py
+++ b/tests/unit/test_wxui_radiothread.py
@@ -189,24 +189,23 @@ class TestStartup(base.BaseTest):
@ddt.data(
# No arguments, no file, no previous, answer no
- [False, False, False, False, False],
+ [None, False, False, False],
# No arguments, no file, no previous, answer yes
- [False, False, False, False, True],
+ [None, False, False, True],
# No arguments, no file, previous yes, no prompt
- [False, False, False, True, None],
+ [None, False, True, None],
# No arguments, exists, previous no, no prompt
- [False, False, True, False, None],
+ [None, True, False, None],
# Opt out, no file, no prompt
- [False, True, False, None, None],
+ [False, False, None, None],
# Opt in, no file, previous yes, still prompt
- [True, False, False, True, True],
+ [True, False, True, True],
# Opt in, exists, previous no, no prompt'),
- [True, False, True, False, None],
+ [True, True, False, None],
)
@ddt.unpack
- def test_linux_desktop_file(self, optin, optout, exists, last, answ):
+ def test_linux_desktop_file(self, optin, exists, last, answ):
self.args.install_desktop_app = optin
- self.args.no_install_desktop_app = optout
os.path.exists.return_value = exists
self.conf.get_bool.return_value = last
wx.MessageBox.return_value = wx.YES if answ else wx.NO
diff --git a/tests/unit/test_yaesu_clone.py b/tests/unit/test_yaesu_clone.py
index f850ff1..c7317a1 100644
--- a/tests/unit/test_yaesu_clone.py
+++ b/tests/unit/test_yaesu_clone.py
@@ -1,13 +1,22 @@
from builtins import bytes
import os
+import random
+import shutil
+import struct
+import subprocess
import tempfile
import unittest
+from chirp import bitwise
from chirp import directory
+from chirp import errors
from chirp.drivers import ft60
from chirp.drivers import ft4
+from chirp.drivers import ftm150
+from chirp.drivers import ftm300d
from chirp.drivers import yaesu_clone
from chirp import memmap
+from chirp.settings import RadioSetting
class TestYaesuChecksum(unittest.TestCase):
@@ -180,3 +189,761 @@ class TestFT25(TestFTX4):
class TestFT25_Asian(TestFT25):
FAKE = FakeFT25R_Asian
+
+
+class TestFTM300Freq(unittest.TestCase):
+ def test_roundtrip_calling(self):
+ mmap, freq = ftm300d.parse_freq_bytes(b"\x00" * 3)
+ ftm300d.encode_freq(freq, 146520000)
+ self.assertEqual(bytes.fromhex("01 46 52"), mmap.get_packed())
+ self.assertEqual(146520000, ftm300d.decode_freq(freq))
+
+ def test_6_25_extra_from_dump(self):
+ raw = bytes.fromhex("a4 46 00")
+ mmap, freq = ftm300d.parse_freq_bytes(raw)
+ self.assertEqual(446006250, ftm300d.decode_freq(freq))
+ ftm300d.encode_freq(freq, 446006250)
+ self.assertEqual(raw, mmap.get_packed())
+
+ def test_tsql_r_from_adms_rev_tone(self):
+ # Dump 31: Tone Mode=REV TONE, byte 5 high nibble 3.
+ raw = bytes.fromhex("81 40 01 46 52 30 00 00 00 08 00 0f 00 0c 00 00")
+ self.assertEqual(3, raw[5] >> 4)
+ self.assertEqual("TSQL-R", ftm300d.TMODE_FROM_RADIO[3])
+ self.assertEqual(3, ftm300d.TMODE_TO_RADIO["TSQL-R"])
+
+ def test_timezone_sign_magnitude(self):
+ self.assertEqual(0, ftm300d.timezone_from_fields(0, 0))
+ self.assertEqual(1, ftm300d.timezone_from_fields(0, 1))
+ self.assertEqual(-1, ftm300d.timezone_from_fields(1, 1))
+ self.assertEqual((0, 0), ftm300d.timezone_to_fields(0))
+ self.assertEqual((0, 1), ftm300d.timezone_to_fields(1))
+ self.assertEqual((1, 1), ftm300d.timezone_to_fields(-1))
+ self.assertEqual((1, 16), ftm300d.timezone_to_fields(-16))
+ self.assertEqual("UTC \u00b10:00", ftm300d.timezone_label(0))
+ self.assertEqual("UTC +0:30", ftm300d.timezone_label(1))
+ self.assertEqual("UTC -0:30", ftm300d.timezone_label(-1))
+ self.assertEqual("UTC -8:00", ftm300d.timezone_label(-16))
+ self.assertEqual(57, len(ftm300d.TIMEZONE_LABELS))
+
+
+def _iter_settings(settings):
+ for element in settings:
+ if isinstance(element, RadioSetting):
+ yield element
+ else:
+ yield from _iter_settings(element)
+
+
+def _setting_map(settings):
+ found = {}
+ for s in _iter_settings(settings):
+ val = s.value
+ if hasattr(val, "format"):
+ found[s.get_name()] = val.format()
+ else:
+ found[s.get_name()] = str(val)
+ return found
+
+
+class FakeFTM300:
+ """SCU-56 style pipe: no echo of the host frame into the read stream.
+
+ acks: None (no reply), a 1-byte bytes (always that reply on a 131-byte
+ write), or a list of 1-byte replies popped per 131-byte write.
+ """
+
+ def __init__(self, readbuf=b"", chunk=None, acks=None):
+ self.readbuf = readbuf
+ self.writebuf = b""
+ self.timeout = 0.25
+ self.chunk = chunk
+ self.acks = acks
+
+ def write(self, data):
+ assert isinstance(data, bytes)
+ self.writebuf += data
+ if len(data) != ftm300d.FRAME_LEN or self.acks is None:
+ return
+ if isinstance(self.acks, list):
+ if self.acks:
+ self.readbuf += self.acks.pop(0)
+ else:
+ self.readbuf += self.acks
+
+ def read(self, n):
+ take = n if self.chunk is None else min(n, self.chunk)
+ buf = self.readbuf[:take]
+ self.readbuf = self.readbuf[take:]
+ return buf
+
+
+class TestFTM300Clone(unittest.TestCase):
+ def _golden(self):
+ img = os.path.join(os.path.dirname(__file__),
+ '..', 'images', 'Yaesu_FTM-300DR.img')
+ return ftm300d.FTM300Radio(img)
+
+ def test_clone_address_list(self):
+ addrs = ftm300d.clone_addresses()
+ self.assertEqual(768, len(addrs))
+ self.assertEqual([0x0000, 0x0100, 0x0180], addrs[:3])
+ self.assertEqual(0xFF80, addrs[509])
+ self.assertNotIn(0x0080, addrs[:510])
+ self.assertNotIn(0x0400, addrs[:510])
+ self.assertEqual(0x0000, addrs[510])
+ self.assertEqual(0x0080, addrs[511])
+ self.assertEqual([0x7F80, 0xFFFD, 0xFFFE], addrs[-3:])
+
+ def test_emitter_trailer_and_checksums(self):
+ src = self._golden()
+ mmap = src.get_mmap().get_packed()
+ frames = ftm300d.image_to_clone_frames(mmap)
+ self.assertEqual(768, len(frames))
+ for frame in frames:
+ self.assertEqual(ftm300d.FRAME_LEN, len(frame))
+ self.assertEqual(sum(frame[:130]) % 256, frame[130])
+ vfo = frames[-2]
+ self.assertEqual(b"\xff\xfd", vfo[:2])
+ self.assertEqual(mmap[0x80:0x100], vfo[2:130])
+ end = frames[-1]
+ self.assertEqual(b"\xff\xfe" + b"\x00" * 128 + b"\xfd", end)
+
+ def test_emitter_inverts_download(self):
+ src = self._golden()
+ frames = ftm300d.image_to_clone_frames(src.get_mmap())
+ dst = ftm300d.FTM300Radio(FakeFTM300(b"".join(frames)))
+ dst.sync_in()
+ self.assertEqual(frames, ftm300d.image_to_clone_frames(dst.get_mmap()))
+
+ def test_download(self):
+ src = self._golden()
+ frames = ftm300d.image_to_clone_frames(src.get_mmap())
+ self.assertEqual(768, len(frames))
+ self.assertEqual(ftm300d.FRAME_LEN, len(frames[0]))
+
+ fake = FakeFTM300(b"".join(frames))
+ dst = ftm300d.FTM300Radio(fake)
+ dst.sync_in()
+
+ self.assertEqual(b"\x06" * 768, fake.writebuf)
+ self.assertEqual(38400, ftm300d.FTM300Radio.BAUD_RATE)
+
+ srcb = src.get_mmap().get_packed()
+ got = dst.get_mmap().get_packed()
+ self.assertEqual(src._memsize, len(got))
+ self.assertEqual(srcb[:0x400], got[:0x400])
+ self.assertEqual(b"\x00" * 0x80, got[0x400:0x480])
+ self.assertEqual(srcb[0x480:], got[0x480:])
+
+ mem = dst.get_memory(1)
+ self.assertEqual(src.get_memory(1).freq, mem.freq)
+ self.assertEqual(src.get_memory(1).name, mem.name)
+
+ def test_download_byte_at_a_time(self):
+ src = self._golden()
+ frames = ftm300d.image_to_clone_frames(src.get_mmap())
+ dst = ftm300d.FTM300Radio(
+ FakeFTM300(b"".join(frames), chunk=1))
+ dst.sync_in()
+ self.assertEqual(src.get_memory(1).freq, dst.get_memory(1).freq)
+ self.assertEqual(b"\x06" * 768, dst.pipe.writebuf)
+
+ def test_download_no_response(self):
+ dst = ftm300d.FTM300Radio(FakeFTM300(b""))
+ with self.assertRaises(errors.RadioNoResponse):
+ dst.sync_in()
+
+ def test_download_bad_ident(self):
+ src = self._golden()
+ frames = ftm300d.image_to_clone_frames(src.get_mmap())
+ payload = bytearray(frames[0][2:130])
+ payload[:5] = b"XXXXX"
+ frames[0] = ftm300d.clone_frame(0, bytes(payload))
+ dst = ftm300d.FTM300Radio(FakeFTM300(b"".join(frames)))
+ with self.assertRaisesRegex(errors.RadioError, "ident"):
+ dst.sync_in()
+
+ def test_download_bad_checksum(self):
+ src = self._golden()
+ frames = ftm300d.image_to_clone_frames(src.get_mmap())
+ bad = bytearray(frames[0])
+ bad[-1] ^= 0xFF
+ dst = ftm300d.FTM300Radio(FakeFTM300(bytes(bad)))
+ with self.assertRaisesRegex(errors.RadioError, "checksum"):
+ dst.sync_in()
+
+ def test_upload(self):
+ src = self._golden()
+ frames = ftm300d.image_to_clone_frames(src.get_mmap())
+ fake = FakeFTM300(acks=b"\x06")
+ src.set_pipe(fake)
+ src.sync_out()
+ self.assertEqual(b"".join(frames), fake.writebuf)
+ self.assertEqual(b"", fake.readbuf)
+
+ def test_clone_out_writes_acked_stream(self):
+ src = self._golden()
+ frames = ftm300d.image_to_clone_frames(src.get_mmap())
+ fake = FakeFTM300(acks=b"\x06")
+ src.set_pipe(fake)
+ ftm300d._clone_out(src)
+ self.assertEqual(b"".join(frames), fake.writebuf)
+ self.assertEqual(b"", fake.readbuf)
+
+ def test_clone_out_no_ack(self):
+ src = self._golden()
+ fake = FakeFTM300()
+ src.set_pipe(fake)
+ with self.assertRaises(errors.RadioNoResponse):
+ ftm300d._clone_out(src)
+ # First frame retried; later frames not sent.
+ first = ftm300d.image_to_clone_frames(src.get_mmap())[0]
+ self.assertEqual(first * 30, fake.writebuf)
+
+ def test_clone_out_refused(self):
+ src = self._golden()
+ fake = FakeFTM300(acks=b"\x00")
+ src.set_pipe(fake)
+ with self.assertRaisesRegex(errors.RadioError, "refused"):
+ ftm300d._clone_out(src)
+ first = ftm300d.image_to_clone_frames(src.get_mmap())[0]
+ self.assertEqual(first, fake.writebuf)
+
+ def test_clone_out_timeout_after_first(self):
+ src = self._golden()
+ fake = FakeFTM300(acks=[b"\x06"])
+ src.set_pipe(fake)
+ with self.assertRaisesRegex(errors.RadioError, "ACK"):
+ ftm300d._clone_out(src)
+ frames = ftm300d.image_to_clone_frames(src.get_mmap())
+ self.assertEqual(frames[0] + frames[1], fake.writebuf)
+
+ def test_emitter_matches_adms_put_capture(self):
+ # Local capture only; CI does not ship the pcap.
+ pcap = os.path.join(
+ os.path.dirname(__file__), '..', '..',
+ 'ignored', 'yaesu', 'ftm-300dr', 'clone-sniff',
+ 'adms-put.pcapng')
+ if not os.path.exists(pcap) or not shutil.which('tshark'):
+ self.skipTest('ADMS PUT capture or tshark not available')
+ out = subprocess.check_output(
+ ['tshark', '-r', pcap, '-Y', 'usb.data_len == 131',
+ '-T', 'fields', '-e', 'usb.capdata'],
+ stderr=subprocess.DEVNULL)
+ captured = [bytes.fromhex(line.strip())
+ for line in out.decode().splitlines() if line.strip()]
+ self.assertEqual(769, len(captured))
+ # First URB had no ACK; identical retry starts the 768-frame clone.
+ self.assertEqual(captured[0], captured[1])
+ acked = captured[1:]
+ self.assertEqual(
+ ftm300d.clone_addresses(),
+ [int.from_bytes(frame[:2], 'big') for frame in acked])
+ radio = ftm300d.FTM300Radio(FakeFTM300(b"".join(acked)))
+ radio.sync_in()
+ self.assertEqual(
+ acked, ftm300d.image_to_clone_frames(radio.get_mmap()))
+
+ def test_settings_defaults_and_roundtrip(self):
+ src = self._golden()
+ values = _setting_map(src.get_settings())
+ self.assertEqual("INCH", values["unit"])
+ self.assertEqual("UTC \u00b10:00", values["timezone"])
+
+ settings = src.get_settings()
+ src.set_settings(settings)
+ for setting in _iter_settings(settings):
+ if setting.get_name() == "unit":
+ setting.value = "METRIC"
+ elif setting.get_name() == "timezone":
+ setting.value = "UTC -8:00"
+ src.set_settings(settings)
+
+ packed = src.get_mmap().get_packed()
+ self.assertEqual(0x00, packed[0xA1])
+ self.assertEqual(0x90, packed[0xA8])
+ values = _setting_map(src.get_settings())
+ self.assertEqual("METRIC", values["unit"])
+ self.assertEqual("UTC -8:00", values["timezone"])
+
+ settings = src.get_settings()
+ for setting in _iter_settings(settings):
+ name = setting.get_name()
+ if name == "lcd_brightness":
+ setting.value = "MIN"
+ elif name == "callsign":
+ setting.value = "N0CALL/A"
+ elif name == "aprs_call":
+ setting.value = "N0CALL"
+ elif name == "aprs_ssid":
+ setting.value = "13"
+ elif name == "aprs_modem":
+ setting.value = "ON"
+ elif name == "beep":
+ setting.value = "HIGH"
+ elif name == "ams_tx_mode":
+ setting.value = "TX DN Fixed"
+ elif name == "fm_bandwidth_a":
+ setting.value = "NARROW"
+ elif name == "date_fmt":
+ setting.value = "YYYY/MMM/DD"
+ elif name == "time_12hr":
+ setting.value = "12 HOUR"
+ elif name == "clock_type_b":
+ setting.value = "B"
+ elif name == "rx_mode_a":
+ setting.value = "AM"
+ elif name == "rx_mode_b":
+ setting.value = "FM"
+ elif name == "standby_beep_off":
+ setting.value = "OFF"
+ elif name == "digital_vw":
+ setting.value = "ON"
+ elif name == "location_service":
+ setting.value = "OFF"
+ elif name == "digital_popup":
+ setting.value = "CONTINUE"
+ elif name == "mic_gain":
+ setting.value = "MAX"
+ elif name == "target_location":
+ setting.value = "NUMERIC"
+ elif name == "compass":
+ setting.value = "NORTH UP"
+ elif name == "band_scope":
+ setting.value = "NARROW"
+ elif name == "display_mode":
+ setting.value = "GPS INFORMATION"
+ elif name == "sub_band_mute":
+ setting.value = "OFF"
+ elif name == "vox":
+ setting.value = "HIGH"
+ elif name == "vox_delay":
+ setting.value = "3.0 SEC"
+ elif name == "recording_band":
+ setting.value = "B"
+ elif name == "recording_mic":
+ setting.value = "ON"
+ elif name == "gps_datum":
+ setting.value = "TOKYO MEAN"
+ elif name == "gps_device":
+ setting.value = "EXTERNAL"
+ elif name == "rpt_ars_a":
+ setting.value = "OFF"
+ elif name == "rpt_shift_freq_a":
+ setting.value = 1.45
+ elif name == "rpt_shift_freq_b":
+ setting.value = 3.10
+ elif name == "vfo_step_a":
+ setting.value = "10.0 kHz"
+ elif name == "rx_coverage_a":
+ setting.value = "NORMAL"
+ elif name == "tot":
+ setting.value = "30 MIN"
+ elif name == "gps_log":
+ setting.value = "60 SEC"
+ elif name == "apo":
+ setting.value = "12.0 HOUR"
+ src.set_settings(settings)
+ packed = src.get_mmap().get_packed()
+ self.assertEqual(0x08, packed[0xEB])
+ self.assertEqual(0x10, packed[0xFA])
+ self.assertEqual(0x02, packed[0xEE])
+ self.assertEqual(0x20, packed[0x81] & 0x20)
+ self.assertEqual(0x00, packed[0x91] & 0x20)
+ self.assertEqual(0x80, packed[0x9A])
+ self.assertEqual(0x00, packed[0xE3] & 0x10)
+ self.assertEqual(0x02, packed[0xE3] & 0x02)
+ self.assertEqual(0x10, packed[0x81] & 0x10)
+ self.assertEqual(0x00, packed[0xF3] & 0x10)
+ self.assertEqual(0x02, packed[0xF3] & 0x02)
+ self.assertEqual(0x00, packed[0x91] & 0x10)
+ self.assertEqual(0x96, packed[0xE8])
+ self.assertEqual(0x00, packed[0x2D6])
+ self.assertEqual(0x20, packed[0xE5] & 0x20)
+ self.assertEqual(0x03, packed[0xAD])
+ self.assertEqual(0xFF, packed[0x2DB])
+ self.assertEqual(0x04, packed[0x2DD])
+ self.assertEqual(0x03, packed[0xE9] & 0x03)
+ self.assertEqual(0x02, packed[0xB6])
+ self.assertEqual(0x05, packed[0xB7])
+ self.assertEqual(0x02, packed[0xB8])
+ self.assertEqual(0x08, packed[0xEA] & 0x08)
+ self.assertEqual(0xB2, packed[0xAF])
+ self.assertEqual(0x80, packed[0xEC] & 0x80)
+ self.assertEqual(0x00, packed[0xE4] & 0x04)
+ self.assertEqual(0x04, packed[0xF4] & 0x04)
+ self.assertEqual(0x1D, packed[0x8D])
+ self.assertEqual(0x3E, packed[0x9D])
+ self.assertEqual(0x03, packed[0x85] & 0x0F)
+ self.assertEqual(0x00, packed[0xE3] & 0x08)
+ self.assertEqual(0x00, packed[0xE3] & 0x20)
+ self.assertEqual(0x20, packed[0xF3] & 0x20)
+ self.assertEqual(0x05, packed[0xAA])
+ self.assertEqual(0x06, packed[0xB5])
+ self.assertEqual(0x18, packed[0xA4])
+ self.assertEqual(0x10, packed[0xF9] & 0x10)
+ self.assertEqual(0x00, packed[0xF9] & 0x07)
+ self.assertEqual(0x03, packed[0x28F])
+ self.assertEqual(
+ b"N0CALL/A" + b"\xff" * 2, packed[0x2C8:0x2D2])
+ self.assertEqual(b"N0CALL", packed[0x508:0x50E])
+ self.assertEqual(0x0D, packed[0x50E])
+ self.assertEqual(0x01, packed[0x534])
+ values = _setting_map(src.get_settings())
+ self.assertEqual("MIN", values["lcd_brightness"])
+ self.assertEqual("N0CALL/A", values["callsign"])
+ self.assertEqual("N0CALL", values["aprs_call"])
+ self.assertEqual("13", values["aprs_ssid"])
+ self.assertEqual("ON", values["aprs_modem"])
+ self.assertEqual("HIGH", values["beep"])
+ self.assertEqual("TX DN Fixed", values["ams_tx_mode"])
+ self.assertEqual("NARROW", values["fm_bandwidth_a"])
+ self.assertEqual("WIDE", values["fm_bandwidth_b"])
+ self.assertEqual("YYYY/MMM/DD", values["date_fmt"])
+ self.assertEqual("12 HOUR", values["time_12hr"])
+ self.assertEqual("B", values["clock_type_b"])
+ self.assertEqual("AM", values["rx_mode_a"])
+ self.assertEqual("FM", values["rx_mode_b"])
+ self.assertEqual("OFF", values["standby_beep_off"])
+ self.assertEqual("ON", values["digital_vw"])
+ self.assertEqual("OFF", values["location_service"])
+ self.assertEqual("CONTINUE", values["digital_popup"])
+ self.assertEqual("MAX", values["mic_gain"])
+ self.assertEqual("NUMERIC", values["target_location"])
+ self.assertEqual("NORTH UP", values["compass"])
+ self.assertEqual("NARROW", values["band_scope"])
+ self.assertEqual("GPS INFORMATION", values["display_mode"])
+ self.assertEqual("OFF", values["sub_band_mute"])
+ self.assertEqual("HIGH", values["vox"])
+ self.assertEqual("3.0 SEC", values["vox_delay"])
+ self.assertEqual("B", values["recording_band"])
+ self.assertEqual("ON", values["recording_mic"])
+ self.assertEqual("TOKYO MEAN", values["gps_datum"])
+ self.assertEqual("EXTERNAL", values["gps_device"])
+ self.assertEqual("OFF", values["rpt_ars_a"])
+ self.assertEqual("ON", values["rpt_ars_b"])
+ self.assertEqual("1.45", values["rpt_shift_freq_a"])
+ self.assertEqual("3.10", values["rpt_shift_freq_b"])
+ self.assertEqual("10.0 kHz", values["vfo_step_a"])
+ self.assertEqual("NORMAL", values["rx_coverage_a"])
+ self.assertEqual("WIDE", values["rx_coverage_b"])
+ self.assertEqual("30 MIN", values["tot"])
+ self.assertEqual("60 SEC", values["gps_log"])
+ self.assertEqual("12.0 HOUR", values["apo"])
+
+ settings = src.get_settings()
+ for setting in _iter_settings(settings):
+ if setting.get_name() == "aprs_ssid":
+ setting.value = ""
+ src.set_settings(settings)
+ packed = src.get_mmap().get_packed()
+ self.assertEqual(0xCA, packed[0x50E])
+ values = _setting_map(src.get_settings())
+ self.assertEqual("", values["aprs_ssid"])
+
+
+def _ftm150_synthetic_image():
+ rnd = random.Random(150)
+ data = bytearray(rnd.randbytes(ftm150.FTM150Radio._memsize))
+ data[0:5] = ftm150.FTM150Radio._model
+ return data
+
+
+class FakeFTM150Receiver:
+ """Collects uploaded frames and ACKs each one, like [59 Other -> This]."""
+ timeout = None
+
+ def __init__(self, ack=b"\x06"):
+ self.frames = []
+ self._ack = ack
+
+ def write(self, data):
+ self.frames.append(bytes(data))
+
+ def read(self, count):
+ return self._ack
+
+
+class FakeFTM150Sender:
+ """Plays a canned clone stream, like [58 This -> Other]."""
+ timeout = None
+
+ def __init__(self, frames):
+ self._buf = b"".join(frames)
+ self.acks = b""
+
+ def write(self, data):
+ self.acks += data
+
+ def read(self, count):
+ out, self._buf = self._buf[:count], self._buf[count:]
+ return out
+
+
+class TestFTM150Clone(unittest.TestCase):
+ def _radio(self, pipe, data=None):
+ radio = ftm150.FTM150Radio(pipe)
+ if data is not None:
+ radio._mmap = memmap.MemoryMapBytes(bytes(data))
+ radio.process_mmap()
+ return radio
+
+ def test_upload_stream(self):
+ data = _ftm150_synthetic_image()
+ pipe = FakeFTM150Receiver()
+ data[ftm150.FILE_CHECKSUM_AT] = 0x5A
+ radio = self._radio(pipe, data)
+ radio.sync_out()
+
+ addrs = [struct.unpack(">H", f[:2])[0] for f in pipe.frames]
+ self.assertEqual(ftm300d.clone_addresses(), addrs)
+ for frame in pipe.frames:
+ self.assertEqual(ftm300d.FRAME_LEN, len(frame))
+ self.assertEqual(sum(frame[:-1]) % 256, frame[-1])
+
+ # The file checksum goes out as 0x00, like the radio sends it, but
+ # only in pass 1: pass 2's block 0x0000 is name table data.
+ self.assertEqual(0, pipe.frames[0][2 + ftm150.FILE_CHECKSUM_AT])
+ # ... while the image keeps it.
+ self.assertEqual(
+ b"\x5A", radio.get_mmap()[ftm150.FILE_CHECKSUM_AT])
+ pass2 = addrs.index(0, 1)
+ self.assertEqual(
+ data[0x10000:0x10080], pipe.frames[pass2][2:2 + 128])
+
+ def test_upload_download_roundtrip(self):
+ data = _ftm150_synthetic_image()
+ up = FakeFTM150Receiver()
+ self._radio(up, data).sync_out()
+
+ down = FakeFTM150Sender(up.frames)
+ radio = self._radio(down)
+ radio.sync_in()
+ result = radio.get_mmap().get_packed()
+
+ self.assertEqual(b"\x06" * len(ftm300d.clone_addresses()),
+ down.acks)
+ # Block 0x0400 is never transmitted; the checksum is recomputed.
+ expected = bytearray(data)
+ expected[0x0400:0x0480] = b"\x00" * 128
+ expected[ftm150.FILE_CHECKSUM_AT] = (
+ sum(expected[:ftm150.FILE_CHECKSUM_AT]) % 256)
+ self.assertEqual(bytes(expected), result)
+
+ def test_upload_refused(self):
+ pipe = FakeFTM150Receiver(ack=b"\x15")
+ with self.assertRaises(errors.RadioError):
+ self._radio(pipe, _ftm150_synthetic_image()).sync_out()
+ self.assertEqual(1, len(pipe.frames))
+
+ def test_upload_no_response(self):
+ pipe = FakeFTM150Receiver(ack=b"")
+ with self.assertRaises(errors.RadioNoResponse):
+ self._radio(pipe, _ftm150_synthetic_image()).sync_out()
+ self.assertEqual(30, len(pipe.frames))
+
+ def test_upload_wrong_image(self):
+ data = _ftm150_synthetic_image()
+ data[0:5] = b"AH071"
+ pipe = FakeFTM150Receiver()
+ with self.assertRaises(errors.RadioError):
+ self._radio(pipe, data).sync_out()
+ self.assertEqual([], pipe.frames)
+
+
+def _ftm150_freq(raw):
+ mmap = memmap.MemoryMapBytes(bytes(raw))
+ freq = bitwise.parse(
+ ftm150.YFREQ_FORMAT + "struct yfreq freq;", mmap).freq
+ return mmap, freq
+
+
+class TestFTM150Freq(unittest.TestCase):
+ def test_roundtrip_calling(self):
+ mmap, freq = _ftm150_freq(b"\x00" * 3)
+ ftm150.encode_freq(freq, 145500000)
+ self.assertEqual(bytes.fromhex("01 45 50"), mmap.get_packed())
+ self.assertEqual(145500000, ftm150.decode_freq(freq))
+
+ def test_6_25_from_dump(self):
+ # 5 kHz + 1.25 kHz, i.e. fine = 0b1010 = 10 x 625 Hz.
+ raw = bytes.fromhex("a4 46 00")
+ mmap, freq = _ftm150_freq(raw)
+ self.assertEqual(10, int(freq.fine))
+ self.assertEqual(446006250, ftm150.decode_freq(freq))
+ ftm150.encode_freq(freq, 446006250)
+ self.assertEqual(raw, mmap.get_packed())
+
+ def test_every_625_step(self):
+ mmap, freq = _ftm150_freq(b"\x00" * 3)
+ for fine in range(16):
+ hz = 433000000 + fine * 625
+ ftm150.encode_freq(freq, hz)
+ self.assertEqual(hz, ftm150.decode_freq(freq))
+ self.assertEqual(bytes([fine << 4 | 4, 0x33, 0x00]),
+ mmap.get_packed())
+
+ def test_8_33_rounds_down_to_625_step(self):
+ # Airband 8.33 kHz channels do not fit; same as ftm300d does.
+ mmap, freq = _ftm150_freq(b"\x00" * 3)
+ ftm150.encode_freq(freq, 118008333)
+ self.assertEqual(118008125, ftm150.decode_freq(freq))
+
+
+class TestFTM150SqlOverride(unittest.TestCase):
+ def setUp(self):
+ img = os.path.join(os.path.dirname(__file__),
+ '..', 'images', 'Yaesu_FTM-150E.img')
+ self.radio = ftm150.FTM150Radio(img)
+ self._mem = self.radio._memobj.memory[0]
+ self.assertTrue(int(self._mem.used))
+
+ def _override(self, mem):
+ return str(mem.extra["sql_override"].value)
+
+ def test_pr_freq_and_pager_survive_write(self):
+ for raw, name in ((5, "PR FREQ"), (6, "PAGER")):
+ self._mem.tone_mode = raw
+ mem = self.radio.get_memory(1)
+ self.assertEqual("", mem.tmode)
+ self.assertEqual(name, self._override(mem))
+ self.radio.set_memory(mem)
+ self.assertEqual(raw, int(self._mem.tone_mode))
+
+ def test_override_wins_over_tmode(self):
+ self._mem.tone_mode = 1
+ mem = self.radio.get_memory(1)
+ self.assertEqual("(None)", self._override(mem))
+ mem.extra["sql_override"].value = "PAGER"
+ self.radio.set_memory(mem)
+ self.assertEqual(6, int(self._mem.tone_mode))
+
+ def test_clearing_override_uses_tmode(self):
+ self._mem.tone_mode = 6
+ mem = self.radio.get_memory(1)
+ mem.tmode = "TSQL"
+ mem.extra["sql_override"].value = "(None)"
+ self.radio.set_memory(mem)
+ self.assertEqual(2, int(self._mem.tone_mode))
+
+ def test_records_from_adms(self):
+ # Channel 1 as ADMS-17 wrote it: (record, mode, CTCSS, User CTCSS)
+ for raw, override, rtone, pr_freq in (
+ ("81 04 01 44 00 54 01 44 00 00 00 03 00 00 00 00",
+ "PR FREQ", 67.0, "300 Hz"),
+ ("81 04 01 44 00 64 01 44 00 0d 00 0b 00 00 00 00",
+ "PAGER", 103.5, "1100 Hz"),
+ ("81 04 01 44 00 64 01 44 00 0d 00 1e 00 00 00 00",
+ "PAGER", 103.5, "3000 Hz")):
+ record = bytes.fromhex(raw)
+ self._mem.set_raw(record)
+ mem = self.radio.get_memory(1)
+ self.assertEqual(override, self._override(mem))
+ self.assertEqual(rtone, mem.rtone)
+ self.assertEqual(pr_freq, str(mem.extra["pr_freq"].value))
+ self.radio.set_memory(mem)
+ self.assertEqual(record, self._mem.get_raw())
+
+ def test_pr_freq_write(self):
+ mem = self.radio.get_memory(1)
+ self.assertEqual("1500 Hz", str(mem.extra["pr_freq"].value))
+ mem.extra["pr_freq"].value = "3000 Hz"
+ self.radio.set_memory(mem)
+ self.assertEqual(30, int(self._mem.pr_freq))
+
+ def test_pager_codes(self):
+ values = _setting_map(self.radio.get_settings())
+ self.assertEqual(
+ ["05", "47", "05", "47"],
+ [values[n] for n in ("pager_rx0", "pager_rx1",
+ "pager_tx0", "pager_tx1")])
+ # RX 40/01 and TX 01/15, as ADMS-17 wrote them
+ new = {"pager_rx0": "40", "pager_rx1": "01",
+ "pager_tx0": "01", "pager_tx1": "15"}
+ settings = self.radio.get_settings()
+ for setting in _iter_settings(settings):
+ if setting.get_name() in new:
+ setting.value = new[setting.get_name()]
+ self.radio.set_settings(settings)
+ self.assertEqual(bytes.fromhex("27 00 00 0e"),
+ self.radio.get_mmap().get_packed()[0x2D2:0x2D6])
+
+ def test_pr_freq_out_of_range_untouched(self):
+ self._mem.pr_freq = 0
+ mem = self.radio.get_memory(1)
+ self.assertNotIn("pr_freq", [s.get_name() for s in mem.extra])
+ self.radio.set_memory(mem)
+ self.assertEqual(0, int(self._mem.pr_freq))
+
+
+class TestFTM150PMG(unittest.TestCase):
+ # Slot records as the radio wrote them; FREQ is a VFO frequency
+ # (145.6125 MHz, -600 kHz) stored in the slot itself.
+ FREQ = bytes.fromhex("81 02 41 45 61 04 00 00 00 8c 00 8f 00 0c 00 00")
+
+ def setUp(self):
+ img = os.path.join(os.path.dirname(__file__),
+ '..', 'images', 'Yaesu_FTM-150E.img')
+ self.radio = ftm150.FTM150Radio(img)
+ pmg = self.radio._memobj.pmg
+ pmg[0].set_raw(ftm150._pmg_ref(10, 3))
+ pmg[1].set_raw(ftm150._pmg_ref(1, 1))
+ pmg[2].set_raw(self.FREQ)
+ pmg[3].set_raw(ftm150._pmg_ref(999, 1))
+ pmg[4].set_raw(b"\x00" + b"\xff" * 15)
+ self.radio._memobj.pmg_selected = 3
+
+ def _raw(self):
+ return [rec.get_raw() for rec in self.radio._memobj.pmg]
+
+ def _set(self, new):
+ settings = self.radio.get_settings()
+ for setting in _iter_settings(settings):
+ if setting.get_name() in new:
+ setting.value = new[setting.get_name()]
+ self.radio.set_settings(settings)
+
+ def test_ref_format(self):
+ # Channel 300 as the radio stored it
+ self.assertEqual(bytes.fromhex("91 ff 01 2b") + b"\xff" * 12,
+ ftm150._pmg_ref(300, 1))
+ self.assertEqual(300, ftm150._pmg_channel(ftm150._pmg_ref(300, 1)))
+ self.assertIsNone(ftm150._pmg_channel(self.FREQ))
+ self.assertIsNone(ftm150._pmg_channel(
+ bytes.fromhex("00 ff 01 2b") + b"\xff" * 12))
+
+ def test_read(self):
+ values = _setting_map(self.radio.get_settings())
+ self.assertTrue(values["pmg0"].startswith("10"))
+ self.assertTrue(values["pmg1"].startswith("1"))
+ self.assertEqual("Frequency 145.612500 MHz", values["pmg2"])
+ self.assertTrue(values["pmg3"].startswith("999"))
+ self.assertEqual("(Empty)", values["pmg4"])
+ self.assertEqual("Slot 4", values["pmg_selected"])
+
+ def test_unchanged_roundtrip(self):
+ before = self.radio.get_mmap().get_packed()
+ self._set({})
+ self.assertEqual(before, self.radio.get_mmap().get_packed())
+
+ def test_empty_slot_moves_later_slots_up(self):
+ old = self._raw()
+ self._set({"pmg1": "(Empty)"})
+ # Like the radio: later slots move up, the last one only loses
+ # its used bit.
+ self.assertEqual(old[0], self._raw()[0])
+ self.assertEqual([self.FREQ, old[3]], self._raw()[1:3])
+ self.assertEqual(b"\x00" + old[3][1:], self._raw()[3])
+ self.assertEqual(old[4], self._raw()[4])
+ # The selected channel 999 moved from slot 4 to slot 3.
+ self.assertEqual(2, int(self.radio._memobj.pmg_selected))
+
+ def test_selected_falls_back_to_slot_1(self):
+ self._set({"pmg3": "(Empty)"})
+ self.assertEqual(0, int(self.radio._memobj.pmg_selected))
+
+ def test_new_ref_uses_channel_band(self):
+ label = self.radio._channel_label(14)
+ self._set({"pmg4": label})
+ self.assertEqual(ftm150._pmg_ref(14, 3), self._raw()[4])
diff --git a/tools/check_commit.sh b/tools/check_commit.sh
index ac95ef5..5b8887c 100755
--- a/tools/check_commit.sh
+++ b/tools/check_commit.sh
@@ -91,6 +91,9 @@ if git log ${BASE}.. --merges | grep .; then
fi
make -C chirp/locale clean all >/dev/null 2>&1
+if [ $? -ne 0 ]; then
+ fail Locale build failed
+fi
if git diff -- chirp/locale | grep '^+[^#+]' | grep -v POT-Creation; then
fail Locale files need updating
fi
diff --git a/tools/checkpatch.sh b/tools/checkpatch.sh
deleted file mode 100755
index 5cf3a6f..0000000
--- a/tools/checkpatch.sh
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/env bash
-#
-# CHIRP coding standards compliance script
-#
-# To add a test to this file, create a new check_foo() function
-# and then add it to the list of TESTS= below
-#
-
-TESTS="check_long_lines check_bug_number check_commit_message_line_length"
-
-function check_long_lines() {
- local rev="$1"
- local files="$2"
-
- # For now, ignore this check on chirp/
- files=$(echo $files | sed -r 's#\bchirp[^ ]*\b##')
-
- if [ -z "$files" ]; then
- return
- fi
-
- pep8 --select=E501 $files || \
- error "Please use <80 columns in source files"
-}
-
-function check_bug_number() {
- local rev="$1"
- hg log -vr $rev | grep -qE '#[0-9]+' || \
- error "A bug number is required like #123"
-}
-
-function _less_than_80() {
- while true; do
- read line
- if [ -z "$line" ]; then
- break
- elif [ $(echo -n "$line" | wc -c) -ge 80 ]; then
- return 1
- fi
- done
-}
-
-function check_commit_message_line_length() {
- local rev="$1"
- hg log -vr $rev | (_less_than_80) || \
- error "Please keep commit message lines to <80 columns"
-}
-
-# --- END OF TEST FUNCTIONS ---
-
-function error() {
- echo FAIL: $*
- ERROR=1
-}
-
-function get_touched_files() {
- local rev="$1"
- hg status -n --change $rev | grep '\.py$'
-}
-
-rev=${1:-tip}
-files=$(get_touched_files $rev)
-
-for testname in $TESTS; do
- eval "$testname $rev \"$files\""
-done
-
-if [ -z "$ERROR" ]; then
- echo "Patch '${rev}' is OK"
-else
- exit 1
-fi
diff --git a/tools/cpep8.py b/tools/cpep8.py
index a1fde83..60db7c3 100755
--- a/tools/cpep8.py
+++ b/tools/cpep8.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
#
# cpep8.py - Check Python source files for PEP8 compliance.
#