summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDave Hibberd <hibby@debian.org>2026-10-31 12:31:46 +0000
committerDave Hibberd <hibby@debian.org>2026-10-31 12:31:46 +0000
commitdd07cc494d2f8a342ee0556a593b068800f9da5b (patch)
tree07f455fe694b4a47959b76e9f93c0306690bc6a2
parentaa0d17d5ad14d671e5ce02cb90f814e0a96fad98 (diff)
parentef0af95bac2c3d310fe55f54853904395b57f884 (diff)
Update upstream source from tag 'upstream/20261030'
Update to upstream version '20261030' with Debian dir 82dda47c52fda693a8e3b8228e4043c187b8dcfc
-rw-r--r--PKG-INFO2
-rw-r--r--chirp.egg-info/PKG-INFO2
-rw-r--r--chirp.egg-info/SOURCES.txt91
-rw-r--r--chirp/__init__.py2
-rw-r--r--chirp/bandplan_iaru_r1.py33
-rw-r--r--chirp/bitwise.py104
-rw-r--r--chirp/checksum.py64
-rw-r--r--chirp/chirp_common.py128
-rw-r--r--chirp/cli/main.py4
-rw-r--r--chirp/directory.py15
-rw-r--r--chirp/drivers/__init__.py57
-rw-r--r--chirp/drivers/alinco.py32
-rw-r--r--chirp/drivers/alinco_dr735t.py6
-rw-r--r--chirp/drivers/anytone.py12
-rw-r--r--chirp/drivers/anytone778uv.py19
-rw-r--r--chirp/drivers/anytone_ht.py16
-rw-r--r--chirp/drivers/anytone_iii.py22
-rw-r--r--chirp/drivers/ap510.py2
-rw-r--r--chirp/drivers/ar8200.py1698
-rw-r--r--chirp/drivers/baofeng_common.py8
-rw-r--r--chirp/drivers/baofeng_digital.py69
-rw-r--r--chirp/drivers/baofeng_dm32uv.py2762
-rw-r--r--chirp/drivers/baofeng_uv17.py2
-rw-r--r--chirp/drivers/baofeng_uv17Pro.py719
-rw-r--r--chirp/drivers/bf_t1.py6
-rw-r--r--chirp/drivers/bf_t8.py8
-rw-r--r--chirp/drivers/boblov_x3plus.py17
-rw-r--r--chirp/drivers/btech.py716
-rw-r--r--chirp/drivers/ft1d.py44
-rw-r--r--chirp/drivers/ft2d.py47
-rw-r--r--chirp/drivers/ft4.py78
-rw-r--r--chirp/drivers/ft450d.py416
-rw-r--r--chirp/drivers/ft50.py12
-rw-r--r--chirp/drivers/ft60.py10
-rw-r--r--chirp/drivers/ft7100.py18
-rw-r--r--chirp/drivers/ft7800.py13
-rw-r--r--chirp/drivers/ft8000r.py635
-rw-r--r--chirp/drivers/ft817.py6
-rw-r--r--chirp/drivers/ft90.py10
-rw-r--r--chirp/drivers/ftm150.py1019
-rw-r--r--chirp/drivers/ftm300d.py1398
-rw-r--r--chirp/drivers/ftm350.py8
-rw-r--r--chirp/drivers/ga510.py30
-rw-r--r--chirp/drivers/generic_csv.py4
-rw-r--r--chirp/drivers/gmrsuv1.py21
-rw-r--r--chirp/drivers/gmrsv2.py4
-rw-r--r--chirp/drivers/h777.py465
-rw-r--r--chirp/drivers/hf90.py6
-rw-r--r--chirp/drivers/hg_uv98.py88
-rw-r--r--chirp/drivers/hobbypcb.py2
-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.py31
-rw-r--r--chirp/drivers/ic2820.py5
-rw-r--r--chirp/drivers/ic9x.py2
-rw-r--r--chirp/drivers/ic9x_ll.py12
-rw-r--r--chirp/drivers/icf.py45
-rw-r--r--chirp/drivers/icomciv.py8
-rw-r--r--chirp/drivers/icp7.py20
-rw-r--r--chirp/drivers/icq7.py10
-rw-r--r--chirp/drivers/ict70.py5
-rw-r--r--chirp/drivers/ict7h.py5
-rw-r--r--chirp/drivers/ict8.py7
-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/iradio_common.py56
-rw-r--r--chirp/drivers/iradio_uv_5118.py69
-rw-r--r--chirp/drivers/iradio_uv_5118plus.py62
-rw-r--r--chirp/drivers/kenwood_d7.py16
-rw-r--r--chirp/drivers/kenwood_itm.py16
-rw-r--r--chirp/drivers/kenwood_live.py538
-rw-r--r--chirp/drivers/kg935g.py276
-rw-r--r--chirp/drivers/kguv8d.py111
-rw-r--r--chirp/drivers/kguv8dplus.py113
-rw-r--r--chirp/drivers/kguv8e.py127
-rw-r--r--chirp/drivers/kguv920pa.py128
-rw-r--r--chirp/drivers/kguv980p.py118
-rw-r--r--chirp/drivers/kguv9dplus.py124
-rw-r--r--chirp/drivers/kyd.py93
-rw-r--r--chirp/drivers/kyd_IP620.py93
-rw-r--r--chirp/drivers/leixen.py13
-rw-r--r--chirp/drivers/lt725uv.py19
-rw-r--r--chirp/drivers/mml_jc8810.py4
-rw-r--r--chirp/drivers/mursv1.py2
-rw-r--r--chirp/drivers/nx800.py1249
-rw-r--r--chirp/drivers/puxing.py4
-rw-r--r--chirp/drivers/radioddity_db40g.py476
-rw-r--r--chirp/drivers/radioddity_gm30.py165
-rw-r--r--chirp/drivers/radioddity_r2.py12
-rw-r--r--chirp/drivers/radtel_rt490.py6
-rw-r--r--chirp/drivers/radtel_rt880g.py2309
-rw-r--r--chirp/drivers/radtel_rt900.py1020
-rw-r--r--chirp/drivers/radtel_t18.py78
-rw-r--r--chirp/drivers/retevis_c2.py1349
-rw-r--r--chirp/drivers/retevis_h777v4.py350
-rw-r--r--chirp/drivers/retevis_ha1g.py857
-rw-r--r--chirp/drivers/retevis_ha2.py1290
-rw-r--r--chirp/drivers/retevis_ra25.py54
-rw-r--r--chirp/drivers/retevis_ra86.py2
-rw-r--r--chirp/drivers/retevis_ra87.py12
-rw-r--r--chirp/drivers/retevis_rb15.py19
-rw-r--r--chirp/drivers/retevis_rb17p.py2
-rw-r--r--chirp/drivers/retevis_rb28.py185
-rw-r--r--chirp/drivers/retevis_rt1.py2
-rw-r--r--chirp/drivers/retevis_rt18.py190
-rw-r--r--chirp/drivers/retevis_rt21.py320
-rw-r--r--chirp/drivers/retevis_rt22.py143
-rw-r--r--chirp/drivers/retevis_rt23.py4
-rw-r--r--chirp/drivers/retevis_rt26.py2
-rw-r--r--chirp/drivers/retevis_rt76p.py54
-rw-r--r--chirp/drivers/retevis_rt87.py10
-rw-r--r--chirp/drivers/retevis_rt97s.py322
-rw-r--r--chirp/drivers/retevis_rt98.py58
-rw-r--r--chirp/drivers/rh5r_v2.py31
-rw-r--r--chirp/drivers/tdh8.py146
-rw-r--r--chirp/drivers/tdm11.py921
-rw-r--r--chirp/drivers/tdxone_tdq8a.py15
-rw-r--r--chirp/drivers/tg_uv2p.py10
-rw-r--r--chirp/drivers/th350.py10
-rw-r--r--chirp/drivers/th7800.py10
-rw-r--r--chirp/drivers/th9000.py104
-rw-r--r--chirp/drivers/th9800.py30
-rw-r--r--chirp/drivers/th_uv3r.py6
-rw-r--r--chirp/drivers/th_uv8000.py18
-rw-r--r--chirp/drivers/th_uv88.py21
-rw-r--r--chirp/drivers/thd72.py27
-rw-r--r--chirp/drivers/thd74.py26
-rw-r--r--chirp/drivers/thuv1f.py4
-rw-r--r--chirp/drivers/tk11.py2563
-rw-r--r--chirp/drivers/tk270.py10
-rw-r--r--chirp/drivers/tk280.py24
-rw-r--r--chirp/drivers/tk690.py20
-rw-r--r--chirp/drivers/tk760.py14
-rw-r--r--chirp/drivers/tk760g.py39
-rw-r--r--chirp/drivers/tk8102.py88
-rw-r--r--chirp/drivers/tk8160.py315
-rw-r--r--chirp/drivers/tk8180.py703
-rw-r--r--chirp/drivers/tmd710.py68
-rw-r--r--chirp/drivers/tmv71.py8
-rw-r--r--chirp/drivers/tmv71_ll.py19
-rw-r--r--chirp/drivers/ts2000.py1
-rw-r--r--chirp/drivers/ts480.py11
-rw-r--r--chirp/drivers/ts590.py16
-rw-r--r--chirp/drivers/ts850.py4
-rw-r--r--chirp/drivers/tyt_uvl15w.py1113
-rw-r--r--chirp/drivers/uv5r.py319
-rw-r--r--chirp/drivers/uv5x3.py21
-rw-r--r--chirp/drivers/uv6r.py21
-rw-r--r--chirp/drivers/uvb5.py10
-rw-r--r--chirp/drivers/uvk5.py247
-rw-r--r--chirp/drivers/uvk5_cn.py763
-rw-r--r--chirp/drivers/uvk5_egzumer.py4
-rw-r--r--chirp/drivers/vgc.py3
-rw-r--r--chirp/drivers/vx1.py1271
-rw-r--r--chirp/drivers/vx150.py778
-rw-r--r--chirp/drivers/vx3.py9
-rw-r--r--chirp/drivers/vx8.py29
-rw-r--r--chirp/drivers/wouxun.py117
-rw-r--r--chirp/drivers/yaesu_clone.py41
-rw-r--r--chirp/errors.py11
-rw-r--r--chirp/import_logic.py26
-rw-r--r--chirp/kenwood_tone.py256
-rw-r--r--chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mobin50740 -> 50611 bytes
-rw-r--r--chirp/locale/cs/LC_MESSAGES/CHIRP.mobin0 -> 89208 bytes
-rw-r--r--chirp/locale/de/LC_MESSAGES/CHIRP.mobin1798 -> 41447 bytes
-rw-r--r--chirp/locale/el/LC_MESSAGES/CHIRP.mobin14848 -> 14846 bytes
-rw-r--r--chirp/locale/es/LC_MESSAGES/CHIRP.mobin90737 -> 94528 bytes
-rw-r--r--chirp/locale/fr/LC_MESSAGES/CHIRP.mobin92790 -> 90475 bytes
-rw-r--r--chirp/locale/it/LC_MESSAGES/CHIRP.mobin90867 -> 150447 bytes
-rw-r--r--chirp/locale/ja_JP/LC_MESSAGES/CHIRP.mobin15414 -> 100001 bytes
-rw-r--r--chirp/locale/pl/LC_MESSAGES/CHIRP.mobin27170 -> 27168 bytes
-rw-r--r--chirp/locale/pt_BR/LC_MESSAGES/CHIRP.mobin1700 -> 87696 bytes
-rw-r--r--chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mobin89721 -> 87413 bytes
-rw-r--r--chirp/locale/ru/LC_MESSAGES/CHIRP.mobin121285 -> 118093 bytes
-rw-r--r--chirp/locale/tr_TR/LC_MESSAGES/CHIRP.mobin83608 -> 90833 bytes
-rw-r--r--chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mobin1625 -> 105485 bytes
-rw-r--r--chirp/locale/zh_CN/LC_MESSAGES/CHIRP.mobin75039 -> 72931 bytes
-rw-r--r--chirp/platform.py45
-rw-r--r--chirp/settings.py30
-rw-r--r--chirp/share/chirp.desktop1
-rw-r--r--chirp/share/welcome_screen_de.pngbin0 -> 27839 bytes
-rw-r--r--chirp/share/welcome_screen_pt_BR.pngbin0 -> 28143 bytes
-rw-r--r--chirp/sources/amsats.py281
-rw-r--r--chirp/sources/base.py2
-rw-r--r--chirp/sources/fips.py (renamed from chirp/wxui/fips.py)0
-rw-r--r--chirp/sources/repeaterbook.py93
-rw-r--r--chirp/stock_configs/FR Marine VHF Channels.csv2
-rw-r--r--chirp/wxui/__init__.py33
-rw-r--r--chirp/wxui/accessibility.py429
-rw-r--r--chirp/wxui/bankedit.py17
-rw-r--r--chirp/wxui/bugreport.py53
-rw-r--r--chirp/wxui/clone.py3
-rw-r--r--chirp/wxui/common.py250
-rw-r--r--chirp/wxui/config.py2
-rw-r--r--chirp/wxui/developer.py15
-rw-r--r--chirp/wxui/main.py86
-rw-r--r--chirp/wxui/memedit.py122
-rw-r--r--chirp/wxui/query_sources.py94
-rw-r--r--chirp/wxui/radioinfo.py21
-rw-r--r--chirp/wxui/report.py3
-rw-r--r--chirp/wxui/serialtrace.py67
-rw-r--r--chirp/wxui/settingsedit.py15
-rw-r--r--requirements.txt7
-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/__pycache__/test_clone.cpython-310-pytest-7.1.3.pycbin5451 -> 6003 bytes
-rw-r--r--tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pycbin8248 -> 8482 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/Bajeton_BJ7800.imgbin0 -> 62433 bytes
-rw-r--r--tests/images/Baofeng_BF-V12D.imgbin0 -> 1221 bytes
-rw-r--r--tests/images/Baofeng_DM-32UV.imgbin0 -> 311449 bytes
-rw-r--r--tests/images/Baofeng_GM-21.imgbin0 -> 33841 bytes
-rw-r--r--tests/images/Baofeng_MP31.imgbin0 -> 1577 bytes
-rw-r--r--tests/images/Baofeng_UV-28Plus.imgbin0 -> 33845 bytes
-rw-r--r--tests/images/Baofeng_UV-5G_Mini.imgbin0 -> 33537 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/Baofeng_UV-5RM_Plus.imgbin0 -> 33857 bytes
-rw-r--r--tests/images/Boblov_X3Plus.imgbin1008 -> 1165 bytes
-rw-r--r--tests/images/Icom_IC-2730E.imgbin0 -> 21493 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/Kenwood_TK-7162.imgbin0 -> 16573 bytes
-rw-r--r--tests/images/Quansheng_TK11.imgbin0 -> 143529 bytes
-rw-r--r--tests/images/Quansheng_UV-K5_losehu.imgbin0 -> 262657 bytes
-rw-r--r--tests/images/Radioddity_DB40-G.imgbin0 -> 6589 bytes
-rw-r--r--tests/images/Radioddity_GM-30_Plus.imgbin0 -> 33861 bytes
-rw-r--r--tests/images/Radioddity_GM-30_Pro.imgbin0 -> 33861 bytes
-rw-r--r--tests/images/Radioddity_GS-10B.imgbin0 -> 62269 bytes
-rw-r--r--tests/images/Radioddity_MU-5.imgbin0 -> 41145 bytes
-rw-r--r--tests/images/Radtel_RT-880G.imgbin0 -> 879789 bytes
-rw-r--r--tests/images/Radtel_RT-920.imgbin62265 -> 62433 bytes
-rw-r--r--tests/images/Retevis_C2.imgbin0 -> 17593 bytes
-rw-r--r--tests/images/Retevis_HA2.imgbin0 -> 72265 bytes
-rw-r--r--tests/images/Retevis_RB48.imgbin0 -> 2233 bytes
-rw-r--r--tests/images/Retevis_RB626.imgbin969 -> 2245 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_RT21H.imgbin0 -> 401 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/TIDRADIO_TD-H8-HAM_G3.imgbin0 -> 8393 bytes
-rw-r--r--tests/images/TIDRADIO_TD-M11_16_PMR.imgbin0 -> 1289 bytes
-rw-r--r--tests/images/TIDRADIO_TD-M11_22_FRS.imgbin0 -> 1289 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/Wouxun_KG-XS20G.imgbin0 -> 32949 bytes
-rw-r--r--tests/images/Wouxun_KG-XS20G_Plus.imgbin0 -> 32973 bytes
-rw-r--r--tests/images/Wouxun_KG-XS20H.imgbin0 -> 32949 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/Yaesu_VX-1.imgbin0 -> 5079 bytes
-rw-r--r--tests/images/Yaesu_VX-150.imgbin0 -> 5538 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_clone.py14
-rw-r--r--tests/test_edges.py4
-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_amsats.cpython-310-pytest-7.1.3.pycbin0 -> 3222 bytes
-rw-r--r--tests/unit/__pycache__/test_btech_docs.cpython-310-pytest-7.1.3.pycbin0 -> 1925 bytes
-rw-r--r--tests/unit/__pycache__/test_checksum.cpython-310-pytest-7.1.3.pycbin0 -> 1252 bytes
-rw-r--r--tests/unit/__pycache__/test_chirp_common.cpython-310-pytest-7.1.3.pycbin33883 -> 34551 bytes
-rw-r--r--tests/unit/__pycache__/test_crc.cpython-310-pytest-7.1.3.pycbin0 -> 895 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_import_logic.cpython-310-pytest-7.1.3.pycbin14847 -> 15823 bytes
-rw-r--r--tests/unit/__pycache__/test_kenwood_tone.cpython-310-pytest-7.1.3.pycbin0 -> 61031 bytes
-rw-r--r--tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pycbin8070 -> 9294 bytes
-rw-r--r--tests/unit/__pycache__/test_retevis_ra25.cpython-310-pytest-7.1.3.pycbin0 -> 5240 bytes
-rw-r--r--tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pycbin2863 -> 5311 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_amsats.py112
-rw-r--r--tests/unit/test_btech_docs.py26
-rw-r--r--tests/unit/test_checksum.py25
-rw-r--r--tests/unit/test_chirp_common.py53
-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_import_logic.py46
-rw-r--r--tests/unit/test_kenwood_tone.py2193
-rw-r--r--tests/unit/test_repeaterbook.py54
-rw-r--r--tests/unit/test_retevis_ra25.py132
-rw-r--r--tests/unit/test_serialtrace.py45
-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.sh30
-rwxr-xr-xtools/checkpatch.sh72
-rwxr-xr-xtools/cpep8.py2
307 files changed, 37994 insertions, 3922 deletions
diff --git a/PKG-INFO b/PKG-INFO
index 49d752f..a61fa73 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 2.4
Name: chirp
-Version: 20251108
+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 49d752f..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: 20251108
+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 30885e2..1438bca 100644
--- a/chirp.egg-info/SOURCES.txt
+++ b/chirp.egg-info/SOURCES.txt
@@ -14,10 +14,12 @@ chirp/bandplan_iaru_r3.py
chirp/bandplan_na.py
chirp/bitwise.py
chirp/bitwise_grammar.py
+chirp/checksum.py
chirp/chirp_common.py
chirp/directory.py
chirp/errors.py
chirp/import_logic.py
+chirp/kenwood_tone.py
chirp/logger.py
chirp/memmap.py
chirp/platform.py
@@ -41,8 +43,10 @@ chirp/drivers/anytone778uv.py
chirp/drivers/anytone_ht.py
chirp/drivers/anytone_iii.py
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
@@ -68,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
@@ -118,6 +125,7 @@ chirp/drivers/id51plus.py
chirp/drivers/id800.py
chirp/drivers/id880.py
chirp/drivers/idrp.py
+chirp/drivers/iradio_common.py
chirp/drivers/iradio_uv_5118.py
chirp/drivers/iradio_uv_5118plus.py
chirp/drivers/kenwood_d7.py
@@ -138,16 +146,21 @@ 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
chirp/drivers/radioddity_gm30.py
chirp/drivers/radioddity_r2.py
chirp/drivers/radtel_rt490.py
chirp/drivers/radtel_rt620.py
+chirp/drivers/radtel_rt880g.py
chirp/drivers/radtel_rt900.py
chirp/drivers/radtel_t18.py
+chirp/drivers/retevis_c2.py
chirp/drivers/retevis_h777v4.py
chirp/drivers/retevis_ha1g.py
+chirp/drivers/retevis_ha2.py
chirp/drivers/retevis_ra25.py
chirp/drivers/retevis_ra86.py
chirp/drivers/retevis_ra87.py
@@ -155,15 +168,18 @@ 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
+chirp/drivers/tdm11.py
chirp/drivers/tdxone_tdq8a.py
chirp/drivers/template.py
chirp/drivers/tg_uv2p.py
@@ -179,6 +195,7 @@ chirp/drivers/th_uvf8d.py
chirp/drivers/thd72.py
chirp/drivers/thd74.py
chirp/drivers/thuv1f.py
+chirp/drivers/tk11.py
chirp/drivers/tk270.py
chirp/drivers/tk280.py
chirp/drivers/tk3140.py
@@ -197,13 +214,17 @@ 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
+chirp/drivers/vx150.py
chirp/drivers/vx170.py
chirp/drivers/vx2.py
chirp/drivers/vx3.py
@@ -216,6 +237,7 @@ chirp/drivers/wouxun.py
chirp/drivers/wouxun_common.py
chirp/drivers/yaesu_clone.py
chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo
+chirp/locale/cs/LC_MESSAGES/CHIRP.mo
chirp/locale/de/LC_MESSAGES/CHIRP.mo
chirp/locale/el/LC_MESSAGES/CHIRP.mo
chirp/locale/en_US/LC_MESSAGES/CHIRP.mo
@@ -242,14 +264,18 @@ chirp/share/com.chirpmyradio.CHIRP.metainfo.xml
chirp/share/plus-icon.png
chirp/share/welcome_screen.png
chirp/share/welcome_screen_bg.png
+chirp/share/welcome_screen_de.png
chirp/share/welcome_screen_es.png
chirp/share/welcome_screen_fr.png
chirp/share/welcome_screen_it.png
+chirp/share/welcome_screen_pt_BR.png
chirp/share/welcome_screen_ro_RO.png
chirp/share/welcome_screen_zh_CN.png
chirp/sources/__init__.py
+chirp/sources/amsats.py
chirp/sources/base.py
chirp/sources/dmrmarc.py
+chirp/sources/fips.py
chirp/sources/mapy73pl.py
chirp/sources/przemienniki_eu.py
chirp/sources/przemienniki_net.py
@@ -277,13 +303,13 @@ chirp/stock_configs/US Marine VHF Channels.csv
chirp/stock_configs/US NOAA Weather Alert.csv
chirp/wxui/__init__.py
chirp/wxui/__main__.py
+chirp/wxui/accessibility.py
chirp/wxui/bankedit.py
chirp/wxui/bugreport.py
chirp/wxui/clone.py
chirp/wxui/common.py
chirp/wxui/config.py
chirp/wxui/developer.py
-chirp/wxui/fips.py
chirp/wxui/main.py
chirp/wxui/memedit.py
chirp/wxui/memquery.py
@@ -297,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
@@ -310,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
@@ -360,6 +387,7 @@ tests/images/BTECH_UV-50X2.img
tests/images/BTECH_UV-50X2_G2.img
tests/images/BTECH_UV-50X3.img
tests/images/BTECH_UV-5X3.img
+tests/images/Bajeton_BJ7800.img
tests/images/Baofeng_5RM.img
tests/images/Baofeng_5RX.img
tests/images/Baofeng_BF-1904.img
@@ -371,16 +399,23 @@ tests/images/Baofeng_BF-T1.img
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
tests/images/Baofeng_K6.img
+tests/images/Baofeng_MP31.img
tests/images/Baofeng_UV-13Pro.img
tests/images/Baofeng_UV-17.img
tests/images/Baofeng_UV-17Pro.img
tests/images/Baofeng_UV-17ProGPS.img
+tests/images/Baofeng_UV-28Plus.img
tests/images/Baofeng_UV-3R.img
+tests/images/Baofeng_UV-5G_Mini.img
tests/images/Baofeng_UV-5G_Pro.img
tests/images/Baofeng_UV-5R.img
+tests/images/Baofeng_UV-5RM_Plus.img
tests/images/Baofeng_UV-5R_Mini.img
tests/images/Baofeng_UV-6R.img
tests/images/Baofeng_UV-9G.img
@@ -403,6 +438,7 @@ tests/images/Icom_IC-2200H.img
tests/images/Icom_IC-2300H.img
tests/images/Icom_IC-2720H.img
tests/images/Icom_IC-2730A.img
+tests/images/Icom_IC-2730E.img
tests/images/Icom_IC-2820H.img
tests/images/Icom_IC-E90.img
tests/images/Icom_IC-F621-2.img
@@ -435,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
@@ -445,6 +482,7 @@ tests/images/Kenwood_TK-3140K.img
tests/images/Kenwood_TK-3180K2.img
tests/images/Kenwood_TK-481.img
tests/images/Kenwood_TK-7160K.img
+tests/images/Kenwood_TK-7162.img
tests/images/Kenwood_TK-760G.img
tests/images/Kenwood_TK-8102.img
tests/images/Kenwood_TK-8180.img
@@ -474,12 +512,19 @@ tests/images/QYT_KT-WP12.img
tests/images/QYT_KT7900D.img
tests/images/QYT_KT8900D.img
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
tests/images/Radioddity_GM-30.img
+tests/images/Radioddity_GM-30_Plus.img
+tests/images/Radioddity_GM-30_Pro.img
+tests/images/Radioddity_GS-10B.img
tests/images/Radioddity_GS-5B.img
+tests/images/Radioddity_MU-5.img
tests/images/Radioddity_R2.img
tests/images/Radioddity_UV-5G.img
tests/images/Radtel_RT-470.img
@@ -491,17 +536,20 @@ tests/images/Radtel_RT-495.img
tests/images/Radtel_RT-620.img
tests/images/Radtel_RT-630.img
tests/images/Radtel_RT-730.img
+tests/images/Radtel_RT-880G.img
tests/images/Radtel_RT-900.img
tests/images/Radtel_RT-900_BT.img
tests/images/Radtel_RT-910.img
tests/images/Radtel_RT-910_BT.img
tests/images/Radtel_RT-920.img
tests/images/Radtel_T18.img
+tests/images/Retevis_C2.img
tests/images/Retevis_H777H_FRS.img
tests/images/Retevis_H777S.img
tests/images/Retevis_H777_V4.img
tests/images/Retevis_HA1G.img
tests/images/Retevis_HA1UV.img
+tests/images/Retevis_HA2.img
tests/images/Retevis_MA1.img
tests/images/Retevis_P2.img
tests/images/Retevis_P62.img
@@ -528,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
@@ -537,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
@@ -544,9 +594,11 @@ 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
+tests/images/Retevis_RT21H.img
tests/images/Retevis_RT22.img
tests/images/Retevis_RT22FRS.img
tests/images/Retevis_RT22S.img
@@ -566,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
@@ -573,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
@@ -581,7 +635,10 @@ tests/images/TDXone_TD-Q8A.img
tests/images/TIDRADIO_TD-H3.img
tests/images/TIDRADIO_TD-H8-GMRS.img
tests/images/TIDRADIO_TD-H8-HAM.img
+tests/images/TIDRADIO_TD-H8-HAM_G3.img
tests/images/TIDRADIO_TD-H8.img
+tests/images/TIDRADIO_TD-M11_16_PMR.img
+tests/images/TIDRADIO_TD-M11_22_FRS.img
tests/images/TYT_TH-350.img
tests/images/TYT_TH-7800.img
tests/images/TYT_TH-9800.img
@@ -592,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
@@ -616,6 +674,9 @@ tests/images/Wouxun_KG-UV9G_Pro.img
tests/images/Wouxun_KG-UV9K.img
tests/images/Wouxun_KG-UV9PX.img
tests/images/Wouxun_KG-UVD1P.img
+tests/images/Wouxun_KG-XS20G.img
+tests/images/Wouxun_KG-XS20G_Plus.img
+tests/images/Wouxun_KG-XS20H.img
tests/images/Yaesu_FT-1500M.img
tests/images/Yaesu_FT-1802M.img
tests/images/Yaesu_FT-1D_R.img
@@ -634,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
@@ -646,9 +708,14 @@ 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
+tests/images/Yaesu_VX-1.img
+tests/images/Yaesu_VX-150.img
tests/images/Yaesu_VX-177.img
tests/images/Yaesu_VX-2.img
tests/images/Yaesu_VX-3.img
@@ -658,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
@@ -665,58 +733,75 @@ tests/unit/rtcsv_ft3d.csv
tests/unit/rtcsv_ftm400.csv
tests/unit/rtcsv_ftm500.csv
tests/unit/test_alinco_clone.py
+tests/unit/test_amsats.py
tests/unit/test_bandplan.py
tests/unit/test_baofeng_fmradio.py
tests/unit/test_bitwise.py
+tests/unit/test_btech_docs.py
+tests/unit/test_checksum.py
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
+tests/unit/test_kenwood_tone.py
tests/unit/test_kguv8d.py
tests/unit/test_kguv920.py
tests/unit/test_logger.py
tests/unit/test_mappingmodel.py
tests/unit/test_network_sources.py
tests/unit/test_repeaterbook.py
+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
tests/unit/__pycache__/__init__.cpython-310.pyc
tests/unit/__pycache__/base.cpython-310.pyc
tests/unit/__pycache__/test_alinco_clone.cpython-310-pytest-7.1.3.pyc
+tests/unit/__pycache__/test_amsats.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_bandplan.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_baofeng_fmradio.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc
+tests/unit/__pycache__/test_btech_docs.cpython-310-pytest-7.1.3.pyc
+tests/unit/__pycache__/test_checksum.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_chirp_common.cpython-310-pytest-7.1.3.pyc
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
+tests/unit/__pycache__/test_kenwood_tone.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_kguv8d.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_kguv920.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_logger.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_mappingmodel.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_network_sources.cpython-310-pytest-7.1.3.pyc
tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc
+tests/unit/__pycache__/test_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 4b6b877..6589ff7 100644
--- a/chirp/__init__.py
+++ b/chirp/__init__.py
@@ -1 +1 @@
-CHIRP_VERSION = "next-20251108"
+CHIRP_VERSION = "next-20261030"
diff --git a/chirp/bandplan_iaru_r1.py b/chirp/bandplan_iaru_r1.py
index 4aecc54..02502bf 100644
--- a/chirp/bandplan_iaru_r1.py
+++ b/chirp/bandplan_iaru_r1.py
@@ -143,9 +143,40 @@ BANDS_10M = (
bandplan.Band((29520000, 29700000), "Wide band", step_khz=10, mode="NFM"),
)
+BANDS_6M = (
+ bandplan.Band((50000000, 54000000), "6 Meter Band"),
+ bandplan.Band((50000000, 50300000), "SSB", mode="USB"),
+ bandplan.Band((50300000, 50500000), "Narrow band modes, beacons"),
+ bandplan.Band((50500000, 52000000), "All modes"),
+ bandplan.Band((50500000, 50700000), "Digital communications", mode="DV"),
+ bandplan.Band((50700000, 50900000), "FM/DV repeater outputs",
+ input_offset=+500000, mode="FM"),
+ bandplan.Band((52000000, 54000000), "All modes"),
+)
+
+BANDS_4M = (
+ bandplan.Band((70000000, 70500000), "4 Meter Band"),
+)
+
+BANDS_2M = (
+ bandplan.Band((144000000, 146000000), "2 Meter Band"),
+ bandplan.Band((144100000, 144150000), "CW", mode="CW"),
+ bandplan.Band((144150000, 144400000), "SSB", mode="USB"),
+ bandplan.Band((144975000, 145806000), "FM", mode="FM"),
+ bandplan.Band((144975000, 145194000), "Repeater inputs", mode="FM"),
+ bandplan.Band((144575000, 145793500), "Repeater outputs", mode="FM",
+ input_offset=-600000),
+ )
+
+BANDS_70CM = (
+ bandplan.Band((430000000, 440000000), "70 Centimeter Band"),
+ bandplan.Band((434594000, 434981000), "Repeater outputs", mode="FM",
+ input_offset=-16000000),
+ )
+
BANDS = BANDS_2100M + BANDS_160M + BANDS_80M + BANDS_40M + BANDS_30M + \
BANDS_20M + BANDS_17M + BANDS_15M + BANDS_12M + BANDS_10M + \
- bandplan.BANDS_AIR
+ BANDS_6M + BANDS_4M + BANDS_2M + BANDS_70CM + bandplan.BANDS_AIR
# EU Analogue/DMR PMR446 Frequencies
diff --git a/chirp/bitwise.py b/chirp/bitwise.py
index 343bd96..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__)
@@ -115,12 +116,11 @@ def string_straight_decode(string):
return ''.join(chr(b) for b in string)
-def format_binary(nbits, value, pad=8):
- s = ""
- for i in range(0, nbits):
- s = "%i%s" % (value & 0x01, s)
- value >>= 1
- return "%s%s" % ((pad - len(s)) * ".", s)
+def format_binary(nbits, value, width=8, shift=0, padchar='.'):
+ padleft = width - shift
+ padright = width - padleft - nbits
+ bits = f'{value << shift:0{nbits}b}'[:nbits]
+ return f'{padleft * padchar}{bits}{padright * padchar}'
def bits_between(start, end):
@@ -151,21 +151,36 @@ def array_copy(dst, src):
dst[i].set_value(src[i])
-def bcd_to_int(bcd_array):
- """Convert an array of bcdDataElement like \x12\x34
- into an int like 1234"""
- value = 0
- for bcd in bcd_array:
- a, b = bcd.get_value()
- value = (value * 100) + (a * 10) + b
- return value
+def bbcd_to_dec(bbcd: int, packed=True) -> int:
+ """Convert a BE BCD int to decimal int. Usually for getting
+ user-friendly value from raw data.
+ For packed, 0x243 (0d579) -> 243.
+ For unpacked, 0x020403 (0d132099) -> 243."""
+ result = 0
+ bit_shift = 4 if packed else 8
+ dec_shift = 0
+ while bbcd > 0:
+ result += (bbcd & 0xF) * (10**dec_shift)
+ bbcd >>= bit_shift
+ dec_shift += 1
+ return result
-def int_to_bcd(bcd_array, value):
- """Convert an int like 1234 into bcdDataElements like "\x12\x34" """
- for i in reversed(range(0, len(bcd_array))):
- bcd_array[i].set_value(value % 100)
- value //= 100
+
+def dec_to_bbcd(dec: int, packed=True) -> int:
+ """Convert a decimal int to BE BCD int. Usually to set raw data from
+ user-friendly value.
+
+ For packed, 243 -> 0x243 (0d579).
+ For unpacked, 243 -> 0x020403 (0d132099)."""
+ result = 0
+ bit_shift_amount = 4 if packed else 8
+ bcd_shift = 0
+ while dec > 0:
+ result += (dec % 10) << bcd_shift
+ dec //= 10
+ bcd_shift += bit_shift_amount
+ return result
def numeric_str_to_bcd(bcdel, string, pad='0'):
@@ -292,7 +307,8 @@ class DataElement:
class arrayDataElement(DataElement):
def __repr__(self):
if isinstance(self.__items[0], bcdDataElement):
- return "%i:[(%i)]" % (len(self.__items), int(self))
+ hex = self.get_raw().hex().upper()
+ return "%i:[0x%s (%i)]" % (len(self.__items), hex, int(self))
if isinstance(self.__items[0], charDataElement):
return "%i:[(%s)]" % (len(self.__items), repr(str(self))[1:-1])
@@ -341,6 +357,8 @@ class arrayDataElement(DataElement):
# for non-ASCII values. On py2 we can just coerce all of these
# types to a string for compatibility.
return "".join([str(x.get_value()) for x in self.__items])
+ elif isinstance(self.__items[0], bcdDataElement):
+ return str(int(self))
else:
return str(self.__items)
@@ -352,8 +370,7 @@ class arrayDataElement(DataElement):
else:
items = reversed(self.__items)
for i in items:
- tens, ones = i.get_value()
- val = (val * 100) + (tens * 10) + ones
+ val = (val * 100) + int(i)
return val
else:
raise ValueError("Cannot coerce this to int")
@@ -710,8 +727,7 @@ class bcdDataElement(DataElement):
self._ignoremask = 0x00
def __int__(self):
- tens, ones = self.get_value()
- return (tens * 10) + ones
+ return bbcd_to_dec(self.get_value())
def set_bits(self, mask):
self._data[self._offset] = ord(self._data[self._offset]) | int(mask)
@@ -741,13 +757,17 @@ class bcdDataElement(DataElement):
def set_value(self, value):
preserve = self._data[self._offset][0] & self._ignoremask
self._data[self._offset] = (
- int("%02i" % value, 16) & ~self._ignoremask) | preserve
+ dec_to_bbcd(int(value) & 0xFF) & ~self._ignoremask) | preserve
def _get_value(self, data):
- data = data[0] & ~self._ignoremask
- a = (data & 0xF0) >> 4
- b = data & 0x0F
- return (a, b)
+ return data[0] & ~self._ignoremask
+
+ def __str__(self):
+ return str(int(self))
+
+ def __repr__(self):
+ hex = self.get_raw().hex().upper()
+ return f'0x{hex} ({int(self)})'
class lbcdDataElement(bcdDataElement):
@@ -764,8 +784,10 @@ class bitDataElement(intDataElement):
_subgen = u8DataElement # Default to a byte
def __repr__(self):
- fmt = "0x%%0%iX (%%sb)" % (self._size * 2)
- return fmt % (int(self), format_binary(self._nbits, self.get_value()))
+ size = self._subgen._size * 8
+ hex_len = size // 4
+ bits = format_binary(self._nbits, self.get_value(), size, self._shift)
+ return f'0x{int(self):0{hex_len}X} ({bits}b)'
def get_value(self):
data = self._subgen(self._data, self._offset).get_value()
@@ -783,6 +805,14 @@ class bitDataElement(intDataElement):
self._subgen(self._data, self._offset).set_value(value)
+ def get_bbcd(self) -> int:
+ """Get BE BCD as a user-friendly decimal. e.g. 0x243 (0d579) -> 243."""
+ return bbcd_to_dec(int(self))
+
+ def set_bbcd(self, decimal: int):
+ """Set decimal as stored BE BCD. e.g. 243 -> 0x243 (0d579)."""
+ self.set_value(dec_to_bbcd(int(decimal)))
+
def size(self):
return int(self._nbits)
@@ -791,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/checksum.py b/chirp/checksum.py
new file mode 100644
index 0000000..cd4d0d6
--- /dev/null
+++ b/chirp/checksum.py
@@ -0,0 +1,64 @@
+# Copyright 2008 Dan Smith <dsmith@danplanet.com>
+# Copyright 2023 Jacek Lipkowski <sq5bpf@lipkowski.org>
+# Copyright 2025 Thibaut Berg <thibaut.berg@hotmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# This is commonly called "xmodem CRC16"
+CRC_POLY_CCITT = 0x1021
+CRC_POLY_IBM_REV = 0xA001
+
+
+def crc16(data, poly, reverse=False):
+ crc = 0x0
+ for byte in data:
+ if reverse:
+ crc ^= byte
+ else:
+ crc ^= (byte << 8)
+ for _ in range(8):
+ if reverse:
+ if crc & 0x0001:
+ crc = (crc >> 1) ^ poly
+ else:
+ crc >>= 1
+ else:
+ crc = crc << 1
+ if crc & 0x10000:
+ crc = (crc ^ poly) & 0xFFFF
+ return crc & 0xFFFF
+
+
+def crc16_xmodem(data: bytes):
+ return crc16(data, CRC_POLY_CCITT)
+
+
+def crc16_ibm_rev(data):
+ return crc16(data, CRC_POLY_IBM_REV, reverse=True)
+
+
+def checksum_8bit(data, modulo=256):
+ """Calculate 8-bit checksum as sum of all bytes"""
+ cs = 0
+ for byte in data:
+ cs += byte
+ return cs % modulo
+
+
+def checksum_xor(data):
+ """Calculate checksum using XOR of all bytes"""
+ cs = 0
+ for byte in data:
+ cs ^= byte
+ return cs & 0xFF
diff --git a/chirp/chirp_common.py b/chirp/chirp_common.py
index a0d97be..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 = (
"",
@@ -644,14 +644,17 @@ class DVMemory(Memory):
self.dv_code = 0
-def FrozenMemory(source):
+def FrozenMemory(source, strict=True):
class _FrozenMemory(source.__class__):
def __init__(self, source):
self.__dict__['_frozen'] = False
for k, v in source.__dict__.items():
if k == '_frozen':
continue
- setattr(self, k, v)
+ try:
+ setattr(self, k, v)
+ except ValueError:
+ pass
self.__dict__['_frozen'] = True
for i in self.extra:
@@ -660,13 +663,17 @@ def FrozenMemory(source):
def __setattr__(self, k, v):
if self._frozen:
# This should really be an error, but we have a number of
- # drivers that make modifications during set_memory(). So this
- # just has to be a warning for now. Later it could turn into
- # a TypeError.
+ # drivers that make modifications during set_memory(). If we
+ # are not being strict, then we just log a warning.
caller = inspect.getframeinfo(inspect.stack()[1][0])
LOG.warning(
'%s@%i: Illegal set on attribute %s - Fix this driver!' % (
caller.filename, caller.lineno, k))
+ if strict:
+ raise errors.FrozenMemoryError(
+ _('Internal driver error: Attempt to modify '
+ 'frozen memory; Please report this as a bug using '
+ '"Report or update a bug" in the Help menu'))
super().__setattr__(k, v)
def dupe(self):
@@ -1067,9 +1074,32 @@ class RadioFeatures:
def __getitem__(self, name):
return self.__dict__[name]
+ @property
+ def concise_bands(self):
+ pp_range_strings = [
+ format_freq(lo).rstrip('0').rstrip('.') +
+ '-' +
+ format_freq(hi).rstrip('0').rstrip('.') +
+ 'MHz'
+ for lo, hi in self.valid_bands]
+ return ', '.join(pp_range_strings)
+
def validate_memory(self, mem):
"""Return a list of warnings and errors that will be encountered
- if trying to set @mem on the current radio"""
+ if trying to set @mem on the current radio.
+
+ An Error will abort the edit, while a Warning will allow it. Both
+ will show a message to the user. Use Errors to reject things that
+ need to be. A Warning is useful to alert the user that something
+ will be fixed/changed/coerced by the driver and that they should
+ expect it to look different than what they entered. Use these
+ sparingly as they can be very annoying to the user if they happen
+ on every edit.
+
+ NOTE: This method MAY NOT modify @mem in any way. It is not a hook
+ to make changes, it is for _validation_ of the memory before it is
+ sent to the driver's set_memory() method.
+ """
msgs = []
lo, hi = self.memory_bounds
@@ -1138,7 +1168,9 @@ class RadioFeatures:
if not valid:
msg = ValidationError(
("Frequency {freq} is out "
- "of supported range").format(freq=format_freq(mem.freq)))
+ "of supported ranges {ranges}").format(
+ freq=format_freq(mem.freq),
+ ranges=self.concise_bands))
msgs.append(msg)
if self.valid_bands and \
@@ -1188,6 +1220,13 @@ class RadioFeatures:
" not supported"))
break
+ if is_airband(mem.freq):
+ try:
+ fix_rounded_step(mem.freq)
+ except errors.InvalidDataError as e:
+ msgs.append(ValidationError(
+ '%s: %s' % (format_freq(mem.freq), e)))
+
return msgs
@@ -1469,12 +1508,20 @@ class DetectableInterface:
return extra + list(detected)
@classmethod
+ def is_detected(cls):
+ return getattr(cls, '_DETECTED_BY', None) is not None
+
+ @classmethod
def detect_model(cls, detected_cls):
detected_attr = class_detected_models_attribute(cls)
if getattr(cls, detected_attr, None) is None:
setattr(cls, detected_attr, [])
getattr(cls, detected_attr).append(detected_cls)
+ @classmethod
+ def is_minor_variant(cls):
+ return getattr(cls, '_MINOR_VARIANT', False)
+
class CloneModeRadio(FileBackedRadio, ExternalMemoryProperties,
DetectableInterface):
@@ -1508,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"""
+ 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
+ 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"""
@@ -1801,12 +1848,51 @@ def fix_rounded_step(freq):
if is_airband(freq):
# Airband can be 25kHz or 8.33kHz (25k / 3) steps
+ # https://en.wikipedia.org/wiki/Airband
if freq % 25000:
- # This must be 8.33kHz - find the closest 8.33k-aligned channel
- # and return that
+ # This must be 8.33kHz. The goal here is to find the closest
+ # 8.33k-aligned channel and return that.
+ # In the 8.33kHz channel scheme, there are "channel names" that
+ # look like 5kHz-aligned frequencies within the 25kHz regular
+ # channels, which don't match the actual frequency being used
+ # (which is 8.33kHz-aligned). We need to be able to detect those
+ # and return the correct actual frequency, as well as allow
+ # matching the actual frequencies themselves.
+
+ # The "base frequency" is the 25kHz-aligned channel frequency that
+ # has been divided into three 8.33kHz channels.
base = freq // 25000 * 25000
- channels = [base + (25000 // 3) * i for i in range(1, 4)]
+ orig = freq
+
+ # This is a channel name if it is 5kHz-aligned and equal-or-above
+ # the base frequency. Adjust down for the lower channel and up for
+ # the upper (no adjustment for the middle one) so that the channel
+ # matching below will find the right closest option.
+ ch_index = (freq - base) / 5000
+ if ch_index == 1.0:
+ # Lower of the three, bump down
+ freq -= (25000 // 3)
+ elif ch_index == 3.0:
+ # Upper of the three, bump up
+ freq += (25000 // 3)
+ elif ch_index >= 4.0 and ch_index == int(ch_index):
+ # This is 5kHz-aligned but not one of the three sub-channels,
+ # thus this is one of the gaps in the channel numbers. Refuse
+ # it so that it's clear to the user.
+ raise errors.InvalidDataError(
+ _('Aircraft frequencies must be aligned to 25kHz, 8.33kHz'
+ ', be or a valid channel'))
+
+ # These are the three possible 8.33kHz-aligned channels within
+ # this 25kHz block.
+ channels = [base + (25000 // 3) * i for i in range(0, 3)]
+
+ # Find the closest one to the original frequency
best = min(channels, key=lambda x: abs(x - freq))
+ LOG.debug('833: Orig %s Channels %s best %s adjusted %s diffs %s '
+ 'chindex %s' % (
+ orig, channels, best, freq,
+ [x - freq for x in channels], ch_index))
return best
else:
return freq
@@ -1892,17 +1978,17 @@ def to_kHz(val):
def from_GHz(val):
"""Convert @val in Hz to GHz"""
- return val // 100000000
+ return val // 1000000000
def from_MHz(val):
"""Convert @val in Hz to MHz"""
- return val // 100000
+ return val // 1000000
def from_kHz(val):
"""Convert @val in Hz to kHz"""
- return val // 100
+ return val // 1000
def split_to_offset(mem, rxfreq, txfreq):
diff --git a/chirp/cli/main.py b/chirp/cli/main.py
index 473ceee..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>
#
@@ -24,6 +24,8 @@ import logging
from chirp import logger
from chirp import chirp_common, errors, directory, util
+sys.modules['builtins']._ = lambda x: x # type: ignore[attr-defined]
+
directory.import_drivers()
LOG = logging.getLogger("chirpc")
diff --git a/chirp/directory.py b/chirp/directory.py
index 42871aa..f7685ec 100644
--- a/chirp/directory.py
+++ b/chirp/directory.py
@@ -77,6 +77,8 @@ def register(cls):
if not hasattr(cls, '_DETECTED_BY'):
cls._DETECTED_BY = None
+ if not hasattr(cls, '_MINOR_VARIANT'):
+ cls._MINOR_VARIANT = False
return cls
@@ -100,6 +102,19 @@ def detected_by(manager_class):
return wrapper
+def minorvariant(cls):
+ """Mark a class as too minor to distinguish from its parent.
+
+ Use this on registered classes that are very minor and used for
+ organization, but need not be exposed to the user as a separate offering.
+ Minor version differences of the same model, for example.
+ """
+ assert issubclass(cls, chirp_common.CloneModeRadio)
+
+ cls._MINOR_VARIANT = True
+ return cls
+
+
DRV_TO_RADIO = {}
RADIO_TO_DRV = {}
AUX_FORMATS = set()
diff --git a/chirp/drivers/__init__.py b/chirp/drivers/__init__.py
index a698ba5..309b25b 100644
--- a/chirp/drivers/__init__.py
+++ b/chirp/drivers/__init__.py
@@ -41,7 +41,7 @@ from chirp.drivers import gmrsv2
from chirp.drivers import h777
from chirp.drivers import hf90
from chirp.drivers import hg_uv98
-from chirp.drivers import alinco
+from chirp.drivers import tk11
from chirp.drivers import bj9900
from chirp.drivers import ic2100
from chirp.drivers import hobbypcb
@@ -106,6 +106,7 @@ from chirp.drivers import retevis_rt26
from chirp.drivers import retevis_rt76p
from chirp.drivers import retevis_rt87
from chirp.drivers import retevis_rt98
+from chirp.drivers import tdh8
from chirp.drivers import bjuv55
from chirp.drivers import rh5r_v2
from chirp.drivers import tdxone_tdq8a
@@ -126,7 +127,7 @@ from chirp.drivers import thuv1f
from chirp.drivers import tk270
from chirp.drivers import tk3140
from chirp.drivers import tk760
-from chirp.drivers import __init__
+from chirp.drivers import alinco
from chirp.drivers import tk8102
from chirp.drivers import tk8160
from chirp.drivers import tk8180
@@ -150,34 +151,52 @@ from chirp.drivers import vx510
from chirp.drivers import vx6
from chirp.drivers import vx7
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 kenwood_d7
+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 retevis_ra87
-from chirp.drivers import uvk5_egzumer
from chirp.drivers import tk481
from chirp.drivers import ict10
-from chirp.drivers import radioddity_gm30
+from chirp.drivers import uvk5
+from chirp.drivers import uvk5_cn
from chirp.drivers import icf520
-from chirp.drivers import tk280
+from chirp.drivers import retevis_ra86
+from chirp.drivers import retevis_ra87
+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 baofeng_uv17Pro
-from chirp.drivers import mml_jc8810
-from chirp.drivers import retevis_ra86
-from chirp.drivers import uvk5
+from chirp.drivers import uvk5_egzumer
+from chirp.drivers import ft8000r
from chirp.drivers import radtel_rt620
-from chirp.drivers import radtel_rt490
-from chirp.drivers import baofeng_digital
+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 tk690
from chirp.drivers import alinco_dr735t
-from chirp.drivers import yaesu_clone
+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 retevis_h777v4
-from chirp.drivers import iradio_uv_5118plus
+from chirp.drivers import radtel_rt880g
+from chirp.drivers import iradio_common
from chirp.drivers import radtel_rt900
-from chirp.drivers import tdh8
-from chirp.drivers import retevis_ha1g
-__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', 'alinco', 'bj9900', 'ic2100', 'hobbypcb', 'ic208', 'ic2300', 'ic2720', 'ic2200', 'ic2730', 'ic2820', 'ic9x_ll', 'ic9x', 'ic9x_icf', 'icf', 'ic9x_icf_ll', 'icomciv', 'icp7', 'icq7', 'ict8', 'icv80', 'ict70', 'ict7h', 'icv86', 'id51', 'icx90', 'icw32', 'icx8x', 'id31', 'id5100', 'id51plus', 'id800', 'id880', 'idrp', 'kg935g', 'kguv8d', 'iradio_uv_5118', 'kenwood_hmk', 'kenwood_itm', 'kenwood_live', 'kguv8e', 'kyd', 'kguv8dplus', 'kguv920pa', 'kguv980p', 'kguv9dplus', 'lt725uv', 'kyd_IP620', 'leixen', 'mursv1', 'puxing', 'ap510', 'puxing_px888k', 'radioddity_r2', 'radtel_t18', 'retevis_rb15', 'retevis_rb17p', 'retevis_rb28', 'retevis_rt1', 'retevis_rt21', 'retevis_rt22', 'retevis_rt23', 'retevis_rt26', 'retevis_rt76p', 'retevis_rt87', 'retevis_rt98', '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', '__init__', 'tk8102', 'tk8160', 'tk8180', 'tmd710', 'tmv71', 'tmv71_ll', 'ts2000', 'ts480', 'ts590', 'ts850', 'uv5r', 'uv5x3', 'uv6r', 'uvb5', 'vgc', 'vx170', 'vx2', 'vx3', 'vx5', 'vx510', 'vx6', 'vx7', 'vx8', 'wouxun', 'wouxun_common', 'kenwood_d7', 'ksun_m6', 'retevis_ra87', 'uvk5_egzumer', 'tk481', 'ict10', 'radioddity_gm30', 'icf520', 'tk280', 'baofeng_uv17', 'retevis_ra25', 'baofeng_uv17Pro', 'mml_jc8810', 'retevis_ra86', 'uvk5', 'radtel_rt620', 'radtel_rt490', 'baofeng_digital', 'ts790e', 'icm710', 'tk690', 'alinco_dr735t', 'yaesu_clone', 'retevis_h777v4', 'iradio_uv_5118plus', 'radtel_rt900', 'tdh8', 'retevis_ha1g']
+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 a53eaf1..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__)
@@ -99,11 +99,11 @@ class AlincoStyleRadio(chirp_common.CloneModeRadio):
resp = self._read(RLENGTH).strip()
if len(resp) == 0:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
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,14 +149,14 @@ 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)
def _upload(self, limit):
if not self._identify():
- raise Exception("I can't talk to this model")
+ raise errors.RadioError("I can't talk to this model")
for addr in range(0x100, limit, 16):
time.sleep(0.1)
@@ -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]
@@ -426,7 +430,7 @@ class DR135Radio(DRx35Radio):
_model = b"DR135"
_memsize = 4096
- _range = [(118000000, 173000000)]
+ _range = [(118000000, 174000000)]
@classmethod
def match_model(cls, filedata, filename):
@@ -541,9 +545,9 @@ class DJ175Radio(DRx35Radio):
_data = self._read(34).strip()
if len(_data) == 0:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
- data = codecs.decode(_data, 'hex')
+ data = binascii.unhexlify(_data)
if len(data) != 16:
LOG.debug("Response was:")
@@ -649,9 +653,9 @@ class AlincoDJG7(AlincoStyleRadio):
# data is encoded in hex, hence we read two chars per byte
_data = self._read(2+2*64+2).strip()
if len(_data) == 0:
- raise errors.RadioError("No response from radio")
+ 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/alinco_dr735t.py b/chirp/drivers/alinco_dr735t.py
index 17351ad..2fbb1eb 100644
--- a/chirp/drivers/alinco_dr735t.py
+++ b/chirp/drivers/alinco_dr735t.py
@@ -128,7 +128,7 @@ class AlincoDR735T(chirp_common.CloneModeRadio):
# expect DR735TN\r\n
radio_id = self.pipe.read(9).strip()
if not radio_id:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
LOG.debug('Model string is %s' % util.hexprint(radio_id))
return radio_id in (b"DR735TN", b"DR735TE")
@@ -199,6 +199,8 @@ class AlincoDR735T(chirp_common.CloneModeRadio):
def sync_in(self):
try:
self._mmap = self.do_download()
+ except errors.RadioError:
+ raise
except Exception as exc:
raise errors.RadioError(f"Failed to download from radio: {exc}")
self.process_mmap()
@@ -206,6 +208,8 @@ class AlincoDR735T(chirp_common.CloneModeRadio):
def sync_out(self):
try:
self.do_upload()
+ except errors.RadioError:
+ raise
except Exception as exc:
raise errors.RadioError(f"Failed to download from radio: {exc}")
diff --git a/chirp/drivers/anytone.py b/chirp/drivers/anytone.py
index 8ae7a39..16021bc 100644
--- a/chirp/drivers/anytone.py
+++ b/chirp/drivers/anytone.py
@@ -18,6 +18,7 @@ import logging
from chirp import bitwise
from chirp import chirp_common
+from chirp import checksum
from chirp import directory
from chirp import errors
from chirp import memmap
@@ -269,18 +270,11 @@ def _finish(radio):
raise errors.RadioError("Radio did not finish cleanly")
-def _checksum(data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
def _send(radio, cmd, addr, length, data=None):
frame = struct.pack(">cHb", cmd, addr, length)
if data:
frame += data
- frame += struct.pack('BB', _checksum(frame[1:]), 0x06)
+ frame += struct.pack('BB', checksum.checksum_8bit(frame[1:]), 0x06)
_echo_write(radio, frame)
LOG.debug("Sent:\n%s" % util.hexprint(frame))
if data:
@@ -304,7 +298,7 @@ def _send(radio, cmd, addr, length, data=None):
LOG.debug(" Length: %02x/%02x" % (length, _length))
LOG.debug(" Addr: %04x/%04x" % (addr, _addr))
raise errors.RadioError("Radio send unexpected block")
- cs = _checksum(result[1:-2])
+ cs = checksum.checksum_8bit(result[1:-2])
if cs != result[-2]:
LOG.debug("Calculated: %02x" % cs)
LOG.debug("Actual: %02x" % result[-2])
diff --git a/chirp/drivers/anytone778uv.py b/chirp/drivers/anytone778uv.py
index 0f7f18f..56196cd 100644
--- a/chirp/drivers/anytone778uv.py
+++ b/chirp/drivers/anytone778uv.py
@@ -39,7 +39,7 @@
# * probably other things too - like things encoded by the unknown bits in the
# memory struct
-from chirp import chirp_common, directory, memmap, errors, util
+from chirp import chirp_common, directory, memmap, errors, util, checksum
from chirp import bitwise
from chirp.settings import RadioSettingGroup, RadioSetting, \
RadioSettingValueBoolean, RadioSettingValueList, \
@@ -328,12 +328,6 @@ def get_band_limits_Hz(limit_value):
# Calculate the checksum used in serial packets
-def checksum(message_bytes):
- mask = 0xFF
- checksum = 0
- for b in message_bytes:
- checksum = (checksum + b) & mask
- return checksum
# Send a command to the radio, return any reply stripping the echo of the
@@ -404,6 +398,9 @@ def enter_program_mode(serial):
# place the radio in program mode, and confirm
program_response = send_serial_command(serial, b'PROGRAM')
+ if not program_response:
+ raise errors.RadioNoResponse()
+
if program_response != b'QX\x06':
raise errors.RadioError('No initial response from radio.')
LOG.debug('entered program mode')
@@ -434,9 +431,13 @@ def exit_program_mode(serial):
# Parse a packet from the radio returning the header (R/W, address, data, and
# checksum valid
def parse_read_response(resp):
+ if not resp:
+ raise errors.RadioNoResponse()
+ if len(resp) < 6:
+ raise errors.RadioError('Short read response from radio')
addr = resp[:4]
data = bytes(resp[4:-2])
- cs = checksum(d for d in resp[1:-2])
+ cs = checksum.checksum_8bit(d for d in resp[1:-2])
valid = cs == resp[-2]
if not valid:
LOG.error('checksumfail: %02x, expected %02x' % (cs, resp[-2]))
@@ -498,7 +499,7 @@ def do_download(radio):
def make_write_data_cmd(addr, data, datalen):
cmd = struct.pack('>BHB', 0x57, addr, datalen)
cmd += data
- cs = checksum(c for c in cmd[1:])
+ cs = checksum.checksum_8bit(c for c in cmd[1:])
cmd += struct.pack('>BB', cs, 0x06)
return cmd
diff --git a/chirp/drivers/anytone_ht.py b/chirp/drivers/anytone_ht.py
index 1775553..a3eefd6 100644
--- a/chirp/drivers/anytone_ht.py
+++ b/chirp/drivers/anytone_ht.py
@@ -18,6 +18,7 @@ import logging
from chirp import bitwise
from chirp import chirp_common
+from chirp import checksum
from chirp import directory
from chirp import errors
from chirp import memmap
@@ -258,9 +259,11 @@ def _ident(radio):
radio.pipe.timeout = 1
_echo_write(radio, b"PROGRAM")
response = radio.pipe.read(3)
+ if not response:
+ raise errors.RadioNoResponse()
if response != b"QX\x06":
LOG.debug("Response was:\n%s" % util.hexprint(response))
- raise errors.RadioError("Radio did not respond. Check connection.")
+ raise errors.RadioError("Unexpected response from radio")
_echo_write(radio, b"\x02")
response = radio.pipe.read(16)
LOG.debug(util.hexprint(response))
@@ -278,18 +281,11 @@ def _finish(radio):
raise errors.RadioError("Radio did not finish cleanly")
-def _checksum(data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
def _send(radio, cmd, addr, length, data=None):
frame = struct.pack(">cHb", cmd, addr, length)
if data:
frame += data
- frame += bytes([_checksum(frame[1:])])
+ frame += bytes([checksum.checksum_8bit(frame[1:])])
frame += b"\x06"
_echo_write(radio, frame)
LOG.debug("Sent:\n%s" % util.hexprint(frame))
@@ -314,7 +310,7 @@ def _send(radio, cmd, addr, length, data=None):
LOG.debug(" Length: %02x/%02x" % (length, _length))
LOG.debug(" Addr: %04x/%04x" % (addr, _addr))
raise errors.RadioError("Radio send unexpected block")
- cs = _checksum(result[1:-2])
+ cs = checksum.checksum_8bit(result[1:-2])
if cs != result[-2]:
LOG.debug("Calculated: %02x" % cs)
LOG.debug("Actual: %02x" % result[-2])
diff --git a/chirp/drivers/anytone_iii.py b/chirp/drivers/anytone_iii.py
index 4f33d26..66c57df 100644
--- a/chirp/drivers/anytone_iii.py
+++ b/chirp/drivers/anytone_iii.py
@@ -19,6 +19,7 @@ import string
from chirp import bitwise
from chirp import chirp_common
+from chirp import checksum
from chirp import directory
from chirp import errors
from chirp import memmap
@@ -567,18 +568,11 @@ def _finish(radio):
raise errors.RadioError("Radio did not finish cleanly")
-def _checksum(data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
def _send(radio, cmd, addr, length, data=None):
frame = struct.pack(">cHb", cmd, addr, length)
if data:
frame += data
- frame += bytes([_checksum(frame[1:])])
+ frame += bytes([checksum.checksum_8bit(frame[1:])])
frame += b"\x06"
_echo_write(radio, frame)
LOG.debug("Sent:\n%s" % util.hexprint(frame))
@@ -603,7 +597,7 @@ def _send(radio, cmd, addr, length, data=None):
LOG.debug(" Length: %02x/%02x" % (length, _length))
LOG.debug(" Addr: %04x/%04x" % (addr, _addr))
raise errors.RadioError("Radio send unexpected block")
- cs = _checksum(result[1:-2])
+ cs = checksum.checksum_8bit(result[1:-2])
if cs != result[-2]:
LOG.debug("Calculated: %02x" % cs)
LOG.debug("Actual: %02x" % result[-2])
@@ -798,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)
]
@@ -1127,7 +1125,7 @@ class AnyTone5888UVIIIRadio(chirp_common.CloneModeRadio,
_mem.offset = mem.offset / 100
if is_hyper_chan:
- mem.name = SEVEN_SPACES
+ _mem.name = SEVEN_SPACES
else:
_mem.name = mem.name.ljust(7)
@@ -2036,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/ap510.py b/chirp/drivers/ap510.py
index 6cf9347..81dee46 100644
--- a/chirp/drivers/ap510.py
+++ b/chirp/drivers/ap510.py
@@ -63,7 +63,7 @@ def enter_setup(pipe):
return True
elif s and "SETUP" in s:
return False
- raise errors.RadioError('Radio did not respond.')
+ raise errors.RadioNoResponse()
def download(radio):
diff --git a/chirp/drivers/ar8200.py b/chirp/drivers/ar8200.py
new file mode 100644
index 0000000..e0e9097
--- /dev/null
+++ b/chirp/drivers/ar8200.py
@@ -0,0 +1,1698 @@
+# Copyright 2026 Darius Rad <alpha@area49.net>
+#
+# 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 logging
+import re
+import threading
+import time
+
+from chirp import chirp_common, errors, directory
+from chirp.settings import RadioSetting, RadioSettingGroup, \
+ RadioSettingSubGroup, RadioSettingValueBoolean, RadioSettingValueFloat, \
+ RadioSettingValueInteger, RadioSettingValueList, RadioSettingValueMap, \
+ RadioSettingValueString, RadioSettings
+
+LOG = logging.getLogger(__name__)
+
+# CHANNEL NUMBERING
+#
+# CHIRP identifies memories with sequentially numbered indices. The
+# memory locations in the AR8200 are mapped to CHIRP memories as
+# follows.
+#
+# Memories 0 through 999
+#
+# Scan memories by bank: A, a, B, b, ... J, j. Each pair of banks
+# (A and a, B and b, etc.) occupies 100 channels. The split between
+# the banks in the pair is determined by the bank size configured
+# under settings.
+#
+# Memories 1000 through 1999
+#
+# Scan pass frequencies by bank: A, a, B, b, ... J, j. There are 50
+# pass frequencies per bank.
+#
+# Memories 2000 through 2099
+#
+# VFO pass frequencies.
+#
+# Memories 2100 through 2139
+#
+# One channel per search bank: A through T, then a through t.
+#
+# Special channels
+#
+# VFO: Single VFO mode channel configuration
+# VFO-A and VFO-B: Twin VFO mode channel configuration
+# QM0 through QM9: VFO quick memories
+
+# ISSUES AND LIMITATIONS
+#
+# After adjusting any of the following settings, it is necessary to
+# refresh certain other memory locations:
+#
+# - Bank split size
+# - Add or remove search pass frequencies
+# - Change offset frequencies
+# - Removing channels from select scan list
+#
+# The radio supports three AM modes, but CHIRP only knows about two.
+# Mode is set to AM for all, and an extra field specifies which AM
+# mode is used.
+#
+# Search pass frequencies cannot be modified, they can only be added
+# or removed. When a pass frequency is removed, all others in the
+# same search bank are moved up.
+#
+# This driver does not provide a bank model because (1) CHIRP does not
+# support banks for live radios, and (2) the banks on the radio don't
+# easily map to the bank model provided by CHIRP.
+#
+# Quick memory channel details beyond the frequency are not available,
+# as reading this from the serial port is not supported.
+#
+# Adding to the select scan list is not supported over the serial
+# port.
+#
+# Auto mode also lets the radio control duplex and offset, tuning
+# step, and step adjust.
+#
+# Radio must be power cycled after using CHIRP. The serial protocol
+# supports a command to terminate the session and release the keypad,
+# but there is no suitable place in CHIRP to make this call. By the
+# time the __del__ method is called, the serial port is already
+# closed.
+#
+# Radio supports additional characters not presently reflected in the
+# valid character set, including arrows, Japanese characters (yen,
+# katakana), Greek letters, other European letters and accents, and
+# math symbols.
+
+
+@directory.register
+class AR8200Radio(chirp_common.LiveRadio):
+ """AOR AR8200"""
+ BAUD_RATE = 19200
+ VENDOR = "AOR"
+ MODEL = "AR8200"
+
+ # These need to match the indices of the MD command.
+ _MODES = [('WFM', 0), ('FM', 1), ('AM', 2), ('USB', 3), ('LSB', 4),
+ ('CW', 5), ('NFM', 6), ('WAM', 7), ('NAM', 8), ('Auto', 0xf)]
+
+ _AM_MODES = ['AM', 'WAM', 'NAM']
+
+ _SCAN_MEMORIES = 1000
+ _SEARCH_PASS_MEMORIES = 1100
+ _SCAN_BANKS = 'AaBbCcDdEeFfGgHhIiJj'
+ _SEARCH_BANKS = 'ABCDEFGHIJKLMNOPQRSTabcdefghijklmnopqrst'
+
+ _SPECIAL_CHANS = {
+ 'VFO': -13,
+ 'VFO-A': -12,
+ 'VFO-B': -11,
+ 'QM0': -10,
+ 'QM1': -9,
+ 'QM2': -8,
+ 'QM3': -7,
+ 'QM4': -6,
+ 'QM5': -5,
+ 'QM6': -4,
+ 'QM7': -3,
+ 'QM8': -2,
+ 'QM9': -1}
+
+ # Skip reading settings that require selecting each stored memory
+ # channel, which significantly slows download time.
+ _SKIP_SELECT = False
+
+ _upper = _SCAN_MEMORIES + _SEARCH_PASS_MEMORIES + len(_SEARCH_BANKS) - 1
+
+ _scan_bank_sizes = {}
+ _GS = None
+ _OL_LIST = None
+ _GR_LIST = None
+ _command_cache = {}
+
+ _rf = None
+
+ def __init__(self, *args, **kwargs):
+ chirp_common.LiveRadio.__init__(self, *args, **kwargs)
+
+ self._memcache = {}
+ self.LOCK = threading.Lock()
+
+ if self.pipe:
+ self.pipe.timeout = 2
+ self.pipe.stopbits = 2
+ self._pipe_reset()
+ if not self._connect():
+ raise Exception("Error connecting to radio")
+
+ # set VFO mode because documentation says not to run MX
+ # command (write data) while scanning or searching
+ self._command('VF')
+
+ # set squelch closed to avoid noise while changing channels
+ self._command('MC1')
+
+ def get_features(self):
+ if self._rf:
+ return self._rf
+
+ rf = chirp_common.RadioFeatures()
+ rf.has_dtcs = False
+ rf.has_dtcs_polarity = False
+ rf.has_bank = False
+ rf.has_ctone = False
+ rf.has_cross = False
+ rf.has_nostep_tuning = True
+ rf.has_settings = True
+
+ rf.valid_modes = ['WFM', 'FM', 'AM', 'USB', 'LSB', 'CW', 'NFM', 'Auto']
+ rf.valid_bands = [(100000, 2040000000)]
+ rf.valid_skips = ['', 'S']
+ rf.valid_characters = chirp_common.CHARSET_ASCII
+ rf.valid_name_length = 12
+ rf.valid_special_chans = list(self._SPECIAL_CHANS.keys())
+ rf.valid_tones = []
+
+ rf.memory_bounds = (0, self._upper)
+
+ self._rf = rf
+ return rf
+
+ def _decode_number(self, number):
+ if number < -10:
+ if number in list(self._SPECIAL_CHANS.values()):
+ return ('vfo', None, number)
+
+ return (None, None, None)
+
+ if number < 0:
+ return ('qm', None, number + 10)
+
+ if number < self._SCAN_MEMORIES:
+ bank = (number // 100) * 2
+ chan = number % 100
+
+ if chan >= self._scan_bank_size(self._SCAN_BANKS[bank]):
+ chan = chan - self._scan_bank_size(self._SCAN_BANKS[bank])
+ bank += 1
+
+ return ('scan', self._SCAN_BANKS[bank], chan)
+
+ number -= self._SCAN_MEMORIES
+
+ if number < self._SEARCH_PASS_MEMORIES:
+ if number > len(self._SEARCH_BANKS) * 50:
+ bank = 'V'
+ chan = number - len(self._SEARCH_BANKS) * 50
+ else:
+ bank = self._SEARCH_BANKS[number // 50]
+ chan = number % 50
+ return ('pass', bank, chan)
+
+ number -= self._SEARCH_PASS_MEMORIES
+
+ if number < len(self._SEARCH_BANKS):
+ return ('search', self._SEARCH_BANKS[number], None)
+
+ return (None, None, None)
+
+ def _encode_number(self, region, bank, chan):
+
+ if region == 'vfo':
+ return self._SPECIAL_CHANS.get(chan, None)
+
+ elif region == 'qm':
+ return chan - 10 if chan < 10 else None
+
+ elif region == 'scan':
+ if bank not in self._SCAN_BANKS or \
+ chan >= self._scan_bank_size(bank):
+ return None
+
+ offset = 100 * (self._SCAN_BANKS.index(bank) // 2)
+ if bank.islower():
+ offset += self._scan_bank_size(bank.upper())
+
+ return offset + chan
+
+ elif region == 'pass':
+ if bank == 'V':
+ offset = self._SCAN_MEMORIES + len(self._SEARCH_BANKS) * 50
+ size = 100
+ elif bank in self._SEARCH_BANKS:
+ offset = self._SCAN_MEMORIES + \
+ self._SEARCH_BANKS.index(bank) * 50
+ size = 50
+
+ return offset + chan if chan < size else None
+
+ elif region == 'search':
+ if bank not in self._SEARCH_BANKS:
+ return None
+
+ return self._SCAN_MEMORIES + self._SEARCH_PASS_MEMORIES + \
+ self._SEARCH_BANKS.index(bank)
+
+ return None
+
+ def _connect(self):
+ """Connect to the radio"""
+ bauds = [19200, 9600, 4800]
+
+ for b in bauds:
+ self.pipe.baudrate = b
+
+ self._command('', '[?]')
+
+ # no real detection mechanism, to just try the VR command
+ res = self._command('VR', 'VR([0-9]+)')
+ if res:
+ return True
+
+ raise errors.RadioError("No response from radio")
+
+ def _pipe_reset(self):
+ self.pipe.reset_input_buffer()
+ self.pipe.reset_output_buffer()
+ self.pipe.write('\r'.encode('ascii'))
+ self.pipe.readline()
+
+ def _command(self, cmd, pattern='$', lines=1, cache=False,
+ varlist=False, retries=5, timeout=None):
+ retry_wait = .25
+ cmd += '\r'
+ old_timeout = None
+
+ if timeout is not None:
+ old_timeout = self.pipe.timeout
+ self.pipe.timeout = timeout
+
+ if cache:
+ pattern = '([A-Za-z0-9]+) (?:(?P<empty>---)$|.*)'
+
+ for retry in range(retries):
+ self.pipe.write(cmd.encode('ascii'))
+ LOG.debug("tx {}".format(cmd.strip()))
+
+ for n in range(lines if cache else 1):
+ res = self.pipe.readline().decode('ascii', errors='replace')
+ res = res.strip()
+ LOG.debug("rx {}".format(res))
+
+ m = re.match(pattern, res)
+ if not m:
+ LOG.error("Unexpected response from radio: {} -> {}"
+ "".format(cmd.strip(), res))
+ break
+
+ if cache:
+ if varlist and m['empty']:
+ m = True
+ break
+
+ if m.lastindex > 0:
+ LOG.debug("command cache {} -> {}".format(m[1], m[0]))
+ self._command_cache[m[1]] = m[0]
+ else:
+ if cache:
+ m = True
+
+ else:
+ for n in range(lines - 1):
+ res = self.pipe.readline().strip()
+ LOG.debug("rx {}".format(res))
+
+ if m:
+ break
+
+ LOG.debug("Retrying...")
+ time.sleep(retry_wait)
+ retry_wait *= 2
+ retry_wait = min(retry_wait, 5)
+ self._pipe_reset()
+ else:
+ m = None
+
+ if old_timeout is not None:
+ self.pipe.timeout = old_timeout
+
+ return m
+
+ def _command_read_WM(self, bank, retries=5):
+ retry_wait = .25
+
+ cmd = 'WM{}\r'.format(bank)
+
+ for n in range(retries):
+ self.pipe.write(cmd.encode('ascii'))
+ LOG.debug("tx {}".format(cmd.strip()))
+
+ ret = ()
+ for b in (bank, bank.lower()):
+ res = self.pipe.readline().decode('ascii', errors='replace')
+ res = res.strip()
+ LOG.debug("rx {}".format(res))
+
+ mat = re.match('WM ([A-Ja-j])([01])', res)
+ if not mat or mat[1] != b:
+ LOG.error("Unexpected response from radio: {} -> {}"
+ "".format(cmd.strip(), res))
+ break
+
+ ret += (bool(int(mat[2])),)
+ else:
+ return ret
+
+ LOG.debug("Retrying...")
+ time.sleep(retry_wait)
+ retry_wait *= 2
+ retry_wait = min(retry_wait, 5)
+ self._pipe_reset()
+
+ return None
+
+ def _command_update_cache(self, cmd, lines=10, varlist=False, retries=5):
+ return self._command(cmd=cmd, lines=lines, cache=True,
+ varlist=varlist, retries=retries)
+
+ def _command_delete_cache(self, key, pattern=False):
+ if not pattern:
+ self._command_cache.pop(key, None)
+
+ else:
+ r = re.compile(key)
+ for k in list(filter(r.match, self._command_cache.keys())):
+ self._command_cache.pop(k, None)
+
+ def _command_cached(self, key, pattern, retries=5):
+ retry_wait = .25
+
+ for n in range(retries):
+ if key not in self._command_cache:
+ cmd = re.match('(OL|MX|QM|GM|GS|PR|GR)', key)
+ if not cmd:
+ LOG.debug("Response not found in cache: {}".format(key))
+ return None
+
+ if cmd[1] == 'OL':
+ for n in range(5):
+ self._command_update_cache('OL')
+
+ elif cmd[1] == 'MX':
+ bank = key[2]
+ size = self._scan_bank_size(bank)
+ self._command_update_cache('MA{}'.format(bank))
+ for n in range(-(size // -10) - 1):
+ self._command_update_cache('MA')
+
+ elif cmd[1] == 'QM':
+ self._command_update_cache('QM')
+
+ elif cmd[1] in ('GM', 'GS'):
+ self._command_update_cache(cmd[1], 2)
+
+ elif cmd[1] == 'PR':
+ for n in range(100 if key[2] == 'V' else 50):
+ cachekey = '{}{:02d}'.format(key[:3], n)
+ val = '{} ---'.format(cachekey)
+ self._command_cache[cachekey] = val
+
+ self._command_update_cache(
+ key[:3], 100 if key[2] == 'V' else 50, varlist=True)
+
+ elif cmd[1] == 'GR':
+ self._command_update_cache('GR', 100, varlist=True)
+
+ else:
+ LOG.debug("Response not found in cache: {}".format(key))
+ return None
+
+ if key in self._command_cache:
+ res = re.match(pattern, self._command_cache[key])
+ if res:
+ return res
+
+ LOG.debug("Unexpected result from radio {}"
+ "".format(self._command_cache[key]))
+ del self._command_cache[key]
+ else:
+ LOG.debug("Response not found in cache: {}".format(key))
+
+ LOG.debug("Retrying...")
+ time.sleep(retry_wait)
+ retry_wait *= 2
+
+ return None
+
+ def _scan_bank_size(self, bank):
+ if bank not in self._SCAN_BANKS:
+ return None
+
+ if bank.upper() not in self._scan_bank_sizes:
+ res = self._command('MW{}'.format(bank.upper()),
+ 'MW [A-J]:([1-9]0) [a-j]:([1-9]0)')
+ self._scan_bank_sizes[bank.upper()] = int(res[1])
+
+ if bank.isupper():
+ return self._scan_bank_sizes[bank]
+ else:
+ return 100 - self._scan_bank_sizes[bank.upper()]
+
+ def _get_ol_list_uncached(self):
+ self._OL_LIST = [0]
+ for n in range(1, 48):
+ res = self._command_cached('OL{:02d}'.format(n),
+ 'OL([0-4][0-9]) RF(0[0-9]{7}00)')
+
+ if n != int(res[1]):
+ raise errors.RadioError(
+ "Unexpected result returned from radio")
+
+ self._OL_LIST.append(int(res[2]))
+ LOG.info("Offset frequency {} is {}".format(n, res[2]))
+
+ return self._OL_LIST
+
+ def _get_ol_list(self, locked=False):
+ if self._OL_LIST:
+ return self._OL_LIST
+
+ if locked:
+ with self.LOCK:
+ return self._get_ol_list_uncached()
+ else:
+ return self._get_ol_list_uncached()
+
+ def _set_pp(self, number):
+ (region, bank, chan) = self._decode_number(number)
+ self._command('PP{}{:02d}'.format(bank, chan))
+
+ def _get_gr_list(self):
+ if isinstance(self._GR_LIST, list):
+ return self._GR_LIST
+
+ self._GR_LIST = []
+
+ for n in range(100):
+ res = self._command_cached(
+ 'GR{:02d}'.format(n),
+ ('GR(?P<num>[0-9]{2}) (?:(?P<empty>---)$|'
+ 'MX(?P<bank>[A-Ja-j])(?P<chan>[0-9]{2}))'))
+ if not res:
+ break
+
+ if n != int(res['num']):
+ raise errors.RadioError(
+ "Unexpected result returned from radio")
+
+ self._GR_LIST.append((res['bank'], int(res['chan'])))
+ LOG.info("Select scan entry {} is {}{:02d}"
+ "".format(n, res['bank'], int(res['chan'])))
+
+ return self._GR_LIST
+
+ def _save_gs(self):
+ if self._GS:
+ return
+
+ res = self._command('GS', 'GS([0-9])', 2)
+ self._GS = int(res[1])
+
+ def _restore_gs(self):
+ self._command('GS{}'.format(self._GS))
+
+ def _invalidate_scan_bank_size(self):
+ self._scan_bank_sizes = {}
+
+ def _invalidate_ol_list(self):
+ self._OL_LIST = None
+ self._command_delete_cache('OL([0-9]{2})', True)
+
+ def _invalidate_gr_list(self):
+ self._GR_LIST = None
+ self._command_delete_cache('GR([0-9]{2})', True)
+
+ def _invalidate_memory(self, region=None, bank=None, chan=None,
+ number=None, emptyonly=False):
+
+ if number is not None:
+ (region, bank, chan) = self._decode_number(number)
+ else:
+ number = self._encode_number(region, bank, chan)
+
+ if number in self._memcache:
+ if emptyonly and not self._memcache[number].empty:
+ return
+ del self._memcache[number]
+
+ if region == 'qm':
+ self._command_delete_cache('QM{:1d}'.format(chan), True)
+
+ elif region == 'scan':
+ self._command_delete_cache('MX{}{:02d}'.format(bank, chan), True)
+
+ elif region == 'pass':
+ self._command_delete_cache('PR{}{:02d}'.format(bank, chan), True)
+
+ elif region == 'search':
+ # commands not cached
+ pass
+
+ def get_memory(self, number):
+ if number in self._memcache:
+ return self._memcache[number]
+
+ with self.LOCK:
+ return self._get_memory_unlocked(number)
+
+ def _get_memory_unlocked(self, number):
+ mem = chirp_common.Memory()
+
+ mem.extra = RadioSettingGroup('extra', 'Extra')
+
+ AM_LIST = ['AM', 'NAM', 'WAM']
+ extra_am = RadioSettingValueList(AM_LIST)
+ rs = RadioSetting('am', 'AM Mode', extra_am)
+ mem.extra.append(rs)
+
+ lv = min(list(zip(*self._rf.valid_bands))[0]) / 1000000
+ uv = max(list(zip(*self._rf.valid_bands))[1]) / 1000000
+ extra_upper = RadioSettingValueFloat(lv, uv, lv, 0.00005, 5)
+ rs = RadioSetting('upper', 'Upper Frequency', extra_upper)
+ mem.extra.append(rs)
+
+ extra_adjust = RadioSettingValueFloat(0, 999.95, 0, 0.05, 2)
+ rs = RadioSetting('adjust', 'Step Adjust', extra_adjust)
+ mem.extra.append(rs)
+
+ extra_att = RadioSettingValueBoolean(False)
+ rs = RadioSetting('att', 'Attenuator', extra_att)
+ mem.extra.append(rs)
+
+ extra_limit = RadioSettingValueBoolean(False)
+ rs = RadioSetting('limit', 'Noise Limiter', extra_limit)
+ mem.extra.append(rs)
+
+ extra_protect = RadioSettingValueBoolean(False)
+ rs = RadioSetting('protect', 'Protect', extra_protect)
+ mem.extra.append(rs)
+
+ extra_select = RadioSettingValueBoolean(False)
+ rs = RadioSetting('select', 'Select Scan', extra_select)
+ mem.extra.append(rs)
+
+ extra_selectindex = RadioSettingValueInteger(0, 99, 0)
+ rs = RadioSetting('selectindex', 'Select Scan Index',
+ extra_selectindex)
+ mem.extra.append(rs)
+
+ if isinstance(number, str):
+ mem.number = self._SPECIAL_CHANS[number]
+ mem.extd_number = number
+ else:
+ mem.number = number
+
+ (region, bank, chan) = self._decode_number(mem.number)
+ if region is None:
+ raise errors.InvalidMemoryLocation(
+ "No such memory {}".format(number))
+
+ if region == 'vfo':
+ if chan == self._SPECIAL_CHANS['VFO']:
+ self._command('VF')
+ mem.name = 'VFO'
+ elif chan == self._SPECIAL_CHANS['VFO-A']:
+ self._command('VA')
+ mem.name = 'VFO-A'
+ elif chan == self._SPECIAL_CHANS['VFO-B']:
+ self._command('VB')
+ mem.name = 'VFO-B'
+
+ ol_list = self._get_ol_list()
+
+ res = self._command(
+ 'RX',
+ ('V[ABF] RF(?P<freq>[0-9]{10}) '
+ 'ST(?P<step>[0-9]{6})(?P<adjust>[+]?) AU(?P<auto>[01]) '
+ 'MD(?P<mode>[0-8]) AT(?P<att>[01])'))
+ if not res:
+ pass
+ else:
+ mem.freq = int(res['freq'])
+
+ if int(res['auto']):
+ mem.mode = 'Auto'
+ else:
+ radio_mode = [mode[0] for mode in self._MODES
+ if mode[1] == int(res['mode'])][0]
+ if radio_mode in self._AM_MODES:
+ mem.mode = 'AM'
+ extra_am.set_value(radio_mode)
+ else:
+ mem.mode = radio_mode
+
+ mem.tuning_step = float(res['step']) / 1000
+
+ extra_att.set_value(int(res['att']))
+
+ res = self._command('OF', 'OF([0-4][0-9])([ +-])')
+ mem.offset = ol_list[int(res[1])] if res else 0
+ mem.duplex = res[2] if res and res[2] in ('+', '-') else ''
+
+ res = self._command('SH', 'SH([0-9]{6})([+]?)')
+ if res:
+ extra_adjust.set_value(
+ int(res[1]) / 1000 if res[2] == '+' else 0)
+
+ res = self._command('NL', 'NL([01])')
+ if res:
+ extra_limit.set_value(int(res[1]))
+
+ extra_protect.set_mutable(False)
+ extra_upper.set_mutable(False)
+
+ mem.immutable += ['name', 'skip', 'extra.upper', 'extra.protect',
+ 'extra.select']
+
+ elif region == 'qm':
+ res = self._command_cached('QM{:1d}'.format(chan),
+ 'QM([0-9]) RF([0-9]{10})')
+ if not res:
+ mem.empty = True
+ else:
+ if chan != int(res[1]):
+ raise errors.RadioError(
+ "Unexpected result returned from radio")
+
+ mem.freq = int(res[2])
+ mem.name = 'QM{:1d}'.format(chan)
+
+ extra_am.set_mutable(False)
+ extra_upper.set_mutable(False)
+ extra_adjust.set_mutable(False)
+ extra_att.set_mutable(False)
+ extra_limit.set_mutable(False)
+ extra_protect.set_mutable(False)
+
+ mem.immutable += ['empty', 'freq', 'name', 'offset', 'mode',
+ 'tuning_step', 'skip', 'duplex', 'extra.upper',
+ 'extra.adjust', 'extra.att', 'extra.limit',
+ 'extra.protect', 'extra.select']
+
+ elif region == 'scan':
+ ol_list = self._get_ol_list()
+ gr_list = self._get_gr_list()
+
+ res = self._command_cached(
+ 'MX{}{:02d}'.format(bank, chan),
+ ('MX(?P<bank>[A-Ja-j])(?P<chan>[0-9]{2}) '
+ '(?:(?P<empty>---)$|MP(?P<pass>[01]) RF(?P<freq>[0-9]{10}) '
+ 'ST(?P<step>[0-9]{6})(?P<adjust>[+]?) AU(?P<auto>[01]) '
+ 'MD(?P<mode>[0-8]) AT(?P<att>[01]) TM(?P<name>.{0,12}))'))
+ if not res:
+ pass
+ elif res['empty']:
+ mem.empty = True
+ else:
+ if res['bank'] != bank or int(res['chan']) != chan:
+ raise errors.RadioError(
+ "Unexpected result returned from radio")
+
+ mem.freq = int(res['freq'])
+ mem.name = res['name']
+
+ if int(res['auto']):
+ mem.mode = 'Auto'
+ else:
+ radio_mode = [mode[0] for mode in self._MODES
+ if mode[1] == int(res['mode'])][0]
+ if radio_mode in self._AM_MODES:
+ mem.mode = 'AM'
+ extra_am.set_value(radio_mode)
+ else:
+ mem.mode = radio_mode
+
+ mem.tuning_step = float(res['step']) / 1000
+ mem.skip = 'S' if int(res['pass']) else ''
+
+ extra_att.set_value(int(res['att']))
+
+ if not self._SKIP_SELECT:
+ self._command('MR{}{:02d}'.format(bank, chan))
+
+ res = self._command('OF', 'OF([0-4][0-9])([ +-])')
+ mem.offset = ol_list[int(res[1])] if res else 0
+ mem.duplex = res[2] if res and res[2] in ('+', '-') else ''
+
+ res = self._command('SH', 'SH([0-9]{6})([+]?)')
+ if res:
+ extra_adjust.set_value(
+ int(res[1]) / 1000 if res[2] == '+' else 0)
+
+ res = self._command('NL', 'NL([01])')
+ if res:
+ extra_limit.set_value(int(res[1]))
+
+ res = self._command('PC', 'PC([01])')
+ if res:
+ extra_protect.set_value(int(res[1]))
+
+ if (bank, chan) in gr_list:
+ extra_select.set_value(True)
+ extra_selectindex.set_value(
+ gr_list.index((bank, chan)))
+ else:
+ mem.immutable += ['extra.select']
+
+ else:
+ extra_adjust.set_mutable(False)
+ extra_limit.set_mutable(False)
+ extra_protect.set_mutable(False)
+
+ mem.immutable += ['offset', 'duplex', 'extra.adjust',
+ 'extra.limit', 'extra.protect',
+ 'extra.select']
+
+ extra_upper.set_mutable(False)
+
+ mem.immutable += ['extra.upper']
+
+ elif region == 'pass':
+ res = self._command_cached(
+ 'PR{}{:02d}'.format(bank, chan),
+ ('PR(?P<bank>[A-Ta-tV])(?P<chan>[0-9]{2}) '
+ '(?:(?P<empty>---)$|(?P<freq>[0-9]{10}))'))
+ if not res or res['empty']:
+ mem.empty = True
+ else:
+ if res['bank'] != bank or int(res['chan']) != chan:
+ raise errors.RadioError(
+ "Unexpected result returned from radio")
+
+ mem.freq = int(res['freq'])
+ mem.name = 'PR{}{:02d}'.format(bank, chan)
+ mem.immutable += ['freq']
+
+ mem.tuning_step = 20.0
+ mem.skip = 'S'
+
+ extra_am.set_mutable(False)
+ extra_upper.set_mutable(False)
+ extra_adjust.set_mutable(False)
+ extra_att.set_mutable(False)
+ extra_limit.set_mutable(False)
+ extra_protect.set_mutable(False)
+
+ mem.immutable += ['name', 'offset', 'mode', 'tuning_step', 'skip',
+ 'duplex', 'extra.upper', 'extra.adjust',
+ 'extra.att', 'extra.limit', 'extra.protect',
+ 'extra.select']
+
+ elif region == 'search':
+ ol_list = self._get_ol_list()
+
+ res = self._command(
+ 'SR{}'.format(bank),
+ ('SR(?P<bank>[A-Ta-t]) (?:(?P<empty>---)$|'
+ 'SL(?P<lower>[0-9]{10}) SU(?P<upper>[0-9]{10}) '
+ 'ST(?P<step>[0-9]{6})(?P<adjust>[+]?) AU(?P<auto>[01]) '
+ 'MD(?P<mode>[0-8]) AT(?P<att>[01]) TT(?P<name>.{0,12}))'))
+ if not res:
+ pass
+ elif res['empty']:
+ mem.empty = True
+ else:
+ if res['bank'] != bank:
+ raise errors.RadioError(
+ "Unexpected result returned from radio")
+
+ mem.freq = int(res['lower'])
+ mem.name = res['name']
+
+ if int(res['auto']):
+ mem.mode = 'Auto'
+ else:
+ radio_mode = [mode[0] for mode in self._MODES
+ if mode[1] == int(res['mode'])][0]
+ if radio_mode in self._AM_MODES:
+ mem.mode = 'AM'
+ extra_am.set_value(radio_mode)
+ else:
+ mem.mode = radio_mode
+
+ mem.tuning_step = float(res['step']) / 1000
+
+ extra_upper.set_value(int(res['upper']) / 1000000)
+ extra_att.set_value(int(res['att']))
+
+ self._save_gs()
+
+ self._command('GS0')
+ self._command('SS{}'.format(bank))
+
+ res = self._command('OF', 'OF([0-4][0-9])([ +-])')
+ mem.offset = ol_list[int(res[1])] if res else 0
+ mem.duplex = res[2] if res and res[2] in ('+', '-') else ''
+
+ res = self._command('SH', 'SH([0-9]{6})([+]?)')
+ if res:
+ v = int(res[1]) / 1000 if res[2] == '+' else 0
+ extra_adjust.set_value(v)
+
+ res = self._command('NL', 'NL([01])')
+ if res:
+ extra_limit.set_value(int(res[1]))
+
+ res = self._command('BP', 'BP([01])')
+ if res:
+ extra_protect.set_value(int(res[1]))
+
+ self._restore_gs()
+ self._command('VF')
+
+ mem.immutable += ['skip', 'extra.select']
+
+ else:
+ mem.empty = True
+
+ extra_select.set_mutable(False)
+
+ mem.immutable += ['extra.selectindex', 'tmode', 'rtone']
+
+ self._memcache[mem.number] = mem
+ return mem
+
+ def validate_memory(self, memory):
+ msgs = []
+
+ ol_list = self._get_ol_list(True)
+ (region, bank, chan) = self._decode_number(memory.number)
+
+ if region in ('scan', 'search'):
+ if memory.offset not in ol_list:
+ msg = chirp_common.ValidationWarning(
+ "Offset frequency is not valid, see table in settings "
+ "for valid values")
+ msgs.append(msg)
+
+ if memory.tuning_step == 0.0 or memory.tuning_step >= 1000.0 or \
+ (int(memory.tuning_step * 1000) % 50) != 0:
+ msg = chirp_common.ValidationWarning(
+ "Tuning step must be non-zero, less than 1000 kHz, and "
+ "divisible by 0.05 kHz")
+ msgs.append(msg)
+
+ if 'adjust' in memory.extra:
+ if float(memory.extra['adjust'].value) >= memory.tuning_step:
+ msg = chirp_common.ValidationWarning(
+ "Step adjust must be smaller than tuning step")
+ msgs.append(msg)
+
+ if region == 'search' and 'upper' in memory.extra:
+ upper = int(float(memory.extra['upper'].value) * 1000000)
+ if memory.freq > upper:
+ msg = chirp_common.ValidationWarning(
+ "Upper search frequency is not greater than lower "
+ "frequency")
+ msgs.append(msg)
+
+ valid = False
+ for (lv, uv) in self._rf.valid_bands:
+ if upper >= lv and upper <= uv:
+ valid = True
+ break
+
+ if not valid:
+ msg = chirp_common.ValidationError(
+ "Upper search frequency {} is not in a valid band"
+ "".format(float(memory.extra['upper'].value)))
+ msgs.append(msg)
+
+ if region == 'pass':
+ if memory.skip != 'S':
+ msg = chirp_common.ValidationWarning(
+ "Search pass frequencies must be marked skip")
+ msgs.append(msg)
+
+ msg = chirp_common.ValidationWarning(
+ "Memories must be refreshed after modifying pass channels")
+ msgs.append(msg)
+
+ return msgs + super().validate_memory(memory)
+
+ def set_memory(self, memory):
+ with self.LOCK:
+ return self._set_memory_unlocked(memory)
+
+ def _set_memory_unlocked(self, memory):
+ self._invalidate_memory(number=memory.number)
+
+ (region, bank, chan) = self._decode_number(memory.number)
+ if region is None:
+ raise errors.InvalidMemoryLocation(
+ "No such memory {}".format(memory.number))
+
+ if region == 'vfo':
+ if chan == self._SPECIAL_CHANS['VFO']:
+ self._command('VF')
+ elif chan == self._SPECIAL_CHANS['VFO-A']:
+ self._command('VA')
+ elif chan == self._SPECIAL_CHANS['VFO-B']:
+ self._command('VB')
+
+ ol_list = self._get_ol_list()
+
+ freq = memory.freq
+ auto = int(memory.mode == 'Auto')
+ step = int(memory.tuning_step * 1000)
+
+ 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] == ammode][0]
+ else:
+ mode = [mode[1] for mode in self._MODES
+ if mode[0] == memory.mode][0]
+
+ att = int(memory.extra['att'].value) \
+ if 'att' in memory.extra else 0
+ duplex = memory.duplex if memory.duplex in ('+', '-') else ''
+ offset = ol_list.index(memory.offset) \
+ if duplex and memory.offset in ol_list else 0
+ adjust = float(memory.extra['adjust'].value) \
+ if 'adjust' in memory.extra else 0
+ limit = int(memory.extra['limit'].value) \
+ if 'limit' in memory.extra else 0
+
+ self._command('RF{:010d}'.format(freq))
+ self._command('AT{:1d}'.format(att))
+ self._command('AU{:1d}'.format(auto))
+
+ if not auto:
+ self._command('MD{:1d}'.format(mode))
+ self._command('ST{:06d}'.format(step))
+ self._command('OF{:02d}{}'.format(offset, duplex))
+
+ # step tuning enable can only be toggled, so get the
+ # current value first
+ toggle = ''
+ res = self._command('SH', 'SH([0-9]{6})([+]?)')
+ if res:
+ toggle = '+' if (res[2] == '+') != (adjust > 0) else ''
+
+ self._command('SH{:06d}{}'.format(int(adjust * 1000), toggle))
+
+ self._command('NL{:1d}'.format(limit))
+
+ elif region == 'qm':
+ raise errors.InvalidDataError(
+ "Quick memory locations are read-only")
+
+ elif region == 'scan':
+ self._command_delete_cache('MX{:1}{:02d}'.format(bank, chan))
+ ol_list = self._get_ol_list()
+ gr_list = self._get_gr_list()
+
+ freq = memory.freq
+ auto = int(memory.mode == 'Auto')
+ step = int(memory.tuning_step * 1000)
+
+ 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] == ammode][0]
+ else:
+ mode = [mode[1] for mode in self._MODES
+ if mode[0] == memory.mode][0]
+
+ att = int(memory.extra['att'].value) \
+ if 'att' in memory.extra else 0
+ duplex = memory.duplex if memory.duplex in ('+', '-') else ''
+ offset = ol_list.index(memory.offset) \
+ if duplex and memory.offset in ol_list else 0
+ adjust = float(memory.extra['adjust'].value) \
+ if 'adjust' in memory.extra else 0
+ limit = int(memory.extra['limit'].value) \
+ if 'limit' in memory.extra else 0
+ protect = int(memory.extra['protect'].value) \
+ if 'protect' in memory.extra else 0
+ select = int(memory.extra['select'].value) \
+ if 'select' in memory.extra else 0
+ name = memory.name
+ mp = 1 if memory.skip == 'S' else 0
+
+ offsetstr = 'OF{:02d}{} '.format(offset, duplex) \
+ if not self._SKIP_SELECT else ''
+ res = self._command(
+ ('MX{}{:02d} RF{:010d} MP{:1d} ST{:06d} MD{:1d} AT{:1d} '
+ '{}AU{:1d} TM{:12}'.format(bank, chan, freq, mp, step, mode,
+ att, offsetstr, auto, name)),
+ '(?:$|{:c}{:c})'.format(0x13, 0x11))
+ if not res:
+ raise errors.InvalidDataError(
+ "Radio refused {}".format(memory.number))
+
+ if not self._SKIP_SELECT:
+ self._command('MR{}{:02d}'.format(bank, chan))
+
+ if not auto:
+ # step tuning enable can only be toggled, so get
+ # the current value first
+ toggle = ''
+ res = self._command('SH', 'SH([0-9]{6})([+]?)')
+ if res:
+ toggle = '+' if (res[2] == '+') != (adjust > 0) else ''
+
+ self._command(
+ 'SH{:06d}{}'.format(int(adjust * 1000), toggle))
+
+ self._command('NL{:1d}'.format(limit))
+ self._command('PC{:1d}'.format(protect))
+
+ if not select and (bank, chan) in gr_list:
+ self._command(
+ 'GD{:02d}'.format(gr_list.index((bank, chan))))
+ self._invalidate_gr_list()
+
+ elif region == 'pass':
+ self._command_delete_cache('PR{}[0-9]{{2}}'.format(bank), True)
+
+ freq = memory.freq
+
+ res = self._command('PW{}{:010d}'.format(bank, freq))
+ if not res:
+ raise errors.InvalidDataError(
+ "Radio refused {}".format(memory.number))
+
+ for n in range(100 if bank == 'V' else 50):
+ self._invalidate_memory(region, bank, n, emptyonly=True)
+
+ elif region == 'search':
+ self._command_delete_cache('SR{}'.format(bank))
+ ol_list = self._get_ol_list()
+
+ lower = memory.freq
+ upper = int(float(memory.extra['upper'].value) * 1000000) \
+ if 'upper' in memory.extra else lower
+ auto = int(memory.mode == 'Auto')
+ step = int(memory.tuning_step * 1000)
+
+ 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] == ammode][0]
+ else:
+ mode = [mode[1] for mode in self._MODES
+ if mode[0] == memory.mode][0]
+
+ att = int(memory.extra['att'].value) \
+ if 'att' in memory.extra else 0
+ duplex = memory.duplex if memory.duplex in ('+', '-') else ''
+ offset = ol_list.index(memory.offset) \
+ if duplex and memory.offset in ol_list else 0
+ adjust = float(memory.extra['adjust'].value) \
+ if 'adjust' in memory.extra else 0
+ limit = int(memory.extra['limit'].value) \
+ if 'limit' in memory.extra else 0
+ protect = int(memory.extra['protect'].value) \
+ if 'protect' in memory.extra else 0
+ name = memory.name
+
+ # correct lower/upper out of order
+ if lower > upper:
+ (lower, upper) = (upper, lower)
+
+ # fix out of range
+ lower = max(lower, min(list(zip(*self._rf.valid_bands))[0]))
+ upper = min(upper, max(list(zip(*self._rf.valid_bands))[1]))
+
+ res = self._command(
+ 'SE{} SL{:010d} SU{:010d} ST{:06d} MD{:1d} AT{:1d} '
+ 'OF{:02d}{:1} AU{:1d} TT{:12}'.format(bank, lower, upper, step,
+ mode, att, offset,
+ duplex, auto, name))
+ if not res:
+ raise errors.InvalidDataError(
+ "Radio refused {}".format(memory.number))
+
+ self._save_gs()
+
+ self._command('GS0')
+ self._command('SS{}'.format(bank))
+
+ if not auto:
+ # step tuning enable can only be toggled, so get the
+ # current value first
+ toggle = ''
+ res = self._command('SH', 'SH([0-9]{6})([+]?)')
+ if res:
+ toggle = '+' if (res[2] == '+') != (adjust > 0) else ''
+
+ self._command('SH{:06d}{}'.format(int(adjust * 1000), toggle))
+
+ self._command('NL{:1d}'.format(limit))
+ self._command('BP{:1d}'.format(protect))
+
+ self._restore_gs()
+ self._command('VF')
+
+ def erase_memory(self, number):
+ with self.LOCK:
+ return self._erase_memory_unlocked(number)
+
+ def _erase_memory_unlocked(self, number):
+ if isinstance(number, str):
+ if number not in self._SPECIAL_CHANS:
+ return
+
+ number = self._SPECIAL_CHANS[number]
+
+ if number not in self._memcache:
+ return
+
+ (region, bank, chan) = self._decode_number(number)
+
+ if region == 'qm':
+ raise errors.InvalidDataError(
+ "Quick memory locations are read-only")
+
+ elif region == 'scan':
+ self._command_delete_cache('MX{}{:02d}'.format(bank, chan))
+ self._command('MR{}{:02d}'.format(bank, chan))
+ self._command('MQ{:02d}'.format(chan))
+
+ elif region == 'pass':
+ self._command_delete_cache('PR{}[0-9]{{2}}'.format(bank), True)
+ self._command('PD{}{:02d}'.format(bank, chan))
+
+ for n in range(chan, 100 if bank == 'V' else 50):
+ self._invalidate_memory(region, bank, n)
+
+ elif region == 'search':
+ self._command_delete_cache('SR{}'.format(bank))
+ self._command('QS{}'.format(bank))
+
+ del self._memcache[number]
+
+ def get_settings(self):
+ with self.LOCK:
+ return self._get_settings_unlocked()
+
+ def _get_settings_unlocked(self):
+ main = RadioSettingGroup('main', 'Main')
+ vfo = RadioSettingGroup('vfo', 'VFO')
+ freq = RadioSettingGroup('freq', 'Offset')
+ scan = RadioSettingGroup('scan', 'Scan')
+ search = RadioSettingGroup('search', 'Search')
+ scanbankprotect = RadioSettingGroup('scanbankprotect',
+ 'Scan Bank Protect')
+ top = RadioSettings(main, vfo, freq, scan, search, scanbankprotect)
+
+ res = self._command('VR', 'VR([0-9]+)')
+ rs = RadioSetting('VR', 'Firmware Version',
+ RadioSettingValueString(0, 4, res[1]))
+ rs.value.set_mutable(False)
+ main.append(rs)
+
+ res = self._command('AF', 'AF([01])')
+ rs = RadioSetting('AF', 'Automatic Frequency Control',
+ RadioSettingValueBoolean(int(res[1])))
+ rs.set_apply_callback(
+ lambda x: self._command('AF{}'.format(int(x.value))))
+ main.append(rs)
+
+ res = self._command('AP', 'AP([0-9][.][0-9])')
+ rs = RadioSetting(
+ 'AP', 'Automatic Power Off (hours)',
+ RadioSettingValueFloat(0, 9.5, float(res[1]), 0.5, 1))
+ rs.set_apply_callback(
+ lambda x: self._command('AP{}'.format(int(x.value))))
+ main.append(rs)
+
+ res = self._command('DT', 'DT([01])')
+ rs = RadioSetting('DT', 'Display Frequency Text',
+ RadioSettingValueBoolean(int(res[1])))
+ rs.set_apply_callback(
+ lambda x: self._command('DT{}'.format(int(x.value))))
+ main.append(rs)
+
+ res = self._command('LB', 'LB([0-9]{2})')
+ rs = RadioSetting('LB', 'LCD Contrast',
+ RadioSettingValueInteger(0, 31, res[1]))
+ rs.set_apply_callback(
+ lambda x: self._command('LB{:02d}'.format(int(x.value))))
+ main.append(rs)
+
+ # OM supports options for standard, no, and custom message,
+ # but the code here always sets the configured text as a
+ # custom message.
+ res = self._command('OM', 'OM([012]) (.{0,48})')
+ rs = RadioSetting('OM', 'Opening Message',
+ RadioSettingValueString(0, 48, res[2]))
+ rs.set_apply_callback(
+ lambda x: self._command('OM2 {}'.format(str(x.value))))
+ main.append(rs)
+
+ res = self._command('PA', 'PA([0-9]{2})')
+ rs = RadioSetting('PA', 'Power Save Delay (seconds)',
+ RadioSettingValueInteger(0, 99, res[1]))
+ rs.set_apply_callback(
+ lambda x: self._command('PA{:02d}'.format(int(x.value))))
+ main.append(rs)
+
+ res = self._command('PI', 'PI([1-9].[05])')
+ rs = RadioSetting(
+ 'PI', 'Power Save Interval (seconds)',
+ RadioSettingValueFloat(1.0, 9.5, float(res[1]), 0.5, 1))
+ rs.set_apply_callback(
+ lambda x: self._command(
+ 'PI{:02d}'.format(int(float(x.value) * 10))))
+ main.append(rs)
+
+ res = self._command('PP', 'PP([A-Ja-j])([0-9]{2})')
+ rs = RadioSetting(
+ 'PP', 'Priority Scan Channel',
+ RadioSettingValueInteger(
+ 0, self._SCAN_MEMORIES - 1,
+ self._encode_number('scan', res[1], int(res[2]))))
+ rs.set_apply_callback(lambda x: self._set_pp(int(x.value)))
+ main.append(rs)
+
+ res = self._command('TI', 'TI([01][0-9])')
+ rs = RadioSetting('TI', 'Priority Interval (seconds)',
+ RadioSettingValueInteger(1, 19, res[1]))
+ rs.set_apply_callback(
+ lambda x: self._command('TI{:02d}'.format(int(x.value))))
+ main.append(rs)
+
+ res = self._command('VL', 'VL([0-9])')
+ rs = RadioSetting('VL', 'Beep Volume',
+ RadioSettingValueInteger(0, 9, res[1]))
+ rs.set_apply_callback(
+ lambda x: self._command('VL{}'.format(int(x.value))))
+ main.append(rs)
+
+ res = self._command('WP', 'WP([01])')
+ rs = RadioSetting('WP', 'Write Protect',
+ RadioSettingValueBoolean(int(res[1])))
+ rs.set_apply_callback(
+ lambda x: self._command('WP{}'.format(int(x.value))))
+ main.append(rs)
+
+ # vfo settings
+
+ res = self._command('DA', 'DA[ +]([012][0-9]{2})')
+ rs = RadioSetting('DA', 'Dial Audio Squelch',
+ RadioSettingValueInteger(0, 255, res[1]))
+ rs.set_apply_callback(
+ lambda x: self._command('DA{:03d}'.format(int(x.value))))
+ vfo.append(rs)
+
+ res = self._command('DB', 'DB[ +]([012][0-9]{2})')
+ rs = RadioSetting('DB', 'Dial Level Squelch',
+ RadioSettingValueInteger(0, 255, res[1]))
+ rs.set_apply_callback(
+ lambda x: self._command('DB{:03d}'.format(int(x.value))))
+ vfo.append(rs)
+
+ res = self._command('DD', 'DD([0-9][.][0-9])')
+
+ rs = RadioSetting('DDFF', 'Dial Search Hold',
+ RadioSettingValueBoolean(res[1] == 'FF'))
+ vfo.append(rs)
+
+ value = float(res[1]) if res[1] != 'FF' else 0
+ rs = RadioSetting('DD', 'Dial Delay (seconds)',
+ RadioSettingValueFloat(0, 9.9, value, 0.1, 1))
+ vfo.append(rs)
+
+ res = self._command('DP', 'DP([0-9]{2})')
+ rs = RadioSetting('DP', 'Dial Pause (seconds)',
+ RadioSettingValueInteger(0, 60, res[1]))
+ rs.set_apply_callback(
+ lambda x: self._command('DP{:02d}'.format(int(x.value))))
+ vfo.append(rs)
+
+ VT_MAP = [('Off', 0), ('On, auto-store to bank J', 1),
+ ('On, erase bank J', 2)]
+ res = self._command('VT', 'VT([012])')
+ rs = RadioSetting('VT', 'VFO Auto-store',
+ RadioSettingValueMap(VT_MAP, int(res[1])))
+ rs.set_apply_callback(
+ lambda x: self._command('VT{}'.format(int(x.value))))
+ vfo.append(rs)
+
+ # frequency offsets
+
+ # 0 means off, 20-47 are read-only
+ ol_list = self._get_ol_list()
+ for n in range(0, 48):
+ rs = RadioSetting(
+ 'OL{:02d}'.format(n),
+ 'Offset Frequency {} (MHz)'.format(n),
+ RadioSettingValueFloat(
+ 0.0, 999.9999, ol_list[n] / 1000000, 0.0001, 4))
+ rs.value.set_mutable(n > 0 and n < 20)
+ rs.set_apply_callback(
+ lambda x, y: self._command(
+ ('OL{:02d} {:010d}'
+ ''.format(y, int(float(x.value) * 1000000)))), n)
+ rs.set_warning("Memories must be refreshed after changing "
+ "offset frequencies.")
+ freq.append(rs)
+
+ # scan settings
+
+ grp = RadioSettingSubGroup('scan general', 'Scan General')
+ scan.append(grp)
+
+ res = self._command('GM', 'GM([0-9])', 2)
+ sel = int(res[1])
+ rs = RadioSetting('GM', 'Selected Scan Group',
+ RadioSettingValueInteger(0, 9, sel))
+ rs.set_apply_callback(
+ lambda x: self._command('GM{}'.format(int(x.value))))
+ grp.append(rs)
+
+ grp = RadioSettingSubGroup('TB', 'Scan Bank Name')
+ scan.append(grp)
+
+ for bank in self._SCAN_BANKS:
+ res = self._command('TB{}'.format(bank), 'TB([A-Ja-j])(.{0,8})')
+ rs = RadioSetting('TB{}'.format(bank), 'Bank {} Name'.format(bank),
+ RadioSettingValueString(0, 8, res[2]))
+ rs.set_apply_callback(
+ lambda x, y: self._command(
+ 'TB{}{:8}'.format(y, str(x.value))), bank)
+ grp.append(rs)
+
+ grp = RadioSettingSubGroup('MW', 'Scan Bank Size')
+ scan.append(grp)
+
+ MW_MAP = [('10/90', 10), ('20/80', 20), ('30/70', 30), ('40/60', 40),
+ ('50/50', 50), ('60/40', 60), ('70/30', 70), ('80/20', 80),
+ ('90/10', 90)]
+
+ for bank in self._SCAN_BANKS[::2]:
+ rs = RadioSetting(
+ 'MW{}'.format(bank), 'Bank {}/{}'.format(bank, bank.lower()),
+ RadioSettingValueMap(MW_MAP, self._scan_bank_size(bank)))
+ rs.set_apply_callback(
+ lambda x, y: self._command(
+ 'MW{}{:2d}'.format(y, int(x.value)), timeout=600), bank)
+ rs.set_warning("Resizing scan banks takes a significant amount of "
+ "time (one minute or longer). Memories must be "
+ "refreshed after changing scan bank size.")
+ grp.append(rs)
+
+ for group in range(10):
+ grp = RadioSettingSubGroup(
+ 'GM{}'.format(group), 'Scan Group {}'.format(group))
+ scan.append(grp)
+
+ self._command('GM{}'.format(group))
+
+ res = self._command_cached(
+ 'GM{:1d}'.format(group),
+ ('GM(?P<group>[0-9]) XD(?P<delay>[0-9][.][0-9]) '
+ 'XB (?P<level>[012][0-9]{2}) XA (?P<audio>[012][0-9]{2}) '
+ 'XP(?P<pause>[0-9]{2}) XM(?P<mode>[0-8F])'))
+ if not res:
+ continue
+
+ rs = RadioSetting('XA{}'.format(group), 'Scan Audio Squelch',
+ RadioSettingValueInteger(0, 255, res['audio']))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ rs = RadioSetting('XB{}'.format(group), 'Scan Level Squelch',
+ RadioSettingValueInteger(0, 255, res['level']))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ rs = RadioSetting(
+ 'XD{}'.format(group), 'Scan Delay (seconds)',
+ RadioSettingValueFloat(0, 9.9, float(res['delay']), 0.1, 1))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ rs = RadioSetting('XP{}'.format(group), 'Scan Pause (seconds)',
+ RadioSettingValueInteger(0, 99, res['pause']))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ rs = RadioSetting(
+ 'XM{}'.format(group), 'Scan Mode',
+ RadioSettingValueMap(self._MODES, int(res['mode'], 16)))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ res = self._command_cached('BM', 'BM ([A-Ja-j-]{20})')
+
+ for bank in self._SCAN_BANKS:
+ rs = RadioSetting(
+ 'BM{}{}'.format(group, bank), 'Bank {}'.format(bank),
+ RadioSettingValueBoolean(bank in res[1]))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ self._command('GM{}'.format(sel))
+
+ # search settings
+
+ grp = RadioSettingSubGroup('search general', 'Search General')
+ search.append(grp)
+
+ res = self._command('GS', 'GS([0-9])', 2)
+ sel = int(res[1])
+ rs = RadioSetting('GS', 'Selected Search Group',
+ RadioSettingValueInteger(0, 9, sel))
+ rs.set_apply_callback(
+ lambda x: self._command('GS{}'.format(int(x.value))))
+ grp.append(rs)
+
+ self._save_gs()
+
+ for group in range(10):
+ grp = RadioSettingSubGroup('GS{}'.format(group),
+ 'Search Group {}'.format(group))
+ search.append(grp)
+
+ self._command('GS{}'.format(group))
+
+ res = self._command_cached(
+ 'GS{:1d}'.format(group),
+ ('GS(?P<group>[0-9]) SD(?P<delay>[0-9][.][0-9]) '
+ 'SB (?P<level>[012][0-9]{2}) SA (?P<audio>[012][0-9]{2}) '
+ 'SP(?P<pause>[0-9]{2}) AS(?P<auto>[012])'))
+ if not res:
+ continue
+
+ rs = RadioSetting('SA{}'.format(group), 'Search Audio Squelch',
+ RadioSettingValueInteger(0, 255, res['audio']))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ rs = RadioSetting('SB{}'.format(group), 'Search Level Squelch',
+ RadioSettingValueInteger(0, 255, res['level']))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ if group != 0:
+ rs = RadioSetting(
+ 'SD{}FF'.format(group), 'Search Hold',
+ RadioSettingValueBoolean(res['delay'] == 'FF'))
+ grp.append(rs)
+
+ value = float(res['delay']) if res['delay'] != 'FF' else 0
+ rs = RadioSetting('SD{}'.format(group), 'Search Delay (seconds)',
+ RadioSettingValueFloat(0, 9.9, value, 0.1, 1))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ rs = RadioSetting('SP{}'.format(group), 'Search Pause (seconds)',
+ RadioSettingValueInteger(0, 99, res['pause']))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ rs = RadioSetting('AS{}'.format(group), 'Search Auto-store',
+ RadioSettingValueMap(VT_MAP, int(res['auto'])))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ res = self._command_cached('BS', 'BS ([A-Ta-t-]{40})')
+
+ for bank in self._SEARCH_BANKS:
+ rs = RadioSetting(
+ 'BS{}{}'.format(group, bank), 'Bank {}'.format(bank),
+ RadioSettingValueBoolean(bank in res[1]))
+ rs.value.set_mutable(group != 0)
+ grp.append(rs)
+
+ self._restore_gs()
+
+ # scan bank protect
+
+ for bank in self._SCAN_BANKS[::2]:
+ res = self._command_read_WM(bank)
+
+ for (b, v) in list(zip((bank, bank.lower()), res)):
+ rs = RadioSetting(
+ 'WM{}'.format(b), 'Scan Bank {} Protect'.format(b),
+ RadioSettingValueBoolean(v))
+ rs.set_apply_callback(
+ lambda x, y: self._command(
+ 'WM{}{}'.format(y, int(x.value))), b)
+ scanbankprotect.append(rs)
+
+ return top
+
+ def _apply_settings_callbacks(self, settings):
+ for element in settings:
+ if not isinstance(element, RadioSetting):
+ self._apply_settings_callbacks(element)
+ elif element.changed() and element.has_apply_callback():
+ LOG.debug("running callback for {}".format(element))
+ element.run_apply_callback()
+
+ def set_settings(self, settings):
+ with self.LOCK:
+ return self._set_settings_unlocked(settings)
+
+ def _set_settings_unlocked(self, settings):
+ self._apply_settings_callbacks(settings)
+
+ setdict = {}
+ for element in settings:
+ if isinstance(element, RadioSettingGroup):
+ setdict[element.get_name()] = element
+
+ if setdict['vfo']['DDFF'].value.changed() or \
+ setdict['vfo']['DD'].value.changed():
+ if int(setdict['vfo']['DDFF'].value):
+ self._command('DDFF')
+ else:
+ v = int(float(setdict['vfo']['DD'].value) * 10)
+ self._command('DD{:02d}'.format(v))
+
+ # BM/BS flags can only be cleared or toggled, so clear all
+ # first, then toggle the flags which are set
+
+ for group in range(1, 10):
+ parent = setdict['scan']['GM{}'.format(group)]
+
+ self._command('GM{}'.format(group))
+ if parent['XA{}'.format(group)].value.changed():
+ v = int(parent['XA{}'.format(group)].value)
+ self._command('XA{:03d}'.format(v))
+ if parent['XB{}'.format(group)].value.changed():
+ v = int(parent['XB{}'.format(group)].value)
+ self._command('XB{:03d}'.format(v))
+ if parent['XD{}'.format(group)].value.changed():
+ v = int(float(parent['XD{}'.format(group)].value) * 10)
+ self._command('XD{:02d}'.format(v))
+ if parent['XP{}'.format(group)].value.changed():
+ v = int(parent['XP{}'.format(group)].value)
+ self._command('XP{:02d}'.format(v))
+ if parent['XM{}'.format(group)].value.changed():
+ v = int(parent['XM{}'.format(group)].value)
+ self._command('XM{:01x}'.format(v))
+
+ if any(parent['BM{}{}'.format(group, bank)].value.changed()
+ for bank in self._SCAN_BANKS):
+
+ v = ''
+ for bank in self._SCAN_BANKS:
+ if int(parent['BM{}{}'.format(group, bank)].value):
+ v += bank
+
+ self._command('BM%%')
+ self._command('BM{}'.format(v), 'BM [A-Ja-j-]{20}')
+
+ v = int(setdict['scan']['scan general']['GM'].value)
+ self._command('GM{}'.format(v))
+
+ for group in range(1, 10):
+ parent = setdict['search']['GS{}'.format(group)]
+
+ self._command('GS{}'.format(group))
+
+ if parent['SA{}'.format(group)].value.changed():
+ v = int(parent['SA{}'.format(group)].value)
+ self._command('SA{:03d}'.format(v))
+ if parent['SB{}'.format(group)].value.changed():
+ v = int(parent['SB{}'.format(group)].value)
+ self._command('SB{:03d}'.format(v))
+
+ if parent['SD{}FF'.format(group)].value.changed() or \
+ parent['SD{}'.format(group)].value.changed():
+ if int(parent['SD{}FF'.format(group)].value):
+ self._command('SDFF')
+ else:
+ v = int(float(parent['SD{}'.format(group)].value) * 10)
+ self._command('SD{:02d}'.format(v))
+
+ if parent['SP{}'.format(group)].value.changed():
+ v = int(parent['SP{}'.format(group)].value)
+ self._command('SP{:02d}'.format(v))
+ if parent['AS{}'.format(group)].value.changed():
+ v = int(parent['AS{}'.format(group)].value)
+ self._command('AS{}'.format(v))
+
+ if any(parent['BS{}{}'.format(group, bank)].value.changed()
+ for bank in self._SEARCH_BANKS):
+
+ v = ''
+ for bank in self._SEARCH_BANKS:
+ if int(parent['BS{}{}'.format(group, bank)].value):
+ v += bank
+
+ self._command('BS%%')
+ self._command('BS{}'.format(v), 'BS [A-Ta-t-]{40}')
+
+ v = int(setdict['search']['search general']['GS'].value)
+ self._command('GS{}'.format(v))
+
+ for n in range(1, 20):
+ if setdict['freq']['OL{:02d}'.format(n)].value.changed():
+ self._invalidate_ol_list()
+ for n in range(self._SCAN_MEMORIES):
+ self._invalidate_memory(number=n)
+
+ for bank in self._SEARCH_BANKS:
+ self._invalidate_memory('search', bank, None)
+
+ break
+
+ changed = False
+ for bank in self._SCAN_BANKS[::2]:
+ if setdict['scan']['MW']['MW{}'.format(bank)].value.changed():
+ changed = True
+ for b in (bank.upper(), bank.lower()):
+ for n in range(self._scan_bank_size(b)):
+ self._invalidate_memory('scan', b, n)
+
+ if changed:
+ self._invalidate_scan_bank_size()
diff --git a/chirp/drivers/baofeng_common.py b/chirp/drivers/baofeng_common.py
index 3d1b3de..7eccffb 100644
--- a/chirp/drivers/baofeng_common.py
+++ b/chirp/drivers/baofeng_common.py
@@ -212,10 +212,12 @@ def _do_ident(radio, magic):
_rawsend(radio, magic)
ack = _rawrecv(radio, 1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != b"\x06":
if ack:
LOG.debug(repr(ack))
- raise errors.RadioError("Radio did not respond")
+ raise errors.RadioError("Unexpected response from radio")
_rawsend(radio, b"\x02")
@@ -256,7 +258,7 @@ def _ident_radio(radio):
time.sleep(2)
if error:
raise error
- raise errors.RadioError("Radio did not respond")
+ raise errors.RadioNoResponse()
def _download(radio):
@@ -529,7 +531,7 @@ class BaofengCommonHT(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_memory(self, number):
_mem = self._memobj.memory[number]
diff --git a/chirp/drivers/baofeng_digital.py b/chirp/drivers/baofeng_digital.py
index 39eba04..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",
@@ -484,3 +486,68 @@ class BaofengBFT20D(BaofengDigital):
]
_serial_id = 0x05
_proto = PROTO_D
+
+
+@directory.register
+class BaofengBFV12D(BaofengDigital):
+ """Baofeng BF-V12D"""
+ MODEL = 'BF-V12D'
+ VALID_BANDS = [(400000000, 480000000)]
+ POWER_LEVELS = [
+ chirp_common.PowerLevel("Low", watts=0.5),
+ chirp_common.PowerLevel("High", watts=2.00),
+ ]
+ _serial_id = 0x0a
+ _proto = PROTO_A
+
+ def _get_radio_id(self):
+ # The V12D requires a ucbfpwd unlock sequence before entering
+ # programming mode, observed from factory software captures.
+ for attempt in range(5):
+ try:
+ baofeng_common._clean_buffer(self)
+
+ # Send unlock command
+ self.pipe.write(b'\x02ucbfpwd')
+ resp = self.pipe.read(1)
+ LOG.debug('ucbfpwd response: %s',
+ resp.hex() if resp else 'empty')
+ if resp != CMD_ACK:
+ raise errors.RadioError(
+ 'No ACK on unlock command (got %s)'
+ % (resp.hex() if resp else 'empty'))
+
+ # Send unlock data and model identifier
+ # (observed from factory software captures)
+ self.pipe.write(b'\x10\xc5\xea\x35')
+ resp = self.pipe.read(1)
+ LOG.debug('unlock data response: %s',
+ resp.hex() if resp else 'empty')
+ if resp != CMD_ACK:
+ raise errors.RadioError(
+ 'No ACK on unlock data')
+
+ # Base64-encoded model identifier from factory software
+ self.pipe.write(
+ b'Q041OTUwMA==\x00\x00\x00\x00')
+ resp = self.pipe.read(1)
+ LOG.debug('model id response: %s',
+ resp.hex() if resp else 'empty')
+ if resp != CMD_ACK:
+ raise errors.RadioError(
+ 'No ACK on model identifier')
+
+ # Now request radio ID
+ self.pipe.write(b'\x02prOGRAM')
+ resp = self.pipe.read(4)
+ LOG.debug('radio ID: %s',
+ resp.hex() if resp else 'empty')
+ if len(resp) != 4:
+ raise errors.RadioError(
+ 'Radio did not send identification')
+ return resp
+ except errors.RadioError:
+ if attempt == 4:
+ raise
+ self._exit_programming()
+ time.sleep(1)
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_uv17.py b/chirp/drivers/baofeng_uv17.py
index 1a04c41..daa7c84 100644
--- a/chirp/drivers/baofeng_uv17.py
+++ b/chirp/drivers/baofeng_uv17.py
@@ -163,7 +163,7 @@ class UV17(baofeng_uv17Pro.UV17Pro):
WRITE_MEM_TOTAL = 0x9000
BLOCK_SIZE = 0x40
BAUD_RATE = 57600
- _magic = b"PSEARCH"
+ _idents = [b"PSEARCH"]
_magics = [(b"PASSSTA", 3),
(b"SYSINFO", 1),
(b"\x56\x00\x00\x0A\x0D", 13),
diff --git a/chirp/drivers/baofeng_uv17Pro.py b/chirp/drivers/baofeng_uv17Pro.py
index 670afc9..6321c77 100644
--- a/chirp/drivers/baofeng_uv17Pro.py
+++ b/chirp/drivers/baofeng_uv17Pro.py
@@ -17,8 +17,9 @@
import logging
from chirp.drivers import baofeng_common as bfc
-from chirp import chirp_common, directory, memmap
+from chirp import chirp_common, directory, memmap, bandplan_na
from chirp import bitwise
+from chirp import platform
from chirp.settings import RadioSetting, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueString, \
@@ -108,21 +109,33 @@ def _sendmagic(radio, magic, response_len):
def _do_ident(radio):
- # Flush input buffer
- bfc._clean_buffer(radio)
+ saw_data = False
+ for ident in radio._idents:
+ # Flush input buffer
+ bfc._clean_buffer(radio)
- # Ident radio
- ack = _sendmagic(radio, radio._magic, len(radio._fingerprint))
-
- if not ack.startswith(radio._fingerprint):
- if ack:
- LOG.debug(repr(ack))
- raise errors.RadioError("Radio did not respond as expected (A)")
+ # Ident radio
+ LOG.debug('Sending ident magic: %r', ident)
+ try:
+ ack = _sendmagic(radio, ident, len(radio._fingerprint))
+ if ack:
+ saw_data = True
+ if not ack.startswith(radio._fingerprint):
+ LOG.debug('Ack %r did not match fingerprint: %r', ack,
+ radio._fingerprint)
+ continue
+ except errors.RadioError:
+ # This is the timeout or invalid response length case
+ LOG.debug('Radio did not respond to ident magic: %r', ident)
+ continue
- for magic, resplen in radio._magics:
- _sendmagic(radio, magic, resplen)
+ for magic, resplen in radio._magics:
+ _sendmagic(radio, magic, resplen)
+ return True
- return True
+ if saw_data:
+ raise errors.RadioError("Unexpected response from radio")
+ raise errors.RadioNoResponse()
def _download(radio):
@@ -146,7 +159,7 @@ def _download(radio):
radio.BLOCK_SIZE):
frame = radio._make_read_frame(addr, radio.BLOCK_SIZE)
- radio.pipe.log('Sending request for %04x' % addr)
+ radio.pipe.log('Sending request for 0x%04x' % addr)
bfc._rawsend(radio, frame)
d = bfc._rawrecv(radio, radio.BLOCK_SIZE + 4)
@@ -161,7 +174,6 @@ def _download(radio):
# UI Update
status.cur = len(data) // radio.BLOCK_SIZE
- status.msg = "Cloning from radio..."
radio.status_fn(status)
return data
@@ -230,7 +242,7 @@ class UV17Pro(bfc.BaofengCommonHT):
_tri_band = True
_fileid = []
- _magic = MSTRING_UV17L
+ _idents = [MSTRING_UV17L]
_fingerprint = b"\x06"
_magics = [(b"\x46", 16),
(b"\x4d", 15),
@@ -247,9 +259,13 @@ class UV17Pro(bfc.BaofengCommonHT):
_has_pilot_tone = False
_has_send_id_delay = False
_has_skey1_short = False
+ _has_skey1_long = False
_has_skey2_short = False
+ _has_skey2_long = False
_has_skey_disable = False
_has_zone_linking = False
+ _has_bt = False
+ _has_scramble = False
_scode_offset = 0
_encrsym = 1
_has_voice = True
@@ -282,6 +298,7 @@ class UV17Pro(bfc.BaofengCommonHT):
_vhf2_range = (200000000, 260000000)
_uhf_range = (400000000, 520000000)
_uhf2_range = (350000000, 390000000)
+ AIRBANDS = [_airband]
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0]
LIST_STEPS = ["2.5", "5.0", "6.25", "10.0", "12.5", "20.0", "25.0", "50.0"]
@@ -405,7 +422,8 @@ class UV17Pro(bfc.BaofengCommonHT):
u8 unknown4[2];
u8 voxdlytime;
u8 menuquittime;
- u8 unknown5[2];
+ u8 bluetooth;
+ u8 unknown5;
u8 dispani;
u8 unknown11[3];
u8 totalarm;
@@ -476,7 +494,7 @@ class UV17Pro(bfc.BaofengCommonHT):
def _make_frame(self, cmd, addr, length, data=""):
"""Pack the info in the header format"""
- frame = cmd + struct.pack(">i", addr)[2:] + struct.pack("b", length)
+ frame = cmd + struct.pack(">i", addr)[2:] + struct.pack("B", length)
# add the data if set
if len(data) != 0:
frame += data
@@ -551,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)
@@ -567,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)
@@ -575,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)
@@ -588,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:
@@ -597,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:
@@ -604,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):
@@ -613,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):
@@ -623,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):
@@ -632,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):
@@ -641,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):
@@ -651,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:
@@ -661,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):
@@ -675,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):
@@ -689,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):
@@ -716,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:
@@ -729,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:
@@ -772,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):
@@ -788,61 +911,70 @@ class UV17Pro(bfc.BaofengCommonHT):
0x0A: 4,
0x0C: 5,
0x34: 6,
- 0x08: 4,
- 0x03: 5}
+ 0x05: 7,
+ 0x03: 8,
+ 0x35: 9}
return key_to_index.get(int(value), 0)
- def apply_Key1short(setting, obj):
- val = str(setting.value)
- key_to_index = {'FM': 0x07,
- 'Scan': 0x1C,
- 'Search': 0x1D,
- 'Vox': 0x2D,
- 'TX Power': 0x0A,
- 'NOAA': 0x0C,
- 'Zone Select': 0x34,
- 'Flashlight': 0x08,
- 'SOS': 0x03}
- obj.key1short = key_to_index.get(val, 0x07)
-
- def getKey2shortIndex(value):
- key_to_index = {0x07: 0,
- 0x1C: 1,
- 0x1D: 2,
- 0x2D: 3,
- 0x0A: 4,
- 0x0C: 5,
- 0x34: 6}
- return key_to_index.get(int(value), 0)
-
- def apply_Key2short(setting, obj):
- val = str(setting.value)
- key_to_index = {'FM': 0x07,
- 'Scan': 0x1C,
- 'Search': 0x1D,
- 'Vox': 0x2D,
- 'TX Power': 0x0A,
- 'NOAA': 0x0C,
- 'Zone Select': 0x34}
- obj.key2short = key_to_index.get(val, 0x07)
-
- if self._has_skey1_short:
- rs = RadioSetting("settings.key1short", "Skey1 Short",
- RadioSettingValueList(
- self.LIST_SKEY2_SHORT,
- current_index=getKey1shortIndex(
- _mem.settings.key1short)))
- rs.set_apply_callback(apply_Key1short, _mem.settings)
- basic.append(rs)
-
- if self._has_skey2_short:
- rs = RadioSetting("settings.key2short", "Skey2 Short",
- RadioSettingValueList(
- self.LIST_SKEY2_SHORT,
- current_index=getKey2shortIndex(
- _mem.settings.key2short)))
- rs.set_apply_callback(apply_Key2short, _mem.settings)
- basic.append(rs)
+ KEY_NAME_TO_CODE = {
+ 'FM': 0x07,
+ 'Scan': 0x1C,
+ 'Search': 0x1D,
+ 'Vox': 0x2D,
+ 'TX Power': 0x0A,
+ 'NOAA': 0x0C,
+ 'Zone Select': 0x34,
+ 'Monitor': 0x05,
+ 'Alarm': 0x03,
+ 'Scan Edit': 0x35,
+ }
+
+ KEY_CODE_TO_INDEX = {
+ code: idx for idx, code in enumerate(KEY_NAME_TO_CODE.values())
+ }
+
+ def make_apply_key(attr_name):
+ def apply(setting, obj):
+ val = str(setting.value)
+ setattr(obj, attr_name,
+ KEY_NAME_TO_CODE.get(val, 0x07))
+ return apply
+
+ apply_key1short = make_apply_key("key1short")
+ apply_key1long = make_apply_key("key1long")
+ apply_key2short = make_apply_key("key2short")
+ apply_key2long = make_apply_key("key2long")
+
+ 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, short_doc % 1),
+ ("_has_skey1_long", "settings.key1long", "Skey1 Long",
+ "key1long", apply_key1long, long_doc % 1),
+ ("_has_skey2_short", "settings.key2short", "Skey2 Short",
+ "key2short", apply_key2short, short_doc % 2),
+ ("_has_skey2_long", "settings.key2long", "Skey2 Long",
+ "key2long", apply_key2long, long_doc % 2),
+ ]
+
+ for flag, path, label, attr, apply_cb, doc in KEY_SETTINGS:
+ if getattr(self, flag):
+ rs = RadioSetting(
+ path,
+ label,
+ RadioSettingValueList(
+ self.LIST_SKEY2_SHORT,
+ current_index=get_key_index(
+ getattr(_mem.settings, attr))
+ )
+ )
+ rs.set_doc(doc)
+ rs.set_apply_callback(apply_cb, _mem.settings)
+ basic.append(rs)
if self._has_skey_disable:
rs = RadioSetting("settings.skdisable", "Side Key Disable",
@@ -855,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",
@@ -900,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:
@@ -919,8 +1076,18 @@ class UV17Pro(bfc.BaofengCommonHT):
current_index=_mem.settings.gpstimezone))
basic.append(rs)
+ if self._has_bt:
+ 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:
@@ -960,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,
@@ -967,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):
@@ -976,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):
@@ -985,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):
@@ -1004,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(
@@ -1011,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]
@@ -1021,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):
@@ -1030,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):
@@ -1039,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):
@@ -1048,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):
@@ -1057,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):
@@ -1066,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):
@@ -1075,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):
@@ -1084,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)
@@ -1256,12 +1467,13 @@ class UV17Pro(bfc.BaofengCommonHT):
def validate_memory(self, mem):
msgs = []
if 'AM' in self.MODES:
- if chirp_common.in_range(mem.freq,
- [self._airband]) and mem.mode != 'AM':
+ in_range = chirp_common.in_range
+ airbands = self.AIRBANDS
+
+ if in_range(mem.freq, airbands) and mem.mode != 'AM':
msgs.append(chirp_common.ValidationWarning(
_('Frequency in this range requires AM mode')))
- if not chirp_common.in_range(mem.freq,
- [self._airband]) and mem.mode == 'AM':
+ if not in_range(mem.freq, airbands) and mem.mode == 'AM':
msgs.append(chirp_common.ValidationWarning(
_('Frequency in this range must not be AM mode')))
@@ -1346,26 +1558,42 @@ class UV17Pro(bfc.BaofengCommonHT):
mem.power = levels[0]
mem.mode = _mem.wide and self.MODES[0] or self.MODES[1]
- if chirp_common.in_range(mem.freq, [self._airband]):
+ if chirp_common.in_range(mem.freq, self.AIRBANDS):
mem.mode = "AM"
mem.extra = RadioSettingGroup("Extra", "extra")
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:
+ rs = RadioSetting("scramble", "Scramble",
+ RadioSettingValueList(
+ self.SCRAMBLE_LIST,
+ current_index=_mem.scramble))
+ mem.extra.append(rs)
+
if self.MODEL in ["BF-F8HP-PRO"]:
rs = RadioSetting("sqmode", "RX DTMF",
RadioSettingValueList(
@@ -1380,19 +1608,20 @@ 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)
- if self.MODEL == "K6":
- rs = RadioSetting("scramble", "Scramble",
- RadioSettingValueList(
- self.SCRAMBLE_LIST,
- current_index=_mem.scramble))
- mem.extra.append(rs)
-
mem.name = str(name).replace('\xFF', ' ').replace('\x00', ' ').rstrip()
def _get_raw_memory(self, number):
@@ -1506,7 +1735,7 @@ class UV17ProGPS(UV17Pro):
_has_support_for_banknames = True
_has_workmode_support = True
- _magic = MSTRING_UV17PROGPS
+ _idents = [MSTRING_UV17PROGPS]
_magics = [(b"\x46", 16),
(b"\x4d", 7),
(b"\x53\x45\x4E\x44\x21\x05\x0D\x01\x01" +
@@ -1532,6 +1761,134 @@ class UV17ProGPS(UV17Pro):
return rf
+class UV17ProGPSGMRS(UV17ProGPS):
+ """UV-17Pro GPS variant with GMRS frequency-based enforcement.
+
+ Shared base for GMRS radios in the UV-17Pro GPS family that use
+ frequency-based TX restrictions with implied modes.
+ """
+ _gmrs = True
+ _low_power_index = 1
+
+ def get_features(self):
+ rf = super().get_features()
+ rf.valid_duplexes = ["", "-", "+", "split", "off"]
+ return rf
+
+ def _apply_gmrs_limits(self, mem):
+ if mem.duplex == "off":
+ return mem.mode, mem.power
+
+ if mem.duplex == "split":
+ tx_freq = mem.offset
+ elif mem.duplex == "+":
+ tx_freq = mem.freq + mem.offset
+ elif mem.duplex == "-":
+ tx_freq = mem.freq - mem.offset
+ else:
+ tx_freq = mem.freq
+
+ if tx_freq in bandplan_na.GMRS_HHONLY:
+ mode = "NFM"
+ power = self.POWER_LEVELS[self._low_power_index]
+ else:
+ mode = mem.mode
+ power = mem.power
+
+ return mode, power
+
+ def get_memory(self, number):
+ mem = super().get_memory(number)
+ if mem.empty:
+ return mem
+ mem.mode, mem.power = self._apply_gmrs_limits(mem)
+ return mem
+
+ def set_memory(self, mem):
+ super().set_memory(mem)
+ mode, power = self._apply_gmrs_limits(mem)
+ _mem = self._get_raw_memory(mem.number)
+ if power is not None:
+ _mem.lowpower = self.POWER_LEVELS.index(power)
+ if mode is not None:
+ _mem.wide = mode == self.MODES[0]
+
+ def validate_memory(self, mem):
+ msgs = super().validate_memory(mem)
+ if mem.empty:
+ return msgs
+
+ msg_tx = "TX frequency must be a GMRS frequency"
+ msg_low_power = (
+ "GMRS 467 MHz interstitial frequencies require low power"
+ )
+ msg_nfm = (
+ "GMRS 467 MHz interstitial frequencies require narrowband (NFM)"
+ )
+
+ gmrs_tx_freqs = set(bandplan_na.ALL_GMRS_FREQS)
+ gmrs_tx_freqs.update(
+ freq + 5000000 for freq in bandplan_na.GMRS_HIRPT
+ )
+
+ if mem.duplex == "off":
+ tx_freq = None
+ elif mem.duplex == "split":
+ tx_freq = mem.offset
+ elif mem.duplex == "+":
+ tx_freq = mem.freq + mem.offset
+ elif mem.duplex == "-":
+ tx_freq = mem.freq - mem.offset
+ else:
+ tx_freq = mem.freq
+
+ if tx_freq is not None and tx_freq not in gmrs_tx_freqs:
+ msgs.append(chirp_common.ValidationWarning(msg_tx))
+ if tx_freq in bandplan_na.GMRS_HHONLY:
+ if mem.power != self.POWER_LEVELS[self._low_power_index]:
+ msgs.append(chirp_common.ValidationWarning(msg_low_power))
+ if mem.mode != "NFM":
+ msgs.append(chirp_common.ValidationWarning(msg_nfm))
+
+ return msgs
+
+
+@directory.register
+class RadioddityGM30Plus(UV17ProGPSGMRS):
+ """Radioddity GM-30 Plus"""
+ VENDOR = "Radioddity"
+ MODEL = "GM-30 Plus"
+
+
+@directory.register
+class RadioddityGM30Pro(UV17ProGPSGMRS):
+ """Radioddity GM-30 Pro"""
+ VENDOR = "Radioddity"
+ MODEL = "GM-30 Pro"
+ _has_gps = False
+ _has_bt = True
+ _has_scramble = True
+
+
+@directory.register
+class BaofengGM21(UV17ProGPSGMRS):
+ """Baofeng GM-21"""
+ VENDOR = "Baofeng"
+ MODEL = "GM-21"
+ _has_gps = False
+ _has_bt = True
+
+
+@directory.register
+class UV32(UV17ProGPS):
+ VENDOR = "Baofeng"
+ MODEL = "UV-32"
+
+ POWER_LEVELS = [chirp_common.PowerLevel("High", watts=10.00),
+ chirp_common.PowerLevel("Low", watts=2.00),
+ chirp_common.PowerLevel("Medium", watts=5.00)]
+
+
@directory.register
class UV21ProGPS(UV17ProGPS):
VENDOR = "Baofeng"
@@ -1542,6 +1899,19 @@ class UV21ProGPS(UV17ProGPS):
@directory.register
+class UV28Plus(UV17ProGPS):
+ VENDOR = "Baofeng"
+ MODEL = "UV-28Plus"
+
+ VALID_BANDS = UV21ProV2.VALID_BANDS
+ MODES = UV21ProV2.MODES
+ POWER_LEVELS = [chirp_common.PowerLevel("High", watts=10.00),
+ chirp_common.PowerLevel("Low", watts=2.00),
+ chirp_common.PowerLevel("Medium", watts=5.00)]
+ _has_bt = True
+
+
+@directory.register
class BF5RM(UV17Pro):
VENDOR = "Baofeng"
MODEL = "5RM"
@@ -1576,6 +1946,21 @@ class BFK5Plus(BF5RM):
@directory.register
+class BaofengUV5RMPlus(BF5RM):
+ VENDOR = "Baofeng"
+ MODEL = "UV-5RM Plus"
+
+ _magics = [(b"\x46", 16),
+ (b"\x4d", 15),
+ (b"\x53\x45\x4E\x44\x13\x0F\x0D\x13\x0E\x0E\x0E\x0D\x0A" +
+ b"\x0E\x0E\x02\x0F\x08\x04\x11\x0C\x00\x0D\x0E\x00", 1)]
+ _encrsym = 13
+ _has_pilot_tone = True
+ _has_send_id_delay = True
+ _has_scramble = True
+
+
+@directory.register
class GM5RH(UV17Pro):
VENDOR = "Baofeng"
MODEL = "GM-5RH"
@@ -1588,7 +1973,7 @@ class GM5RH(UV17Pro):
LIST_PW_SAVEMODE = ["Off", "1:1", "2:1", "3:1", "4:1"]
_has_workmode_support = True
- _magic = MSTRING_GM5RH
+ _idents = [MSTRING_GM5RH]
@directory.register
@@ -1613,11 +1998,11 @@ class F8HPPro(UV17Pro):
# ==========
# Notice to developers:
- # The BF-F8HP-PRO support in this driver is currently based upon v0.44
+ # The BF-F8HP-PRO support in this driver is currently based upon v0.52
# firmware.
# ==========
- _magic = MSTRING_BFF8HPPRO
+ _idents = [MSTRING_BFF8HPPRO]
_magics = [(b"\x46", 16),
(b"\x4d", 6),
(b"\x53\x45\x4E\x44\x12\x0D\x0A\x0A\x10\x03\x0D\x02\x11\x0C" +
@@ -1629,10 +2014,14 @@ class F8HPPro(UV17Pro):
"100.0"]
_airband = (108000000, 136999999)
- _vhf_range = (137000000, 174000000)
-
- VALID_BANDS = [_airband, _vhf_range, UV17Pro._vhf2_range,
- UV17Pro._uhf_range, UV17Pro._uhf2_range]
+ _vhf_range = (137000000, 173999999)
+ _airband2 = (174000000, 218999999)
+ _vhf2_range = (219000000, 224999999)
+ _airband3 = (225000000, 399999999)
+ AIRBANDS = [_airband, _airband2, _airband3]
+
+ VALID_BANDS = [_airband, _vhf_range, _airband2, _vhf2_range, _airband3,
+ UV17Pro._uhf_range]
POWER_LEVELS = [chirp_common.PowerLevel("High", watts=10.00),
chirp_common.PowerLevel("Low", watts=1.00),
chirp_common.PowerLevel('Mid', watts=3.00)]
@@ -1645,10 +2034,11 @@ class F8HPPro(UV17Pro):
"20 sec", "30 sec", "60 sec"]
LIST_ID_DELAY = ["%s ms" % x for x in range(100, 3100, 100)]
LIST_SKEY2_SHORT = ["FM", "Scan", "Search", "Vox", "TX Power", "NOAA",
- "Zone Select"]
+ "Zone Select", "Monitor", "Alarm", "Scan Edit"]
MODES = UV17Pro.MODES + ['AM']
SQUELCH_LIST = ["Off"] + list("12345678")
LIST_SKEY_DISABLE = ["Off", "SK Only", "PTT Only", "SK + PTT"]
+ LIST_MODE = ["Name", "Frequency", "Channel Number", "Name + Frequency"]
_has_support_for_banknames = True
_vfoscan = True
@@ -1657,7 +2047,9 @@ class F8HPPro(UV17Pro):
_has_pilot_tone = True
_has_send_id_delay = True
_has_skey1_short = True
+ _has_skey1_long = True
_has_skey2_short = True
+ _has_skey2_long = True
_has_skey_disable = True
_has_voice = False
_has_when_to_send_aniid = False
@@ -1732,9 +2124,10 @@ class F8HPPro(UV17Pro):
u8 gpsw;
u8 gpsmode;
u8 key1short;
- u8 unknown7;
+ u8 key1long;
u8 key2short;
- u8 unknown8[2];
+ u8 key2long;
+ u8 unknown8;
u8 rstmenu;
u8 singlewatch;
u8 hangup;
@@ -1859,7 +2252,8 @@ class BFK6(UV17Pro):
VENDOR = "Baofeng"
MODEL = "K6"
- _magic = MSTRING_BFK6
+ _has_scramble = True
+ _idents = [MSTRING_BFK6]
_magics = [(b"\x46", 16),
]
_uses_encr = False
@@ -2162,9 +2556,12 @@ class UV5RMini(UV17Pro):
MEM_TOTAL = 0x8240
+ _is_on_ble = False
+
_has_support_for_banknames = False
+ _has_bt = True # allow BT setting
- _magic = MSTRING_UV17PROGPS
+ _idents = [MSTRING_UV17PROGPS]
_mem_size = MEM_TOTAL
_has_voxsw = True
_has_pilot_tone = True
@@ -2189,6 +2586,81 @@ class UV5RMini(UV17Pro):
_uhf_rx2_range]
MODES = UV17Pro.MODES + ['AM']
+ BLE_UP_BLOCK_SIZE = 0x80 # uploading to radio over BLE uses 0x80 blocksize
+
+ def sync_in(self):
+ self._is_on_ble = platform.get_platform().is_ble_serial(self.pipe)
+ LOG.debug('Detected BLE: %s' % self._is_on_ble)
+ return super().sync_in()
+
+ def sync_out(self):
+ self._is_on_ble = platform.get_platform().is_ble_serial(self.pipe)
+ LOG.debug('Detected BLE: %s' % self._is_on_ble)
+ return super().sync_out()
+
+ def _upload(radio):
+ """Upload to UV5R Mini (over BLE or USB/Serial)"""
+ # Put radio in program mode and identify it and
+ # determine if on BLE or USB/Serial connection
+ _do_ident(radio)
+
+ if radio._is_on_ble: # BLE upload needs a diff blocksize
+ _blocksize = radio.BLE_UP_BLOCK_SIZE
+ else:
+ _blocksize = radio.BLOCK_SIZE
+
+ data = b""
+
+ # UI progress
+ status = chirp_common.Status()
+ status.cur = 0
+ status.max = radio.MEM_TOTAL // _blocksize
+ status.msg = "Cloning to radio on %s/Serial..." % \
+ ('BLE' if radio._is_on_ble else 'USB')
+ radio.status_fn(status)
+
+ data_addr = 0x00
+ radio_mem = radio.get_mmap()
+ radio.pipe.log('Uploading to radio using block size of 0x%04x'
+ % _blocksize)
+ for i in range(len(radio.MEM_SIZES)):
+ MEM_SIZE = radio.MEM_SIZES[i]
+ MEM_START = radio.MEM_STARTS[i]
+ for addr in range(MEM_START, MEM_START + MEM_SIZE,
+ _blocksize):
+ # calc min byte count to keep from reading too many bytes
+ byte_count = min(_blocksize, (MEM_START + MEM_SIZE) - addr)
+ data = radio_mem[data_addr:data_addr + byte_count]
+
+ if byte_count < _blocksize: # does block need padding?
+ radio.pipe.log('Padding partial block with \\xff '
+ 'by 0x%02x bytes' %
+ (_blocksize - len(data)))
+ # pad partial block with \xff
+ data += (b'\xff' * (_blocksize - len(data)))
+
+ if radio._uses_encr:
+ data = _crypt(radio._encrsym, data)
+
+ data_addr += byte_count # advance read pointer
+
+ frame = radio._make_frame(b"W", addr, _blocksize, data)
+ radio.pipe.log('Sending address %04x' % addr)
+ bfc._rawsend(radio, frame)
+
+ ack = bfc._rawrecv(radio, 1)
+ if ack != b"\x06":
+ msg = "Bad ack writing block %04x" % addr
+ raise errors.RadioError(msg)
+
+ # UI Update
+ status.cur = data_addr // _blocksize
+ radio.status_fn(status)
+
+ return data
+
+ upload_function = _upload
+
_end_fmt = """
// #seekto 0x8220;
struct {
@@ -2203,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
@@ -2217,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)
@@ -2226,5 +2705,47 @@ 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)
+
+
+@directory.register
+class UV5GMini(UV5RMini):
+ # ==========
+ # Notice to developers:
+ # The UV-5G Mini support in this driver is
+ # currently based upon v0.05 firmware.
+ #
+ # This driver will also work with the UV-5G Mini with v0.01 firmware.
+ # For the UV-5G Mini with Fw 0.01 it is not necessary to use
+ # the UV-5R Mini driver
+ # ==========
+ """Baofeng UV-5G Mini"""
+ VENDOR = "Baofeng"
+ MODEL = "UV-5G Mini"
+
+ _idents = [
+ b'PROGRAMGMRS5RMIU', # magic for Fw v0.05
+ MSTRING_UV17PROGPS, # magic for Fw v0.01
+ ]
+
+ _low_power_index = 1
+
+ def get_memory(self, number):
+ mem = super().get_memory(number)
+
+ # inhibit changing freq, duplex and offset for GMRS channels 1-30
+ if mem.number >= 1 and mem.number <= 30:
+ mem.immutable = ['freq', 'duplex', 'offset']
+ # channels 8 - 14 have to be Narrow FM and Low power
+ if mem.number >= 8 and mem.number <= 14:
+ mem.mode = 'NFM'
+ # force low power
+ mem.power = self.POWER_LEVELS[self._low_power_index]
+ # inhibit changing freq, bandwidth, TX power, duplex and offset
+ mem.immutable = ['freq', 'mode', 'power',
+ 'duplex', 'offset']
+
+ return mem
diff --git a/chirp/drivers/bf_t1.py b/chirp/drivers/bf_t1.py
index cffc003..caa7ee6 100644
--- a/chirp/drivers/bf_t1.py
+++ b/chirp/drivers/bf_t1.py
@@ -126,9 +126,11 @@ def _rawrecv(radio, amount=0):
# fail if no data is received
if len(data) == 0:
- raise errors.RadioError("No data received from radio")
+ raise errors.RadioNoResponse()
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
raise errors.RadioError("Error reading data from radio")
return data
diff --git a/chirp/drivers/bf_t8.py b/chirp/drivers/bf_t8.py
index 7e8db1a..bd99b55 100644
--- a/chirp/drivers/bf_t8.py
+++ b/chirp/drivers/bf_t8.py
@@ -173,6 +173,8 @@ def _enter_programming_mode(radio):
# check if we had EXITO
if exito is False:
_exit_programming_mode(radio)
+ if not ack:
+ 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)
@@ -219,6 +221,8 @@ def _read_block(radio, block_addr, block_size):
try:
serial.write(cmd)
response = serial.read(4 + block_size)
+ if not response:
+ raise errors.RadioNoResponse()
if response[:4] != expectedresponse:
raise Exception("Error reading block %04x." % (block_addr))
@@ -383,7 +387,9 @@ class BFT8Radio(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
do_upload(self)
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
LOG.exception('Unexpected error during upload')
diff --git a/chirp/drivers/boblov_x3plus.py b/chirp/drivers/boblov_x3plus.py
index 4203c3d..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"""
@@ -526,7 +521,7 @@ class BoblovX3Plus(chirp_common.CloneModeRadio,
ack = self._read(1)
if not ack:
- raise errors.RadioError('No response from radio')
+ raise errors.RadioNoResponse()
elif ack != self.CMD_ACK:
raise errors.RadioError('Radio refused to enter '
'programming mode')
diff --git a/chirp/drivers/btech.py b/chirp/drivers/btech.py
index bbb8329..964b638 100644
--- a/chirp/drivers/btech.py
+++ b/chirp/drivers/btech.py
@@ -1,4 +1,4 @@
-# Copyright 2016-2023:
+# Copyright 2016-2026:
# * Pavel Milanes CO7WT, <pavelmc@gmail.com>
# * Jim Unroe KC9HI, <rock.unroe@gmail.com>
#
@@ -140,7 +140,7 @@ LIST_2TONE_DEC = ["A-B", "A-C", "A-D",
LIST_2TONE_RESPONSE = ["None", "Alert", "Transpond", "Alert+Transpond"]
# This is a general serial timeout for all serial read functions.
-STIMEOUT = 0.25
+STIMEOUT = 1.5
# this var controls the verbosity in the debug and by default it's low (False)
# make it True and you will to get a very verbose debug.log
@@ -334,33 +334,6 @@ MSTRING_KTWP12 = b"\x55\x20\x18\x11\x02\xFF\xDC\x02"
MSTRING_KT5000 = b"\x55\x20\x21\x01\x23\xFF\xDC\x02"
-def _clean_buffer(radio):
- """Cleaning the read serial buffer, hard timeout to survive an infinite
- data stream"""
-
- # touching the serial timeout to optimize the flushing
- # restored at the end to the default value
- radio.pipe.timeout = 0.1
- dump = b"1"
- datacount = 0
-
- try:
- while len(dump) > 0:
- dump = radio.pipe.read(100)
- datacount += len(dump)
- # hard limit to survive a infinite serial data stream
- # 5 times bigger than a normal rx block (69 bytes)
- if datacount > 345:
- seriale = "Please check your serial port selection."
- raise errors.RadioError(seriale)
-
- # restore the default serial timeout
- radio.pipe.timeout = STIMEOUT
-
- except Exception:
- raise errors.RadioError("Unknown error cleaning the serial buffer")
-
-
def _rawrecv(radio, amount):
"""Raw read from the radio device, less intensive way"""
@@ -376,14 +349,16 @@ def _rawrecv(radio, amount):
# fail if no data is received
if len(data) == 0:
- raise errors.RadioError("No data received from radio")
+ raise errors.RadioNoResponse()
# notice on the logs if short
if len(data) < amount:
- LOG.warn("Short reading %d bytes from the %d requested." %
- (len(data), amount))
+ LOG.warning("Short reading %d bytes from the %d requested." %
+ (len(data), amount))
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
raise errors.RadioError("Error reading data from radio")
return data
@@ -427,7 +402,8 @@ def _recv(radio, addr):
raise errors.RadioError("Short read of the block 0x%04x" % addr)
# checking for the ack
- if block[0] != ACK_CMD:
+ # occasionally the ack returned may be \x05 so support both
+ if block[0] not in b"\x06\x05":
raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
# header validation
@@ -447,8 +423,10 @@ def _do_ident(radio, status, upload=False):
radio.pipe.baudrate = 9600
radio.pipe.parity = "N"
- # lengthen the timeout here as these radios are resetting due to timeout
- radio.pipe.timeout = 0.75
+ # set timeout for download
+ radio.pipe.timeout = STIMEOUT
+
+ radio.pipe.reset_input_buffer()
# send the magic word
_send(radio, radio._magic)
@@ -460,9 +438,7 @@ def _do_ident(radio, status, upload=False):
if ident[0] != ACK_CMD:
raise errors.RadioError("Bad ack from radio")
- # basic check for the ident block
- if len(ident) != 50:
- raise errors.RadioError("Radio send a short ident block.")
+ # removed 'basic check' since it duplicates the check in _rawrecv()
# check if ident is OK
itis = False
@@ -483,49 +459,19 @@ def _do_ident(radio, status, upload=False):
# pause here for the radio to catch up
sleep(0.1)
- # the OEM software reads this additional block, so we will, too
-
- # Get the full 21 bytes at a time to reduce load
- # 1 byte ACK + 4 bytes header + 16 bytes of data (BLOCK_SIZE)
- frame = _make_frame("S", 0x3DF0, 16)
- _send(radio, frame)
- id2 = _rawrecv(radio, 21)
-
- # restore the default serial timeout
- radio.pipe.timeout = STIMEOUT
-
- # checking for the ack
- if id2[:1] not in b"\x06\x05":
- raise errors.RadioError("Bad ack from radio")
-
- # basic check for the additional block
- if len(id2) < 21:
- raise errors.RadioError("The extra ID is short, aborting.")
-
- # this radios need a extra request/answer here on the upload
- # the amount of data received depends of the radio type
+ # The color display models introduced what earlier versions of CHIRP
+ # called an "id2". The OEM CPS made a request to read a 16-byte block
+ # in high memory (0x3DF0). CHIRP attempted to mirror the CPS but the CPS
+ # appears to pipeline requests rather than synchronizing each transaction
+ # before issuing the next request acks. This has acks showing up further
+ # downstream in reads where it doesn't belong. When downloading, the OEM
+ # CPS actually reads the first block in an apparent attempt to clear the
+ # read buffer and then starts actual download starting with the first block
+ # again.
#
- # also the first block of TX must no have the ACK at the beginning
- # see _upload for this.
- if upload is True:
- # send an ACK
- _send(radio, b"\x06")
-
- # the amount of data depend on the radio, so far we have two radios
- # reading two bytes with an ACK at the end and just ONE with just
- # one byte (QYT KT8900)
- # the JT-6188 appears a clone of the last, but reads TWO bytes.
- #
- # we will read two bytes with a custom timeout to not penalize the
- # users for this.
- #
- # we just check for a response and last byte being a ACK, that is
- # the common stone for all radios (3 so far)
- ack = _rawrecv(radio, 2)
-
- # checking
- if len(ack) == 0 or ack[-1] != ACK_CMD:
- raise errors.RadioError("Radio didn't ACK the upload")
+ # Extensive testing across supported radios showed that the response is
+ # never used by the driver and upload/download succeeds without requesting
+ # it. Removing it makes the cloning process the same for all models.
# DEBUG
LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
@@ -564,6 +510,9 @@ def _download(radio):
status.msg = "Cloning from radio..."
radio.status_fn(status)
+ # ACK the final block of the download
+ _send(radio, b"\x06")
+
return data
@@ -597,10 +546,8 @@ def _upload(radio):
# build the frame to send
frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
- # first block must not send the ACK at the beginning for the
- # ones that has the extra id, since this have to do a extra step
- if addr == 0:
- frame = frame[1:]
+ # There is no longer a need to strip the first block ack for some
+ # models.
# send the frame
_send(radio, frame)
@@ -612,8 +559,14 @@ def _upload(radio):
if len(ack) != 1:
raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
- if ack not in bytes(b"\x06\x05"):
- raise errors.RadioError("Bad ACK writing block 0x%04x:" % addr)
+ first = ack
+
+ if first != b"\x06":
+ second = _rawrecv(radio, 1)
+ if second != b"\x06":
+ raise errors.RadioError(
+ "Unexpected ACK sequence: %s %s" %
+ (util.hexprint(first), util.hexprint(second)))
# UI Update
status.cur = addr // TX_BLOCK_SIZE
@@ -665,7 +618,6 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
_upper = 199
_magic = MSTRING
_fileid = []
- _id2 = False
btech3 = False
_gmrs = False
@@ -735,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:
@@ -882,15 +836,25 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
scramble = RadioSetting("scramble", "Scramble",
RadioSettingValueBoolean(bool(
_mem.scramble)))
+ scramble.set_doc(
+ "Enables voice inversion on this channel. Both radios must "
+ "use compatible scrambling; this does not provide secure "
+ "encryption.")
mem.extra.append(scramble)
bcl = RadioSetting("bcl", "Busy channel lockout",
RadioSettingValueBoolean(bool(_mem.bcl)))
+ bcl.set_doc(
+ "Prevents transmitting on this channel while the radio is "
+ "receiving a signal, helping avoid interruptions.")
mem.extra.append(bcl)
pttid = RadioSetting("pttid", "PTT ID",
RadioSettingValueList(PTTID_LIST,
current_index=_mem.pttid))
+ pttid.set_doc(
+ "Controls when this channel sends its selected PTT-ID: at the "
+ "beginning of transmission (BOT), the end (EOT), both, or never.")
mem.extra.append(pttid)
# validating scode
@@ -899,18 +863,28 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
RadioSettingValueList(
PTTIDCODE_LIST,
current_index=scode))
+ pttidcode.set_doc(
+ "Selects which of the 15 programmed signalling codes this "
+ "channel uses for PTT-ID and automatic calling.")
mem.extra.append(pttidcode)
optsig = RadioSetting("optsig", "Optional signaling",
RadioSettingValueList(
OPTSIG_LIST,
current_index=_mem.optsig))
+ optsig.set_doc(
+ "Selects whether this channel requires DTMF, 2-tone, or 5-tone "
+ "optional signalling, or uses none.")
mem.extra.append(optsig)
spmute = RadioSetting("spmute", "Speaker mute",
RadioSettingValueList(
SPMUTE_LIST,
current_index=_mem.spmute))
+ spmute.set_doc(
+ "Controls which signals open this channel's speaker: its "
+ "CTCSS/DCS tone, the selected optional signalling, or the "
+ "configured combination of both.")
mem.extra.append(spmute)
immutable = []
@@ -1115,15 +1089,25 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings.tmr, len(self.LIST_TMR) - 1)
rs = RadioSettingValueList(self.LIST_TMR, current_index=val)
tmr = RadioSetting("settings.tmr", "Transceiver multi-receive", rs)
+ tmr.set_doc(
+ "Selects which displays are watched in the background in "
+ "addition to the primary display.")
basic.append(tmr)
else:
tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
RadioSettingValueBoolean(_mem.settings.tdr))
+ tdr.set_doc(
+ "Enables Dual Watch so the radio alternates between displays "
+ "A and B and pauses on a display that receives a signal.")
basic.append(tdr)
val = min(_mem.settings.sql, 9)
rs = RadioSettingValueInteger(0, 9, val)
sql = RadioSetting("settings.sql", "Squelch level", rs)
+ sql.set_doc(
+ "Sets how strong a received signal must be before the speaker "
+ "unmutes. 0 leaves squelch open; higher values reject more weak "
+ "signals and noise.")
basic.append(sql)
if self.MODEL == "GMRS-50X1" or self.MODEL == "GMRS-50V2":
@@ -1140,6 +1124,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings.tot, len(LIST_TOT) - 1)
rs = RadioSettingValueList(LIST_TOT, current_index=val)
tot = RadioSetting("settings.tot", "Time out timer", rs)
+ tot.set_doc(
+ "Limits one continuous transmission to the selected time. This "
+ "helps prevent overheating and an accidentally stuck "
+ "transmitter.")
basic.append(tot)
if self.MODEL == "KT-8R":
@@ -1153,20 +1141,39 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings.apo, len(LIST_APO) - 1)
rs = RadioSettingValueList(LIST_APO, current_index=val)
apo = RadioSetting("settings.apo", "Auto power off timer", rs)
+ apo.set_doc(
+ "Automatically powers the radio off after the selected "
+ "period without receiver activity. Off disables "
+ "automatic power-off.")
basic.append(apo)
else:
val = min(_mem.settings.apo, len(LIST_OFF1TO10) - 1)
rs = RadioSettingValueList(LIST_OFF1TO10, current_index=val)
toa = RadioSetting("settings.apo", "Time out alert timer", rs)
+ toa.set_doc(
+ "Sets how many seconds before the Time-out Timer expires "
+ "that the radio flashes a pre-alert. Off disables the "
+ "warning.")
basic.append(toa)
val = min(_mem.settings.abr, len(LIST_OFF1TO50) - 1)
rs = RadioSettingValueList(LIST_OFF1TO50, current_index=val)
abr = RadioSetting("settings.abr", "Backlight timer", rs)
+ if self.MODEL == "KT8900D":
+ abr.set_doc(
+ "This menu item is marked unused in the KT8900D manual; "
+ "changing it is not expected to affect the radio.")
+ else:
+ abr.set_doc(
+ "Sets how long the LCD backlight remains on after radio "
+ "activity. Off keeps the backlight on continuously.")
basic.append(abr)
rs = RadioSettingValueBoolean(_mem.settings.beep)
beep = RadioSetting("settings.beep", "Key beep", rs)
+ beep.set_doc(
+ "Enables the audible confirmation tone for front-panel and "
+ "microphone keypad presses.")
basic.append(beep)
if self.MODEL == "GMRS-20V2":
@@ -1194,26 +1201,43 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings.dtmfst, len(LIST_DTMFST) - 1)
rs = RadioSettingValueList(LIST_DTMFST, current_index=val)
dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone", rs)
+ dtmfst.set_doc(
+ "Chooses which transmitted DTMF tones are heard through the "
+ "speaker: manually keyed tones, automatic ANI/PTT-ID tones, "
+ "both, or neither.")
basic.append(dtmfst)
if not self.COLOR_LCD:
rs = RadioSettingValueBoolean(_mem.settings.prisc)
prisc = RadioSetting("settings.prisc", "Priority scan", rs)
+ prisc.set_doc(
+ "Checks the selected Priority Channel periodically while "
+ "scanning other channels.")
basic.append(prisc)
val = min(_mem.settings.prich, self._upper)
rs = RadioSettingValueInteger(0, self._upper, val)
prich = RadioSetting("settings.prich", "Priority channel", rs)
+ prich.set_doc(
+ "Selects the memory channel checked periodically when "
+ "Priority Scan is enabled.")
basic.append(prich)
val = min(_mem.settings.screv, len(LIST_SCREV) - 1)
rs = RadioSettingValueList(LIST_SCREV, current_index=val)
screv = RadioSetting("settings.screv", "Scan resume method", rs)
+ screv.set_doc(
+ "Controls scanning after a signal is found. TO resumes after a "
+ "short delay, CO resumes when the signal disappears, and SE "
+ "stops until scanning is started again.")
basic.append(screv)
val = min(_mem.settings.pttlt, 30)
rs = RadioSettingValueInteger(0, 30, val)
pttlt = RadioSetting("settings.pttlt", "PTT transmit delay", rs)
+ pttlt.set_doc(
+ "Sets the delay before an automatic PTT-ID is transmitted, "
+ "allowing the receiving path time to open first.")
basic.append(pttlt)
if self.VENDOR == "BTECH" and self.COLOR_LCD and not \
@@ -1226,43 +1250,68 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings.emctp, len(LIST_EMCTP) - 1)
rs = RadioSettingValueList(LIST_EMCTP, current_index=val)
emctp = RadioSetting("settings.emctp", "Alarm mode", rs)
+ emctp.set_doc(
+ "Chooses whether the alarm sounds locally, transmits the "
+ "alarm and ANI/PTT-ID, or does both.")
basic.append(emctp)
val = min(_mem.settings.emcch, self._upper)
rs = RadioSettingValueInteger(0, self._upper, val)
emcch = RadioSetting("settings.emcch", "Alarm channel", rs)
+ emcch.set_doc(
+ "Selects the memory channel used to transmit the alarm and "
+ "ANI/PTT-ID when the alarm mode includes transmission.")
basic.append(emcch)
if self.COLOR_LCD:
rs = RadioSettingValueBoolean(_mem.settings.sigbp)
sigbp = RadioSetting("settings.sigbp", "Signal beep", rs)
+ sigbp.set_doc(
+ "Sounds a pager alert after matching DTMF, 2-tone, or 5-tone "
+ "optional signalling is received.")
basic.append(sigbp)
else:
val = min(_mem.settings.ringt, len(LIST_OFF1TO9) - 1)
rs = RadioSettingValueList(LIST_OFF1TO9, current_index=val)
ringt = RadioSetting("settings.ringt", "Ring time", rs)
+ ringt.set_doc(
+ "Sets how long the pager alert sounds after matching optional "
+ "signalling is received. Off disables the alert.")
basic.append(ringt)
val = min(_mem.settings.camdf, len(LIST_MDF) - 1)
rs = RadioSettingValueList(LIST_MDF, current_index=val)
camdf = RadioSetting("settings.camdf", "Display mode A", rs)
+ camdf.set_doc(
+ "In Channel (MR) mode, chooses whether display A shows the "
+ "frequency, channel number, or programmed channel name.")
basic.append(camdf)
val = min(_mem.settings.cbmdf, len(LIST_MDF) - 1)
rs = RadioSettingValueList(LIST_MDF, current_index=val)
cbmdf = RadioSetting("settings.cbmdf", "Display mode B", rs)
+ cbmdf.set_doc(
+ "In Channel (MR) mode, chooses whether display B shows the "
+ "frequency, channel number, or programmed channel name.")
basic.append(cbmdf)
if self.COLOR_LCD:
val = min(_mem.settings.ccmdf, len(LIST_MDF) - 1)
rs = RadioSettingValueList(LIST_MDF, current_index=val)
ccmdf = RadioSetting("settings.ccmdf", "Display mode C", rs)
+ ccmdf.set_doc(
+ "In Channel (MR) mode, chooses whether display C shows the "
+ "frequency, channel number, or programmed channel name.")
basic.append(ccmdf)
if not self.COLOR_LCD4:
val = min(_mem.settings.cdmdf, len(LIST_MDF) - 1)
rs = RadioSettingValueList(LIST_MDF, current_index=val)
cdmdf = RadioSetting("settings.cdmdf", "Display mode D", rs)
+ cdmdf.set_doc(
+ "In Channel (MR) mode, chooses whether display D shows "
+ "the frequency, channel number, or programmed channel "
+ "name.")
basic.append(cdmdf)
if self.MODEL in ["UV-50X2_G2", "UV-25X2_G2", "UV-25X4_G2"]:
@@ -1279,6 +1328,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings.langua, len(LIST_LANGUA) - 1)
rs = RadioSettingValueList(LIST_LANGUA, current_index=val)
langua = RadioSetting("settings.langua", "Language", rs)
+ langua.set_doc(
+ "Selects English or Chinese for the radio's on-screen "
+ "menu prompts.")
basic.append(langua)
if self.MODEL == "KT-8R":
val = min(_mem.settings.voice, len(LIST_VOICE) - 1)
@@ -1325,6 +1377,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings.ponmsg, len(LIST_PONMSG) - 1)
rs = RadioSettingValueList(LIST_PONMSG, current_index=val)
ponmsg = RadioSetting("settings.ponmsg", "Power-on message", rs)
+ ponmsg.set_doc(
+ "Chooses the startup display: a full-screen test, the "
+ "programmed power-on message, or the supply voltage.")
basic.append(ponmsg)
if self.COLOR_LCD and not (self.COLOR_LCD2 or self.COLOR_LCD3 or
@@ -1333,6 +1388,8 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(LIST_COLOR9, current_index=val)
mainfc = RadioSetting("settings.mainfc",
"Main LCD foreground color", rs)
+ mainfc.set_doc(
+ "Selects the foreground and text color of the main LCD area.")
basic.append(mainfc)
if not self.COLOR_LCD4:
@@ -1340,12 +1397,17 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(LIST_COLOR9, current_index=val)
mainbc = RadioSetting("settings.mainbc",
"Main LCD background color", rs)
+ mainbc.set_doc(
+ "Selects the background color of the main LCD area.")
basic.append(mainbc)
val = min(_mem.settings.menufc, len(LIST_COLOR9) - 1)
rs = RadioSettingValueList(LIST_COLOR9, current_index=val)
menufc = RadioSetting("settings.menufc",
"Menu foreground color", rs)
+ menufc.set_doc(
+ "Selects the foreground and text color of the on-screen "
+ "menu.")
basic.append(menufc)
if not self.COLOR_LCD4:
@@ -1353,12 +1415,17 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(LIST_COLOR9, current_index=val)
menubc = RadioSetting("settings.menubc",
"Menu background color", rs)
+ menubc.set_doc(
+ "Selects the background color of the on-screen menu.")
basic.append(menubc)
val = min(_mem.settings.stafc, len(LIST_COLOR9) - 1)
rs = RadioSettingValueList(LIST_COLOR9, current_index=val)
stafc = RadioSetting("settings.stafc",
"Top status foreground color", rs)
+ stafc.set_doc(
+ "Selects the foreground and text color of the top status "
+ "bar.")
basic.append(stafc)
if not self.COLOR_LCD4:
@@ -1366,12 +1433,17 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(LIST_COLOR9, current_index=val)
stabc = RadioSetting("settings.stabc",
"Top status background color", rs)
+ stabc.set_doc(
+ "Selects the background color of the top status bar.")
basic.append(stabc)
val = min(_mem.settings.sigfc, len(LIST_COLOR9) - 1)
rs = RadioSettingValueList(LIST_COLOR9, current_index=val)
sigfc = RadioSetting("settings.sigfc",
"Bottom status foreground color", rs)
+ sigfc.set_doc(
+ "Selects the foreground and text color of the bottom "
+ "signal/status bar.")
basic.append(sigfc)
if not self.COLOR_LCD4:
@@ -1379,18 +1451,27 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(LIST_COLOR9, current_index=val)
sigbc = RadioSetting("settings.sigbc",
"Bottom status background color", rs)
+ sigbc.set_doc(
+ "Selects the background color of the bottom signal/status "
+ "bar.")
basic.append(sigbc)
val = min(_mem.settings.rxfc, len(LIST_COLOR9) - 1)
rs = RadioSettingValueList(LIST_COLOR9, current_index=val)
rxfc = RadioSetting("settings.rxfc",
"Receiving character color", rs)
+ rxfc.set_doc(
+ "Selects the text color used to mark the display that is "
+ "receiving.")
basic.append(rxfc)
val = min(_mem.settings.txfc, len(LIST_COLOR9) - 1)
rs = RadioSettingValueList(LIST_COLOR9, current_index=val)
txfc = RadioSetting("settings.txfc",
"Transmitting character color", rs)
+ txfc.set_doc(
+ "Selects the text color used to mark the display that is "
+ "transmitting.")
basic.append(txfc)
if not self.COLOR_LCD4:
@@ -1398,6 +1479,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(LIST_TXDISP, current_index=val)
txdisp = RadioSetting("settings.txdisp",
"Transmitting status display", rs)
+ txdisp.set_doc(
+ "Chooses whether the bottom meter shows transmitter "
+ "power or microphone audio level while transmitting.")
basic.append(txdisp)
elif self.COLOR_LCD2 or self.COLOR_LCD3:
@@ -1534,26 +1618,41 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(LIST_COLOR4, current_index=val)
wtled = RadioSetting("settings.wtled",
"Standby backlight Color", rs)
+ wtled.set_doc(
+ "Selects the LCD backlight color while the radio is in "
+ "standby, or turns standby illumination off.")
basic.append(wtled)
val = min(_mem.settings.rxled, len(LIST_COLOR4) - 1)
rs = RadioSettingValueList(LIST_COLOR4, current_index=val)
rxled = RadioSetting("settings.rxled", "RX backlight Color", rs)
+ rxled.set_doc(
+ "Selects the LCD backlight color while receiving, or turns "
+ "receive illumination off.")
basic.append(rxled)
val = min(_mem.settings.txled, len(LIST_COLOR4) - 1)
rs = RadioSettingValueList(LIST_COLOR4, current_index=val)
txled = RadioSetting("settings.txled", "TX backlight Color", rs)
+ txled.set_doc(
+ "Selects the LCD backlight color while transmitting, or "
+ "turns transmit illumination off.")
basic.append(txled)
val = min(_mem.settings.anil, len(LIST_ANIL) - 1)
rs = RadioSettingValueList(LIST_ANIL, current_index=val)
anil = RadioSetting("settings.anil", "ANI length", rs)
+ anil.set_doc(
+ "Sets the expected ANI radio-ID length to three, four, or five "
+ "digits.")
basic.append(anil)
val = min(_mem.settings.reps, len(LIST_REPS) - 1)
rs = RadioSettingValueList(LIST_REPS, current_index=val)
reps = RadioSetting("settings.reps", "Relay signal (tone burst)", rs)
+ reps.set_doc(
+ "Selects the tone-burst frequency sent by the CALL key for "
+ "repeater access.")
basic.append(reps)
if self.COLOR_LCD4:
@@ -1572,6 +1671,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings.repm, len(LIST_REPM) - 1)
rs = RadioSettingValueList(LIST_REPM, current_index=val)
repm = RadioSetting("settings.repm", "Relay condition", rs)
+ repm.set_doc(
+ "Configures repeater forwarding when two radios are linked: "
+ "forward after a carrier, matching CTCSS/DCS, matching "
+ "2-tone/5-tone, or matching DTMF signal.")
basic.append(repm)
if self.VENDOR == "BTECH" or self.COLOR_LCD:
@@ -1579,6 +1682,11 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings.tmrmr, len(LIST_OFF1TO50) - 1)
rs = RadioSettingValueList(LIST_OFF1TO50, current_index=val)
tmrmr = RadioSetting("settings.tmrmr", "TMR return time", rs)
+ tmrmr.set_doc(
+ "After activity on a watched display clears, sets how "
+ "long PTT continues to use that display before returning "
+ "to the primary display. Off always transmits on the "
+ "primary display.")
basic.append(tmrmr)
else:
val = min(_mem.settings.tdrab, len(LIST_OFF1TO50) - 1)
@@ -1588,17 +1696,29 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueBoolean(_mem.settings.ste)
ste = RadioSetting("settings.ste", "Squelch tail eliminate", rs)
+ ste.set_doc(
+ "Transmits a compatible end-of-transmission signal to reduce "
+ "the squelch burst heard by another radio. Both radios must "
+ "support and enable this feature.")
basic.append(ste)
if self.COLOR_LCD4:
val = min(_mem.settings.rpste, len(LIST_OFF1TO10) - 1)
rs = RadioSettingValueList(LIST_OFF1TO10, current_index=val)
rpste = RadioSetting("settings.rpste", "Repeater STE", rs)
+ rpste.set_doc(
+ "Selects the squelch-tail elimination timing used with a "
+ "compatible repeater. Use Off when the repeater does not "
+ "support it.")
basic.append(rpste)
else:
val = min(_mem.settings.rpste, len(LIST_OFF1TO9) - 1)
rs = RadioSettingValueList(LIST_OFF1TO9, current_index=val)
rpste = RadioSetting("settings.rpste", "Repeater STE", rs)
+ rpste.set_doc(
+ "Selects the squelch-tail elimination timing used with a "
+ "compatible repeater. Use Off when the repeater does not "
+ "support it.")
basic.append(rpste)
if self.COLOR_LCD4:
@@ -1606,12 +1726,20 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(LIST_OFF1TO60, current_index=val)
rptdl = RadioSetting("settings.rptdl",
"Repeater STE delay", rs)
+ rptdl.set_doc(
+ "Sets the delay before repeater squelch-tail elimination "
+ "is applied. Match it to the repeater, or use Off when it "
+ "is not required.")
basic.append(rptdl)
else:
val = min(_mem.settings.rptdl, len(LIST_RPTDL) - 1)
rs = RadioSettingValueList(LIST_RPTDL, current_index=val)
rptdl = RadioSetting("settings.rptdl",
"Repeater STE delay", rs)
+ rptdl.set_doc(
+ "Sets the delay before repeater squelch-tail elimination "
+ "is applied. Match it to the repeater, or use Off when it "
+ "is not required.")
basic.append(rptdl)
if self.MODEL == "DB25-G":
@@ -1630,6 +1758,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings.dtmfg, 60)
rs = RadioSettingValueInteger(0, 60, val)
dtmfg = RadioSetting("settings.dtmfg", "DTMF gain", rs)
+ dtmfg.set_doc(
+ "Adjusts transmitted DTMF tone level from 0 (quietest) to 60 "
+ "(loudest).")
basic.append(dtmfg)
if self.VENDOR == "BTECH" and self.COLOR_LCD:
@@ -1680,40 +1811,64 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Power-on message line 1",
RadioSettingValueString(0, 8, _filter(
_msg.line1)))
+ line1.set_doc(
+ "Sets line 1 of the custom message shown when the radio "
+ "starts.")
advanced.append(line1)
line2 = RadioSetting("poweron_msg.line2",
"Power-on message line 2",
RadioSettingValueString(0, 8, _filter(
_msg.line2)))
+ line2.set_doc(
+ "Sets line 2 of the custom message shown when the radio "
+ "starts.")
advanced.append(line2)
line3 = RadioSetting("poweron_msg.line3",
"Power-on message line 3",
RadioSettingValueString(0, 8, _filter(
_msg.line3)))
+ line3.set_doc(
+ "Sets line 3 of the custom message shown when the radio "
+ "starts.")
advanced.append(line3)
line4 = RadioSetting("poweron_msg.line4",
"Power-on message line 4",
RadioSettingValueString(0, 8, _filter(
_msg.line4)))
+ line4.set_doc(
+ "Sets line 4 of the custom message shown when the radio "
+ "starts.")
advanced.append(line4)
line5 = RadioSetting("poweron_msg.line5",
"Power-on message line 5",
RadioSettingValueString(0, 8, _filter(
_msg.line5)))
+ line5.set_doc(
+ "Sets line 5 of the custom message shown when the radio "
+ "starts.")
advanced.append(line5)
line6 = RadioSetting("poweron_msg.line6",
"Power-on message line 6",
RadioSettingValueString(0, 8, _filter(
_msg.line6)))
+ line6.set_doc(
+ "Sets line 6 of the custom message shown when the radio "
+ "starts.")
advanced.append(line6)
line7 = RadioSetting("poweron_msg.line7",
"Power-on message line 7",
RadioSettingValueString(0, 8, _filter(
_msg.line7)))
+ line7.set_doc(
+ "Sets line 7 of the custom message shown when the radio "
+ "starts.")
advanced.append(line7)
line8 = RadioSetting("poweron_msg.line8", "Static message",
RadioSettingValueString(0, 8, _filter(
_msg.line8)))
+ line8.set_doc(
+ "Sets the static text shown on the color display when the "
+ "radio starts.")
advanced.append(line8)
elif self.COLOR_LCD2 or self.COLOR_LCD3 or self.COLOR_LCD4:
_msg = self._memobj.static_msg
@@ -1727,11 +1882,17 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Power-on message line 1",
RadioSettingValueString(0, 6, _filter(
_msg.line1)))
+ line1.set_doc(
+ "Sets line 1 of the custom message shown when the radio "
+ "starts.")
advanced.append(line1)
line2 = RadioSetting("poweron_msg.line2",
"Power-on message line 2",
RadioSettingValueString(0, 6, _filter(
_msg.line2)))
+ line2.set_doc(
+ "Sets line 2 of the custom message shown when the radio "
+ "starts.")
advanced.append(line2)
if self.MODEL in ("UV-2501", "UV-5001"):
@@ -1771,12 +1932,18 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = RadioSettingValueString(0, 3, _limit)
val.set_mutable(False)
vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
+ vhf_low.set_doc(
+ "Read-only factory VHF low frequency limit in MHz. It shows the "
+ "range accepted by this radio image.")
other.append(vhf_low)
_limit = convert_bytes_to_limit(_ranges.vhf_high)
val = RadioSettingValueString(0, 3, _limit)
val.set_mutable(False)
vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
+ vhf_high.set_doc(
+ "Read-only factory VHF high frequency limit in MHz. It shows the "
+ "range accepted by this radio image.")
other.append(vhf_high)
if self.BANDS == 3 or self.BANDS == 4:
@@ -1796,12 +1963,18 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = RadioSettingValueString(0, 3, _limit)
val.set_mutable(False)
uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
+ uhf_low.set_doc(
+ "Read-only factory UHF low frequency limit in MHz. It shows the "
+ "range accepted by this radio image.")
other.append(uhf_low)
_limit = convert_bytes_to_limit(_ranges.uhf_high)
val = RadioSettingValueString(0, 3, _limit)
val.set_mutable(False)
uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
+ uhf_high.set_doc(
+ "Read-only factory UHF high frequency limit in MHz. It shows the "
+ "range accepted by this radio image.")
other.append(uhf_high)
if self.BANDS == 4:
@@ -1820,6 +1993,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
val.set_mutable(False)
fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
+ fp.set_doc(
+ "Read-only radio firmware fingerprint used to identify "
+ "compatible images.")
other.append(fp)
# Work
@@ -1827,69 +2003,108 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.settings2.dispab, len(LIST_ABC) - 1)
rs = RadioSettingValueList(LIST_ABC, current_index=val)
dispab = RadioSetting("settings2.dispab", "Display", rs)
+ dispab.set_doc(
+ "Selects the active display used for tuning, transmitting, "
+ "and other front-panel operations.")
work.append(dispab)
elif self.COLOR_LCD:
val = min(_mem.settings2.dispab, len(LIST_ABCD) - 1)
rs = RadioSettingValueList(LIST_ABCD, current_index=val)
dispab = RadioSetting("settings2.dispab", "Display", rs)
+ dispab.set_doc(
+ "Selects the active display used for tuning, transmitting, "
+ "and other front-panel operations.")
work.append(dispab)
else:
val = min(_mem.settings2.dispab, len(LIST_AB) - 1)
rs = RadioSettingValueList(LIST_AB, current_index=val)
dispab = RadioSetting("settings2.dispab", "Display", rs)
+ dispab.set_doc(
+ "Selects the active display used for tuning, transmitting, "
+ "and other front-panel operations.")
work.append(dispab)
if self.COLOR_LCD:
val = min(_mem.settings2.vfomra, len(LIST_VFOMR) - 1)
rs = RadioSettingValueList(LIST_VFOMR, current_index=val)
vfomra = RadioSetting("settings2.vfomra", "VFO/MR A mode", rs)
+ vfomra.set_doc(
+ "Selects Frequency (VFO) mode for direct tuning or Channel "
+ "(MR) mode for programmed memories on display A.")
work.append(vfomra)
val = min(_mem.settings2.vfomrb, len(LIST_VFOMR) - 1)
rs = RadioSettingValueList(LIST_VFOMR, current_index=val)
vfomrb = RadioSetting("settings2.vfomrb", "VFO/MR B mode", rs)
+ vfomrb.set_doc(
+ "Selects Frequency (VFO) mode for direct tuning or Channel "
+ "(MR) mode for programmed memories on display B.")
work.append(vfomrb)
val = min(_mem.settings2.vfomrc, len(LIST_VFOMR) - 1)
rs = RadioSettingValueList(LIST_VFOMR, current_index=val)
vfomrc = RadioSetting("settings2.vfomrc", "VFO/MR C mode", rs)
+ vfomrc.set_doc(
+ "Selects Frequency (VFO) mode for direct tuning or Channel "
+ "(MR) mode for programmed memories on display C.")
work.append(vfomrc)
if not self.COLOR_LCD4:
val = min(_mem.settings2.vfomrd, len(LIST_VFOMR) - 1)
rs = RadioSettingValueList(LIST_VFOMR, current_index=val)
vfomrd = RadioSetting("settings2.vfomrd", "VFO/MR D mode", rs)
+ vfomrd.set_doc(
+ "Selects Frequency (VFO) mode for direct tuning or "
+ "Channel (MR) mode for programmed memories on display D.")
work.append(vfomrd)
else:
val = min(_mem.settings2.vfomr, len(LIST_VFOMR) - 1)
rs = RadioSettingValueList(LIST_VFOMR, current_index=val)
vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode", rs)
+ vfomr.set_doc(
+ "Selects Frequency (VFO) mode for direct tuning or Channel "
+ "(MR) mode for programmed memories.")
work.append(vfomr)
rs = RadioSettingValueBoolean(_mem.settings2.keylock)
keylock = RadioSetting("settings2.keylock", "Keypad lock", rs)
+ keylock.set_doc(
+ "Sets the current keypad-lock state. Hold the # key on the "
+ "microphone to lock or unlock the controls.")
work.append(keylock)
val = min(_mem.settings2.mrcha, self._upper)
rs = RadioSettingValueInteger(0, self._upper, val)
mrcha = RadioSetting("settings2.mrcha", "MR A channel", rs)
+ mrcha.set_doc(
+ "Selects the memory channel shown on display A when that display "
+ "is in Channel (MR) mode.")
work.append(mrcha)
val = min(_mem.settings2.mrchb, self._upper)
rs = RadioSettingValueInteger(0, self._upper, val)
mrchb = RadioSetting("settings2.mrchb", "MR B channel", rs)
+ mrchb.set_doc(
+ "Selects the memory channel shown on display B when that display "
+ "is in Channel (MR) mode.")
work.append(mrchb)
if self.COLOR_LCD:
val = min(_mem.settings2.mrchc, self._upper)
rs = RadioSettingValueInteger(0, self._upper, val)
mrchc = RadioSetting("settings2.mrchc", "MR C channel", rs)
+ mrchc.set_doc(
+ "Selects the memory channel shown on display C when that "
+ "display is in Channel (MR) mode.")
work.append(mrchc)
if not self.COLOR_LCD4:
val = min(_mem.settings2.mrchd, self._upper)
rs = RadioSettingValueInteger(0, self._upper, val)
mrchd = RadioSetting("settings2.mrchd", "MR D channel", rs)
+ mrchd.set_doc(
+ "Selects the memory channel shown on display D when that "
+ "display is in Channel (MR) mode.")
work.append(mrchd)
def my_validate(value):
@@ -1948,6 +2163,8 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
bfc.bcd_decode_freq(_mem.vfo.a.freq))
val1a.set_validate_callback(my_validate)
vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
+ vfoafreq.set_doc(
+ "Sets display A's receive frequency in Frequency (VFO) mode.")
vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
work.append(vfoafreq)
@@ -1958,6 +2175,8 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val1b = RadioSettingValueString(0, 10, val)
val1b.set_validate_callback(my_validate)
vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
+ vfobfreq.set_doc(
+ "Sets display B's receive frequency in Frequency (VFO) mode.")
vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
work.append(vfobfreq)
@@ -1967,6 +2186,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
_mem.vfo.c.freq))
val1c.set_validate_callback(my_validate)
vfocfreq = RadioSetting("vfo.c.freq", "VFO C frequency", val1c)
+ vfocfreq.set_doc(
+ "Sets display C's receive frequency in Frequency (VFO) "
+ "mode.")
vfocfreq.set_apply_callback(apply_freq, _mem.vfo.c)
work.append(vfocfreq)
@@ -1978,6 +2200,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val1d = RadioSettingValueString(0, 10, val)
val1d.set_validate_callback(my_validate)
vfodfreq = RadioSetting("vfo.d.freq", "VFO D frequency", val1d)
+ vfodfreq.set_doc(
+ "Sets display D's receive frequency in Frequency (VFO) "
+ "mode.")
vfodfreq.set_apply_callback(apply_freq, _mem.vfo.d)
work.append(vfodfreq)
@@ -1985,17 +2210,29 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.vfo.a.shiftd, len(LIST_SHIFT) - 1)
rs = RadioSettingValueList(LIST_SHIFT, current_index=val)
vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift", rs)
+ vfoashiftd.set_doc(
+ "Sets VFO A's repeater shift direction. + transmits above "
+ "the receive frequency, - below it, and Off uses the receive "
+ "frequency.")
work.append(vfoashiftd)
val = min(_mem.vfo.b.shiftd, len(LIST_SHIFT) - 1)
rs = RadioSettingValueList(LIST_SHIFT, current_index=val)
vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift", rs)
+ vfobshiftd.set_doc(
+ "Sets VFO B's repeater shift direction. + transmits above "
+ "the receive frequency, - below it, and Off uses the receive "
+ "frequency.")
work.append(vfobshiftd)
if self.COLOR_LCD:
val = min(_mem.vfo.c.shiftd, len(LIST_SHIFT) - 1)
rs = RadioSettingValueList(LIST_SHIFT, current_index=val)
vfocshiftd = RadioSetting("vfo.c.shiftd", "VFO C shift", rs)
+ vfocshiftd.set_doc(
+ "Sets VFO C's repeater shift direction. + transmits "
+ "above the receive frequency, - below it, and Off uses "
+ "the receive frequency.")
work.append(vfocshiftd)
if not self.COLOR_LCD4:
@@ -2003,6 +2240,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(LIST_SHIFT, current_index=val)
vfodshiftd = RadioSetting("vfo.d.shiftd",
"VFO D shift", rs)
+ vfodshiftd.set_doc(
+ "Sets VFO D's repeater shift direction. + transmits "
+ "above the receive frequency, - below it, and Off "
+ "uses the receive frequency.")
work.append(vfodshiftd)
def convert_bytes_to_offset(bytes):
@@ -2024,6 +2265,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
vfoaoffset = RadioSetting("vfo.a.offset",
"VFO A offset (0.000-999.999)",
val1a)
+ vfoaoffset.set_doc(
+ "Sets the difference in MHz between VFO A's receive and "
+ "transmit frequencies. Shift determines whether it is "
+ "added or subtracted.")
vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
work.append(vfoaoffset)
@@ -2032,6 +2277,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
vfoboffset = RadioSetting("vfo.b.offset",
"VFO B offset (0.000-999.999)",
val1b)
+ vfoboffset.set_doc(
+ "Sets the difference in MHz between VFO B's receive and "
+ "transmit frequencies. Shift determines whether it is "
+ "added or subtracted.")
vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
work.append(vfoboffset)
@@ -2040,6 +2289,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
vfocoffset = RadioSetting("vfo.c.offset",
"VFO C offset (0.000-999.999)",
val1c)
+ vfocoffset.set_doc(
+ "Sets the difference in MHz between VFO C's receive and "
+ "transmit frequencies. Shift determines whether it is "
+ "added or subtracted.")
vfocoffset.set_apply_callback(apply_offset, _mem.vfo.c)
work.append(vfocoffset)
@@ -2050,6 +2303,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
vfodoffset = RadioSetting("vfo.d.offset",
"VFO D offset (0.000-999.999)",
val1d)
+ vfodoffset.set_doc(
+ "Sets the difference in MHz between VFO D's receive "
+ "and transmit frequencies. Shift determines whether "
+ "it is added or subtracted.")
vfodoffset.set_apply_callback(apply_offset, _mem.vfo.d)
work.append(vfodoffset)
else:
@@ -2057,6 +2314,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
_mem.vfo.a.offset))
vfoaoffset = RadioSetting("vfo.a.offset",
"VFO A offset (0.000-99.999)", val1a)
+ vfoaoffset.set_doc(
+ "Sets the difference in MHz between VFO A's receive and "
+ "transmit frequencies. Shift determines whether it is "
+ "added or subtracted.")
vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
work.append(vfoaoffset)
@@ -2064,6 +2325,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
_mem.vfo.b.offset))
vfoboffset = RadioSetting("vfo.b.offset",
"VFO B offset (0.000-99.999)", val1b)
+ vfoboffset.set_doc(
+ "Sets the difference in MHz between VFO B's receive and "
+ "transmit frequencies. Shift determines whether it is "
+ "added or subtracted.")
vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
work.append(vfoboffset)
@@ -2071,40 +2336,61 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = min(_mem.vfo.a.power, len(LIST_TXP) - 1)
rs = RadioSettingValueList(LIST_TXP, current_index=val)
vfoatxp = RadioSetting("vfo.a.power", "VFO A power", rs)
+ vfoatxp.set_doc(
+ "Selects VFO A's transmitter power. Use the lowest power "
+ "that provides reliable communication.")
work.append(vfoatxp)
val = min(_mem.vfo.b.power, len(LIST_TXP) - 1)
rs = RadioSettingValueList(LIST_TXP, current_index=val)
vfobtxp = RadioSetting("vfo.b.power", "VFO B power", rs)
+ vfobtxp.set_doc(
+ "Selects VFO B's transmitter power. Use the lowest power "
+ "that provides reliable communication.")
work.append(vfobtxp)
if self.COLOR_LCD:
val = min(_mem.vfo.c.power, len(LIST_TXP) - 1)
rs = RadioSettingValueList(LIST_TXP, current_index=val)
vfoctxp = RadioSetting("vfo.c.power", "VFO C power", rs)
+ vfoctxp.set_doc(
+ "Selects VFO C's transmitter power. Use the lowest power "
+ "that provides reliable communication.")
work.append(vfoctxp)
if not self.COLOR_LCD4:
val = min(_mem.vfo.d.power, len(LIST_TXP) - 1)
rs = RadioSettingValueList(LIST_TXP, current_index=val)
vfodtxp = RadioSetting("vfo.d.power", "VFO D power", rs)
+ vfodtxp.set_doc(
+ "Selects VFO D's transmitter power. Use the lowest "
+ "power that provides reliable communication.")
work.append(vfodtxp)
if not self.MODEL == "GMRS-50X1":
val = min(_mem.vfo.a.wide, len(LIST_WIDE) - 1)
rs = RadioSettingValueList(LIST_WIDE, current_index=val)
vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth", rs)
+ vfoawide.set_doc(
+ "Selects wide or narrow FM for VFO A. Use the bandwidth "
+ "required by the channel plan.")
work.append(vfoawide)
val = min(_mem.vfo.b.wide, len(LIST_WIDE) - 1)
rs = RadioSettingValueList(LIST_WIDE, current_index=val)
vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth", rs)
+ vfobwide.set_doc(
+ "Selects wide or narrow FM for VFO B. Use the bandwidth "
+ "required by the channel plan.")
work.append(vfobwide)
if self.COLOR_LCD:
val = min(_mem.vfo.c.wide, len(LIST_WIDE) - 1)
rs = RadioSettingValueList(LIST_WIDE, current_index=val)
vfocwide = RadioSetting("vfo.c.wide", "VFO C bandwidth", rs)
+ vfocwide.set_doc(
+ "Selects wide or narrow FM for VFO C. Use the bandwidth "
+ "required by the channel plan.")
work.append(vfocwide)
if not self.COLOR_LCD4:
@@ -2112,38 +2398,59 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(LIST_WIDE, current_index=val)
vfodwide = RadioSetting("vfo.d.wide",
"VFO D bandwidth", rs)
+ vfodwide.set_doc(
+ "Selects wide or narrow FM for VFO D. Use the "
+ "bandwidth required by the channel plan.")
work.append(vfodwide)
val = min(_mem.vfo.a.step, len(LIST_STEP) - 1)
rs = RadioSettingValueList(LIST_STEP, current_index=val)
vfoastep = RadioSetting("vfo.a.step", "VFO A step", rs)
+ vfoastep.set_doc(
+ "Sets how far VFO A moves for each tuning step and while "
+ "scanning in Frequency mode.")
work.append(vfoastep)
val = min(_mem.vfo.b.step, len(LIST_STEP) - 1)
rs = RadioSettingValueList(LIST_STEP, current_index=val)
vfobstep = RadioSetting("vfo.b.step", "VFO B step", rs)
+ vfobstep.set_doc(
+ "Sets how far VFO B moves for each tuning step and while "
+ "scanning in Frequency mode.")
work.append(vfobstep)
if self.COLOR_LCD:
val = min(_mem.vfo.c.step, len(LIST_STEP) - 1)
rs = RadioSettingValueList(LIST_STEP, current_index=val)
vfocstep = RadioSetting("vfo.c.step", "VFO C step", rs)
+ vfocstep.set_doc(
+ "Sets how far VFO C moves for each tuning step and while "
+ "scanning in Frequency mode.")
work.append(vfocstep)
if not self.COLOR_LCD4:
val = min(_mem.vfo.d.step, len(LIST_STEP) - 1)
rs = RadioSettingValueList(LIST_STEP, current_index=val)
vfodstep = RadioSetting("vfo.d.step", "VFO D step", rs)
+ vfodstep.set_doc(
+ "Sets how far VFO D moves for each tuning step and while "
+ "scanning in Frequency mode.")
work.append(vfodstep)
val = min(_mem.vfo.a.optsig, len(OPTSIG_LIST) - 1)
rs = RadioSettingValueList(OPTSIG_LIST, current_index=val)
vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal", rs)
+ vfoaoptsig.set_doc(
+ "Selects whether VFO A requires DTMF, 2-tone, or 5-tone optional "
+ "signalling, or uses none.")
work.append(vfoaoptsig)
val = min(_mem.vfo.b.optsig, len(OPTSIG_LIST) - 1)
rs = RadioSettingValueList(OPTSIG_LIST, current_index=val)
vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal", rs)
+ vfoboptsig.set_doc(
+ "Selects whether VFO B requires DTMF, 2-tone, or 5-tone optional "
+ "signalling, or uses none.")
work.append(vfoboptsig)
if self.COLOR_LCD:
@@ -2151,6 +2458,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(OPTSIG_LIST, current_index=val)
vfocoptsig = RadioSetting("vfo.c.optsig",
"VFO C optional signal", rs)
+ vfocoptsig.set_doc(
+ "Selects whether VFO C requires DTMF, 2-tone, or 5-tone "
+ "optional signalling, or uses none.")
work.append(vfocoptsig)
if not self.COLOR_LCD4:
@@ -2158,22 +2468,35 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(OPTSIG_LIST, current_index=val)
vfodoptsig = RadioSetting("vfo.d.optsig",
"VFO D optional signal", rs)
+ vfodoptsig.set_doc(
+ "Selects whether VFO D requires DTMF, 2-tone, or 5-tone "
+ "optional signalling, or uses none.")
work.append(vfodoptsig)
val = min(_mem.vfo.a.spmute, len(SPMUTE_LIST) - 1)
rs = RadioSettingValueList(SPMUTE_LIST, current_index=val)
vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute", rs)
+ vfoaspmute.set_doc(
+ "Controls whether VFO A's speaker opens for its CTCSS/DCS tone, "
+ "the optional signal, or the configured combination of both.")
work.append(vfoaspmute)
val = min(_mem.vfo.b.spmute, len(SPMUTE_LIST) - 1)
rs = RadioSettingValueList(SPMUTE_LIST, current_index=val)
vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute", rs)
+ vfobspmute.set_doc(
+ "Controls whether VFO B's speaker opens for its CTCSS/DCS tone, "
+ "the optional signal, or the configured combination of both.")
work.append(vfobspmute)
if self.COLOR_LCD:
val = min(_mem.vfo.c.spmute, len(SPMUTE_LIST) - 1)
rs = RadioSettingValueList(SPMUTE_LIST, current_index=val)
vfocspmute = RadioSetting("vfo.c.spmute", "VFO C speaker mute", rs)
+ vfocspmute.set_doc(
+ "Controls whether VFO C's speaker opens for its CTCSS/DCS "
+ "tone, the optional signal, or the configured combination "
+ "of both.")
work.append(vfocspmute)
if not self.COLOR_LCD4:
@@ -2181,42 +2504,67 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(SPMUTE_LIST, current_index=val)
vfodspmute = RadioSetting("vfo.d.spmute",
"VFO D speaker mute", rs)
+ vfodspmute.set_doc(
+ "Controls whether VFO D's speaker opens for its "
+ "CTCSS/DCS tone, the optional signal, or the configured "
+ "combination of both.")
work.append(vfodspmute)
if not self.COLOR_LCD or \
(self.COLOR_LCD and not self.VENDOR == "BTECH"):
rs = RadioSettingValueBoolean(_mem.vfo.a.scramble)
vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble", rs)
+ vfoascr.set_doc(
+ "Enables voice inversion on VFO A. Both radios must use "
+ "compatible scrambling; this is not secure encryption.")
work.append(vfoascr)
rs = RadioSettingValueBoolean(_mem.vfo.b.scramble)
vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble", rs)
+ vfobscr.set_doc(
+ "Enables voice inversion on VFO B. Both radios must use "
+ "compatible scrambling; this is not secure encryption.")
work.append(vfobscr)
if self.COLOR_LCD and not self.VENDOR == "BTECH":
rs = RadioSettingValueBoolean(_mem.vfo.c.scramble)
vfocscr = RadioSetting("vfo.c.scramble", "VFO C scramble", rs)
+ vfocscr.set_doc(
+ "Enables voice inversion on VFO C. Both radios must use "
+ "compatible scrambling; this is not secure encryption.")
work.append(vfocscr)
rs = RadioSettingValueBoolean(_mem.vfo.d.scramble)
vfodscr = RadioSetting("vfo.d.scramble", "VFO D scramble", rs)
+ vfodscr.set_doc(
+ "Enables voice inversion on VFO D. Both radios must use "
+ "compatible scrambling; this is not secure encryption.")
work.append(vfodscr)
if not self.MODEL == "GMRS-50X1":
val = min(_mem.vfo.a.scode, len(PTTIDCODE_LIST) - 1)
rs = RadioSettingValueList(PTTIDCODE_LIST, current_index=val)
vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID", rs)
+ vfoascode.set_doc(
+ "Selects which of the 15 programmed signalling codes VFO A "
+ "uses for PTT-ID and automatic calling.")
work.append(vfoascode)
val = min(_mem.vfo.b.scode, len(PTTIDCODE_LIST) - 1)
rs = RadioSettingValueList(PTTIDCODE_LIST, current_index=val)
vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID", rs)
+ vfobscode.set_doc(
+ "Selects which of the 15 programmed signalling codes VFO B "
+ "uses for PTT-ID and automatic calling.")
work.append(vfobscode)
if self.COLOR_LCD:
val = min(_mem.vfo.c.scode, len(PTTIDCODE_LIST) - 1)
rs = RadioSettingValueList(PTTIDCODE_LIST, current_index=val)
vfocscode = RadioSetting("vfo.c.scode", "VFO C PTT-ID", rs)
+ vfocscode.set_doc(
+ "Selects which of the 15 programmed signalling codes VFO "
+ "C uses for PTT-ID and automatic calling.")
work.append(vfocscode)
if not self.COLOR_LCD4:
@@ -2224,12 +2572,18 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
rs = RadioSettingValueList(PTTIDCODE_LIST,
current_index=val)
vfodscode = RadioSetting("vfo.d.scode", "VFO D PTT-ID", rs)
+ vfodscode.set_doc(
+ "Selects which of the 15 programmed signalling codes "
+ "VFO D uses for PTT-ID and automatic calling.")
work.append(vfodscode)
if not self.MODEL == "GMRS-50X1":
val = min(_mem.settings.pttid, len(PTTID_LIST) - 1)
rs = RadioSettingValueList(PTTID_LIST, current_index=val)
pttid = RadioSetting("settings.pttid", "PTT ID", rs)
+ pttid.set_doc(
+ "Controls when the selected PTT-ID is sent: at the beginning "
+ "of transmission (BOT), the end (EOT), both, or never.")
work.append(pttid)
if not self.COLOR_LCD:
@@ -2267,6 +2621,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Station name " + str(i),
RadioSettingValueString(0, 6, _filter(
preset.broadcast_station_name)))
+ line.set_doc(
+ "Sets the 6-character name shown for broadcast FM preset "
+ "%s." % i)
line.set_apply_callback(apply_fm_preset_name,
preset.broadcast_station_name)
@@ -2278,6 +2635,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val = RadioSettingValueFloat(0, 108, presetval)
fmfreq = RadioSetting("fm_presets_" + str(i) + "_freq",
"Frequency " + str(i), val)
+ fmfreq.set_doc(
+ "Sets broadcast FM preset %s's frequency. Use "
+ "87.5-108.0 MHz, or 0 to leave it unused." % i)
val.set_validate_callback(fm_validate)
fmfreq.set_apply_callback(apply_fm_freq, preset)
fm_presets.append(line)
@@ -2296,12 +2656,19 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"TX-Disable",
RadioSettingValueBoolean(
_mem.dtmf_settings.txdisable))
+ txdisable.set_doc(
+ "Stores whether DTMF remote control has disabled transmission. "
+ "Normally leave this off; a remote stun or kill command can set "
+ "it.")
dtmf_enc_settings.append(txdisable)
rxdisable = RadioSetting("dtmf_settings.rxdisable",
"RX-Disable",
RadioSettingValueBoolean(
_mem.dtmf_settings.rxdisable))
+ rxdisable.set_doc(
+ "Stores whether DTMF remote control has disabled reception. "
+ "Normally leave this off; a remote kill command can set it.")
dtmf_enc_settings.append(rxdisable)
if _mem.dtmf_settings.dtmfspeed_on > 0x0F:
@@ -2313,6 +2680,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"DTMF Speed (On Time)",
RadioSettingValueList(LIST_DTMF_SPEED,
current_index=val))
+ dtmfspeed_on.set_doc(
+ "Sets how long each DTMF tone is transmitted. Increase it if the "
+ "receiving system does not reliably decode digits.")
dtmf_enc_settings.append(dtmfspeed_on)
if _mem.dtmf_settings.dtmfspeed_off > 0x0F:
@@ -2324,6 +2694,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"DTMF Speed (Off Time)",
RadioSettingValueList(LIST_DTMF_SPEED,
current_index=val))
+ dtmfspeed_off.set_doc(
+ "Sets the silent gap between transmitted DTMF tones. Increase it "
+ "if the receiving system cannot separate adjacent digits.")
dtmf_enc_settings.append(dtmfspeed_off)
def memory2string(dmtf_mem):
@@ -2354,6 +2727,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
False, CHARSET_DTMF_DIGITS)
line = RadioSetting("dtmf_code_" + str(i) + "_code",
"DMTF Code " + str(i), val)
+ line.set_doc(
+ "Programs DTMF calling code %s. Select this code as a "
+ "channel or VFO's PTT-ID to send it automatically." % i)
line.set_apply_callback(apply_dmtf_frame, dtmfcode.code)
dtmf_enc_settings.append(line)
i = i + 1
@@ -2362,6 +2738,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Master and Vice ID",
RadioSettingValueBoolean(
_mem.dtmf_settings.mastervice))
+ line.set_doc(
+ "Enables the secondary (vice) controller ID in addition to the "
+ "master ID for DTMF remote-control commands.")
dtmf_dec_settings.append(line)
val = RadioSettingValueString(0, 16, memory2string(
@@ -2369,6 +2748,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
False, CHARSET_DTMF_DIGITS)
line = RadioSetting("dtmf_settings.masterid",
"Master Control ID ", val)
+ line.set_doc(
+ "Programs the DTMF ID that a master controller must send before "
+ "the radio accepts an enabled remote-control command.")
line.set_apply_callback(apply_dmtf_frame,
_mem.dtmf_settings.masterid)
dtmf_dec_settings.append(line)
@@ -2377,30 +2759,45 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Master Inspection",
RadioSettingValueBoolean(
_mem.dtmf_settings.minspection))
+ line.set_doc(
+ "Allows the master control ID to request a radio status check "
+ "after it has identified itself.")
dtmf_dec_settings.append(line)
line = RadioSetting("dtmf_settings.mmonitor",
"Master Monitor",
RadioSettingValueBoolean(
_mem.dtmf_settings.mmonitor))
+ line.set_doc(
+ "Allows the master control ID to open the radio's microphone "
+ "remotely after it has identified itself.")
dtmf_dec_settings.append(line)
line = RadioSetting("dtmf_settings.mstun",
"Master Stun",
RadioSettingValueBoolean(
_mem.dtmf_settings.mstun))
+ line.set_doc(
+ "Allows the master control ID to disable transmitting after it "
+ "has identified itself.")
dtmf_dec_settings.append(line)
line = RadioSetting("dtmf_settings.mkill",
"Master Kill",
RadioSettingValueBoolean(
_mem.dtmf_settings.mkill))
+ line.set_doc(
+ "Allows the master control ID to disable transmitting and "
+ "receiving after it has identified itself.")
dtmf_dec_settings.append(line)
line = RadioSetting("dtmf_settings.mrevive",
"Master Revive",
RadioSettingValueBoolean(
_mem.dtmf_settings.mrevive))
+ line.set_doc(
+ "Allows the master control ID to restore a stunned or killed "
+ "radio after it has identified itself.")
dtmf_dec_settings.append(line)
val = RadioSettingValueString(0, 16, memory2string(
@@ -2408,6 +2805,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
False, CHARSET_DTMF_DIGITS)
line = RadioSetting("dtmf_settings.viceid",
"Vice Control ID ", val)
+ line.set_doc(
+ "Programs the DTMF ID for the secondary (vice) controller. It is "
+ "used when Master and Vice ID is enabled.")
line.set_apply_callback(apply_dmtf_frame,
_mem.dtmf_settings.viceid)
dtmf_dec_settings.append(line)
@@ -2416,30 +2816,45 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Vice Inspection",
RadioSettingValueBoolean(
_mem.dtmf_settings.vinspection))
+ line.set_doc(
+ "Allows the vice control ID to request a radio status check "
+ "after it has identified itself.")
dtmf_dec_settings.append(line)
line = RadioSetting("dtmf_settings.vmonitor",
"Vice Monitor",
RadioSettingValueBoolean(
_mem.dtmf_settings.vmonitor))
+ line.set_doc(
+ "Allows the vice control ID to open the radio's microphone "
+ "remotely after it has identified itself.")
dtmf_dec_settings.append(line)
line = RadioSetting("dtmf_settings.vstun",
"Vice Stun",
RadioSettingValueBoolean(
_mem.dtmf_settings.vstun))
+ line.set_doc(
+ "Allows the vice control ID to disable transmitting after it has "
+ "identified itself.")
dtmf_dec_settings.append(line)
line = RadioSetting("dtmf_settings.vkill",
"Vice Kill",
RadioSettingValueBoolean(
_mem.dtmf_settings.vkill))
+ line.set_doc(
+ "Allows the vice control ID to disable transmitting and "
+ "receiving after it has identified itself.")
dtmf_dec_settings.append(line)
line = RadioSetting("dtmf_settings.vrevive",
"Vice Revive",
RadioSettingValueBoolean(
_mem.dtmf_settings.vrevive))
+ line.set_doc(
+ "Allows the vice control ID to restore a stunned or killed radio "
+ "after it has identified itself.")
dtmf_dec_settings.append(line)
val = RadioSettingValueString(0, 16, memory2string(
@@ -2447,6 +2862,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
False, CHARSET_DTMF_DIGITS)
line = RadioSetting("dtmf_settings.inspection",
"Inspection", val)
+ line.set_doc(
+ "Programs the DTMF sequence for the remote inspection or "
+ "status-check command.")
line.set_apply_callback(apply_dmtf_frame,
_mem.dtmf_settings.inspection)
dtmf_dec_settings.append(line)
@@ -2456,6 +2874,8 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
False, CHARSET_DTMF_DIGITS)
line = RadioSetting("dtmf_settings.alarmcode",
"Alarm", val)
+ line.set_doc(
+ "Programs the DTMF sequence used for the alarm command.")
line.set_apply_callback(apply_dmtf_frame,
_mem.dtmf_settings.alarmcode)
dtmf_dec_settings.append(line)
@@ -2465,6 +2885,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
False, CHARSET_DTMF_DIGITS)
line = RadioSetting("dtmf_settings.kill",
"Kill", val)
+ line.set_doc(
+ "Programs the DTMF remote-kill sequence. A valid controller can "
+ "use it to disable both transmitting and receiving.")
line.set_apply_callback(apply_dmtf_frame,
_mem.dtmf_settings.kill)
dtmf_dec_settings.append(line)
@@ -2474,6 +2897,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
False, CHARSET_DTMF_DIGITS)
line = RadioSetting("dtmf_settings.monitor",
"Monitor", val)
+ line.set_doc(
+ "Programs the DTMF remote-monitor sequence used to open the "
+ "radio's microphone from a compatible controller.")
line.set_apply_callback(apply_dmtf_frame,
_mem.dtmf_settings.monitor)
dtmf_dec_settings.append(line)
@@ -2483,6 +2909,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
False, CHARSET_DTMF_DIGITS)
line = RadioSetting("dtmf_settings.stun",
"Stun", val)
+ line.set_doc(
+ "Programs the DTMF remote-stun sequence. A valid controller can "
+ "use it to disable transmitting.")
line.set_apply_callback(apply_dmtf_frame,
_mem.dtmf_settings.stun)
dtmf_dec_settings.append(line)
@@ -2492,6 +2921,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
False, CHARSET_DTMF_DIGITS)
line = RadioSetting("dtmf_settings.revive",
"Revive", val)
+ line.set_doc(
+ "Programs the DTMF remote-revive sequence used to restore a "
+ "radio after a stun or kill command.")
line.set_apply_callback(apply_dmtf_frame,
_mem.dtmf_settings.revive)
dtmf_dec_settings.append(line)
@@ -2513,6 +2945,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Group Code",
RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
current_index=idx))
+ line.set_doc(
+ "Selects the special DTMF digit interpreted as a group-call "
+ "wildcard by the decoder.")
line.set_apply_callback(apply_dmtf_listvalue,
_mem.dtmf_settings.groupcode)
dtmf_dec_settings.append(line)
@@ -2527,6 +2962,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Space Code",
RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
current_index=idx))
+ line.set_doc(
+ "Selects the special DTMF digit interpreted as a separator by "
+ "the decoder.")
line.set_apply_callback(apply_dmtf_listvalue,
_mem.dtmf_settings.spacecode)
dtmf_dec_settings.append(line)
@@ -2541,6 +2979,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Reset time",
RadioSettingValueList(LIST_5TONE_RESET_COLOR,
current_index=val))
+ line.set_doc(
+ "Sets how long the DTMF decoder remains active after a valid "
+ "code before returning to its normal state.")
dtmf_dec_settings.append(line)
else:
if _mem.dtmf_settings.resettime > 0x4F:
@@ -2552,6 +2993,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Reset time",
RadioSettingValueList(LIST_5TONE_RESET,
current_index=val))
+ line.set_doc(
+ "Sets how long the DTMF decoder remains active after a valid "
+ "code before returning to its normal state.")
dtmf_dec_settings.append(line)
if _mem.dtmf_settings.delayproctime > 0x27:
@@ -2563,6 +3007,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Delay processing time",
RadioSettingValueList(LIST_DTMF_DELAY,
current_index=val))
+ line.set_doc(
+ "Sets how long the radio waits after decoding a DTMF command "
+ "before processing its response.")
dtmf_dec_settings.append(line)
# 5 Tone Settings
@@ -2598,6 +3045,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Period (ms)", RadioSettingValueList
(LIST_5TONE_STANDARD_PERIODS,
current_index=period))
+ line.set_doc(
+ "Sets the duration of each tone when using the %s "
+ "5-tone standard." % LIST_5TONE_STANDARDS[i])
line.set_apply_callback(apply_list_value, standard.period)
std_5tone.append(line)
else:
@@ -2615,6 +3065,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Group Tone",
RadioSettingValueList(LIST_5TONE_DIGITS,
current_index=group_tone))
+ line.set_doc(
+ "Selects the digit that represents a group call in the "
+ "%s 5-tone standard." % LIST_5TONE_STANDARDS[i])
line.set_apply_callback(apply_list_value,
standard.group_tone)
std_5tone.append(line)
@@ -2633,6 +3086,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Repeat Tone",
RadioSettingValueList(LIST_5TONE_DIGITS,
current_index=repeat_tone))
+ line.set_doc(
+ "Selects the substitute digit sent for consecutive "
+ "repeated digits in the %s 5-tone standard." %
+ LIST_5TONE_STANDARDS[i])
line.set_apply_callback(apply_list_value,
standard.repeat_tone)
std_5tone.append(line)
@@ -2698,6 +3155,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"_5tone_code_" + str(i) + "_std", " Standard",
RadioSettingValueList(
LIST_5TONE_STANDARDS, current_index=currentVal))
+ line.set_doc(
+ "Selects the signalling standard used by 5-tone calling "
+ "code %s." % i)
line.set_apply_callback(my_apply_5tonestdlist_value,
code.standard)
code_5tone.append(line)
@@ -2706,6 +3166,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
frame2string(code.frame1), False)
line = RadioSetting("_5tone_code_" + str(i) + "_frame1",
" Frame 1", val)
+ line.set_doc(
+ "Programs frame 1 of 5-tone calling code %s. Enter exactly "
+ "five digits, or leave it blank to disable this frame." % i)
val.set_validate_callback(validate_5tone_frame)
line.set_apply_callback(apply_5tone_frame, code.frame1)
code_5tone.append(line)
@@ -2714,6 +3177,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
frame2string(code.frame2), False)
line = RadioSetting("_5tone_code_" + str(i) + "_frame2",
" Frame 2", val)
+ line.set_doc(
+ "Programs frame 2 of 5-tone calling code %s. Enter exactly "
+ "five digits, or leave it blank to disable this frame." % i)
val.set_validate_callback(validate_5tone_frame)
line.set_apply_callback(apply_5tone_frame, code.frame2)
code_5tone.append(line)
@@ -2722,6 +3188,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
frame2string(code.frame3), False)
line = RadioSetting("_5tone_code_" + str(i) + "_frame3",
" Frame 3", val)
+ line.set_doc(
+ "Programs frame 3 of 5-tone calling code %s. Enter exactly "
+ "five digits, or leave it blank to disable this frame." % i)
val.set_validate_callback(validate_5tone_frame)
line.set_apply_callback(apply_5tone_frame, code.frame3)
code_5tone.append(line)
@@ -2732,6 +3201,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"5 Tone decode call Frame 1",
RadioSettingValueBoolean(
_mem._5tone_settings._5tone_decode_call_frame1))
+ _5_tone_decode1.set_doc(
+ "Sounds a call alert after frame 1 of a received 5-tone code is "
+ "decoded.")
group_5tone.append(_5_tone_decode1)
_5_tone_decode2 = RadioSetting(
@@ -2739,6 +3211,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"5 Tone decode call Frame 2",
RadioSettingValueBoolean(
_mem._5tone_settings._5tone_decode_call_frame2))
+ _5_tone_decode2.set_doc(
+ "Sounds a call alert after frame 2 of a received 5-tone code is "
+ "decoded.")
group_5tone.append(_5_tone_decode2)
_5_tone_decode3 = RadioSetting(
@@ -2746,6 +3221,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"5 Tone decode call Frame 3",
RadioSettingValueBoolean(
_mem._5tone_settings._5tone_decode_call_frame3))
+ _5_tone_decode3.set_doc(
+ "Sounds a call alert after frame 3 of a received 5-tone code is "
+ "decoded.")
group_5tone.append(_5_tone_decode3)
_5_tone_decode_disp1 = RadioSetting(
@@ -2753,6 +3231,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"5 Tone decode disp Frame 1",
RadioSettingValueBoolean(
_mem._5tone_settings._5tone_decode_disp_frame1))
+ _5_tone_decode_disp1.set_doc(
+ "Shows the decoded call after frame 1 of a received 5-tone code "
+ "is decoded.")
group_5tone.append(_5_tone_decode_disp1)
_5_tone_decode_disp2 = RadioSetting(
@@ -2760,6 +3241,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"5 Tone decode disp Frame 2",
RadioSettingValueBoolean(
_mem._5tone_settings._5tone_decode_disp_frame2))
+ _5_tone_decode_disp2.set_doc(
+ "Shows the decoded call after frame 2 of a received 5-tone code "
+ "is decoded.")
group_5tone.append(_5_tone_decode_disp2)
_5_tone_decode_disp3 = RadioSetting(
@@ -2767,6 +3251,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"5 Tone decode disp Frame 3",
RadioSettingValueBoolean(
_mem._5tone_settings._5tone_decode_disp_frame3))
+ _5_tone_decode_disp3.set_doc(
+ "Shows the decoded call after frame 3 of a received 5-tone code "
+ "is decoded.")
group_5tone.append(_5_tone_decode_disp3)
decode_standard = _mem._5tone_settings.decode_standard
@@ -2778,6 +3265,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
RadioSettingValueList(
LIST_5TONE_STANDARDS_without_none,
current_index=decode_standard))
+ line.set_doc(
+ "Selects the signalling standard used to decode incoming "
+ "5-tone calls.")
group_5tone.append(line)
else:
LOG.debug("Invalid decode std...")
@@ -2791,6 +3281,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
current_index=_5tone_delay1)
line = RadioSetting("_5tone_settings._5tone_delay1",
"5 Tone Delay Frame 1", list)
+ line.set_doc(
+ "Sets the pause after frame 1 when sending a multi-frame "
+ "5-tone calling code.")
group_5tone.append(line)
else:
LOG.debug(
@@ -2806,6 +3299,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
current_index=_5tone_delay2)
line = RadioSetting("_5tone_settings._5tone_delay2",
"5 Tone Delay Frame 2", list)
+ line.set_doc(
+ "Sets the pause after frame 2 when sending a multi-frame "
+ "5-tone calling code.")
group_5tone.append(line)
else:
LOG.debug("Invalid value for 5tone delay (frame2)! Disabling.")
@@ -2820,6 +3316,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
current_index=_5tone_delay3)
line = RadioSetting("_5tone_settings._5tone_delay3",
"5 Tone Delay Frame 3", list)
+ line.set_doc(
+ "Sets the pause after frame 3 when sending a multi-frame "
+ "5-tone calling code.")
group_5tone.append(line)
else:
LOG.debug("Invalid value for 5tone delay (frame3)! Disabling.")
@@ -2836,6 +3335,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
line = RadioSetting(
"_5tone_settings._5tone_first_digit_ext_length",
"First digit extend length", list)
+ line.set_doc(
+ "Extends the first digit of a transmitted 5-tone code by the "
+ "selected time.")
group_5tone.append(line)
else:
LOG.debug("Invalid value for 5tone ext length! Disabling.")
@@ -2850,6 +3352,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
current_index=decode_reset_time)
line = RadioSetting("_5tone_settings.decode_reset_time",
"Decode reset time", list)
+ line.set_doc(
+ "Sets how long a successful 5-tone decode remains active "
+ "before the decoder resets.")
group_5tone.append(line)
else:
LOG.debug("Invalid value decode reset time! Disabling.")
@@ -2872,6 +3377,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
current_index=duration_1st_tone)
line = RadioSetting("_2tone.duration_1st_tone",
"Duration 1st Tone", val)
+ line.set_doc(
+ "Sets how long the first tone of every 2-tone calling code "
+ "is transmitted.")
encode_2tone.append(line)
duration_2nd_tone = self._memobj._2tone.duration_2nd_tone
@@ -2885,6 +3393,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
current_index=duration_2nd_tone)
line = RadioSetting("_2tone.duration_2nd_tone",
"Duration 2nd Tone", val)
+ line.set_doc(
+ "Sets how long the second tone of every 2-tone calling code "
+ "is transmitted.")
encode_2tone.append(line)
duration_gap = self._memobj._2tone.duration_gap
@@ -2898,6 +3409,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"_2tone.duration_gap", "Duration of gap",
RadioSettingValueList(
LIST_5TONE_DELAY, current_index=duration_gap))
+ line.set_doc(
+ "Sets the silent gap between the first and second tones of a "
+ "2-tone calling code.")
encode_2tone.append(line)
def _2tone_validate(value):
@@ -2929,6 +3443,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val1 = RadioSettingValueInteger(0, 65535, tmp)
freq1 = RadioSetting("2tone_code_" + str(i) + "_freq1",
"Frequency 1", val1)
+ freq1.set_doc(
+ "Sets tone 1 of 2-tone calling code %s in hertz. Use "
+ "300-3000 Hz, or 0 to leave it unused." % i)
val1.set_validate_callback(_2tone_validate)
freq1.set_apply_callback(apply_2tone_freq, code.freq1)
code_2tone.append(freq1)
@@ -2939,6 +3456,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
val2 = RadioSettingValueInteger(0, 65535, tmp)
freq2 = RadioSetting("2tone_code_" + str(i) + "_freq2",
"Frequency 2", val2)
+ freq2.set_doc(
+ "Sets tone 2 of 2-tone calling code %s in hertz. Use "
+ "300-3000 Hz, or 0 to leave it unused." % i)
val2.set_validate_callback(_2tone_validate)
freq2.set_apply_callback(apply_2tone_freq, code.freq2)
code_2tone.append(freq2)
@@ -2955,6 +3475,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
current_index=decode_reset_time)
line = RadioSetting("_2tone.reset_time",
"Decode reset time", list)
+ line.set_doc(
+ "Sets how long a successful 2-tone decode remains active "
+ "before the decoder resets.")
decode_2tone.append(line)
else:
LOG.debug("Invalid value decode reset time! Disabling.")
@@ -2997,6 +3520,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Dec " + str(j), RadioSettingValueList
(LIST_2TONE_DEC,
current_index=val))
+ line.set_doc(
+ "Selects the ordered pair of decode frequencies for "
+ "match rule %s of 2-tone decode code %s." % (j, i))
line.set_apply_callback(apply_list_value, dec.dec)
_2tone_dec_code.append(line)
else:
@@ -3016,6 +3542,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Response " + str(j), RadioSettingValueList
(LIST_2TONE_RESPONSE,
current_index=val))
+ line.set_doc(
+ "Selects the radio's response after match rule %s of "
+ "2-tone decode code %s is received." % (j, i))
line.set_apply_callback(apply_list_value, dec.response)
_2tone_dec_code.append(line)
else:
@@ -3036,6 +3565,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
"Alert " + str(j), RadioSettingValueList
(PTTIDCODE_LIST,
current_index=val))
+ line.set_doc(
+ "Selects the programmed alert entry associated with "
+ "match rule %s of 2-tone decode code %s." % (j, i))
line.set_apply_callback(apply_list_value, dec.alert)
_2tone_dec_code.append(line)
else:
@@ -3061,6 +3593,10 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
frq = RadioSetting("2tone_dec_" + str(i) +
"_freq" + str(char),
("Decode Frequency " + str(char)), val)
+ frq.set_doc(
+ "Sets decode frequency %s for 2-tone decode code %s in "
+ "hertz. Use 300-3000 Hz, or 0 to leave it unused." %
+ (char, i))
val.set_validate_callback(_2tone_validate)
frq.set_apply_callback(apply_2tone_freq_pair, freq)
_2tone_dec_code.append(frq)
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 6b463ff..7a0ffcb 100644
--- a/chirp/drivers/ft4.py
+++ b/chirp/drivers/ft4.py
@@ -32,6 +32,7 @@ from chirp.settings import RadioSetting, RadioSettingGroup, \
LOG = logging.getLogger(__name__)
COMM_DIRECTION_FROM = 0
COMM_DIRECTION_TO = 1
+PROGRAM_CMD = b"PROGRAM"
# Layout of Radio memory image.
@@ -237,6 +238,8 @@ def variable_len_resp(pipe):
toolong = 256 # arbitrary
while True:
b = pipe.read(1)
+ if not b:
+ raise errors.RadioError("No response from radio")
if b == b'\x06':
break
else:
@@ -262,6 +265,8 @@ def sendcmd(pipe, cmd, response_len, retry=0):
"""
pipe.write(cmd)
echo = pipe.read(len(cmd))
+ if not echo:
+ raise errors.RadioError("No echo from cable")
if echo != cmd:
msg = "Bad echo. Sent:" + util.hexprint(cmd) + ", "
msg += "Received:" + util.hexprint(echo)
@@ -272,6 +277,9 @@ def sendcmd(pipe, cmd, response_len, retry=0):
return variable_len_resp(pipe)
if response_len > 0:
response = pipe.read(response_len)
+ if not response:
+ if cmd == PROGRAM_CMD:
+ raise errors.RadioNoResponse()
else:
response = b""
ack = pipe.read(1)
@@ -295,8 +303,10 @@ def enter_clonemode(radio):
for use_end in range(0, 3):
for i in range(0, 3):
try:
- if b"QX" == sendcmd(radio.pipe, b"PROGRAM", 2):
+ if b"QX" == sendcmd(radio.pipe, PROGRAM_CMD, 2):
return
+ except errors.RadioNoResponse:
+ raise
except Exception:
continue
sendcmd(radio.pipe, b"END", 0)
@@ -540,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
@@ -670,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
@@ -765,6 +791,8 @@ class YaesuSC35GenericRadio(chirp_common.CloneModeRadio,
def sync_in(self):
try:
self._mmap = do_download(self)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError("Failed to communicate with radio: %s" % e)
self.process_mmap()
@@ -773,6 +801,8 @@ class YaesuSC35GenericRadio(chirp_common.CloneModeRadio,
def sync_out(self):
try:
do_upload(self)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError("Failed to communicate with radio: %s" % e)
@@ -872,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",
@@ -1143,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"]
@@ -1220,6 +1253,11 @@ class YaesuSC35GenericRadio(chirp_common.CloneModeRadio,
store_bit(self._memobj.enable, ndx, False)
return
+ # Clear unknowns
+ _mem.unused = 0
+ _mem.unknown1 = 0
+ _mem.unknown2 = 0
+
txfreq = mem.freq / 10 # really. RX freq is used for TX base
_mem.freq = txfreq
self.encode_sql(mem, _mem)
@@ -1283,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):
"""
@@ -1310,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 2f96ccf..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]
@@ -457,6 +463,10 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
if data:
break
time.sleep(0.5)
+ if not data:
+ if blocknum == 0:
+ raise errors.RadioNoResponse()
+ raise errors.RadioError("No response reading block %02X" % blocknum)
if len(data) == block + 2 and data[0] == blocknum:
checksum = yaesu_clone.YaesuChecksum(1, block)
if checksum.get_existing(data) != \
@@ -564,7 +574,11 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
if not buf or buf[:1] != CMD_ACK:
time.sleep(delay)
buf = self.pipe.read(1)
- if not buf or buf[:1] != CMD_ACK:
+ if not buf:
+ if blocks == 0:
+ raise errors.RadioNoResponse()
+ raise errors.RadioError("Radio did not ack block %i" % blocks)
+ if buf[:1] != CMD_ACK:
raise Exception(_("Radio did not ack block %i") % blocks)
pos += block
blocks += 1
@@ -641,8 +655,8 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
# since the special memories have string tags on the GUI and not
# numbers. Convert these back to the int for the specials
if isinstance(memory.number, str):
- memory.number = self.SPECIAL_MEMORIES[memory.number]
- return self._set_special(memory)
+ numeric_number = self.SPECIAL_MEMORIES[memory.number]
+ return self._set_special(memory, mem_number=numeric_number)
if memory.number < 0:
return self._set_special(memory)
else:
@@ -716,33 +730,35 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
return mem
- def _set_special(self, mem):
- if mem.empty and mem.number not in self.SPECIAL_PMS.values():
+ def _set_special(self, mem, mem_number=None):
+ number = mem_number if mem_number is not None else mem.number
+
+ if mem.empty and number not in self.SPECIAL_PMS.values():
# can't delete special memories! But can delete PMS mems
raise errors.RadioError("Sorry, special memory can't be deleted")
- cur_mem = self._get_special(self.SPECIAL_MEMORIES_REV[mem.number])
-
- if mem.number in range(self.FIRST_VFOA_INDEX,
- self.LAST_VFOA_INDEX - 1, -1):
- _mem = self._memobj.vfoa[-self.LAST_VFOA_INDEX + mem.number]
- elif mem.number in range(self.FIRST_VFOB_INDEX,
- self.LAST_VFOB_INDEX - 1, -1):
- _mem = self._memobj.vfob[-self.LAST_VFOB_INDEX + mem.number]
- elif mem.number in range(-4, -6, -1):
- _mem = self._memobj.home[5 + mem.number]
- elif mem.number == -3:
+ cur_mem = self._get_special(self.SPECIAL_MEMORIES_REV[number])
+
+ if number in range(self.FIRST_VFOA_INDEX,
+ self.LAST_VFOA_INDEX - 1, -1):
+ _mem = self._memobj.vfoa[-self.LAST_VFOA_INDEX + number]
+ elif number in range(self.FIRST_VFOB_INDEX,
+ self.LAST_VFOB_INDEX - 1, -1):
+ _mem = self._memobj.vfob[-self.LAST_VFOB_INDEX + number]
+ elif number in range(-4, -6, -1):
+ _mem = self._memobj.home[5 + number]
+ elif number == -3:
_mem = self._memobj.qmb
- elif mem.number == -2:
+ elif number == -2:
_mem = self._memobj.mtqmb
- elif mem.number == -1:
+ elif number == -1:
_mem = self._memobj.mtune
- elif mem.number in self.SPECIAL_PMS.values():
+ elif number in self.SPECIAL_PMS.values():
# ft450 does NOT use the pmsvisible or pmsfilled fields,
# it uses the next 4 bits after the 500 normal memories
# in the main visible and filled settings area.
if self.FT450:
- pmsnum = 501 + (-self.LAST_PMS_INDEX) + mem.number
+ pmsnum = 501 + (-self.LAST_PMS_INDEX) + number
wasused = (self._memobj.visible[(pmsnum - 1) // 8] >>
(pmsnum - 1) % 8) & 0x01
wasvalid = (self._memobj.filled[(pmsnum - 1) // 8] >>
@@ -758,9 +774,9 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
% 8
self._memobj.filled[(pmsnum - 1) // 8] |= 1 << (pmsnum - 1) \
% 8
- _mem = self._memobj.pms[-self.LAST_PMS_INDEX + mem.number]
+ _mem = self._memobj.pms[-self.LAST_PMS_INDEX + number]
else: #self.FT450
- bitindex = (-self.LAST_PMS_INDEX) + mem.number
+ bitindex = (-self.LAST_PMS_INDEX) + number
wasused = (self._memobj.pmsvisible >> bitindex) & 0x01
wasvalid = (self._memobj.pmsfilled >> bitindex) & 0x01
if mem.empty:
@@ -775,7 +791,7 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
# pylint get confused by |= operator
self._memobj.pmsvisible = self._memobj.pmsvisible | 1 << bitindex
self._memobj.pmsfilled = self._memobj.pmsfilled | 1 << bitindex
- _mem = self._memobj.pms[-self.LAST_PMS_INDEX + mem.number]
+ _mem = self._memobj.pms[-self.LAST_PMS_INDEX + number]
else:
raise errors.RadioError("Sorry, you can't edit"
" that special memory.")
@@ -930,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
@@ -981,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",
@@ -1001,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
@@ -1140,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
@@ -1206,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)]
@@ -1218,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 - - -
@@ -1282,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
@@ -1369,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
@@ -1428,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",
@@ -1449,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
@@ -1458,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
@@ -1479,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
@@ -1505,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
@@ -1551,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/ft50.py b/chirp/drivers/ft50.py
index d181388..efcd758 100644
--- a/chirp/drivers/ft50.py
+++ b/chirp/drivers/ft50.py
@@ -502,7 +502,7 @@ class FT50Radio(yaesu_clone.YaesuCloneModeRadio):
RadioSettingValueBoolean(_settings.code_dec_c_en))
dtmf.append(rs)
- _str = str(bitwise.bcd_to_int(_settings.pagingcodec_ro))
+ _str = str(_settings.pagingcodec_ro)
code = RadioSettingValueString(0, 3, _str)
code.set_charset(NUMERIC_CHARSET + list(" "))
code.set_mutable(False)
@@ -514,7 +514,7 @@ class FT50Radio(yaesu_clone.YaesuCloneModeRadio):
RadioSettingValueBoolean(_settings.code_dec_p_en))
dtmf.append(rs)
- _str = str(bitwise.bcd_to_int(_settings.pagingcodep))
+ _str = str(_settings.pagingcodep)
code = RadioSettingValueString(0, 3, _str)
code.set_charset(NUMERIC_CHARSET + list(" "))
rs = RadioSetting("pagingcodep", "Paging Code P", code)
@@ -528,7 +528,7 @@ class FT50Radio(yaesu_clone.YaesuCloneModeRadio):
RadioSettingValueBoolean(getattr(_settings, name)))
dtmf.append(rs)
- _str = str(bitwise.bcd_to_int(_settings.pagingcode[i].digits))
+ _str = str(_settings.pagingcode[i].digits)
code = RadioSettingValueString(0, 3, _str)
code.set_charset(NUMERIC_CHARSET + list(" "))
rs = RadioSetting("pagingcode" + num, "Paging Code " + num, code)
@@ -561,13 +561,11 @@ class FT50Radio(yaesu_clone.YaesuCloneModeRadio):
_settings.digits = newval
continue
if (setting == "pagingcodep"):
- bitwise.int_to_bcd(_settings.pagingcodep,
- int(element.value))
+ _settings.pagingcodep = int(element.value)
continue
if re.match(r'pagingcode\d', setting):
idx = int(setting[-1:]) - 1
- bitwise.int_to_bcd(_settings.pagingcode[idx].digits,
- int(element.value))
+ _settings.pagingcode[idx].digits = int(element.value)
continue
newval = element.value
oldval = getattr(_settings, setting)
diff --git a/chirp/drivers/ft60.py b/chirp/drivers/ft60.py
index 361bbbb..b5d122d 100644
--- a/chirp/drivers/ft60.py
+++ b/chirp/drivers/ft60.py
@@ -30,6 +30,8 @@ ACK = b"\x06"
def _send(pipe, data):
pipe.write(data)
echo = pipe.read(len(data))
+ if not echo:
+ raise errors.RadioError("No echo from cable")
if echo != data:
raise errors.RadioError("Error reading echo (Bad cable?)")
@@ -47,7 +49,7 @@ def _download(radio):
LOG.info("Trying again...")
if not data:
- raise Exception("Radio is not responding")
+ raise errors.RadioNoResponse()
_send(radio.pipe, ACK)
@@ -74,13 +76,17 @@ def _upload(radio):
_send(radio.pipe, radio.get_mmap()[0:8])
ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != ACK:
- raise Exception("Radio did not respond")
+ raise Exception("Unexpected response from radio")
for i in range(0, 448):
offset = 8 + (i * 64)
_send(radio.pipe, radio.get_mmap()[offset:offset + 64])
ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioError(_("Radio did not ack block %i") % i)
if ack != ACK:
raise Exception(_("Radio did not ack block %i") % i)
diff --git a/chirp/drivers/ft7100.py b/chirp/drivers/ft7100.py
index dc97daa..97f2219 100644
--- a/chirp/drivers/ft7100.py
+++ b/chirp/drivers/ft7100.py
@@ -63,7 +63,7 @@ def _send_ack(pipe):
def _wait_for_ack(pipe):
echo = pipe.read(1)
if echo == b"":
- raise Exception("Failed to read ACK. No response from radio.")
+ raise errors.RadioNoResponse()
if echo != ACK:
raise Exception("Failed to read ACK. Expected: %r, got: %r.",
ACK, echo)
@@ -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/ft7800.py b/chirp/drivers/ft7800.py
index 4b6b722..c446b1a 100644
--- a/chirp/drivers/ft7800.py
+++ b/chirp/drivers/ft7800.py
@@ -162,6 +162,8 @@ def _send(ser, data):
ser.write(bytes([i]))
time.sleep(0.002)
echo = ser.read(len(data))
+ if not echo:
+ raise errors.RadioError("No echo from cable")
if echo != data:
raise errors.RadioError("Error reading echo (Bad cable?)")
@@ -176,6 +178,8 @@ def _download(radio):
break
if len(chunk) != radio._block_lengths[0]:
+ if not chunk:
+ raise errors.RadioNoResponse()
raise Exception("Failed to read header (%i)" % len(chunk))
data += chunk
@@ -204,14 +208,21 @@ def _download(radio):
def _upload(radio):
cur = 0
mmap = radio.get_mmap().get_byte_compatible()
+ first_exchange = True
for block in radio._block_lengths:
for _i in range(0, block, radio._block_size):
length = min(radio._block_size, block)
# LOG.debug("i=%i length=%i range: %i-%i" %
# (i, length, cur, cur+length))
_send(radio.pipe, mmap[cur:cur+length])
- if radio.pipe.read(1) != ACK:
+ ack = radio.pipe.read(1)
+ if not ack:
+ if first_exchange:
+ raise errors.RadioNoResponse()
raise errors.RadioError("Radio did not ack block at %i" % cur)
+ if ack != ACK:
+ raise errors.RadioError("Radio did not ack block at %i" % cur)
+ first_exchange = False
cur += length
time.sleep(0.05)
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/ft817.py b/chirp/drivers/ft817.py
index ea9e1c2..3d2c178 100644
--- a/chirp/drivers/ft817.py
+++ b/chirp/drivers/ft817.py
@@ -306,6 +306,8 @@ class FT817Radio(yaesu_clone.YaesuCloneModeRadio):
if data:
break
time.sleep(0.5)
+ if not data:
+ raise errors.RadioNoResponse()
if len(data) == block + 2 and data[0] == blocknum:
checksum = yaesu_clone.YaesuChecksum(1, block)
if checksum.get_existing(data) != \
@@ -401,7 +403,9 @@ class FT817Radio(yaesu_clone.YaesuCloneModeRadio):
if not buf or buf[0] != CMD_ACK:
time.sleep(delay)
buf = self.pipe.read(1)
- if not buf or buf[0] != CMD_ACK:
+ if not buf:
+ raise errors.RadioNoResponse()
+ if buf[0] != CMD_ACK:
LOG.debug(util.hexprint(buf))
raise Exception(_("Radio did not ack block %i") % blocks)
pos += block
diff --git a/chirp/drivers/ft90.py b/chirp/drivers/ft90.py
index a6d54c9..a4d1849 100644
--- a/chirp/drivers/ft90.py
+++ b/chirp/drivers/ft90.py
@@ -238,6 +238,11 @@ struct {
def _read(self, blocksize, blocknum):
data = self.pipe.read(blocksize+2)
+ if not data:
+ if blocknum == 0:
+ raise errors.RadioNoResponse()
+ raise errors.RadioError(
+ "No response reading block %02X" % blocknum)
# chew echo'd ack
self.pipe.write(CMD_ACK)
@@ -319,6 +324,11 @@ struct {
buf = self.pipe.read(1)
LOG.debug("ack recd:")
LOG.debug(util.hexprint(buf))
+ if not buf:
+ if blocknum == 0:
+ raise errors.RadioNoResponse()
+ raise errors.RadioError(
+ "Radio did not ack block %i" % blocknum)
if buf != CMD_ACK:
raise Exception("Radio did not ack block %i" % blocknum)
pos += blocksize
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/ftm350.py b/chirp/drivers/ftm350.py
index a1dd3af..6811306 100644
--- a/chirp/drivers/ftm350.py
+++ b/chirp/drivers/ftm350.py
@@ -125,12 +125,14 @@ def _clone_in(radio):
while length < radio._memsize:
frame = radio.pipe.read(131)
if length and not frame:
- raise errors.RadioError("Radio not responding")
+ raise errors.RadioError("Timed out reading from radio")
if not frame:
attempts -= 1
if attempts <= 0:
- raise errors.RadioError("Radio not responding")
+ if length:
+ raise errors.RadioError("Timed out reading from radio")
+ raise errors.RadioNoResponse()
if frame:
addr, = struct.unpack(">H", frame[0:2])
@@ -186,6 +188,8 @@ def _clone_out(radio):
frame += bytes([cs % 256])
radio.pipe.write(frame)
ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != b"\x06":
raise errors.RadioError("Radio refused block %i" % (i / 128))
time.sleep(0.05)
diff --git a/chirp/drivers/ga510.py b/chirp/drivers/ga510.py
index 7a9d24c..8c0f78b 100644
--- a/chirp/drivers/ga510.py
+++ b/chirp/drivers/ga510.py
@@ -50,13 +50,19 @@ def start_program(radio):
radio.pipe.read(256)
radio.pipe.write(radio._magic)
ack = radio.pipe.read(256)
+ if not ack:
+ raise errors.RadioNoResponse()
if not ack.endswith(b'\x06'):
LOG.debug('Ack was %r' % ack)
- raise errors.RadioError('Radio did not respond to clone request')
+ raise errors.RadioError('Unexpected response to clone request')
radio.pipe.write(b'F')
ident = radio.pipe.read(8)
+ if not ident:
+ raise errors.RadioNoResponse()
+ if len(ident) != 8:
+ raise errors.RadioError('Radio sent short ident response')
LOG.debug('Radio ident string is %r' % ident)
return ident
@@ -76,6 +82,10 @@ def do_download(radio):
radio.pipe.write(cmd)
block = radio.pipe.read(0x44)
+ if not block:
+ raise errors.RadioNoResponse()
+ if len(block) < 4:
+ raise errors.RadioError('Radio sent short block header')
header = block[:4]
rcmd, raddr, rlen = struct.unpack('>BHB', header)
block = block[4:]
@@ -112,6 +122,8 @@ def do_upload(radio):
radio.pipe.write(block)
ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != b'\x06':
raise errors.RadioError('Radio refused block at addr %04x' % addr)
@@ -360,6 +372,7 @@ class RadioddityGA510Radio(chirp_common.CloneModeRadio):
@classmethod
def detect_from_serial(cls, pipe):
+ saw_data = False
for rcls in reversed(cls.detected_models()):
pipe.baudrate = rcls.BAUD_RATE
radio = rcls(pipe)
@@ -368,13 +381,22 @@ class RadioddityGA510Radio(chirp_common.CloneModeRadio):
ident = baofeng_uv17Pro._do_ident(radio)
else:
ident = start_program(radio)
- except errors.RadioError:
+ except errors.RadioNoResponse:
LOG.debug('No response from radio with %s', rcls)
pipe.read(256)
continue
+ except errors.RadioError:
+ saw_data = True
+ LOG.debug('Unexpected response from radio with %s', rcls)
+ pipe.read(256)
+ continue
if ident:
+ saw_data = True
return rcls
- raise errors.RadioError('No response from radio')
+ saw_data = True
+ if saw_data:
+ raise errors.RadioError('Unexpected response from radio')
+ raise errors.RadioNoResponse()
def sync_in(self):
try:
@@ -1144,7 +1166,7 @@ class RadioddityGA510v2(baofeng_uv17.UV17):
BLOCK_SIZE = 0x40
BAUD_RATE = 57600
- _magic = b"PSEARCH"
+ _idents = [b"PSEARCH"]
_magic_response_length = 8
_magics = [(b"PASSSTA", 3), (b"SYSINFO", 1),
(b"\x56\x00\x00\x0A\x0D", 13), (b"\x06", 1),
diff --git a/chirp/drivers/generic_csv.py b/chirp/drivers/generic_csv.py
index 64dd8e4..2d50a4e 100644
--- a/chirp/drivers/generic_csv.py
+++ b/chirp/drivers/generic_csv.py
@@ -329,6 +329,9 @@ class CSVRadio(chirp_common.FileBackedRadio):
def set_memory(self, newmem):
newmem = newmem.dupe()
+ # unset immutable to allow name rstrip
+ newmem.immutable = []
+ newmem.name = newmem.name.rstrip()
if newmem.power is None:
newmem.power = DEFAULT_POWER_LEVEL
else:
@@ -338,7 +341,6 @@ class CSVRadio(chirp_common.FileBackedRadio):
chirp_common.dBm_to_watts(float(newmem.power)))
self._grow(newmem.number)
self.memories[newmem.number] = newmem
- self.memories[newmem.number].name = newmem.name.rstrip()
def erase_memory(self, number):
mem = chirp_common.Memory()
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 0586fd0..0d76901 100644
--- a/chirp/drivers/h777.py
+++ b/chirp/drivers/h777.py
@@ -23,10 +23,27 @@ 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__)
+MEM_FORMAT_SETTINGS = """
+#seekto 0x02B0;
+struct {
+ u8 voiceprompt;
+ u8 voicelanguage;
+ u8 scan;
+ u8 vox;
+ u8 voxlevel;
+ u8 voxinhibitonrx;
+ u8 lowvolinhibittx;
+ u8 highvolinhibittx;
+ u8 alarm;
+ u8 fmradio;
+} settings;
+"""
+
MEM_FORMAT = """
#seekto 0x0010;
struct {
@@ -44,20 +61,7 @@ struct {
bcl:1;
u8 unknown4[3];
} memory[16];
-#seekto 0x02B0;
-struct {
- u8 voiceprompt;
- u8 voicelanguage;
- u8 scan;
- u8 vox;
- u8 voxlevel;
- u8 voxinhibitonrx;
- u8 lowvolinhibittx;
- u8 highvolinhibittx;
- u8 alarm;
- u8 fmradio;
-} settings;
-"""
+""" + MEM_FORMAT_SETTINGS
H777_SETTINGS2 = """
#seekto 0x03C0;
@@ -116,7 +120,7 @@ def _h777_enter_programming_mode(serial, radio_cls):
raise errors.RadioError("Error communicating with radio")
if not ack:
- raise errors.RadioError("No response from radio to program command")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
LOG.warning('Ack from program command was %r, expected %r',
ack, CMD_ACK)
@@ -144,7 +148,7 @@ def _h777_enter_programming_mode(serial, radio_cls):
raise errors.RadioError('No ACK after reading ident')
return ident
- raise errors.RadioError('No identification received from radio')
+ raise errors.RadioNoResponse()
def _h777_exit_programming_mode(serial):
@@ -206,7 +210,7 @@ def _h777_write_block(radio, block_addr, block_size):
def _h777_enter_single_programming_mode(radio):
ident = _h777_enter_programming_mode(radio.pipe, radio.__class__)
if not ident:
- raise errors.RadioError('Radio did not identify')
+ raise errors.RadioNoResponse()
if not any(rc_ident in ident for rc_ident in radio.IDENT):
LOG.warning('Expected %s for %s but got:\n%s',
radio.IDENT, radio.__class__.__name__,
@@ -224,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()
@@ -335,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
@@ -387,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)
@@ -446,6 +464,9 @@ class H777Radio(chirp_common.CloneModeRadio):
mem.extra = RadioSettingGroup("Extra", "extra")
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 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)",
@@ -485,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.
@@ -495,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")
@@ -505,16 +533,26 @@ class H777Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("voiceprompt", "Voice prompt",
RadioSettingValueBoolean(_settings.voiceprompt))
+ 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('Selects the language the spoken voice prompts use. It '
+ 'has no effect unless Voice prompts are enabled.')
basic.append(rs)
rs = RadioSetting("scan", "Scan",
RadioSettingValueBoolean(_settings.scan))
+ rs.set_doc('Set the channel selector to channel 16 to scan '
+ 'channels 1-15. Scanning stops when a signal is '
+ 'detected and resumes once it clears. At least two '
+ 'channels are required, and scanning is unavailable '
+ 'while the FM radio function is active')
basic.append(rs)
if self._has_scanmodes:
@@ -527,11 +565,17 @@ class H777Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("vox", "VOX",
RadioSettingValueBoolean(_settings.vox))
+ 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('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",
@@ -554,6 +598,9 @@ class H777Radio(chirp_common.CloneModeRadio):
else:
rs = RadioSetting("alarm", "Alarm",
RadioSettingValueBoolean(_settings.alarm))
+ rs.set_doc('Emergency alarm triggered by the side key. Depending '
+ 'on the model this either sounds a local siren or also '
+ 'alerts other radios on the channel')
basic.append(rs)
# TODO: This should probably be called “FM Broadcast Band Radio”
@@ -561,21 +608,37 @@ class H777Radio(chirp_common.CloneModeRadio):
if self._has_fm:
rs = RadioSetting("fmradio", "FM function",
RadioSettingValueBoolean(_settings.fmradio))
+ rs.set_doc('Broadcast FM radio receiver. The radio cannot scan '
+ 'while this is active')
basic.append(rs)
rs = RadioSetting("settings2.beep", "Beep",
RadioSettingValueBoolean(
self._memobj.settings2.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("settings2.batterysaver", "Battery saver",
RadioSettingValueBoolean(
self._memobj.settings2.batterysaver))
+ 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('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:
@@ -591,6 +654,10 @@ class H777Radio(chirp_common.CloneModeRadio):
RadioSettingValueList(
TIMEOUTTIMER_LIST,
current_index=self._memobj.settings2.timeouttimer))
+ 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
@@ -656,6 +723,65 @@ class RetevisH777(H777Radio):
return False
+MP31_MEM_FORMAT = """
+#seekto 0x0000;
+struct {
+ lbcd rxfreq[4];
+ lbcd txfreq[4];
+ lbcd rxtone[2];
+ lbcd txtone[2];
+ u8 unknown3:1,
+ unknown2:1,
+ unknown1:1,
+ skip:1,
+ highpower:1,
+ narrow:1,
+ beatshift:1,
+ bcl:1;
+ u8 unknown4[3];
+} memory[38];
+"""
+
+MP31_SETTINGS2 = """
+#seekto 0x026B;
+struct {
+ u8 squelchlevel;
+ u8 batterysaver;
+ u8 voxdelay;
+ u8 timeouttimer;
+ u8 scanmode;
+ u8 beep;
+ u8 sidekey;
+ u8 rxemergency;
+} settings2;
+"""
+
+
+@directory.register
+class MP31Radio(H777Radio):
+ """Baofeng MP31"""
+ VENDOR = "Baofeng"
+ MODEL = "MP31"
+ IDENT = [b"P3107\xf7\x00\x00"]
+ _ranges = [(0x0000, 0x0400)]
+ _memsize = 0x0400
+ _has_sidekey = False
+ ALIASES = []
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(
+ MP31_MEM_FORMAT + MP31_SETTINGS2 + MEM_FORMAT_SETTINGS, self._mmap)
+
+ def get_features(self):
+ rf = super().get_features()
+ rf.memory_bounds = (1, 38)
+ return rf
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return False
+
+
class H777TestCase(unittest.TestCase):
def setUp(self):
@@ -703,6 +829,23 @@ class H777TestCase(unittest.TestCase):
self.driver._encode_tone(self.testdata.foo, '', 67.0, 'N')
self.assertEqual(16665, int(self.testdata.foo))
+ def test_mp31_38_channels(self):
+ radio = MP31Radio(None)
+ rf = radio.get_features()
+ self.assertEqual(rf.memory_bounds, (1, 38))
+
+ def test_mp31_memsize(self):
+ radio = MP31Radio(None)
+ self.assertEqual(radio._memsize, 0x0400)
+
+ def test_mp31_ranges(self):
+ radio = MP31Radio(None)
+ self.assertEqual(radio._ranges, [(0x0000, 0x0400)])
+
+ def test_mp31_ident(self):
+ radio = MP31Radio(None)
+ self.assertIn(b"P3107\xf7\x00\x00", radio.IDENT)
+
@directory.register
class ROGA2SRadio(H777Radio):
@@ -849,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/hf90.py b/chirp/drivers/hf90.py
index c2c37a2..8fe9dc9 100644
--- a/chirp/drivers/hf90.py
+++ b/chirp/drivers/hf90.py
@@ -104,7 +104,10 @@ class HF90StyleRadio(chirp_common.CloneModeRadio,
def _serial_prompt(self):
reset_buffer(self.pipe)
self._send(b'\r')
- return self._read(3) == b'\r\n#'
+ resp = self._read(3)
+ if not resp:
+ raise errors.RadioNoResponse()
+ return resp == b'\r\n#'
def _download_chunk(self, addr):
if addr % 16:
@@ -304,7 +307,6 @@ class HF90StyleRadio(chirp_common.CloneModeRadio,
rf.valid_skips = []
rf.valid_tmodes = []
rf.valid_tones = []
- # TODO how does one make the Tone column go away?
return rf
def apply_txpower(self, setting, obj):
diff --git a/chirp/drivers/hg_uv98.py b/chirp/drivers/hg_uv98.py
index c5ce38e..fdf369b 100644
--- a/chirp/drivers/hg_uv98.py
+++ b/chirp/drivers/hg_uv98.py
@@ -25,6 +25,7 @@ import struct
from chirp import chirp_common, directory, memmap, errors, util
from chirp import bitwise
+from chirp import kenwood_tone
from chirp.settings import RadioSettingGroup, RadioSetting
from chirp.settings import RadioSettingValueBoolean, RadioSettingValueList
from chirp.settings import RadioSettings
@@ -35,8 +36,8 @@ MEM_FORMAT = """
struct {
lbcd rx_freq[4];
lbcd tx_freq[4];
- ul16 rx_tone;
- ul16 tx_tone;
+ ul16 rxtone;
+ ul16 txtone;
u8 unknown1:6,
wide:1,
highpower:1;
@@ -306,6 +307,8 @@ class LanchonlhHG_UV98(chirp_common.CloneModeRadio, chirp_common.ExperimentalRad
BAUD_RATE = 9600
_upper = MAX_CHANNELS
+ _tone_model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x2800, pol_mask=0x8000, tone_init=0xFFFF, tone_flag=0x0000)
@classmethod
def get_prompts(cls):
@@ -370,45 +373,6 @@ class LanchonlhHG_UV98(chirp_common.CloneModeRadio, chirp_common.ExperimentalRad
def get_raw_memory(self, number):
return repr(self._memobj.memory[number - 1])
- def _get_tone(self, _mem, mem):
- def _get_dcs(val):
- code = int("%03o" % (val & 0x07FF))
- pol = (val & 0x8000) and "R" or "N"
- return code, pol
-
- if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
- tcode, tpol = _get_dcs(_mem.tx_tone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.tx_tone != 0xFFFF:
- mem.rtone = _mem.tx_tone / 10.0
- txmode = "Tone"
- else:
- txmode = ""
-
- if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
- rcode, rpol = _get_dcs(_mem.rx_tone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rx_tone != 0xFFFF:
- mem.ctone = _mem.rx_tone / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- if mem.tmode == "DTCS":
- mem.dtcs_polarity = "%s%s" % (tpol, rpol)
-
def get_memory(self, number):
mem = chirp_common.Memory()
@@ -445,7 +409,7 @@ class LanchonlhHG_UV98(chirp_common.CloneModeRadio, chirp_common.ExperimentalRad
else:
mem.offset = 0
- self._get_tone(_mem, mem)
+ self._tone_model.get_tone(_mem, mem)
mem.power = POWER_LEVELS[_mem.highpower]
mem.mode = MODES[_mem.wide]
mem.skip = not _mem.scan and "S" or ""
@@ -458,44 +422,6 @@ class LanchonlhHG_UV98(chirp_common.CloneModeRadio, chirp_common.ExperimentalRad
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- val = int("%i" % code, 8) + 0x2800
- if pol == "R":
- val += 0xA000
- return val
-
- rx_mode = tx_mode = None
- rx_tone = tx_tone = 0xFFFF
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- tx_tone = int(mem.rtone * 10)
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rx_tone = tx_tone = int(mem.ctone * 10)
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- tx_tone = int(mem.rtone * 10)
- if rx_mode == "DTCS":
- rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rx_tone = int(mem.ctone * 10)
-
- _mem.rx_tone = rx_tone
- _mem.tx_tone = tx_tone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
-
def set_memory(self, mem):
_mem = self._memobj.memory[mem.number - 1]
@@ -526,7 +452,7 @@ class LanchonlhHG_UV98(chirp_common.CloneModeRadio, chirp_common.ExperimentalRad
else:
_mem.tx_freq = mem.freq / 10
- self._set_tone(mem, _mem)
+ self._tone_model.set_tone(mem, _mem)
_mem.highpower = mem.power == POWER_LEVELS[1]
_mem.wide = mem.mode == "NFM"
diff --git a/chirp/drivers/hobbypcb.py b/chirp/drivers/hobbypcb.py
index ae2a40d..fd16ab4 100644
--- a/chirp/drivers/hobbypcb.py
+++ b/chirp/drivers/hobbypcb.py
@@ -57,7 +57,7 @@ class HobbyPCBRSUV3Radio(chirp_common.LiveRadio):
if self.pipe:
baud = detect_baudrate(self)
if not baud:
- raise errors.RadioError('Radio did not respond')
+ raise errors.RadioNoResponse()
def _cmd(self, command, rsize=None):
command = command.encode()
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 6bb643b..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
@@ -1352,3 +1357,29 @@ class IC2730Radio(icf.IcomCloneModeRadio):
except Exception:
LOG.debug(element.get_name())
raise
+
+
+@directory.register
+class IC2730ERadio(IC2730Radio):
+ """Icom IC-2730E (European variant)"""
+ MODEL = "IC-2730E"
+
+ # The IC-2730E speaks the initial clone handshake at 19200 baud
+ # (not 9600 like the IC-2730A) and requires the radio's model code
+ # in the CLONE_ID query payload instead of all zeros. After the
+ # handshake the standard hispeed transition to 38400 still applies.
+ BAUD_RATE = 19200
+ _id_query_with_model = True
+
+ # The IC-2730E ends a clone-out with "Icom Inc.4D" rather than the
+ # "Icom Inc.4E" sent by the A variant.
+ _endframe = "Icom Inc\x2e4D"
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ # The IC-2730A and IC-2730E are byte-indistinguishable in
+ # legacy raw-image dumps (same _model and _memsize). Files
+ # saved by modern CHIRP carry an explicit driver-class tag in
+ # the .img metadata trailer and route there directly, so this
+ # variant only needs to abstain from blind auto-detection.
+ return False
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/ic9x.py b/chirp/drivers/ic9x.py
index 4ec7883..7588cd2 100644
--- a/chirp/drivers/ic9x.py
+++ b/chirp/drivers/ic9x.py
@@ -163,7 +163,7 @@ class IC9xRadio(icf.IcomLiveRadio):
return
time.sleep(1)
LOG.warning('Made %i attempts to wake radio', i + 1)
- raise errors.RadioError('Radio not responding')
+ raise errors.RadioNoResponse()
def __init__(self, *args, **kwargs):
if 'lock' in kwargs:
diff --git a/chirp/drivers/ic9x_ll.py b/chirp/drivers/ic9x_ll.py
index 1c66e73..70a8aaf 100644
--- a/chirp/drivers/ic9x_ll.py
+++ b/chirp/drivers/ic9x_ll.py
@@ -156,7 +156,7 @@ class IC92Frame:
response = ic9x_recv(pipe)
if not response:
- raise errors.InvalidDataError("No response from radio")
+ raise errors.RadioNoResponse()
return response[0]
@@ -179,7 +179,7 @@ class IC92GetBankFrame(IC92Frame):
rframes = ic9x_send(pipe, self.get_raw())
if len(rframes) == 0:
- raise errors.InvalidDataError("No response from radio")
+ raise errors.RadioNoResponse()
return rframes
@@ -345,13 +345,15 @@ class IC92MemoryFrame(IC92Frame):
"""Take Memory object @mem and configure the frame accordingly"""
if mem.number < 0:
self.set_iscall(True)
- mem.number = abs(mem.number) - 1
+ number = abs(mem.number) - 1
LOG.debug("Memory is %i (call %s)" %
(mem.number, self.get_iscall()))
+ else:
+ number = mem.number
_mem = bitwise.parse(MEMORY_FRAME_FORMAT, self).mem
- _mem.number = mem.number
+ _mem.number = number
_mem.freq = mem.freq
_mem.offset = mem.offset
@@ -444,7 +446,7 @@ def get_memory(pipe, vfo, number):
rframe = get_memory_frame(pipe, vfo, number)
if len(rframe.get_payload()) < 1:
- raise errors.InvalidMemoryLocation("No response from radio")
+ raise errors.RadioError("Unexpected empty response from radio")
if rframe.get_payload()[3] == b'\xff':
raise errors.InvalidMemoryLocation("Radio says location is empty")
diff --git a/chirp/drivers/icf.py b/chirp/drivers/icf.py
index bc62bd5..d690e05 100644
--- a/chirp/drivers/icf.py
+++ b/chirp/drivers/icf.py
@@ -213,6 +213,8 @@ def get_model_data(radio, mdata=b"\x00\x00\x00\x00", stream=None):
stream = RadioStream(radio.pipe)
frames = stream.get_frames()
+ if len(frames) == 0:
+ raise errors.RadioNoResponse()
if len(frames) != 1:
raise errors.RadioError("Unexpected response from radio")
@@ -333,8 +335,22 @@ def start_hispeed_clone(radio, cmd):
radio.pipe.flush()
+def _id_query_payload(radio):
+ """Build the payload for the initial CLONE_ID query.
+
+ Most Icom clone-mode radios reply to a query with all-zero payload.
+ A few (e.g. IC-2730E) only respond when the query carries the radio's
+ own model code with the last byte zeroed; those drivers set the
+ `_id_query_with_model` flag (defined on IcomCloneModeRadio).
+ """
+ if radio._id_query_with_model:
+ model = radio.get_model().ljust(4, b"\x00")[:4]
+ return model[:3] + b"\x00"
+ return b"\x00\x00\x00\x00"
+
+
def _clone_from_radio(radio):
- md = get_model_data(radio)
+ md = get_model_data(radio, mdata=_id_query_payload(radio))
try:
radio_rev = decode_model(md)
@@ -410,6 +426,8 @@ def clone_from_radio(radio):
"""Do a full clone out of the radio's memory"""
try:
return _clone_from_radio(radio)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError("Failed to communicate with the radio: %s" % e)
@@ -457,10 +475,12 @@ def _clone_to_radio(radio):
# Uncomment to save out a capture of what we actually write to the radio
# SAVE_PIPE = file("pipe_capture.log", "w", 0)
+ mdata = _id_query_payload(radio)
+
stream = RadioStream(radio.pipe)
- md = get_model_data(radio, stream=stream)
+ md = get_model_data(radio, mdata=mdata, stream=stream)
if radio._double_ident:
- md = get_model_data(radio, stream=stream)
+ md = get_model_data(radio, mdata=mdata, stream=stream)
if md[0:4] != radio.get_model():
raise errors.RadioError("I can't talk to this model")
@@ -514,7 +534,7 @@ def _clone_to_radio(radio):
return True
if len(frames) == 0:
- raise errors.RadioError("Did not get clone result from radio")
+ raise errors.RadioNoResponse()
elif result.cmd != CMD_CLONE_OK:
LOG.error('Clone failed result frame:\n%s' % result)
raise errors.RadioError('Radio rejected clone')
@@ -528,6 +548,8 @@ def clone_to_radio(radio):
"""Initiate a full memory clone out to @radio"""
try:
return _clone_to_radio(radio)
+ except errors.RadioError:
+ raise
except Exception as e:
logging.exception("Failed to communicate with the radio")
raise errors.RadioError("Failed to communicate with the radio: %s" % e)
@@ -828,6 +850,11 @@ class IcomCloneModeRadio(chirp_common.CloneModeRadio):
_can_hispeed = False
_double_ident = False # A couple radios require double ident before upload
+ # If True, the initial CLONE_ID query payload carries the radio's
+ # own model code (with the last byte zeroed) instead of all zeros.
+ # Required by IC-2730E; most clone-mode Icoms answer to all-zeros.
+ _id_query_with_model = False
+
# Newer radios (ID51Plus2, ID5100, IC2730) use a slightly
# different CLONE_DAT format
_raw_frames = False
@@ -918,10 +945,12 @@ class IcomCloneModeRadio(chirp_common.CloneModeRadio):
return self._mmap
def sync_out(self):
- # We always start at 9600 baud. The UI may have handed us the same
- # rate we ended with last time (for radios which have variable but
- # unchanging speeds) but we always have to start in low-speed mode.
- self.pipe.baudrate = 9600
+ # We always have to start in low-speed mode. The UI may have
+ # handed us a different rate left over from a prior hispeed run,
+ # so reset to the driver's configured rate here. For most Icom
+ # clone-mode radios that's 9600 (the default inherited from
+ # chirp_common.Radio); a few (e.g. IC-2730E) override it.
+ self.pipe.baudrate = self.BAUD_RATE
clone_to_radio(self)
def get_bank_model(self):
diff --git a/chirp/drivers/icomciv.py b/chirp/drivers/icomciv.py
index af46fa9..a96a232 100644
--- a/chirp/drivers/icomciv.py
+++ b/chirp/drivers/icomciv.py
@@ -774,7 +774,7 @@ class IcomCIVRadio(icf.IcomLiveRadio):
mem.dtcs_polarity = "NN"
if self._rf.has_dtcs:
- mem.dtcs = bitwise.bcd_to_int(memobj.dtcs)
+ mem.dtcs = int(memobj.dtcs)
if "Tone" in self._rf.valid_tmodes:
mem.rtone = int(memobj.rtone) / 10.0
@@ -904,7 +904,7 @@ class IcomCIVRadio(icf.IcomLiveRadio):
memobj.dtcs_polarity = 0x00
if self._rf.has_dtcs:
- bitwise.int_to_bcd(memobj.dtcs, mem.dtcs)
+ memobj.dtcs = mem.dtcs
if self._rf.can_odd_split and mem.duplex == "split":
memobj.spl = 1
@@ -1524,7 +1524,7 @@ class Icom9700SatelliteBand(Icom9700Radio):
else:
mem.dtcs_polarity = "NN"
- mem.dtcs = bitwise.bcd_to_int(memobj.dtcs)
+ mem.dtcs = int(memobj.dtcs)
mem.rtone = int(memobj.rtone) / 10.0
mem.ctone = int(memobj.ctone) / 10.0
mem.duplex = 'split'
@@ -1589,7 +1589,7 @@ class Icom9700SatelliteBand(Icom9700Radio):
else:
memobj.dtcs_polarity = 0x00
- bitwise.int_to_bcd(memobj.dtcs, mem.dtcs)
+ memobj.dtcs = mem.dtcs
memobj.tx.freq = int(mem.offset)
memobj.tx.tmode = memobj.tmode
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 60f9fcd..0a53250 100644
--- a/chirp/drivers/icq7.py
+++ b/chirp/drivers/icq7.py
@@ -17,7 +17,7 @@ import logging
from chirp.drivers import icf
from chirp import chirp_common, directory, bitwise
-from chirp.chirp_common import to_GHz, from_GHz
+from chirp.chirp_common import to_GHz
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueInteger, RadioSettings
@@ -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
@@ -189,7 +194,8 @@ class ICQ7Radio(icf.IcomCloneModeRadio):
if mem.freq > to_GHz(1):
_mem.freq = (mem.freq // 1000) - to_GHz(1)
- upper = from_GHz(mem.freq) << 4
+ # For 1300MHz, but 13 in these bits
+ upper = (mem.freq // 100000000) << 4
_mem.freq[0].clr_bits(0xF0)
_mem.freq[0].set_bits(upper)
else:
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 37484e5..6331ca3 100644
--- a/chirp/drivers/ict8.py
+++ b/chirp/drivers/ict8.py
@@ -54,7 +54,7 @@ def _get_freq(bcd_array):
def _set_freq(bcd_array, freq):
- bitwise.int_to_bcd(bcd_array, freq / 1000)
+ bcd_array.set_value(freq / 1000)
bcd_array[2].set_raw(bcd_array[2].get_bits(0xF0) + freq % 10000 // 500)
@@ -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/iradio_common.py b/chirp/drivers/iradio_common.py
new file mode 100644
index 0000000..db569f0
--- /dev/null
+++ b/chirp/drivers/iradio_common.py
@@ -0,0 +1,56 @@
+# Copyright 2023 Jim Unroe <rock.unroe@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+"""common function for iRadio (or similar) radios"""
+
+import logging
+from chirp import errors
+
+LOG = logging.getLogger(__name__)
+
+CMD_ACK = b"\x06"
+
+
+def enter_programming_mode(serial, magic, timeout=0.25):
+ previous_timeout = serial.timeout
+ serial.timeout = timeout
+
+ try:
+ for attempt in range(0, 5):
+ serial.write(magic)
+ ack = serial.read(1)
+
+ if ack == CMD_ACK:
+ return
+
+ if not ack and attempt == 4:
+ raise errors.RadioNoResponse()
+
+ LOG.debug(f"Attempt #{attempt + 1} failed, trying again")
+
+ # retries all failed, raise error
+ 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)
+
+ finally:
+ serial.timeout = previous_timeout
+
+
+def exit_programming_mode(serial, magic):
+ try:
+ serial.write(magic)
+ except Exception:
+ raise errors.RadioError("Radio refused to exit programming mode")
diff --git a/chirp/drivers/iradio_uv_5118.py b/chirp/drivers/iradio_uv_5118.py
index 2296282..3342405 100644
--- a/chirp/drivers/iradio_uv_5118.py
+++ b/chirp/drivers/iradio_uv_5118.py
@@ -16,13 +16,16 @@
import struct
import logging
-from chirp import chirp_common, directory, memmap
+from chirp import chirp_common, directory, memmap, checksum
from chirp import bitwise, errors, util
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueInteger, RadioSettingValueList, \
RadioSettingValueBoolean, RadioSettingValueFloat, \
RadioSettings
+from chirp.drivers.iradio_common import enter_programming_mode, \
+ exit_programming_mode
+
LOG = logging.getLogger(__name__)
MEM_FORMAT = """
@@ -155,56 +158,12 @@ TXALLOW_CHOICES = ["RX Only", "TX/RX"]
TXALLOW_VALUES = [0xFF, 0x00]
-def _checksum(data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
-def _enter_programming_mode(radio):
- serial = radio.pipe
-
- # lengthen the timeout here as these radios are resetting due to timeout
- radio.pipe.timeout = 0.75
-
- exito = False
- for i in range(0, 5):
- serial.write(radio.magic)
- ack = serial.read(1)
-
- try:
- if ack == CMD_ACK:
- exito = True
- break
- except:
- LOG.debug("Attempt #%s, failed, trying again" % i)
- pass
-
- # return timeout to default value
- radio.pipe.timeout = 0.25
-
- # check if we had EXITO
- if exito is False:
- msg = "The radio did not accept program mode after five tries.\n"
- msg += "Check you interface cable and power cycle your radio."
- raise errors.RadioError(msg)
-
-
-def _exit_programming_mode(radio):
- serial = radio.pipe
- try:
- serial.write(b"93" + b"\x05\xEE\x5F")
- except:
- raise errors.RadioError("Radio refused to exit programming mode")
-
-
def _read_block(radio, block_addr, block_size):
serial = radio.pipe
cmd = struct.pack(">BH", ord(b'R'), block_addr + 0x0340)
- ccs = bytes([_checksum(cmd)])
+ ccs = bytes([checksum.checksum_8bit(cmd)])
expectedresponse = b"R" + cmd[1:]
@@ -216,7 +175,7 @@ def _read_block(radio, block_addr, block_size):
serial.write(cmd)
response = serial.read(3 + block_size + 1)
- cs = _checksum(response[:-1])
+ cs = checksum.checksum_8bit(response[:-1])
if response[:3] != expectedresponse:
raise Exception("Error reading block %04x." % (block_addr +
@@ -242,7 +201,7 @@ def _write_block(radio, block_addr, block_size):
cmd = struct.pack(">BH", ord(b'W'), block_addr + 0x0340)
- cs = bytes([_checksum(cmd + data)])
+ cs = bytes([checksum.checksum_8bit(cmd + data)])
data += cs
LOG.debug("Writing Data:")
@@ -259,7 +218,8 @@ def _write_block(radio, block_addr, block_size):
def do_download(radio):
LOG.debug("download")
- _enter_programming_mode(radio)
+ enter_programming_mode(radio.pipe, radio.magic_enter,
+ radio.program_timeout)
data = b""
@@ -279,7 +239,7 @@ def do_download(radio):
LOG.debug("Address: %04x" % addr)
LOG.debug(util.hexprint(block))
- _exit_programming_mode(radio)
+ exit_programming_mode(radio.pipe, radio.magic_exit)
return memmap.MemoryMapBytes(data)
@@ -288,7 +248,8 @@ def do_upload(radio):
status = chirp_common.Status()
status.msg = "Uploading to radio"
- _enter_programming_mode(radio)
+ enter_programming_mode(radio.pipe, radio.magic_enter,
+ radio.program_timeout)
status.cur = 0
status.max = radio._memsize
@@ -299,7 +260,7 @@ def do_upload(radio):
radio.status_fn(status)
_write_block(radio, addr, radio.BLOCK_SIZE)
- _exit_programming_mode(radio)
+ exit_programming_mode(radio.pipe, radio.magic_exit)
class IradioUV5118(chirp_common.CloneModeRadio):
@@ -309,7 +270,9 @@ class IradioUV5118(chirp_common.CloneModeRadio):
BAUD_RATE = 9600
BLOCK_SIZE = 0x10
- magic = b"93" + b"\x05\x10\x81"
+ magic_enter = b"93" + b"\x05\x10\x81"
+ magic_exit = b"93" + b"\x05\xEE\x5F"
+ program_timeout = 0.75
VALID_BANDS = [(20000000, 64000000), # RX only
(108000000, 136000000), # RX only (Air Band)
diff --git a/chirp/drivers/iradio_uv_5118plus.py b/chirp/drivers/iradio_uv_5118plus.py
index f8920c3..bae096e 100644
--- a/chirp/drivers/iradio_uv_5118plus.py
+++ b/chirp/drivers/iradio_uv_5118plus.py
@@ -16,13 +16,16 @@
import struct
import logging
-from chirp import chirp_common, directory, memmap
+from chirp import chirp_common, directory, memmap, checksum
from chirp import bitwise, errors, util
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueInteger, RadioSettingValueList, \
RadioSettingValueBoolean, RadioSettingValueString, \
RadioSettingValueFloat, RadioSettings
+from chirp.drivers.iradio_common import enter_programming_mode, \
+ exit_programming_mode
+
LOG = logging.getLogger(__name__)
MEM_FORMAT = """
@@ -189,50 +192,12 @@ VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
DTMF_CHARS = list("0123456789ABCD*#")
-def _checksum(data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
-def _enter_programming_mode(radio):
- serial = radio.pipe
-
- exito = False
- for i in range(0, 5):
- serial.write(radio.magic)
- ack = serial.read(1)
-
- try:
- if ack == CMD_ACK:
- exito = True
- break
- except Exception:
- LOG.debug("Attempt #%s, failed, trying again" % i)
- pass
-
- # check if we had EXITO
- if exito is False:
- msg = "The radio did not accept program mode after five tries.\n"
- msg += "Check you interface cable and power cycle your radio."
- raise errors.RadioError(msg)
-
-
-def _exit_programming_mode(radio):
- serial = radio.pipe
- try:
- serial.write(b"58" + b"\x05\xEE\x60")
- except Exception:
- raise errors.RadioError("Radio refused to exit programming mode")
-
-
def _read_block(radio, block_addr, block_size):
serial = radio.pipe
cmd = struct.pack(">BH", ord(b'R'), block_addr + radio.READ_OFFSET)
- ccs = bytes([_checksum(cmd)])
+ ccs = bytes([checksum.checksum_8bit(cmd)])
expectedresponse = b"R" + cmd[1:]
@@ -244,7 +209,7 @@ def _read_block(radio, block_addr, block_size):
serial.write(cmd)
response = serial.read(3 + block_size + 1)
- cs = _checksum(response[:-1])
+ cs = checksum.checksum_8bit(response[:-1])
if response[:3] != expectedresponse:
raise Exception("Error reading block %04x." % block_addr)
@@ -272,7 +237,7 @@ def _write_block(radio, block_addr, block_size):
cmd = struct.pack(">BH", ord(b'I'), block_addr)
- cs = bytes([_checksum(cmd + data)])
+ cs = bytes([checksum.checksum_8bit(cmd + data)])
data += cs
LOG.debug("Writing Data:")
@@ -289,7 +254,7 @@ def _write_block(radio, block_addr, block_size):
def do_download(radio):
LOG.debug("download")
- _enter_programming_mode(radio)
+ enter_programming_mode(radio.pipe, radio.magic_enter)
data = b""
@@ -309,7 +274,7 @@ def do_download(radio):
LOG.debug("Address: %04x" % addr)
LOG.debug(util.hexprint(block))
- _exit_programming_mode(radio)
+ exit_programming_mode(radio.pipe, radio.magic_exit)
return memmap.MemoryMapBytes(data)
@@ -318,7 +283,7 @@ def do_upload(radio):
status = chirp_common.Status()
status.msg = "Uploading to radio"
- _enter_programming_mode(radio)
+ enter_programming_mode(radio.pipe, radio.magic_enter)
status.cur = 0
status.max = radio._memsize
@@ -333,7 +298,7 @@ def do_upload(radio):
radio.status_fn(status)
_write_block(radio, addr, radio.BLOCK_SIZE)
- _exit_programming_mode(radio)
+ exit_programming_mode(radio.pipe, radio.magic_exit)
class IradioUV5118plus(chirp_common.CloneModeRadio):
@@ -344,7 +309,8 @@ class IradioUV5118plus(chirp_common.CloneModeRadio):
BAUD_RATE = 115200
BLOCK_SIZE = 0x80
- magic = b"58" + b"\x05\x10\x82"
+ magic_enter = b"58" + b"\x05\x10\x82"
+ magic_exit = b"58" + b"\x05\xEE\x60"
VALID_BANDS = [(108000000, 136000000), # RX only (Air Band)
(136000000, 174000000), # TX/RX (VHF)
@@ -421,6 +387,8 @@ class IradioUV5118plus(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
do_upload(self)
+ except errors.RadioError:
+ raise
except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
diff --git a/chirp/drivers/kenwood_d7.py b/chirp/drivers/kenwood_d7.py
index e08d519..87e5295 100644
--- a/chirp/drivers/kenwood_d7.py
+++ b/chirp/drivers/kenwood_d7.py
@@ -617,6 +617,7 @@ class KenwoodD7Family(chirp_common.LiveRadio):
def _get_id(self):
"""Get the ID of the radio attached to @ser"""
+ saw_response = False
for i in self._BAUDS:
LOG.info("Trying ID at baud %i" % i)
@@ -633,6 +634,9 @@ class KenwoodD7Family(chirp_common.LiveRadio):
# or not talking to a kenwood live radio.
continue
+ if resp:
+ saw_response = True
+
ret = self._parse_id_response(resp)
if ret is not None:
self._baud = i
@@ -648,7 +652,9 @@ class KenwoodD7Family(chirp_common.LiveRadio):
if ret is not None:
self._baud = i
return ret
- raise errors.RadioError("No response from radio")
+ if saw_response:
+ raise errors.RadioError("Unexpected response from radio")
+ raise errors.RadioNoResponse()
def _get_immutable(self, memid_or_index):
if self._is_call(memid_or_index):
@@ -920,7 +926,13 @@ class KenwoodD7Family(chirp_common.LiveRadio):
def _refresh_settings(self):
for entry in self._setcache.values():
if not entry.kenwood_d7_loaded:
- self._refresh_setting(entry)
+ try:
+ self._refresh_setting(entry)
+ except errors.RadioError as e:
+ # Don't fail if we can't read a setting. Some radios
+ # refuse to return MCL (perhaps v1 radios?)
+ LOG.error("Error refreshing setting %s: %s"
+ % (entry.get_name(), str(e)))
def _validate_memid(self, memid_or_index):
if isinstance(memid_or_index, int):
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 52475bc..7bb0de8 100644
--- a/chirp/drivers/kenwood_live.py
+++ b/chirp/drivers/kenwood_live.py
@@ -115,6 +115,7 @@ class KenwoodLiveRadio(chirp_common.LiveRadio):
bauds.remove(self.LAST_BAUD)
# Make sure LAST_BAUD is last so that it is tried first below
bauds.append(self.LAST_BAUD)
+ saw_response = False
command_delimiters = [("\r", " "), (";", "")]
@@ -135,6 +136,9 @@ class KenwoodLiveRadio(chirp_common.LiveRadio):
# or not talking to a Kenwood live radio.
continue
+ if resp:
+ saw_response = True
+
# most Kenwood radios
if " " in resp:
self.LAST_BAUD = i
@@ -154,7 +158,9 @@ class KenwoodLiveRadio(chirp_common.LiveRadio):
if resp in list(RADIO_IDS.keys()):
return RADIO_IDS[resp]
- raise errors.RadioError("No response from radio")
+ if saw_response:
+ raise errors.RadioError("Unexpected response from radio")
+ raise errors.RadioNoResponse()
def _command(self, ser, cmd, *args):
"""Send @cmd to radio via @ser"""
@@ -281,9 +287,7 @@ class KenwoodLiveRadio(chirp_common.LiveRadio):
r2 = self.command(
self.pipe,
*self._cmd_set_memory_name(memory.number, memory.name))
- if not iserr(r2):
- memory.name = memory.name.rstrip()
- else:
+ if iserr(r2):
raise errors.InvalidDataError("Radio refused name %i: %s" %
(memory.number,
repr(memory.name)))
@@ -406,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):
@@ -498,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),
@@ -507,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]
@@ -1047,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
@@ -1064,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):
@@ -1135,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()
@@ -1142,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
@@ -1150,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):
@@ -1174,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 51157de..b6f20bd 100644
--- a/chirp/drivers/kg935g.py
+++ b/chirp/drivers/kg935g.py
@@ -29,11 +29,13 @@ import time
import logging
from chirp import util, chirp_common, bitwise, memmap, errors, directory
+from chirp import checksum
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueInteger, RadioSettingValueString, \
RadioSettingValueFloat, RadioSettingValueMap, RadioSettings, \
InvalidValueError
+from chirp import kenwood_tone
LOG = logging.getLogger(__name__)
@@ -90,6 +92,21 @@ config_map_935H = ( # map address, write size, write count
(0x4780, 32, 375), # Memory Names 0-999
(0x7670, 8, 125), # Ch Valid bytes 0-999
)
+config_map_x20h = ( # map address, write size, write count
+ # (0x00, 64, 512), #- Use for full upload testing
+ # (0x44, 32, 1), # Freq Limits
+ # (0x440, 8, 1), # Area Message
+ # (0x480, 8, 5), # Scan Groups
+ # (0x500, 8, 15), # Call Codes
+ # (0x580, 8, 15), # Call Names
+ # (0x600, 8, 5), # FM Presets
+ # (0x800, 64, 2), # settings
+ # (0x880, 16, 1), # VFO A
+ # (0x8C0, 16, 1), # VFO B
+ (0x900, 64, 250), # Channel Memory 0-999
+ (0x4780, 32, 375), # Memory Names 0-999
+ (0x7670, 8, 125), # Ch Valid bytes 0-999
+ )
AB_LIST = ["A", "B"]
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0, 50.0, 100.0]
@@ -695,7 +712,7 @@ _MEM_FORMAT_935GPLUS = """
power:4;
u8 unknown3:2,
scan_add:1,
- unknown4:1,
+ favorite:1,
compander:1,
mute_mode:2,
iswide:1;
@@ -1244,7 +1261,7 @@ _MEM_FORMAT_935H = """
power:4;
u8 unknown3:2,
scan_add:1,
- unknown4:1,
+ favorite:1,
compander:1,
mute_mode:2,
iswide:1;
@@ -1329,32 +1346,60 @@ class KG935GRadio(chirp_common.CloneModeRadio,
chirp_common.PowerLevel("H", watts=5.5)]
_record_start = 0x7C
config_map = config_map_935G
-
- def _checksum(self, data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
+ HAS_SCRAMBLER = True
+ HAS_FAVORITE = False
+
+ def __init__(self, pipe):
+ super().__init__(pipe)
+ self.tone_model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000,
+ pol_mask=0x2000,
+ tone_init=0x0000)
+
+ def get_extra(self, _mem, mem):
+ mem.extra = RadioSettingGroup("Extra", "Extra")
+ _mem.mute_mode = 2 if _mem.mute_mode > 2 else _mem.mute_mode
+ rs = RadioSetting("mute_mode", "Mute Mode",
+ RadioSettingValueList(
+ SPMUTE_LIST, current_index=_mem.mute_mode))
+ mem.extra.append(rs)
+ if self.HAS_SCRAMBLER:
+ rs = RadioSetting("scrambler", "Scramble Descramble",
+ RadioSettingValueList(
+ SCRAMBLE_LIST, current_index=_mem.scrambler))
+ mem.extra.append(rs)
+ rs = RadioSetting("compander", "Compander",
+ RadioSettingValueList(
+ ONOFF_LIST, current_index=_mem.compander))
+ mem.extra.append(rs)
+ if self.HAS_FAVORITE:
+ rs = RadioSetting("favorite", "Favorite",
+ RadioSettingValueList(
+ ONOFF_LIST, current_index=_mem.favorite))
+ mem.extra.append(rs)
+ return
def _write_record(self, cmd, payload=b''):
_packet = struct.pack('BBBB', self._record_start, cmd, 0xFF,
len(payload))
- checksum = bytes([self._checksum(_packet[1:] + payload)])
- _packet += self.encrypt(payload + checksum)
+ cs = bytes([checksum.checksum_8bit(_packet[1:] + payload)])
+ _packet += self.encrypt(payload + cs)
LOG.debug("Sent:\n%s" % util.hexprint(_packet))
self.pipe.write(_packet)
def _read_record(self):
# read 4 chars for the header
_header = self.pipe.read(4)
+ if not _header:
+ raise errors.RadioNoResponse()
if len(_header) != 4:
- raise errors.RadioError('Radio did not respond')
+ raise errors.RadioError('Radio sent short header')
_length = struct.unpack('xxxB', _header)[0]
_packet = self.pipe.read(_length)
_rcs_xor = _packet[-1]
_packet = self.decrypt(_packet)
- _cs = self._checksum(_header[1:])
- _cs += self._checksum(_packet)
+ _cs = checksum.checksum_8bit(_header[1:])
+ _cs += checksum.checksum_8bit(_packet)
_cs %= 256
_rcs = self.strxor(self.pipe.read(1)[0], _rcs_xor)[0]
LOG.debug("_cs =%x", _cs)
@@ -1403,7 +1448,7 @@ class KG935GRadio(chirp_common.CloneModeRadio,
if _resp[0:9] == self._model:
return
if len(_resp) == 0:
- raise Exception("Radio not responding")
+ raise errors.RadioNoResponse()
else:
raise Exception("Unable to identify radio")
@@ -1554,56 +1599,16 @@ class KG935GRadio(chirp_common.CloneModeRadio,
def get_raw_memory(self, number):
return repr(self._memobj.memory[number])
- def _get_tone(self, _mem, mem):
- # MRT - corrected the Polarity decoding to match 935G implementation
- # use 0x2000 bit mask for R
- # MRT - 0x2000 appears to be the bit mask for Inverted DCS tones
- # MRT - n DCS Tone will be 0x4xxx values - i DCS Tones will
- # be 0x6xxx values.
- # MRT - Chirp Uses N for n DCS Tones and R for i DCS Tones
- def _get_dcs(val):
- code = int("%03o" % (val & 0x07FF))
- pol = (val & 0x2000) and "R" or "N"
- return code, pol
- # MRT - Modified the function below to bitwise AND with 0x4000
- # to check for 935G DCS Tone decoding
- # MRT 0x4000 appears to be the bit mask for DCS tones
- tpol = False
- # MRT Beta 1.1 - Fix the txtone compare to 0x4000 - was rxtone.
- if _mem.txtone != 0xFFFF and (_mem.txtone & 0x4000) == 0x4000:
- tcode, tpol = _get_dcs(_mem.txtone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
- mem.rtone = (_mem.txtone & 0x7fff) / 10.0
- txmode = "Tone"
- else:
- txmode = ""
- # MRT - Modified the function below to bitwise AND with 0x4000
- # to check for 935G DCS Tone decoding
- rpol = False
- if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x4000) == 0x4000:
- rcode, rpol = _get_dcs(_mem.rxtone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
- mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
+ def _get_power(self, _mem, mem):
+ _mem.power = _mem.power & 0x3
+ try:
+ mem.power = self.POWER_LEVELS[_mem.power]
+ except IndexError:
+ mem.power = self.POWER_LEVELS[-1]
- # always set it even if no dtcs is used
- mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")
+ def _set_power(self, mem):
+ temp_val = self.POWER_LEVELS.index(mem.power)
+ return temp_val
def get_memory(self, number):
_mem = self._memobj.memory[number]
@@ -1620,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
@@ -1639,70 +1648,35 @@ class KG935GRadio(chirp_common.CloneModeRadio,
mem.name += chr(char)
mem.name = mem.name.rstrip()
- self._get_tone(_mem, mem)
+ self.get_extra(_mem, mem)
+ self.tone_model.get_tone(_mem, mem)
mem.skip = "" if bool(_mem.scan_add) else "S"
- _mem.power = _mem.power & 0x3
- if _mem.power > 2:
- _mem.power = 2
- mem.power = self.POWER_LEVELS[_mem.power]
+ self._get_power(_mem, mem)
mem.mode = _mem.iswide and "FM" or "NFM"
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- # MRT Change from + 0x2800 to bitwise OR with 0x4000 to
- # set the bit for DCS
- val = int("%i" % code, 8) | 0x4000
- if pol == "R":
- # MRT Change to 0x2000 from 0x8000 to set the bit for
- # i/R polarity
- val += 0x2000
- return val
-
- rx_mode = tx_mode = None
- rxtone = txtone = 0x0000
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- txtone = int(mem.rtone * 10) + 0x8000
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rxtone = txtone = int(mem.ctone * 10) + 0x8000
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- txtone = int(mem.rtone * 10) + 0x8000
- if rx_mode == "DTCS":
- rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rxtone = int(mem.ctone * 10) + 0x8000
-
- _mem.rxtone = rxtone
- _mem.txtone = txtone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
-
def set_memory(self, mem):
number = mem.number
+ # Determine if we are moving from Empty -> Not Empty
+ was_empty = (self._memobj.valid[number] != MEM_VALID)
+
_mem = self._memobj.memory[number]
_nam = self._memobj.names[number]
if mem.empty:
- _mem.set_raw("\x00" * (_mem.size() // 8))
+ _mem.fill_raw(b'\x00')
self._memobj.valid[number] = 0
- self._memobj.names[number].set_raw("\x00" * (_nam.size() // 8))
+ self._memobj.names[number].fill_raw(b'\x00')
return
+ # If it's a NEW channel, wipe it to all 0s first
+ # This prevents "ghost" data from previous radio use or factory junk
+ if was_empty:
+ _mem.fill_raw(b'\x00')
+ _nam.fill_raw(b'\x00')
+
_mem.rxfreq = int(mem.freq / 10)
if mem.duplex == "off":
_mem.txfreq = 0xFFFFFFFF
@@ -1720,22 +1694,16 @@ class KG935GRadio(chirp_common.CloneModeRadio,
_mem.scan_add = int(mem.skip != "S")
_mem.iswide = int(mem.mode == "FM")
# set the tone
- self._set_tone(mem, _mem)
- # MRT set the scrambler and compander to off by default
- # MRT This changes them in the channel memory
- _mem.scrambler = 0
- _mem.compander = 0
+ self.tone_model.set_tone(mem, _mem)
# set the power
_mem.power = _mem.power & 0x3
- if mem.power:
- if _mem.power > 2:
- _mem.power = 2
- _mem.power = self.POWER_LEVELS.index(mem.power)
+ if mem.power is not None:
+ _mem.power = self._set_power(mem)
else:
- _mem.power = True
- # MRT set to mute mode to QT (not QT+DTMF or QT*DTMF) by default
- # MRT This changes them in the channel memory
- _mem.mute_mode = 0
+ _mem.power = 0 # default to Low power if not set
+
+ for setting in mem.extra:
+ setattr(_mem, setting.get_name(), setting.value)
# MRT it is unknown what impact these values have
# MRT This changes them in the channel memory to match what
@@ -1745,8 +1713,6 @@ class KG935GRadio(chirp_common.CloneModeRadio,
# _mem.unknown1 = 0
# MRT Set to 3 to TO MATCH CPS VALUES
_mem.unknown3 = 3
- # MRT Set to 1 to TO MATCH CPS VALUES
- _mem.unknown4 = 1
# MRT set unknown5 to 1 and unknown6 to 0
_mem.unknown5 = 1
_mem.unknown6 = 255
@@ -2509,6 +2475,8 @@ class KG935GPlusRadio(KG935GRadio):
"""Wouxun KG-935G Plus"""
VENDOR = "Wouxun"
MODEL = "KG-935G Plus"
+ HAS_SCRAMBLER = True
+ HAS_FAVORITE = True
def process_mmap(self):
self._memobj = bitwise.parse(_MEM_FORMAT_935GPLUS, self._mmap)
@@ -2535,6 +2503,58 @@ class KG935HRadio(KG935GRadio):
chirp_common.PowerLevel("M", watts=5.0),
chirp_common.PowerLevel("H", watts=8.0)]
config_map = config_map_935H
+ HAS_SCRAMBLER = True
+ HAS_FAVORITE = True
def process_mmap(self):
self._memobj = bitwise.parse(_MEM_FORMAT_935H, self._mmap)
+
+
+@directory.register
+class KGXS20G(KG935GRadio):
+
+ """Wouxun KG-XS20G"""
+ VENDOR = "Wouxun"
+ MODEL = "KG-XS20G"
+ _model = b"KG-UV8D-A"
+ _record_start = 0x79
+ config_map = config_map_x20h
+ POWER_LEVELS = [chirp_common.PowerLevel("L", watts=5.0),
+ chirp_common.PowerLevel("H", watts=20.0)]
+ HAS_SCRAMBLER = False
+ HAS_FAVORITE = False
+
+ def get_features(self):
+ rf = super().get_features()
+ rf.has_settings = False # Set to False until settings are mapped
+ return rf
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(_MEM_FORMAT_935GPLUS, self._mmap)
+
+ def _get_power(self, _mem, mem):
+ if _mem.power == 0:
+ mem.power = self.POWER_LEVELS[0]
+ else:
+ mem.power = self.POWER_LEVELS[1]
+
+ def _set_power(self, mem):
+ temp_val = 0 if mem.power == self.POWER_LEVELS[0] else 2
+ return temp_val
+
+
+@directory.register
+class KGXS20HRadio(KGXS20G):
+
+ """Wouxun KG-XS20H"""
+ VENDOR = "Wouxun"
+ MODEL = "KG-XS20H"
+ HAS_SCRAMBLER = True
+
+
+@directory.register
+class KGXS20GPlusRadio(KGXS20G):
+
+ """Wouxun KG-XS20G Plus"""
+ VENDOR = "Wouxun"
+ MODEL = "KG-XS20G Plus"
diff --git a/chirp/drivers/kguv8d.py b/chirp/drivers/kguv8d.py
index 2bead57..3104f6c 100644
--- a/chirp/drivers/kguv8d.py
+++ b/chirp/drivers/kguv8d.py
@@ -18,10 +18,12 @@
import time
import logging
from chirp import util, chirp_common, bitwise, memmap, errors, directory
+from chirp import checksum
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueInteger, RadioSettingValueString, \
RadioSettings
+from chirp.kenwood_tone import KenwoodToneModel
import struct
LOG = logging.getLogger(__name__)
@@ -287,11 +289,12 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
chirp_common.PowerLevel("H", watts=5)]
_record_start = 0x7D
- def _checksum(self, data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
+ def __init__(self, pipe):
+ super().__init__(pipe)
+ self.tone_model = KenwoodToneModel(
+ dcs_base=0x2800,
+ pol_mask=0x8000,
+ tone_init=0xFFFF)
def _write_record(self, cmd, payload=None):
# build the packet
@@ -303,19 +306,21 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
# add the chars to the packet
_packet += payload
# calculate and add the checksum to the packet
- _packet += bytes([self._checksum(_packet[1:])])
+ _packet += bytes([checksum.checksum_8bit(_packet[1:])])
LOG.debug("Sent:\n%s" % util.hexprint(_packet))
self.pipe.write(_packet)
def _read_record(self):
# read 4 chars for the header
_header = self.pipe.read(4)
+ if not _header:
+ raise errors.RadioNoResponse()
if len(_header) != 4:
- raise errors.RadioError('Radio did not respond')
+ raise errors.RadioError('Radio sent short header')
_length = struct.unpack('xxxB', _header)[0]
_packet = self.pipe.read(_length)
- _cs = self._checksum(_header[1:])
- _cs += self._checksum(_packet)
+ _cs = checksum.checksum_8bit(_header[1:])
+ _cs += checksum.checksum_8bit(_packet)
_cs %= 256
_rcs = self.pipe.read(1)[0]
LOG.debug("_cs =%x", _cs)
@@ -359,7 +364,7 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
if _resp[0:7] == self._model:
return
if len(_resp) == 0:
- raise Exception("Radio not responding")
+ raise errors.RadioNoResponse()
else:
raise Exception("Unable to identify radio")
@@ -493,50 +498,6 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
def get_raw_memory(self, number):
return repr(self._memobj.memory[number])
- def _get_tone(self, _mem, mem):
- def _get_dcs(val):
- code = int("%03o" % (val & 0x07FF))
- pol = (val & 0x8000) and "R" or "N"
- return code, pol
-
- tpol = False
- if _mem.txtone != 0xFFFF and (_mem.txtone & 0x2800) == 0x2800:
- tcode, tpol = _get_dcs(_mem.txtone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
- mem.rtone = (_mem.txtone & 0x7fff) / 10.0
- txmode = "Tone"
- else:
- txmode = ""
-
- rpol = False
- if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x2800) == 0x2800:
- rcode, rpol = _get_dcs(_mem.rxtone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
- mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- # always set it even if no dtcs is used
- mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")
-
- LOG.debug("Got TX %s (%i) RX %s (%i)" %
- (txmode, _mem.txtone, rxmode, _mem.rxtone))
-
def get_memory(self, number):
_mem = self._memobj.memory[number]
_nam = self._memobj.names[number]
@@ -573,7 +534,7 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
mem.name += chr(char)
mem.name = mem.name.rstrip()
- self._get_tone(_mem, mem)
+ self.tone_model.get_tone(_mem, mem)
mem.skip = "" if bool(_mem.scan_add) else "S"
@@ -581,44 +542,6 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
mem.mode = _mem.iswide and "FM" or "NFM"
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- val = int("%i" % code, 8) + 0x2800
- if pol == "R":
- val += 0x8000
- return val
-
- rx_mode = tx_mode = None
- rxtone = txtone = 0xFFFF
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- txtone = int(mem.rtone * 10)
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rxtone = txtone = int(mem.ctone * 10)
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- txtone = int(mem.rtone * 10)
- if rx_mode == "DTCS":
- rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rxtone = int(mem.ctone * 10)
-
- _mem.rxtone = rxtone
- _mem.txtone = txtone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
-
def set_memory(self, mem):
number = mem.number
@@ -648,7 +571,7 @@ class KGUV8DRadio(chirp_common.CloneModeRadio,
_mem.scan_add = int(mem.skip != "S")
_mem.iswide = int(mem.mode == "FM")
# set the tone
- self._set_tone(mem, _mem)
+ self.tone_model.set_tone(mem, _mem)
# set the power
if mem.power:
_mem.power = self.POWER_LEVELS.index(mem.power)
diff --git a/chirp/drivers/kguv8dplus.py b/chirp/drivers/kguv8dplus.py
index e500edd..c20514e 100644
--- a/chirp/drivers/kguv8dplus.py
+++ b/chirp/drivers/kguv8dplus.py
@@ -29,10 +29,12 @@ import struct
import time
import logging
from chirp import util, chirp_common, bitwise, memmap, errors, directory
+from chirp import checksum
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueInteger, RadioSettingValueString, \
RadioSettings
+from chirp.kenwood_tone import KenwoodToneModel
LOG = logging.getLogger(__name__)
@@ -308,31 +310,34 @@ class KGUV8DPlusRadio(chirp_common.CloneModeRadio,
_mmap = ""
_record_start = 0x7A
- def _checksum(self, data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
+ def __init__(self, pipe):
+ super().__init__(pipe)
+ self.tone_model = KenwoodToneModel(
+ dcs_base=0x4000,
+ pol_mask=0x2000,
+ tone_init=0x0000)
def _write_record(self, cmd, payload=b''):
_packet = struct.pack('BBBB', self._record_start, cmd, 0xFF,
len(payload))
- checksum = bytes([self._checksum(_packet[1:] + payload)])
- _packet += self.encrypt(payload + checksum)
+ cs = bytes([checksum.checksum_8bit(_packet[1:] + payload)])
+ _packet += self.encrypt(payload + cs)
LOG.debug("Sent:\n%s" % util.hexprint(_packet))
self.pipe.write(_packet)
def _read_record(self):
# read 4 chars for the header
_header = self.pipe.read(4)
+ if not _header:
+ raise errors.RadioNoResponse()
if len(_header) != 4:
- raise errors.RadioError('Radio did not respond')
+ raise errors.RadioError('Radio sent short header')
_length = struct.unpack('xxxB', _header)[0]
_packet = self.pipe.read(_length)
_rcs_xor = _packet[-1]
_packet = self.decrypt(_packet)
- _cs = self._checksum(_header[1:])
- _cs += self._checksum(_packet)
+ _cs = checksum.checksum_8bit(_header[1:])
+ _cs += checksum.checksum_8bit(_packet)
_cs %= 256
_rcs = self.strxor(self.pipe.read(1)[0], _rcs_xor)[0]
LOG.debug("_cs =%x", _cs)
@@ -394,7 +399,7 @@ class KGUV8DPlusRadio(chirp_common.CloneModeRadio,
if _resp[0:7] == self._model:
return
if len(_resp) == 0:
- raise Exception("Radio not responding")
+ raise errors.RadioNoResponse()
else:
raise Exception("Unable to identify radio")
@@ -525,50 +530,6 @@ class KGUV8DPlusRadio(chirp_common.CloneModeRadio,
def get_raw_memory(self, number):
return repr(self._memobj.memory[number])
- def _get_tone(self, _mem, mem):
- def _get_dcs(val):
- code = int("%03o" % (val & 0x07FF))
- pol = (val & 0x2000) and "R" or "N"
- return code, pol
-
- tpol = False
- if _mem.txtone != 0xFFFF and (_mem.txtone & 0x4000) == 0x4000:
- tcode, tpol = _get_dcs(_mem.txtone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
- mem.rtone = (_mem.txtone & 0x7fff) / 10.0
- txmode = "Tone"
- else:
- txmode = ""
-
- rpol = False
- if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x4000) == 0x4000:
- rcode, rpol = _get_dcs(_mem.rxtone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
- mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- # always set it even if no dtcs is used
- mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")
-
- LOG.debug("Got TX %s (%i) RX %s (%i)" %
- (txmode, _mem.txtone, rxmode, _mem.rxtone))
-
def get_memory(self, number):
_mem = self._memobj.memory[number]
_nam = self._memobj.names[number]
@@ -604,7 +565,7 @@ class KGUV8DPlusRadio(chirp_common.CloneModeRadio,
mem.name += chr(char)
mem.name = mem.name.rstrip()
- self._get_tone(_mem, mem)
+ self.tone_model.get_tone(_mem, mem)
mem.skip = "" if bool(_mem.scan_add) else "S"
@@ -612,44 +573,6 @@ class KGUV8DPlusRadio(chirp_common.CloneModeRadio,
mem.mode = _mem.iswide and "FM" or "NFM"
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- val = int("%i" % code, 8) + 0x4000
- if pol == "R":
- val += 0x2000
- return val
-
- rx_mode = tx_mode = None
- rxtone = txtone = 0x0000
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- txtone = int(mem.rtone * 10) + 0x8000
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rxtone = txtone = int(mem.ctone * 10) + 0x8000
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- txtone = int(mem.rtone * 10) + 0x8000
- if rx_mode == "DTCS":
- rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rxtone = int(mem.ctone * 10) + 0x8000
-
- _mem.rxtone = rxtone
- _mem.txtone = txtone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
-
def set_memory(self, mem):
number = mem.number
@@ -679,7 +602,7 @@ class KGUV8DPlusRadio(chirp_common.CloneModeRadio,
_mem.scan_add = int(mem.skip != "S")
_mem.iswide = int(mem.mode == "FM")
# set the tone
- self._set_tone(mem, _mem)
+ self.tone_model.set_tone(mem, _mem)
# set the scrambler and compander to off by default
_mem.scrambler = 0
_mem.compander = 0
diff --git a/chirp/drivers/kguv8e.py b/chirp/drivers/kguv8e.py
index 1e71216..e022400 100644
--- a/chirp/drivers/kguv8e.py
+++ b/chirp/drivers/kguv8e.py
@@ -22,11 +22,12 @@
import struct
import time
import logging
-from chirp import util, chirp_common, bitwise, memmap, errors, directory
+from chirp import checksum, util, chirp_common, bitwise, memmap, errors, directory
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueInteger, RadioSettingValueString, \
RadioSettings
+from chirp.kenwood_tone import KenwoodToneModel
LOG = logging.getLogger(__name__)
@@ -302,38 +303,49 @@ class KGUV8ERadio(chirp_common.CloneModeRadio,
"""Wouxun KG-UV8E"""
VENDOR = "Wouxun"
MODEL = "KG-UV8E"
+
+ def __init__(self, pipe):
+ super().__init__(pipe)
+ self.tone_model = KenwoodToneModel(
+ dcs_base=0x2800,
+ pol_mask=0x8000,
+ tone_init=0x0000
+ )
_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
- def _checksum(self, data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
def _write_record(self, cmd, payload=b''):
_packet = struct.pack('BBBB', self._record_start, cmd, 0xFF,
len(payload))
- checksum = bytes([self._checksum(_packet[1:] + payload)])
- _packet += self.encrypt(payload + checksum)
+ cs = bytes([checksum.checksum_8bit(_packet[1:] + payload)])
+ _packet += self.encrypt(payload + cs)
LOG.debug("Sent:\n%s" % util.hexprint(_packet))
self.pipe.write(_packet)
def _read_record(self):
# read 4 chars for the header
_header = self.pipe.read(4)
+ if not _header:
+ raise errors.RadioNoResponse()
if len(_header) != 4:
- raise errors.RadioError('Radio did not respond')
+ raise errors.RadioError('Radio sent short header')
_length = struct.unpack('xxxB', _header)[0]
_packet = self.pipe.read(_length)
_rcs_xor = _packet[-1]
_packet = self.decrypt(_packet)
- _cs = self._checksum(_header[1:])
- _cs += self._checksum(_packet)
+ _cs = checksum.checksum_8bit(_header[1:])
+ _cs += checksum.checksum_8bit(_packet)
_cs %= 256
_rcs = self.strxor(self.pipe.read(1)[0], _rcs_xor)[0]
LOG.debug("_cs =%x", _cs)
@@ -375,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):
@@ -394,7 +401,7 @@ class KGUV8ERadio(chirp_common.CloneModeRadio,
if _resp[0:9] == self._model:
return
if len(_resp) == 0:
- raise Exception("Radio not responding")
+ raise errors.RadioNoResponse()
else:
raise Exception("Unable to identify radio")
@@ -531,50 +538,6 @@ class KGUV8ERadio(chirp_common.CloneModeRadio,
def get_raw_memory(self, number):
return repr(self._memobj.memory[number])
- def _get_tone(self, _mem, mem):
- def _get_dcs(val):
- code = int("%03o" % (val & 0x07FF))
- pol = (val & 0x8000) and "R" or "N"
- return code, pol
-
- tpol = False
- if _mem.txtone != 0xFFFF and (_mem.txtone & 0x2800) == 0x2800:
- tcode, tpol = _get_dcs(_mem.txtone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
- mem.rtone = (_mem.txtone & 0x7fff) / 10.0
- txmode = "Tone"
- else:
- txmode = ""
-
- rpol = False
- if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x2800) == 0x2800:
- rcode, rpol = _get_dcs(_mem.rxtone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
- mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- # always set it even if no dtcs is used
- mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")
-
- LOG.debug("Got TX %s (%i) RX %s (%i)" %
- (txmode, _mem.txtone, rxmode, _mem.rxtone))
-
def get_memory(self, number):
_mem = self._memobj.memory[number]
_nam = self._memobj.names[number]
@@ -610,7 +573,7 @@ class KGUV8ERadio(chirp_common.CloneModeRadio,
mem.name += chr(char)
mem.name = mem.name.rstrip()
- self._get_tone(_mem, mem)
+ self.tone_model.get_tone(_mem, mem)
mem.skip = "" if bool(_mem.scan_add) else "S"
@@ -618,44 +581,6 @@ class KGUV8ERadio(chirp_common.CloneModeRadio,
mem.mode = _mem.iswide and "FM" or "NFM"
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- val = int("%i" % code, 8) + 0x2800
- if pol == "R":
- val += 0x8000
- return val
-
- rx_mode = tx_mode = None
- rxtone = txtone = 0x0000
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- txtone = int(mem.rtone * 10) + 0x8000
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rxtone = txtone = int(mem.ctone * 10) + 0x8000
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- txtone = int(mem.rtone * 10) + 0x8000
- if rx_mode == "DTCS":
- rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rxtone = int(mem.ctone * 10) + 0x8000
-
- _mem.rxtone = rxtone
- _mem.txtone = txtone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
-
def set_memory(self, mem):
number = mem.number
@@ -685,7 +610,7 @@ class KGUV8ERadio(chirp_common.CloneModeRadio,
_mem.scan_add = int(mem.skip != "S")
_mem.iswide = int(mem.mode == "FM")
# set the tone
- self._set_tone(mem, _mem)
+ self.tone_model.set_tone(mem, _mem)
# set the scrambler and compander to off by default
_mem.scrambler = 0
_mem.compander = 0
diff --git a/chirp/drivers/kguv920pa.py b/chirp/drivers/kguv920pa.py
index 049fe52..42ec8b6 100644
--- a/chirp/drivers/kguv920pa.py
+++ b/chirp/drivers/kguv920pa.py
@@ -18,11 +18,13 @@
import time
import logging
from chirp import util, chirp_common, bitwise, memmap, errors, directory
+from chirp import checksum
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueInteger, RadioSettingValueString, \
RadioSettingValueMap, RadioSettingValueFloat, RadioSettings
import struct
+from chirp.kenwood_tone import KenwoodToneModel
LOG = logging.getLogger(__name__)
@@ -329,13 +331,6 @@ _MEM_FORMAT = """
"""
-def _checksum(data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 16
-
-
def _str_decode(in_str):
out_str = ''
for c in in_str:
@@ -409,90 +404,6 @@ def _roger_encode(in_roger):
return roger_str
-def _get_tone(_mem, mem):
- def _get_dcs(val):
- code = (val & 0x3FF)
- pol = (val & 0x4000) and "R" or "N"
- return code, pol
-
- tpol = False
- if _mem.txtone != 0xFFFF and (_mem.txtone & 0x8000) == 0x8000:
- tcode, tpol = _get_dcs(_mem.txtone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
- mem.rtone = (_mem.txtone & 0xFff) / 10.0
- txmode = "Tone"
- else:
- txmode = ""
-
- rpol = False
- if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x8000) == 0x8000:
- rcode, rpol = _get_dcs(_mem.rxtone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
- mem.ctone = (_mem.rxtone & 0xFff) / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- # always set it even if no dtcs is used
- mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")
-
- LOG.debug("Got TX %s (%i) RX %s (%i)" %
- (txmode, _mem.txtone, rxmode, _mem.rxtone))
-
-
-def _set_tone(mem, _mem):
- def _set_dcs(code, pol):
- val = (code & 0x3FF) + 0x8000
- if pol == "R":
- val += 0x4000
- return val
-
- rx_mode = tx_mode = None
- rxtone = txtone = 0
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- txtone = int(mem.rtone * 10)
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rxtone = txtone = int(mem.ctone * 10)
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- txtone = int(mem.rtone * 10)
- if rx_mode == "DTCS":
- rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rxtone = int(mem.ctone * 10)
-
- _mem.rxtone = rxtone
- _mem.txtone = txtone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
-
-
# Support for the Wouxun KG-UV920P-A radio
# Serial coms are at 19200 baud
# The data is passed in variable length records
@@ -522,10 +433,23 @@ 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)]
+ def __init__(self, pipe):
+ super().__init__(pipe)
+ self.tone_model = KenwoodToneModel(
+ dcs_base=0x8000,
+ pol_mask=0x4000,
+ tone_init=0x0000,
+ tone_flag=0x0000,
+ dcs_enc_base=10)
+
def _write_record(self, cmd, payload=None):
_length = 0
if payload:
@@ -535,33 +459,31 @@ class KGUV920PARadio(chirp_common.CloneModeRadio,
# add the chars to the packet
_packet += payload
# calculate and add the checksum to the packet
- _packet += bytes([_checksum(_packet[1:])])
+ _packet += bytes([checksum.checksum_8bit(_packet[1:], 16)])
LOG.debug("Sent:\n%s" % util.hexprint(_packet))
self.pipe.write(_packet)
def _read_record(self):
# read 4 chars for the header
_header = self.pipe.read(4)
+ if not _header:
+ raise errors.RadioNoResponse()
if len(_header) != 4:
- raise errors.RadioError('Radio did not respond')
+ raise errors.RadioError('Radio sent short header')
_length = _header[3]
_packet = self.pipe.read(_length)
- _cs = _checksum(_header[1:])
- _cs += _checksum(_packet)
+ _cs = checksum.checksum_8bit(_header[1:], 16)
+ _cs += checksum.checksum_8bit(_packet, 16)
_cs %= 16
try:
_rcs = self.pipe.read(1)[0]
except (TypeError, IndexError):
- raise errors.RadioError('Radio did not respond')
+ raise errors.RadioNoResponse()
if _rcs != _cs:
LOG.error("_cs =%x", _cs)
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
@@ -575,7 +497,7 @@ class KGUV920PARadio(chirp_common.CloneModeRadio,
if _chksum_err:
raise Exception("Checksum error")
if len(_resp) == 0:
- raise Exception("Radio not responding")
+ raise errors.RadioNoResponse()
reported_model = _str_decode(_resp[0:10])
if reported_model != self._model:
raise Exception("Unable to identify radio (Got %s, Expected)" %
@@ -745,7 +667,7 @@ class KGUV920PARadio(chirp_common.CloneModeRadio,
else:
mem.name = ''
- _get_tone(_mem, mem)
+ self.tone_model.get_tone(_mem, mem)
mem.skip = "" if bool(_mem.scan_add) else "S"
@@ -811,7 +733,7 @@ class KGUV920PARadio(chirp_common.CloneModeRadio,
_mem.isnarrow = 0b11 * int(mem.mode == "NFM")
# set the tone
- _set_tone(mem, _mem)
+ self.tone_model.set_tone(mem, _mem)
# set the power
if mem.power:
diff --git a/chirp/drivers/kguv980p.py b/chirp/drivers/kguv980p.py
index 905759a..dd73a55 100644
--- a/chirp/drivers/kguv980p.py
+++ b/chirp/drivers/kguv980p.py
@@ -27,6 +27,7 @@ import logging
import struct
from chirp import util, chirp_common, bitwise, memmap, errors, directory
+from chirp.kenwood_tone import KenwoodToneModel
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueInteger, RadioSettingValueString, \
@@ -721,6 +722,15 @@ class KG980PRadio(chirp_common.CloneModeRadio,
chirp_common.PowerLevel("M", watts=20.0),
chirp_common.PowerLevel("H", watts=50.0)]
+ def __init__(self, pipe):
+ super().__init__(pipe)
+ self.tone_model = KenwoodToneModel(
+ dcs_base=0x8000,
+ pol_mask=0x4000,
+ tone_init=0x0000,
+ tone_flag=0x0000,
+ dcs_enc_base=10)
+
def _checksum(self, data):
cs = 0
for byte in data:
@@ -738,8 +748,10 @@ class KG980PRadio(chirp_common.CloneModeRadio,
def _read_record(self):
# read 4 chars for the header
_header = self.pipe.read(4)
+ if not _header:
+ raise errors.RadioNoResponse()
if len(_header) != 4:
- raise errors.RadioError('Radio did not respond')
+ raise errors.RadioError('Radio sent short header')
_length = struct.unpack('xxxB', _header)[0]
_packet = self.pipe.read(_length)
_rcs_xor = _packet[-1]
@@ -786,7 +798,7 @@ class KG980PRadio(chirp_common.CloneModeRadio,
self._write_record(CMD_ID)
_chksum_err, _resp = self._read_record()
if len(_resp) == 0:
- raise errors.RadioError("Radio not responding")
+ raise errors.RadioNoResponse()
else:
LOG.debug("Got:\n%s" % util.hexprint(_resp))
LOG.debug("Model received is %s" % _resp[0:10])
@@ -948,58 +960,6 @@ class KG980PRadio(chirp_common.CloneModeRadio,
def get_raw_memory(self, number):
return repr(self._memobj.memory[number])
- def _get_tone(self, _mem, mem):
- # - corrected the Polarity decoding to match 980P implementation
- # use 0x4000 bit mask for R
- # - 0x4000 appears to be the bit mask for Inverted DCS tones
- # - n DCS Tone will be 0x8xxx values - i DCS Tones will
- # be 0xCxxx values.
- # - Chirp Uses N for n DCS Tones and R for i DCS Tones
- # - 980P encodes DCS tone # in decimal - NOT OCTAL
- def _get_dcs(val):
- code = int("%03d" % (val & 0x07FF))
- pol = (val & 0x4000) and "R" or "N"
- return code, pol
- # - Modified the function below to bitwise AND with 0x4000
- # to check for 980P DCS Tone decoding
- # 0x8000 appears to be the bit mask for DCS tones
- tpol = False
- # Beta 1.1 - Fix the txtone compare to 0x8000 - was rxtone.
- if _mem.txtone != 0xFFFF and (_mem.txtone & 0x8000) == 0x8000:
- tcode, tpol = _get_dcs(_mem.txtone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
- mem.rtone = (_mem.txtone & 0x7fff) / 10.0
- txmode = "Tone"
- else:
- txmode = ""
- # - Modified the function below to bitwise AND with 0x4000
- # to check for 980P DCS Tone decoding
- rpol = False
- if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x8000) == 0x8000:
- rcode, rpol = _get_dcs(_mem.rxtone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
- mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- # always set it even if no dtcs is used
- mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")
-
def get_memory(self, number):
_mem = self._memobj.memory[number]
@@ -1059,7 +1019,7 @@ class KG980PRadio(chirp_common.CloneModeRadio,
else:
mem.name = ''
- self._get_tone(_mem, mem)
+ self.tone_model.get_tone(_mem, mem)
mem.skip = "" if bool(_mem.scan_add) else "S"
@@ -1087,49 +1047,6 @@ class KG980PRadio(chirp_common.CloneModeRadio,
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- # Change to 0x8000 to
- # set the bit for DCS- code is a decimal version
- # of the code # - NOT OCTAL
- val = code | 0x8000
- if pol == "R":
- # Change to 0x4000 to set the bit for
- # i/R polarity
- val += 0x4000
- return val
-
- rx_mode = tx_mode = None
- rxtone = txtone = 0x0000
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- txtone = int(mem.rtone * 10)
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rxtone = txtone = int(mem.ctone * 10)
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- txtone = int(mem.rtone * 10)
- if rx_mode == "DTCS":
- rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rxtone = int(mem.ctone * 10)
-
- _mem.rxtone = rxtone
- _mem.txtone = txtone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
-
def set_memory(self, mem):
# _mem = Stored Memory value
# mem = New value from user entry
@@ -1178,14 +1095,13 @@ class KG980PRadio(chirp_common.CloneModeRadio,
_mem.isnarrow = False
# set the tone
- self._set_tone(mem, _mem)
+ self.tone_model.set_tone(mem, _mem)
# set the scrambler and compander to off by default
# This changes them in the channel memory
_mem.scrambler = 0
_mem.compander = 0
# set the power
- # Updated to resolve "Illegal set on attribute power" Warning
- if str(mem.power) == "None":
+ if mem.power is None:
_mem.power = 0 # Default to Low power
else:
index = self.POWER_LEVELS.index(mem.power)
diff --git a/chirp/drivers/kguv9dplus.py b/chirp/drivers/kguv9dplus.py
index ff88869..0945388 100644
--- a/chirp/drivers/kguv9dplus.py
+++ b/chirp/drivers/kguv9dplus.py
@@ -25,6 +25,7 @@ import time
import logging
import struct
from chirp import chirp_common, bitwise, memmap, errors, directory
+from chirp.kenwood_tone import KenwoodToneModel
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, \
RadioSettingValueList, RadioSettingValueInteger, \
@@ -350,8 +351,8 @@ struct {
struct {
u32 rxfreq;
u32 txfreq;
- u16 encQT;
- u16 decQT;
+ u16 txtone;
+ u16 rxtone;
u8 bit7_5:3, // all ones
qt:3,
bit1_0:2;
@@ -614,8 +615,8 @@ struct {
struct {
u32 rxfreq;
u32 txfreq;
- u16 encQT;
- u16 decQT;
+ u16 txtone;
+ u16 rxtone;
u8 bit7_5:3, // all ones
qt:3,
bit1_0:2;
@@ -1092,12 +1093,19 @@ 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)]
_step_list = STEP_LIST
_valid_steps = STEPS
_mmap = ""
+ _tone_model = KenwoodToneModel(
+ dcs_base=0x8000, pol_mask=0x4000, tone_init=0x0000,
+ tone_flag=0x0000, dcs_enc_base=8)
def _read_record(self):
""" Read and validate the header of a radio reply.
@@ -1115,8 +1123,10 @@ class KGUV9DPlusRadio(chirp_common.CloneModeRadio,
# first get the header and validate it
data = bytearray(self.pipe.read(4))
+ if not data:
+ raise errors.RadioNoResponse()
if (len(data) < 4):
- raise errors.RadioError('Radio did not respond')
+ raise errors.RadioError('Radio sent short header')
if (data[0] != 0x7D):
raise errors.RadioError(
'Radio reply garbled (%02x)' % data[0])
@@ -1142,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.
@@ -1172,7 +1173,7 @@ class KGUV9DPlusRadio(chirp_common.CloneModeRadio,
self._write_record(CMD_IDENT)
chksum_match, op, _resp = self._read_record()
if len(_resp) == 0:
- raise Exception("Radio not responding")
+ raise errors.RadioNoResponse()
if len(_resp) != 74:
LOG.error(
"Expected and IDENT reply of 78 bytes. Got (%d)" %
@@ -1380,55 +1381,6 @@ class KGUV9DPlusRadio(chirp_common.CloneModeRadio,
def get_raw_memory(self, number):
return repr(self._memobj.chan_blk[number - 1])
- def _get_tone(self, _mem, mem):
- """Decode both the encode and decode CTSS/DCS codes from
- the memory channel and stuff them into the UI
- memory channel row.
- """
- txtone = short2tone(_mem.encQT)
- rxtone = short2tone(_mem.decQT)
- pt = "N"
- pr = "N"
-
- if txtone == "----":
- txmode = ""
- elif txtone[0] == "D":
- mem.dtcs = int(txtone[1:4])
- if txtone[4] == "I":
- pt = "R"
- txmode = "DTCS"
- else:
- mem.rtone = float(txtone)
- txmode = "Tone"
-
- if rxtone == "----":
- rxmode = ""
- elif rxtone[0] == "D":
- mem.rx_dtcs = int(rxtone[1:4])
- if rxtone[4] == "I":
- pr = "R"
- rxmode = "DTCS"
- else:
- mem.ctone = float(rxtone)
- rxmode = "Tone"
-
- if txmode == "Tone" and len(rxmode) == 0:
- mem.tmode = "Tone"
- elif (txmode == rxmode and txmode == "Tone" and
- mem.rtone == mem.ctone):
- mem.tmode = "TSQL"
- elif (txmode == rxmode and txmode == "DTCS" and
- mem.dtcs == mem.rx_dtcs):
- mem.tmode = "DTCS"
- elif (len(rxmode) + len(txmode)) > 0:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- mem.dtcs_polarity = pt + pr
-
- LOG.debug("_get_tone: Got TX %s (%i) RX %s (%i)" %
- (txmode, _mem.encQT, rxmode, _mem.decQT))
-
def get_memory(self, number):
""" Public get_memory
Return the channel memory referenced by number to the UI.
@@ -1505,7 +1457,7 @@ class KGUV9DPlusRadio(chirp_common.CloneModeRadio,
mem.name = name2str(_nam.name)
- self._get_tone(_mem, mem)
+ self._tone_model.get_tone(_mem, mem)
mem.skip = "" if bool(_mem.scan) else "S"
@@ -1519,46 +1471,6 @@ class KGUV9DPlusRadio(chirp_common.CloneModeRadio,
# qt has no home in the UI
return mem
- def _set_tone(self, mem, _mem):
- """Update the memory channel block CTCC/DCS tones
- from the UI fields
- """
- def _set_dcs(code, pol):
- val = int("%i" % code, 8) | 0x8000
- if pol == "R":
- val |= 0x4000
- return val
-
- rx_mode = tx_mode = None
- rxtone = txtone = 0x0000
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- txtone = int(mem.rtone * 10)
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rxtone = txtone = int(mem.ctone * 10)
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- txtone = int(mem.rtone * 10)
- if rx_mode == "DTCS":
- rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rxtone = int(mem.ctone * 10)
-
- _mem.decQT = rxtone
- _mem.encQT = txtone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.encQT, rx_mode, _mem.decQT))
-
def set_memory(self, mem):
""" Public set_memory
Inverse of get_memory. Update the radio memory image
@@ -1613,7 +1525,7 @@ class KGUV9DPlusRadio(chirp_common.CloneModeRadio,
_mem.mod = 0
_mem.fm_dev = 0 # Catchall default is FM
# set the tone
- self._set_tone(mem, _mem)
+ self._tone_model.set_tone(mem, _mem)
# set the power
if mem.power:
_mem.pwr = self.POWER_LEVELS.index(mem.power)
diff --git a/chirp/drivers/kyd.py b/chirp/drivers/kyd.py
index 8dd4e8b..29a793f 100644
--- a/chirp/drivers/kyd.py
+++ b/chirp/drivers/kyd.py
@@ -19,6 +19,7 @@ import logging
from chirp import chirp_common, directory, memmap
from chirp import bitwise, errors, util
+from chirp import kenwood_tone
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueInteger, RadioSettingValueList, \
RadioSettingValueBoolean, RadioSettings
@@ -30,8 +31,8 @@ MEM_FORMAT = """
struct {
lbcd rxfreq[4];
lbcd txfreq[4];
- ul16 rx_tone;
- ul16 tx_tone;
+ ul16 rxtone;
+ ul16 txtone;
u8 unknown1:3,
bcl:2, // Busy Lock
unknown2:3;
@@ -85,7 +86,7 @@ def _nc630a_enter_programming_mode(radio):
raise errors.RadioError("Error communicating with radio")
if not ack:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")
@@ -214,6 +215,8 @@ class NC630aRadio(chirp_common.CloneModeRadio):
_memsize = 0x03C8
_block_size = 0x08
_fileid = b"P32073"
+ _tone_model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x2800, pol_mask=0x8000, tone_init=0xFFFF, tone_flag=0x0000)
def get_features(self):
rf = chirp_common.RadioFeatures()
@@ -252,48 +255,6 @@ class NC630aRadio(chirp_common.CloneModeRadio):
def get_raw_memory(self, number):
return repr(self._memobj.memory[number - 1])
- def _get_tone(self, _mem, mem):
- def _get_dcs(val):
- code = int("%03o" % (val & 0x07FF))
- pol = (val & 0x8000) and "R" or "N"
- return code, pol
-
- if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
- tcode, tpol = _get_dcs(_mem.tx_tone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.tx_tone != 0xFFFF:
- mem.rtone = _mem.tx_tone / 10.0
- txmode = "Tone"
- else:
- txmode = ""
-
- if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
- rcode, rpol = _get_dcs(_mem.rx_tone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rx_tone != 0xFFFF:
- mem.ctone = _mem.rx_tone / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- if mem.tmode == "DTCS":
- mem.dtcs_polarity = "%s%s" % (tpol, rpol)
-
- LOG.debug("Got TX %s (%i) RX %s (%i)" %
- (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
-
def get_memory(self, number):
bitpos = (1 << ((number - 1) % 8))
bytepos = ((number - 1) / 8)
@@ -329,7 +290,7 @@ class NC630aRadio(chirp_common.CloneModeRadio):
mem.mode = _mem.wide and "FM" or "NFM"
- self._get_tone(_mem, mem)
+ self._tone_model.get_tone(_mem, mem)
mem.power = NC630A_POWER_LEVELS[_mem.highpower]
@@ -345,44 +306,6 @@ class NC630aRadio(chirp_common.CloneModeRadio):
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- val = int("%i" % code, 8) + 0x2800
- if pol == "R":
- val += 0x8000
- return val
-
- rx_mode = tx_mode = None
- rx_tone = tx_tone = 0xFFFF
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- tx_tone = int(mem.rtone * 10)
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rx_tone = tx_tone = int(mem.ctone * 10)
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- tx_tone = int(mem.rtone * 10)
- if rx_mode == "DTCS":
- rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rx_tone = int(mem.ctone * 10)
-
- _mem.rx_tone = rx_tone
- _mem.tx_tone = tx_tone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
-
def set_memory(self, mem):
bitpos = (1 << ((mem.number - 1) % 8))
bytepos = ((mem.number - 1) / 8)
@@ -413,7 +336,7 @@ class NC630aRadio(chirp_common.CloneModeRadio):
_mem.wide = mem.mode == "FM"
- self._set_tone(mem, _mem)
+ self._tone_model.set_tone(mem, _mem)
_mem.highpower = mem.power == NC630A_POWER_LEVELS[1]
diff --git a/chirp/drivers/kyd_IP620.py b/chirp/drivers/kyd_IP620.py
index f98ddc3..b59c628 100644
--- a/chirp/drivers/kyd_IP620.py
+++ b/chirp/drivers/kyd_IP620.py
@@ -24,6 +24,7 @@ import struct
import time
import logging
from chirp import util, chirp_common, bitwise, memmap, errors, directory
+from chirp import kenwood_tone
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueList, RadioSettings
@@ -34,8 +35,8 @@ IP620_MEM_FORMAT = """
struct { // Channel memory structure
lbcd rx_freq[4]; // RX frequency
lbcd tx_freq[4]; // TX frequency
- ul16 rx_tone; // RX tone
- ul16 tx_tone; // TX tone
+ ul16 rxtone; // RX tone
+ ul16 txtone; // TX tone
u8 unknown_1:4, // n-a
busy_loc:2, // NO-00, Carrier wave-01, SM-10
n_a:2; // n-a
@@ -169,6 +170,8 @@ class IP620Radio(chirp_common.CloneModeRadio,
(0x0000, 0x2000),
]
_memsize = 0x2000
+ _tone_model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x2800, pol_mask=0x8000, tone_init=0xFFFF, tone_flag=0x0000)
@classmethod
def match_model(cls, filedata, filename):
@@ -194,7 +197,7 @@ class IP620Radio(chirp_common.CloneModeRadio,
except Exception as e:
raise errors.RadioError("Error communicating with radio: %s" % e)
if not _ack:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif _ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")
try:
@@ -325,48 +328,6 @@ class IP620Radio(chirp_common.CloneModeRadio,
def get_raw_memory(self, number):
return repr(self._memobj.memory[number - 1])
- def _get_tone(self, _mem, mem):
- def _get_dcs(val):
- code = int("%03o" % (val & 0x07FF))
- pol = (val & 0x8000) and "R" or "N"
- return code, pol
-
- if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
- tcode, tpol = _get_dcs(_mem.tx_tone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.tx_tone != 0xFFFF:
- mem.rtone = _mem.tx_tone / 10.0
- txmode = "Tone"
- else:
- txmode = ""
-
- if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
- rcode, rpol = _get_dcs(_mem.rx_tone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rx_tone != 0xFFFF:
- mem.ctone = _mem.rx_tone / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- if mem.tmode == "DTCS":
- mem.dtcs_polarity = "%s%s" % (tpol, rpol)
-
- LOG.debug("Got TX %s (%i) RX %s (%i)" % (txmode, _mem.tx_tone,
- rxmode, _mem.rx_tone))
-
def get_memory(self, number):
_mem = self._memobj.memory[number - 1]
_nam = self._memobj.chan_names[number - 1]
@@ -395,7 +356,7 @@ class IP620Radio(chirp_common.CloneModeRadio,
mem.offset = abs(int(_mem.rx_freq) - int(_mem.tx_freq)) * 10
mem.mode = _mem.w_n and "FM" or "NFM"
- self._get_tone(_mem, mem)
+ self._tone_model.get_tone(_mem, mem)
mem.power = POWER_LEVELS[_mem.power]
mem.extra = RadioSettingGroup("Extra", "extra")
@@ -429,44 +390,6 @@ class IP620Radio(chirp_common.CloneModeRadio,
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- val = int("%i" % code, 8) + 0x2800
- if pol == "R":
- val += 0x8000
- return val
-
- rx_mode = tx_mode = None
- rx_tone = tx_tone = 0xFFFF
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- tx_tone = int(mem.rtone * 10)
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rx_tone = tx_tone = int(mem.ctone * 10)
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- tx_tone = int(mem.rtone * 10)
- if rx_mode == "DTCS":
- rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rx_tone = int(mem.ctone * 10)
-
- _mem.rx_tone = rx_tone
- _mem.tx_tone = tx_tone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
-
def set_memory(self, mem):
_mem = self._memobj.memory[mem.number - 1]
if mem.empty:
@@ -484,7 +407,7 @@ class IP620Radio(chirp_common.CloneModeRadio,
_mem.tx_freq = mem.freq / 10
_mem.w_n = mem.mode == "FM"
- self._set_tone(mem, _mem)
+ self._tone_model.set_tone(mem, _mem)
_mem.power = mem.power == POWER_LEVELS[1]
for setting in ('lout', 'busy_loc', 'scan_add'):
diff --git a/chirp/drivers/leixen.py b/chirp/drivers/leixen.py
index 6d0bd25..48e4ae0 100644
--- a/chirp/drivers/leixen.py
+++ b/chirp/drivers/leixen.py
@@ -16,7 +16,7 @@
import struct
import logging
-from chirp import chirp_common, directory, memmap, errors, util
+from chirp import chirp_common, directory, memmap, errors, util, checksum
from chirp import bitwise
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueInteger, RadioSettingValueList, \
@@ -238,18 +238,11 @@ def _image_ident_from_image(radio):
return _image_ident_from_data(radio.get_mmap())
-def checksum(frame):
- x = 0
- for b in frame:
- x ^= b
- return x & 0xFF
-
-
def make_frame(cmd, addr, data=b""):
payload = struct.pack(">H", addr) + data
header = struct.pack(">cB", cmd, len(payload))
frame = header + payload
- return frame + bytes([checksum(frame)])
+ return frame + bytes([checksum.checksum_xor(frame)])
def send(radio, frame):
@@ -424,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/lt725uv.py b/chirp/drivers/lt725uv.py
index cc495dd..bc90c13 100644
--- a/chirp/drivers/lt725uv.py
+++ b/chirp/drivers/lt725uv.py
@@ -254,6 +254,9 @@ def _rawrecv(radio, amount):
msg = "Generic error reading data from radio; check your cable."
raise errors.RadioError(msg)
+ if not data:
+ _exit_program_mode(radio)
+ raise errors.RadioNoResponse()
if len(data) != amount:
_exit_program_mode(radio)
msg = "Error reading from radio: not the amount of data we want."
@@ -307,11 +310,13 @@ def _do_ident(radio):
_rawsend(radio, magic)
ack = _rawrecv(radio, 1)
+ if not ack:
+ _exit_program_mode(radio)
+ raise errors.RadioNoResponse()
if ack != b"\x06":
_exit_program_mode(radio)
- if ack:
- LOG.debug(repr(ack))
- raise errors.RadioError("Radio did not respond")
+ LOG.debug(repr(ack))
+ raise errors.RadioError("Unexpected response from radio")
return True
@@ -550,7 +555,9 @@ class LT725UV(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
_upload(self)
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
LOG.exception('Unexpected error during upload')
@@ -568,10 +575,10 @@ class LT725UV(chirp_common.CloneModeRadio):
return getattr(self._memobj, "%s_memory%s" % (self._vfo, suffix))
def _get_dcs(self, val):
- return int(str(val)[2:-18])
+ return val.get_bbcd()
def _set_dcs(self, val):
- return int(str(val), 16)
+ return bitwise.dec_to_bbcd(val)
def get_memory(self, number):
_mem = self._memory_obj()[number - 1]
diff --git a/chirp/drivers/mml_jc8810.py b/chirp/drivers/mml_jc8810.py
index 3a43daf..7eda7cf 100644
--- a/chirp/drivers/mml_jc8810.py
+++ b/chirp/drivers/mml_jc8810.py
@@ -291,6 +291,8 @@ def _enter_programming_mode(radio):
# check if we had EXITO
if exito is False:
+ if not ack:
+ 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)
@@ -492,6 +494,8 @@ class JC8810base(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
do_upload(self)
+ except errors.RadioError:
+ raise
except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
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/puxing.py b/chirp/drivers/puxing.py
index b49801a..03b22f8 100644
--- a/chirp/drivers/puxing.py
+++ b/chirp/drivers/puxing.py
@@ -361,8 +361,10 @@ def puxing_2r_prep(radio):
radio.pipe.timeout = 0.2
radio.pipe.write(b"PROGRAM\x02")
ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != b"\x06":
- raise Exception("Radio is not responding")
+ raise Exception("Unexpected response from radio")
radio.pipe.write(ack)
ident = radio.pipe.read(16)
diff --git a/chirp/drivers/radioddity_db40g.py b/chirp/drivers/radioddity_db40g.py
new file mode 100644
index 0000000..54d7c5d
--- /dev/null
+++ b/chirp/drivers/radioddity_db40g.py
@@ -0,0 +1,476 @@
+# Copyright 2026 Tony Gies <tgies@tgies.net>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import logging
+import struct
+
+from chirp import bandplan_na
+from chirp import bitwise
+from chirp import chirp_common
+from chirp import directory
+from chirp import errors
+from chirp import memmap
+from chirp import util
+from chirp.settings import MemSetting, RadioSettingGroup, \
+ RadioSettingValueInteger, RadioSettingValueList, \
+ RadioSettings
+
+LOG = logging.getLogger(__name__)
+
+# Serial protocol constants
+CMD_ACK = b"\x06"
+CMD_PROGRAM = b"\x02PROGRAM"
+CMD_EXIT = b"\x62"
+IDENT_PREFIX = b"SMP558"
+
+# Memory layout constants
+NUM_CHANNELS = 199
+CH_START_ADDR = 0x0010
+PAGE_STRIDE = 0x10
+PAGE_SIZE = 0x20 # 32 bytes per page read
+SETTINGS_ADDR = 0xE000
+SETTINGS_OFFSET = NUM_CHANNELS * PAGE_SIZE # 0x18E0
+MEM_SIZE = (NUM_CHANNELS + 1) * PAGE_SIZE # 6400
+
+POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5),
+ chirp_common.PowerLevel("Mid", watts=20),
+ chirp_common.PowerLevel("High", watts=40)]
+
+# Tone encoding flags (big-endian u16 bitfield):
+# bit 15: DCS inverted polarity
+# bit 13: DCS mode
+# bit 11: set for DCS (not CTCSS)
+# bits 0-10: DCS code as int(octal, 8), or full u16 = CTCSS Hz*10
+TONE_OFF = 0xFFFF
+TONE_DCS_FLAG = 0x2000 # bit 13
+TONE_INV_FLAG = 0x8000 # bit 15
+TONE_DCS_MASK = 0x07FF # bits 0-10: DCS code value
+
+TOT_OPTIONS = ["Off", "30s", "60s", "90s", "120s", "150s",
+ "180s", "210s", "240s", "270s", "300s"]
+
+MEM_FORMAT = """
+struct channel {
+ u32 rxfreq;
+ u32 txfreq;
+ u16 rxtone;
+ u16 txtone;
+ u8 bandwidth;
+ u8 txpower;
+ char name[8];
+ u8 pad[10];
+};
+
+struct settings {
+ u8 busylock;
+ u8 keytone;
+ u8 tot;
+ u8 squelch;
+ u8 pad[28];
+};
+
+#seekto 0x0000;
+struct channel memory[%d];
+
+#seekto 0x%04X;
+struct settings settings;
+"""
+
+
+# --- Serial protocol ---
+
+def _enter_programming(radio):
+ """Three-step handshake to enter programming mode."""
+ serial = radio.pipe
+
+ try:
+ serial.write(CMD_PROGRAM)
+ ack = serial.read(1)
+ except Exception:
+ raise errors.RadioError(
+ "Error communicating with radio")
+ if ack != CMD_ACK:
+ raise errors.RadioError(
+ "Radio did not respond to program mode request")
+
+ try:
+ serial.write(b"\x02")
+ ident = serial.read(8)
+ except Exception:
+ raise errors.RadioError(
+ "Error communicating with radio")
+ LOG.debug("Ident: %s", util.hexprint(ident))
+ if not ident.startswith(IDENT_PREFIX):
+ raise errors.RadioError(
+ "Unsupported radio (ident %s)" % ident.hex())
+
+ try:
+ serial.write(CMD_ACK)
+ ack = serial.read(1)
+ except Exception:
+ raise errors.RadioError(
+ "Error communicating with radio")
+ if ack != CMD_ACK:
+ raise errors.RadioError(
+ "Radio refused programming mode")
+
+
+def _exit_programming(radio):
+ try:
+ radio.pipe.write(CMD_EXIT)
+ except Exception:
+ raise errors.RadioError(
+ "Failed to exit programming mode")
+
+
+def _read_page(radio, addr):
+ """Read one 32-byte page. Response echoes R prefix (not W)."""
+ serial = radio.pipe
+ cmd = struct.pack(">cHB", b"R", addr, PAGE_SIZE)
+ LOG.debug("Read page 0x%04X", addr)
+
+ try:
+ serial.write(cmd)
+ response = serial.read(4 + PAGE_SIZE)
+ except Exception:
+ raise errors.RadioError(
+ "Failed to read from radio at 0x%04X" % addr)
+
+ if len(response) != 4 + PAGE_SIZE:
+ raise errors.RadioError(
+ "Short read at 0x%04X (%d bytes)" % (
+ addr, len(response)))
+
+ expected = struct.pack(">cHB", b"R", addr, PAGE_SIZE)
+ if response[:4] != expected:
+ raise errors.RadioError(
+ "Bad read response at 0x%04X" % addr)
+
+ return response[4:]
+
+
+def _write_page(radio, addr, data):
+ """Write one 32-byte page. Expects ACK."""
+ serial = radio.pipe
+ cmd = struct.pack(">cHB", b"W", addr, PAGE_SIZE)
+ LOG.debug("Write page 0x%04X", addr)
+
+ try:
+ serial.write(cmd + data)
+ ack = serial.read(1)
+ except Exception:
+ raise errors.RadioError(
+ "Failed to write to radio at 0x%04X" % addr)
+
+ if ack != CMD_ACK:
+ raise errors.RadioError(
+ "No ACK after write at 0x%04X" % addr)
+
+
+def do_download(radio):
+ _enter_programming(radio)
+
+ data = b""
+ status = chirp_common.Status()
+ status.msg = "Cloning from radio"
+ status.cur = 0
+ status.max = NUM_CHANNELS + 1
+
+ for i in range(NUM_CHANNELS):
+ addr = CH_START_ADDR + i * PAGE_STRIDE
+ data += _read_page(radio, addr)
+ status.cur = i + 1
+ radio.status_fn(status)
+
+ data += _read_page(radio, SETTINGS_ADDR)
+ status.cur = status.max
+ radio.status_fn(status)
+
+ _exit_programming(radio)
+ return memmap.MemoryMapBytes(data)
+
+
+def do_upload(radio):
+ _enter_programming(radio)
+
+ status = chirp_common.Status()
+ status.msg = "Uploading to radio"
+ status.cur = 0
+ status.max = NUM_CHANNELS + 1
+
+ raw = radio.get_mmap().get_packed()
+
+ for i in range(NUM_CHANNELS):
+ addr = CH_START_ADDR + i * PAGE_STRIDE
+ offset = i * PAGE_SIZE
+ page = raw[offset:offset + PAGE_SIZE]
+ _write_page(radio, addr, page)
+ status.cur = i + 1
+ radio.status_fn(status)
+
+ _write_page(radio, SETTINGS_ADDR,
+ raw[SETTINGS_OFFSET:SETTINGS_OFFSET + PAGE_SIZE])
+ status.cur = status.max
+ radio.status_fn(status)
+
+ _exit_programming(radio)
+
+
+# --- Tone encoding ---
+
+def _decode_tone(value):
+ """Decode 16-bit tone to (mode, value, polarity).
+
+ Bit layout of the u16 tone value:
+ bit 15: DCS inverted polarity
+ bit 13: DCS mode flag
+ bits 0-10: DCS code (as int(octal, 8))
+ If DCS flag clear: full u16 is CTCSS Hz * 10
+ 0xFFFF = Off
+ """
+ if value == TONE_OFF:
+ return '', None, None
+ if value & TONE_DCS_FLAG:
+ code_dec = value & TONE_DCS_MASK
+ code_oct = int(oct(code_dec)[2:])
+ pol = 'R' if value & TONE_INV_FLAG else 'N'
+ return 'DTCS', code_oct, pol
+ return 'Tone', value / 10.0, None
+
+
+def _encode_tone(mode, value, polarity):
+ """Encode tone to 16-bit value for radio."""
+ if mode == '':
+ return TONE_OFF
+ elif mode == 'Tone':
+ return int(value * 10)
+ elif mode == 'DTCS':
+ code_dec = int(str(value), 8)
+ result = TONE_DCS_FLAG | 0x0800 | code_dec
+ if polarity == 'R':
+ result |= TONE_INV_FLAG
+ return result
+ raise errors.RadioError(
+ "Unsupported tone mode: %s" % mode)
+
+
+# --- Driver class ---
+
+@directory.register
+class RadioddityDB40G(chirp_common.CloneModeRadio):
+ """Radioddity DB40-G"""
+ VENDOR = "Radioddity"
+ MODEL = "DB40-G"
+ BAUD_RATE = 19200
+
+ _memsize = MEM_SIZE
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_settings = True
+ rf.has_bank = False
+ rf.has_tuning_step = False
+ rf.has_rx_dtcs = True
+ rf.has_ctone = True
+ rf.has_cross = True
+ rf.can_odd_split = True
+ 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 = ["", "-", "+", "split", "off"]
+ rf.valid_skips = []
+ rf.valid_characters = chirp_common.CHARSET_ASCII
+ rf.valid_name_length = 8
+ rf.valid_power_levels = POWER_LEVELS
+ rf.valid_bands = [(400000000, 480000000)]
+ rf.memory_bounds = (1, NUM_CHANNELS)
+ rf.valid_tuning_steps = [5.0, 6.25, 12.5, 25.0]
+ return rf
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(
+ MEM_FORMAT % (NUM_CHANNELS, SETTINGS_OFFSET),
+ self._mmap)
+
+ def sync_in(self):
+ self._mmap = do_download(self)
+ self.process_mmap()
+
+ def sync_out(self):
+ do_upload(self)
+
+ 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
+
+ rxfreq = int(_mem.rxfreq)
+ if rxfreq == 0 or rxfreq == 0xFFFFFFFF:
+ mem.empty = True
+ return mem
+
+ mem.freq = rxfreq
+
+ txfreq = int(_mem.txfreq)
+ if txfreq == 0:
+ mem.duplex = "off"
+ mem.offset = 0
+ elif txfreq == rxfreq:
+ mem.duplex = ""
+ mem.offset = 0
+ elif txfreq > rxfreq:
+ mem.duplex = "+"
+ mem.offset = txfreq - rxfreq
+ else:
+ mem.duplex = "-"
+ mem.offset = rxfreq - txfreq
+
+ mem.mode = "FM" if _mem.bandwidth else "NFM"
+
+ pwr = int(_mem.txpower)
+ if 0 <= pwr < len(POWER_LEVELS):
+ mem.power = POWER_LEVELS[pwr]
+ else:
+ mem.power = POWER_LEVELS[0]
+
+ mem.name = str(_mem.name).rstrip("\x00 ")
+
+ txtone = _decode_tone(int(_mem.txtone))
+ rxtone = _decode_tone(int(_mem.rxtone))
+ chirp_common.split_tone_decode(mem, txtone, rxtone)
+
+ return mem
+
+ def validate_memory(self, mem):
+ msgs = super().validate_memory(mem)
+ if mem.empty:
+ return msgs
+
+ if mem.duplex == "split":
+ tx_freq = mem.offset
+ elif mem.duplex == "+":
+ tx_freq = mem.freq + mem.offset
+ elif mem.duplex == "-":
+ tx_freq = mem.freq - mem.offset
+ elif mem.duplex == "off":
+ tx_freq = 0
+ else:
+ tx_freq = mem.freq
+
+ if tx_freq:
+ rpt = [f + 5000000
+ for f in bandplan_na.GMRS_HIRPT]
+ all_tx = (list(bandplan_na.ALL_GMRS_FREQS)
+ + rpt)
+ if tx_freq not in all_tx:
+ msgs.append(
+ chirp_common.ValidationWarning(
+ "TX frequency %s is not a "
+ "standard GMRS frequency"
+ % chirp_common.format_freq(
+ tx_freq)))
+
+ if tx_freq in bandplan_na.GMRS_HHONLY:
+ if mem.power and \
+ mem.power != POWER_LEVELS[0]:
+ msgs.append(
+ chirp_common.ValidationWarning(
+ "GMRS 467 MHz channels "
+ "require low power"))
+ if mem.mode != "NFM":
+ msgs.append(
+ chirp_common.ValidationWarning(
+ "GMRS 467 MHz channels "
+ "require narrowband"))
+
+ return msgs
+
+ def set_memory(self, mem):
+ _mem = self._memobj.memory[mem.number - 1]
+
+ if mem.empty:
+ _mem.set_raw(b"\x00" * PAGE_SIZE)
+ return
+
+ _mem.rxfreq = mem.freq
+
+ if mem.duplex == "off":
+ _mem.txfreq = 0
+ elif mem.duplex == "+":
+ _mem.txfreq = mem.freq + mem.offset
+ elif mem.duplex == "-":
+ _mem.txfreq = mem.freq - mem.offset
+ elif mem.duplex == "split":
+ _mem.txfreq = mem.offset
+ else:
+ _mem.txfreq = mem.freq
+
+ _mem.bandwidth = 1 if mem.mode == "FM" else 0
+
+ if mem.power:
+ _mem.txpower = POWER_LEVELS.index(mem.power)
+ else:
+ _mem.txpower = 0
+
+ _mem.name = mem.name.ljust(8, "\x00")[:8]
+
+ ((txmode, txval, txpol),
+ (rxmode, rxval, rxpol)) = \
+ chirp_common.split_tone_encode(mem)
+ _mem.txtone = _encode_tone(txmode, txval, txpol)
+ _mem.rxtone = _encode_tone(rxmode, rxval, rxpol)
+
+ def get_settings(self):
+ _s = self._memobj.settings
+
+ basic = RadioSettingGroup("basic", "Basic Settings")
+
+ rs = RadioSettingValueList(
+ ["Off", "On"], current_index=int(_s.busylock))
+ basic.append(MemSetting(
+ "settings.busylock", "Busy Lock", rs))
+
+ rs = RadioSettingValueList(
+ ["Off", "On"], current_index=int(_s.keytone))
+ basic.append(MemSetting(
+ "settings.keytone", "Key Tone", rs))
+
+ tot_val = int(_s.tot)
+ if tot_val >= len(TOT_OPTIONS):
+ tot_val = 0
+ rs = RadioSettingValueList(
+ TOT_OPTIONS, current_index=tot_val)
+ basic.append(MemSetting(
+ "settings.tot", "TX Timeout", rs))
+
+ rs = RadioSettingValueInteger(
+ 0, 9, int(_s.squelch))
+ basic.append(MemSetting(
+ "settings.squelch", "Squelch Level", rs))
+
+ return RadioSettings(basic)
+
+ def set_settings(self, settings):
+ settings.apply_to(self._memobj)
diff --git a/chirp/drivers/radioddity_gm30.py b/chirp/drivers/radioddity_gm30.py
index b08a241..99b8147 100644
--- a/chirp/drivers/radioddity_gm30.py
+++ b/chirp/drivers/radioddity_gm30.py
@@ -60,15 +60,16 @@ struct{
u8 tail_revert;
u8 tail_delay;
u8 tbst;
+ u8 unk_sett[6];
u8 unk_bits_5:6,
- a_ch_disp:1,
- b_ch_disp:1;
- u8 unk_sett[30];
+ b_ch_disp:1,
+ a_ch_disp:1;
+ u8 unk_sett_2[24];
u8 passw_w_ena;
u8 passw_r_ena;
u8 passw_w_val[8];
u8 passw_r_val[8];
- u8 unk_sett_2[5];
+ u8 unk_sett_3[5];
} settings;
struct{
u8 unusedsettings[32];
@@ -480,6 +481,10 @@ class RadioddityGM30(chirp_common.CloneModeRadio):
(lambda x: x in self.VALID_CHARSET,
str(_name)))
+ def get_raw_memory(self, number):
+ return repr(self._memobj.memory[number - 1]) + \
+ repr(self._memobj.memnames[number - 1])
+
def get_memory(self, number):
mem = chirp_common.Memory()
mem.number = number
@@ -949,3 +954,155 @@ class RadioddityGM30(chirp_common.CloneModeRadio):
except Exception:
LOG.debug(element.get_name())
raise
+
+
+@directory.register
+class BaofengGM15Pro(RadioddityGM30):
+ """Baofeng GM-15Pro"""
+ VENDOR = "Baofeng"
+ MODEL = "GM-15Pro"
+ _range = [(136000000, 174000000), (400000000, 512000000)]
+
+
+@directory.register
+class RadioddityMU5(RadioddityGM30):
+ """Radioddity MU-5 (MURS)
+
+ Identical to Radioddity GM-30 except for the following:
+
+ MURS channels 1-20 are fixed to the 5 MURS frequencies in a repeating
+ pattern. Frequency in EEPROM is ignored for 1-20. Channels 21-250 are
+ user-programmable RX-only channels. Changing power level is not allowed
+ on 1-20. It is possible to set power level on 21-250, but it is not used
+ (radio forces RX-only).
+ """
+ VENDOR = "Radioddity"
+ MODEL = "MU-5"
+
+ # MU-5 does not actually support variable power levels
+ # MURS channels are fixed to "Low" power which is presumably 2W
+ POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=2.00),
+ chirp_common.PowerLevel("High", watts=2.00)]
+
+ MURS_FREQS = [151820000, 151880000, 151940000, 154570000, 154600000]
+
+ def _get_murs_freq(self, channel):
+ return self.MURS_FREQS[(channel - 1) % 5]
+
+ def _is_murs_narrowband(self, channel):
+ return ((channel - 1) % 5) < 3
+
+ def get_memory(self, number):
+ mem = chirp_common.Memory()
+ mem.number = number
+ _mem = self._memobj.memory[number-1]
+ _name = self._memobj.memnames[number-1]["name"]
+ str_name = self.get_str_name(_name)
+ mem.name = str_name.rstrip()
+
+ # 1-20 always exist and may have 0xFFFFFFFF for freq
+ # other channels with 0xFFFFFFFF for freq are empty
+ if _mem.rx_freq.get_raw() == b'\xff\xff\xff\xff':
+ if not (1 <= number <= 20):
+ mem.empty = True
+ return mem
+
+ mem.freq = int(_mem.rx_freq) * 10
+
+ if _mem.tx_freq.get_raw() == b'\xff\xff\xff\xff':
+ mem.duplex = 'off'
+ elif int(_mem.tx_freq) - int(_mem.rx_freq) > 0:
+ mem.duplex = '+'
+ mem.offset = (int(_mem.tx_freq) - int(_mem.rx_freq)) * 10
+ elif int(_mem.tx_freq) - int(_mem.rx_freq) < 0:
+ mem.duplex = '-'
+ mem.offset = (int(_mem.rx_freq) - int(_mem.tx_freq)) * 10
+
+ mem.mode = self.val_or_def(_mem.mode, self.VALID_MODES)
+ mem.power = self.val_or_def(_mem.power, self.POWER_LEVELS)
+ mem.skip = "" if _mem.scan else "S"
+
+ # MURS channels 1-20: fixed freq, simplex, fixed power
+ if 1 <= mem.number <= 20:
+ mem.freq = self._get_murs_freq(mem.number)
+ mem.duplex = ""
+ mem.offset = 0
+ mem.immutable = ['freq', 'duplex', 'offset', 'power', 'empty']
+ # Narrowband channels have fixed mode
+ if self._is_murs_narrowband(mem.number):
+ mem.mode = "NFM"
+ mem.immutable = mem.immutable + ['mode']
+ # Channels 21-250: RX-only user channels
+ elif mem.number > 20:
+ mem.duplex = "off"
+ mem.immutable = ['duplex', 'offset']
+
+ txtone = self.get_tone(_mem.tx_tone)
+ rxtone = self.get_tone(_mem.rx_tone)
+ chirp_common.split_tone_decode(mem, txtone, rxtone)
+
+ mem.extra = RadioSettingGroup("Extra", "extra")
+
+ rs = RadioSettingValueBoolean(_mem.busy_lock)
+ rset = RadioSetting("busy_lock", "Busy Lock", rs)
+ mem.extra.append(rset)
+
+ rs = RadioSettingValueBoolean(_mem.freq_hop)
+ rset = RadioSetting("freq_hop", "Freq. Hop", rs)
+ mem.extra.append(rset)
+
+ _current = _mem.signal if _mem.signal else 1
+ rs = RadioSettingValueInteger(1, 15, current=_current)
+ rset = RadioSetting("signal", "DTMF ID", rs)
+ mem.extra.append(rset)
+
+ options = ['Off', 'BOT', 'EOT', 'BOTH']
+ rs = RadioSettingValueList(options, current_index=_mem.ptt_id)
+ rset = RadioSetting("ptt_id", "PTT ID", rs)
+ mem.extra.append(rset)
+
+ return mem
+
+ def validate_memory(self, mem):
+ if 1 <= mem.number <= 20:
+ expected_freq = self._get_murs_freq(mem.number)
+ if mem.freq != expected_freq:
+ return [chirp_common.ValidationError(
+ f'MURS Channel {mem.number} must be '
+ f'{expected_freq / 1000000:.3f} MHz')]
+ if self._is_murs_narrowband(mem.number) and mem.mode != "NFM":
+ return [chirp_common.ValidationError(
+ f'MURS Channel {mem.number} must be narrowband (NFM)')]
+ return chirp_common.CloneModeRadio.validate_memory(self, mem)
+
+ def set_memory(self, mem):
+ # For MURS channels 1-20, write 0xFFFFFFFF for rx/tx freq
+ # The radio firmware hardcodes the actual MURS frequency
+ # This is what the official CPS does
+ if 1 <= mem.number <= 20:
+ number = mem.number
+ _mem = self._memobj.memory[number-1]
+ _name = self._memobj.memnames[number-1]
+ newname = [str(c) for c in mem.name]
+ _name.name = "".join(newname).ljust(6, '\x00')
+
+ if mem.empty:
+ _mem.set_raw(b'\xff' * 13 + b'\x06\x11\x00')
+ return
+
+ _mem.rx_freq.fill_raw(b'\xff')
+ _mem.tx_freq.fill_raw(b'\xff')
+
+ _mem.mode = self.idx_or_def(mem.mode, self.VALID_MODES)
+ _mem.power = self.idx_or_def(mem.power, self.POWER_LEVELS)
+ _mem.scan = False if mem.skip == "S" else True
+
+ ((txmode, txval, txpol),
+ (rxmode, rxval, rxpol)) = chirp_common.split_tone_encode(mem)
+ self.set_tone(_mem.tx_tone, txmode, txval, txpol)
+ self.set_tone(_mem.rx_tone, rxmode, rxval, rxpol)
+
+ for setting in mem.extra:
+ setattr(_mem, setting.get_name(), setting.value)
+ else:
+ super().set_memory(mem)
diff --git a/chirp/drivers/radioddity_r2.py b/chirp/drivers/radioddity_r2.py
index 0554bae..1e19943 100644
--- a/chirp/drivers/radioddity_r2.py
+++ b/chirp/drivers/radioddity_r2.py
@@ -136,6 +136,8 @@ def _r2_enter_programming_mode(radio):
# check if we had EXITO
if exito is False:
+ if not ack:
+ raise errors.RadioNoResponse()
msg = "The radio did not accept program mode after five tries.\n"
msg += "Check your interface cable and power cycle your radio."
raise errors.RadioError(msg)
@@ -391,7 +393,9 @@ class RadioddityR2(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
do_upload(self)
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
LOG.exception('Unexpected error during upload')
@@ -663,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 8729954..d489158 100644
--- a/chirp/drivers/radtel_rt490.py
+++ b/chirp/drivers/radtel_rt490.py
@@ -288,6 +288,8 @@ def _enter_programming_mode(radio):
# check if we had EXITO
if exito is False:
+ if not ack:
+ 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)
@@ -479,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
new file mode 100644
index 0000000..91e78d9
--- /dev/null
+++ b/chirp/drivers/radtel_rt880g.py
@@ -0,0 +1,2309 @@
+# Copyright 2023 Jim Unroe <rock.unroe@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import struct
+import logging
+from enum import Enum
+
+from chirp import chirp_common, directory, memmap, checksum
+from chirp import bitwise, errors, util
+from chirp.settings import RadioSetting, RadioSettingGroup, \
+ RadioSettingValueInteger, RadioSettingValueList, \
+ RadioSettingValueBoolean, RadioSettingValueString, \
+ RadioSettingValueFloat, RadioSettings
+
+from chirp.drivers.iradio_common import enter_programming_mode, \
+ exit_programming_mode
+
+LOG = logging.getLogger(__name__)
+
+MEM_FORMAT = """
+#seekto 0x0000;
+struct {
+ u8 unknown_1[16]; // 0000-000f
+ u8 startup_image_enable; // 0010
+ u8 unknown_2[2]; // 0011-0012
+ u8 startup_ringtone_enable; // 0013
+ u8 welcome_message_enable; // 0014
+ ul16 welcome_text_color; // 0015-0016
+ ul16 welcome_start_line; // 0017-0018
+ ul16 welcome_start_column; // 0019-001a
+ u8 startup_password_enable; // 001b
+ char startup_password[16]; // 001c-002b
+ char welcome_message[32]; // 002c-004b
+ char name_callsign[16]; // 004c-005b
+ u8 voice_prompt; // 005c
+ u8 key_beep; // 005d
+ u8 unknown_3; // 005e
+ u8 lock_timer; // 005f
+ u8 key_led; // 0060
+ u8 brightness; // 0061
+ u8 lcd_timer; // 0062
+ u8 save_mode; // 0063
+ u8 save_start_timer; // 0064
+ u8 menu_exit; // 0065
+ u8 tx_priority; // 0066
+ u8 talkaround; // 0067
+ u8 alarm_type; // 0068
+ u8 auto_power_off; // 0069
+ ul32 auto_power_off_time; // 006a-006d
+ u8 auto_wake_up; // 006e
+ ul32 auto_wake_up_time; // 006f-0072
+ u8 multi_ptt; // 0073
+ u8 work_range; // 0074
+ u8 current_area; // 0075
+ u8 multi_standby; // 0076
+ u8 uv_repeater; // 0077
+ u8 freq_step; // 0078
+ u8 area_a_mode; // 0079
+ u8 area_a_show; // 007a
+ u8 area_a_zone; // 007b
+ ul16 area_a_channel; // 007c-007d
+ u8 area_b_mode; // 007e
+ u8 area_b_show; // 007f
+ u8 area_b_zone; // 0080
+ ul16 area_b_channel; // 0081-0082
+ u8 area_c_mode; // 0083
+ u8 area_c_show; // 0084
+ u8 area_c_zone; // 0085
+ ul16 area_c_channel; // 0086-0087
+ u8 lock_range_1_type; // 0088
+ ul16 lock_range_1_start; // 0089-008a
+ ul16 lock_range_1_end; // 008b-008c
+ u8 lock_range_2_type; // 008d
+ ul16 lock_range_2_start; // 008e-008f
+ ul16 lock_range_2_end; // 0090-0091
+ u8 lock_range_3_type; // 0092
+ ul16 lock_range_3_start; // 0093-0094
+ ul16 lock_range_3_end; // 0095-0096
+ u8 lock_range_4_type; // 0097
+ ul16 lock_range_4_start; // 0098-0099
+ ul16 lock_range_4_end; // 009a-009b
+ u8 scan_direction; // 009c
+ u8 scan_mode; // 009d
+ u8 scan_return; // 009e
+ u8 scan_dwell_timer; // 009f
+ u8 tx_voice_refresh; // 00a0
+ u8 rx_rssi_refresh; // 00a1
+ ul16 single_tone; // 00a2-00a3
+ u8 squelch_level; // 00a4
+ u8 tx_start_tone; // 00a5
+ u8 tx_end_tone; // 00a6
+ u8 vox; // 00a7
+ u8 vox_threshold; // 00a8
+ u8 vox_delay; // 00a9
+ u8 detect_range; // 00aa
+ u8 repeater_delay; // 00ab
+ u8 noaa_monitor; // 00ac
+ u8 mic_gain; // 00ad
+ u8 fm_spk_gain; // 00ae
+ u8 fm_dac_gain; // 00af
+ u8 am_spk_gain; // 00b0
+ u8 am_dac_gain; // 00b1
+ u8 glitch_threshold; // 00b2
+ u8 tt_rx_test; // 00b3
+ u8 tt_rssi_threshold; // 00b4
+ u8 tt_noise_threshold; // 00b5
+ u8 tt_power_test; // 00b6
+ u8 tt_power_136_174; // 00b7
+ u8 tt_power_400_480; // 00b8
+ u8 tt_power_18_64; // 00b9
+ u8 tt_power_64_136; // 00ba
+ u8 tt_power_173_240; // 00bb
+ u8 tt_power_240_320; // 00bc
+ u8 tt_power_320_400; // 00bd
+ u8 tt_power_480_560; // 00be
+ u8 tt_power_560_620; // 00bf
+ u8 tt_power_840_920; // 00c0
+ u8 tt_power_920_1000; // 00c1
+ u8 tt_power_1000_1080; // 00c2
+ u8 tt_power_1080_1160; // 00c3
+ u8 tt_power_1160_1240; // 00c4
+ u8 tt_power_1240_1300; // 00c5
+ u8 side_key_1_s; // 00c6
+ u8 side_key_1_l; // 00c7
+ u8 side_key_2_s; // 00c8
+ u8 side_key_2_l; // 00c9
+ u8 alarm_key_2_s; // 00ca
+ u8 alarm_key_2_l; // 00cb
+ u8 key_0_long; // 00cc
+ u8 key_1_long; // 00cd
+ u8 key_2_long; // 00ce
+ u8 key_3_long; // 00cf
+ u8 key_4_long; // 00d0
+ u8 key_5_long; // 00d1
+ u8 key_6_long; // 00d2
+ u8 key_7_long; // 00d3
+ u8 key_8_long; // 00d4
+ u8 key_9_long; // 00d5
+ u8 gps_enable; // 00d6
+ u8 gps_baud_rate; // 00d7
+ u8 gps_utc_zone; // 00d8
+ u8 unknown_4; // 00d9
+ u8 gps_auto_record; // 00da
+ u8 gps_auto_record_interval; // 00db
+ u8 unknown_5[40]; // 00dc-0103
+ u8 freq_input; // 0104
+ u8 fm_rx_standby; // 0105 * bool
+ u8 fm_channel; // 0106 * 1-128
+ u8 repeater_monitor; // 0107
+ u8 denoise; // 0108
+} settings;
+
+struct tone {
+ ul16 unknown:2,
+ is_dtcs:1,
+ // when is_dtcs is false, tone_or_inverted specifies if mode is tone
+ // when is_dtcs is true, tone_or_inverted specifies if dtcs is inverted
+ tone_or_inverted:1,
+ tone_val:12;
+};
+
+struct memory {
+ u8 rx_mode; // 00
+ u8 limit_rx_tx; // 01
+ u8 enabled; // 02
+ u8 isnarrow; // 03
+ struct tone rx_tone; // 04-05
+ ul32 rxfreq; // 06-0a
+ ul32 txfreq; // 0b-0e
+ struct tone tx_tone; // 0f-10
+ u8 power; // 11
+ u8 bcl; // 12
+ u8 dcs_encrypt:3, // 13
+ tot:5; //
+ u8 scan_remove:1, // 14
+ tail_tone:3, //
+ scrambler:4; //
+ ul32 mutecode; // 15-18
+ u8 unknown[8]; // 19-20
+ char name[16]; // 21-2f
+};
+
+struct dtmf_code {
+ char code[14]; // 00-0d
+ u8 unknown; // 0e
+ u8 code_length; // 0f
+};
+
+#seekto 0x200;
+struct {
+ u8 dtmf_delay; // 0200
+ u8 dtmf_interval; // 0201
+ u8 dtmf_duration; // 0202
+ u8 dtmf_mode; // 0203
+ u8 dtmf_select; // 0204
+ u8 dtmf_display; // 0205
+ u8 dtmf_tx_gain; // 0206
+ u8 dtmf_rx_threshold; // 0207
+ u8 dtmf_control; // 0208
+ u8 time_calibrate; // 0209
+ struct dtmf_code dtmf_codes[16]; // 020a
+ struct dtmf_code remote_stun; // 030a
+ struct dtmf_code remote_kill; // 031a
+ struct dtmf_code remote_wake; // 032a
+ struct dtmf_code remote_monitor; // 033a
+} dtmf;
+
+#seekto 0x34a;
+struct {
+ u8 reverse_channel; // 034a
+ u8 ctdcs_code_show; // 034b
+ u8 ch_alias_color; // 034c
+ u8 unknown[3]; // 034d-034f
+ u8 tx_unlimit; // 0350
+} settings2;
+
+#seekto 0x400;
+struct {
+ struct memory vfo_uv_a; // 0400
+ struct memory vfo_uv_b; // 0430
+ struct memory vfo_uv_c; // 0460
+ struct memory vfo_cb_a; // 0490
+ struct memory vfo_cb_b; // 04c0
+ struct memory vfo_cb_c; // 04f0
+ struct memory vfo_850_a; // 0520
+ struct memory vfo_850_b; // 0550
+ struct memory vfo_850_c; // 0580
+} vfo;
+
+#seekto 0xc00;
+struct {
+ u8 gps_coord_type; // 0c00
+ u8 gps_speed_unit; // 0c01
+ u8 gps_distance_unit; // 0c02
+ u8 gps_altitude_unit; // 0c03
+ char gps_fixed_lat[7]; // 0c04-0c0a
+ u8 unknown_1[3]; // 0c0b-0c0d
+ char gps_fixed_lat_dir; // 0c0e
+ char gps_fixed_long[8]; // 0c0f-0c16
+ u8 unknown_2[3]; // 0c17-0c19
+ char gps_fixed_long_dir; // 0c1a
+ char gps_fixed_altitude[7]; // 0c1b-0c21
+ u8 unknown_3[4]; // 0c22-0c25
+ u8 gps_mileage_type; // 0c26
+} gps;
+
+#seekto 0xc20;
+struct {
+ u8 unknown_1[7]; // 0c20-0c26
+ u8 aprs_station_mode; // 0c27
+ u8 aprs_rx_ch; // 0c28
+ u8 aprs_tx_ch; // 0c29
+ u8 aprs_ptt_priority; // 0c2a
+ u8 aprs_ptt_delay; // 0c2b
+ u8 aprs_beacon_popup; // 0c2c
+ u8 unknown_2[3]; // 0c2d-0c2f
+ char aprs_callsign[6]; // 0c30-0c35
+ u8 aprs_ssid; // 0c36
+ u8 aprs_symbol_table; // 0c37
+ u8 aprs_symbol; // 0c38
+ char aprs_comment[128]; // 0c39-0cb8
+ u8 aprs_mice_enable; // 0cb9
+ u8 aprs_mice_mode; // 0cba
+ char aprs_path_1[6]; // 0cbb-0cc0
+ u8 aprs_path_1_count; // 0cc1
+ char aprs_path_2[6]; // 0cc2-0cc7
+ u8 aprs_path_2_count; // 0cc8
+ u8 aprs_tx_voltage; // 0cc9
+ u8 unknown_3[2]; // 0cca-0ccb
+ u8 aprs_tx_star; // 0ccc
+ u8 aprs_tx_mileage; // 0ccd
+ u8 aprs_beacon_ptt_after; // 0cce
+ u8 aprs_smart_beacon; // 0ccf
+ u8 aprs_beacon_time_mode; // 0cd0
+ ul32 aprs_beacon_time; // 0cd1-0cd4
+ u8 aprs_queue_beacon; // 0cd5
+ u8 aprs_queue_interval; // 0cd6
+ u8 aprs_digi_rep_ch; // 0cd7
+ u8 aprs_digi_1_enable; // 0cd8
+ char aprs_digi_1_name[6]; // 0cd9-0cde
+ u8 aprs_digi_2_enable; // 0cdf
+ char aprs_digi_2_name[6]; // 0ce0-0ce5
+ u8 aprs_digi_wait_before_rep; // 0ce6
+ char aprs_digi_remote_password[6]; // 0ce7-0cec
+ u8 aprs_enable; // 0ced
+ u8 unknown_4[2]; // 0cee-0cef
+ u8 aprs_demod_tone; // 0cf0
+ u8 aprs_tx_level; // 0cf1
+ u8 aprs_rx_level; // 0cf2
+ u8 aprs_beacon_save; // 0cf3
+ u8 aprs_beacon_ptt_after_ch; // 0cf4
+ u8 aprs_rx_ch_mute; // 0cf5
+ u8 unknown_5[10]; // 0cf6-0cff
+} aprs;
+
+#seekto 0x2000;
+struct memory channels[1024];
+
+struct zone {
+ u8 channel_count1; // 0000
+ u8 channel_count2; // 0001
+ u8 unknown1[2]; // 0002-0003
+ char name[16]; // 0004-0013
+ ul16 channels[200]; // 0014-01a3
+ u8 unknown2[92]; // 01a4-01ff
+};
+
+#seekto 0x1a000;
+struct zone zones[256];
+
+struct fm_memory {
+ // 64-108 MHz, 2.0-30.0 MHz, 520-1710 KHz, 153-279 KHz
+ u8 range; // 00 *
+ // FM, AM, LSB, USB, CW
+ u8 demodulation; // 01 *
+ // 1 K, 5 K, 10 K, 50 K, 100 K, 500 K, 1 M, 9 K
+ u8 step; // 02 *
+ // 0.5 K, 1.0 K, 1.2 K, 2.2 K, 3.0 K, 4.0 K
+ u8 bandwidth; // 03 *
+ // AGC, 0, -1, -2, ..., -37
+ u8 attenuation; // 04 *
+ // x-32768?
+ ul16 bfo; // 05-06 *
+ ul16 frequency; // 07-08 *
+ // bool
+ u8 enabled; // 09 *
+ u8 unknown[6]; // 0a-0f
+ char name[16]; // 10-1f *
+};
+
+#seekto 0xd4000;
+struct fm_memory fm_channels[128]; // *
+"""
+
+CMD_ACK = b"\x06"
+
+DTCS_CODES = tuple(sorted(chirp_common.DTCS_CODES + (645,)))
+
+LIST_ALARMTYPE = ["Local Alarm", "Remote Alarm", "Local + Remote"]
+LIST_APRSBEACONAFTER = ["Off", "Area Match", "All Area"]
+LIST_APRSBEACONSAVE = ["Not Stored", "FCS Check OK", "Stored All"]
+LIST_APRSCHANNEL = ["Off", "CH-A", "CH-B", "CH-C"]
+LIST_APRSCHANNELCOMBOS = ["CH-A", "CH-B", "CH-C", "CH-A + CH-B", "CH-A + CH-C",
+ "CH-B + CH-C", "CH-A + CH-B + CH-C"]
+LIST_APRSLEVEL = ["-10.5dB", "-9.0dB", "-7.5dB", "-6.0dB",
+ "-4.5dB", "-3.0dB", "-1.5dB", "0dB"]
+LIST_APRESMICEMODE = ["M0: Off Duty", "M1: En Route", "M2: In Service",
+ "M3: Returning", "M4: Committed", "M5: Special",
+ "M6: Priority", "Emergency"]
+LIST_APRSPTTDELAY = LIST_DELAY = ["%s ms" % x for x in range(200, 650, 50)]
+LIST_APRSPTTPRIORITY = ["Call", "APRS"]
+LIST_APRSSMARTBEACON = ["Off", "Type 1", "Type 2", "Type 3"]
+LIST_APRSSTATIONMODE = ["Fixed", "GPS"]
+LIST_APRSSYMBOLS = chirp_common.APRS_SYMBOLS + \
+ ("| TNC Stream Sw", "}", "~ TNC Stream Sw")
+LIST_APRSSYMBOLTABLE = ["/", "\\"]
+LIST_AREA = ["A", "B", "C"]
+LIST_AREAMODE = ["Frequency", "Channel", "Zone"]
+LIST_AREASHOW = ["Channel Number", "Frequency"]
+LIST_BCL = ["Off", "Carrier Match", "CTC/DCS Match"]
+LIST_BRIGHTNESS = ["%s" % x for x in range(0, 5, 1)]
+LIST_COLOR = ["Blue", "Green", "Red", "Yellow", "White",
+ "Fuchsia", "Pink", "Orange", "Tomato", "Cyan", "Golden"]
+LIST_DCSENCRYPT = ["Standard", "Encrypt 1",
+ "Encrypt 2", "Encrypt 3", "Mute Code"]
+LIST_DELAY = ["%s ms" % x for x in range(0, 2100, 100)]
+LIST_DENOISE = ["Off", "On", "840-1000MHz"]
+LIST_DETECTRANGE = ["18-64 MHz", "64-136 MHz", "136-174 MHz", "174-240 MHz",
+ "240-320 MHz", "320-400 MHz", "400-480 MHz", "480-560 MHz",
+ "560-620 MHz", "840-920 MHz", "920-1000 MHz"]
+LIST_DIRECTION = ["Up", "Down"]
+LIST_DTMFMODE = ["Off", "TX Start", "TX End"]
+LIST_DTMFSELECT = ["DTMF-%s" % x for x in range(1, 17)]
+LIST_FREQINPUT = ["6 digit", "8 digit"]
+LIST_FREQSTEP = ["0.25K", "1.25K", "2.5K", "5K", "6.25K", "10K", "12.5K",
+ "20K", "25K", "50K", "100K", "500K", "1M", "5M"]
+LIST_GPSALT = ["m", "foot"]
+LIST_GPSBAUD = ["4800", "9600", "14400", "19200", "38400",
+ "56000", "57600", "115200", "128000", "256000"]
+LIST_GPSCOORD = ["degree", "degree.min", "degree.min.sec"]
+LIST_GPSDIST = ["km", "n mile", "mile"]
+LIST_GPSLATDIR = ["N", "S"]
+LIST_GPSLONGDIR = ["E", "W"]
+LIST_GPSMILEAGE = ["Startup Zero", "Keep"]
+LIST_GPSSPEED = ["km/h", "knot", "mph"]
+LIST_GPSUTC = ["UTC 0", "UTC+1", "UTC+2", "UTC+3",
+ "UTC+3.5", "UTC+4", "UTC+5", "UTC+5.5"] + \
+ ["UTC+%s" % x for x in range(6, 13, 1)] + \
+ ["UTC-%s" % x for x in range(1, 13, 1)]
+LIST_INTERVAL = ["%s ms" % x for x in range(30, 210, 10)]
+LIST_KEYDEFINE = ["None", "Monitor", "Power Switch", "Scanning", "VOX",
+ "Squelch", "Frequency Step", "Multi Standby", "Tx Priority",
+ "Roger Beep", "FM Radio", "Talkaround", "Alarm",
+ "Send Single Tone", "Frequency Detect", "CTC/DCS Scan",
+ "Spectrum", "Radio Sleep", "Query Status", "Save Channel",
+ "Rx Demodulation", "NOAA Channels", "LCD On-Off",
+ "LCD Brightness", "Key LED On-Off", "U/V Repeater", "GPS",
+ "GPS Manual REC", "GPS Track Query", "APRS Beacon REC",
+ "Zone Selection", "Work Range"]
+LIST_LIMITRXTX = ["Rx+Tx", "Only Rx", "Only Tx"]
+LIST_LOCK = ["Unlock", "Rx Only", "Lock"]
+LIST_SAVEMODE = ["Off", "1:1", "1:2", "1:3"]
+LIST_SCANMODE = ["CO", "TO", "SE"]
+LIST_SCANRETURN = ["Original Channel", "Current Channel"]
+LIST_SCANTIMER = ["Off"] + ["%s seconds" % x for x in range(1, 31, 1)]
+LIST_SCRAMBLER = ["Off"] + ["%s" % x for x in range(1, 9, 1)]
+LIST_TAILTONE = ["Off", "55Hz No Shift",
+ "120° Shift", "180° Shift", "240° Shift", ]
+LIST_TALKAROUND = ["Off", "Talkaround", "Invert Frequency"]
+LIST_TIMER = ["Off", "5 seconds", "10 seconds"] + [
+ "%s seconds" % x for x in range(15, 615, 15)]
+LIST_TXENDTONE = ["Off", "Roger Beep 1",
+ "Roger Beep 2", "Send Radio Name", "Send GPS"]
+LIST_TXPRI = ["Edit", "Busy"]
+LIST_WORKRANGE = ["64-620MHz", "18-64MHz", "840-1000MHz"]
+
+VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
+ "`{|}!\"#$%&'()*+,-./:;<=>?@[]^_"
+DTMF_CHARS = list("0123456789ABCD*#")
+HEX_CHARS = "0123456789ABCDEF"
+
+
+class MemoryRegions(Enum):
+ """
+ Defines the logical memory regions for this radio model.
+ """
+ settingData = 0
+ channelData = 1
+ zoneData = 2
+ fmData = 3
+
+
+MEMORY_REGIONS_RANGES = {
+ # (Start addr, length in blocks, region id)
+ MemoryRegions.settingData: (0x0000, 4, 0x90),
+ MemoryRegions.channelData: (0x2000, 48, 0x91),
+ MemoryRegions.zoneData: (0x1a000, 128, 0x92),
+ MemoryRegions.fmData: (0xd4000, 4, 0x99),
+}
+
+
+def _read_block(radio, block_addr, block_size):
+ serial = radio.pipe
+
+ cmd = struct.pack(">BH", ord(b'R'), block_addr)
+ ccs = bytes([checksum.checksum_8bit(cmd)])
+
+ expectedresponse = b"R" + cmd[1:]
+
+ cmd = cmd + ccs
+
+ LOG.debug("Reading block %04x..." % block_addr)
+
+ try:
+ serial.write(cmd)
+ response = serial.read(3 + block_size + 1)
+
+ cs = checksum.checksum_8bit(response[:-1])
+
+ if response[:3] != expectedresponse:
+ raise Exception("Error reading block %04x." % block_addr)
+
+ chunk = response[3:]
+
+ if chunk[-1] != cs:
+ raise Exception("Block failed checksum!")
+
+ block_data = chunk[:-1]
+ except Exception:
+ raise errors.RadioError("Failed to read block at %04x" % block_addr)
+
+ return block_data
+
+
+def _write_block(radio, block_number, block_size, region, data):
+ serial = radio.pipe
+
+ # map the upload address to the mmap start and end addresses
+ start_addr = block_number * block_size
+ end_addr = start_addr + block_size
+
+ block_data = data[start_addr:end_addr]
+
+ cmd = struct.pack(">BH", region, block_number)
+
+ cs = bytes([checksum.checksum_8bit(cmd + block_data)])
+ block_data += cs
+
+ LOG.debug("Writing Data:")
+ LOG.debug(util.hexprint(cmd + block_data))
+
+ try:
+ serial.write(cmd + block_data)
+ if serial.read(1) != CMD_ACK:
+ raise Exception("No ACK")
+ except Exception:
+ raise errors.RadioError("Failed to send block "
+ "to radio at %04x" % block_number)
+
+
+def do_download(radio):
+ LOG.debug("download")
+
+ data = b""
+
+ status = chirp_common.Status()
+ status.msg = "Cloning from radio"
+
+ status.cur = 0
+ status.max = radio.END_ADDR
+
+ for addr in range(radio.START_ADDR, radio.END_ADDR, 1):
+ status.cur = addr
+ radio.status_fn(status)
+
+ block = _read_block(radio, addr + radio.READ_OFFSET, radio.BLOCK_SIZE)
+ data += block
+
+ LOG.debug("Address: %04x" % addr)
+ LOG.debug(util.hexprint(block))
+
+ return memmap.MemoryMapBytes(data)
+
+
+def do_upload(radio):
+ status = chirp_common.Status()
+ status.msg = "Uploading to radio"
+
+ status.cur = 0
+ status.max = get_total_upload_blocks()
+
+ # The OEM software reads the 1st block from the radio before commencing
+ # with the upload. That behavior will be mirrored here.
+ _read_block(radio, radio.START_ADDR, radio.BLOCK_SIZE)
+
+ data_bytes = radio.get_mmap()
+
+ for item in MemoryRegions:
+ _, length, regionId = MEMORY_REGIONS_RANGES[item]
+ item_bytes = get_bytes_for_region(data_bytes, item, radio.BLOCK_SIZE)
+
+ for block in range(0, length):
+ status.cur += 1
+ radio.status_fn(status)
+ _write_block(radio, block, radio.BLOCK_SIZE, regionId, item_bytes)
+
+
+def get_bytes_for_region(all_bytes: bytearray, item, blockSize):
+ start, length, _ = MEMORY_REGIONS_RANGES[item]
+ return all_bytes[start:start+(length*blockSize)]
+
+
+def get_total_upload_blocks():
+ return sum(length for _, length, _ in MEMORY_REGIONS_RANGES.values())
+
+
+class RT880GBank(chirp_common.NamedBank):
+
+ def get_name(self):
+ _bank = self._model._radio._memobj.zones[self.index]
+ return str(_bank.name).rstrip().replace("\xFF", "")
+
+ def set_name(self, name):
+ _bank = self._model._radio._memobj.zones[self.index]
+ _bank.name = str(name)[:16].rstrip().ljust(16, '\xFF')
+
+
+class RT880GBankModel(chirp_common.BankModel):
+
+ def get_num_mappings(self):
+ return len(self.get_mappings())
+
+ def get_mappings(self):
+ banks = self._radio._memobj.zones
+ bank_mappings = []
+ for index, _bank in enumerate(banks):
+ bank = RT880GBank(self, "%i" % index, "b%i" % (index + 1))
+ bank.index = index
+ bank_mappings.append(bank)
+
+ return bank_mappings
+
+ def _get_channel_numbers_in_bank(self, bank):
+ _bank_used = self._radio._memobj.zones[bank.index].channel_count1 > 0
+ if not _bank_used:
+ return set()
+
+ _members = self._radio._memobj.zones[bank.index].channels
+ return set([int(ch) + 1 for ch in _members if ch != 0xFFFF])
+
+ def _update_bank_with_channel_numbers(self, bank, channels_in_bank):
+ _zone = self._radio._memobj.zones[bank.index]
+ if len(channels_in_bank) > len(_zone.channels):
+ raise Exception("Too many entries in bank %d" % bank.index)
+
+ _channel_count = len(channels_in_bank)
+ _zone.channel_count1 = _channel_count
+ _zone.channel_count2 = _channel_count
+
+ for index, item in enumerate(channels_in_bank):
+ _zone.channels[index] = item - 1
+
+ for index in range(_channel_count, len(_zone.channels)):
+ _zone.channels[index] = 0xFFFF
+
+ def add_memory_to_mapping(self, memory, bank):
+ channels_in_bank = self._get_channel_numbers_in_bank(bank)
+ channels_in_bank.add(memory.number)
+ self._update_bank_with_channel_numbers(bank, channels_in_bank)
+
+ def remove_memory_from_mapping(self, memory, bank):
+ channels_in_bank = self._get_channel_numbers_in_bank(bank)
+ try:
+ channels_in_bank.remove(memory.number)
+ except KeyError:
+ raise Exception("Memory %i is not in bank %s. Cannot remove" %
+ (memory.number, bank))
+ self._update_bank_with_channel_numbers(bank, channels_in_bank)
+
+ def get_mapping_memories(self, bank):
+ memories = []
+ for channel in self._get_channel_numbers_in_bank(bank):
+ memories.append(self._radio.get_memory(channel))
+
+ return memories
+
+ def get_memory_mappings(self, memory):
+ banks = []
+ for bank in self.get_mappings():
+ if memory.number in self._get_channel_numbers_in_bank(bank):
+ banks.append(bank)
+
+ return banks
+
+
+@directory.register
+class RT880G(chirp_common.CloneModeRadio):
+ """Radtel RT-880G"""
+ VENDOR = "Radtel"
+ MODEL = "RT-880G"
+ NAME_LENGTH = 16
+ BAUD_RATE = 115200
+
+ _channelCount = 1024
+
+ _airband = (108000000, 135999999)
+ _work_range_1 = (64000000, 620000000)
+ _work_range_2 = (18000000, 64000000)
+ _work_range_3 = (840000000, 1000000000)
+
+ SPECIALS = {
+ "VFO UV-A": (_channelCount + 1, _work_range_1),
+ "VFO UV-B": (_channelCount + 2, _work_range_1),
+ "VFO UV-C": (_channelCount + 3, _work_range_1),
+ "VFO CB-A": (_channelCount + 4, _work_range_2),
+ "VFO CB-B": (_channelCount + 5, _work_range_2),
+ "VFO CB-C": (_channelCount + 6, _work_range_2),
+ "VFO 850-A": (_channelCount + 7, _work_range_3),
+ "VFO 850-B": (_channelCount + 8, _work_range_3),
+ "VFO 850-C": (_channelCount + 9, _work_range_3),
+ }
+
+ BLOCK_SIZE = 0x400
+ magic_enter = b"4R" + b"\x05\x10\x9b"
+ magic_exit = b"4R" + b"\x05\xEE\x79"
+
+ POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1),
+ chirp_common.PowerLevel("Medium", watts=5),
+ chirp_common.PowerLevel("High", watts=10)]
+
+ # Radio's write address starts at 0x0000
+ # Radio's write address ends at 0x0140
+ START_ADDR = 0
+ END_ADDR = 0x035b
+ # Radio's read address starts at 0x7820
+ # Radio's read address ends at 0x795F
+ READ_OFFSET = 0x0008
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_settings = True
+ rf.has_bank = True
+ rf.has_bank_names = True
+ rf.has_ctone = True
+ rf.has_cross = True
+ rf.has_rx_dtcs = True
+ rf.has_tuning_step = False
+ rf.can_odd_split = True
+ rf.has_name = True
+ rf.valid_name_length = self.NAME_LENGTH
+ rf.valid_characters = chirp_common.CHARSET_ASCII
+ rf.valid_skips = ["", "S"]
+ rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
+ rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
+ "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
+ rf.valid_power_levels = self.POWER_LEVELS
+ rf.valid_duplexes = ["", "-", "+", "split"]
+ # SSB is included as USB here since SSB isn't in the master list
+ # of chirp modes
+ rf.valid_modes = ["FM", "NFM", "AM", "USB"]
+ rf.valid_dtcs_codes = DTCS_CODES
+ rf.memory_bounds = (1, self._channelCount)
+ rf.has_nostep_tuning = True
+ rf.valid_bands = [self._work_range_2, self._work_range_1,
+ self._work_range_3]
+ rf.valid_special_chans = list(self.SPECIALS.keys())
+
+ return rf
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+
+ def sync_in(self):
+ """Download from radio"""
+ try:
+ enter_programming_mode(self.pipe, self.magic_enter)
+ data = do_download(self)
+ except errors.RadioError:
+ # Pass through any real errors we raise
+ raise
+ except Exception:
+ # If anything unexpected happens, make sure we raise
+ # a RadioError and log the problem
+ LOG.exception('Unexpected error during download')
+ raise errors.RadioError('Unexpected error communicating '
+ 'with the radio')
+ finally:
+ exit_programming_mode(self.pipe, self.magic_exit)
+
+ self._mmap = data
+ self.process_mmap()
+
+ def sync_out(self):
+ """Upload to radio"""
+ try:
+ enter_programming_mode(self.pipe, self.magic_enter)
+ self.pipe.timeout = 1
+ do_upload(self)
+ except errors.RadioError:
+ raise
+ except Exception:
+ # If anything unexpected happens, make sure we raise
+ # a RadioError and log the problem
+ LOG.exception('Unexpected error during upload')
+ raise errors.RadioError('Unexpected error communicating '
+ 'with the radio')
+ finally:
+ self.pipe.timeout = 0.25
+ exit_programming_mode(self.pipe, self.magic_exit)
+
+ def get_raw_memory(self, number):
+ return repr(self._memobj.memory[number - 1])
+
+ def get_bank_model(self):
+ return RT880GBankModel(self)
+
+ @staticmethod
+ def _decode_tone(tone: bitwise.structDataElement):
+ if not tone.is_dtcs and not tone.tone_or_inverted:
+ return '', None, None
+ elif tone.is_dtcs and tone.tone_or_inverted:
+ code = int('%o' % tone.tone_val)
+ return 'DTCS', code, 'R'
+ elif tone.is_dtcs and not tone.tone_or_inverted:
+ code = int('%o' % tone.tone_val)
+ return 'DTCS', code, 'N'
+ elif not tone.is_dtcs and tone.tone_or_inverted:
+ return 'Tone', (tone.tone_val / 10.0), None
+ else:
+ raise errors.RadioError('Unsupported tone value')
+
+ @staticmethod
+ def _encode_tone(mode, val, pol):
+ if not mode:
+ return 0, 0, 0
+ elif mode == 'Tone':
+ code = int(val * 10)
+ return 0, 1, code
+ elif mode == 'DTCS':
+ code = int('%i' % val, 8)
+ inverted = 0
+ if pol == 'R':
+ inverted = 1
+ return 1, inverted, code
+ else:
+ raise errors.RadioError('Unsupported tone mode %r' % mode)
+
+ def _get_memobjs(self, number):
+ if isinstance(number, str):
+ return getattr(
+ self._memobj.vfo,
+ number.lower().replace(" ", "_").replace("-", "_"))
+ elif number > self._channelCount:
+ for k, v in list(self.SPECIALS.items()):
+ ch_num, _ = v
+ if number == ch_num:
+ return getattr(
+ self._memobj.vfo,
+ k.lower().replace(" ", "_").replace("-", "_"))
+ else:
+ return self._memobj.channels[number - 1]
+
+ def get_memory(self, number):
+ _mem = self._get_memobjs(number)
+ mem = chirp_common.Memory()
+ if isinstance(number, str):
+ ch_num, _ = self.SPECIALS[number]
+ mem.number = ch_num
+ mem.extd_number = number
+ else:
+ mem.number = number
+
+ mem.freq = int(_mem.rxfreq) * 10
+
+ # We'll consider any blank (i.e. 0 MHz frequency) to be empty
+ if mem.freq == 0:
+ mem.empty = True
+ return mem
+
+ if _mem.rxfreq.get_raw() == b"\xFF\xFF\xFF\xFF":
+ mem.freq = 0
+ mem.empty = True
+ return mem
+
+ # Freq and offset
+ mem.freq = int(_mem.rxfreq) * 10
+ # TX freq set
+ offset = (int(_mem.txfreq) * 10) - mem.freq
+ if offset != 0:
+ if chirp_common.is_split(self.get_features().valid_bands,
+ mem.freq, int(_mem.txfreq) * 10):
+ mem.duplex = "split"
+ mem.offset = int(_mem.txfreq) * 10
+ elif offset < 0:
+ mem.offset = abs(offset)
+ mem.duplex = "-"
+ elif offset > 0:
+ mem.offset = offset
+ mem.duplex = "+"
+ else:
+ mem.offset = 0
+
+ mem.name = str(_mem.name).rstrip(" ").replace("\xFF", "")
+
+ mem.mode = _mem.isnarrow and "NFM" or "FM"
+
+ chirp_common.split_tone_decode(mem,
+ self._decode_tone(_mem.tx_tone),
+ self._decode_tone(_mem.rx_tone))
+
+ # mode
+ if _mem.rx_mode == 0x02:
+ mem.mode = "USB"
+ elif _mem.rx_mode == 0x01:
+ mem.mode = "AM"
+ elif _mem.rx_mode == 0x00 and _mem.isnarrow == 0x01:
+ mem.mode = "NFM"
+ else:
+ mem.mode = "FM"
+
+ # power
+ if _mem.power == 0x02:
+ mem.power = self.POWER_LEVELS[2]
+ elif _mem.power == 0x01:
+ mem.power = self.POWER_LEVELS[1]
+ else:
+ mem.power = self.POWER_LEVELS[0]
+
+ if _mem.scan_remove:
+ mem.skip = "S"
+
+ mem.extra = RadioSettingGroup("Extra", "extra")
+
+ rs = RadioSettingValueList(
+ LIST_DCSENCRYPT, current_index=_mem.dcs_encrypt)
+ rset = RadioSetting("dcs_encrypt", "DCS Encrypt", rs)
+ mem.extra.append(rset)
+
+ rs = RadioSettingValueString(
+ 0, 8, f"{_mem.mutecode.get_value():x}".upper(), False, HEX_CHARS)
+ rset = RadioSetting("mutecode", "Mute Code", rs)
+ mem.extra.append(rset)
+
+ rs = RadioSettingValueList(
+ LIST_TAILTONE, current_index=_mem.tail_tone)
+ rset = RadioSetting("tail_tone", "Tail Tone", rs)
+ mem.extra.append(rset)
+
+ rs = RadioSettingValueList(
+ LIST_SCRAMBLER, current_index=_mem.scrambler)
+ rset = RadioSetting("scrambler", "Scrambler", rs)
+ mem.extra.append(rset)
+
+ rs = RadioSettingValueList(
+ LIST_BCL, current_index=_mem.bcl if _mem.bcl <= 2 else 0)
+ rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
+ mem.extra.append(rset)
+
+ rs = RadioSettingValueList(
+ LIST_LIMITRXTX, current_index=_mem.limit_rx_tx)
+ rset = RadioSetting("limit_rx_tx", "Limit Rx/Tx", rs)
+ mem.extra.append(rset)
+
+ rs = RadioSettingValueList(
+ LIST_TIMER, current_index=_mem.tot)
+ rset = RadioSetting("tot", "Time Out Timer", rs)
+ mem.extra.append(rset)
+
+ return mem
+
+ def set_memory(self, mem):
+ LOG.debug("Setting %i(%s)" % (mem.number, mem.extd_number))
+ _mem = self._get_memobjs(mem.number)
+
+ # if empty memory
+ if mem.empty:
+ _mem.set_raw("\xFF" * 48)
+ return
+
+ _mem.set_raw("\x00" * 32 + "\x20" * 16)
+
+ _mem.enabled = 0x01
+
+ _mem.rxfreq = mem.freq / 10
+
+ if 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
+
+ _mem.name = mem.name.rstrip(' ').ljust(self.NAME_LENGTH, '\xFF')
+
+ _mem.scan_remove = mem.skip == "S"
+
+ # mode
+ if str(mem.mode) == "NFM":
+ _mem.rx_mode = 0x00
+ _mem.isnarrow = 0x01
+ elif str(mem.mode) == "AM":
+ _mem.rx_mode = 0x01
+ _mem.isnarrow = 0x00
+ elif str(mem.mode) == "USB":
+ _mem.rx_mode = 0x02
+ _mem.isnarrow = 0x00
+ else: # FM
+ _mem.rx_mode = 0x00
+ _mem.isnarrow = 0x00
+
+ # power
+ if str(mem.power) == str(self.POWER_LEVELS[2]):
+ _mem.power = 0x02
+ elif str(mem.power) == str(self.POWER_LEVELS[1]):
+ _mem.power = 0x01
+ else:
+ _mem.power = 0x00
+
+ # tones
+ txtone, rxtone = chirp_common.split_tone_encode(mem)
+
+ is_dtcs, tone_or_inverted, tone_val = self._encode_tone(*txtone)
+ _mem.tx_tone.is_dtcs = is_dtcs
+ _mem.tx_tone.tone_or_inverted = tone_or_inverted
+ _mem.tx_tone.tone_val = tone_val
+
+ is_dtcs, tone_or_inverted, tone_val = self._encode_tone(*rxtone)
+ _mem.rx_tone.is_dtcs = is_dtcs
+ _mem.rx_tone.tone_or_inverted = tone_or_inverted
+ _mem.rx_tone.tone_val = tone_val
+
+ # extras
+ for setting in mem.extra:
+ if setting.get_name() == "mutecode":
+ setattr(_mem, setting.get_name(), int(str(setting.value), 16))
+ else:
+ setattr(_mem, setting.get_name(), setting.value)
+
+ def validate_memory(self, mem):
+ msgs = []
+
+ # airband should always be AM
+ if (chirp_common.in_range(mem.freq, [self._airband])
+ and mem.mode != 'AM'):
+ msgs.append(chirp_common.ValidationWarning(
+ 'Frequency in this range requires AM mode'))
+
+ # adjust VFO channels to their appropriate work range
+ if mem.number > self._channelCount:
+ _, work_range = self.SPECIALS[mem.extd_number]
+
+ if not chirp_common.in_range(mem.freq, [work_range]):
+ msgs.append(chirp_common.ValidationError(
+ 'Frequency out of valid range'))
+
+ return msgs + super().validate_memory(mem)
+
+ def apply_string(self, setting, obj):
+ """
+ Callback for set_apply_callback to pad with 0xFF instead of spaces
+ """
+ length = len(str(setting.value))
+ setattr(obj, setting.get_name().rsplit('.', 1)[-1],
+ str(setting.value).rstrip(' ').ljust(length, '\xFF'))
+
+ def get_settings(self):
+ basic = RadioSettingGroup("basic", "Basic Settings")
+ startup = RadioSettingGroup("startup", "Startup Settings")
+ keydefine = RadioSettingGroup("keydefine", "Key Define Settings")
+ analog = RadioSettingGroup("analog", "Analog Settings")
+ dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
+ gps = RadioSettingGroup("gps", "GPS Settings")
+ aprs = RadioSettingGroup("aprs", "APRS Settings")
+ time = RadioSettingGroup("time", "Time Settings")
+ top = RadioSettings(basic, startup, keydefine, analog,
+ dtmf, gps, aprs, time)
+ try:
+ self.get_basic_settings(basic)
+ self.get_startup_settings(startup)
+ self.get_keydefine_settings(keydefine)
+ self.get_analog_settings(analog)
+ self.get_dtmf_settings(dtmf)
+ self.get_gps_settings(gps)
+ self.get_aprs_settings(aprs)
+ self.get_time_settings(time)
+ except Exception as e:
+ LOG.exception("Error getting settings: %s", e)
+ return top
+
+ def get_basic_settings(self, group):
+ _settings = self._memobj.settings
+ _settings2 = self._memobj.settings2
+
+ # Name/Callsign
+ _codeobj = _settings.name_callsign
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 16, _code, True)
+ rset = RadioSetting("name_callsign", "Name/Callsign", rs)
+ rset.set_apply_callback(self.apply_string, _settings)
+ group.append(rset)
+
+ # Voice Prompt
+ rs = RadioSettingValueBoolean(_settings.voice_prompt)
+ rset = RadioSetting("voice_prompt", "Voice Prompt", rs)
+ group.append(rset)
+
+ # Key Beep
+ rs = RadioSettingValueBoolean(_settings.key_beep)
+ rset = RadioSetting("key_beep", "Key Beep", rs)
+ group.append(rset)
+
+ # Key Lock Timer
+ rs = RadioSettingValueList(
+ LIST_TIMER, current_index=_settings.lock_timer)
+ rset = RadioSetting("lock_timer", "Key Lock Timer", rs)
+ group.append(rset)
+
+ # Key LED
+ rs = RadioSettingValueBoolean(_settings.key_led)
+ rset = RadioSetting("key_led", "Key LED", rs)
+ group.append(rset)
+
+ # Display Timer
+ rs = RadioSettingValueList(
+ LIST_TIMER, current_index=_settings.lcd_timer)
+ rset = RadioSetting("lcd_timer", "Display Timer", rs)
+ group.append(rset)
+
+ # LCD Brightness
+ rs = RadioSettingValueList(
+ LIST_BRIGHTNESS, current_index=_settings.brightness)
+ rset = RadioSetting("brightness", "LCD Brightness", rs)
+ group.append(rset)
+
+ # Menu Exit Timer
+ rs = RadioSettingValueList(
+ LIST_TIMER, current_index=_settings.menu_exit)
+ rset = RadioSetting("menu_exit", "Menu Exit Timer", rs)
+ group.append(rset)
+
+ # Tx Priority
+ rs = RadioSettingValueList(
+ LIST_TXPRI, current_index=_settings.tx_priority)
+ rset = RadioSetting("tx_priority", "Tx Priority", rs)
+ group.append(rset)
+
+ # Frequency Step
+ rs = RadioSettingValueList(
+ LIST_FREQSTEP, current_index=_settings.freq_step)
+ rset = RadioSetting("freq_step", "Frequency Step", rs)
+ group.append(rset)
+
+ # Talkaround
+ rs = RadioSettingValueList(
+ LIST_TALKAROUND, current_index=_settings.talkaround)
+ rset = RadioSetting("talkaround", "Talkaround", rs)
+ group.append(rset)
+
+ # Save Mode
+ rs = RadioSettingValueList(
+ LIST_SAVEMODE, current_index=_settings.save_mode)
+ rset = RadioSetting("save_mode", "Save Mode", rs)
+ group.append(rset)
+
+ # Save Start Timer
+ rs = RadioSettingValueList(
+ LIST_TIMER, current_index=_settings.save_start_timer)
+ rset = RadioSetting("save_start_timer", "Save Start Timer", rs)
+ group.append(rset)
+
+ # Scan Mode
+ rs = RadioSettingValueList(
+ LIST_SCANMODE, current_index=_settings.scan_mode)
+ rset = RadioSetting("scan_mode", "Scan Mode", rs)
+ group.append(rset)
+
+ # Scan Direction
+ rs = RadioSettingValueList(
+ LIST_DIRECTION, current_index=_settings.scan_direction)
+ rset = RadioSetting("scan_direction", "Scan Direction", rs)
+ group.append(rset)
+
+ # Scan Return
+ rs = RadioSettingValueList(
+ LIST_SCANRETURN, current_index=_settings.scan_return)
+ rset = RadioSetting("scan_return", "Scan Return", rs)
+ group.append(rset)
+
+ # Scan Dwell Timer
+ rs = RadioSettingValueList(
+ LIST_SCANTIMER, current_index=_settings.scan_dwell_timer)
+ rset = RadioSetting("scan_dwell_timer", "Scan Dwell Timer", rs)
+ group.append(rset)
+
+ # Alarm Type
+ rs = RadioSettingValueList(
+ LIST_ALARMTYPE, current_index=_settings.alarm_type)
+ rset = RadioSetting("alarm_type", "Alarm Type", rs)
+ group.append(rset)
+
+ # Work Range
+ rs = RadioSettingValueList(
+ LIST_WORKRANGE, current_index=_settings.work_range)
+ rset = RadioSetting("work_range", "Work Range", rs)
+ group.append(rset)
+
+ # Denoise
+ rs = RadioSettingValueList(
+ LIST_DENOISE, current_index=_settings.denoise)
+ rset = RadioSetting("denoise", "Denoise", rs)
+ group.append(rset)
+
+ # Multi Standby
+ rs = RadioSettingValueBoolean(_settings.multi_standby)
+ rset = RadioSetting("multi_standby", "Multi Standby", rs)
+ group.append(rset)
+
+ # U/V Repeater
+ rs = RadioSettingValueBoolean(_settings.uv_repeater)
+ rset = RadioSetting("uv_repeater", "U/V Repeater", rs)
+ group.append(rset)
+
+ # Repeater Monitor
+ rs = RadioSettingValueBoolean(_settings.repeater_monitor)
+ rset = RadioSetting("repeater_monitor", "Repeater Monitor", rs)
+ group.append(rset)
+
+ # NOAA Monitor
+ rs = RadioSettingValueBoolean(_settings.noaa_monitor)
+ rset = RadioSetting("noaa_monitor", "NOAA Monitor", rs)
+ group.append(rset)
+
+ # Frequency Input
+ rs = RadioSettingValueList(
+ LIST_FREQINPUT, current_index=_settings.freq_input)
+ rset = RadioSetting("freq_input", "Frequency Input", rs)
+ group.append(rset)
+
+ # Reverse Channel
+ rs = RadioSettingValueBoolean(_settings2.reverse_channel)
+ rset = RadioSetting("settings2.reverse_channel", "Reverse Channel", rs)
+ group.append(rset)
+
+ # CT/DCS Code Show
+ rs = RadioSettingValueBoolean(_settings2.ctdcs_code_show)
+ rset = RadioSetting("settings2.ctdcs_code_show",
+ "CT/DCS Code Show", rs)
+ group.append(rset)
+
+ # Channel Alias Color
+ rs = RadioSettingValueList(
+ LIST_COLOR, current_index=_settings2.ch_alias_color)
+ rset = RadioSetting("settings2.ch_alias_color",
+ "Channel Alias Color", rs)
+ group.append(rset)
+
+ # Tx Limit
+ rs = RadioSettingValueBoolean(_settings2.tx_unlimit)
+ rset = RadioSetting("settings2.tx_unlimit", "Tx Limit", rs)
+ group.append(rset)
+
+ area_group = RadioSettingGroup("basic_area", "Areas")
+ group.append(area_group)
+
+ def apply_with_offset(setting, obj, offset):
+ setattr(obj, setting.get_name(), int(setting.value) + offset)
+
+ # Current Area
+ rs = RadioSettingValueList(
+ LIST_AREA, current_index=_settings.current_area)
+ rset = RadioSetting("current_area", "Current Area", rs)
+ area_group.append(rset)
+
+ # Area A Mode
+ rs = RadioSettingValueList(
+ LIST_AREAMODE, current_index=_settings.area_a_mode)
+ rset = RadioSetting("area_a_mode", "Area A Mode", rs)
+ area_group.append(rset)
+
+ # Area A Show
+ rs = RadioSettingValueList(
+ LIST_AREASHOW, current_index=_settings.area_a_show)
+ rset = RadioSetting("area_a_show", "Area A Show", rs)
+ area_group.append(rset)
+
+ # Area A Zone
+ rs = RadioSettingValueInteger(1, 256, _settings.area_a_zone + 1)
+ rset = RadioSetting("area_a_zone", "Area A Zone", rs)
+ rset.set_doc('Value between 1-256')
+ rset.set_apply_callback(apply_with_offset, _settings, -1)
+ area_group.append(rset)
+
+ # Area A Channel
+ rs = RadioSettingValueInteger(1, self._channelCount,
+ _settings.area_a_channel + 1)
+ rset = RadioSetting("area_a_channel", "Area A Channel", rs)
+ rset.set_doc(f'Value between 1-{self._channelCount}')
+ rset.set_apply_callback(apply_with_offset, _settings, -1)
+ area_group.append(rset)
+
+ # Area B Mode
+ rs = RadioSettingValueList(
+ LIST_AREAMODE, current_index=_settings.area_b_mode)
+ rset = RadioSetting("area_b_mode", "Area B Mode", rs)
+ area_group.append(rset)
+
+ # Area B Show
+ rs = RadioSettingValueList(
+ LIST_AREASHOW, current_index=_settings.area_b_show)
+ rset = RadioSetting("area_b_show", "Area B Show", rs)
+ area_group.append(rset)
+
+ # Area B Zone
+ rs = RadioSettingValueInteger(1, 256, _settings.area_b_zone + 1)
+ rset = RadioSetting("area_b_zone", "Area B Zone", rs)
+ rset.set_doc('Value between 1-256')
+ rset.set_apply_callback(apply_with_offset, _settings, -1)
+ area_group.append(rset)
+
+ # Area B Channel
+ rs = RadioSettingValueInteger(1, self._channelCount,
+ _settings.area_b_channel + 1)
+ rset = RadioSetting("area_b_channel", "Area B Channel", rs)
+ rset.set_doc(f'Value between 1-{self._channelCount}')
+ rset.set_apply_callback(apply_with_offset, _settings, -1)
+ area_group.append(rset)
+
+ # Area C Mode
+ rs = RadioSettingValueList(
+ LIST_AREAMODE, current_index=_settings.area_c_mode)
+ rset = RadioSetting("area_c_mode", "Area C Mode", rs)
+ area_group.append(rset)
+
+ # Area C Show
+ rs = RadioSettingValueList(
+ LIST_AREASHOW, current_index=_settings.area_c_show)
+ rset = RadioSetting("area_c_show", "Area C Show", rs)
+ area_group.append(rset)
+
+ # Area C Zone
+ rs = RadioSettingValueInteger(1, 256, _settings.area_c_zone + 1)
+ rset = RadioSetting("area_c_zone", "Area C Zone", rs)
+ rset.set_doc('Value between 1-256')
+ rset.set_apply_callback(apply_with_offset, _settings, -1)
+ area_group.append(rset)
+
+ # Area C Channel
+ rs = RadioSettingValueInteger(1, self._channelCount,
+ _settings.area_c_channel + 1)
+ rset = RadioSetting("area_c_channel", "Area C Channel", rs)
+ rset.set_doc(f'Value between 1-{self._channelCount}')
+ rset.set_apply_callback(apply_with_offset, _settings, -1)
+ area_group.append(rset)
+
+ lock_group = RadioSettingGroup("basic_lock", "Lock Ranges")
+ group.append(lock_group)
+
+ # Lock Range 1 Type
+ rs = RadioSettingValueList(
+ LIST_LOCK, current_index=_settings.lock_range_1_type)
+ rset = RadioSetting("lock_range_1_type", "Lock Range 1 Type", rs)
+ lock_group.append(rset)
+
+ # Lock Range 1 Start
+ rs = RadioSettingValueInteger(18, 1000, _settings.lock_range_1_start)
+ rset = RadioSetting("lock_range_1_start", "Lock Range 1 Start", rs)
+ rset.set_doc('Value between 18-1000 (MHz)')
+ lock_group.append(rset)
+
+ # Lock Range 1 End
+ rs = RadioSettingValueInteger(18, 1000, _settings.lock_range_1_end)
+ rset = RadioSetting("lock_range_1_end", "Lock Range 1 End", rs)
+ rset.set_doc('Value between 18-1000 (MHz)')
+ lock_group.append(rset)
+
+ # Lock Range 2 Type
+ rs = RadioSettingValueList(
+ LIST_LOCK, current_index=_settings.lock_range_2_type)
+ rset = RadioSetting("lock_range_2_type", "Lock Range 2 Type", rs)
+ lock_group.append(rset)
+
+ # Lock Range 2 Start
+ rs = RadioSettingValueInteger(18, 1000, _settings.lock_range_2_start)
+ rset = RadioSetting("lock_range_2_start", "Lock Range 2 Start", rs)
+ rset.set_doc('Value between 18-1000 (MHz)')
+ lock_group.append(rset)
+
+ # Lock Range 2 End
+ rs = RadioSettingValueInteger(18, 1000, _settings.lock_range_2_end)
+ rset = RadioSetting("lock_range_2_end", "Lock Range 2 End", rs)
+ rset.set_doc('Value between 18-1000 (MHz)')
+ lock_group.append(rset)
+
+ # Lock Range 3 Type
+ rs = RadioSettingValueList(
+ LIST_LOCK, current_index=_settings.lock_range_3_type)
+ rset = RadioSetting("lock_range_3_type", "Lock Range 3 Type", rs)
+ lock_group.append(rset)
+
+ # Lock Range 3 Start
+ rs = RadioSettingValueInteger(18, 1000, _settings.lock_range_3_start)
+ rset = RadioSetting("lock_range_3_start", "Lock Range 3 Start", rs)
+ rset.set_doc('Value between 18-1000 (MHz)')
+ lock_group.append(rset)
+
+ # Lock Range 3 End
+ rs = RadioSettingValueInteger(18, 1000, _settings.lock_range_3_end)
+ rset = RadioSetting("lock_range_3_end", "Lock Range 3 End", rs)
+ rset.set_doc('Value between 18-1000 (MHz)')
+ lock_group.append(rset)
+
+ # Lock Range 4 Type
+ rs = RadioSettingValueList(
+ LIST_LOCK, current_index=_settings.lock_range_4_type)
+ rset = RadioSetting("lock_range_4_type", "Lock Range 4 Type", rs)
+ lock_group.append(rset)
+
+ # Lock Range 4 Start
+ rs = RadioSettingValueInteger(18, 1000, _settings.lock_range_4_start)
+ rset = RadioSetting("lock_range_4_start", "Lock Range 4 Start", rs)
+ rset.set_doc('Value between 18-1000 (MHz)')
+ lock_group.append(rset)
+
+ # Lock Range 4 End
+ rs = RadioSettingValueInteger(18, 1000, _settings.lock_range_4_end)
+ rset = RadioSetting("lock_range_4_end", "Lock Range 4 End", rs)
+ rset.set_doc('Value between 18-1000 (MHz)')
+ lock_group.append(rset)
+
+ def get_startup_settings(self, group):
+ _settings = self._memobj.settings
+
+ # Welcome Message
+ _codeobj = _settings.welcome_message
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 32, _code, True)
+ rset = RadioSetting("welcome_message", "Welcome Message", rs)
+ rset.set_apply_callback(self.apply_string, _settings)
+ group.append(rset)
+
+ # Welcome Message Enable
+ rs = RadioSettingValueBoolean(_settings.welcome_message_enable)
+ rset = RadioSetting("welcome_message_enable",
+ "Welcome Message Enable", rs)
+ group.append(rset)
+
+ # Welcome Message Color
+ rs = RadioSettingValueInteger(0, 65536, _settings.welcome_text_color)
+ rset = RadioSetting("welcome_text_color", "Welcome Message Color", rs)
+ rset.set_doc('Value between 0-65536')
+ group.append(rset)
+
+ # Welcome Message Start Line
+ rs = RadioSettingValueInteger(0, 319, _settings.welcome_start_line)
+ rset = RadioSetting("welcome_start_line",
+ "Welcome Message Start Line", rs)
+ rset.set_doc('Value between 0-319')
+ group.append(rset)
+
+ # Welcome Message Start Column
+ rs = RadioSettingValueInteger(0, 239, _settings.welcome_start_column)
+ rset = RadioSetting("welcome_start_column",
+ "Welcome Message Start Column", rs)
+ rset.set_doc('Value between 0-239')
+ group.append(rset)
+
+ # Startup Image Enable
+ rs = RadioSettingValueBoolean(_settings.startup_image_enable)
+ rset = RadioSetting("startup_image_enable",
+ "Startup Image Enable", rs)
+ group.append(rset)
+
+ # Startup Ringtone Enable
+ rs = RadioSettingValueBoolean(_settings.startup_ringtone_enable)
+ rset = RadioSetting("startup_ringtone_enable",
+ "Startup Ringtone Enable", rs)
+ group.append(rset)
+
+ # Startup Password
+ _codeobj = _settings.startup_password
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 16, _code, True)
+ rset = RadioSetting("startup_password", "Startup Password", rs)
+ rset.set_apply_callback(self.apply_string, _settings)
+ group.append(rset)
+
+ # Startup Password Enable
+ rs = RadioSettingValueBoolean(_settings.startup_password_enable)
+ rset = RadioSetting("startup_password_enable",
+ "Startup Password Enable", rs)
+ group.append(rset)
+
+ def get_keydefine_settings(self, group):
+ _settings = self._memobj.settings
+
+ # Multi PTT
+ rs = RadioSettingValueBoolean(_settings.multi_ptt)
+ rset = RadioSetting("multi_ptt", "Multi PTT", rs)
+ group.append(rset)
+
+ # Side Key 1 Short
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.side_key_1_s)
+ rset = RadioSetting("side_key_1_s", "Side Key 1 Short", rs)
+ group.append(rset)
+
+ # Side Key 1 Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.side_key_1_l)
+ rset = RadioSetting("side_key_1_l", "Side Key 1 Long", rs)
+ group.append(rset)
+
+ # Side Key 2 Short
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.side_key_2_s)
+ rset = RadioSetting("side_key_2_s", "Side Key 2 Short", rs)
+ group.append(rset)
+
+ # Side Key 2 Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.side_key_2_l)
+ rset = RadioSetting("side_key_2_l", "Side Key 2 Long", rs)
+ group.append(rset)
+
+ # Alarm Key 2 Short
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.alarm_key_2_s)
+ rset = RadioSetting("alarm_key_2_s", "Alarm Key 2 Short", rs)
+ group.append(rset)
+
+ # Alarm Key 2 Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.alarm_key_2_l)
+ rset = RadioSetting("alarm_key_2_l", "Alarm Key 2 Long", rs)
+ group.append(rset)
+
+ # 0 Press Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.key_0_long)
+ rset = RadioSetting("key_0_long", "0 Press Long", rs)
+ group.append(rset)
+
+ # 1 Press Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.key_1_long)
+ rset = RadioSetting("key_1_long", "1 Press Long", rs)
+ group.append(rset)
+
+ # 2 Press Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.key_2_long)
+ rset = RadioSetting("key_2_long", "2 Press Long", rs)
+ group.append(rset)
+
+ # 3 Press Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.key_3_long)
+ rset = RadioSetting("key_3_long", "3 Press Long", rs)
+ group.append(rset)
+
+ # 4 Press Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.key_4_long)
+ rset = RadioSetting("key_4_long", "4 Press Long", rs)
+ group.append(rset)
+
+ # 5 Press Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.key_5_long)
+ rset = RadioSetting("key_5_long", "5 Press Long", rs)
+ group.append(rset)
+
+ # 6 Press Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.key_6_long)
+ rset = RadioSetting("key_6_long", "6 Press Long", rs)
+ group.append(rset)
+
+ # 7 Press Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.key_7_long)
+ rset = RadioSetting("key_7_long", "7 Press Long", rs)
+ group.append(rset)
+
+ # 8 Press Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.key_8_long)
+ rset = RadioSetting("key_8_long", "8 Press Long", rs)
+ group.append(rset)
+
+ # 9 Press Long
+ rs = RadioSettingValueList(
+ LIST_KEYDEFINE, current_index=_settings.key_9_long)
+ rset = RadioSetting("key_9_long", "9 Press Long", rs)
+ group.append(rset)
+
+ def get_analog_settings(self, group):
+ _settings = self._memobj.settings
+
+ # Squelch Level
+ rs = RadioSettingValueInteger(0, 10, _settings.squelch_level)
+ rset = RadioSetting("squelch_level", "Squelch Level", rs)
+ rset.set_doc('Value between 0-10')
+ group.append(rset)
+
+ # Tx Start Tone
+ rs = RadioSettingValueBoolean(_settings.tx_start_tone)
+ rset = RadioSetting("tx_start_tone", "Tx Start Tone", rs)
+ group.append(rset)
+
+ # Tx End Tone
+ rs = RadioSettingValueList(
+ LIST_TXENDTONE, current_index=_settings.tx_end_tone)
+ rset = RadioSetting("tx_end_tone", "Tx End Tone", rs)
+ group.append(rset)
+
+ # Single Tone
+ rs = RadioSettingValueInteger(0, 9999, _settings.single_tone)
+ rset = RadioSetting("single_tone", "Single Tone (Hz)", rs)
+ rset.set_doc('Value between 0-9999')
+ group.append(rset)
+
+ # VOX
+ rs = RadioSettingValueBoolean(_settings.vox)
+ rset = RadioSetting("vox", "VOX", rs)
+ group.append(rset)
+
+ # VOX Threshold
+ rs = RadioSettingValueInteger(0, 254, _settings.vox_threshold)
+ rset = RadioSetting("vox_threshold", "VOX Threshold", rs)
+ rset.set_doc('Value between 0-254')
+ group.append(rset)
+
+ # VOX Delay
+ rs = RadioSettingValueInteger(0, 5, _settings.vox_delay)
+ rset = RadioSetting("vox_delay", "VOX Delay", rs)
+ rset.set_doc('Value between 0-5')
+ group.append(rset)
+
+ # Detect Range
+ rs = RadioSettingValueList(
+ LIST_DETECTRANGE, current_index=_settings.detect_range)
+ rset = RadioSetting("detect_range", "Detect Range", rs)
+ group.append(rset)
+
+ # Repeater Delay
+ rs = RadioSettingValueList(
+ LIST_DELAY, current_index=_settings.repeater_delay)
+ rset = RadioSetting("repeater_delay", "Repeater Delay", rs)
+ group.append(rset)
+
+ # Mic Gain
+ rs = RadioSettingValueInteger(0, 31, _settings.mic_gain)
+ rset = RadioSetting("mic_gain", "Mic Gain", rs)
+ rset.set_doc('Value between 0-31')
+ group.append(rset)
+
+ # FM Mode SPK Gain
+ rs = RadioSettingValueInteger(0, 63, _settings.fm_spk_gain)
+ rset = RadioSetting("fm_spk_gain", "FM Mode SPK Gain", rs)
+ rset.set_doc('Value between 0-63')
+ group.append(rset)
+
+ # FM Mode DAC Gain
+ rs = RadioSettingValueInteger(0, 15, _settings.fm_dac_gain)
+ rset = RadioSetting("fm_dac_gain", "FM Mode DAC Gain", rs)
+ rset.set_doc('Value between 0-15')
+ group.append(rset)
+
+ # AM Mode SPK Gain
+ rs = RadioSettingValueInteger(0, 63, _settings.am_spk_gain)
+ rset = RadioSetting("am_spk_gain", "AM Mode SPK Gain", rs)
+ rset.set_doc('Value between 0-63')
+ group.append(rset)
+
+ # AM Mode DAC Gain
+ rs = RadioSettingValueInteger(0, 15, _settings.am_dac_gain)
+ rset = RadioSetting("am_dac_gain", "AM Mode DAC Gain", rs)
+ rset.set_doc('Value between 0-15')
+ group.append(rset)
+
+ # Glitch Threshold
+ rs = RadioSettingValueInteger(0, 10, _settings.glitch_threshold)
+ rset = RadioSetting("glitch_threshold", "Glitch Threshold", rs)
+ rset.set_doc('Value between 0-10')
+ group.append(rset)
+
+ # Voice Level Refresh
+ rs = RadioSettingValueList(
+ LIST_DELAY, current_index=_settings.tx_voice_refresh)
+ rset = RadioSetting("tx_voice_refresh", "Voice Level Refresh", rs)
+ group.append(rset)
+
+ # RSSI Level Refresh
+ rs = RadioSettingValueList(
+ LIST_DELAY, current_index=_settings.rx_rssi_refresh)
+ rset = RadioSetting("rx_rssi_refresh", "RSSI Level Refresh", rs)
+ group.append(rset)
+
+ tt_group = RadioSettingGroup("analog_tt", "Temporary Tuning")
+ group.append(tt_group)
+
+ # Temporary Tuning Rx Test
+ rs = RadioSettingValueBoolean(_settings.tt_rx_test)
+ rset = RadioSetting("tt_rx_test", "Rx Test", rs)
+ tt_group.append(rset)
+
+ # Temporary Tuning RSSI Threshold
+ rs = RadioSettingValueInteger(0, 127, _settings.tt_rssi_threshold)
+ rset = RadioSetting("tt_rssi_threshold", "RSSI Threshold", rs)
+ rset.set_doc('Value between 0-127')
+ tt_group.append(rset)
+
+ # Temporary Tuning Noise Threshold
+ rs = RadioSettingValueInteger(0, 127, _settings.tt_noise_threshold)
+ rset = RadioSetting("tt_noise_threshold", "Noise Threshold", rs)
+ rset.set_doc('Value between 0-127')
+ tt_group.append(rset)
+
+ # Temporary Tuning Power Test
+ rs = RadioSettingValueBoolean(_settings.tt_power_test)
+ rset = RadioSetting("tt_power_test", "Power Test", rs)
+ tt_group.append(rset)
+
+ # Temporary Tuning 136-174MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_136_174)
+ rset = RadioSetting("tt_power_136_174", "136-174MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 400-480MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_400_480)
+ rset = RadioSetting("tt_power_400_480", "400-480MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 18-64MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_18_64)
+ rset = RadioSetting("tt_power_18_64", "18-64MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 64-136MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_64_136)
+ rset = RadioSetting("tt_power_64_136", "64-136MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 173-240MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_173_240)
+ rset = RadioSetting("tt_power_173_240", "173-240MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 240-320MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_240_320)
+ rset = RadioSetting("tt_power_240_320", "240-320MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 320-400MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_320_400)
+ rset = RadioSetting("tt_power_320_400", "320-400MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 480-560MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_480_560)
+ rset = RadioSetting("tt_power_480_560", "480-560MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 560-620MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_560_620)
+ rset = RadioSetting("tt_power_560_620", "560-620MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 840-920MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_840_920)
+ rset = RadioSetting("tt_power_840_920", "840-920MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 920-1000MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_920_1000)
+ rset = RadioSetting("tt_power_920_1000", "920-1000MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 1000-1080MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_1000_1080)
+ rset = RadioSetting("tt_power_1000_1080", "1000-1080MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 1080-1160MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_1080_1160)
+ rset = RadioSetting("tt_power_1080_1160", "1080-1160MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 1160-1240MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_1160_1240)
+ rset = RadioSetting("tt_power_1160_1240", "1160-1240MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ # Temporary Tuning 1240-1300MHz Power
+ rs = RadioSettingValueInteger(0, 255, _settings.tt_power_1240_1300)
+ rset = RadioSetting("tt_power_1240_1300", "1240-1300MHz Power", rs)
+ rset.set_doc('Value between 0-255')
+ tt_group.append(rset)
+
+ def get_dtmf_settings(self, group):
+ _dtmf = self._memobj.dtmf
+
+ # DTMF Delay
+ rs = RadioSettingValueList(
+ LIST_DELAY, current_index=_dtmf.dtmf_delay)
+ rset = RadioSetting("dtmf.dtmf_delay", "DTMF Delay", rs)
+ group.append(rset)
+
+ # DTMF Interval
+ rs = RadioSettingValueList(
+ LIST_INTERVAL, current_index=_dtmf.dtmf_interval)
+ rset = RadioSetting("dtmf.dtmf_interval", "DTMF Interval", rs)
+ group.append(rset)
+
+ # DTMF Duration
+ rs = RadioSettingValueList(
+ LIST_INTERVAL, current_index=_dtmf.dtmf_duration)
+ rset = RadioSetting("dtmf.dtmf_duration", "DTMF Duration", rs)
+ group.append(rset)
+
+ # DTMF Mode
+ rs = RadioSettingValueList(
+ LIST_DTMFMODE, current_index=_dtmf.dtmf_mode)
+ rset = RadioSetting("dtmf.dtmf_mode", "DTMF Mode", rs)
+ group.append(rset)
+
+ # DTMF Select
+ rs = RadioSettingValueList(
+ LIST_DTMFSELECT, current_index=_dtmf.dtmf_select)
+ rset = RadioSetting("dtmf.dtmf_select", "DTMF Select", rs)
+ group.append(rset)
+
+ # DTMF Display
+ rs = RadioSettingValueBoolean(_dtmf.dtmf_display)
+ rset = RadioSetting("dtmf.dtmf_display", "DTMF Display", rs)
+ group.append(rset)
+
+ # DTMF Tx Gain
+ rs = RadioSettingValueInteger(0, 127, _dtmf.dtmf_tx_gain)
+ rset = RadioSetting("dtmf.dtmf_tx_gain", "DTMF Tx Gain", rs)
+ rset.set_doc('Value between 0-127')
+ group.append(rset)
+
+ # DTMF Rx Threshold
+ rs = RadioSettingValueInteger(0, 63, _dtmf.dtmf_rx_threshold)
+ rset = RadioSetting("dtmf.dtmf_rx_threshold", "DTMF Rx Threshold", rs)
+ rset.set_doc('Value between 0-63')
+ group.append(rset)
+
+ # DTMF Control
+ rs = RadioSettingValueBoolean(_dtmf.dtmf_control)
+ rset = RadioSetting("dtmf.dtmf_control", "DTMF Control", rs)
+ group.append(rset)
+
+ # Time Calibrate
+ rs = RadioSettingValueBoolean(_dtmf.time_calibrate)
+ rset = RadioSetting("dtmf.time_calibrate", "Time Calibrate", rs)
+ group.append(rset)
+
+ def apply_code(setting, obj, length):
+ code = ""
+ for char in str(setting.value):
+ if char in DTMF_CHARS:
+ code += char
+ else:
+ code += ""
+ obj.code_length = len(str(code))
+ obj.code = code.ljust(length, chr(255))
+
+ # DTMF Codes
+ for i in range(0, 16):
+ _codeobj = _dtmf.dtmf_codes[i].code
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 14, _code, False, DTMF_CHARS)
+ rset = RadioSetting("dtmf.dtmf_codes/%i.code" % i,
+ "Code %i" % (i + 1), rs)
+ rset.set_apply_callback(apply_code, _dtmf.dtmf_codes[i], 14)
+ group.append(rset)
+
+ # Remote Stun
+ _codeobj = _dtmf.remote_stun.code
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 14, _code, False, DTMF_CHARS)
+ rset = RadioSetting("dtmf.remote_stun", "Remote Stun", rs)
+ rset.set_apply_callback(apply_code, _dtmf.remote_stun, 14)
+ group.append(rset)
+
+ # Remote Kill
+ _codeobj = _dtmf.remote_kill.code
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 14, _code, False, DTMF_CHARS)
+ rset = RadioSetting("dtmf.remote_kill", "Remote Kill", rs)
+ rset.set_apply_callback(apply_code, _dtmf.remote_kill, 14)
+ group.append(rset)
+
+ # Remote Wake
+ _codeobj = _dtmf.remote_wake.code
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 14, _code, False, DTMF_CHARS)
+ rset = RadioSetting("dtmf.remote_wake", "Remote Wake", rs)
+ rset.set_apply_callback(apply_code, _dtmf.remote_wake, 14)
+ group.append(rset)
+
+ # Remote Monitor
+ _codeobj = _dtmf.remote_monitor.code
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 14, _code, False, DTMF_CHARS)
+ rset = RadioSetting("dtmf.remote_monitor", "Remote Monitor", rs)
+ rset.set_apply_callback(apply_code, _dtmf.remote_monitor, 14)
+ group.append(rset)
+
+ def get_gps_settings(self, group):
+ _settings = self._memobj.settings
+ _gps = self._memobj.gps
+
+ # GPS Enable
+ rs = RadioSettingValueBoolean(_settings.gps_enable)
+ rset = RadioSetting("gps_enable", "GPS Enable", rs)
+ group.append(rset)
+
+ # GPS Baud Rate
+ rs = RadioSettingValueList(
+ LIST_GPSBAUD, current_index=_settings.gps_baud_rate)
+ rset = RadioSetting("gps_baud_rate", "Baud Rate", rs)
+ group.append(rset)
+
+ # GPS UTC Zone
+ rs = RadioSettingValueList(
+ LIST_GPSUTC, current_index=_settings.gps_utc_zone)
+ rset = RadioSetting("gps_utc_zone", "UTC Zone", rs)
+ group.append(rset)
+
+ # GPS Coordinate Type
+ rs = RadioSettingValueList(
+ LIST_GPSCOORD, current_index=_gps.gps_coord_type)
+ rset = RadioSetting("gps.gps_coord_type", "Coordinate Type", rs)
+ group.append(rset)
+
+ # GPS Speed Unit
+ rs = RadioSettingValueList(
+ LIST_GPSSPEED, current_index=_gps.gps_speed_unit)
+ rset = RadioSetting("gps.gps_speed_unit", "Speed Unit", rs)
+ group.append(rset)
+
+ # GPS Distance Unit
+ rs = RadioSettingValueList(
+ LIST_GPSDIST, current_index=_gps.gps_distance_unit)
+ rset = RadioSetting("gps.gps_distance_unit", "Distance Unit", rs)
+ group.append(rset)
+
+ # GPS Altitude Unit
+ rs = RadioSettingValueList(
+ LIST_GPSALT, current_index=_gps.gps_altitude_unit)
+ rset = RadioSetting("gps.gps_altitude_unit", "Altitude Unit", rs)
+ group.append(rset)
+
+ # GPS Mileage Type
+ rs = RadioSettingValueList(
+ LIST_GPSMILEAGE, current_index=_gps.gps_mileage_type)
+ rset = RadioSetting("gps.gps_mileage_type", "Mileage Type", rs)
+ group.append(rset)
+
+ # GPS Auto Record
+ rs = RadioSettingValueBoolean(_settings.gps_auto_record)
+ rset = RadioSetting("gps_auto_record", "Auto Record", rs)
+ group.append(rset)
+
+ # Fixed coordinates are stored as strings with an implicit decimal
+ def fixed_coord_to_float(val, wholeDigits):
+ valStr = str(val).replace("-", "0").replace('\00', "0")
+ return float(f"{valStr[:wholeDigits]}.{valStr[wholeDigits:]}")
+
+ def apply_fixed_coord(setting, obj, width, precision):
+ setattr(obj, setting.get_name()
+ .rsplit('.', 1)[-1],
+ f"{float(setting.value):0{width}.{precision}f}"
+ .replace(".", ""))
+
+ def fixed_coord_dir_index(list, val):
+ try:
+ return list.index(str(val))
+ except ValueError:
+ return 0
+
+ def apply_fixed_coord_dir(setting, obj, dirArray):
+ setattr(obj, setting.get_name().rsplit('.', 1)[-1],
+ dirArray[int(setting.value)])
+
+ # GPS Fixed Latitude
+ val = fixed_coord_to_float(_gps.gps_fixed_lat, 2)
+ rs = RadioSettingValueFloat(0, 99.99999, val, 0.00001, 5)
+ rset = RadioSetting("gps.gps_fixed_lat", "Fixed Latitude", rs)
+ rset.set_apply_callback(apply_fixed_coord, _gps, 8, 5)
+ group.append(rset)
+
+ # GPS Fixed Latitude Direction
+ val = fixed_coord_dir_index(LIST_GPSLATDIR, _gps.gps_fixed_lat_dir)
+ rs = RadioSettingValueList(LIST_GPSLATDIR, current_index=val)
+ rset = RadioSetting("gps.gps_fixed_lat_dir",
+ "Fixed Latitude Direction", rs)
+ rset.set_apply_callback(apply_fixed_coord_dir, _gps, LIST_GPSLATDIR)
+ group.append(rset)
+
+ # GPS Fixed Longitude
+ val = fixed_coord_to_float(_gps.gps_fixed_long, 3)
+ rs = RadioSettingValueFloat(0, 999.99999, val, 0.00001, 5)
+ rset = RadioSetting("gps.gps_fixed_long", "Fixed Longitude", rs)
+ rset.set_apply_callback(apply_fixed_coord, _gps, 9, 5)
+ group.append(rset)
+
+ # GPS Fixed Longitude Direction
+ val = fixed_coord_dir_index(LIST_GPSLONGDIR, _gps.gps_fixed_long_dir)
+ rs = RadioSettingValueList(LIST_GPSLONGDIR, current_index=val)
+ rset = RadioSetting("gps.gps_fixed_long_dir",
+ "Fixed Longitude Direction", rs)
+ rset.set_apply_callback(apply_fixed_coord_dir, _gps, LIST_GPSLONGDIR)
+ group.append(rset)
+
+ # GPS Fixed Altitude
+ val = fixed_coord_to_float(_gps.gps_fixed_altitude, 6)
+ rs = RadioSettingValueFloat(0, 999999.9, val, 0.1, 1)
+ rset = RadioSetting("gps.gps_fixed_altitude", "Fixed Altitude", rs)
+ rset.set_apply_callback(apply_fixed_coord, _gps, 8, 1)
+ group.append(rset)
+
+ def get_aprs_settings(self, group):
+ _aprs = self._memobj.aprs
+
+ # APRS Enable
+ rs = RadioSettingValueBoolean(_aprs.aprs_enable)
+ rset = RadioSetting("aprs.aprs_enable", "APRS Enable", rs)
+ group.append(rset)
+
+ # APRS Station Mode
+ rs = RadioSettingValueList(
+ LIST_APRSSTATIONMODE, current_index=_aprs.aprs_station_mode)
+ rset = RadioSetting("aprs.aprs_station_mode", "Station Mode", rs)
+ group.append(rset)
+
+ # APRS Callsign
+ _codeobj = _aprs.aprs_callsign
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 6, _code, True)
+ rset = RadioSetting("aprs.aprs_callsign", "Callsign", rs)
+ rset.set_apply_callback(self.apply_string, _aprs)
+ group.append(rset)
+
+ # APRS SSID
+ rs = RadioSettingValueList(
+ chirp_common.APRS_SSID, current_index=_aprs.aprs_ssid)
+ rset = RadioSetting("aprs.aprs_ssid", "SSID", rs)
+ group.append(rset)
+
+ # APRS Symbol Table
+ rs = RadioSettingValueList(
+ LIST_APRSSYMBOLTABLE, current_index=_aprs.aprs_symbol_table)
+ rset = RadioSetting("aprs.aprs_symbol_table", "Symbol Table", rs)
+ group.append(rset)
+
+ # APRS Symbol
+ rs = RadioSettingValueList(
+ LIST_APRSSYMBOLS, current_index=_aprs.aprs_symbol)
+ rset = RadioSetting("aprs.aprs_symbol", "Symbol", rs)
+ group.append(rset)
+
+ # APRS Comment
+ _codeobj = _aprs.aprs_comment
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 128, _code, True)
+ rset = RadioSetting("aprs.aprs_comment", "Comment", rs)
+ rset.set_apply_callback(self.apply_string, _aprs)
+ group.append(rset)
+
+ # APRS MIC-E Enable
+ rs = RadioSettingValueBoolean(_aprs.aprs_mice_enable)
+ rset = RadioSetting("aprs.aprs_mice_enable", "MIC-E Enable", rs)
+ group.append(rset)
+
+ # APRS MIC-E Mode
+ rs = RadioSettingValueList(
+ LIST_APRESMICEMODE, current_index=_aprs.aprs_mice_mode)
+ rset = RadioSetting("aprs.aprs_mice_mode", "MIC-E Mode", rs)
+ group.append(rset)
+
+ # APRS Path 1
+ _codeobj = _aprs.aprs_path_1
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 6, _code, True)
+ rset = RadioSetting("aprs.aprs_path_1", "Path 1", rs)
+ rset.set_apply_callback(self.apply_string, _aprs)
+ group.append(rset)
+
+ # APRS Path 1 Count
+ rs = RadioSettingValueInteger(0, 9, _aprs.aprs_path_1_count)
+ rset = RadioSetting("aprs.aprs_path_1_count", "Path 1 Count", rs)
+ rset.set_doc('Value between 0-9')
+ group.append(rset)
+
+ # APRS Path 2
+ _codeobj = _aprs.aprs_path_2
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 6, _code, True)
+ rset = RadioSetting("aprs.aprs_path_2", "Path 2", rs)
+ rset.set_apply_callback(self.apply_string, _aprs)
+ group.append(rset)
+
+ # APRS Path 2 Count
+ rs = RadioSettingValueInteger(0, 9, _aprs.aprs_path_2_count)
+ rset = RadioSetting("aprs.aprs_path_2_count", "Path 2 Count", rs)
+ rset.set_doc('Value between 0-9')
+ group.append(rset)
+
+ # APRS Tx Voltage
+ rs = RadioSettingValueBoolean(_aprs.aprs_tx_voltage)
+ rset = RadioSetting("aprs.aprs_tx_voltage", "Tx Voltage", rs)
+ group.append(rset)
+
+ # APRS Tx Star
+ rs = RadioSettingValueBoolean(_aprs.aprs_tx_star)
+ rset = RadioSetting("aprs.aprs_tx_star", "Tx Star", rs)
+ group.append(rset)
+
+ # APRS Tx Mileage
+ rs = RadioSettingValueBoolean(_aprs.aprs_tx_mileage)
+ rset = RadioSetting("aprs.aprs_tx_mileage", "Tx Mileage", rs)
+ group.append(rset)
+
+ # APRS Rx Channel
+ rs = RadioSettingValueList(
+ LIST_APRSCHANNEL, current_index=_aprs.aprs_rx_ch)
+ rset = RadioSetting("aprs.aprs_rx_ch", "Rx Channel", rs)
+ group.append(rset)
+
+ # APRS Tx Channel
+ rs = RadioSettingValueList(
+ LIST_APRSCHANNELCOMBOS, current_index=_aprs.aprs_tx_ch)
+ rset = RadioSetting("aprs.aprs_tx_ch", "Tx Channel", rs)
+ group.append(rset)
+
+ # APRS PTT Priority
+ rs = RadioSettingValueList(
+ LIST_APRSPTTPRIORITY, current_index=_aprs.aprs_ptt_priority)
+ rset = RadioSetting("aprs.aprs_ptt_priority", "PTT Priority", rs)
+ group.append(rset)
+
+ # APRS PTT Delay
+ rs = RadioSettingValueList(
+ LIST_APRSPTTDELAY, current_index=_aprs.aprs_ptt_delay)
+ rset = RadioSetting("aprs.aprs_ptt_delay", "PTT Delay", rs)
+ group.append(rset)
+
+ # APRS Beacon Popup
+ rs = RadioSettingValueBoolean(_aprs.aprs_beacon_popup)
+ rset = RadioSetting("aprs.aprs_beacon_popup", "Beacon Popup", rs)
+ group.append(rset)
+
+ # APRS Beacon After
+ rs = RadioSettingValueList(
+ LIST_APRSBEACONAFTER, current_index=_aprs.aprs_beacon_ptt_after)
+ rset = RadioSetting("aprs.aprs_beacon_ptt_after", "Beacon After", rs)
+ group.append(rset)
+
+ # APRS Smart Beacon
+ rs = RadioSettingValueList(
+ LIST_APRSSMARTBEACON, current_index=_aprs.aprs_smart_beacon)
+ rset = RadioSetting("aprs.aprs_smart_beacon", "Smart Beacon", rs)
+ group.append(rset)
+
+ # APRS Beacon Time Mode
+ rs = RadioSettingValueBoolean(_aprs.aprs_beacon_time_mode)
+ rset = RadioSetting("aprs.aprs_beacon_time_mode",
+ "Beacon Time Mode", rs)
+ group.append(rset)
+
+ # APRS Beacon Time
+ rs = RadioSettingValueInteger(10, 99999999, _aprs.aprs_beacon_time)
+ rset = RadioSetting("aprs.aprs_beacon_time", "Beacon Time", rs)
+ rset.set_doc('Value between 10-99999999')
+ group.append(rset)
+
+ # APRS Queue Beacon
+ rs = RadioSettingValueBoolean(_aprs.aprs_queue_beacon)
+ rset = RadioSetting("aprs.aprs_queue_beacon", "Queue Beacon", rs)
+ group.append(rset)
+
+ # APRS Queue Interval
+ rs = RadioSettingValueInteger(0, 59, _aprs.aprs_queue_interval)
+ rset = RadioSetting("aprs.aprs_queue_interval", "Queue Interval", rs)
+ rset.set_doc('Value between 0-59')
+ group.append(rset)
+
+ # APRS Demod Tone
+ rs = RadioSettingValueBoolean(_aprs.aprs_demod_tone)
+ rset = RadioSetting("aprs.aprs_demod_tone", "Demod Tone", rs)
+ group.append(rset)
+
+ # APRS Tx Level
+ rs = RadioSettingValueList(
+ LIST_APRSLEVEL, current_index=_aprs.aprs_tx_level)
+ rset = RadioSetting("aprs.aprs_tx_level", "Tx Level", rs)
+ group.append(rset)
+
+ # APRS Rx Level
+ rs = RadioSettingValueList(
+ LIST_APRSLEVEL, current_index=_aprs.aprs_rx_level)
+ rset = RadioSetting("aprs.aprs_rx_level", "Rx Level", rs)
+ group.append(rset)
+
+ # APRS Beacon Save
+ rs = RadioSettingValueList(
+ LIST_APRSBEACONSAVE, current_index=_aprs.aprs_beacon_save)
+ rset = RadioSetting("aprs.aprs_beacon_save", "Beacon Save", rs)
+ group.append(rset)
+
+ # APRS Beacon After Channel
+ rs = RadioSettingValueList(
+ LIST_APRSCHANNELCOMBOS,
+ current_index=_aprs.aprs_beacon_ptt_after_ch)
+ rset = RadioSetting("aprs.aprs_beacon_ptt_after_ch",
+ "Beacon After Channel", rs)
+ group.append(rset)
+
+ # APRS Rx Channel Mute
+ rs = RadioSettingValueBoolean(_aprs.aprs_rx_ch_mute)
+ rset = RadioSetting("aprs.aprs_rx_ch_mute", "Rx Channel Mute", rs)
+ group.append(rset)
+
+ digi_group = RadioSettingGroup("aprs_digi", "Digipeater")
+ group.append(digi_group)
+
+ # APRS Digipeater Channel
+ rs = RadioSettingValueList(
+ LIST_APRSCHANNELCOMBOS, current_index=_aprs.aprs_digi_rep_ch)
+ rset = RadioSetting("aprs.aprs_digi_rep_ch", "Channel", rs)
+ digi_group.append(rset)
+
+ # APRS Digipeater 1 Enable
+ rs = RadioSettingValueBoolean(_aprs.aprs_digi_1_enable)
+ rset = RadioSetting("aprs.aprs_digi_1_enable",
+ "Digipeater 1 Enable", rs)
+ digi_group.append(rset)
+
+ # APRS Digipeater 1 Name
+ _codeobj = _aprs.aprs_digi_1_name
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 6, _code, True)
+ rset = RadioSetting("aprs.aprs_digi_1_name", "Digipeater 1 Name", rs)
+ rset.set_apply_callback(self.apply_string, _aprs)
+ digi_group.append(rset)
+
+ # APRS Digipeater 2 Enable
+ rs = RadioSettingValueBoolean(_aprs.aprs_digi_2_enable)
+ rset = RadioSetting("aprs.aprs_digi_2_enable",
+ "Digipeater 2 Enable", rs)
+ digi_group.append(rset)
+
+ # APRS Digipeater 2 Name
+ _codeobj = _aprs.aprs_digi_2_name
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 6, _code, True)
+ rset = RadioSetting("aprs.aprs_digi_2_name", "Digipeater 2 Name", rs)
+ rset.set_apply_callback(self.apply_string, _aprs)
+ digi_group.append(rset)
+
+ # APRS Digipeater Wait Before Repeat
+ rs = RadioSettingValueInteger(0, 9, _aprs.aprs_digi_wait_before_rep)
+ rset = RadioSetting("aprs.aprs_digi_wait_before_rep",
+ "Wait Before Repeat", rs)
+ rset.set_doc('Value between 0-9')
+ digi_group.append(rset)
+
+ # APRS Digipeater Remote Password
+ _codeobj = _aprs.aprs_digi_remote_password
+ _code = str(_codeobj).rstrip('\xFF')
+ rs = RadioSettingValueString(0, 6, _code, True)
+ rset = RadioSetting("aprs.aprs_digi_remote_password",
+ "Remote Password", rs)
+ digi_group.append(rset)
+
+ def get_time_settings(self, group):
+ _settings = self._memobj.settings
+
+ # Automatic Power Off
+ rs = RadioSettingValueBoolean(_settings.auto_power_off)
+ rset = RadioSetting("auto_power_off",
+ "Automatic Power Off", rs)
+ group.append(rset)
+
+ # Automatic Power Off Time
+ rs = RadioSettingValueInteger(0, 235929599,
+ _settings.auto_power_off_time)
+ rset = RadioSetting("auto_power_off_time", "Auto Power Off Time", rs)
+ rset.set_doc('Value between 0-235929599')
+ group.append(rset)
+
+ # Automatic Wake Up
+ rs = RadioSettingValueBoolean(_settings.auto_wake_up)
+ rset = RadioSetting("auto_wake_up",
+ "Automatic Wake Up", rs)
+ group.append(rset)
+
+ # Automatic Wake Up Time
+ rs = RadioSettingValueInteger(0, 235929599,
+ _settings.auto_wake_up_time)
+ rset = RadioSetting("auto_wake_up_time", "Auto Wake Up Time", rs)
+ rset.set_doc('Value between 0-235929599')
+ group.append(rset)
+
+ def set_settings(self, settings):
+ for element in settings:
+ if not isinstance(element, RadioSetting):
+ self.set_settings(element)
+ continue
+ else:
+ try:
+ name = element.get_name()
+ if "." in name:
+ bits = name.split(".")
+ obj = self._memobj
+ for bit in bits[:-1]:
+ if "/" in bit:
+ bit, index = bit.split("/", 1)
+ index = int(index)
+ obj = getattr(obj, bit)[index]
+ else:
+ obj = getattr(obj, bit)
+ setting = bits[-1]
+ else:
+ obj = self._memobj.settings
+ setting = element.get_name()
+
+ if element.has_apply_callback():
+ LOG.debug("Using apply callback")
+ element.run_apply_callback()
+ elif element.value.get_mutable():
+ LOG.debug("Setting %s = %s" % (setting, element.value))
+ setattr(obj, setting, element.value)
+ except Exception as e:
+ LOG.debug(element.get_name(), e)
+ raise
diff --git a/chirp/drivers/radtel_rt900.py b/chirp/drivers/radtel_rt900.py
index f1798bf..52ac148 100644
--- a/chirp/drivers/radtel_rt900.py
+++ b/chirp/drivers/radtel_rt900.py
@@ -1,7 +1,8 @@
-# Copyright 2025 Fred Trimble <chirpdriver@gmail.com>
+# Copyright 2025, 2026 Fred Trimble <chirpdriver@gmail.com>
# Derived from prior copyrighted work:
# Copyright 2024 Pavel Moravec, OK2MOP <moravecp.cz@gmail.com>
# Copyright 2023 Jim Unroe <rock.unroe@gmail.com>
+#
# CHIRP driver for Ratel RT-900 Series radios
#
# This program is free software: you can redistribute it and/or modify
@@ -40,19 +41,50 @@ from chirp.settings import (
RadioSettingValueString,
RadioSettingValueMap,
MemSetting,
- InvalidValueError
+ InvalidValueError,
)
from textwrap import dedent
from chirp.drivers import (
baofeng_uv17Pro,
mml_jc8810,
- baofeng_common as bfc
+ baofeng_common as bfc,
)
import struct
LOG = logging.getLogger(__name__)
+# FHSS Code is a 24-bit per-channel value. The OEM CPS represents an
+# unset code as 0xFFFFFF in raw memory and as a blank field in the UI.
+# When a code is set, the OEM also writes 0xA0 into the adjacent flag
+# byte; when the code is cleared, that flag byte is restored to 0xFF.
+FHSS_CODE_NULL = 0xFFFFFF
+FHSS_CODE_FLAG_ACTIVE = 0xA0
+FHSS_CODE_FLAG_NULL = 0xFF
+
+
+def _fhss_code_to_text(raw_code):
+ raw = int(raw_code)
+ if raw == FHSS_CODE_NULL:
+ return ""
+ return "%06X" % (raw & 0x7FFFFF)
+
+
+def _validate_fhss_code(value):
+ s = str(value).strip()
+ if s == "":
+ return value
+ try:
+ v = int(s, 16)
+ except ValueError:
+ raise InvalidValueError(
+ "FHSS Code must be a hex value (e.g. 1A2B3C) or blank")
+ if not (0 <= v <= 0x7FFFFF):
+ raise InvalidValueError(
+ "FHSS Code must be between 000000 and 7FFFFF")
+ return value
+
+
MEM_FORMAT = """
struct {
lbcd rxfreq[4]; // 0-3
@@ -71,9 +103,9 @@ struct {
bcl:1, // BCL
scan:1, // Scan 0 = Skip, 1 = Scan
am_modulation:1, // Per chan AM modulation
- learning:1; // Learning
- lbcd code[3]; // 0-2 Code
- u8 unknown6; // 3
+ learning:1; // FHSS Learning
+ ul24 code; // 0-2 FHSS Code (little-endian, 0-0x7FFFFF)
+ u8 code_flag; // 3 0xA0 when Code set, 0xFF when blank
char name[12]; // 4-F 12-character Alpha Tag
} memory[%d];
@@ -183,16 +215,17 @@ struct {
tailcode:1; // Tail Code (RT-470L)
u8 unknown_9023; // 9023
u8 single_mode ; // 9024 Single Mode (RT-900 BT)
- u8 unknown_9025; // 9025
+ u8 unknown_9025; // 9025 Always 0x01 on all RT-900 variants
u8 unknown_9026; // 9026
u8 unknown_9027; // 9027
- u8 unknown_9028; // 9028
+ u8 zone_or_channel; // 9028 Zone or Channel (RT-920 fw V0.16)
+ // 0: Zone mode, 1: Channel mode
u8 unused_9029:6, // 9029
qtsave:2; // QT Save Type
- u8 skey2_sp; // 902A Skey2 Short
- u8 skey2_lp; // 902B Skey2 Long
- u8 skey3_sp; // 902C Skey3 Short
- u8 skey3_lp; // 902D Skey3 Long
+ u8 skey2_sp0; // 902A Skey2 Short RT-900BT
+ u8 skey2_sp1; // 902B Skey2 Short, Long RT-900BT
+ u8 skey2_lp; // 902C Skey2 Long, Skey3 Short RT-900BT
+ u8 skey3_sp; // 902D Skey3 Short
u8 topkey_sp; // 902E Top Key (RT-470L)
u8 unused_902f:6, // 902F
rxendtail:2; // RX END TAIL (RT-470)
@@ -200,7 +233,7 @@ struct {
u8 noise_reduction; // 9031 NOISE REDUCTION
u8 unknown_9032; // 9032
u8 unknown_9033; // 9033
- u8 unknown_9034; // 9034
+ u8 fm_interrupt; // 9034
u8 unknown_9035; // 9035
u8 unknown_9036; // 9036
u8 unknown_9037; // 9037
@@ -222,8 +255,8 @@ struct {
#seekto 0xA020;
struct {
- u8 code[5]; // 5-character DTMF Encoder Groups
- u8 unused[11];
+ u8 code[6]; // 6-character DTMF PTT-IDs
+ u8 unused[10];
} pttid[15];
#seekto 0xD000; // radio operationg mode
@@ -243,10 +276,10 @@ TXPOWER_LOW = 0x02
ABR_LIST = ["On", "5 seconds", "10 seconds", "15 seconds", "20 seconds",
"30 seconds", "1 minute", "2 minutes", "3 minutes"]
-ALMODE_LIST = ["Site", "Tone", "Code"]
+ALMODE_LIST = ["On Site", "Send Sound", "Send Code"]
AUTOLK_LIST = ["Off"] + ABR_LIST[1:4]
DTMFSPEED_LIST = ["50 ms", "100 ms", "200 ms", "300 ms", "500 ms"]
-DTMFST_LIST = ["Off", "KeyBoard Side Tone", "ANI Side Tone", "KB ST + ANI ST"]
+DTMFST_LIST = ["Off", "DT-ST", "ANI-ST", "DT+ANI"]
DUALTX_LIST = ["Off", "A", "B"]
LANGUAGE_LIST = ["English", "Chinese"]
MDF_LIST = ["Name", "Frequency", "Channel"]
@@ -427,12 +460,12 @@ class RT900BT(chirp_common.CloneModeRadio):
("Default", 0xff), ("GMRS", 0xa5),
("PMR", 0x66), ("144-146/430-440", 0x55),
("Super", 0x56), ("Factory", 0x00),
- ("unknown Mode 2", 0x28)
+ ("unknown Mode 2", 0x28),
]
POWER_LEVELS = [
chirp_common.PowerLevel("High", watts=8.00),
chirp_common.PowerLevel("Middle", watts=4.00),
- chirp_common.PowerLevel("Low", watts=1.00)
+ chirp_common.PowerLevel("Low", watts=1.00),
]
SKEY_LIST = ["Radio",
@@ -442,7 +475,7 @@ class RT900BT(chirp_common.CloneModeRadio):
"NOAA",
"SOS",
"Switch AM/FM",
- "Bluetooth"]
+ "Bluetooth",]
SKEY_SP_LIST = SKEY_LIST
_upper = 999 # fw 1.20 expands from 512 to 999 channels_steps,
@@ -465,7 +498,7 @@ class RT900BT(chirp_common.CloneModeRadio):
(0x8000, 0x8040),
(0x9000, 0x9040),
(0xA000, 0xA140),
- (0xD000, 0xD040) # Radio mode hidden setting
+ (0xD000, 0xD040), # Radio mode hidden setting
]
_calibration = (0xF000, 0xF250) # Calibration data
@@ -475,13 +508,18 @@ class RT900BT(chirp_common.CloneModeRadio):
_has_am_per_channel = True
_has_am_switch = not _has_am_per_channel
_has_single_mode = True
+ _has_zone_or_channel = False
+ _has_zone_names = False
+ _has_sp0 = True # spkey addresses are shifted -1
+ _has_hf = False
+
_valid_chars = chirp_common.CHARSET_ALPHANUMERIC + \
"`~!@#$%^&*()-=_+[]\\{}|;':\",./<>?"
_steps = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0, 8.33]
_step_map = [("2.5 K", 0), ("5.0 K", 1), ("6.25 K", 2), ("8.33 K", 8),
("10.0 K", 3), ("12.5 K", 4), ("20.0 K", 5), ("25.0 K", 6),
- ("50.0 K", 7)]
+ ("50.0 K", 7),]
_bandwidth_list = ["Wide (25 KHz)", "Narrow (12.5 KHz)"]
_offset_list = ["Off", "+", "-"]
_rx_modulation_list = ["FM", "AM"]
@@ -519,6 +557,8 @@ class RT900BT(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
do_upload(self)
+ except errors.RadioError:
+ raise
except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
@@ -538,144 +578,181 @@ class RT900BT(chirp_common.CloneModeRadio):
# Menu 12: TOT
rs = RadioSettingValueList(TOT_LIST, current_index=_settings.tot)
rset = MemSetting("settings.tot", "Time Out Timer", rs)
+ rset.set_doc("Set the Time Out Timer for transmit (Seconds).")
basic.append(rset)
# Menu 00: SQL
rs = RadioSettingValueInteger(0, 9, _settings.sql)
rset = MemSetting("settings.sql", "Squelch Level", rs)
+ rset.set_doc("Set the receive squelch level. Setting to zero will "
+ "disable the squlech.")
basic.append(rset)
# Menu 13: VOX
rs = RadioSettingValueList(OFF1TO9_LIST, current_index=_settings.vox)
rset = MemSetting("settings.vox", "VOX", rs)
+ rset.set_doc("Set the VOX sensitivity level.")
basic.append(rset)
# Menu 39: VOX DELAY
rs = RadioSettingValueList(VOXD_LIST, current_index=_settings.voxd)
rset = MemSetting("settings.voxd", "VOX Delay", rs)
+ rset.set_doc("Set the VOX delay time (Seconds).")
basic.append(rset)
# Menu 15: VOICE
rs = RadioSettingValueBoolean(_settings.voice)
rset = MemSetting("settings.voice", "Voice Prompts", rs)
+ rset.set_doc("Set the radio voice prompts.")
basic.append(rset)
# Menu 17: LANGUAGE
rs = RadioSettingValueList(LANGUAGE_LIST,
current_index=_settings.language)
rset = MemSetting("settings.language", "Language", rs)
+ rset.set_doc("Set the radio menu and voice promopts language.")
basic.append(rset)
# Menu 23: ABR
rs = RadioSettingValueList(ABR_LIST, current_index=_settings.abr)
rset = MemSetting("settings.abr", "Auto BackLight", rs)
+ rset.set_doc("Set the radio Backlight auto switch off time (Seconds).")
basic.append(rset)
# Menu 19: SC-REV
rs = RadioSettingValueList(SCREV_LIST, current_index=_settings.screv)
rset = MemSetting("settings.screv", "Scan Resume Method", rs)
+ rset.set_doc("Set the Scan Resume method: TO (time scanning), "
+ "CO (carrier detect), SE (search scanning).")
basic.append(rset)
# Menu 10: SAVE
rs = RadioSettingValueList(SAVE_LIST,
current_index=_settings.save)
rset = MemSetting("settings.save", "Battery Save Mode", rs)
+ rset.set_doc("Set the Battery power save mode.")
basic.append(rset)
# Menu 42: MDF-A
rs = RadioSettingValueList(MDF_LIST, current_index=_settings.mdfa)
rset = MemSetting("settings.mdfa", "Memory Display Format A", rs)
+ rset.set_doc("Set A band display mode.")
basic.append(rset)
# Menu 43: MDF-B
rs = RadioSettingValueList(MDF_LIST, current_index=_settings.mdfb)
rset = MemSetting("settings.mdfb", "Memory Display Format B", rs)
+ rset.set_doc("Set B band display mode.")
basic.append(rset)
# Menu 33: DTMFST (DTMF ST)
rs = RadioSettingValueList(DTMFST_LIST, current_index=_settings.dtmfst)
rset = MemSetting("settings.dtmfst", "DTMF Side Tone", rs)
+ rset.set_doc("Set how DTMF tones are heard when a PTT ID DTMF Code "
+ "is sent.")
basic.append(rset)
# Menu 37: PTT-LT
rs = RadioSettingValueList(PTTLT_LIST, current_index=_settings.pttlt)
rset = MemSetting("settings.pttlt", "PTT Delay", rs)
+ rset.set_doc("Set the PTT delay time.")
basic.append(rset)
# Menu 36: TONE
rs = RadioSettingValueList(TONE_LIST, current_index=_settings.tone)
rset = MemSetting("settings.tone", "Tone-burst Frequency", rs)
+ rset.set_doc("Set the Tone-burst Frequency.")
basic.append(rset)
# Mneu 29: POWER ON MSG
rs = RadioSettingValueList(PONMSG_LIST, current_index=_settings.ponmsg)
rset = MemSetting("settings.ponmsg", "Power On Message", rs)
+ rset.set_doc("Set the Power On Message.")
basic.append(rset)
# Menu 46: STE
rs = RadioSettingValueBoolean(_settings.ste)
rset = MemSetting("settings.ste",
"Squelch Tail Eliminate (HT to HT)", rs)
+ rset.set_doc("Set the Squelch Tail Eliminate for HT to HT "
+ "communication.")
basic.append(rset)
# Menu 40: RP-STE
rs = RadioSettingValueList(RPSTE_LIST, current_index=_settings.rpste)
rset = MemSetting("settings.rpste",
"Squelch Tail Eliminate (repeater)", rs)
+ rset.set_doc("Set the Squelch Tail Eliminate time for repeater "
+ "communication.")
basic.append(rset)
# Menu 41: RPT-RL
rs = RadioSettingValueList(RPSTE_LIST, current_index=_settings.rptrl)
rset = MemSetting("settings.rptrl", "STE Repeater Delay", rs)
+ rset.set_doc("Set the delay time for Squelch Tail Eliminate "
+ "when using a repeater.")
basic.append(rset)
# Menu 38: MENU EXIT TIME
rs = RadioSettingValueList(MENUQUIT_LIST,
current_index=_settings.menuquit)
rset = MemSetting("settings.menuquit", "Menu Auto Quit", rs)
+ rset.set_doc("Set the time for the radio to automatically exit the "
+ "menu system.")
basic.append(rset)
# Menu 34: AUTOLOCK
rs = RadioSettingValueList(AUTOLK_LIST, current_index=_settings.autolk)
rset = MemSetting("settings.autolk", "Key Auto Lock", rs)
+ rset.set_doc("Set the time for the radio to automatically lock "
+ "the keypad.")
basic.append(rset)
- # Menu 28: CDCSS SAVE MODE
+ # Menu 28: CTCSS SAVE MODE
rs = RadioSettingValueList(QTSAVE_LIST, current_index=_settings.qtsave)
rset = MemSetting("settings.qtsave", "QT Save Type", rs)
+ rset.set_doc("Set how the CTCSS/DCS codes are saved to a channel.")
basic.append(rset)
# Menu 47: AL-MODE
rs = RadioSettingValueList(ALMODE_LIST, current_index=_settings.almode)
rset = MemSetting("settings.almode", "Alarm Mode", rs)
+ rset.set_doc("Set how the radio will send an Alarm.")
basic.append(rset)
# Menu 11: ROGER
rs = RadioSettingValueList(ROGER_LIST, current_index=_settings.roger)
rset = MemSetting("settings.roger", "Roger", rs)
+ rset.set_doc("Set the Roger Beep mode for when the PTT is released.")
basic.append(rset)
- # Menu 44: Alarm Mode
+ # Menu 44: Alarm ON/OFF
rs = RadioSettingValueBoolean(_settings.alarmsound)
rset = MemSetting("settings.alarmsound", "Alarm Sound", rs)
+ rset.set_doc("Enable to allow the radio to send an alarm.")
basic.append(rset)
- # Menu 44: TDR
- rs = RadioSettingValueBoolean(_settings.tdr)
- rset = MemSetting("settings.tdr", "TDR", rs)
- basic.append(rset)
+ if self._has_hf:
+ s1 = "FM/AM/SSB Radio"
+ s2 = "Allow access to FM/AM/SSB RX channels on radio."
+ else:
+ s1 = "FM Radio"
+ s2 = "Allow access to FM broadcast RX channels on radio."
rs = RadioSettingValueInvertedBoolean(not _settings.fmradio)
- rset = MemSetting("settings.fmradio", "FM Radio", rs)
+ rset = MemSetting("settings.fmradio", s1, rs)
+ rset.set_doc(s2)
basic.append(rset)
rs = RadioSettingValueBoolean(_settings.kblock)
rset = MemSetting("settings.kblock", "KB Lock", rs)
+ rset.set_doc("Enable radio keypad locked by default.")
basic.append(rset)
# Menu 16: BEEP PROMPT
rs = RadioSettingValueBoolean(_settings.beep)
rset = MemSetting("settings.beep", "Beep", rs)
+ rset.set_doc("Enable radio keypad Beep when pressing keys.")
basic.append(rset)
dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
@@ -693,26 +770,31 @@ class RT900BT(chirp_common.CloneModeRadio):
for i in range(0, 15):
_codeobj = self._memobj.pttid[i].code
_code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
- rs = RadioSettingValueString(0, 5, _code, False)
+ rs = RadioSettingValueString(0, 6, _code, False)
rs.set_charset(DTMF_CHARS)
rset = RadioSetting("pttid/%i.code" % i,
"PTT-ID Code %i" % (i + 1), rs)
- rset.set_apply_callback(apply_code, self._memobj.pttid[i], 5)
+ rset.set_apply_callback(apply_code, self._memobj.pttid[i], 6)
+ rset.set_doc("Set the PTT-ID % i Code DTMF sequence." % (i + 1))
dtmf.append(rset)
rs = RadioSettingValueList(DTMFSPEED_LIST,
current_index=_dtmf.dtmfon)
- rset = MemSetting("dtmf.dtmfon", "DTMF Speed (on)", rs)
+ rset = MemSetting("dtmf.dtmfon", "DTMF Speed (On)", rs)
+ rset.set_doc("Set the duration for how long each DMTF tone is ON.")
dtmf.append(rset)
rs = RadioSettingValueList(DTMFSPEED_LIST,
current_index=_dtmf.dtmfoff)
- rset = MemSetting("dtmf.dtmfoff", "DTMF Speed (off)", rs)
+ rset = MemSetting("dtmf.dtmfoff", "DTMF Speed (Off)", rs)
+ rset.set_doc("Set the duration for how long the pause is between "
+ "DTMF tones.")
dtmf.append(rset)
rs = RadioSettingValueList(
PTTID_LIST, current_index=_settings.pttid)
rset = MemSetting("settings.pttid", "PTT ID", rs)
+ rset.set_doc("Set when the PTT-ID is to be sent.")
dtmf.append(rset)
spec = RadioSettingGroup("spec", self.MODEL + " Specific")
@@ -734,6 +816,7 @@ class RT900BT(chirp_common.CloneModeRadio):
'and back ON to have the MODE changes take full effect.\n'
'DO NOT attempt to edit any settings until uploading to and '
'downloading from the radio with the new operating MODE.')
+ rset.set_doc("Set the radio's Operating Mode.")
spec.append(rset)
if self._has_bt_denoise:
@@ -741,29 +824,57 @@ class RT900BT(chirp_common.CloneModeRadio):
rs = RadioSettingValueBoolean(_settings.noise_reduction)
rset = MemSetting("settings.noise_reduction",
"Noise reduction", rs)
+ rset.set_doc("Set the radio's automatic Noise Reduction feature.")
spec.append(rset)
# Menu 47: Bluetooth
rs = RadioSettingValueBoolean(_settings.bluetooth)
rset = MemSetting("settings.bluetooth", "Bluetooth", rs)
+ rset.set_doc("Enable Bluetooth (BLE). "
+ "Bluetooth can be used to program the radio over a "
+ "BLE connection.")
spec.append(rset)
# Menu 23: PF2 Short
+ if self._has_sp0:
+ skey2_sp = _settings.skey2_sp0
+ key = "settings.skey2_sp0"
+ else:
+ skey2_sp = _settings.skey2_sp1
+ key = "settings.skey2_sp1"
+
rs = RadioSettingValueList(self.SKEY_SP_LIST,
- current_index=_settings.skey2_sp)
- rset = MemSetting("settings.skey2_sp", "PF2 Key (Short Press)", rs)
+ current_index=skey2_sp)
+ rset = MemSetting(key, "PF2 Key (Short Press)", rs)
+ rset.set_doc("Set what a Short Press on the PF2 Key will do.")
spec.append(rset)
# Menu 24: PF2 Long
+ if self._has_sp0:
+ skey2_lp = _settings.skey2_sp1
+ key = "settings.skey2_sp1"
+ else:
+ skey2_lp = _settings.skey2_lp
+ key = "settings.skey2_lp"
+
rs = RadioSettingValueList(
- self.SKEY_LIST, current_index=_settings.skey2_lp)
- rset = MemSetting("settings.skey2_lp", "PF2 Key (Long Press)", rs)
+ self.SKEY_LIST, current_index=skey2_lp)
+ rset = MemSetting(key, "PF2 Key (Long Press)", rs)
+ rset.set_doc("Set what a Long Press on the PF2 Key will do.")
spec.append(rset)
# Menu 25: PF3 Short
+ if self._has_sp0:
+ skey3_sp = _settings.skey2_lp
+ key = "settings.skey2_lp"
+ else:
+ skey3_sp = _settings.skey3_sp
+ key = "settings.skey3_sp"
+
rs = RadioSettingValueList(
- self.SKEY_LIST, current_index=_settings.skey3_sp)
- rset = MemSetting("settings.skey3_sp", "PF3 Key (Short Press)", rs)
+ self.SKEY_LIST, current_index=skey3_sp)
+ rset = MemSetting(key, "PF3 Key (Short Press)", rs)
+ rset.set_doc("Set what a Short Press on the PF3 Key will do.")
spec.append(rset)
if self.MODEL not in ["RT-900_BT", "RT-920"]:
@@ -771,17 +882,44 @@ class RT900BT(chirp_common.CloneModeRadio):
if self._has_am_switch:
rs = RadioSettingValueBoolean(_settings.am_mode)
rset = MemSetting("settings.am_mode", "AM Mode", rs)
+ rset.set_doc("Enable to set the RX modulation mode to AM.")
spec.append(rset)
# Menu 7: TDR - Dual freq standby
rs = RadioSettingValueBoolean(_settings.tdr)
rset = MemSetting("settings.tdr", "TDR - Dual frequency standby", rs)
+ rset.set_doc("Set Dual Frequency Standby (Dual Watch).")
spec.append(rset)
if self._has_single_mode:
- # Menu 51: Single Mode - Single fre channel display
+ # Menu 51: Single Mode - Single freq channel display
rs = RadioSettingValueBoolean(_settings.single_mode)
rset = MemSetting("settings.single_mode", "Single Mode", rs)
+ rset.set_doc("Set radio to display a single frequency/channel.")
+ spec.append(rset)
+
+ if self.MODEL in ["RT-920"]:
+ # Menu 53: FM Interupt
+ rs = RadioSettingValueBoolean(_settings.fm_interrupt)
+ rset = MemSetting("settings.fm_interrupt", "FM Interrupt", rs)
+ rset.set_doc("While using broadcast FM, "
+ "allow incoming RX to interrupt the FM "
+ "broadcast audio.")
+ spec.append(rset)
+
+ if self._has_zone_or_channel:
+ # Menu 10: Zone or Channel
+ rs = RadioSettingValueList(self._zone_or_channel_list,
+ current_index=_settings.zone_or_channel)
+ rset = MemSetting("settings.zone_or_channel",
+ "Zone or Channel", rs)
+ rset.set_warning(
+ "Changing this setting requires saving the .IMG file and "
+ "opening it back up to enable/disable the Banks (Zones) "
+ "preview tab.") # and the Zone Name sub-menu.")
+ rset.set_doc(
+ "Set Zone Mode (static banks) or Full Channel "
+ "(flat) memmory channel mode.")
spec.append(rset)
# VFO A/B settings
@@ -793,21 +931,24 @@ class RT900BT(chirp_common.CloneModeRadio):
# Menu 21: VFO A/B BCL (Busy lock)
rs = RadioSettingValueBoolean(_settings.busy_lock)
rset = MemSetting("settings.busy_lock", "BCL", rs)
+ rset.set_doc("Set Busy Channel Lockout. When selected, disables PTT "
+ "when the current frequency is busy.")
abblock.append(rset)
# Menu 30 VFO DTMF code
rs = RadioSettingValueList(
PTTID_LIST,
current_index=_settings.pttid
- # current_index=self._memobj.vfodtmf.code
)
rset = MemSetting("settings.pttid", "DTMF Code", rs)
+ rset.set_doc("Set when to send PTT-ID DTMF codes")
abblock.append(rset)
# Menu 42: TX-A/B
rs = RadioSettingValueList(
DUALTX_LIST, current_index=_settings.dualtx)
rset = MemSetting("settings.dualtx", "TX-A/B", rs)
+ rset.set_doc("Set which Band will be used for TX when PTT is pressed.")
abblock.append(rset)
# VFO A channel sub menu
@@ -818,6 +959,7 @@ class RT900BT(chirp_common.CloneModeRadio):
rs = RadioSettingValueList(WORKMODE_LIST,
current_index=_settings.vfomra)
rset = MemSetting("settings.vfomra", "Work Mode", rs)
+ rset.set_doc("Set A Band Work Mode.")
achannel.append(rset)
# VFO A Freq
@@ -860,23 +1002,27 @@ class RT900BT(chirp_common.CloneModeRadio):
rs.set_validate_callback(freq_validate)
rset = RadioSetting("vfo.a.freq", "Frequency", rs)
rset.set_apply_callback(apply_freq, vfo.a)
+ rset.set_doc("Set A Band VFO frequency.")
achannel.append(rset)
# Menu 01: A Step
rs = RadioSettingValueMap(self._step_map, vfo.a.step)
rset = MemSetting("vfo.a.step", "Tuning Step", rs)
+ rset.set_doc("Set A Band frequency Tuning Step.")
achannel.append(rset)
# Menu 02: TX Power
rs = RadioSettingValueList([str(x) for x in self.POWER_LEVELS],
current_index=vfo.a.txpower)
rset = MemSetting("vfo.a.txpower", "TX Power", rs)
+ rset.set_doc("Set A Band TX Power.")
achannel.append(rset)
# Menu 05: Wide/Narrow Band
rs = RadioSettingValueList(self._bandwidth_list,
current_index=vfo.a.widenarr)
rset = MemSetting("vfo.a.widenarr", "Bandwidth", rs)
+ rset.set_doc("Set A Band Bandwidth.")
achannel.append(rset)
# Menu 12,13: RX ctcss/dtsc
@@ -886,6 +1032,7 @@ class RT900BT(chirp_common.CloneModeRadio):
rset = RadioSetting("vfo.a.rxtone", "RX CTCSS/DCS", rs)
rset.set_apply_callback(self.apply_vfo_tone,
self._memobj.vfo.a, "rxtone")
+ rset.set_doc("Set A Band RX CTCSS or DCS code.")
achannel.append(rset)
# Menu 14,15: TX ctcss/dtsc
@@ -895,6 +1042,7 @@ class RT900BT(chirp_common.CloneModeRadio):
rset = RadioSetting("vfo.a.txtone", "TX CTCSS/DCS", rs)
rset.set_apply_callback(self.apply_vfo_tone,
self._memobj.vfo.a, "txtone")
+ rset.set_doc("Set A Band TX CTCSS or DCS code.")
achannel.append(rset)
# Menu 16: Voice Privacy (encryption)
@@ -902,6 +1050,7 @@ class RT900BT(chirp_common.CloneModeRadio):
current_index=vfo.a.voicepri)
rset = RadioSetting("vfo.a.voicepri",
"Voice Privacy - Subtone Encryption", rs)
+ rset.set_doc("Set A Band Voice Privacy - subtone voice encryption.")
achannel.append(rset)
def convert_bytes_to_offset(bytes):
@@ -921,23 +1070,27 @@ class RT900BT(chirp_common.CloneModeRadio):
convert_bytes_to_offset(vfo.a.offset))
rset = RadioSetting("vfo.a.offset", "Offset (MHz)", rs)
rset.set_apply_callback(apply_offset, vfo.a)
+ rset.set_doc("Set A Band TX frequency offset value.")
achannel.append(rset)
# Menu 27: Offset direction
rs = RadioSettingValueList(self._offset_list,
current_index=vfo.a.sftd)
rset = MemSetting("vfo.a.sftd", "Offset Direction", rs)
+ rset.set_doc("Set A Band TX frequency offset direction.")
achannel.append(rset)
# Menu 29: S-Code DTMF 1-15
rs = RadioSettingValueList(self._scode_list,
current_index=vfo.a.scode)
rset = MemSetting("vfo.a.scode", "S-CODE", rs)
+ rset.set_doc("Set the A Band DTMF code ID to use for PTT ID.")
achannel.append(rset)
# Menu 45: Scramble
rs = RadioSettingValueMap(self._scramble_map, vfo.a.scramble)
rset = MemSetting("vfo.a.scramble", "Scramble", rs)
+ rset.set_doc("Set A Band voice Scramble.")
achannel.append(rset)
# Menu 50: RX Modulation
@@ -945,6 +1098,7 @@ class RT900BT(chirp_common.CloneModeRadio):
rs = RadioSettingValueList(self._rx_modulation_list,
current_index=vfo.a.rxmod)
rset = MemSetting("vfo.a.rxmod", "RX Modulation", rs)
+ rset.set_doc("Set A Band RX Modulation.")
achannel.append(rset)
# VFO B channel sub menu
@@ -955,6 +1109,7 @@ class RT900BT(chirp_common.CloneModeRadio):
rs = RadioSettingValueList(WORKMODE_LIST,
current_index=_settings.vfomrb)
rset = MemSetting("settings.vfomrb", "Work Mode", rs)
+ rset.set_doc("Set B Band Work Mode.")
bchannel.append(rset)
# VFO B Freq
@@ -963,23 +1118,27 @@ class RT900BT(chirp_common.CloneModeRadio):
rs.set_validate_callback(freq_validate)
rset = RadioSetting("vfo.b.freq", "Frequency", rs)
rset.set_apply_callback(apply_freq, vfo.b)
+ rset.set_doc("Set B Band VFO frequency.")
bchannel.append(rset)
# Menu 01: B Step
rs = RadioSettingValueMap(self._step_map, vfo.b.step)
rset = MemSetting("vfo.b.step", "Tuning Step", rs)
+ rset.set_doc("Set B Band frequency Tuning Step.")
bchannel.append(rset)
# Menu 02: TX Power
rs = RadioSettingValueList([str(x) for x in self.POWER_LEVELS],
current_index=vfo.b.txpower)
rset = MemSetting("vfo.b.txpower", "TX Power", rs)
+ rset.set_doc("Set B Band TX Power.")
bchannel.append(rset)
# Menu 05: Wide/Narrow Band
rs = RadioSettingValueList(self._bandwidth_list,
current_index=vfo.b.widenarr)
rset = MemSetting("vfo.b.widenarr", "Bandwidth", rs)
+ rset.set_doc("Set B Band Bandwidth.")
bchannel.append(rset)
# Menu 12,13: RX ctcss/dtsc
@@ -989,6 +1148,7 @@ class RT900BT(chirp_common.CloneModeRadio):
rset = RadioSetting("vfo.b.rxtone", "RX CTCSS/DCS", rs)
rset.set_apply_callback(self.apply_vfo_tone,
self._memobj.vfo.b, "rxtone")
+ rset.set_doc("Set B Band RX CTCSS or DCS code.")
bchannel.append(rset)
# Menu 14,15: TX ctcss/dtsc
@@ -998,6 +1158,7 @@ class RT900BT(chirp_common.CloneModeRadio):
rset = RadioSetting("vfo.b.txtone", "TX CTCSS/DCS", rs)
rset.set_apply_callback(self.apply_vfo_tone,
self._memobj.vfo.b, "txtone")
+ rset.set_doc("Set B Band TX CTCSS or DCS code.")
bchannel.append(rset)
# Menu 16: Voice Privacy (encryption)
@@ -1005,6 +1166,7 @@ class RT900BT(chirp_common.CloneModeRadio):
current_index=vfo.b.voicepri)
rset = MemSetting("vfo.b.voicepri",
"Voice Privacy - Subtone Encryption", rs)
+ rset.set_doc("Set B Band Voice Privacy - subtone voice encryption.")
bchannel.append(rset)
# Menu 26: Offset
@@ -1012,22 +1174,26 @@ class RT900BT(chirp_common.CloneModeRadio):
convert_bytes_to_offset(vfo.b.offset))
rset = RadioSetting("vfo.b.offset", "Offset (MHz)", rs)
rset.set_apply_callback(apply_offset, vfo.b)
+ rset.set_doc("Set B Band TX frequency offset value.")
bchannel.append(rset)
# Menu 27: Offset direction
rs = RadioSettingValueList(self._offset_list, current_index=vfo.b.sftd)
rset = MemSetting("vfo.b.sftd", "Offset Direction", rs)
+ rset.set_doc("Set B Band TX frequency offset direction.")
bchannel.append(rset)
# Menu 29: S-Code DTMF 1-15
rs = RadioSettingValueList(
self._scode_list, current_index=vfo.b.scode)
rset = MemSetting("vfo.b.scode", "S-CODE", rs)
+ rset.set_doc("Set the B Band DTMF code ID to use for PTT ID.")
bchannel.append(rset)
# Menu 45: Scramble
rs = RadioSettingValueMap(self._scramble_map, vfo.b.scramble)
rset = MemSetting("vfo.b.scramble", "Scramble", rs)
+ rset.set_doc("Set B Band voice Scramble.")
bchannel.append(rset)
# Menu 50: RX Modulation
@@ -1035,8 +1201,83 @@ class RT900BT(chirp_common.CloneModeRadio):
rs = RadioSettingValueList(self._rx_modulation_list,
current_index=vfo.b.rxmod)
rset = MemSetting("vfo.b.rxmod", "RX Modulation", rs)
+ rset.set_doc("Set B Band RX Modulation.")
bchannel.append(rset)
+ # SSB Settings, RT-920, BJ7800 Only
+ if self._has_hf:
+ ssbblock = RadioSettingGroup("ssbblock", "FM/AM/SSB Modulation")
+ spec.append(ssbblock)
+
+ # HF mode submenu
+ modes = RadioSettingSubGroup("modes", "Modes")
+ ssbblock.append(modes)
+
+ # SSB Work Mode
+ ssbwm = self._memobj.ssb_settings
+ rs = RadioSettingValueList(
+ self._ssb_workmode_list,
+ current_index=ssbwm.workmode
+ )
+ rset = MemSetting("ssb_settings.workmode", "Work Mode", rs)
+ rset.set_doc("Set HF Workmode.")
+ modes.append(rset)
+
+ # SSB Modulation Mode
+ ssb = self._memobj.ssb
+ rs = RadioSettingValueList(
+ self._ssb_modulation_list,
+ current_index=ssb.modulation
+ )
+ rset = MemSetting("ssb.modulation", "Modulation Mode", rs)
+ rset.set_doc("Set HF RX Modulation Mode.")
+ modes.append(rset)
+
+ # AM mode submenu
+ amsettings = RadioSettingSubGroup("amsettings", "AM Settings")
+ ssbblock.append(amsettings)
+
+ # AM Step Freq
+ stepfreq = self._memobj.stepfreq
+ rs = RadioSettingValueList(
+ self._am_step_freq_list,
+ current_index=stepfreq.am
+ )
+ rset = MemSetting("stepfreq.am", "Step Freq", rs)
+ rset.set_doc("Set HF AM RX Step Frequency.")
+ amsettings.append(rset)
+
+ # AM RX Gain
+ rs = RadioSettingValueList(
+ self._rx_gain_list,
+ current_index=ssb.am_rxgain
+ )
+ rset = MemSetting("ssb.am_rxgain", "RX Gain", rs)
+ rset.set_doc("Set HF AM RX Gain value.")
+ amsettings.append(rset)
+
+ # SSB mode submenu
+ ssbsettings = RadioSettingSubGroup("ssbsettings", "SSB Settings")
+ ssbblock.append(ssbsettings)
+
+ # SSB Step Freq
+ rs = RadioSettingValueList(
+ self._ssb_step_freq_list,
+ current_index=stepfreq.ssb
+ )
+ rset = MemSetting("stepfreq.ssb", "Step Freq", rs)
+ rset.set_doc("Set HF SSB RX Step Frequency.")
+ ssbsettings.append(rset)
+
+ # SSB RX Gain
+ rs = RadioSettingValueList(
+ self._rx_gain_list,
+ current_index=stepfreq.ssb_rxgain
+ )
+ rset = MemSetting("stepfreq.ssb_rxgain", "RX Gain", rs)
+ rset.set_doc("Set HF SSB RX Gain value.")
+ ssbsettings.append(rset)
+
return group
@classmethod
@@ -1089,7 +1330,7 @@ class RT900BT(chirp_common.CloneModeRadio):
"""Parse the tone data to encode from UI to mem"""
match mode:
case "" | None:
- memval.set_raw("\x00\x00")
+ memval.fill_raw(b"\x00")
case "Tone" | "TSQL":
memval.set_value(int(value * 10))
case "DTCS":
@@ -1100,26 +1341,10 @@ class RT900BT(chirp_common.CloneModeRadio):
else:
index += 0x6A
memval.set_value(index)
- except IndexError:
+ except ValueError:
msg = "DTCS Code '%d' is not supported" % value
LOG.error(msg)
raise errors.RadioError(msg)
- case "Cross":
- txmode, rxmode = mem.cross_mode.split("->", 1)
-
- if txmode == "Tone":
- memval.set_value(int(mem.rtone * 10))
- elif txmode == "DTCS":
- memval.set_value(DTCS.index(mem.dtcs) + 1)
- else:
- memval.set_value(0)
-
- if rxmode == "Tone":
- memval.set_value(int(mem.ctone * 10))
- elif rxmode == "DTCS":
- memval.set_value(DTCS.index(mem.rx_dtcs) + 1)
- else:
- memval.set_value(0)
case _:
raise Exception("Internal error: invalid mode '%s'" % mode)
@@ -1160,7 +1385,7 @@ class RT900BT(chirp_common.CloneModeRadio):
code = index + 0x6a
elif tone.endswith('N'): # normal
code = index + 1
- except IndexError:
+ except (IndexError, ValueError):
msg = "Unknown CTCSS/DTC tone: %s" % tone
LOG.exception(msg)
raise InvalidValueError(msg)
@@ -1174,6 +1399,9 @@ class RT900BT(chirp_common.CloneModeRadio):
rf.valid_tuning_steps = self._steps
return rf
+ def get_raw_memory(self, number):
+ return repr(self._memobj.memory[number - 1])
+
def get_memory(self, number):
"""Get the mem representation from the radio image"""
_mem = self._memobj.memory[number - 1]
@@ -1184,7 +1412,7 @@ class RT900BT(chirp_common.CloneModeRadio):
# Memory number
mem.number = number
- if _mem.get_raw()[:1] == b"\xFF":
+ if _mem.get_raw()[:1] == b"\xff":
mem.empty = True
return mem
@@ -1193,7 +1421,7 @@ class RT900BT(chirp_common.CloneModeRadio):
if mem.freq == 0:
mem.empty = True
# tx freq can be blank
- if _mem.txfreq.get_raw() == b"\xFF\xFF\xFF\xFF":
+ if _mem.txfreq.get_raw() == b"\xff\xff\xff\xff":
# TX freq not set
mem.offset = 0
mem.duplex = "off"
@@ -1265,16 +1493,39 @@ class RT900BT(chirp_common.CloneModeRadio):
# BCL (Busy Channel Lockout)
rs = RadioSettingValueBoolean(_mem.bcl)
rset = RadioSetting("bcl", "BCL", rs)
+ rset.set_doc("Set Busy Channel Lockout. When selected, disables PTT "
+ "when the current channel is busy.")
+ mem.extra.append(rset)
+
+ # LearnFHSS (per-channel learn / FHSS flag). The OEM CPS labels
+ # this column "LearnFHSS"; the open-source firmware reads the
+ # same bit as chFlag3.b0 / fhssFlag (Core/Radio.c).
+ rs = RadioSettingValueBoolean(_mem.learning)
+ rset = RadioSetting("learning", "Learn FHSS", rs)
+ rset.set_doc("Enable to allow automatic FHSS code selection.")
+ mem.extra.append(rset)
+
+ # FHSS Code (24-bit little-endian, range 0x000000-0x7FFFFF).
+ # Displayed and accepted as a 6-digit uppercase hex string, or
+ # blank to clear the code (raw 0xFFFFFF). Validation is hoisted
+ # to a module-level function so this RadioSetting stays
+ # picklable for clipboard copy.
+ rs = RadioSettingValueString(0, 6, _fhss_code_to_text(_mem.code))
+ rs.set_validate_callback(_validate_fhss_code)
+ rset = RadioSetting("fhss_code", "FHSS Code (hex)", rs)
+ rset.set_doc("Enter manual FHSS Code using HEX digits.")
mem.extra.append(rset)
# PTT-ID
rs = RadioSettingValueList(PTTID_LIST, current_index=_mem.pttid)
rset = RadioSetting("pttid", "PTT ID", rs)
+ rset.set_doc("Set when the PTT-ID is to be sent.")
mem.extra.append(rset)
# Signal (DTMF Encoder Group #)
rs = RadioSettingValueList(PTTIDCODE_LIST, current_index=_mem.scode)
rset = RadioSetting("scode", "PTT ID Code", rs)
+ rset.set_doc("Set the DTMF code ID to use for PTT ID.")
mem.extra.append(rset)
return mem
@@ -1283,15 +1534,15 @@ class RT900BT(chirp_common.CloneModeRadio):
_mem = self._memobj.memory[mem.number - 1]
if mem.empty:
- _mem.set_raw("\xff" * 32)
+ _mem.fill_raw(b"\xff")
return
- _mem.set_raw("\x00" * 16 + "\xFF" * 16)
+ _mem.set_raw("\x00" * 16 + "\xff" * 16)
_mem.rxfreq = mem.freq / 10
if mem.duplex == "off":
- _mem.txfreq.fill_raw(b"\xFF")
+ _mem.txfreq.fill_raw(b"\xff")
elif mem.duplex == "split":
_mem.txfreq = mem.offset / 10
elif mem.duplex == "+":
@@ -1306,7 +1557,7 @@ class RT900BT(chirp_common.CloneModeRadio):
try:
_mem.name[i] = mem.name[i]
except IndexError:
- _mem.name[i] = "\xFF"
+ _mem.name[i] = "\xff"
txmode = rxmode = ''
txval = rxval = 0
@@ -1348,7 +1599,19 @@ class RT900BT(chirp_common.CloneModeRadio):
_mem.narrow = 0b1
for setting in mem.extra:
- setattr(_mem, setting.get_name(), setting.value)
+ if setting.get_name() == 'fhss_code':
+ # Mirror OEM CPS: blank input clears Code (0xFFFFFF) and
+ # restores the adjacent flag byte to 0xFF; any value
+ # writes Code and sets the flag byte to 0xA0.
+ s = str(setting.value).strip()
+ if s == "":
+ _mem.code = FHSS_CODE_NULL
+ _mem.code_flag = FHSS_CODE_FLAG_NULL
+ else:
+ _mem.code = int(s, 16)
+ _mem.code_flag = FHSS_CODE_FLAG_ACTIVE
+ else:
+ setattr(_mem, setting.get_name(), setting.value)
def validate_memory(self, mem):
msgs = []
@@ -1378,7 +1641,7 @@ class RT900(RT900BT):
# ==========
# Notice to developers:
# The RT-900 support in this driver is currently based upon stock
- # factory firmware.
+ # factory firmware, V0.14P
# ==========
"""Radtel RT-900 (without Bluetooth)"""
@@ -1389,8 +1652,9 @@ class RT900(RT900BT):
_has_am_per_channel = False
_has_am_switch = not _has_am_per_channel
_has_single_mode = False
+ _has_hf = False
- _upper = 512 # fw 1.04P expands from 256 to 512 channels
+ _upper = 999 # fw V1.14P expands from 512 to 999 channels
SKEY_LIST = ["FM Radio",
"TX Power Level",
@@ -1412,7 +1676,8 @@ class RT900(RT900BT):
def get_prompts(cls):
rp = super().get_prompts()
rp.experimental = \
- ('This driver is a beta version for the RT-900\n'
+ ('This driver is a beta version for the RT-900'
+ ' running Firmware V0.14P\n'
'\n'
'Please save an unedited copy of your first successful\n'
'download to a CHIRP Radio Images(*.img) file.\n\n'
@@ -1425,7 +1690,7 @@ class RT900(RT900BT):
class RT910BT(RT900BT):
# ==========
# Notice to developers:
- # The RT-910 BT support in this driver is currently based upon Vx.yyP
+ # The RT-910 BT support in this driver is currently based upon V0.24P
# firmware with 15 banks/zones of 64 channels steps.
# ==========
"""Radtel RT-910_BT 960"""
@@ -1465,7 +1730,7 @@ class RT910BT(RT900BT):
def get_features(self):
rf = super().get_features()
- rf.has_bank = True # Firmware Vx.yyP supports 15
+ rf.has_bank = True # Firmware V0.24P supports 15
# "static zones" of 64 frequencies
rf.valid_tuning_steps = self._steps
return rf
@@ -1475,7 +1740,7 @@ class RT910BT(RT900BT):
rp = super().get_prompts()
rp.experimental = \
('This driver is a beta version for the RT-910 BT'
- ' running Firmware V0x.yy\n'
+ ' running Firmware V0.24P\n'
'\n'
'Please save an unedited copy of your first successful\n'
'download to a CHIRP Radio Images(*.img) file.\n\n'
@@ -1488,21 +1753,21 @@ class RT910BT(RT900BT):
class RT910(RT910BT):
# ==========
# Notice to developers:
- # The RT-910 support in this driver is currently based upon V0.09P
- # firmware with 15 banks/zones of 64 channels steps.
+ # The RT-910 support in this driver is currently based upon V0.11
+ # firmware with 15 banks/zones of 64 channel steps.
# ==========
- """Radtel RT-910 512 (without Bluetooth)"""
+ """Radtel RT-910 960 (without Bluetooth)"""
VENDOR = "Radtel"
MODEL = "RT-910"
- _upper = 512 # fw V0.09P supports 512 channels
+ _upper = 960 # fw V0.11 supports 960 channels
_mem_params = (_upper, # number of channels
)
_ranges = [
- (0x0000, 0x4000), # 8 zones of 64 frequencies,
- # equals 512 channels of 32 bytes each
- # 8 * 64 * 32 = 0x4000
+ (0x0000, 0x7800), # 15 zones of 64 frequencies,
+ # equals 960 channels of 32 bytes each
+ # 15 * 64 * 32 = 0x7800
(0x8000, 0x8040),
(0x9000, 0x9040),
(0xA000, 0xA140),
@@ -1512,17 +1777,18 @@ class RT910(RT910BT):
_has_bt_denoise = False
_has_am_per_channel = True
_has_am_switch = not _has_am_per_channel
- _has_single_mode = False
+ _has_single_mode = True
+ _has_hf = False
def get_bank_model(self):
- return chirp_common.StaticBankModel(self, banks=8)
+ return chirp_common.StaticBankModel(self, banks=15)
@classmethod
def get_prompts(cls):
rp = super().get_prompts()
rp.experimental = \
('This driver is a beta version for the RT-910'
- ' Non Bluetooth running Firmware V0.09\n'
+ ' Non-Bluetooth running Firmware V0.11\n'
'\n'
'Please save an unedited copy of your first successful\n'
'download to a CHIRP Radio Images(*.img) file.\n\n'
@@ -1531,19 +1797,47 @@ class RT910(RT910BT):
return rp
+class RT920Bank(chirp_common.NamedBank):
+ """RT-920 Bank"""
+ def get_name(self):
+ """decode bank name from char array into string"""
+ _bank = self._model._radio._memobj.zones[self._index - 1]
+ name = str(_bank.name).rstrip(" \n\t\x00\xff") # remove filler chars
+
+ if len(name) == 0:
+ name = "ZONE %i" % self._index
+
+ return name
+
+ def set_name(self, name):
+ """encode bank name into \xff filled char array"""
+ _bank = self._model._radio._memobj.zones[self._index - 1]
+ _bank.name = name[:len(_bank.name)].rstrip()\
+ .ljust(len(_bank.name), "\xff")
+
+
+class RT920BankModel(chirp_common.StaticBankModel):
+ """RT-920 Bank Model"""
+ def __init__(self, radio, name, banks):
+ super(RT920BankModel, self).__init__(radio, name, banks)
+ self._num_banks = banks
+ self._rf = radio.get_features()
+ self._banks = []
+ for i in range(self._num_banks):
+ self._banks.append(RT920Bank(self, i + 1, "ZONE %i" % (i + 1)))
+
+
@directory.register
class RT920(RT900BT):
# ==========
# Notice to developers:
- # The RT-920 support in this driver is currently based upon V0.14P
- # firmware with 15 banks/zones of 64 channels steps.
- # Also known to work on the SHJ H28Y Pro V0.07 firmware
+ # The RT-920 support in this driver is currently based upon V0.18
+ # firmware with 10 banks/zones of 99 channels.
# ==========
"""Radtel RT-920"""
VENDOR = "Radtel"
MODEL = "RT-920"
- # _magic = b"PROGRAMBT80U" # RT-900
_magic = b"PROGRAMBT11U" # RT-920
# step of 1.25 to allow UK CB Freqs
_steps = [1.25, 2.5, 5.0, 6.25, 8.33, 10.0, 12.5, 20.0, 25.0, 50.0]
@@ -1556,44 +1850,580 @@ class RT920(RT900BT):
"SOS",
"Spectrum"]
SKEY_SP_LIST = SKEY_LIST + ["PTTB"]
+ _zone_or_channel_list = ["Zone Mode", "Full Channel"]
+ _ssb_modulation_list = [
+ "FM",
+ "AM",
+ "LSB",
+ "USB",
+ "CW",
+ ]
+ _ssb_workmode_list = [
+ "VFO Mode",
+ "CH Mode",
+ ]
+ _am_step_freq_list = [
+ "1K",
+ "5K",
+ "9K",
+ "10K",
+ "100K",
+ ]
+ _ssb_step_freq_list = [
+ "1K",
+ "5K",
+ "10K",
+ "100K",
+ "500K",
+ "1000K",
+ ]
+ _rx_gain_list = ["AGC"] + \
+ ["%ddB" % x for x in range(0, -36, -1)]
- _upper = 960 # fw V0.24P supports 960 channels
+ _upper = 990 # fw V0.18 supports 990 channels
_mem_params = (_upper, # number of channels
)
+ _banks = 10
+ _ranges = [
+ (0x0000, 0x7BC0), # 10 zones of 99 frequencies,
+ # equals 990 channels of 32 bytes each
+ # 10 * 99 * 32 = 0x7BC0
+ (0x8000, 0x8040),
+ (0x9000, 0x9040),
+ (0xA000, 0xA140),
+ (0xB000, 0xB400), # FM, AM, HF frequencies
+ (0xC000, 0xC400), # FM, AM, HF names
+ (0xC800, 0XC8A0), # static bank names, 10 banks * 16 bytes ea = 0xA0
+ (0xD000, 0xD040), # Radio mode hidden setting
+ ]
+
+ _rt920_specific_fmt = """
+ #seekto 0xb000;
+ // 2 byte fm vfo freq
+ struct {
+ ul16 freq;
+ } fm_vfo;
+ // 15ea 2 byte fm chan freq
+ struct {
+ ul16 freq;
+ } fm_freqs[%d];
+
+ #seekto 0xb021; // SSB settings
+ struct {
+ u8 workmode; // VFO/Ch
+ } ssb_settings;
+
+ #seekto 0xb022;
+ // 2 byte am vfo freq
+ struct {
+ ul16 freq;
+ } am_vfo;
+ // 15ea 2 byte am chan freq
+ struct {
+ ul16 freq;
+ } am_freqs[%d];
+
+ #seekto 0xb043; // ssb
+ struct {
+ u8 modulation; // modulation mode
+ u8 am_rxgain; // AM RX gain
+ } ssb;
+
+ #seekto 0xb045;
+ // 5 byte hf vfo chan
+ struct {
+ ul16 freq;
+ u8 bandwidth;
+ il16 beatfreq; // can be negitive
+ } hf_vfo;
+ // 15ea 5 byte hf chans
+ struct {
+ ul16 freq;
+ u8 bandwidth;
+ il16 beatfreq; // can be negitive
+ } hf_freqs[%d];
+
+ #seekto 0xb096;
+ struct {
+ u8 ssb;
+ u8 am;
+ u8 ssb_rxgain;
+ } stepfreq;
+
+ #seekto 0xc010; // 15ea 16 byte fm chan names
+ struct {
+ char name[12];
+ u8 unused[4];
+ } fm_names[%d];
+
+ #seekto 0xc110; // 15ea 16 byte am chan names (RT-920 fw v 0.xx)
+ struct {
+ char name[12];
+ u8 unused[4];
+ } am_names[%d];
+
+ #seekto 0xc210; // 15ea 16 byte ssb chan names (RT-920 fw v 0.xx)
+ struct {
+ char name[12];
+ u8 unused[4];
+ } hf_names[%d];
+
+ #seekto 0xC800; // 10ea 16 byte zone names (RT-920 fw V0.17)
+ struct {
+ char name[10];
+ u8 unused[6];
+ } zones[%d];
+ """
+
+ _has_bt_denoise = True
+ _has_am_per_channel = True
+ _has_am_switch = not _has_am_per_channel
+ _has_single_mode = True
+ _has_zone_or_channel = True
+ _has_zone_names = True
+ _has_sp0 = False # spkey addresses are not shifted
+ _has_hf = True
+
+ def get_bank_model(self):
+ return RT920BankModel(self, "Zones", self._banks)
+
+ def get_features(self):
+ rf = super().get_features()
+ # Firmware V0.18 supports 10
+ # optional "static zones" of 99 frequencies
+ # or 990 flat chanels
+ if self._memobj is not None and hasattr(self._memobj, "settings"):
+ rf.has_bank = not self._memobj.settings.zone_or_channel
+ else:
+ rf.has_bank = False # default to flat mode if settings not init'ed
+
+ rf.has_bank_names = self._has_zone_names
+ rf.valid_tuning_steps = self._steps
+ rf.has_sub_devices = self._has_hf
+ return rf
+
+ def process_mmap(self):
+ AUX_CHANS_FM = AUX_CHANS_AM = AUX_CHANS_HF = 15
+ mem_format = MEM_FORMAT % self._mem_params + \
+ self._rt920_specific_fmt % (
+ AUX_CHANS_FM,
+ AUX_CHANS_AM,
+ AUX_CHANS_HF,
+ AUX_CHANS_FM,
+ AUX_CHANS_AM,
+ AUX_CHANS_HF,
+ self._banks,
+ )
+ self._memobj = bitwise.parse(mem_format, self._mmap)
+
+ @classmethod
+ def get_prompts(cls):
+ rp = super().get_prompts()
+ rp.experimental = \
+ ('This driver is a beta version for the RT-920'
+ ' running Firmware V0.18\n'
+ '\n'
+ 'Please save an unedited copy of your first successful\n'
+ 'download to a CHIRP Radio Images(*.img) file.\n\n'
+ 'PROCEED AT YOUR OWN RISK!'
+ )
+ return rp
+
+ def get_sub_devices(self):
+ return [RT920VhfUfh(self._mmap),
+ RT920FM(self._mmap),
+ RT920AM(self._mmap),
+ RT920HF(self._mmap),
+ ]
+
+
+class RT920VhfUfh(RT920):
+ """Radtel RT-920 VHF/UHF subdevice"""
+ VENDOR = "Radtel"
+ MODEL = "RT-920"
+ VARIANT = "VHF/UHF"
+
+
+class RT920FM(RT920):
+ """Radtel RT-920 FM broadcast subdevice"""
+ VENDOR = "Radtel"
+ MODEL = "RT-920"
+ VARIANT = "FM Broadcast"
+
+ _upper = 15
+ _mem_params = (_upper, # number of channels
+ )
+ _valid_bands = [(64000000, 108000000)] # in Mhz, 64.0-108 MHz
+ SPECIAL_CHANNELS = ["VFO"]
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.valid_bands = self._valid_bands
+ rf.memory_bounds = (1, self._upper)
+ rf.can_delete = True
+ rf.can_odd_split = False
+ rf.has_bank = False
+ rf.has_bank_index = False
+ rf.has_bank_names = False
+ rf.has_comment = False
+ rf.has_cross = False
+ rf.has_ctone = False
+ rf.has_dtcs = False
+ rf.has_dtcs_polarity = False
+ rf.has_mode = True
+ rf.has_offset = False
+ rf.has_settings = False
+ rf.has_sub_devices = False
+ rf.has_tuning_step = False
+ rf.valid_characters = RT900._valid_chars
+ rf.valid_cross_modes = []
+ rf.valid_dtcs_codes = []
+ rf.valid_dtcs_pols = []
+ rf.valid_duplexes = []
+ rf.valid_modes = ["AM", "WFM", "Auto"]
+ rf.valid_name_length = 12
+ rf.valid_skips = []
+ rf.valid_special_chans = self.SPECIAL_CHANNELS
+ rf.valid_tuning_steps = [
+ 1.0, 2.5, 5.0, 6.25, 8.33, 10.0, 12.5, 20.0, 25.0, 50.0,
+ ]
+ rf.valid_tmodes = []
+ rf.valid_tones = []
+ return rf
+
+ def get_raw_memory(self, number):
+ if isinstance(number, str):
+ return repr(self._memobj.fm_vfo)
+ else:
+ return (repr(self._memobj.fm_freqs[number - 1]) +
+ repr(self._memobj.fm_names[number - 1]))
+
+ def get_memory(self, number):
+ mem = chirp_common.Memory()
+
+ if isinstance(number, str):
+ mem.number = self._upper + self.SPECIAL_CHANNELS.index(number) + 1
+ mem.extd_number = number
+ _mem = self._memobj.fm_vfo
+ else:
+ mem.number = number
+ _mem = self._memobj.fm_freqs[number - 1]
+ _name = self._memobj.fm_names[number - 1]
+
+ freq = int(_mem.freq) * 10000
+
+ if freq == 0:
+ mem.empty = True
+ return mem
+
+ mem.freq = freq
+
+ if mem.number > self._upper:
+ mem.immutable += ["name"]
+ else:
+ mem.name = str(_name.name).rstrip("\xff ")
+
+ mem.mode = "WFM"
+
+ mem.immutable += ["mode", "ctone", "rtone"]
+ return mem
+
+ def set_memory(self, mem):
+
+ if mem.number > self._upper:
+ _mem = self._memobj.fm_vfo
+ else:
+ _mem = self._memobj.fm_freqs[mem.number - 1]
+ _name = self._memobj.fm_names[mem.number - 1]
+
+ if mem.empty:
+ _mem.freq.fill_raw(b"\x00")
+ if mem.number <= self._upper:
+ _name.name.fill_raw(b"\xff")
+ return
+
+ _mem.freq = int(mem.freq / 10000)
+
+ if mem.number <= self._upper:
+ _name.name = mem.name.ljust(12, "\xff")
+
+
+class RT920AM(RT920FM):
+ """Radtel RT-920 AM broadcast subdevice"""
+ VENDOR = "Radtel"
+ MODEL = "RT-920"
+ VARIANT = "AM Broadcast"
+
+ _valid_bands = [(153000, 279000), # in Mhz, 153-279 KHz
+ (520000, 1710000), # 520-1710 KHz
+ (2300000, 26100000), # 2300-26100 KHz
+ ]
+
+ def get_raw_memory(self, number):
+ if isinstance(number, str):
+ return repr(self._memobj.am_vfo)
+ else:
+ return (repr(self._memobj.am_freqs[number - 1]) +
+ repr(self._memobj.am_names[number - 1]))
+
+ def get_memory(self, number):
+ mem = chirp_common.Memory()
+
+ if isinstance(number, str):
+ mem.number = self._upper + self.SPECIAL_CHANNELS.index(number) + 1
+ mem.extd_number = number
+ _mem = self._memobj.am_vfo
+ else:
+ mem.number = number
+ _mem = self._memobj.am_freqs[number - 1]
+ _name = self._memobj.am_names[number - 1]
+
+ freq = int(_mem.freq) * 1000
+
+ if freq == 0:
+ mem.empty = True
+ return mem
+
+ mem.freq = freq
+
+ if mem.number > self._upper:
+ mem.immutable += ["name"]
+ else:
+ mem.name = str(_name.name).rstrip("\xff ")
+
+ mem.mode = "AM"
+
+ mem.immutable += ["mode", "ctone", "rtone"]
+ return mem
+
+ def set_memory(self, mem):
+
+ if mem.number > self._upper:
+ _mem = self._memobj.am_vfo
+ else:
+ _mem = self._memobj.am_freqs[mem.number - 1]
+ _name = self._memobj.am_names[mem.number - 1]
+
+ if mem.empty:
+ _mem.freq.fill_raw(b"\x00")
+ if mem.number <= self._upper:
+ _name.name.fill_raw(b"\xff")
+ return
+
+ _mem.freq = int(mem.freq / 1000)
+
+ if mem.number <= self._upper:
+ _name.name = mem.name.ljust(12, "\xff")
+
+
+class RT920HF(RT920FM):
+ """Radtel RT-920 HF LSB, USB, CW subdevice"""
+ VENDOR = "Radtel"
+ MODEL = "RT-920"
+ VARIANT = "HF"
+
+ _valid_bands = [(150000, 30000000)] # in Mhz, 150-30000 KHz
+
+ _ssb_bandwidth_list = [
+ "0.5K", "1.0K", "1.2K", "2.2K", "3.0K", "4.0K",
+ ]
+
+ def get_raw_memory(self, number):
+ if isinstance(number, str):
+ return repr(self._memobj.hf_vfo)
+ else:
+ return (repr(self._memobj.hf_freqs[number - 1]) +
+ repr(self._memobj.hf_names[number - 1]))
+
+ def get_memory(self, number):
+ mem = chirp_common.Memory()
+
+ if isinstance(number, str):
+ mem.number = self._upper + self.SPECIAL_CHANNELS.index(number) + 1
+ mem.extd_number = number
+ _mem = self._memobj.hf_vfo
+ else:
+ mem.number = number
+ _mem = self._memobj.hf_freqs[number - 1]
+ _name = self._memobj.hf_names[number - 1]
+
+ freq = int(_mem.freq) * 1000
+
+ if freq == 0:
+ mem.empty = True
+ return mem
+
+ mem.freq = freq
+
+ if mem.number > self._upper:
+ mem.immutable += ["name"]
+ else:
+ mem.name = str(_name.name).rstrip("\xff ")
+
+ # use Modulation Mode from SSB settings to determine Mode
+ # defaut to LSB if AM or FM is selected as SSB Modulation Mode
+ _ssb_mod = self._memobj.ssb.modulation
+ mem.mode = "LSB" if self._ssb_modulation_list[_ssb_mod] \
+ in ["AM", "FM"] else \
+ self._ssb_modulation_list[_ssb_mod]
+
+ mem.immutable += ["mode", "ctone", "rtone"]
+
+ mem.extra = RadioSettingGroup("Extra", "extra")
+
+ # Bandwidth
+ rs = RadioSettingValueList(
+ self._ssb_bandwidth_list,
+ current_index=int(_mem.bandwidth)
+ )
+ rset = RadioSetting("bandwidth", "Bandwidth", rs)
+ rset.set_doc("SSB Channel Bandwidth (KHz).")
+ mem.extra.append(rset)
+
+ # Beat Freq
+ rs = RadioSettingValueInteger(-32760, 27240, int(_mem.beatfreq), 1)
+ rset = RadioSetting("beatfreq", "Beat Freq Offset (Hz)", rs)
+ rset.set_doc("SSB Beat Frequency Offset (Hz).")
+ mem.extra.append(rset)
+
+ return mem
+
+ def set_memory(self, mem):
+
+ if mem.number > self._upper:
+ _mem = self._memobj.hf_vfo
+ else:
+ _mem = self._memobj.hf_freqs[mem.number - 1]
+ _name = self._memobj.hf_names[mem.number - 1]
+
+ if mem.empty:
+ _mem.fill_raw(b"\x00")
+ if mem.number <= self._upper:
+ _name.name.fill_raw(b"\xff")
+ return
+
+ _mem.freq = int(mem.freq / 1000)
+
+ if mem.number <= self._upper:
+ _name.name = mem.name.ljust(12, "\xff")
+
+ for setting in mem.extra:
+ setattr(_mem, setting.get_name(), int(setting.value))
+
+
+@directory.register
+class RadioddityGS10B(RT900BT):
+ # ==========
+ # Radioddity GS-10B: RT-900 BT variant with 256 channels.
+ # Same magic (PROGRAMBT80U), fingerprints, and protocol as the
+ # RT-900 BT. Memory layout is identical but with fewer channels.
+ # Based on firmware V0.03.
+ # ==========
+ """Radioddity GS-10B"""
+ VENDOR = "Radioddity"
+ MODEL = "GS-10B"
+
+ _upper = 256 # 256 channels
+ _has_single_mode = False
+
+ _mem_params = (_upper, # number of channels
+ )
+
+ _ranges = [
+ (0x0000, 0x2000), # 256 channels of 32 bytes each
+ # 256 * 32 = 0x2000
+ (0x8000, 0x8040),
+ (0x9000, 0x9040),
+ (0xA000, 0xA140),
+ (0xD000, 0xD040), # Radio mode hidden setting
+ ]
+
+ @classmethod
+ def get_prompts(cls):
+ rp = super().get_prompts()
+ rp.experimental = \
+ ('This driver is a beta version for the Radioddity GS-10B\n'
+ '\n'
+ 'Please save an unedited copy of your first successful\n'
+ 'download to a CHIRP Radio Images(*.img) file.\n\n'
+ 'PROCEED AT YOUR OWN RISK!'
+ )
+ return rp
+
+
+@directory.register
+class BJ7800(RT920):
+ # ==========
+ # Notice to developers:
+ # The BJ7800 support in this driver is currently based upon V0.15P
+ # firmware with 15 banks/zones of 64 channels.
+ # Should also work with the SHU H28Y Pro
+ # ==========
+ """Bajeton BJ7800"""
+ VENDOR = "Bajeton"
+ MODEL = "BJ7800"
+
+ _upper = 960 # fw V0.15P supports 960 channels
+ _mem_params = (_upper, # number of channels
+ )
+ _banks = 15
_ranges = [
(0x0000, 0x7800), # 15 zones of 64 frequencies,
# equals 960 channels of 32 bytes each
- # 15 * 64 * 32 = 0x7800
+ # 15 * 64 * 32 = 0X7800
(0x8000, 0x8040),
(0x9000, 0x9040),
+ (0xB000, 0xB400), # FM, AM, HF frequencies
+ (0xC000, 0xC400), # FM, AM, HF names
(0xA000, 0xA140),
- (0xD000, 0xD040) # Radio mode hidden setting
+ (0xD000, 0xD040), # Radio mode hidden setting
]
_has_bt_denoise = True
_has_am_per_channel = True
_has_am_switch = not _has_am_per_channel
_has_single_mode = False
+ _has_zone_or_channel = False
+ _has_zone_names = False # dosen't have named zones like the RT-920
+ _has_hf = True
def get_bank_model(self):
- return chirp_common.StaticBankModel(self, banks=15)
+ return chirp_common.StaticBankModel(self, banks=self._banks)
def get_features(self):
rf = super().get_features()
- rf.has_bank = True # Firmware V0.14P supports 15
- # "static zones" of 64 frequencies
+ # Firmware V0.15P supports 15
+ # "static zones" of 64 frequencies
+ # for 960 channels
+ rf.has_bank = True
+ rf.has_bank_names = self._has_zone_names
rf.valid_tuning_steps = self._steps
+ rf.has_sub_devices = self._has_hf
return rf
@classmethod
def get_prompts(cls):
rp = super().get_prompts()
rp.experimental = \
- ('This driver is a beta version for the RT-920'
- ' running Firmware V0.14P\n'
+ ('This driver is a beta version for the BJ7800'
+ ' running Firmware V0.15P\n'
'\n'
'Please save an unedited copy of your first successful\n'
'download to a CHIRP Radio Images(*.img) file.\n\n'
'PROCEED AT YOUR OWN RISK!'
)
return rp
+
+ def get_sub_devices(self):
+ return [BJ7800VhfUfh(self._mmap),
+ RT920FM(self._mmap),
+ RT920AM(self._mmap),
+ RT920HF(self._mmap),
+ ]
+
+
+class BJ7800VhfUfh(BJ7800):
+ """Bajeton BJ7800 VHF/UHF subdevice"""
+ VENDOR = "Bajeton"
+ MODEL = "BJ7800"
+ VARIANT = "VHF/UHF"
diff --git a/chirp/drivers/radtel_t18.py b/chirp/drivers/radtel_t18.py
index 3337d18..9ee106b 100644
--- a/chirp/drivers/radtel_t18.py
+++ b/chirp/drivers/radtel_t18.py
@@ -264,7 +264,7 @@ def _t18_enter_programming_mode(radio):
raise errors.RadioError("Error communicating with radio")
if not ack:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")
@@ -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()
@@ -563,6 +566,10 @@ class T18Radio(chirp_common.CloneModeRadio):
mem.extra = RadioSettingGroup("Extra", "extra")
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 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 \
@@ -730,12 +737,23 @@ class T18Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("squelchlevel", "Squelch level",
RadioSettingValueInteger(
0, 9, _settings.squelchlevel))
+ 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)
rs = RadioSetting("timeouttimer", "Timeout timer",
RadioSettingValueList(
self.TIMEOUTTIMER_LIST,
current_index=_settings.timeouttimer))
+ 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)
if self.MODEL == "RB18" or self.MODEL == "RB618":
@@ -746,6 +764,13 @@ class T18Radio(chirp_common.CloneModeRadio):
self.MODEL == "BF-T20FRS":
rs = RadioSetting("settings2.scan", "Scan",
RadioSettingValueBoolean(_settings2.scan))
+ rs.set_doc(
+ "Enables channel scanning. The radio steps through the "
+ "programmed channels, stops on the first one it finds busy "
+ "and resumes a few seconds after that channel goes quiet. "
+ "Channels marked to skip are left out, and at least two "
+ "channels have to remain in the scan list for scanning to "
+ "start.")
basic.append(rs)
else:
rs = RadioSetting("scanmode", "Scan mode",
@@ -772,6 +797,10 @@ class T18Radio(chirp_common.CloneModeRadio):
self.MODEL == "BF-T20FRS":
rs = RadioSetting("settings2.voicesw", "Voice prompts",
RadioSettingValueBoolean(_settings2.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)
elif self.MODEL == "RT15":
rs = RadioSetting("voiceprompt", "Voice prompts",
@@ -789,6 +818,12 @@ class T18Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("batterysaver", "Battery saver",
RadioSettingValueBoolean(_settings.batterysaver))
+ 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)
if self.MODEL not in ["RB29",
@@ -799,6 +834,9 @@ class T18Radio(chirp_common.CloneModeRadio):
]:
rs = RadioSetting("beep", "Beep",
RadioSettingValueBoolean(_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)
if self.MODEL == "RB19" or self.MODEL == "RB19P" \
@@ -991,38 +1029,69 @@ class T18Radio(chirp_common.CloneModeRadio):
RadioSettingValueList(
SIDEKEYV8A_LIST,
current_index=_settings.sidekey2))
+ rs.set_doc(
+ "Chooses what the programmable key does: Monitor opens the "
+ "squelch so that signals too weak to break it can still be "
+ "heard, High/Low Power switches the transmit power, and "
+ "Alarm triggers the emergency alarm.")
basic.append(rs)
rs = RadioSetting("settings2.rxemergency", "RX emergency",
RadioSettingValueBoolean(_settings2.rxemergency))
+ rs.set_doc(
+ "Lets this radio respond to an emergency alarm sent by "
+ "another radio on the same channel instead of ignoring it.")
basic.append(rs)
rs = RadioSetting("settings2.voiceselect", "Language",
RadioSettingValueList(
VOICE_LIST2,
current_index=_settings2.voiceselect))
+ 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("settings2.hivoltnotx",
"High voltage inhibit TX",
RadioSettingValueBoolean(_settings2.hivoltnotx))
+ rs.set_doc(
+ "Blocks transmitting while the battery voltage is above the "
+ "safe range, which protects the radio when an out-of-spec "
+ "battery or charger is fitted.")
basic.append(rs)
rs = RadioSetting("settings2.lovoltnotx", "Low voltage inhibit TX",
RadioSettingValueBoolean(_settings2.lovoltnotx))
+ rs.set_doc(
+ "Blocks transmitting once the battery is nearly flat. "
+ "Transmitting draws far more current than receiving, so "
+ "this keeps the remaining charge available for listening.")
basic.append(rs)
rs = RadioSetting("settings2.vox", "VOX",
RadioSettingValueBoolean(_settings2.vox))
+ 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("settings2.voxnotxonrx", "RX disable VOX",
RadioSettingValueBoolean(_settings2.voxnotxonrx))
+ rs.set_doc(
+ "Suspends VOX while a signal is being received, so that "
+ "your own voice does not key the transmitter on top of the "
+ "station you are listening to.")
basic.append(rs)
rs = RadioSetting("settings2.voxgain", "Vox Gain",
RadioSettingValueInteger(
1, 5, _settings2.voxgain))
+ 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)
if self.MODEL == "RB29" or self.MODEL == "RB629":
@@ -1486,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_c2.py b/chirp/drivers/retevis_c2.py
new file mode 100644
index 0000000..73c583f
--- /dev/null
+++ b/chirp/drivers/retevis_c2.py
@@ -0,0 +1,1349 @@
+# Copyright 2026 Tony Gies <tgies@tgies.net>
+#
+# 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/>.
+
+"""Retevis C2 GMRS radio driver.
+
+The C2 uses a DLE-stuffed STX/ETX serial protocol at 115200 baud.
+"""
+
+import logging
+import time
+
+
+from chirp import bandplan_na, bitwise, chirp_common, directory
+from chirp import errors, memmap
+from chirp.settings import (
+ MemSetting,
+ RadioSetting,
+ RadioSettingGroup,
+ RadioSettings,
+ RadioSettingValueBoolean,
+ RadioSettingValueInteger,
+ RadioSettingValueList,
+ RadioSettingValueMap,
+ RadioSettingValueString,
+)
+
+LOG = logging.getLogger(__name__)
+
+MEM_FORMAT = """
+#seekto 0x0000;
+u8 ident_data[28]; // 0x0000 firmware/hardware ident (read-only)
+ul32 local_id; // 0x001C
+ul32 settings_0020; // 0x0020 bit0=voice prompt
+ul32 unknown_0024; // 0x0024
+ul32 power_save; // 0x0028
+ul32 unknown_002c; // 0x002C
+ul32 unknown_0030; // 0x0030
+ul32 unknown_0034; // 0x0034
+ul32 vox_packed; // 0x0038 vox_level*4 + (1=on, 2=off)
+ul32 unknown_003c; // 0x003C
+ul32 sk_short; // 0x0040 key assignment
+ul32 sk_long; // 0x0044 key assignment (0xFFFFFFFF=None)
+ul32 pf1_short; // 0x0048 key assignment
+ul32 pf1_long; // 0x004C key assignment
+ul32 pf2_short; // 0x0050 key assignment
+ul32 pf2_long; // 0x0054 key assignment
+
+#seekto 0x0080;
+ul32 tot; // 0x0080 seconds (0=Off)
+ul32 unknown_0084; // 0x0084
+ul32 freq_step; // 0x0088 Hz
+
+#seekto 0x0090;
+ul32 scan_mode; // 0x0090 0=Search, 1=Carrier, 2=Time
+ul32 keytone; // 0x0094 0=Off, 1=On
+
+#seekto 0x0118;
+ul32 vox_delay; // 0x0118 ms
+
+#seekto 0x019C;
+ul32 unknown_019c[4]; // 0x019C
+
+#seekto 0x01BC;
+ul32 recorder; // 0x01BC 0=Off, 1=On
+ul32 work_mode; // 0x01C0 0=Channel, 1=Memory
+ul32 unknown_01c4; // 0x01C4
+ul32 squelch; // 0x01C8 1-9 (Sq Level)
+ul32 unknown_01cc; // 0x01CC
+ul32 unknown_01d0; // 0x01D0
+ul32 ai_denoise_packed; // 0x01D4 bits 0:1 = AI denoise enable
+ul32 unknown_01d8; // 0x01D8
+ul32 ctcss_tail_tone; // 0x01DC CTCSS tail freq (freq*40+2)
+ul32 cdcss_tail_tone; // 0x01E0 CDCSS tail freq (freq*40+2)
+ul32 no_ctcss_tail_freq; // 0x01E4 NO CTCSS tail freq (Hz*10)
+u8 unknown_01e8[6]; // 0x01E8
+il16 micgain_analog; // 0x01EE -3 to 3
+
+#seekto 0x0330;
+char dtmf_local_id[8]; // 0x0330
+u8 unknown_0338; // 0x0338
+u8 unknown_0339; // 0x0339
+char dtmf_sep_code; // 0x033A
+char dtmf_group_code; // 0x033B
+ul16 unknown_033c; // 0x033C
+ul16 dtmf_first_time; // 0x033E 0.5ms units (e.g. 400=200ms)
+
+#seekto 0x0347;
+u8 tot_warning; // 0x0347 value << 4 (0=Off, 1-10)
+
+#seekto 0x035C;
+ul32 settings_035c; // 0x035C byte0=tx_start_beep, bytes1-3=pri_ch
+
+#seekto 0x0360;
+struct {
+ u8 cfg_unk0:1, // +00 bit 7
+ highpower:1, // bit 6
+ cfg_unk1:1, // bit 5
+ busylock:1, // bit 4
+ talkaround:1, // bit 3
+ cfg_unk2:3; // bits 2-0 (default 0b101)
+ ul16 bandwidth; // +01 25000=Wide, 12500=Narrow
+ u8 pad0; // +03
+ ul32 rxfreq; // +04 Hz
+ ul32 rxtone; // +08 custom encoding
+ ul32 txfreq; // +0C Hz
+ ul32 txtone; // +10 custom encoding
+ u8 unknown1[20]; // +14
+ char name[12]; // +28
+ ul16 unk15:1, // bit 15
+ compand:1, // bit 14
+ unk13_12:2, // bits 13-12
+ unk11:1, // bit 11 (default 1)
+ unk10:1, // bit 10
+ dtmf_group:4, // bits 9-6 (0-indexed)
+ ani:1, // bit 5
+ scanadd:1, // bit 4
+ unk3:1, // bit 3
+ pttid:3; // bits 2-0 (1=Off,2=Start,3=End,4=Both)
+ ul16 scramble; // +36 Hz (0xFFFF=Off)
+} memory[256];
+
+#seekto 0x3C64;
+ul32 dwatch; // 0x3C64 1=Off, 2=On
+
+#seekto 0x3C80;
+ul32 group_call_ch; // 0x3C80 0-indexed channel number
+ul32 noaa_ch; // 0x3C84 0-indexed (0=WX1 .. 6=WX7)
+
+#seekto 0x3D34;
+ul32 noaa_freq; // 0x3D34 NOAA freq in Hz (auto from noaa_ch)
+
+#seekto 0x3D74;
+ul32 key_lock; // 0x3D74 ms (0=Off)
+ul32 settings_3d78; // 0x3D78 bits0:1=fm_auto
+ // (1=On,2=Off), bit2=allow_tx_beep
+ul32 unknown_3d7c; // 0x3D7C
+ul32 unknown_3d80[7]; // 0x3D80
+ul32 lcd_brightness; // 0x3D9C 1-5
+ul32 auto_bl_time; // 0x3DA0 ms
+ul32 apo_time; // 0x3DA4 ms (0=Off)
+ul32 password; // 0x3DA8 pwd*4 + flag (1=on, 0=off)
+ul32 chnameshow; // 0x3DAC 0=Off, 1=On
+ul32 tone_burst; // 0x3DB0 Hz (1750, 2100, etc.)
+ul32 abswitch; // 0x3DB4 0=Auto, 1=On, 2=Off
+ul32 css_packed; // 0x3DB8 bit0=css_vague, bit4=cancel_all_ctdt
+ul32 unknown_3dbc; // 0x3DBC
+ul32 unknown_3dc0; // 0x3DC0
+ul32 show_bat; // 0x3DC4 0=Off, 1=On
+ul32 dtmf_show; // 0x3DC8 0=Off, 1=On
+ul32 unknown_3dcc; // 0x3DCC
+ul32 group_switch; // 0x3DD0 0=Off, 1=On
+ul32 unknown_3dd4; // 0x3DD4
+ul32 noaa_warning; // 0x3DD8 0=Off, 0x40000=On
+"""
+
+# Protocol constants
+STX = 0x02
+ETX = 0x03
+DLE = 0x10
+
+# Bytes that must be DLE-escaped in the protocol
+ESCAPE_MAP = {0x00: 0x13, 0x02: 0x01, 0x03: 0x11, 0x10: 0x12, 0xFF: 0x14}
+UNESCAPE_MAP = {v: k for k, v in ESCAPE_MAP.items()}
+
+# Protocol commands (byte 1 of request/response frames)
+CMD_IDENT = 0x01
+CMD_READ = 0x02
+CMD_WRITE = 0x03
+CMD_VERIFY = 0x04
+CMD_FINALIZE = 0x05
+
+# Table IDs (byte 2 — selects which data table to access)
+TBL_SYSCONFIG = 0x01
+TBL_RFCAL = 0x02
+TBL_SETTINGS = 0x03
+TBL_CHANNELS = 0x04
+TBL_EXTRA = 0x05
+TBL_FINAL = 0x07
+
+# Memory layout — user data region (uploaded back to radio)
+IDENT_SIZE = 28
+SETTINGS_OFFSET = 0x001C
+SETTINGS_SIZE = 836
+CHANNELS_OFFSET = 0x0360
+CHANNEL_SIZE = 56
+NUM_CHANNELS = 256
+EXTRA_OFFSET = 0x3B60
+EXTRA_COUNT = 8
+EXTRA_SIZE = 32
+FINAL_OFFSET = 0x3C60
+FINAL_SIZE = 480
+# Calibration region (downloaded but not uploaded)
+SYSCONFIG_OFFSET = 0x3E40
+SYSCONFIG_SIZE = 1100
+RFCAL_OFFSET = 0x428C
+RFCAL_COUNT = 10
+RFCAL_SIZE = 36
+MEMSIZE = 17396
+
+IMAGE_VERSION = 1
+
+POWER_LEVELS = [
+ chirp_common.PowerLevel("High", watts=5.00),
+ chirp_common.PowerLevel("Low", watts=0.50),
+]
+
+# NOAA WX frequencies
+NOAA_FREQS = [
+ 162550000, # WX1: 162.550 MHz
+ 162400000, # WX2: 162.400 MHz
+ 162475000, # WX3: 162.475 MHz
+ 162425000, # WX4: 162.425 MHz
+ 162450000, # WX5: 162.450 MHz
+ 162500000, # WX6: 162.500 MHz
+ 162525000, # WX7: 162.525 MHz
+]
+
+# Valid GMRS TX frequencies (main channels + repeater outputs)
+GMRS_TX_FREQS = (
+ set(bandplan_na.ALL_GMRS_FREQS) |
+ {f + 5000000 for f in bandplan_na.GMRS_HIRPT}
+)
+
+# Tail elimination frequency options (50.0-260.0 Hz in 0.1 Hz steps)
+TAIL_TONES = [round(50.0 + i * 0.1, 1) for i in range(2101)]
+
+# CTCSS/CDCSS tail freq encoding: freq_hz * 40 + 2
+TAIL_TONE_MAP = [("%.1f" % t, int(round(t * 40)) + 2)
+ for t in TAIL_TONES]
+
+# NO CTCSS tail freq encoding: freq_hz * 10
+NO_CTCSS_TAIL_MAP = [("%.1f" % t, int(round(t * 10)))
+ for t in TAIL_TONES]
+
+# Per-channel setting maps
+PTTID_MAP = [("Off", 1), ("Start", 2), ("End", 3), ("Both", 4)]
+SCRAMBLE_MAP = ([("Off", 0xFFFF)] +
+ [("%d Hz" % f, f) for f in range(2700, 3500, 100)])
+
+# Lists used in get_settings / get_memory
+LIST_NOAA = ["WX%d" % (i + 1) for i in range(7)]
+LIST_PRIORITY_SCAN = ["Off"] + ["CH%03d" % (i + 1) for i in range(256)]
+
+# Valid DTMF symbol charset
+DTMF_CHARS = "0123456789ABCD*#"
+
+
+# --- DCS tone encoding/decoding ---
+
+def _reverse_bits(val, nbits):
+ """Reverse the bit order of an integer."""
+ result = 0
+ for i in range(nbits):
+ if val & (1 << i):
+ result |= (1 << (nbits - 1 - i))
+ return result
+
+
+def _golay_remainder(data_12):
+ """Compute Golay(23,12) check bits using DCS polynomial 0xAE3."""
+ msg = data_12 << 11
+ for i in range(11, -1, -1):
+ if msg & (1 << (i + 11)):
+ msg ^= (0xAE3 << i)
+ return msg & 0x7FF
+
+
+def _dcs_encode(code_oct, pol='N'):
+ """Encode a DCS code and polarity to the C2's 32-bit tone value.
+
+ The radio stores these in a format similar to the DCS wire format.
+
+ The encoding uses a Golay(23,12) codeword with the 9-bit DCS code
+ stored at bits [10:2] of the tone value. The codeword is bit-reversed
+ relative to the standard Golay encoding. Bit 25 indicates inverted
+ polarity. CTCSS and DCS values are distinguished by bit 1 (DCS=1).
+ """
+ code_dec = int(str(code_oct), 8)
+
+ if pol == 'R':
+ # Inverted: compute Golay for the complemented code
+ code_9bit = (~code_dec) & 0x1FF
+ low3 = 0x06
+ else:
+ code_9bit = code_dec
+ low3 = 0x01
+
+ data_12 = (_reverse_bits(code_9bit, 9) << 3) | low3
+ rem = _golay_remainder(data_12)
+ cw23 = (data_12 << 11) | rem
+ cw23_rev = _reverse_bits(cw23, 23)
+ tone = (cw23_rev << 2) | 0x02
+
+ if pol == 'R':
+ # Set inversion flag (bit 25 = bit 1 of byte 3)
+ tone = tone | (0x02 << 24)
+
+ return tone
+
+
+def _dcs_decode(tone_val):
+ """Decode a 32-bit DCS tone value to (code_oct, polarity)."""
+ raw9 = (tone_val >> 2) & 0x1FF
+ inv_flag = (tone_val >> 25) & 1
+ if inv_flag:
+ code = (~raw9) & 0x1FF
+ return int('%o' % code), 'R'
+ else:
+ return int('%o' % raw9), 'N'
+
+
+def _decode_tone(val):
+ """Decode a 32-bit tone value to (mode, value, polarity).
+
+ Returns ('', 0, 'N') for no tone, ('Tone', freq_hz, 'N') for CTCSS,
+ or ('DTCS', code, pol) for DCS.
+ """
+ if val == 0:
+ return '', 0, 'N'
+ if not (val & 0x02):
+ # CTCSS: bit 1 clear, value = tone_hz * 40 + 1
+ tone_hz = (val - 1) / 40.0
+ return 'Tone', tone_hz, 'N'
+ # DCS: bit 1 set
+ code, pol = _dcs_decode(val)
+ return 'DTCS', code, pol
+
+
+def _encode_tone(mode, value, pol):
+ """Encode tone parameters to a 32-bit value."""
+ if mode in ('Tone', 'TSQL'):
+ return int(round(value * 40)) + 1
+ elif mode == 'DTCS':
+ return _dcs_encode(value, pol)
+ return 0
+
+
+# --- Protocol framing ---
+
+def _dle_escape(data):
+ """Apply DLE byte-stuffing to raw data."""
+ result = bytearray()
+ for b in data:
+ if b in ESCAPE_MAP:
+ result.append(DLE)
+ result.append(ESCAPE_MAP[b])
+ else:
+ result.append(b)
+ return bytes(result)
+
+
+def _dle_unescape(data):
+ """Remove DLE byte-stuffing from escaped data."""
+ result = bytearray()
+ i = 0
+ while i < len(data):
+ if data[i] == DLE and i + 1 < len(data):
+ escaped = data[i + 1]
+ if escaped in UNESCAPE_MAP:
+ result.append(UNESCAPE_MAP[escaped])
+ else:
+ result.append(escaped)
+ i += 2
+ else:
+ result.append(data[i])
+ i += 1
+ return bytes(result)
+
+
+def _make_frame(payload):
+ """Build a complete STX/ETX frame with checksum and DLE escaping."""
+ chk = sum(payload) & 0xFF
+ raw = payload + bytes([chk])
+ return bytes([STX]) + _dle_escape(raw) + bytes([ETX])
+
+
+def _parse_frame(frame_data):
+ """Extract and verify payload from a received frame.
+
+ Returns the payload (without checksum) or raises RadioError.
+ """
+ if not frame_data or frame_data[0] != STX or frame_data[-1] != ETX:
+ raise errors.RadioError("Invalid frame")
+ inner = _dle_unescape(frame_data[1:-1])
+ if len(inner) < 2:
+ raise errors.RadioError("Frame too short")
+ payload = inner[:-1]
+ chk = inner[-1]
+ expected = sum(payload) & 0xFF
+ if chk != expected:
+ raise errors.RadioError(
+ "Checksum mismatch: got 0x%02x, expected 0x%02x" %
+ (chk, expected))
+ return payload
+
+
+# --- Serial communication ---
+
+def _read_frame(pipe, timeout=5.0):
+ """Read a complete STX...ETX frame from the serial port.
+
+ Uses byte-at-a-time blocking reads to track DLE byte-stuffing
+ and correctly identify the real ETX terminator.
+ """
+ data = bytearray()
+ in_escape = False
+ start = time.monotonic()
+ while time.monotonic() - start < timeout:
+ try:
+ b = pipe.read(1)
+ except Exception as e:
+ raise errors.RadioError(
+ "Error reading from radio: %s" % e)
+ if not b:
+ continue
+ data.append(b[0])
+ if len(data) == 1:
+ if b[0] != STX:
+ data = bytearray()
+ continue
+ if in_escape:
+ in_escape = False
+ continue
+ if b[0] == DLE:
+ in_escape = True
+ continue
+ if b[0] == ETX:
+ return bytes(data)
+ if data:
+ LOG.debug("Incomplete frame (%d bytes): %s",
+ len(data), data[:20].hex())
+ return b''
+
+
+class NoData(errors.RadioError):
+ """Internal signal that we received nothing from the radio.
+
+ Used to distinguish between no response and incorrect response. Distinct
+ from errors.RadioNoResponse, which is raised _only_ when we have not
+ receieved any response from the radio in this session (compared to just
+ a sudden lack of response to a particular command).
+ """
+ pass
+
+
+def _send_recv(radio, payload):
+ """Send a command and receive the response.
+
+ Retries up to 3 times on timeout to handle occasional
+ timing-related failures on some USB serial adapters.
+ Returns the response payload (header + data, no checksum).
+ """
+ frame = _make_frame(payload)
+ pipe = radio.pipe
+
+ for attempt in range(3):
+ try:
+ pipe.write(frame)
+ pipe.flush()
+ except Exception as e:
+ raise errors.RadioError(
+ "Error communicating with radio: %s" % e)
+
+ resp_frame = _read_frame(pipe)
+ if resp_frame:
+ return _parse_frame(resp_frame)
+
+ LOG.warning("No response on attempt %d", attempt + 1)
+ # Drain any garbage data before retrying
+ try:
+ avail = pipe.in_waiting
+ if avail:
+ pipe.read(avail)
+ except Exception:
+ pass
+
+ raise NoData(
+ "No response from radio after 3 attempts (cmd=%s)" %
+ ' '.join('%02x' % b for b in payload))
+
+
+def _read_block(radio, cmd, table, index):
+ """Read a data block from the radio.
+
+ Returns just the data portion (no header bytes).
+ """
+ payload = bytes([0x01, cmd, table, index])
+ resp = _send_recv(radio, payload)
+ # Response format: [resp_type, cmd, table, index, ...data...]
+ if len(resp) < 4 or resp[1:4] != payload[1:4]:
+ raise errors.RadioError(
+ "Unexpected response header: got %s, expected cmd=%02x "
+ "tbl=%02x idx=%02x" % (resp[:4].hex(), cmd, table, index))
+ return resp[4:]
+
+
+def _write_block(radio, cmd, table, index, data):
+ """Write a data block to the radio."""
+ payload = bytes([0x01, cmd, table, index]) + data
+ frame = _make_frame(payload)
+
+ pipe = radio.pipe
+ try:
+ pipe.write(frame)
+ pipe.flush()
+ except Exception as e:
+ raise errors.RadioError("Error communicating with radio: %s" % e)
+
+ resp_frame = _read_frame(pipe)
+ if not resp_frame:
+ avail = pipe.in_waiting
+ if avail:
+ raw = pipe.read(avail)
+ LOG.error("Got non-frame data: %s", raw.hex())
+ raise errors.RadioError(
+ "No response to write (cmd=%02x tbl=%02x idx=%02x, %d bytes)" %
+ (cmd, table, index, len(data)))
+
+ resp = _parse_frame(resp_frame)
+ if len(resp) < 4 or resp[1:4] != payload[1:4]:
+ raise errors.RadioError(
+ "Unexpected write response: got %s, expected cmd=%02x "
+ "tbl=%02x idx=%02x" % (resp[:4].hex(), cmd, table, index))
+ return resp
+
+
+# --- Download / Upload ---
+
+def do_download(radio):
+ """Download memory image from the radio."""
+ status = chirp_common.Status()
+ status.msg = "Cloning from radio"
+ status.cur = 0
+ status.max = MEMSIZE
+
+ mmap_data = bytearray(MEMSIZE)
+ offset = 0
+
+ # 1. Read ident
+ try:
+ data = _read_block(radio, CMD_IDENT, 0x00, 0x00)
+ except NoData:
+ raise errors.RadioNoResponse()
+ except Exception:
+ raise
+ mmap_data[offset:offset + len(data)] = data
+ offset += len(data)
+ status.cur = offset
+ radio.status_fn(status)
+
+ # 2. Read settings
+ data = _read_block(radio, CMD_READ, TBL_SETTINGS, 0x00)
+ mmap_data[offset:offset + len(data)] = data
+ offset += len(data)
+ status.cur = offset
+ radio.status_fn(status)
+
+ # 3. Read channels (256)
+ for i in range(NUM_CHANNELS):
+ data = _read_block(radio, CMD_READ, TBL_CHANNELS, i)
+ mmap_data[offset:offset + len(data)] = data
+ offset += len(data)
+ status.cur = offset
+ if i % 16 == 0:
+ radio.status_fn(status)
+
+ # 4. Read extra blocks
+ for i in range(EXTRA_COUNT):
+ data = _read_block(radio, CMD_READ, TBL_EXTRA, i)
+ mmap_data[offset:offset + len(data)] = data
+ offset += len(data)
+
+ # 5. Read final block
+ data = _read_block(radio, CMD_READ, TBL_FINAL, 0x00)
+ mmap_data[offset:offset + len(data)] = data
+ offset += len(data)
+
+ # 6. Read calibration data (downloaded but not uploaded)
+ data = _read_block(radio, CMD_READ, TBL_SYSCONFIG, 0x00)
+ mmap_data[offset:offset + len(data)] = data
+ offset += len(data)
+
+ for i in range(RFCAL_COUNT):
+ data = _read_block(radio, CMD_READ, TBL_RFCAL, i)
+ mmap_data[offset:offset + len(data)] = data
+ offset += len(data)
+
+ status.cur = MEMSIZE
+ radio.status_fn(status)
+
+ LOG.debug("Downloaded %d bytes", offset)
+
+ radio._metadata['image_version'] = IMAGE_VERSION
+
+ return memmap.MemoryMapBytes(bytes(mmap_data[:offset]))
+
+
+def do_upload(radio):
+ """Upload memory image to the radio."""
+ status = chirp_common.Status()
+ status.msg = "Uploading to radio"
+ status.cur = 0
+ status.max = MEMSIZE
+
+ mmap = radio.get_mmap()
+
+ # 1. Read ident (handshake)
+ try:
+ _read_block(radio, CMD_IDENT, 0x00, 0x00)
+ except NoData:
+ raise errors.RadioNoResponse()
+ except Exception:
+ raise
+
+ # 2. Read current settings (verify communication)
+ _read_block(radio, CMD_READ, TBL_SETTINGS, 0x00)
+
+ # 3. Write settings
+ settings_data = mmap[SETTINGS_OFFSET:SETTINGS_OFFSET + SETTINGS_SIZE]
+ _write_block(radio, CMD_WRITE, TBL_SETTINGS, 0x00, settings_data)
+ _read_block(radio, CMD_VERIFY, TBL_SETTINGS, 0x00)
+ status.cur = SETTINGS_OFFSET + SETTINGS_SIZE
+ radio.status_fn(status)
+
+ # 4. Write channels
+ for i in range(NUM_CHANNELS):
+ ch_offset = CHANNELS_OFFSET + i * CHANNEL_SIZE
+ ch_data = mmap[ch_offset:ch_offset + CHANNEL_SIZE]
+ _write_block(radio, CMD_WRITE, TBL_CHANNELS, i, ch_data)
+ _read_block(radio, CMD_VERIFY, TBL_CHANNELS, i)
+ status.cur = ch_offset + CHANNEL_SIZE
+ if i % 16 == 0:
+ radio.status_fn(status)
+
+ # 5. Write extra blocks
+ for i in range(EXTRA_COUNT):
+ blk_start = EXTRA_OFFSET + i * EXTRA_SIZE
+ blk_data = mmap[blk_start:blk_start + EXTRA_SIZE]
+ _write_block(radio, CMD_WRITE, TBL_EXTRA, i, blk_data)
+ _read_block(radio, CMD_VERIFY, TBL_EXTRA, i)
+
+ # 6. Write final block (448 of 480 bytes, matching CPS protocol)
+ final_data = mmap[FINAL_OFFSET:FINAL_OFFSET + 448]
+ _write_block(radio, CMD_WRITE, TBL_FINAL, 0x00, final_data)
+ _read_block(radio, CMD_VERIFY, TBL_FINAL, 0x00)
+
+ # 7. Finalize
+ _read_block(radio, CMD_FINALIZE, 0x00, 0x00)
+
+ status.cur = MEMSIZE
+ radio.status_fn(status)
+
+
+# --- Main radio class ---
+
+@directory.register
+class RetevisC2(chirp_common.CloneModeRadio):
+ """Retevis C2"""
+ VENDOR = "Retevis"
+ MODEL = "C2"
+ BAUD_RATE = 115200
+ WANTS_RTS = False
+
+ _memsize = MEMSIZE
+
+ POWER_LEVELS = POWER_LEVELS
+
+ VALID_BANDS = [(100000000, 520000000)]
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_settings = True
+ rf.has_bank = False
+ rf.has_tuning_step = False
+ rf.has_rx_dtcs = True
+ rf.has_ctone = True
+ rf.has_cross = True
+ rf.has_name = True
+ rf.valid_name_length = 12
+ rf.valid_characters = (chirp_common.CHARSET_ALPHANUMERIC +
+ " !@#$%&*()-+=")
+ rf.valid_modes = ["FM", "NFM"]
+ rf.valid_skips = ["", "S"]
+ 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 = self.POWER_LEVELS
+ rf.valid_bands = self.VALID_BANDS
+ rf.valid_tuning_steps = chirp_common.TUNING_STEPS
+ rf.valid_dtcs_codes = chirp_common.DTCS_CODES
+ rf.can_odd_split = True
+ rf.memory_bounds = (1, NUM_CHANNELS)
+ return rf
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+
+ def sync_in(self):
+ self._mmap = do_download(self)
+ self.process_mmap()
+
+ def sync_out(self):
+ do_upload(self)
+
+ def 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 int(_mem.rxfreq) == 0:
+ mem.empty = True
+ return mem
+
+ mem.freq = int(_mem.rxfreq)
+
+ # TX freq / duplex
+ txfreq = int(_mem.txfreq)
+ if txfreq == 0 or txfreq == 0xFFFFFFFF:
+ mem.duplex = "off"
+ mem.offset = 0
+ else:
+ offset = txfreq - mem.freq
+ if offset == 0:
+ mem.duplex = ""
+ mem.offset = 0
+ elif offset > 0:
+ if chirp_common.is_split(
+ self.get_features().valid_bands,
+ mem.freq, txfreq):
+ mem.duplex = "split"
+ mem.offset = txfreq
+ else:
+ mem.duplex = "+"
+ mem.offset = offset
+ elif offset < 0:
+ mem.duplex = "-"
+ mem.offset = abs(offset)
+
+ # Mode (bandwidth)
+ bw = int(_mem.bandwidth)
+ mem.mode = "FM" if bw == 25000 else "NFM"
+
+ # Power
+ if _mem.highpower:
+ mem.power = self.POWER_LEVELS[0] # High
+ else:
+ mem.power = self.POWER_LEVELS[1] # Low
+
+ # Tones
+ txtone = _decode_tone(int(_mem.txtone))
+ rxtone = _decode_tone(int(_mem.rxtone))
+ chirp_common.split_tone_decode(mem, txtone, rxtone)
+
+ # Name
+ name = str(_mem.name).rstrip('\x00').rstrip()
+ mem.name = name
+
+ # Skip (scanadd: 1=add, 0=skip)
+ if not _mem.scanadd:
+ mem.skip = "S"
+
+ # Per-channel extras
+ mem.extra = RadioSettingGroup("Extra", "extra")
+
+ rs = RadioSetting("_compand", "Compand",
+ RadioSettingValueBoolean(
+ bool(_mem.compand)))
+ mem.extra.append(rs)
+
+ rs = RadioSetting("_talkaround", "Talk Around",
+ RadioSettingValueBoolean(
+ bool(_mem.talkaround)))
+ mem.extra.append(rs)
+
+ rs = RadioSetting("_busylock", "Busy Lock",
+ RadioSettingValueBoolean(
+ bool(_mem.busylock)))
+ mem.extra.append(rs)
+
+ rs = RadioSetting("_ani", "ANI",
+ RadioSettingValueBoolean(
+ bool(_mem.ani)))
+ mem.extra.append(rs)
+
+ rs = RadioSetting("_pttid", "PTT ID",
+ RadioSettingValueMap(
+ PTTID_MAP, int(_mem.pttid)))
+ mem.extra.append(rs)
+
+ dtmf_grp = int(_mem.dtmf_group)
+ rs = RadioSetting("_dtmf_group", "DTMF Group",
+ RadioSettingValueInteger(
+ 1, 16, dtmf_grp + 1))
+ mem.extra.append(rs)
+
+ rs = RadioSetting("_scramble", "Scramble",
+ RadioSettingValueMap(
+ SCRAMBLE_MAP, int(_mem.scramble)))
+ mem.extra.append(rs)
+
+ # GMRS implied modes
+ mem.mode, mem.power = self._apply_gmrs_limits(mem)
+
+ return mem
+
+ def _compute_tx_freq(self, mem):
+ """Compute TX frequency from memory duplex settings.
+
+ Returns None if TX is disabled (duplex='off').
+ """
+ if mem.duplex == "off":
+ return None
+ elif mem.duplex == "split":
+ return mem.offset
+ elif mem.duplex == "+":
+ return mem.freq + mem.offset
+ elif mem.duplex == "-":
+ return mem.freq - mem.offset
+ return mem.freq
+
+ def _apply_gmrs_limits(self, mem):
+ """Compute GMRS frequency-based restrictions (implied modes).
+
+ Returns (mode, power) tuple. Interstitial channels
+ (467.5625-467.7125 MHz) are forced to NFM and low power.
+ """
+ tx_freq = self._compute_tx_freq(mem)
+ if tx_freq is not None and tx_freq in bandplan_na.GMRS_HHONLY:
+ return "NFM", self.POWER_LEVELS[1]
+ return mem.mode, mem.power
+
+ def set_memory(self, mem):
+ _mem = self._memobj.memory[mem.number - 1]
+
+ if mem.empty:
+ _mem.set_raw(b'\x00' * 56)
+ _mem.bandwidth = 25000
+ _mem.highpower = 1
+ _mem.cfg_unk2 = 5 # CPS default (bits 2,0 set)
+ _mem.scanadd = 1
+ _mem.pttid = 1 # Off
+ _mem.unk11 = 1 # CPS default (bit 11)
+ _mem.scramble = 0xFFFF
+ return
+
+ _mem.rxfreq = mem.freq
+
+ # TX freq
+ if mem.duplex == "off":
+ _mem.txfreq = 0
+ elif mem.duplex == "split":
+ _mem.txfreq = mem.offset
+ elif mem.duplex == "+":
+ _mem.txfreq = mem.freq + mem.offset
+ elif mem.duplex == "-":
+ _mem.txfreq = mem.freq - mem.offset
+ else:
+ _mem.txfreq = mem.freq
+
+ # Enforce GMRS HH-only limits on write
+ tx_freq = self._compute_tx_freq(mem)
+ is_hhonly = tx_freq is not None and tx_freq in bandplan_na.GMRS_HHONLY
+
+ # Mode
+ if is_hhonly:
+ _mem.bandwidth = 12500
+ else:
+ _mem.bandwidth = 25000 if mem.mode == "FM" else 12500
+
+ # Power
+ _mem.highpower = (not is_hhonly and
+ mem.power == self.POWER_LEVELS[0])
+
+ # Tones
+ ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
+ chirp_common.split_tone_encode(mem)
+ _mem.txtone = _encode_tone(txmode, txtone, txpol)
+ _mem.rxtone = _encode_tone(rxmode, rxtone, rxpol)
+
+ # Name
+ name = mem.name.ljust(12, '\x00')[:12]
+ _mem.name = name
+
+ # Skip (scanadd: 1=add, 0=skip)
+ _mem.scanadd = mem.skip != "S"
+
+ _mem.pad0 = 0
+
+ # Per-channel extras - reset to defaults if not provided
+ # (e.g. CSV import or copy where extras are absent)
+ if not mem.extra:
+ _mem.busylock = 0
+ _mem.talkaround = 0
+ _mem.compand = 0
+ _mem.dtmf_group = 0
+ _mem.ani = 0
+ _mem.pttid = 1 # Off
+ _mem.scramble = 0xFFFF
+ return
+
+ for setting in mem.extra:
+ name = setting.get_name()
+ if name == "_compand":
+ _mem.compand = int(bool(setting.value))
+ elif name == "_talkaround":
+ _mem.talkaround = int(bool(setting.value))
+ elif name == "_busylock":
+ _mem.busylock = int(bool(setting.value))
+ elif name == "_ani":
+ _mem.ani = int(bool(setting.value))
+ elif name == "_pttid":
+ _mem.pttid = int(setting.value)
+ elif name == "_dtmf_group":
+ _mem.dtmf_group = int(setting.value) - 1
+ elif name == "_scramble":
+ _mem.scramble = int(setting.value)
+
+ def get_settings(self):
+ _mem = self._memobj
+ basic = RadioSettingGroup("basic", "Basic Settings")
+ vox = RadioSettingGroup("vox", "VOX Settings")
+ dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
+ top = RadioSettings(basic, vox, dtmf)
+
+ ABSWITCH_MAP = [("Auto", 0), ("On", 1), ("Off", 2)]
+ STEP_MAP = [("2.5K", 2500), ("5.0K", 5000), ("6.25K", 6250),
+ ("10.0K", 10000), ("12.5K", 12500), ("20.0K", 20000),
+ ("25.0K", 25000), ("50.0K", 50000)]
+ TOT_MAP = [("Off", 0)] + [("%d" % x, x) for x in range(15, 615, 15)]
+ VOXDELAY_MAP = [("0.5", 500), ("1.0", 1000), ("1.5", 1500),
+ ("2.0", 2000), ("2.5", 2500), ("3.0", 3000)]
+
+ basic.append(MemSetting("tot", "TOT (seconds)",
+ RadioSettingValueMap(
+ TOT_MAP, int(_mem.tot))))
+ TOTWARN_MAP = [("Off", 0)] + [
+ ("%d" % x, x << 4) for x in range(1, 11)]
+ basic.append(MemSetting("tot_warning", "TOT Warning Time",
+ RadioSettingValueMap(
+ TOTWARN_MAP,
+ int(_mem.tot_warning))))
+ basic.append(MemSetting("freq_step", "Frequency Step",
+ RadioSettingValueMap(
+ STEP_MAP, int(_mem.freq_step))))
+ basic.append(MemSetting("abswitch", "A/B Switch",
+ RadioSettingValueMap(
+ ABSWITCH_MAP,
+ int(_mem.abswitch))))
+ KEY_MAP = [
+ ("Off", 0xFFFFFFFF),
+ ("Monitor", 1),
+ ("TX Power", 4),
+ ("Scan", 5),
+ ("Flashlight", 6),
+ ("Denoise", 12),
+ ("Frequency Detect", 15),
+ ("VOX", 17),
+ ("Local Alarm", 20),
+ ("Remote Alarm", 21),
+ ("Weather", 22),
+ ("Talk Around", 23),
+ ("Reverse Frequency", 24),
+ ]
+ SKEY_MAP = KEY_MAP + [("SUB-PTT", 25), ("Group PTT", 26)]
+ for field, label, kmap in [
+ ("pf1_short", "P1 Short Press", KEY_MAP),
+ ("pf1_long", "P1 Long Press", KEY_MAP),
+ ("pf2_short", "P2 Short Press", KEY_MAP),
+ ("pf2_long", "P2 Long Press", KEY_MAP),
+ ("sk_short", "Side Key Short", SKEY_MAP),
+ ("sk_long", "Side Key Long", KEY_MAP)]:
+ basic.append(MemSetting(
+ field, label,
+ RadioSettingValueMap(
+ kmap, int(getattr(_mem, field)))))
+ rs = RadioSettingValueInteger(1, 256, int(_mem.group_call_ch) + 1)
+ basic.append(RadioSetting(
+ "_group_call_ch", "Group Call Channel", rs))
+ basic.append(MemSetting(
+ "squelch", "Squelch Level",
+ RadioSettingValueInteger(0, 9, min(int(_mem.squelch), 9))))
+
+ basic.append(MemSetting("chnameshow",
+ "Display Channel Names",
+ RadioSettingValueBoolean(
+ bool(int(_mem.chnameshow)))))
+ basic.append(MemSetting("keytone", "Key Tone",
+ RadioSettingValueBoolean(
+ bool(int(_mem.keytone)))))
+ rs = RadioSettingValueBoolean(int(_mem.dwatch) == 2)
+ basic.append(RadioSetting("_dwatch", "Dual Watch", rs))
+ basic.append(MemSetting("group_switch", "Group Call",
+ RadioSettingValueBoolean(
+ bool(int(_mem.group_switch)))))
+
+ noaa_idx = int(_mem.noaa_ch)
+ if noaa_idx >= 7:
+ noaa_idx = 0
+ rs = RadioSettingValueList(LIST_NOAA, current_index=noaa_idx)
+ basic.append(RadioSetting(
+ "_noaa_ch", "NOAA Weather Channel", rs))
+ rs = RadioSettingValueBoolean(int(_mem.noaa_warning) != 0)
+ basic.append(RadioSetting(
+ "_noaa_warning", "NOAA Weather Warning", rs))
+ fm_raw = int(_mem.settings_3d78)
+ rs = RadioSettingValueBoolean((fm_raw & 0x03) == 1)
+ basic.append(RadioSetting("_fm_auto", "FM Radio", rs))
+ rs = RadioSettingValueBoolean(bool(fm_raw & 0x04))
+ basic.append(RadioSetting(
+ "_allow_tx_beep", "Allow TX Beep", rs))
+ # AI Denoise: ul32 = level*96 + 4 + (3 if on else 0)
+ ai_raw = int(_mem.ai_denoise_packed)
+ ai_enabled = (ai_raw & 0x03) == 0x03
+ ai_level = ((ai_raw & ~3) - 4) // 96
+ if ai_level < 1:
+ ai_level = 1
+ if ai_level > 10:
+ ai_level = 10
+ rs = RadioSettingValueBoolean(ai_enabled)
+ basic.append(RadioSetting("_ai_denoise", "AI Denoise", rs))
+ rs = RadioSettingValueInteger(1, 10, ai_level)
+ basic.append(RadioSetting(
+ "_ai_denoise_level", "AI Denoise Level", rs))
+
+ basic.append(MemSetting("recorder", "Recording Playback",
+ RadioSettingValueBoolean(
+ bool(int(_mem.recorder)))))
+ basic.append(MemSetting("show_bat", "Show Battery Voltage",
+ RadioSettingValueBoolean(
+ bool(int(_mem.show_bat)))))
+ basic.append(MemSetting("dtmf_show", "DTMF Show",
+ RadioSettingValueBoolean(
+ bool(int(_mem.dtmf_show)))))
+ rs = RadioSettingValueBoolean(bool(int(_mem.css_packed) & 0x01))
+ basic.append(RadioSetting("_css_vague", "CSS Vague", rs))
+ rs = RadioSettingValueBoolean(bool(int(_mem.css_packed) & 0x10))
+ basic.append(RadioSetting(
+ "_cancel_all_ctdt", "Cancel All CTCSS/DCS", rs))
+
+ basic.append(MemSetting("ctcss_tail_tone",
+ "CTCSS Tail Freq (Hz)",
+ RadioSettingValueMap(
+ TAIL_TONE_MAP,
+ int(_mem.ctcss_tail_tone))))
+ basic.append(MemSetting("cdcss_tail_tone",
+ "CDCSS Tail Freq (Hz)",
+ RadioSettingValueMap(
+ TAIL_TONE_MAP,
+ int(_mem.cdcss_tail_tone))))
+ basic.append(MemSetting("no_ctcss_tail_freq",
+ "NO CTCSS Tail Freq (Hz)",
+ RadioSettingValueMap(
+ NO_CTCSS_TAIL_MAP,
+ int(_mem.no_ctcss_tail_freq))))
+
+ rs = RadioSettingValueBoolean(bool(int(_mem.settings_0020) & 1))
+ basic.append(RadioSetting("_voice", "Voice Prompt", rs))
+
+ POWERSAVE_MAP = [("Off", 0), ("1", 1), ("2", 4),
+ ("3", 6), ("4", 9)]
+ basic.append(MemSetting("power_save", "Battery Save",
+ RadioSettingValueMap(
+ POWERSAVE_MAP,
+ int(_mem.power_save))))
+
+ WORKMODE_MAP = [("Channel", 0), ("Memory", 1)]
+ basic.append(MemSetting("work_mode", "Work Mode",
+ RadioSettingValueMap(
+ WORKMODE_MAP,
+ int(_mem.work_mode))))
+
+ basic.append(MemSetting(
+ "micgain_analog", "Mic Gain (Analog)",
+ RadioSettingValueInteger(
+ -3, 3, max(-3, min(3, int(_mem.micgain_analog))))))
+
+ pri_raw = int(_mem.settings_035c)
+ rs = RadioSettingValueBoolean(bool(pri_raw & 0x01))
+ basic.append(RadioSetting(
+ "_tx_start_beep", "TX Start Beep", rs))
+ rs = RadioSettingValueBoolean(bool(pri_raw & 0x04))
+ basic.append(RadioSetting(
+ "_tx_stop_beep", "TX Stop Beep", rs))
+
+ pri_ch = pri_raw >> 8
+ if pri_ch == 0xFFFFFF:
+ pri_idx = 0
+ else:
+ pri_idx = pri_ch + 1
+ if pri_idx < 1 or pri_idx > 256:
+ pri_idx = 0
+ rs = RadioSettingValueList(
+ LIST_PRIORITY_SCAN, current_index=pri_idx)
+ basic.append(RadioSetting(
+ "_priority_scan", "Priority Scan Channel", rs))
+
+ SCANMODE_MAP = [("Search", 0), ("Carrier", 1), ("Time", 2)]
+ basic.append(MemSetting("scan_mode", "Scan Mode",
+ RadioSettingValueMap(
+ SCANMODE_MAP,
+ int(_mem.scan_mode))))
+
+ basic.append(MemSetting(
+ "lcd_brightness", "LCD Brightness",
+ RadioSettingValueInteger(
+ 1, 5, min(max(int(_mem.lcd_brightness), 1), 5))))
+
+ KEYLOCK_MAP = [("Off", 0), ("5s", 5000), ("10s", 10000),
+ ("15s", 15000), ("20s", 20000), ("25s", 25000),
+ ("30s", 30000)]
+ basic.append(MemSetting("key_lock", "Key Lock",
+ RadioSettingValueMap(
+ KEYLOCK_MAP, int(_mem.key_lock))))
+
+ ABLTIME_MAP = [("Always", 0), ("5s", 5000), ("10s", 10000),
+ ("15s", 15000), ("20s", 20000)]
+ basic.append(MemSetting("auto_bl_time", "Auto Backlight Time",
+ RadioSettingValueMap(
+ ABLTIME_MAP, int(_mem.auto_bl_time))))
+
+ APO_MAP = [("Off", 0), ("10min", 600000), ("30min", 1800000)] + \
+ [("%dhr" % h, h * 3600000) for h in range(1, 13)]
+ basic.append(MemSetting("apo_time", "Auto Power Off",
+ RadioSettingValueMap(
+ APO_MAP, int(_mem.apo_time))))
+
+ # Password: packed as pwd_int * 4 + flag (1=on, 0=off)
+ pwd_raw = int(_mem.password)
+ pwd_enabled = (pwd_raw % 4) == 1
+ pwd_num = pwd_raw // 4
+ pwd_str = "%06d" % pwd_num
+ rs = RadioSettingValueBoolean(pwd_enabled)
+ basic.append(RadioSetting(
+ "_pwd_enable", "Password Enable", rs))
+ rs = RadioSettingValueString(6, 6, pwd_str)
+ rs.set_charset("0123456789")
+ basic.append(RadioSetting("_pwd_code", "Password", rs))
+
+ TONE_MAP = [("1000", 1000), ("1450", 1450),
+ ("1750", 1750), ("2100", 2100)]
+ basic.append(MemSetting("tone_burst", "Tone Burst (Hz)",
+ RadioSettingValueMap(
+ TONE_MAP, int(_mem.tone_burst))))
+ # VOX is packed: vox_level*4 + (1=on, 2=off)
+ vox_packed = int(_mem.vox_packed)
+ vox_on = (vox_packed % 4) == 1
+ vox_level = vox_packed // 4
+ if vox_level < 1:
+ vox_level = 1
+ if vox_level > 9:
+ vox_level = 5
+
+ rs = RadioSettingValueBoolean(vox_on)
+ vox.append(RadioSetting("_vox_enabled", "VOX Function", rs))
+
+ vox.append(RadioSetting(
+ "_vox_level", "VOX Level",
+ RadioSettingValueInteger(1, 9, vox_level)))
+
+ vox.append(MemSetting("vox_delay", "VOX Delay Time",
+ RadioSettingValueMap(
+ VOXDELAY_MAP, int(_mem.vox_delay))))
+
+ # DTMF settings
+ dtmf_id = str(_mem.dtmf_local_id).rstrip('\x00')
+ rs = RadioSettingValueString(0, 8, dtmf_id,
+ mem_pad_char='\x00')
+ rs.set_charset(DTMF_CHARS)
+ dtmf.append(MemSetting("dtmf_local_id", "DTMF Local ID", rs))
+
+ DTMF_FIRST_MAP = [("%dms" % ms, ms * 2)
+ for ms in range(150, 1010, 10)]
+ dtmf.append(MemSetting("dtmf_first_time",
+ "DTMF First Code Time",
+ RadioSettingValueMap(
+ DTMF_FIRST_MAP,
+ int(_mem.dtmf_first_time))))
+
+ LIST_SEP = ['*', '#', 'A', 'B', 'C', 'D']
+ sep = str(_mem.dtmf_sep_code)
+ sep_idx = LIST_SEP.index(sep) if sep in LIST_SEP else 0
+ rs = RadioSettingValueList(LIST_SEP, current_index=sep_idx)
+ dtmf.append(RadioSetting(
+ "dtmf_sep_code", "Separate Code", rs))
+
+ LIST_GRP = ['A', 'B', 'C', 'D', '*', '#']
+ grp = str(_mem.dtmf_group_code)
+ grp_idx = LIST_GRP.index(grp) if grp in LIST_GRP else 0
+ rs = RadioSettingValueList(LIST_GRP, current_index=grp_idx)
+ dtmf.append(RadioSetting(
+ "dtmf_group_code", "Group Code", rs))
+
+ return top
+
+ def set_settings(self, settings):
+ _mem = self._memobj
+ for element in settings:
+ if isinstance(element, MemSetting):
+ element.apply_to_memobj(_mem)
+ elif isinstance(element, RadioSetting):
+ # Packed/composite settings need manual encoding
+ name = element.get_name()
+ if name == '_group_call_ch':
+ _mem.group_call_ch = int(element.value) - 1
+ elif name == '_fm_auto':
+ cur = int(_mem.settings_3d78) & ~0x03
+ _mem.settings_3d78 = \
+ cur | (1 if bool(element.value) else 2)
+ elif name == '_allow_tx_beep':
+ cur = int(_mem.settings_3d78)
+ if bool(element.value):
+ _mem.settings_3d78 = cur | 0x04
+ else:
+ _mem.settings_3d78 = cur & ~0x04
+ elif name == '_dwatch':
+ _mem.dwatch = 2 if bool(element.value) else 1
+ elif name == '_voice':
+ cur = int(_mem.settings_0020)
+ if bool(element.value):
+ _mem.settings_0020 = cur | 1
+ else:
+ _mem.settings_0020 = cur & ~1
+ elif name == '_vox_enabled':
+ # Repack VOX: vox_level*4 + (1=on, 2=off)
+ cur = int(_mem.vox_packed)
+ level = cur // 4
+ flag = 1 if bool(element.value) else 2
+ _mem.vox_packed = level * 4 + flag
+ elif name == '_vox_level':
+ cur = int(_mem.vox_packed)
+ flag = cur % 4
+ _mem.vox_packed = int(element.value) * 4 + flag
+ elif name == '_pwd_enable':
+ cur = int(_mem.password)
+ pwd = cur // 4
+ if bool(element.value):
+ _mem.password = pwd * 4 + 1
+ else:
+ _mem.password = pwd * 4
+ elif name == '_pwd_code':
+ cur = int(_mem.password)
+ flag = cur % 4
+ _mem.password = \
+ int(str(element.value)) * 4 + flag
+ elif name == '_ai_denoise':
+ cur = int(_mem.ai_denoise_packed)
+ if bool(element.value):
+ _mem.ai_denoise_packed = (cur & ~3) | 3
+ else:
+ _mem.ai_denoise_packed = cur & ~3
+ elif name == '_ai_denoise_level':
+ cur = int(_mem.ai_denoise_packed)
+ enable = cur & 3
+ _mem.ai_denoise_packed = \
+ int(element.value) * 96 + 4 + enable
+ elif name == '_tx_start_beep':
+ cur = int(_mem.settings_035c)
+ if bool(element.value):
+ _mem.settings_035c = cur | 0x01
+ else:
+ _mem.settings_035c = cur & ~0x01
+ elif name == '_tx_stop_beep':
+ cur = int(_mem.settings_035c)
+ if bool(element.value):
+ _mem.settings_035c = cur | 0x04
+ else:
+ _mem.settings_035c = cur & ~0x04
+ elif name == '_priority_scan':
+ cur = int(_mem.settings_035c) & 0xFF
+ idx = int(element.value)
+ if idx == 0:
+ _mem.settings_035c = \
+ (0xFFFFFF << 8) | cur
+ else:
+ _mem.settings_035c = \
+ ((idx - 1) << 8) | cur
+ elif name == '_css_vague':
+ cur = int(_mem.css_packed)
+ if bool(element.value):
+ _mem.css_packed = cur | 0x01
+ else:
+ _mem.css_packed = cur & ~0x01
+ elif name == '_cancel_all_ctdt':
+ cur = int(_mem.css_packed)
+ if bool(element.value):
+ _mem.css_packed = cur | 0x10
+ else:
+ _mem.css_packed = cur & ~0x10
+ elif name == '_noaa_ch':
+ idx = int(element.value)
+ _mem.noaa_ch = idx
+ _mem.noaa_freq = NOAA_FREQS[idx]
+ elif name == '_noaa_warning':
+ cur = int(_mem.noaa_warning)
+ if bool(element.value):
+ _mem.noaa_warning = cur | 0x40000
+ else:
+ _mem.noaa_warning = cur & ~0x40000
+ elif name in ('dtmf_sep_code', 'dtmf_group_code'):
+ setattr(_mem, name, str(element.value))
+ else:
+ LOG.warning("Unhandled setting: %s", name)
+ else:
+ self.set_settings(element)
+
+ def validate_memory(self, mem):
+ msgs = super().validate_memory(mem)
+ if mem.empty:
+ return msgs
+
+ tx_freq = self._compute_tx_freq(mem)
+
+ if tx_freq is not None:
+ if tx_freq not in GMRS_TX_FREQS:
+ msgs.append(chirp_common.ValidationWarning(
+ "TX frequency %s is not a GMRS frequency"
+ % chirp_common.format_freq(tx_freq)))
+ if tx_freq in bandplan_na.GMRS_HHONLY:
+ if mem.mode != "NFM":
+ msgs.append(chirp_common.ValidationWarning(
+ "GMRS 467 MHz channels require NFM"))
+ if mem.power and mem.power != self.POWER_LEVELS[1]:
+ msgs.append(chirp_common.ValidationWarning(
+ "GMRS 467 MHz channels require low power"))
+
+ return msgs
diff --git a/chirp/drivers/retevis_h777v4.py b/chirp/drivers/retevis_h777v4.py
index a61998b..d7184b5 100644
--- a/chirp/drivers/retevis_h777v4.py
+++ b/chirp/drivers/retevis_h777v4.py
@@ -27,6 +27,7 @@ from chirp import (
from chirp.drivers import h777
from chirp.settings import (
MemSetting,
+ RadioSetting,
RadioSettingGroup,
RadioSettings,
RadioSettingValueBoolean,
@@ -49,7 +50,7 @@ struct {
ishighpower:1, // Power Level 0 = Low, 1 = High
narrow:1, // Bandwidth 0 = Wide, 1 = Narrow
unknown1:1, //
- bcl:1; // Busy Channel Locklut 0 = On, 1 = Off
+ bcl:1; // Busy Channel Lockout 0 = On, 1 = Off
} memory[16];
struct {
@@ -73,17 +74,74 @@ struct {
} settings;
"""
+MEM_FORMAT_RT21H = """
+struct {
+ ul24 rxfreq; // 0-2
+ ul24 txfreq; // 3-5
+ lbcd rx_tone[2]; // 6-7
+ lbcd tx_tone[2]; // 8-9
+ u8 speccode:1, // A Spec Code 0 = On, 1 = Off
+ compand:1, // Compander 0 = On, 1 = Off
+ scramb:1, // Scramble 0 = Off, 1 = On
+ scanadd:1, // Scan Add 0 = Scan, 1 = Skip
+ ishighpower:1, // Power Level 0 = Low, 1 = High
+ narrow:1, // Bandwidth 0 = Wide, 1 = Narrow
+ unknown1:1, //
+ bcl:1; // Busy Channel Lockout 0 = On, 1 = Off
+ u8 scrambopt; // B Scramble Options
+} memory[16];
+
+struct {
+ u8 unknown_4:1, // 00C0
+ scanm:1, // Scan Mode
+ roger:1, // Roger
+ lowbattwarn:1, // Low Battery Warning
+ unknown_0:1,
+ voice:1, // Voice Annunciation
+ save:1, // Battery Save
+ voxs:1; // VOX Switch
+ u8 squelch; // 00C1 Squelch Level
+ u8 tot; // 00C2 Time-out Timer
+ u8 voxd; // 00C3 Vox Delay
+ u8 vox_level; // 00C4 VOX Level
+ u8 unknown_1;
+ u8 unknown_2;
+ u8 skey1L:4, // 00C7 Side Key 1 (long)
+ skey1S:4; // Side Key 1 (short)
+ u8 unknown_3:5, // 00C8
+ removectdcs:1, // Remove CT/DCS
+ beep:1, // Beep Tone
+ specmode:1; // Spec Mode
+} settings;
+"""
+
CMD_ACK = b"\x06"
DTCS = tuple(sorted(chirp_common.DTCS_CODES + (645,)))
OFF1TO9_LIST = ["Off"] + ["%s" % x for x in range(1, 10)]
+ONE_TO_NINE_LIST = OFF1TO9_LIST[1:] # ["1", "2", ..., "9"]
SCANM_LIST = ["Carrier", "Time"]
+SCRAMBOPT_LIST = ["1", "2", "3", "4", "5", "6", "7", "8"]
+SPECMODE_LIST = ["Spec Code 1", "Spec Code 2"]
+SKEY1_LIST = ["Off", "Monitor", "Scan", "Channel Lock", "VOX", "Power",
+ "Alarm", "Roger"]
SKEY2_LIST = ["Off", "VOX", "Power", "Scan"]
TIMEOUTTIMER_LIST = ["Off"] + ["%s seconds" % x for x in range(30, 210, 30)]
VOICE_LIST = ["Off", "English"]
-VOXD_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0"]
+
+MODEL_CONFIG = {
+ "RT21H": {
+ "base_freq_offset": 0x2000000,
+ "freq_storage_bits": 24,
+ },
+}
+
+DEFAULT_CONFIG = {
+ "base_freq_offset": 0,
+ "freq_storage_bits": 32,
+}
def _read_block(radio, block_addr, block_size):
@@ -127,6 +185,12 @@ def _write_block(radio, block_addr, block_size):
def do_download(radio):
LOG.debug("download")
+ if not radio.is_detected() and not radio.detected_models():
+ # If we are a detect-ee or detect-or, don't re-initialize programming
+ # mode. But if we're one of the other subclasses of this work that
+ # would not have run through detection, we need to do so.
+ h777._h777_enter_single_programming_mode(radio)
+
data = b""
status = chirp_common.Status()
@@ -172,9 +236,25 @@ class H777V4BaseRadio(chirp_common.CloneModeRadio):
BLOCK_SIZE = 0x0D
BLOCK_SIZE_UP = 0x0D
+ VOXD_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0"]
+ VOXD_DOC = "VOX Delay: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0 seconds"
+ VOXL_DOC = "VOX Level: Off, 1, 2, 3, 4, 5, 6, 7, 8, 9"
+
+ _has_codeswitch = True
+ _has_compander = False
+ _has_low_battery_warning = False
+ _has_remove_ctdcs = False
+ _has_scramble_options = False
+ _has_spec_code = False
+ _has_sidekey1 = False
+ _has_sidekey2 = True
+ _has_spec_mode = False
+ _has_vox_level_off = True
+
POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
chirp_common.PowerLevel("High", watts=2.00)
]
+ VALID_BANDS = [(400000000, 520000000)]
PROGRAM_CMD = b"C777HAM"
_ranges = [
@@ -202,7 +282,7 @@ class H777V4BaseRadio(chirp_common.CloneModeRadio):
rf.valid_dtcs_codes = DTCS
rf.memory_bounds = (1, 16)
rf.valid_tuning_steps = [2.5, 5., 6.25, 10., 12.5, 20., 25., 50.]
- rf.valid_bands = [(400000000, 520000000)]
+ rf.valid_bands = self.VALID_BANDS
return rf
def process_mmap(self):
@@ -278,7 +358,19 @@ class H777V4BaseRadio(chirp_common.CloneModeRadio):
def _encode_tone(self, _toneval, mode, val, pol):
toneval = 0
if mode == "Tone":
- toneval = int("%i" % (val * 10), 16)
+ v = int(round(val * 10))
+
+ thousands = (v // 1000) % 10
+ hundreds = (v // 100) % 10
+ tens = (v // 10) % 10
+ ones = v % 10
+
+ toneval = (
+ (thousands << 12)
+ | (hundreds << 8)
+ | (tens << 4)
+ | ones
+ )
elif mode == "DTCS":
toneval = int('%i' % val, 8)
toneval |= 0x8000
@@ -290,6 +382,15 @@ class H777V4BaseRadio(chirp_common.CloneModeRadio):
_toneval[0].set_raw(toneval & 0xFF)
_toneval[1].set_raw((toneval >> 8) & 0xFF)
+ def _model_cfg(self):
+ cfg = MODEL_CONFIG.get(self.MODEL, DEFAULT_CONFIG).copy()
+ cfg["tx_unused_marker"] = (1 << cfg["freq_storage_bits"]) - 1
+ return cfg
+
+ def _decode_freq(self, raw):
+ cfg = self._model_cfg()
+ return (int(raw) + cfg["base_freq_offset"]) * 10
+
def get_raw_memory(self, number):
return repr(self._memobj.memory[number - 1])
@@ -303,22 +404,27 @@ class H777V4BaseRadio(chirp_common.CloneModeRadio):
mem.empty = True
return mem
- mem.freq = int(_mem.rxfreq) * 10
+ cfg = self._model_cfg()
+
+ rx_hz = self._decode_freq(_mem.rxfreq)
+ mem.freq = rx_hz
- if _mem.txfreq == 0xFFFFFFFF:
- # TX freq not set
+ if _mem.txfreq == cfg["tx_unused_marker"]:
mem.duplex = "off"
mem.offset = 0
- elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 25000000:
- mem.duplex = "split"
- mem.offset = int(_mem.txfreq) * 10
- elif int(_mem.rxfreq) == int(_mem.txfreq):
- mem.duplex = ""
- mem.offset = 0
else:
- mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) \
- and "-" or "+"
- mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
+ tx_hz = self._decode_freq(_mem.txfreq)
+ diff = rx_hz - tx_hz
+
+ if abs(diff) > 25_000_000:
+ mem.duplex = "split"
+ mem.offset = tx_hz
+ elif diff == 0:
+ mem.duplex = ""
+ mem.offset = 0
+ else:
+ mem.duplex = "-" if diff > 0 else "+"
+ mem.offset = abs(diff)
txmode, txval, txpol = self._decode_tone(_mem.tx_tone, 'TX', number)
rxmode, rxval, rxpol = self._decode_tone(_mem.rx_tone, 'RX', number)
@@ -348,26 +454,64 @@ class H777V4BaseRadio(chirp_common.CloneModeRadio):
rset.set_doc("Frequency inversion Scramble")
mem.extra.append(rset)
+ # Compander
+ if self._has_compander:
+ rs = RadioSettingValueInvertedBoolean(not bool(_mem.compand))
+ rset = MemSetting("compand", "Compander", rs)
+ rset.set_doc("Voice Compander")
+ mem.extra.append(rset)
+
+ # Spec Code
+ if self._has_spec_code:
+ rs = RadioSettingValueInvertedBoolean(not bool(_mem.speccode))
+ rset = MemSetting("speccode", "Spec Code", rs)
+ rset.set_doc("Spec Code")
+ mem.extra.append(rset)
+
+ # Scramble Options
+ if self._has_scramble_options:
+ if _mem.scrambopt > 0x07:
+ val = 0x00
+ else:
+ val = _mem.scrambopt
+ rs = RadioSettingValueList(SCRAMBOPT_LIST, current_index=val)
+ rset = MemSetting("scrambopt", "Scramble Options", rs)
+ rset.set_doc("Scramble Options: 1, 2, 3, 4, 5, 6, 7, 8")
+ mem.extra.append(rset)
+
return mem
+ def _encode_freq(self, hz):
+ cfg = self._model_cfg()
+ raw = int(hz / 10) - cfg["base_freq_offset"]
+ if not (0 <= raw <= cfg["tx_unused_marker"]):
+ raise ValueError(f"Frequency {hz} out of 24-bit range")
+ return raw
+
def set_memory(self, mem):
_mem = self._memobj.memory[mem.number - 1]
- _mem.set_raw(b"\xff" * 13)
+ cfg = self._model_cfg()
+
if mem.empty:
+ _mem.set_raw(b"\xFF" * (_mem.size() // 8))
return
- _mem.rxfreq = mem.freq / 10
+ rx = self._encode_freq(mem.freq)
+ _mem.rxfreq = rx
+
if mem.duplex == "off":
- _mem.txfreq = 0xFFFFFFFF
+ tx = cfg["tx_unused_marker"]
elif mem.duplex == "split":
- _mem.txfreq = mem.offset / 10
+ tx = self._encode_freq(mem.offset)
elif mem.duplex == "+":
- _mem.txfreq = (mem.freq + mem.offset) / 10
+ tx = self._encode_freq(mem.freq + mem.offset)
elif mem.duplex == "-":
- _mem.txfreq = (mem.freq - mem.offset) / 10
+ tx = self._encode_freq(mem.freq - mem.offset)
else:
- _mem.txfreq = _mem.rxfreq
+ tx = rx
+
+ _mem.txfreq = tx
(txmode, txval, txpol), (rxmode, rxval, rxpol) = \
chirp_common.split_tone_encode(mem)
@@ -380,10 +524,6 @@ class H777V4BaseRadio(chirp_common.CloneModeRadio):
_mem.ishighpower = mem.power == self.POWER_LEVELS[1]
- # resetting unknowns, this have to be set by hand
- _mem.unknown0 = 3
- _mem.unknown1 = 1
-
for setting in mem.extra:
setting.apply_to_memobj(_mem)
@@ -407,18 +547,42 @@ class H777V4BaseRadio(chirp_common.CloneModeRadio):
basic.append(rset)
# Vox Level
- rs = RadioSettingValueList(OFF1TO9_LIST, current_index=_settings.vox)
- rset = MemSetting("vox", "VOX Level", rs)
- rset.set_doc("VOX Level: Off, 1, 2, 3, 4, 5, 6, 7, 8, 9")
+ if self._has_vox_level_off:
+ # H777 behavior: 0-9 maps directly
+ rs = RadioSettingValueList(
+ OFF1TO9_LIST,
+ current_index=_settings.vox
+ )
+ rset = MemSetting("vox", "VOX Level", rs)
+ else:
+ # RT21H behavior: hide "Off"
+ # Firmware: 1-9
+ # UI index: 0-8
+ index = min(8, max(0, _settings.vox_level - 1))
+ rs = RadioSettingValueList(
+ ONE_TO_NINE_LIST,
+ current_index=index
+ )
+ rset = MemSetting("vox_level", "VOX Level", rs)
+
+ rset.set_doc(self.VOXL_DOC)
basic.append(rset)
# Vox Delay
- rs = RadioSettingValueList(VOXD_LIST,
+ rs = RadioSettingValueList(self.VOXD_LIST,
current_index=_settings.voxd)
rset = MemSetting("voxd", "Vox Delay", rs)
- rset.set_doc("VOX Delay: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0 seconds")
+ rset.set_doc(self.VOXD_DOC)
basic.append(rset)
+ # Spec Mode
+ if self._has_spec_mode:
+ rs = RadioSettingValueList(SPECMODE_LIST,
+ current_index=_settings.specmode)
+ rset = MemSetting("specmode", "Spec Mode", rs)
+ rset.set_doc("Spec Mode: Spec Code 1, Spec Code 2")
+ basic.append(rset)
+
# Scan Mode
rs = RadioSettingValueList(SCANM_LIST, current_index=_settings.scanm)
rset = MemSetting("scanm", "Scan Mode", rs)
@@ -432,18 +596,40 @@ class H777V4BaseRadio(chirp_common.CloneModeRadio):
rset.set_doc("Voice Prompts: Off, English")
basic.append(rset)
- # Side Key 2 (long)
- rs = RadioSettingValueList(SKEY2_LIST,
- current_index=_settings.skey2)
- rset = MemSetting("skey2", "Side Key 2", rs)
- rset.set_doc("Side Key 2 (long press): Off, VOX, Power, Scan")
- basic.append(rset)
+ # Side Key 1
+ if self._has_sidekey1:
+ SKEY1_DOC = ("Off, Monitor, Scan, Channel Lock, VOX, Power," +
+ " Alarm, Roger")
+
+ # Side Key 1 (short)
+ rs = RadioSettingValueList(SKEY1_LIST,
+ current_index=_settings.skey1S)
+ rset = MemSetting("skey1S", "Side Key 1 (short)", rs)
+ rset.set_doc("Side Key 1 (short press): " + SKEY1_DOC)
+ basic.append(rset)
+
+ # Side Key 1 (long)
+ rs = RadioSettingValueList(SKEY1_LIST,
+ current_index=_settings.skey1L)
+ rset = MemSetting("skey1L", "Side Key 1 (long)", rs)
+ rset.set_doc("Side Key 1 (long press): " + SKEY1_DOC)
+ basic.append(rset)
+
+ # Side key 2
+ if self._has_sidekey2:
+ # Side Key 2 (long)
+ rs = RadioSettingValueList(SKEY2_LIST,
+ current_index=_settings.skey2)
+ rset = MemSetting("skey2", "Side Key 2", rs)
+ rset.set_doc("Side Key 2 (long press): Off, VOX, Power, Scan")
+ basic.append(rset)
# Code Switch
- rs = RadioSettingValueBoolean(_settings.codesw)
- rset = MemSetting("codesw", "Code Switch", rs)
- rset.set_doc("Code Switch: Off, Enabled")
- basic.append(rset)
+ if self._has_codeswitch:
+ rs = RadioSettingValueBoolean(_settings.codesw)
+ rset = MemSetting("codesw", "Code Switch", rs)
+ rset.set_doc("Code Switch: Off, Enabled")
+ basic.append(rset)
# Battery Save
rs = RadioSettingValueBoolean(_settings.save)
@@ -463,12 +649,26 @@ class H777V4BaseRadio(chirp_common.CloneModeRadio):
rset.set_doc("VOX Switch: Off, Enabled")
basic.append(rset)
+ # Low Battery Warning
+ if self._has_low_battery_warning:
+ rs = RadioSettingValueBoolean(_settings.lowbattwarn)
+ rset = MemSetting("lowbattwarn", "Low Battery Warning", rs)
+ rset.set_doc("Low Battery Warning: Off, Enabled")
+ basic.append(rset)
+
# Roger
rs = RadioSettingValueBoolean(_settings.roger)
rset = MemSetting("roger", "Roger", rs)
rset.set_doc("Roger: Off, Enabled")
basic.append(rset)
+ # Remove CT/DCS
+ if self._has_remove_ctdcs:
+ rs = RadioSettingValueBoolean(_settings.removectdcs)
+ rset = MemSetting("removectdcs", "Remove CT/DCS", rs)
+ rset.set_doc("Remove CT/DCS: Off, Enabled")
+ basic.append(rset)
+
return group
def set_settings(self, settings):
@@ -503,3 +703,69 @@ class H777V4(H777V4BaseRadio):
# SKU #: A9294D (same as SKU #: A9294B (2 pack))
# Serial #: 24XXR777XXXXXXX
+
+
+@directory.register
+class RT21HRadio(H777V4BaseRadio):
+ """RETEVIS RT21H"""
+ VENDOR = "Retevis"
+ MODEL = "RT21H"
+
+ # SKU #: A9118R (sold as FRS radio but supports full band TX/RX)
+ # SKU #: A9118S (sold as PMR radio but supports full band TX/RX)
+
+ IDENT = [b'SMP558\x02\xFF', b'SMP558\x02\x00']
+ BLOCK_SIZE = 0x0C
+ BLOCK_SIZE_UP = 0x0C
+
+ VOXD_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0", "3.5"]
+ VOXD_DOC = "VOX Delay: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5 seconds"
+ VOXL_DOC = "VOX Level: 1, 2, 3, 4, 5, 6, 7, 8, 9"
+
+ _has_codeswitch = False
+ _has_compander = True
+ _has_low_battery_warning = True
+ _has_remove_ctdcs = True
+ _has_scramble_options = True
+ _has_sidekey1 = True
+ _has_sidekey2 = False
+ _has_spec_code = True
+ _has_spec_mode = True
+ _has_vox_level_off = False
+
+ POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
+ chirp_common.PowerLevel("High", watts=2.00)
+ ]
+ VALID_BANDS = [(400000000, 502000000)]
+
+ PROGRAM_CMD = b"T210GAM"
+ _ranges = [
+ (0x0000, 0x00D8),
+ ]
+ _memsize = 0x00D8
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(MEM_FORMAT_RT21H, self._mmap)
+
+ def set_settings(self, settings):
+ for element in settings:
+ if not isinstance(element, RadioSetting):
+ self.set_settings(element)
+ continue
+
+ obj = self._memobj.settings
+ setting = element.get_name()
+
+ try:
+ if setting == "vox_level":
+ # UI index 0-8 ? firmware value 1-9
+ value = min(9, max(1, int(element.value) + 1))
+ else:
+ value = element.value
+
+ LOG.debug("Setting %s = %s", setting, value)
+ setattr(obj, setting, value)
+
+ except Exception:
+ LOG.debug("Error applying setting %s", setting)
+ raise
diff --git a/chirp/drivers/retevis_ha1g.py b/chirp/drivers/retevis_ha1g.py
index c6d10b9..8fc308c 100644
--- a/chirp/drivers/retevis_ha1g.py
+++ b/chirp/drivers/retevis_ha1g.py
@@ -21,6 +21,7 @@ import time
from enum import Enum
from chirp import memmap, chirp_common, bitwise, directory, errors
+from chirp import checksum
from chirp.settings import (
RadioSetting,
RadioSettingGroup,
@@ -33,10 +34,11 @@ from chirp.settings import (
LOG = logging.getLogger(__name__)
-MEM_FORMAT = """
+SERIAL_TIMEOUT = 1.0
-#seekto 0x0E;
-struct{
+
+MEM_DEFINITIONS = """
+struct radioinfo {
u8 modelnumber[32];
u8 hardwareversion[2];
u8 serialno[16];
@@ -46,14 +48,134 @@ struct{
u8 saleterr;
u8 radiomode;
u8 rev[7];
-} radioinfo;
+};
-#seekto 0x52;
-struct{
+struct dataver {
u8 dataver[2];
u8 softver[4];
u8 rev[4];
- }dataver;
+};
+
+struct zoneinfo {
+ ul16 zonenum;
+ ul16 zoneindex[16];
+ struct {
+ char name[14];
+ ul16 chnum;
+ ul16 chindex[64];
+ } zones[16];
+};
+
+struct scaninfo {
+ ul16 scannum;
+ ul16 scanindex[16];
+ struct {
+ char name[14];
+ u8 scantxch:4,
+ scancondition:4;
+ u8 hangtime:4,
+ talkback:1,
+ scanstatus:3;
+ u8 chnum;
+ ul16 specifych;
+ ul16 PriorityCh1;
+ ul16 PriorityCh2;
+ u8 scanmode;
+ ul16 chindex[100];
+ } scans[16];
+};
+
+struct vfoscaninfo {
+ ul16 vfoscannum;
+ ul16 vfoscanindex[3];
+ struct {
+ u8 scantxch:4,
+ scancondition:4;
+ u8 hangtime:4,
+ talkback:1,
+ startcondition:1,
+ rev_1:2;
+ u8 scanmode;
+ ul32 vhffreq_start;
+ ul32 vhffreq_end;
+ ul32 uhffreq_start;
+ ul32 uhffreq_end;
+ u8 rev;
+ } vfoscans[3];
+};
+
+struct alarminfo {
+ ul16 alarmnum;
+ ul16 alarmindex[8];
+ struct {
+ char name[14];
+ u8 alarmtype:4,
+ alarmmode:4;
+ ul16 jumpch;
+ u8 localalarm:1,
+ txbackground:1,
+ ctcmode:2,
+ rev_1:4;
+ u8 alarmtime:4,
+ alarmcycle:4;
+ u8 mictime:4,
+ txinterval:4;
+ u8 alarmid[8];
+ u8 alarmstatus;
+ u8 rev_3[1];
+ } alarms[8];
+};
+
+struct dtmfinfo {
+ ul16 dtmfnum;
+ ul16 dtmfindex[4];
+ struct {
+ u8 autoresettime:4,
+ codedelaytime:4;
+ u8 stunmode:2,
+ showani:1,
+ sidetone:1,
+ pttidtype:2,
+ rev_1:2;
+ char callid[10];
+ char stunid[10];
+ char revive[10];
+ char bot[16];
+ char eot[16];
+ char rev_2[8];
+ } dtmfcomm;
+ struct {
+ char name[14];
+ u8 codelen:4,
+ signaling:4;
+ u8 groupcode:4,
+ intermediatecode:4;
+ char fastcall1[16];
+ char fastcall2[16];
+ char fastcall3[16];
+ char fastcall4[16];
+ char fastcall5[16];
+ char fastcall6[16];
+ char fastcall7[16];
+ char fastcall8[16];
+ char fastcall9[16];
+ char fastcall10[16];
+ u8 rev_1:6,
+ EncodingEnable:1,
+ DecodingEnable:1;
+ u8 dtmfstatus;
+ u8 rev_2[12];
+ } dtmfs[4];
+};
+"""
+
+MEM_FORMAT = """
+
+#seekto 0x0E;
+struct radioinfo radioinfo;
+
+#seekto 0x52;
+struct dataver dataver;
#seekto 0x5C;
struct {
@@ -134,17 +256,7 @@ struct {
} settings;
#seekto 0xc0;
-struct {
- ul16 zonenum;
- ul16 zoneindex[64];
-} zonedata;
-
-#seekto 0x142;
-struct {
- char name[14];
- ul16 chnum;
- ul16 chindex[16];
-} zones[64];
+struct zoneinfo zoneinfo;
#seekto 0x0D42;
struct {
@@ -185,128 +297,25 @@ struct {
u8 autoscan:1,
scanlist:7;
u8 alarmlist;
- u8 dtmfsignalinglist:4,
+ u8 rev_4:2,
pttidtype:2,
- rev_4:2;
+ dtmfsignalinglist:4;
ul16 dtmfcallid;
u8 reserve[3];
} channels[1027];
#seekto 0xb5c2;
-struct {
- ul16 scannum;
- ul16 scanindex[16];
-} scandata;
-
-#seekto 0xb5e4;
-struct {
- char name[14];
- u8 scantxch:4,
- scancondition:4;
- u8 hangtime:4,
- talkback:1,
- scanstatus:3;
- u8 chnum;
- ul16 specifych;
- ul16 PriorityCh1;
- ul16 PriorityCh2;
- u8 scanmode;
- ul16 chindex[100];
-} scans[16];
+struct scaninfo scans;
#seekto 0xc3e4;
-struct {
- ul16 vfoscannum;
- ul16 vfoscanindex[3];
-} vfoscandata;
-
-#seekto 0xc3ec;
-struct {
- u8 scantxch:4,
- scancondition:4;
- u8 hangtime:4,
- talkback:1,
- startcondition:1,
- rev_1:2;
- u8 scanmode;
- ul32 vhffreq_start;
- ul32 vhffreq_end;
- ul32 uhffreq_start;
- ul32 uhffreq_end;
- u8 rev;
-} vfoscans[3];
+struct vfoscaninfo vfoscans;
#seekto 0xc444;
-struct {
- ul16 alarmnum;
- ul16 alarmindex[8];
-} alarmdata;
-
-#seekto 0xc456;
-struct {
- char name[14];
- u8 alarmtype:4,
- alarmmode:4;
- ul16 jumpch;
- u8 localalarm:1,
- txbackground:1,
- ctcmode:2,
- rev_1:4;
- u8 alarmtime:4,
- alarmcycle:4;
- u8 mictime:4,
- txinterval:4;
- u8 alarmid[8];
- u8 alarmstatus;
- u8 rev_3[1];
- } alarms[8];
+struct alarminfo alarms;
#seekto 0xc848;
-struct {
- ul16 dtmfnum;
- ul16 dtmfindex[4];
-} dtmfdata;
+struct dtmfinfo dtmfinfos;
-#seekto 0xc852;
-struct {
- u8 autoresettime:4,
- codedelaytime:4;
- u8 stunmode:2,
- showani:1,
- sidetone:1,
- pttidtype:2,
- rev_1:2;
- char callid[10];
- char stunid[10];
- char revive[10];
- char bot[16];
- char eot[16];
- char rev_2[8];
-} dtmfcomm;
-
-#seekto 0xc89a;
-struct {
- char name[14];
- u8 codelen:4,
- signaling:4;
- u8 groupcode:4,
- intermediatecode:4;
- char fastcall1[16];
- char fastcall2[16];
- char fastcall3[16];
- char fastcall4[16];
- char fastcall5[16];
- char fastcall6[16];
- char fastcall7[16];
- char fastcall8[16];
- char fastcall9[16];
- char fastcall10[16];
- u8 rev_1:6,
- EncodingEnable:1,
- DecodingEnable:1;
- u8 dtmfstatus;
- u8 rev_2[12];
-} dtmfs[4];
"""
@@ -315,40 +324,13 @@ class HandshakeStatuses(Enum):
Wrong = 1
PwdWrong = 3
RadioWrong = 4
+ NoResponse = 5
-class MemoryRegions(Enum):
- """
- Defines the logical memory regions for this radio model.
- """
- radioHead = 2
- radioInfo = 3
- radioVer = 4
- settingData = 6
- zoneData = 7
- channelData = 8
- scanData = 11
- vfoScanData = 12
- alarmData = 13
- dTMFData = 15
-
-
-MEMORY_REGIONS_RANGES = {
- MemoryRegions.radioHead: (0, 14), # (Start addr, len)
- MemoryRegions.radioInfo: (14, 68),
- MemoryRegions.radioVer: (82, 10),
- MemoryRegions.settingData: (92, 100),
- MemoryRegions.zoneData: (192, 3202),
- MemoryRegions.channelData: (3394, 43136),
- MemoryRegions.scanData: (46530, 3618),
- MemoryRegions.vfoScanData: (50148, 68),
- MemoryRegions.alarmData: (50244, 258),
- MemoryRegions.dTMFData: (51272, 842)}
-
DTMFCHARSET = "0123456789ABCDabcd#*"
NAMECHARSET = chirp_common.CHARSET_ALPHANUMERIC + "-/;,._!? *#@$%&+=/<>~(){}]'"
SPECIAL_MEMORIES = {"VFOA": -2, "VFOB": -1}
-BANDWIDEH_LIST = ["NFM", "FM"]
+MODES = ["NFM", "FM", "AM"]
POWER_LEVELS = [
chirp_common.PowerLevel("Low", watts=5),
chirp_common.PowerLevel("High", watts=50)]
@@ -383,14 +365,128 @@ FREQ_STEP_List = [
{"name": "25kHz", "id": 25000}]
+class HA1GBank(chirp_common.NamedBank):
+
+ def get_name(self):
+ _bank = self._model._radio._memobj.zoneinfo.zones[self.index]
+ name = "".join(filter(_bank.name, NAMECHARSET, 14))
+ return name.rstrip()
+
+ def set_name(self, name):
+ _bank = self._model._radio._memobj.zoneinfo.zones[self.index]
+ _bank.name = str(name).ljust(14)[:14]
+
+
+class HA1GBankModel(chirp_common.BankModel):
+
+ @property
+ def zinfo(self):
+ return self._radio._memobj.zoneinfo
+
+ channelAlwaysHasBank = True
+
+ def get_num_mappings(self):
+ return len(self.get_mappings())
+
+ def get_mappings(self):
+ banks = self.zinfo.zones
+ bank_mappings = []
+ for index, _bank in enumerate(banks):
+ bank = HA1GBank(self, "%i" % index, "b%i" % (index + 1))
+ bank.index = index
+ bank_mappings.append(bank)
+
+ return bank_mappings
+
+ def get_used_zone_index(self):
+ return [x for x in
+ self.zinfo.zoneindex[0:self.zinfo.zonenum] if x != 0xFFFF]
+
+ def _get_channel_numbers_in_bank(self, bank):
+ if bank.index not in self.get_used_zone_index():
+ return set()
+
+ _members = self.zinfo.zones[bank.index]
+ return set([int(ch) - self._radio._skip_vfoch_count + 1
+ for ch in _members.chindex if ch != 0xFFFF
+ and int(ch) - self._radio._skip_vfoch_count + 1 > 0])
+
+ def _update_bank_with_channel_numbers(self, bank, channels_in_bank):
+ _members = self.zinfo.zones[bank.index]
+ if len(channels_in_bank) > len(_members.chindex):
+ raise Exception("Too many entries in bank %d" % bank.index)
+
+ empty = 0
+ for index, channel_number in enumerate(sorted(channels_in_bank)):
+ _members.chindex[index] = (
+ channel_number + self._radio._skip_vfoch_count - 1)
+ empty = index + 1
+ for index in range(empty, len(_members.chindex)):
+ _members.chindex[index] = 0xFFFF
+
+ _members.chnum = len(channels_in_bank)
+
+ def add_memory_to_mapping(self, memory, bank):
+ channels_in_bank = self._get_channel_numbers_in_bank(bank)
+ channels_in_bank.add(memory.number)
+ self._update_bank_with_channel_numbers(bank, channels_in_bank)
+
+ # enable bank
+ if bank.index not in self.get_used_zone_index():
+ self.zinfo.zoneindex[self.zinfo.zonenum] = bank.index
+ self.zinfo.zonenum += 1
+
+ def remove_memory_from_mapping(self, memory, bank):
+ channels_in_bank = self._get_channel_numbers_in_bank(bank)
+ try:
+ channels_in_bank.remove(memory.number)
+ except KeyError:
+ raise Exception("Memory %i is not in bank %s. Cannot remove" %
+ (memory.number, bank))
+ self._update_bank_with_channel_numbers(bank, channels_in_bank)
+
+ if not channels_in_bank and bank.index in self.get_used_zone_index():
+ # disable bank
+ settings = self._radio._memobj.settings
+ if settings.homepoweronzone_1 == bank.index:
+ settings.homepoweronzone_1 = 0xFFF
+ if settings.homepoweronzone_2 == bank.index:
+ settings.homepoweronzone_2 = 0xFFF
+ _zone_index = [x for x in self.get_used_zone_index()
+ if x != bank.index]
+ self.zinfo.zoneindex = (
+ _zone_index + [0xFFFF] * (
+ len(self.zinfo.zoneindex) - len(_zone_index)))
+ self.zinfo.zonenum -= 1
+
+ def get_mapping_memories(self, bank):
+ memories = []
+ for channel in self._get_channel_numbers_in_bank(bank):
+ memories.append(self._radio.get_memory(channel))
+
+ return memories
+
+ def get_memory_mappings(self, memory):
+ banks = []
+ for bank in self.get_mappings():
+ if memory.number in self._get_channel_numbers_in_bank(bank):
+ banks.append(bank)
+
+ return banks
+
+
def do_download(self):
error_map = {
HandshakeStatuses.RadioWrong: "Radio model mismatch",
HandshakeStatuses.PwdWrong: "Radio is password protected"}
try:
- handshake_result = handshake(self, self.pipe)
- if handshake_result == HandshakeStatuses.Normal:
- all_bytes = read_items(self, self.pipe)
+ serial = self.pipe
+ serial.timeout = SERIAL_TIMEOUT
+ handshake_result = handshake(self, serial)
+ if handshake_result == HandshakeStatuses.NoResponse:
+ raise errors.RadioNoResponse()
+ elif handshake_result == HandshakeStatuses.Normal:
+ all_bytes = self.read_items(serial)
return memmap.MemoryMapBytes(bytes(all_bytes))
raise errors.RadioError(error_map.get(
handshake_result, "Unknown error communicating with radio"))
@@ -408,9 +504,13 @@ def do_upload(self):
HandshakeStatuses.RadioWrong: "Radio model mismatch",
HandshakeStatuses.PwdWrong: "Radio is password protected"}
try:
- handshake_result = handshake(self, self.pipe)
- if handshake_result == HandshakeStatuses.Normal:
- write_items(self, self.pipe)
+ serial = self.pipe
+ serial.timeout = SERIAL_TIMEOUT
+ handshake_result = handshake(self, serial)
+ if handshake_result == HandshakeStatuses.NoResponse:
+ raise errors.RadioNoResponse()
+ elif handshake_result == HandshakeStatuses.Normal:
+ self.write_items(serial)
else:
raise errors.RadioError(error_map.get(
handshake_result, "Unknown error communicating with radio"))
@@ -429,53 +529,16 @@ def handshake(self, serial):
retry_delay = 0.05
for num in range(max_retries):
flag, databytes = exchange_block_with_radio(
- get_handshake_bytes(self.MODEL + " "),
+ get_handshake_bytes(self.current_model + " "),
serial, self.read_packet_len)
time.sleep(retry_delay)
if flag:
break
+ if not databytes:
+ return HandshakeStatuses.NoResponse
return validate_connection_handshake(self, databytes)
-def read_items(self, serial):
- all_bytes = bytearray(self._memsize)
- status = chirp_common.Status()
- status.msg = "Cloning from radio"
- status.cur = 0
- status.max = self._memsize
- for item in MemoryRegions:
- try:
- item_bytes = get_read_current_packet_bytes(
- self, item.value, serial, status)
- if item_bytes:
- write_memory_region(all_bytes, item_bytes, item)
- except Exception as e:
- LOG.error(
- f"read item_data error: {item.name} error_msg: {e}")
- continue
- return all_bytes
-
-
-def write_items(self, serial):
- status = chirp_common.Status()
- status.msg = "Uploading to radio"
- status.cur = 0
- status.max = self._memsize
- data_bytes = self.get_mmap()
- EXCLUDED_REGIONS = {MemoryRegions.radioHead,
- MemoryRegions.radioInfo,
- MemoryRegions.radioVer,
- MemoryRegions.zoneData,
- MemoryRegions.scanData,
- MemoryRegions.alarmData}
- for item in MemoryRegions:
- if item in EXCLUDED_REGIONS:
- continue
- item_bytes = get_write_item_bytes(data_bytes, item)
- write_item_current_page_bytes(
- self, serial, item_bytes, item.value, status)
-
-
def validate_connection_handshake(self, dataByte: bytes):
success_status = b"\x00\x01"
pwd_faild_flag = 1
@@ -483,8 +546,8 @@ def validate_connection_handshake(self, dataByte: bytes):
return HandshakeStatuses.Wrong
if dataByte[20] == pwd_faild_flag:
return HandshakeStatuses.PwdWrong
- radioType = dataByte[20: 20 + len(self.MODEL)]
- model_bytes = self.MODEL.encode("ascii")
+ radioType = dataByte[20: 20 + len(self.current_model)]
+ model_bytes = self.current_model.encode("ascii")
if radioType == model_bytes:
return HandshakeStatuses.Normal
else:
@@ -589,30 +652,13 @@ def write_item_current_page_bytes(self, serial, item_Bytes: bytes,
self.status_fn(status)
-def get_write_item_bytes(all_bytes: bytearray, item):
- """
- Get the bytes for a specific memory region
- - Uses MEMORY_REGIONS_RANGES to find start and length
- """
- if item not in MEMORY_REGIONS_RANGES:
- LOG.debug(f"Unknown memory Range:{item}")
- return b""
- start, length = MEMORY_REGIONS_RANGES[item]
- return all_bytes[start:start+length]
-
-
-def write_memory_region(all_bytes: bytearray,
- item_bytes: bytes, item):
+def copy_to_memory(all_bytes: bytearray,
+ item_bytes: bytes, start_addr: int, item_len: int):
"""
Put the given region bytes into the main memory array
- - Uses MEMORY_REGIONS_RANGES to find start and length
"""
- if item not in MEMORY_REGIONS_RANGES:
- LOG.debug(f"Unknown memory Range:{item}")
- return
- start, length = MEMORY_REGIONS_RANGES[item]
- item_len = min(len(item_bytes), length)
- all_bytes[start:start + item_len] = item_bytes[:item_len]
+ item_len = min(len(item_bytes), item_len)
+ all_bytes[start_addr:start_addr + item_len] = item_bytes[:item_len]
def exit_programming_mode(self):
@@ -651,16 +697,36 @@ def get_send_packet_bytes(data_type: int, packet_index: int,
return data_part + calculate_crc16(data_part) + b"\xff"
-def calculate_crc16(buf):
- crc = 0x0000
- for b in buf:
- crc ^= b
- for _ in range(8):
- if crc & 0x0001:
- crc = (crc >> 1) ^ 0xA001
- else:
- crc >>= 1
- return struct.pack("<H", crc)
+def format_version(ver):
+ return 'v%02i.%02i.%02i.%03i' % ver
+
+
+def unpack_version(raw_bytes):
+ current_ver = struct.unpack("BBBB", raw_bytes)
+ return format_version(current_ver)
+
+
+def validate_version(self, ver):
+ if compare_version(ver, self.REQUIRED_VER) < 0:
+ raise errors.RadioError(
+ ("Firmware is %s; You must update to %s or higher "
+ "to be compatible with CHIRP") % (ver, self.REQUIRED_VER))
+
+
+def compare_version(a, b):
+ version1 = tuple(map(int, a.lstrip('v').split('.')) if a else [])
+ version2 = tuple(map(int, b.lstrip('v').split('.')) if b else [])
+
+ if version1 > version2:
+ return 1
+ if version2 > version1:
+ return -1
+
+ return 0
+
+
+def calculate_crc16(data):
+ return struct.pack('<H', checksum.crc16_ibm_rev(data))
def _get_memory(self, mem, _mem, ch_index):
@@ -692,6 +758,22 @@ def _get_memory(self, mem, _mem, ch_index):
current_index=_mem.autoscan)))
mem.extra.append(
RadioSetting(
+ "alarmlist",
+ "Alarm System",
+ RadioSettingValueList(
+ get_namedict_by_items(self._alarm_list),
+ current_index=get_item_by_id(self._alarm_list,
+ _mem.alarmlist))))
+ mem.extra.append(
+ RadioSetting(
+ "dtmfsignalinglist",
+ "DTMF System",
+ RadioSettingValueList(
+ get_namedict_by_items(self._dtmf_list),
+ current_index=get_item_by_id(self._dtmf_list,
+ _mem.dtmfsignalinglist))))
+ mem.extra.append(
+ RadioSetting(
"offlineorreversal",
"Talkaround & Reversal",
RadioSettingValueList(OFFLINE_REVERSAL_LIST,
@@ -726,12 +808,16 @@ def _get_memory(self, mem, _mem, ch_index):
mem.duplex = ""
mem.offset = 0
elif tx_freq == 0xFFFFFFFF:
- mem.duplex = ""
+ mem.duplex = "off"
mem.offset = 0
else:
mem.duplex = mem.freq > tx_freq and "-" or "+"
mem.offset = abs(mem.freq - tx_freq)
- mem.mode = BANDWIDEH_LIST[(1 if _mem.bandwidth >= 3 else 0)]
+
+ mem.mode = MODES[(1 if _mem.bandwidth >= 3 else 0)]
+ if chirp_common.in_range(mem.freq, [self._airband]):
+ mem.mode = "AM"
+
rxtone = txtone = None
if _mem.rxctcvaluetype == 1:
tone_value = _mem.rxctc / 10.0
@@ -770,6 +856,11 @@ def get_model_info(self, model_info):
rs = RadioSetting("modelinfo.freqrange", "Frequency Range[MHz]", rs_value)
model_info.append(rs)
+ firmware_version = self.metadata.get('ha1g_firmware', 'UNKNOWN')
+ val = RadioSettingValueString(0, 128, firmware_version)
+ val.set_mutable(False)
+ model_info.append(RadioSetting("fw_ver", "Firmware Version", val))
+
def get_common_setting(self, common):
_settings = self._memobj.settings
@@ -880,7 +971,7 @@ def get_common_setting(self, common):
"Power On B",
RadioSettingValueList(opts,
current_index=_settings.poweron_type_2)))
- opts_dict = get_scan_item_list(self)
+ opts_dict = self.get_scan_item_list()
common.append(
get_radiosetting_by_key(
self, _settings, "scanlist", "Enable Scan List",
@@ -964,7 +1055,7 @@ def get_common_setting(self, common):
def get_dtmf_setting(self, dtmf):
- _dtmf_comm = self._memobj.dtmfcomm
+ _dtmf_comm = self._memobj.dtmfinfos.dtmfcomm
opts = ["OFF"] + ["%ss" % x for x in range(1, 16, 1)]
dtmf.append(
RadioSetting(
@@ -1035,7 +1126,7 @@ def get_dtmf_setting(self, dtmf):
def get_vfo_scan(self, vfoscan):
- _vfo_scan = self._memobj.vfoscans[0]
+ _vfo_scan = self._memobj.vfoscans.vfoscans[0]
opts = ["Carrier", "Time", "Search"]
vfoscan.append(
RadioSetting(
@@ -1064,17 +1155,17 @@ def get_vfo_scan(self, vfoscan):
RadioSettingValueList(opts,
current_index=_vfo_scan.startcondition)))
- freq_start = _vfo_scan.vhffreq_start / 1000000
+ freq_start = from_MHz(_vfo_scan.vhffreq_start)
vfoscan.append(
RadioSetting(
"vfoscan.vhffreq_start", "Start Frequency",
- RadioSettingValueFloat(136, 480, freq_start, 0.00001, 5)))
+ RadioSettingValueFloat(108, 480, freq_start, 0.00001, 5)))
- freq_end = _vfo_scan.vhffreq_end / 1000000
+ freq_end = from_MHz(_vfo_scan.vhffreq_end)
vfoscan.append(
RadioSetting(
"vfoscan.vhffreq_end", "End Frequency",
- RadioSettingValueFloat(136, 480, freq_end, 0.00001, 5)))
+ RadioSettingValueFloat(108, 480, freq_end, 0.00001, 5)))
def _set_memory(self, mem, _mem, ch_index):
@@ -1085,6 +1176,7 @@ def _set_memory(self, mem, _mem, ch_index):
ch_index_dict.append(ch_index)
elif ch_index in ch_index_dict and rx_freq <= 0:
ch_index_dict.remove(ch_index)
+ self.update_channel_indexes(ch_index, ch_index_dict)
set_ch_index(self, ch_index_dict)
_mem.set_raw(b"\x00" * 40)
if mem.empty:
@@ -1129,6 +1221,12 @@ def _set_memory(self, mem, _mem, ch_index):
if setting.get_name() == "tottime":
_mem.tottime = get_item_by_name(
TIMEOUTTIMER_LIST, str(setting.value))
+ elif setting.get_name() == "alarmlist":
+ _mem.alarmlist = get_item_by_name(
+ self._alarm_list, setting.value)
+ elif setting.get_name() == "dtmfsignalinglist":
+ _mem.dtmfsignalinglist = get_item_by_name(
+ self._dtmf_list, setting.value)
else:
setattr(_mem, setting.get_name(), setting.value)
return _mem
@@ -1144,7 +1242,7 @@ def get_radiosetting_by_key(self, _setting, item_key,
opts, current_index=get_item_by_id(opts_dict, item_value)))
item.set_apply_callback(
set_item_callback if callback is None else callback,
- _setting, item_key, opts_dict, self)
+ _setting, item_key, opts_dict)
return item
@@ -1156,7 +1254,7 @@ def get_item_by_id(items, value):
return next((i for i, item in enumerate(items) if item["id"] == value), 0)
-def set_item_callback(set_item, obj, name, items, self):
+def set_item_callback(set_item, obj, name, items):
item_value = get_item_by_name(items, set_item.value)
setattr(obj, name, item_value)
@@ -1196,7 +1294,7 @@ def set_ch_index(self, ch_index_list):
if len(_ch_data.chindex) < ch_num:
raise ValueError("Not enough space in chindex array")
_ch_data.chnum = ch_num
- for i in range(1027):
+ for i in range(len(_ch_data.chindex)):
_ch_data.chindex[i] = (
ch_index_list[i] if i < ch_num else 0xFFFF)
self._ch_cache = ch_index_list.copy()
@@ -1208,8 +1306,8 @@ def get_ch_rxfreq(mem):
ch_freq = (mem.freq // 10) * 10
if mem.freq == 0:
return mem.freq
- elif mem.freq < 136000000:
- ch_freq = 136000000
+ elif mem.freq < 108000000:
+ ch_freq = 108000000
elif mem.freq > 174000000 and mem.freq < 400000000:
ch_freq = 174000000
elif mem.freq > 480000000:
@@ -1217,21 +1315,6 @@ def get_ch_rxfreq(mem):
return ch_freq
-def get_scan_item_list(self):
- _scandata = self._memobj.scandata
- _scans = self._memobj.scans
- scan_dict = []
- scan_num = _scandata.scannum
- if scan_num > 0:
- for i in range(0, scan_num):
- scan_index = _scandata.scanindex[i]
- if scan_index < 16:
- scan_item = _scans[scan_index]
- scanname = "".join(filter(scan_item.name, NAMECHARSET, 12))
- scan_dict.append({"name": scanname, "id": scan_index})
- return scan_dict
-
-
def set_band_selection(set_item, obj,
opts, home_select_field_name,
home_index_field_name):
@@ -1253,6 +1336,11 @@ def filter(s, char_set, max_length=10, is_upper=False):
return s_
+def from_MHz(freq):
+ """Like chirp_common.from_MHz but returns a float"""
+ return freq / 1000000
+
+
@directory.register
class HA1G(chirp_common.CloneModeRadio):
"""Retevis HA1G"""
@@ -1260,11 +1348,44 @@ class HA1G(chirp_common.CloneModeRadio):
VENDOR = "Retevis"
MODEL = "HA1G"
BAUD_RATE = 115200
- _memsize = 0xD868
read_packet_len = 1047
write_page_len = 1024
current_model = "HA1G"
+ _skip_vfoch_count = 3
_ch_cache = None
+ _dtmf_list = [{"name": "OFF", "id": 15}]
+ _alarm_list = [{"name": "OFF", "id": 255}]
+
+ # This is the minimum required firmare version supported by this driver
+ REQUIRED_VER = "v1.1.11.6"
+
+ _airband = (108000000, 135999999)
+ _vhf = (136000000, 174000010)
+ _uhf = (400000000, 480000010)
+
+ """
+ Defines the logical memory regions for this radio model.
+ """
+ MEMORY_REGIONS_RANGES = {
+ "radioHead": (2, 0, 14), # (Region Id, Start addr, len)
+ "radioInfo": (3, 14, 68),
+ "radioVer": (4, 82, 10),
+ "settingData": (6, 92, 100),
+ "zoneData": (7, 192, 3202),
+ "channelData": (8, 3394, 43136),
+ "scanData": (11, 46530, 3618),
+ "vfoScanData": (12, 50148, 68),
+ "alarmData": (13, 50244, 258),
+ "dTMFData": (15, 51272, 842)}
+
+ EXCLUDED_REGIONS = {"radioHead",
+ "radioInfo",
+ "radioVer",
+ "scanData",
+ "alarmData"}
+
+ _memsize = max(start + size for _, start,
+ size in MEMORY_REGIONS_RANGES.values())
def get_features(self):
rf = chirp_common.RadioFeatures()
@@ -1274,8 +1395,9 @@ class HA1G(chirp_common.CloneModeRadio):
rf.has_rx_dtcs = True
rf.has_dtcs = True
rf.has_cross = True
- rf.has_bank = False
- rf.valid_bands = [(136000000, 174000010), (400000000, 480000010)]
+ rf.has_bank = self.supports_banks()
+ rf.has_bank_names = True
+ rf.valid_bands = [self._airband, self._vhf, self._uhf]
rf.has_tuning_step = False
rf.has_nostep_tuning = True
rf.valid_name_length = 12
@@ -1285,7 +1407,7 @@ class HA1G(chirp_common.CloneModeRadio):
c for c in "-/;,._!? *#@$%&+=/<>~(){}]'"
if c not in chirp_common.CHARSET_UPPER_NUMERIC)
rf.has_settings = True
- rf.valid_modes = BANDWIDEH_LIST
+ rf.valid_modes = MODES
rf.valid_power_levels = POWER_LEVELS
rf.has_comment = True
rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
@@ -1299,8 +1421,32 @@ class HA1G(chirp_common.CloneModeRadio):
"DTCS->DTCS"]
return rf
+ def validate_memory(self, mem):
+ msgs = []
+
+ if (chirp_common.in_range(mem.freq, [self._airband])
+ and not self.supports_airband()):
+ msgs.append(chirp_common.ValidationError(
+ _('Frequency in this range not supported by firmware')))
+
+ if (chirp_common.in_range(mem.freq, [self._airband])
+ and mem.mode != 'AM'):
+ msgs.append(chirp_common.ValidationWarning(
+ _('Frequency in this range requires AM mode')))
+ if (not chirp_common.in_range(mem.freq, [self._airband])
+ and mem.mode == 'AM'):
+ msgs.append(chirp_common.ValidationWarning(
+ _('Frequency in this range must not be AM mode')))
+
+ return msgs + super().validate_memory(mem)
+
+ def get_bank_model(self):
+ return HA1GBankModel(self)
+
def process_mmap(self):
- self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+ self._memobj = bitwise.parse(MEM_DEFINITIONS + MEM_FORMAT, self._mmap)
+ self._dtmf_list = self.get_dtmf_item_list()
+ self._alarm_list = self.get_alarm_item_list()
def sync_in(self):
try:
@@ -1317,12 +1463,62 @@ class HA1G(chirp_common.CloneModeRadio):
try:
logging.debug("come in sync_out")
do_upload(self)
+ except errors.RadioError:
+ raise
except Exception as e:
LOG.exception(
"Unexpected error during upload: %s" % e)
raise errors.RadioError(
"Unexpected error communicating with the radio")
+ def read_items(self, serial):
+ all_bytes = bytearray(self._memsize)
+ status = chirp_common.Status()
+ status.msg = "Cloning from radio"
+ status.cur = 0
+ status.max = self._memsize
+ items = self.MEMORY_REGIONS_RANGES.items()
+ for item_name, (region_id, start_addr, length) in items:
+ try:
+ item_bytes = get_read_current_packet_bytes(
+ self, region_id, serial, status)
+ if item_name == "radioVer" and item_bytes:
+ firmware_version = unpack_version(item_bytes[2:6])
+ validate_version(self, firmware_version)
+ self.metadata = {'ha1g_firmware': firmware_version}
+ if item_bytes:
+ copy_to_memory(all_bytes, item_bytes,
+ start_addr, length)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.error(
+ f"read item_data error: {item_name} error_msg: {e}")
+ continue
+ return all_bytes
+
+ def write_items(self, serial):
+ status = chirp_common.Status()
+ status.max = self._memsize
+ status.msg = "Uploading to radio"
+ status.cur = 0
+ data_bytes = self.get_mmap()
+ radiover_id, _, _ = self.MEMORY_REGIONS_RANGES["radioVer"]
+ item_bytes = get_read_current_packet_bytes(
+ self, radiover_id, serial, status)
+ if item_bytes:
+ firmware_version = unpack_version(item_bytes[2:6])
+ validate_version(self, firmware_version)
+ items = self.MEMORY_REGIONS_RANGES.items()
+ for item_name, (region_id, start_addr, length) in items:
+ if item_name in self.EXCLUDED_REGIONS:
+ continue
+ if not self.supports_banks() and item_name == "zoneData":
+ continue
+ item_bytes = data_bytes[start_addr:start_addr+length]
+ write_item_current_page_bytes(
+ self, serial, item_bytes, region_id, status)
+
def get_memory(self, number):
mem = chirp_common.Memory()
ch_index = 0
@@ -1400,7 +1596,7 @@ class HA1G(chirp_common.CloneModeRadio):
setattr(_settings, name, value)
elif name.startswith("dtmfsetting."):
name = name[12:]
- _dtmfcomm = self._memobj.dtmfcomm
+ _dtmfcomm = self._memobj.dtmfinfos.dtmfcomm
if (name in ["callid", "stunid", "revive"]):
value = filter(value, DTMFCHARSET, 10, True)
value = value.ljust(10, "\x00")
@@ -1410,15 +1606,132 @@ class HA1G(chirp_common.CloneModeRadio):
setattr(_dtmfcomm, name, value)
elif name.startswith("vfoscan."):
name = name[8:]
- _vfo_scan = self._memobj.vfoscans[0]
+ _vfo_scan = self._memobj.vfoscans.vfoscans[0]
if name in ["vhffreq_start", "vhffreq_end"]:
- value = int(value * 1000000)
+ value = chirp_common.to_MHz(value)
setattr(_vfo_scan, name, value)
LOG.debug("Setting %s: %s", name, value)
except Exception:
LOG.exception(element.get_name())
raise
+ def get_alarm_item_list(self):
+ _alarmdata = self._memobj.alarms
+ alarm_list = [{"name": "OFF", "id": 255}]
+ max_count = 8
+ alarm_num = min(_alarmdata.alarmnum, max_count)
+ if alarm_num > 0:
+ for i in range(alarm_num):
+ alarm_index = min(_alarmdata.alarmindex[i], max_count - 1)
+ alarm_item = _alarmdata.alarms[alarm_index]
+ alarm_item.alarmstatus = 1
+ alarmname = "".join(filter(alarm_item.name, NAMECHARSET, 12))
+ alarm_list.append({"name": alarmname, "id": alarm_index})
+ return alarm_list
+
+ def get_dtmf_item_list(self):
+ _dtmfdata = self._memobj.dtmfinfos
+ dtmf_list = [{"name": "OFF", "id": 15}]
+ max_count = 4
+ dtmf_num = min(_dtmfdata.dtmfnum, max_count)
+ if dtmf_num > 0:
+ for i in range(dtmf_num):
+ dtmf_index = min(_dtmfdata.dtmfindex[i], max_count - 1)
+ dtmf_item = _dtmfdata.dtmfs[dtmf_index]
+ dtmf_item.dtmfstatus = 1
+ dtmfname = "".join(filter(dtmf_item.name, NAMECHARSET, 12))
+ dtmf_list.append({"name": dtmfname, "id": dtmf_index})
+ return dtmf_list
+
+ def get_scan_item_list(self):
+ _scandata = self._memobj.scans
+ scan_dict = []
+ max_count = 16
+ scan_num = min(_scandata.scannum, max_count)
+ if scan_num > 0:
+ for i in range(0, scan_num):
+ scan_index = min(_scandata.scanindex[i], max_count)
+ scan_item = _scandata.scans[scan_index]
+ scanname = "".join(filter(scan_item.name, NAMECHARSET, 12))
+ scan_dict.append({"name": scanname, "id": scan_index})
+ return scan_dict
+
+ def supports_airband(self):
+ return compare_version(self.metadata.get(
+ 'ha1g_firmware', '0.0.0.0'), '1.1.12.5') >= 0
+
+ def supports_banks(self):
+ return compare_version(self.metadata.get(
+ 'ha1g_firmware', '0.0.0.0'), '1.1.13.1') >= 0
+
+ def update_channel_indexes(self, ch_index, ch_index_list):
+ """Check if home power on channels are valid,
+ if not, the radio will keep restarting"""
+ self.update_poweron_channel_index(ch_index, ch_index_list)
+ self.update_zone_channel_index(ch_index)
+ self.update_scan_channel_index(ch_index, ch_index_list)
+ self.update_alarm_channel_index(ch_index)
+
+ def update_poweron_channel_index(self, ch_index, ch_index_list):
+ settings = self._memobj.settings
+ if settings.homepoweronch_1 == ch_index:
+ settings.homepoweronzone_1 = 0xFFF
+ settings.homepoweronch_1 = (
+ ch_index_list[self._skip_vfoch_count] if ch_index_list else 0)
+ if settings.homepoweronch_2 == ch_index:
+ settings.homepoweronzone_2 = 0xFFF
+ settings.homepoweronch_2 = (
+ ch_index_list[self._skip_vfoch_count] if ch_index_list else 0)
+
+ def update_zone_channel_index(self, ch_index):
+ zones = self._memobj.zoneinfo
+ zonenum = min(len(zones.zoneindex), zones.zonenum)
+ for i in range(zonenum):
+ idx = zones.zoneindex[i]
+ if idx == 0xFFFF or idx >= len(zones.zones):
+ break
+ zone = zones.zones[idx]
+ if ch_index in zone.chindex:
+ chidx = zone.chindex.index(ch_index)
+ for j in range(chidx, zone.chnum-1):
+ zone.chindex[j] = zone.chindex[j+1]
+ zone.chindex[zone.chnum - 1] = 0xFFFF
+ zone.chnum -= 1
+
+ def update_scan_channel_index(self, ch_index, ch_index_list):
+ scans = self._memobj.scans
+ scannum = min(len(scans.scanindex), scans.scannum)
+ for i in range(scannum):
+ idx = scans.scanindex[i]
+ if idx == 0xFFFF or idx >= len(scans.scans):
+ break
+ scan = scans.scans[idx]
+ if scan.specifych == ch_index:
+ scan.specifych = (
+ ch_index_list[self._skip_vfoch_count]
+ if ch_index_list else 0)
+ if scan.PriorityCh1 == ch_index:
+ scan.PriorityCh1 = 0xFFFF
+ if scan.PriorityCh2 == ch_index:
+ scan.PriorityCh2 = 0xFFFF
+ if ch_index in scan.chindex:
+ chidx = scan.chindex.index(ch_index)
+ for j in range(chidx, scan.chnum-1):
+ scan.chindex[j] = scan.chindex[j+1]
+ scan.chindex[scan.chnum - 1] = 0xFFFF
+ scan.chnum -= 1
+
+ def update_alarm_channel_index(self, ch_index):
+ alarms = self._memobj.alarms
+ alarnum = min(len(alarms.alarmindex), alarms.alarmnum)
+ for i in range(alarnum):
+ idx = alarms.alarmindex[i]
+ if idx == 0xFFFF or idx >= len(alarms.alarms):
+ break
+ alarm = alarms.alarms[idx]
+ if alarm.jumpch == ch_index:
+ alarm.jumpch = 0
+
@directory.register
class HA1UV(HA1G):
diff --git a/chirp/drivers/retevis_ha2.py b/chirp/drivers/retevis_ha2.py
new file mode 100644
index 0000000..63cd9e3
--- /dev/null
+++ b/chirp/drivers/retevis_ha2.py
@@ -0,0 +1,1290 @@
+# Copyright 2024 Tommy <tommy83033@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 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 logging
+from chirp import chirp_common, bitwise, directory
+from chirp.settings import (
+ RadioSetting,
+ RadioSettingGroup,
+ RadioSettingSubGroup,
+ RadioSettingValueList,
+ RadioSettingValueString,
+ RadioSettings,
+ RadioSettingValueBoolean,
+ RadioSettingValueFloat,
+ RadioSettingValueInteger
+)
+from chirp.drivers import retevis_ha1g
+
+LOG = logging.getLogger(__name__)
+
+MEM_FORMAT = """
+#seekto 0x0E;
+struct radioinfo radioinfo;
+#seekto 0x52;
+struct dataver dataver;
+#seekto 0x5C;
+struct {
+ u8 readpwd[8];
+ u8 writepwd[8];
+ u8 poweronpwd[8];
+ u8 squelch;
+ u8 powersavingdelaytime:4,
+ powersavingmode:4;
+ u8 tk1_short;
+ u8 tk1_long;
+ u8 sk1_short;
+ u8 sk1_long;
+ u8 sk2_short;
+ u8 sk2_long;
+ u8 rev_2;
+ u8 chknoblock:1,
+ sidekeylock:1,
+ panellock:1,
+ rev_3:3,
+ autoormanuallock:1,
+ keylockswitch:1;
+ u8 rev_4:5,
+ lowbattery:1,
+ stunmode:2;
+ u8 voiceprompts:1,
+ touchtone:1,
+ txpermittone:1,
+ rev_5:1,
+ screenlight:1,
+ DualWatch:1,
+ rogerbeep:2;
+ ul16 poweron_type_1:4,
+ homepoweronzone_1:12;
+ ul16 homepoweronch_1;
+ u8 rev_6[27];
+ u8 micgain;
+ u8 rev_7[2];
+ u8 autooff;
+ u8 menuouttime;
+ u8 voxthreshold:4,
+ voxdelaytime:4;
+ u8 rev_8:1,
+ homeselect:3,
+ homeindex:2,
+ chdisplay:2;
+ ul16 poweron_type_2:4,
+ homepoweronzone_2:12;
+ ul16 homepoweronch_2;
+ u8 rev_9[4];
+ u8 freqstep;
+ u8 rev_10[2];
+ u8 backlightbrightness:4,
+ backlighttime:4;
+ u8 wxch;
+ u8 calltone;
+ u8 rev_11:5,
+ homechtype_3:1,
+ homechtype_2:1,
+ homechtype_1:1;
+ u8 spreadspectrummode;
+ u8 salezone;
+ u8 tailsoundeliminationsfre:7,
+ tailsoundeliminationswitch:1;
+ u8 singletone;
+ u8 rev_12:3,
+ btswitch:1,
+ rev_13:1,
+ aviationfreqrx:1,
+ fmchtype:1,
+ aliasdisplay:1;
+ u8 btinmic:1,
+ btinspk:1,
+ rev_14:6;
+ u8 scanlist;
+ u8 rev_15[2];
+ u16 radioid;
+ u8 rev_16[12];
+ u8 pttidaliastxmode;
+ u8 batterydisplaymode;
+ u8 rev_17[28];
+ u8 fmchannel;
+ u8 rev_18;
+ u8 aliasnum;
+ u8 timezone;
+ u8 rev_19[6];
+} settings;
+
+#seekto 0xf4;
+struct zoneinfo zoneinfo;
+
+struct channel {
+ char alias[14];
+ u8 chmode:4,
+ chpro:4;
+ u8 fixedpower:1,
+ fixedbandwidth:1,
+ rev_20:2,
+ power:2,
+ bandwidth:2;
+ ul32 rxfreq;
+ ul32 txfreq;
+ u16 rxctcvaluetype:2,
+ rxctctypecode:1,
+ rev_1:1,
+ rxctc:12;
+ u8 rxsqlmode;
+ u16 txctcvaluetype:2,
+ txctctypecode:1,
+ rev_2:1,
+ txctc:12;
+ u8 totpermissions:2,
+ tottime:6;
+ u8 vox:1,
+ offlineorreversal:2,
+ companding:2,
+ scramble:1,
+ rev_3:2;
+ u8 scrambleFreq;
+ u8 freqdiff;
+ u8 autoscan:1,
+ scanlist:7;
+ u8 alarmlist;
+ u8 rev_4:2,
+ pttidtype:2,
+ dtmfsignalinglist:4;
+ ul32 difffreq;
+};
+
+#seekto 0x0a16;
+struct {
+ ul16 chnum;
+ ul16 chindex[1024];
+ struct channel channels[1024];
+} channeldata;
+
+#seekto 0xb218;
+struct {
+ ul16 chnum;
+ ul16 chindex[3];
+ struct channel vfochannels[3];
+} vfochanneldata;
+
+#seekto 0xb298;
+struct scaninfo scans;
+
+#seekto 0xc0ba;
+struct vfoscaninfo vfoscans;
+
+#seekto 0xc0fe;
+struct alarminfo alarms;
+
+#seekto 0xc200;
+struct {
+ ul16 fmnum;
+ ul16 fmindex[64];
+ struct {
+ char name[14];
+ ul32 freq;
+ u8 bandwidth;
+ u8 rev_1[3];
+ } fms[64];
+} fmdata;
+
+#seekto 0xc802;
+struct dtmfinfo dtmfinfos;
+
+struct callsign {
+ char callsign[8];
+ u8 ssid;
+};
+
+#seekto 0xcc6e;
+struct {
+ u8 rev_1:4,
+ anaptttype:2,
+ aprsswitch:2;
+ u8 smartbeaconing:2,
+ rev_2:2,
+ beaconmode:2,
+ positionorgps:1,
+ beaconreceivetone:1;
+ u8 rev_3[3];
+ u8 digi_path:4,
+ aprsaudio:1,
+ rev_4:3;
+ struct callsign call;
+ struct callsign digi_path_p1[2];
+ struct callsign digi_path_p2[2];
+ struct callsign digi_path_p3[2];
+ struct callsign digi_path_p4[2];
+ struct callsign digi_path_f1[8];
+ struct callsign digi_path_f2[8];
+ char fixsymbol[2];
+ u8 rev_5[5];
+ struct {
+ char degrees[2];
+ char minutes[2];
+ char dot;
+ char seconds[2];
+ u8 direction;
+ } latitude;
+ struct {
+ char degrees[3];
+ char minutes[2];
+ char dot;
+ char seconds[2];
+ u8 direction;
+ } longitude;
+ u8 rev_6;
+ u8 tx_delay;
+ u8 autointerval;
+ u8 rev_7;
+ u8 screenhold;
+ u8 rev_8[4];
+ u8 ana_ch;
+ u8 rev_9[9];
+ struct {
+ u8 lowspeed;
+ u8 highspeed;
+ u8 slowrate;
+ u8 fastrate;
+ u8 turnangle;
+ u8 turnslope;
+ u8 turntime;
+ u8 rev_10;
+ } smartbeacons[4];
+ u8 rev_11[64];
+ struct {
+ ul32 freq;
+ u8 band;
+ } ana_chs[8];
+ u8 rev_12[188];
+ char commenttext[64];
+} aprsinfo;
+
+#seekto 0x11812;
+struct {
+ u8 gnssswitch:1,
+ pttuploadmode:2,
+ rev_1:5;
+ u8 rev_2[4];
+ u8 txtype:4,
+ autotxtime:4;
+ char replaytext[60];
+ u8 rev_3[10];
+} gnssinfo;
+
+#seekto 0x1185e;
+struct {
+ ul16 aliasnum;
+ ul16 aliasindex[30];
+ struct {
+ char alias[8];
+ } alias[30];
+} aliaslist;
+"""
+
+COMPANDER_LIST = ["OFF", "Tx/Rx", "Rx", "Tx"]
+
+SCRAMBLE_LIST = [
+ {"id": 255, "name": "Off"},
+ {"id": 0, "name": "2800"},
+ {"id": 1, "name": "2900"},
+ {"id": 2, "name": "3000"},
+ {"id": 3, "name": "3100"},
+ {"id": 4, "name": "3200"},
+ {"id": 5, "name": "3290"},
+ {"id": 6, "name": "3300"},
+ {"id": 7, "name": "3380"},
+ {"id": 8, "name": "3400"},
+ {"id": 9, "name": "3450"}
+]
+
+SIDE_KEY_LIST = [
+ {"name": "OFF", "id": 0},
+ {"name": "TX Power", "id": 1},
+ {"name": "Scan", "id": 2},
+ {"name": "FM Radio", "id": 3},
+ {"name": "Talkaround/Reversal", "id": 5},
+ {"name": "Monitor", "id": 15},
+ {"name": "Zone Plus", "id": 20},
+ {"name": "Zone Minus", "id": 21},
+ {"name": "Squelch", "id": 28},
+ {"name": "Emergency Start", "id": 29},
+ {"name": "Emergency Stop", "id": 30},
+ {"name": "Optional DTMF Code", "id": 32},
+ {"name": "Switch To QuickZone", "id": 35},
+ {"name": "Prog PTT", "id": 31}
+]
+
+DTMF_SIGNALINGLIST_DISABLED = 15
+TOTTIME_DISABLED = 36
+SQUELCHLEVEL_DISABLED = 4
+
+
+def _get_memory(radio, mem, _mem, ch_index, isvfo=False):
+ was_empty = False
+ if not isvfo:
+ ch_index_dict = retevis_ha1g.get_ch_index(radio)
+ was_empty = ch_index not in ch_index_dict
+
+ mem.extra = RadioSettingGroup("Extra", "extra")
+ mem.extra.append(
+ RadioSetting(
+ "tottime",
+ "TOT",
+ RadioSettingValueList(
+ retevis_ha1g.get_namedict_by_items(
+ retevis_ha1g.TIMEOUTTIMER_LIST),
+ current_index=(
+ was_empty and TOTTIME_DISABLED - 1 or (_mem.tottime - 1)))))
+ mem.extra.append(
+ RadioSetting(
+ "totpermissions",
+ "TX Permissions",
+ RadioSettingValueList(retevis_ha1g.TOTPERMISSIONS_LIST,
+ current_index=_mem.totpermissions)))
+ mem.extra.append(
+ RadioSetting(
+ "rxsqlmode",
+ "Squelch Level",
+ RadioSettingValueList(
+ retevis_ha1g.SQUELCHLEVEL_LIST,
+ current_index=(
+ was_empty and SQUELCHLEVEL_DISABLED or _mem.rxsqlmode))))
+ mem.extra.append(
+ RadioSetting(
+ "alarmlist",
+ "Alarm System",
+ RadioSettingValueList(
+ retevis_ha1g.get_namedict_by_items(radio._alarm_list),
+ current_index=retevis_ha1g.get_item_by_id(radio._alarm_list,
+ _mem.alarmlist))))
+ mem.extra.append(
+ RadioSetting(
+ "dtmfsignalinglist",
+ "DTMF System",
+ RadioSettingValueList(
+ retevis_ha1g.get_namedict_by_items(radio._dtmf_list),
+ current_index=retevis_ha1g.get_item_by_id(
+ radio._dtmf_list,
+ (was_empty and DTMF_SIGNALINGLIST_DISABLED
+ or _mem.dtmfsignalinglist)))))
+ mem.extra.append(
+ RadioSetting(
+ "offlineorreversal",
+ "Talkaround & Reversal",
+ RadioSettingValueList(retevis_ha1g.OFFLINE_REVERSAL_LIST,
+ current_index=_mem.offlineorreversal)))
+ mem.extra.append(
+ RadioSetting(
+ "companding", "Compander",
+ RadioSettingValueList(COMPANDER_LIST,
+ current_index=_mem.companding)))
+
+ scramble_index = (0 if _mem.scramble == 0
+ else retevis_ha1g.get_item_by_id(
+ SCRAMBLE_LIST, _mem.scrambleFreq))
+ mem.extra.append(
+ RadioSetting("scrambleFreq", "Scramble",
+ RadioSettingValueList(
+ retevis_ha1g.get_namedict_by_items(SCRAMBLE_LIST),
+ current_index=scramble_index)))
+ mem.extra.append(
+ RadioSetting(
+ "vox", "VOX",
+ RadioSettingValueBoolean(_mem.vox)))
+ mem.freq = int(_mem.rxfreq)
+ mem.name = radio.filter_name(str(_mem.alias).rstrip())
+ if isvfo:
+ mem.immutable += ["name"]
+
+ if was_empty or _mem.rxfreq == 0 or _mem.rxfreq == 0xFFFFFFFF:
+ mem.freq = 0
+ mem.empty = True
+ return mem
+
+ tx_freq = int(_mem.txfreq)
+ if mem.freq == tx_freq:
+ mem.duplex = ""
+ mem.offset = 0
+ elif tx_freq == 0xFFFFFFFF:
+ mem.duplex = "off"
+ mem.offset = 0
+ else:
+ mem.duplex = mem.freq > tx_freq and "-" or "+"
+ mem.offset = abs(mem.freq - tx_freq)
+
+ mem.mode = retevis_ha1g.MODES[(1 if _mem.bandwidth >= 3 else 0)]
+ if chirp_common.in_range(mem.freq, [radio._airband]):
+ mem.mode = "AM"
+
+ rxtone = txtone = None
+ if _mem.rxctcvaluetype == 1:
+ tone_value = _mem.rxctc / 10.0
+ if tone_value in chirp_common.TONES:
+ rxtone = tone_value
+ elif _mem.rxctcvaluetype in [2, 3]:
+ rxtone = int("%03o" % _mem.rxctc)
+
+ if _mem.txctcvaluetype == 1:
+ tone_value = _mem.txctc / 10.0
+ if tone_value in chirp_common.TONES:
+ txtone = tone_value
+ elif _mem.txctcvaluetype in [2, 3]:
+ txtone = int("%03o" % _mem.txctc)
+
+ rx_tone = (("" if _mem.rxctcvaluetype == 0
+ else "Tone" if _mem.rxctcvaluetype == 1 else "DTCS"),
+ rxtone, (_mem.rxctcvaluetype == 0x3) and "R" or "N")
+ tx_tone = (("" if _mem.txctcvaluetype == 0
+ else "Tone" if _mem.txctcvaluetype == 1 else "DTCS"),
+ txtone, (_mem.txctcvaluetype == 0x3) and "R" or "N")
+ chirp_common.split_tone_decode(mem, tx_tone, rx_tone)
+ mem.power = retevis_ha1g.POWER_LEVELS[(1 if _mem.power == 2 else 0)]
+ return mem
+
+
+def _set_memory(radio, mem, _mem, ch_index, isvfo=False):
+ if not isvfo:
+ ch_index_dict = retevis_ha1g.get_ch_index(radio)
+ flag = ch_index not in ch_index_dict and mem.freq != 0
+ if mem.freq != 0xFFFFFFFF and flag:
+ ch_index_dict.append(ch_index)
+ elif ch_index in ch_index_dict and mem.freq <= 0:
+ ch_index_dict.remove(ch_index)
+ radio.update_channel_indexes(ch_index, ch_index_dict)
+ retevis_ha1g.set_ch_index(radio, ch_index_dict)
+
+ _mem.fill_raw(b"\x00")
+ if mem.empty:
+ _mem.dtmfsignalinglist = DTMF_SIGNALINGLIST_DISABLED
+ _mem.tottime = TOTTIME_DISABLED
+ _mem.rxsqlmode = SQUELCHLEVEL_DISABLED
+ return
+
+ _mem.rxfreq = mem.freq
+ _mem.alias = mem.name.ljust(14)
+ txfrq = (int(mem.freq - mem.offset)
+ if mem.duplex == "-" and mem.offset > 0
+ else (int(mem.freq + mem.offset)
+ if mem.duplex == "+" and mem.offset > 0
+ else mem.freq))
+ _mem.txfreq = txfrq
+ _mem.bandwidth = 3 if mem.mode == "FM" else 1
+
+ if mem.power in retevis_ha1g.POWER_LEVELS:
+ _mem.power = (2 if retevis_ha1g.POWER_LEVELS.index(mem.power) == 1
+ else 0)
+ else:
+ _mem.power = 0
+
+ ((txmode, txtone, txpol),
+ (rxmode, rxtone, rxpol)) = chirp_common.split_tone_encode(mem)
+
+ if rxmode == "Tone":
+ _mem.rxctcvaluetype = 1
+ _mem.rxctc = int(rxtone * 10)
+ elif rxmode == "DTCS":
+ _mem.rxctcvaluetype = 3 if rxpol == "R" else 2
+ _mem.rxctc = int(str(rxtone), 8)
+ else:
+ _mem.rxctcvaluetype = 0
+
+ if txmode == "Tone":
+ _mem.txctcvaluetype = 1
+ _mem.txctc = int(txtone * 10)
+ elif txmode == "DTCS":
+ _mem.txctcvaluetype = 3 if txpol == "R" else 2
+ _mem.txctc = int(str(txtone), 8)
+ else:
+ _mem.txctcvaluetype = 0
+
+ for setting in mem.extra:
+ name = setting.get_name()
+ if name == "tottime":
+ _mem.tottime = retevis_ha1g.get_item_by_name(
+ retevis_ha1g.TIMEOUTTIMER_LIST, str(setting.value))
+ elif name == "alarmlist":
+ _mem.alarmlist = retevis_ha1g.get_item_by_name(
+ radio._alarm_list, setting.value)
+ elif name == "dtmfsignalinglist":
+ _mem.dtmfsignalinglist = retevis_ha1g.get_item_by_name(
+ radio._dtmf_list, setting.value)
+ elif name == "scrambleFreq":
+ _mem.scrambleFreq = retevis_ha1g.get_item_by_name(
+ SCRAMBLE_LIST, setting.value)
+ _mem.scramble = 0 if _mem.scrambleFreq == 255 else 1
+ else:
+ setattr(_mem, name, setting.value)
+ return _mem
+
+
+def _get_common_setting(radio, common):
+ _settings = radio._memobj.settings
+ opts = ["Low", "Normal", "Strengthen"]
+ common.append(RadioSetting(
+ "settings.micgain", "Mic Gain",
+ RadioSettingValueList(opts, current_index=_settings.micgain)))
+
+ opts = ["Stun WakeUp", "Stun TX", "Stun TX/RX"]
+ common.append(
+ RadioSetting("settings.stunmode", "Stun Type",
+ RadioSettingValueList(opts,
+ current_index=_settings.stunmode)))
+
+ opts_dict = [{"name": "%s" % (x + 1), "id": x} for x in range(0, 10, 1)]
+ common.append(retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "calltone", "Call Tone",
+ _settings.calltone, opts_dict))
+
+ opts = ["2.5kHz", "5kHz", "6.25kHz", "7.5kHz",
+ "8.33kHz", "10kHz", "12.5kHz", "15kHz",
+ "20kHz", "25kHz", "30kHz", "50kHz", "100kHz"]
+ common.append(
+ RadioSetting(
+ "settings.freqstep", "Frequency Step",
+ RadioSettingValueList(opts, current_index=_settings.freqstep)))
+
+ opts = ["OFF", "1:1", "1:2", "1:4"]
+ common.append(
+ RadioSetting(
+ "settings.powersavingmode", "Battery Mode",
+ RadioSettingValueList(
+ opts, current_index=_settings.powersavingmode)))
+
+ opts_dict = [
+ {"name": "%ss" % ((x + 1) * 5), "id": x} for x in range(0, 16, 1)]
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "powersavingdelaytime", "Battery Delay Time",
+ _settings.powersavingdelaytime, opts_dict))
+
+ opts_dict = [{"name": "%s" % x, "id": x} for x in range(1, 16, 1)]
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "backlightbrightness", "Backlight Brightness",
+ _settings.backlightbrightness, opts_dict))
+
+ opts = [
+ "Always", "5s", "10s", "15s", "20s", "25s", "30s",
+ "1min", "2min", "3min", "4min", "5min", "15min", "30min",
+ "45min", "1h"]
+ common.append(
+ RadioSetting("settings.backlighttime", "Backlight Time",
+ RadioSettingValueList(
+ opts, current_index=_settings.backlighttime)))
+
+ opts_dict = [{"name": "%s" % x, "id": x} for x in range(1, 16, 1)]
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "voxthreshold", "VOX Level",
+ _settings.voxthreshold, opts_dict))
+
+ opts_dict = [
+ {"name": "%sms" % (x * 500), "id": x} for x in range(1, 5, 1)]
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "voxdelaytime", "VOX Delay Time",
+ _settings.voxdelaytime, opts_dict))
+
+ opts_dict = [{"name": "OFF", "id": 0}] + [
+ {"name": "%ss" % x, "id": x} for x in range(5, 256, 5)]
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "menuouttime", "Menu Timeout Setting",
+ _settings.menuouttime, opts_dict))
+
+ opts = ["Manual", "Auto"]
+ common.append(
+ RadioSetting(
+ "settings.autoormanuallock", "Key Lock Mode",
+ RadioSettingValueList(opts,
+ current_index=_settings.autoormanuallock)))
+
+ opts = ["Frequency", "Name", "Channel"]
+ common.append(
+ RadioSetting(
+ "settings.chdisplay", "Display Mode",
+ RadioSettingValueList(opts, current_index=_settings.chdisplay)))
+
+ opts = ["Band A", "Band B", "Band A & Band B", "Band B & Band A"]
+ rs = RadioSetting(
+ "settings.homeselect",
+ "Band Selection",
+ RadioSettingValueList(
+ opts,
+ current_index=retevis_ha1g.get_band_selection(
+ _settings.homeselect, _settings.homeindex)))
+ rs.set_apply_callback(
+ retevis_ha1g.set_band_selection, _settings, opts,
+ "homeselect", "homeindex")
+ common.append(rs)
+
+ opts = ["Channel", "VFO Frequency"]
+ common.append(
+ RadioSetting(
+ "settings.homechtype_1",
+ "Channel Type A",
+ RadioSettingValueList(opts, current_index=_settings.homechtype_1)))
+ common.append(
+ RadioSetting(
+ "settings.homechtype_2",
+ "Channel Type B",
+ RadioSettingValueList(opts, current_index=_settings.homechtype_2)))
+
+ opts = ["Last Active Channel", "Designated Channel"]
+ common.append(
+ RadioSetting(
+ "settings.poweron_type_1",
+ "Power On A",
+ RadioSettingValueList(opts,
+ current_index=_settings.poweron_type_1)))
+ common.append(
+ RadioSetting(
+ "settings.poweron_type_2",
+ "Power On B",
+ RadioSettingValueList(opts,
+ current_index=_settings.poweron_type_2)))
+
+ opts = ["Icon", "Percent", "Voltage"]
+ common.append(RadioSetting(
+ "settings.batterydisplaymode", "Battery Display Mode",
+ RadioSettingValueList(
+ opts, current_index=_settings.batterydisplaymode)))
+
+ opts_dict = radio.get_scan_item_list()
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "scanlist", "Enable Scan List",
+ _settings.scanlist, opts_dict))
+
+ short_dict = SIDE_KEY_LIST[:13]
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "tk1_short", "Short Press Top Key",
+ _settings.tk1_short, short_dict))
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "tk1_long", "Long Press Top Key",
+ _settings.tk1_long, short_dict))
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "sk1_short", "Short Press Side Key 1",
+ _settings.sk1_short, short_dict))
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "sk1_long", "Long Press Side Key 1",
+ _settings.sk1_long, SIDE_KEY_LIST))
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "sk2_short", "Short Press Side Key 2",
+ _settings.sk2_short, short_dict))
+ common.append(
+ retevis_ha1g.get_radiosetting_by_key(
+ radio, _settings, "sk2_long", "Long Press Side Key 2",
+ _settings.sk2_long, retevis_ha1g.SIDE_KEY_LIST))
+
+ opts = ["55Hz", "120°", "180°", "240°"]
+ common.append(
+ RadioSetting(
+ "settings.tailsoundeliminationsfre", "CTC Tail Elimination",
+ RadioSettingValueList(
+ opts, current_index=_settings.tailsoundeliminationsfre)))
+
+ if _settings.salezone != 2:
+ opts = ["NOAA-%s" % x for x in range(1, 13, 1)]
+ common.append(
+ RadioSetting(
+ "settings.wxch", "NOAA Channel",
+ RadioSettingValueList(opts, current_index=_settings.wxch)))
+
+ opts = ["1000Hz", "1450Hz", "1750Hz", "2100Hz"]
+ common.append(
+ RadioSetting(
+ "settings.singletone", "Single Tone",
+ RadioSettingValueList(opts, current_index=_settings.singletone)))
+
+ opts = ["OFF", "Roger Beep", "MDC"]
+ common.append(
+ RadioSetting(
+ "settings.rogerbeep", "Roger Beep",
+ RadioSettingValueList(opts, current_index=_settings.rogerbeep)))
+
+ opts = ["OFF", "0.5h", "1.0h", "1.5h", "2.0h", "2.5h", "3.0h"]
+ common.append(
+ RadioSetting(
+ "settings.autooff", "Auto Power Off",
+ RadioSettingValueList(opts, current_index=_settings.autooff)))
+
+ opts = ["OFF", "BOT", "EOT", "BOTH"]
+ common.append(
+ RadioSetting(
+ "settings.pttidaliastxmode", "PTTID Alias TX Mode",
+ RadioSettingValueList(opts,
+ current_index=_settings.pttidaliastxmode)))
+
+ opts = ["Alias-%s" % x for x in range(1, 31, 1)]
+ rs = RadioSetting(
+ "settings.aliasnum", "Radio Alias",
+ RadioSettingValueList(opts, current_index=_settings.aliasnum))
+ rs.set_doc("Radio Alias can quickly identify who is calling")
+ common.append(rs)
+
+ opts = [("UTC%s" % x if x < 0 else "UTC+%s" % x)
+ for x in range(-12, 14, 1)]
+ common.append(
+ RadioSetting(
+ "settings.timezone", "Time Zone",
+ RadioSettingValueList(opts, current_index=_settings.timezone)))
+
+ common.append(
+ RadioSetting(
+ "settings.tailsoundeliminationswitch",
+ "Tail Elimination Switch",
+ RadioSettingValueBoolean(_settings.tailsoundeliminationswitch)))
+ common.append(
+ RadioSetting(
+ "settings.touchtone", "Key Beep",
+ RadioSettingValueBoolean(_settings.touchtone)))
+ common.append(
+ RadioSetting(
+ "settings.txpermittone", "TX Permit Tone",
+ RadioSettingValueBoolean(_settings.txpermittone)))
+ common.append(
+ RadioSetting(
+ "settings.voiceprompts", "Voice Broadcast",
+ RadioSettingValueBoolean(_settings.voiceprompts)))
+ common.append(
+ RadioSetting(
+ "settings.chknoblock", "Channel Knob Lock",
+ RadioSettingValueBoolean(_settings.chknoblock)))
+ common.append(
+ RadioSetting(
+ "settings.panellock", "Keyboard Lock",
+ RadioSettingValueBoolean(_settings.panellock)))
+ common.append(
+ RadioSetting(
+ "settings.sidekeylock", "Side Key Lock",
+ RadioSettingValueBoolean(_settings.sidekeylock)))
+ common.append(
+ RadioSetting(
+ "settings.lowbattery", "Low Battery Alert",
+ RadioSettingValueBoolean(_settings.lowbattery)))
+ common.append(
+ RadioSetting(
+ "settings.btswitch", "BT Switch",
+ RadioSettingValueBoolean(_settings.btswitch)))
+ common.append(
+ RadioSetting(
+ "settings.screenlight", "Call in Light",
+ RadioSettingValueBoolean(_reverse_state(_settings.screenlight))))
+ common.append(
+ RadioSetting(
+ "settings.btinspk", "BT + INT Spk",
+ RadioSettingValueBoolean(_settings.btinspk)))
+
+
+def _get_vfo_scan(radio, vfoscan):
+ _vfo_scan = radio._memobj.vfoscans.vfoscans[0]
+ opts = ["Carrier", "Time", "Search"]
+ vfoscan.append(
+ RadioSetting(
+ "vfoscan.scanmode", "Scan Mode",
+ RadioSettingValueList(opts, current_index=_vfo_scan.scanmode)))
+
+ opts = ["Carrier", "CTC/DCS"]
+ vfoscan.append(
+ RadioSetting(
+ "vfoscan.scancondition", "Scan Condition",
+ RadioSettingValueList(opts,
+ current_index=_vfo_scan.scancondition)))
+
+ opts = ["%s" % (x + 1) for x in range(0, 16, 1)]
+ vfoscan.append(
+ RadioSetting(
+ "vfoscan.hangtime", "Scan Hang Time[s]",
+ RadioSettingValueList(opts, current_index=_vfo_scan.hangtime)))
+ vfoscan.append(
+ RadioSetting(
+ "vfoscan.talkback", "Talk Back Enable",
+ RadioSettingValueBoolean(_vfo_scan.talkback)))
+
+ opts = ["Current Frequency", "Preset Frequency"]
+ vfoscan.append(
+ RadioSetting(
+ "vfoscan.startcondition", "Start Condition",
+ RadioSettingValueList(opts,
+ current_index=_vfo_scan.startcondition)))
+
+ freq_start = retevis_ha1g.from_MHz(_vfo_scan.vhffreq_start)
+ vfoscan.append(
+ RadioSetting(
+ "vfoscan.vhffreq_start", "Start Frequency",
+ RadioSettingValueFloat(108, 600, freq_start, 0.00001, 5)))
+
+ freq_end = retevis_ha1g.from_MHz(_vfo_scan.vhffreq_end)
+ vfoscan.append(
+ RadioSetting(
+ "vfoscan.vhffreq_end", "End Frequency",
+ RadioSettingValueFloat(108, 600, freq_end, 0.00001, 5)))
+
+
+def _get_aprs_setting(radio, aprs):
+ _aprsinfo = radio._memobj.aprsinfo
+ aprs.append(
+ RadioSetting(
+ "aprsinfo.aprsswitch", "APRS Switch",
+ RadioSettingValueBoolean(_aprsinfo.aprsswitch)))
+
+ opts = ["Auto", "Manual", "Smart"]
+ aprs.append(RadioSetting(
+ "aprsinfo.beaconmode", "Beacon TX Mode",
+ RadioSettingValueList(opts, current_index=_aprsinfo.beaconmode)))
+
+ opts = ["100ms", "150ms", "200ms", "250ms",
+ "300ms", "400ms", "500ms", "750ms", "1000ms"]
+ aprs.append(RadioSetting(
+ "aprsinfo.tx_delay", "APRS Tx Delay",
+ RadioSettingValueList(opts, current_index=_aprsinfo.tx_delay)))
+
+ opts = ["%ss" % x for x in range(3, 16, 1)] + ["Infinite"]
+ aprs.append(RadioSetting(
+ "aprsinfo.screenhold", "APRS Screen Hold Time",
+ RadioSettingValueList(opts, current_index=_aprsinfo.screenhold)))
+
+ opts = [
+ "30s", "1min", "2min", "3min", "5min", "10min", "15min",
+ "20min", "30min", "60min"
+ ]
+ aprs.append(RadioSetting(
+ "aprsinfo.autointerval", "APRS Beacon Interval",
+ RadioSettingValueList(opts, current_index=_aprsinfo.autointerval)))
+
+ aprs.append(
+ RadioSetting(
+ "aprsinfo.beaconreceivetone", "APRS Ringer",
+ RadioSettingValueBoolean(
+ _reverse_state(_aprsinfo.beaconreceivetone))))
+
+ opts = ["GNSS", "Manual"]
+ aprs.append(RadioSetting(
+ "aprsinfo.positionorgps", "My Position",
+ RadioSettingValueList(opts, current_index=_aprsinfo.positionorgps)))
+
+ opts = ["OFF", "Type 1", "Type 2", "Type 3"]
+ aprs.append(RadioSetting(
+ "aprsinfo.smartbeaconing", "Smart Beacon",
+ RadioSettingValueList(opts, current_index=_aprsinfo.smartbeaconing)))
+
+ for i in range(3):
+ smartbeacon = _aprsinfo.smartbeacons[i]
+ rsg = RadioSettingSubGroup(
+ "Type-%d" % (i + 1), "Smart Beacon Type %d" % (i + 1))
+ rs = RadioSetting(
+ "aprsinfo.smartbeacons.lowspeed_%d" % i, "Low Speed (km/h)",
+ RadioSettingValueInteger(2, 30, smartbeacon.lowspeed))
+ rs.set_apply_callback(_set_int_callback, smartbeacon, "lowspeed")
+ rsg.append(rs)
+ rs = RadioSetting(
+ "aprsinfo.smartbeacons.highspeed_%d" % i, "High Speed (km/h)",
+ RadioSettingValueInteger(3, 90, smartbeacon.highspeed))
+ rs.set_apply_callback(_set_int_callback, smartbeacon, "highspeed")
+ rsg.append(rs)
+ rs = RadioSetting(
+ "aprsinfo.smartbeacons.slowrate_%d" % i, "Slow Rate (min)",
+ RadioSettingValueInteger(1, 100, smartbeacon.slowrate))
+ rs.set_apply_callback(_set_int_callback, smartbeacon, "slowrate")
+ rsg.append(rs)
+ rs = RadioSetting(
+ "aprsinfo.smartbeacons.fastrate_%d" % i, "Fast Rate (s)",
+ RadioSettingValueInteger(10, 180, smartbeacon.fastrate))
+ rs.set_apply_callback(_set_int_callback, smartbeacon, "fastrate")
+ rsg.append(rs)
+ rs = RadioSetting(
+ "aprsinfo.smartbeacons.turnangle_%d" % i, "Turn Angle (deg)",
+ RadioSettingValueInteger(1, 100, smartbeacon.turnangle))
+ rs.set_apply_callback(_set_int_callback, smartbeacon, "turnangle")
+ rsg.append(rs)
+ rs = RadioSetting(
+ "aprsinfo.smartbeacons.turnslope_%d" % i, "Turn Slope (deg)",
+ RadioSettingValueInteger(10, 180, smartbeacon.turnslope))
+ rs.set_apply_callback(_set_int_callback, smartbeacon, "turnslope")
+ rsg.append(rs)
+ rs = RadioSetting(
+ "aprsinfo.smartbeacons.turntime_%d" % i, "Turn Time (s)",
+ RadioSettingValueInteger(1, 100, smartbeacon.turntime))
+ rs.set_apply_callback(_set_int_callback, smartbeacon, "turntime")
+ rsg.append(rs)
+ aprs.append(rsg)
+
+
+def _get_ana_aprs_setting(radio, aprs):
+ _aprsinfo = radio._memobj.aprsinfo
+ aprs.append(
+ RadioSetting(
+ "aprsinfo.anaptttype", "PTT Report Mode",
+ RadioSettingValueBoolean(_reverse_state(_aprsinfo.anaptttype))))
+ aprs.append(
+ RadioSetting(
+ "aprsinfo.aprsaudio", "APRS Audio",
+ RadioSettingValueBoolean(_aprsinfo.aprsaudio)))
+ _get_callsign_setting(aprs, [_aprsinfo.call], "_aprsinfo.Mycall", "My")
+ opts = [
+ "Selected Channel", "Channel 1", "Channel 2", "Channel 3",
+ "Channel 4", "Channel 5", "Channel 6", "Channel 7",
+ "Channel 8"]
+ aprs.append(RadioSetting(
+ "aprsinfo.ana_ch", "Channel",
+ RadioSettingValueList(opts, current_index=_aprsinfo.ana_ch)))
+
+ opts = [
+ "None", "WIDE1-1", "WIDE1-1,WIDE1-2", "Path1",
+ "Path2", "Path3", "Path4", "Full1", "Full2"]
+ aprs.append(RadioSetting(
+ "aprsinfo.digi_path", "DIGI Path",
+ RadioSettingValueList(opts, current_index=_aprsinfo.digi_path)))
+
+ rsg = RadioSettingSubGroup("AnaChannel", "Channel")
+ for i in range(len(_aprsinfo.ana_chs)):
+ ch_freq = _aprsinfo.ana_chs[i].freq / 100000
+ rs = RadioSetting(
+ "aprsinfo.ana_ch_%d" % i, "Channel %d" % (i + 1),
+ RadioSettingValueFloat(108, 600, ch_freq, 0.00001, 5))
+ rs.set_apply_callback(_set_freq_callback,
+ _aprsinfo.ana_chs[i], "freq", 100000)
+ rsg.append(rs)
+ aprs.append(rsg)
+
+ path_names = ["Path1", "Path2", "Path3", "Path4", "Full1", "Full2"]
+ path_objs = [
+ _aprsinfo.digi_path_p1, _aprsinfo.digi_path_p2,
+ _aprsinfo.digi_path_p3, _aprsinfo.digi_path_p4,
+ _aprsinfo.digi_path_f1, _aprsinfo.digi_path_f2]
+ for name, obj in zip(path_names, path_objs):
+ rsg = RadioSettingSubGroup(name, name)
+ _get_callsign_setting(rsg, obj, name)
+ aprs.append(rsg)
+
+
+def _get_gnss_setting(radio, gnss):
+ _gnssinfo = radio._memobj.gnssinfo
+ gnss.append(
+ RadioSetting(
+ "gnssinfo.gnssswitch", "GNSS On/Off",
+ RadioSettingValueBoolean(_gnssinfo.gnssswitch)))
+
+ opts = ["OFF", "TX Start", "TX End"]
+ gnss.append(RadioSetting(
+ "gnssinfo.pttuploadmode", "PTT Report Mode",
+ RadioSettingValueList(opts, current_index=_gnssinfo.pttuploadmode)))
+
+ opts = ["Manual", "Auto"]
+ gnss.append(RadioSetting(
+ "gnssinfo.txtype", "TX Type",
+ RadioSettingValueList(opts, current_index=_gnssinfo.txtype)))
+
+ opts = [
+ "30s", "1min", "2min", "3min", "5min",
+ "10min", "20min", "30min", "60min"
+ ]
+ gnss.append(RadioSetting(
+ "gnssinfo.autotxtime", "Auto TX Interval",
+ RadioSettingValueList(opts, current_index=_gnssinfo.autotxtime)))
+
+ replay_text_len = 60
+ rs = RadioSetting(
+ "gnssinfo.replaytext", "Comment Text",
+ RadioSettingValueString(
+ 0, replay_text_len,
+ "".join(retevis_ha1g.filter(
+ _gnssinfo.replaytext, retevis_ha1g.NAMECHARSET,
+ replay_text_len, True)),
+ False, retevis_ha1g.NAMECHARSET))
+ rs.set_apply_callback(
+ _set_char_callback, _gnssinfo, "replaytext",
+ replay_text_len, retevis_ha1g.NAMECHARSET)
+ gnss.append(rs)
+
+
+def _get_fm_setting(radio, fm):
+ _fminfo = radio._memobj.fmdata.fms
+ _settings = radio._memobj.settings
+ fm.append(
+ RadioSetting(
+ "settings.DualWatch", "dual watch",
+ RadioSettingValueBoolean(_reverse_state(_settings.DualWatch))))
+
+ opts = ["Channel", "VFO Frequency"]
+ fm.append(RadioSetting(
+ "settings.fmchtype", "Channel Type",
+ RadioSettingValueList(opts, current_index=_settings.fmchtype)))
+
+ opts = ["FM-%d" % x for x in range(1, 65)]
+ fm.append(RadioSetting(
+ "settings.fmchannel", "Channel",
+ RadioSettingValueList(opts, current_index=_settings.fmchannel)))
+
+ for i in range(len(_fminfo)):
+ fm_freq = retevis_ha1g.from_MHz(_fminfo[i].freq)
+ rs = RadioSetting(
+ "fms.freq_%s" % i, "freq %s" % (i + 1),
+ RadioSettingValueFloat(50, 115, fm_freq, 0.0, 1))
+ rs.set_apply_callback(_set_freq_callback,
+ _fminfo[i], "freq", 1000000)
+ fm.append(rs)
+
+
+def _get_radio_alias_setting(radio, radioalias):
+ _radioaliasinfo = radio._memobj.aliaslist.alias
+ alias_len = 8
+ for i in range(len(_radioaliasinfo)):
+ rs = RadioSetting(
+ "radioalias.alias_%s" % i, "alias %s" % (i + 1),
+ RadioSettingValueString(
+ 0, alias_len,
+ "".join(retevis_ha1g.filter(
+ _radioaliasinfo[i].alias, retevis_ha1g.NAMECHARSET,
+ alias_len, True)),
+ False, retevis_ha1g.NAMECHARSET))
+ rs.set_apply_callback(
+ _set_char_callback, _radioaliasinfo[i], "alias", alias_len)
+ radioalias.append(rs)
+
+
+def _get_model_info(radio, model_info):
+ rs_value = RadioSettingValueString(0, 20, radio.current_model)
+ rs_value.set_mutable(False)
+ rs = RadioSetting("modelinfo.Machinecode", "Machine Code", rs_value)
+ model_info.append(rs)
+ rs_value = RadioSettingValueString(0, 100, "108.00000-600.00000")
+ rs_value.set_mutable(False)
+ rs = RadioSetting("modelinfo.freqrange", "Frequency Range[MHz]", rs_value)
+ model_info.append(rs)
+
+
+def _get_callsign_setting(rsg, item, name, name_prefix=""):
+ callsign_input_len = 6
+ callsign_max_len = 8
+ opts = ["-%d" % x for x in range(0, 16, 1)]
+ item_len = len(item)
+ for i in range(item_len):
+ cs_name = ("%s Callsign %d" % (name_prefix, (i + 1))
+ if item_len > 1 else "%s Callsign" % name_prefix)
+ rs = RadioSetting(
+ "%s.callsign_%s" % (name, i), cs_name,
+ RadioSettingValueString(
+ 0, callsign_input_len,
+ "".join(retevis_ha1g.filter(
+ item[i].callsign, retevis_ha1g.NAMECHARSET,
+ callsign_input_len, True)),
+ False, retevis_ha1g.NAMECHARSET))
+ rs.set_apply_callback(
+ _set_char_callback, item[i], "callsign",
+ callsign_max_len, retevis_ha1g.NAMECHARSET)
+ rsg.append(rs)
+ ssid_name = ("%s SSID %d" % (name_prefix, (i + 1))
+ if item_len > 1 else "%s SSID" % name_prefix)
+ rs = RadioSetting(
+ "%s.ssid_%s" % (name, i), ssid_name,
+ RadioSettingValueList(opts, current_index=item[i].ssid))
+ rs.set_apply_callback(_set_ssid_callback, item[i], "ssid")
+ rsg.append(rs)
+
+
+def _set_char_callback(set_item, obj, name: str, charlen: int, charset=None):
+ if charset is None:
+ setattr(obj, name, str(set_item.value).ljust(charlen, "\x00"))
+ else:
+ setattr(obj, name, retevis_ha1g.filter(
+ set_item.value, retevis_ha1g.NAMECHARSET, charlen, True
+ ).ljust(charlen, "\x00"))
+
+
+def _set_freq_callback(set_item, obj, name: str, freq_hz):
+ setattr(obj, name, int(round(set_item.value * freq_hz)))
+
+
+def _set_int_callback(set_item, obj, name: str):
+ setattr(obj, name, int(set_item.value))
+
+
+def _set_ssid_callback(set_item, obj, name: str):
+ setattr(obj, name, int(set_item.value))
+
+
+def _reverse_state(value):
+ return value == 0
+
+
+@directory.register
+class HA2(retevis_ha1g.HA1G):
+ """Retevis HA2 Driver Implementation"""
+
+ MODEL = "HA2"
+ current_model = "Ailunce HA2"
+ NEEDS_VER_CHECK = False
+ REQUIRED_VER = "v1.0.0.0"
+ _skip_vfoch_count = 0
+
+ MEMORY_REGIONS_RANGES = {
+ "radioHead": (2, 0, 14),
+ "radioInfo": (3, 14, 68),
+ "radioVer": (4, 82, 10),
+ "settingData": (6, 92, 152),
+ "zoneData": (7, 244, 2338),
+ "channelData": (8, 2582, 43010),
+ "vfoChannelData": (9, 45592, 128),
+ "scanData": (11, 45720, 3618),
+ "vfoScanData": (12, 49338, 68),
+ "alarmData": (13, 49406, 258),
+ "fmdata": (14, 49664, 1538),
+ "dTMFData": (15, 51202, 842),
+ "aprsData": (38, 52334, 19364),
+ "gnssData": (51, 71698, 76),
+ "aliasData": (53, 71774, 302)
+ }
+ _memsize = max(start + size for _, start,
+ size in MEMORY_REGIONS_RANGES.values())
+ _airband = (108000000, 135999999)
+ _vhf_uhf = (136000000, 600000001)
+
+ def get_features(self):
+ rf = super().get_features()
+ rf.memory_bounds = (1, 1024)
+ rf.valid_bands = [self._airband, self._vhf_uhf]
+ return rf
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(retevis_ha1g.MEM_DEFINITIONS + MEM_FORMAT,
+ self._mmap)
+ self._dtmf_list = self.get_dtmf_item_list()
+ self._alarm_list = self.get_alarm_item_list()
+
+ def get_memory(self, number):
+ mem = chirp_common.Memory()
+ _chs = self._memobj.channeldata.channels
+ _vfochs = self._memobj.vfochanneldata.vfochannels
+ channels_len = len(_chs)
+ if isinstance(number, str):
+ mem.extd_number = number
+ ch_index = 0 if number == "VFOA" else 1
+ mem.number = channels_len + ch_index + 1
+ _mem = _vfochs[ch_index]
+ elif number > channels_len:
+ mem.extd_number = "VFOA" if number - channels_len == 1 else "VFOB"
+ ch_index = 0 if mem.extd_number == "VFOA" else 1
+ _mem = _vfochs[ch_index]
+ mem.number = channels_len + ch_index + 1
+ else:
+ mem.number = number
+ ch_index = number - 1
+ _mem = _chs[ch_index]
+ return _get_memory(self, mem, _mem, ch_index,
+ mem.number > channels_len)
+
+ def set_memory(self, mem):
+ _chs = self._memobj.channeldata.channels
+ _vfochs = self._memobj.vfochanneldata.vfochannels
+ channels_len = len(_chs)
+ if mem.number > channels_len:
+ ch_index = 0 if mem.extd_number == "VFOA" else 1
+ _mem = _vfochs[ch_index]
+ _set_memory(self, mem, _mem, ch_index, True)
+ else:
+ _mem = _chs[mem.number - 1]
+ _set_memory(self, mem, _mem, mem.number - 1)
+ LOG.debug("Setting %i(%s)" % (mem.number, mem.extd_number))
+
+ def get_settings(self):
+ model_info = RadioSettingGroup("info", "Model Information")
+ common = RadioSettingGroup("basic", "Common Settings")
+ dtmf = RadioSettingGroup("dtmfe", "DTMF Settings")
+ vfoscan = RadioSettingGroup("vfoscan", "VFO Scan")
+ aprs = RadioSettingGroup("aprsinfo", "APRS Settings")
+ ana_aprs = RadioSettingGroup("aprsinfo", "Analog APRS Settings")
+ gnss = RadioSettingGroup("gnssinfo", "GNSS Settings")
+ fm = RadioSettingGroup("fminfo", "FM Settings")
+ radioalias = RadioSettingGroup("aliasinfo", "Radio Alias Settings")
+ setmode = RadioSettings(model_info, common, dtmf,
+ vfoscan, aprs, ana_aprs, gnss, fm, radioalias)
+ try:
+ _get_model_info(self, model_info)
+ _get_common_setting(self, common)
+ retevis_ha1g.get_dtmf_setting(self, dtmf)
+ _get_vfo_scan(self, vfoscan)
+ _get_aprs_setting(self, aprs)
+ _get_ana_aprs_setting(self, ana_aprs)
+ _get_gnss_setting(self, gnss)
+ _get_fm_setting(self, fm)
+ _get_radio_alias_setting(self, radioalias)
+ except Exception as e:
+ LOG.exception("Error getting settings: %s", e)
+ return setmode
+
+ def set_settings(self, uisettings):
+ for element in uisettings:
+ if not isinstance(element, RadioSetting):
+ self.set_settings(element)
+ continue
+ if not element.changed():
+ continue
+ try:
+ if element.has_apply_callback():
+ LOG.debug("Using apply callback")
+ element.run_apply_callback()
+ else:
+ name = element.get_name()
+ value = element.value
+ if name.startswith("settings."):
+ name = name[9:]
+ if name == "screenlight" or name == "DualWatch":
+ value = 0 if value else 1
+ _settings = self._memobj.settings
+ setattr(_settings, name, value)
+ elif name.startswith("aprsinfo."):
+ name = name[9:]
+ if name == "beaconreceivetone" or name == "anaptttype":
+ value = 0 if value else 1
+ _settings = self._memobj.aprsinfo
+ setattr(_settings, name, value)
+ elif name.startswith("gnssinfo."):
+ name = name[9:]
+ _settings = self._memobj.gnssinfo
+ setattr(_settings, name, value)
+ elif name.startswith("dtmfsetting."):
+ name = name[12:]
+ _dtmfcomm = self._memobj.dtmfinfos.dtmfcomm
+ if name in ["callid", "stunid", "revive"]:
+ value = retevis_ha1g.filter(
+ value, retevis_ha1g.DTMFCHARSET, 10, True)
+ value = value.ljust(10, "\x00")
+ elif name in ["bot", "eot"]:
+ value = retevis_ha1g.filter(
+ value, retevis_ha1g.DTMFCHARSET, 16, True)
+ value = value.ljust(16, "\x00")
+ setattr(_dtmfcomm, name, value)
+ elif name.startswith("vfoscan."):
+ name = name[8:]
+ _vfo_scan = self._memobj.vfoscans.vfoscans[0]
+ if name in ["vhffreq_start", "vhffreq_end"]:
+ value = chirp_common.to_MHz(value)
+ setattr(_vfo_scan, name, value)
+ LOG.debug("Setting %s: %s", name, value)
+ except Exception:
+ LOG.exception(element.get_name())
+ raise
+
+ def supports_airband(self):
+ return True
+
+ def supports_banks(self):
+ return True
diff --git a/chirp/drivers/retevis_ra25.py b/chirp/drivers/retevis_ra25.py
index 34bbb12..a26d702 100644
--- a/chirp/drivers/retevis_ra25.py
+++ b/chirp/drivers/retevis_ra25.py
@@ -58,7 +58,8 @@ struct{
char name[8];
u8 busychannellockout;
u8 tone_id;
- u8 unk_mem4[3];
+ u8 sql_mode;
+ u8 unk_mem4[2];
} vfo[2];
struct{
@@ -92,7 +93,8 @@ struct {
char name[8];
u8 busychannellockout;
u8 tone_id;
- u8 unk_mem4[3];
+ u8 sql_mode;
+ u8 unk_mem4[2];
} memory[504];
struct{
@@ -294,6 +296,8 @@ def send_cmd(serial, cmd, length):
err = (f'Data send expected {length} got {len(resp)}')
LOG.error(err)
raise errors.RadioError(err)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(f'Error sending to serial {e}')
return resp
@@ -301,12 +305,18 @@ def send_cmd(serial, cmd, length):
def start_programming(serial):
try:
- r = send_cmd(serial, b'PROGRAM', 1)
+ serial.write(b'PROGRAM')
+ serial.flush()
+ r = serial.read(1)
+ if not r:
+ raise errors.RadioNoResponse()
if r != b'\x06':
err = (f'Enter Programming failed '
f'expected 0x06 got {hex(r[0])}')
LOG.error(err)
raise errors.RadioError(err)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(f'Error Entering Program Mode {e}')
return True
@@ -317,6 +327,8 @@ def end_programming(serial):
r = send_cmd(serial, b'END', 1)
if r != b'\x06':
LOG.error(f'Error {hex(r[0])}')
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(f"Error {e}")
@@ -340,6 +352,8 @@ def get_ident(radio):
err = f'ERROR: Model: {model} Ver: {ver} is not supported!'
LOG.error(err)
raise errors.RadioError(err)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(e)
@@ -364,9 +378,9 @@ def sum_map(MAP):
def do_download(radio):
+ serial = radio.pipe
try:
data = b''
- serial = radio.pipe
serial.timeout = SERIAL_TIMEOUT
status = chirp_common.Status()
status.msg = "Connecting to Radio..."
@@ -390,10 +404,15 @@ def do_download(radio):
data += parse_response(r)
status.cur += btr
radio.status_fn(status)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(f'Exception During Download: {e}')
finally:
- end_programming(serial)
+ try:
+ end_programming(serial)
+ except errors.RadioError:
+ pass
return memmap.MemoryMapBytes(data)
@@ -412,8 +431,8 @@ def write_data(serial, addr, data):
def do_upload(radio):
+ serial = radio.pipe
try:
- serial = radio.pipe
serial.timeout = SERIAL_TIMEOUT
status = chirp_common.Status()
r = start_programming(serial)
@@ -437,10 +456,15 @@ def do_upload(radio):
status.cur += btw
radio.status_fn(status)
i += 1
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(f"Exception During Upload: {e}")
finally:
- end_programming(serial)
+ try:
+ end_programming(serial)
+ except errors.RadioError:
+ pass
return
@@ -645,6 +669,17 @@ class RA25UVRadio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
_mem.channel_width = 0 if mem.mode == "FM" else 1
self.set_tones__mem(_mem, mem)
self.set_duplex__mem(_mem, mem)
+
+ # Set sql_mode based on tmode - CT/DCS (1) if receive tone is set,
+ # otherwise SQ (0).
+ if mem.tmode in ("TSQL", "DTCS"):
+ _mem.sql_mode = 1
+ elif mem.tmode == "Cross":
+ txmode, rxmode = mem.cross_mode.split("->", 1)
+ _mem.sql_mode = 1 if rxmode else 0
+ else:
+ _mem.sql_mode = 0
+
_mem.tx_offset = mem.offset/10
_mem.step = self.VALID_TUNING_STEPS.index(mem.tuning_step)
@@ -1146,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_ra86.py b/chirp/drivers/retevis_ra86.py
index c50d52c..79dd4b6 100644
--- a/chirp/drivers/retevis_ra86.py
+++ b/chirp/drivers/retevis_ra86.py
@@ -111,7 +111,7 @@ def _enter_programming_mode(radio):
raise errors.RadioError("Error communicating with radio")
if not ack:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")
diff --git a/chirp/drivers/retevis_ra87.py b/chirp/drivers/retevis_ra87.py
index 2d46c32..2ab67a3 100644
--- a/chirp/drivers/retevis_ra87.py
+++ b/chirp/drivers/retevis_ra87.py
@@ -250,7 +250,7 @@ def _enter_programming_mode_download(radio):
raise errors.RadioError("Error communicating with radio")
if not ack:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")
@@ -311,7 +311,7 @@ def _enter_programming_mode_upload(radio):
raise errors.RadioError("Error communicating with radio")
if not ack:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")
@@ -446,7 +446,9 @@ class RA87StyleRadio(chirp_common.CloneModeRadio):
VALID_BANDS = [(400000000, 480000000)]
_magic = b"PROGRAM"
- _fingerprint = [b"\xFF\xFF\xFF\xFF\xFF\xA5\x2C\xFF"]
+ _fingerprint = [b"\xFF\xFF\xFF\xFF\xFF\xA5\x2C\xFF",
+ b"\xFF\xFF\xFF\xFF\xFF\xA5\x26\xFF",
+ ]
_upper = 99
_gmrs = True
_echo = True
@@ -519,10 +521,10 @@ class RA87StyleRadio(chirp_common.CloneModeRadio):
_exit_programming_mode(self)
def _get_dcs(self, val):
- return int(str(val)[2:-16])
+ return val.get_bbcd()
def _set_dcs(self, val):
- return int(str(val), 16)
+ return bitwise.dec_to_bbcd(val)
def _memory_obj(self, suffix=""):
return getattr(self._memobj, "%s_memory%s" % (self._vfo, suffix))
diff --git a/chirp/drivers/retevis_rb15.py b/chirp/drivers/retevis_rb15.py
index 7e59e97..1b388dd 100644
--- a/chirp/drivers/retevis_rb15.py
+++ b/chirp/drivers/retevis_rb15.py
@@ -16,7 +16,7 @@
import struct
import logging
-from chirp import chirp_common, directory, memmap
+from chirp import chirp_common, directory, memmap, checksum
from chirp import bitwise, errors, util
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueInteger, RadioSettingValueList, \
@@ -103,13 +103,6 @@ TOT_VALUES = [0x00, 0x0F, 0x1E, 0x2D, 0x3C, 0x4B, 0x5A, 0x69, 0x78,
]
-def _checksum(data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
def tone2short(t):
"""Convert a string tone or DCS to an encoded u16
"""
@@ -167,6 +160,8 @@ def _rb15_enter_programming_mode(radio):
# check if we had EXITO
if exito is False:
+ if not ack:
+ 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)
@@ -185,7 +180,7 @@ def _rb15_read_block(radio, block_addr, block_size):
cmd = struct.pack(">BH", ord(b'R'), block_addr)
- ccs = bytes([_checksum(cmd)])
+ ccs = bytes([checksum.checksum_8bit(cmd)])
expectedresponse = b"R" + cmd[1:]
@@ -197,7 +192,7 @@ def _rb15_read_block(radio, block_addr, block_size):
serial.write(cmd)
response = serial.read(3 + block_size + 1)
- cs = bytes([_checksum(response[:-1])])
+ cs = bytes([checksum.checksum_8bit(response[:-1])])
if response[:3] != expectedresponse:
raise Exception("Error reading block %04x." % (block_addr))
@@ -220,7 +215,7 @@ def _rb15_write_block(radio, block_addr, block_size):
cmd = struct.pack(">BH", ord(b'W'), block_addr)
data = radio.get_mmap()[block_addr:block_addr + block_size]
- cs = bytes([_checksum(cmd + data)])
+ cs = bytes([checksum.checksum_8bit(cmd + data)])
data += cs
LOG.debug("Writing Data:")
@@ -344,6 +339,8 @@ class RB15RadioBase(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
do_upload(self)
+ except errors.RadioError:
+ raise
except:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
diff --git a/chirp/drivers/retevis_rb17p.py b/chirp/drivers/retevis_rb17p.py
index 3668352..47775c3 100644
--- a/chirp/drivers/retevis_rb17p.py
+++ b/chirp/drivers/retevis_rb17p.py
@@ -118,7 +118,7 @@ def _enter_programming_mode(radio):
raise errors.RadioError("Error communicating with radio")
if not ack:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")
diff --git a/chirp/drivers/retevis_rb28.py b/chirp/drivers/retevis_rb28.py
index d9cb760..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):
@@ -168,7 +174,7 @@ def _enter_programming_mode(radio):
raise errors.RadioError("Error communicating with radio")
if not ack:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")
@@ -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
@@ -377,7 +391,9 @@ class RB28Radio(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
do_upload(self)
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
LOG.exception('Unexpected error during upload')
@@ -410,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:
@@ -462,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)
@@ -573,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)
@@ -607,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)
@@ -619,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)
@@ -636,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)
@@ -649,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)
@@ -663,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
@@ -708,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):
@@ -732,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_rt1.py b/chirp/drivers/retevis_rt1.py
index f8cb18d..b4b598e 100644
--- a/chirp/drivers/retevis_rt1.py
+++ b/chirp/drivers/retevis_rt1.py
@@ -140,7 +140,7 @@ def _rt1_enter_programming_mode(radio):
if not ack:
_rt1_exit_programming_mode(radio)
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
LOG.debug("Incorrect response, got this:\n\n" + util.hexprint(ack))
_rt1_exit_programming_mode(radio)
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 662a377..dfb5289 100644
--- a/chirp/drivers/retevis_rt21.py
+++ b/chirp/drivers/retevis_rt21.py
@@ -1,4 +1,4 @@
-# Copyright 2021-2023 Jim Unroe <rock.unroe@gmail.com>
+# Copyright 2021-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
@@ -182,17 +182,26 @@ struct {
#seekto %(settings_offset)s;
u8 skipflags[4]; // Scan Add
+#seekto 0x020F;
+struct {
+ u8 unknown_11:3, //
+ is_pmr:1, //
+ chnumber16:4; // Channel Number (RB626)
+} settings4;
+
#seekto 0x029F;
struct {
- u8 chnumber; // Channel Number 029F
+ u8 chnumber; // Channel Number (RB26)
} settings2;
-#seekto 0x031D;
+#seekto %(settings_offset2)s;
struct {
- u8 unused:7, // 031D
+ u8 unknown_9:7, //
+ chgroup:1; // Channel Group (RB626)
+ u8 unknown_10:7, //
vox:1; // Vox
- u8 voxl; // Vox Level 031E
- u8 voxd; // Vox Delay 031F
+ u8 voxl; // Vox Level
+ u8 voxd; // Vox Delay
} settings3;
"""
@@ -548,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"]
@@ -555,6 +601,7 @@ BCL_LIST = ["Off", "Carrier", "QT/DQT"]
BOOTSEL_LIST = ["Channel Mode", "Voice Mode"]
CDCSS_LIST = ["Normal Code", "Special Code 2", "Special Code 1"]
CDCSS2_LIST = ["Normal Code", "Special Code"] # RT29 UHF and RT29 VHF
+CHGROUP_LIST = ["Normal", "PMR"]
FREQHOP_LIST = ["Off", "Hopping 1", "Hopping 2", "Hopping 3"]
FUNCTION_LIST = ["Off", "Scramble", "Compand"]
GAIN_LIST = ["Standard", "Enhanced"]
@@ -608,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]
@@ -645,7 +697,7 @@ def _enter_programming_mode(radio):
raise errors.RadioError("Error communicating with radio")
if not ack:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")
@@ -883,7 +935,9 @@ class RT21Radio(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
do_upload(self)
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
LOG.exception('Unexpected error during upload')
@@ -1070,11 +1124,18 @@ class RT21Radio(chirp_common.CloneModeRadio):
rset = RadioSetting("compander", "Compander", rs)
mem.extra.append(rset)
- if self.MODEL == "RB26" or self.MODEL == "RT76" \
- or self.MODEL == "RB23" or self.MODEL == "AR-63" \
- or self.MODEL == "RB89":
- if self.MODEL == "RB26" or self.MODEL == "RB23" \
- or self.MODEL == "RB89":
+ if self.MODEL in ["AR-63",
+ "RB23",
+ "RB26",
+ "RB89",
+ "RB626",
+ "RT76",
+ ]:
+ if self.MODEL in ["RB23",
+ "RB26",
+ "RB89",
+ "RB626",
+ ]:
rs = RadioSettingValueBoolean(_mem.bcl)
rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
mem.extra.append(rset)
@@ -1288,6 +1349,7 @@ class RT21Radio(chirp_common.CloneModeRadio):
if mem.empty:
if self.MODEL in ["RB23",
"RB26",
+ "RB626",
"RT40B",
"RT76",
"RT86",
@@ -1519,6 +1581,7 @@ class RT21Radio(chirp_common.CloneModeRadio):
if self.MODEL in ["AR-63",
"RB23",
"RB26",
+ "RB626",
"RT19",
"RT40B",
"RT76",
@@ -1527,11 +1590,17 @@ class RT21Radio(chirp_common.CloneModeRadio):
"RB89",
"RT86S",
]:
- if self.MODEL == "RB26" or self.MODEL == "RB23" \
- or self.MODEL == "RB89"or self.MODEL == "RT86S":
+ if self.MODEL in ["RB23",
+ "RB26",
+ "RB626",
+ "RT86S",
+ "RB89",
+ ]:
_settings2 = self._memobj.settings2
_settings3 = self._memobj.settings3
- if self.MODEL == "RT86S":
+ if self.MODEL in ["RB626",
+ "RT86S",
+ ]:
_settings4 = self._memobj.settings4
rs = RadioSettingValueInteger(0, 9, _settings.squelch)
@@ -1586,20 +1655,22 @@ class RT21Radio(chirp_common.CloneModeRadio):
rset = RadioSetting("voice", "Voice Annumciation", rs)
basic.append(rset)
- if self.MODEL == "RB26" or self.MODEL == "RB23" \
- or self.MODEL == "RB89" or self.MODEL == "RT86S":
+ if self.MODEL in ["RB23",
+ "RB26",
+ "RB89",
+ "RB626",
+ "RT86S",
+ ]:
rs = RadioSettingValueList(VOICE_LIST2,
current_index=_settings.voice)
rset = RadioSetting("voice", "Voice Annumciation", rs)
basic.append(rset)
- if self.MODEL == "RB26":
- rs = RadioSettingValueBoolean(not _settings.chnumberd)
- rset = RadioSetting("chnumberd", "Channel Number Enable", rs)
- basic.append(rset)
-
- if self.MODEL == "RT86" or self.MODEL == "RB89" \
- or self.MODEL == "RT86S":
+ if self.MODEL in ["RB626",
+ "RB89",
+ "RT86",
+ "RT86S",
+ ]:
rs = RadioSettingValueList(SPECIAL_LIST,
current_index=_settings.tailmode)
rset = RadioSetting("tailmode", "QT/DQT Tail Mode", rs)
@@ -1615,6 +1686,7 @@ class RT21Radio(chirp_common.CloneModeRadio):
if self.MODEL in ["RB23",
"RB26",
+ "RB626",
"RT86",
"RB89",
"RT86S",
@@ -1687,8 +1759,11 @@ class RT21Radio(chirp_common.CloneModeRadio):
rset = RadioSetting("voxd", "Vox Delay", rs)
basic.append(rset)
- if self.MODEL == "RB26" or self.MODEL == "RB23" \
- or self.MODEL == "RB89":
+ if self.MODEL in ["RB23",
+ "RB26",
+ "RB626",
+ "RB89",
+ ]:
rs = RadioSettingValueBoolean(_settings3.vox)
rset = RadioSetting("settings3.vox", "Vox Function", rs)
basic.append(rset)
@@ -1703,7 +1778,9 @@ class RT21Radio(chirp_common.CloneModeRadio):
rset = RadioSetting("settings3.voxd", "Vox Delay", rs)
basic.append(rset)
- if self.MODEL == "RB26":
+ if self.MODEL in ["RB26",
+ "RB626",
+ ]:
rs = RadioSettingValueList(PFKEY_LIST,
current_index=_settings.pf1)
rset = RadioSetting("pf1", "PF1 Key Set", rs)
@@ -1744,8 +1821,31 @@ class RT21Radio(chirp_common.CloneModeRadio):
_settings.pf2)
basic.append(rset)
- rs = RadioSettingValueInteger(1, 30, _settings2.chnumber + 1)
- rset = RadioSetting("settings2.chnumber", "Channel Number", rs)
+ if self.MODEL == "RB626":
+ rs = RadioSettingValueList(
+ CHGROUP_LIST, current_index=_settings3.chgroup)
+ rset = RadioSetting("settings3.chgroup",
+ "Channel Group", rs)
+ rset.set_doc("Normal (1-16), PMR (17-32)")
+ basic.append(rset)
+
+ rs = RadioSettingValueInteger(1, self._upper / 2,
+ _settings4.chnumber16 + 1)
+ rset = RadioSetting("settings4.chnumber16",
+ "Channel Number", rs)
+ basic.append(rset)
+ else:
+ rs = RadioSettingValueInteger(1, self._upper,
+ _settings2.chnumber + 1)
+ rset = RadioSetting("settings2.chnumber",
+ "Channel Number", rs)
+ basic.append(rset)
+
+ if self.MODEL in ["RB26",
+ "RB626",
+ ]:
+ rs = RadioSettingValueBoolean(not _settings.chnumberd)
+ rset = RadioSetting("chnumberd", "Channel Number Enable", rs)
basic.append(rset)
if self.MODEL == "RT76":
@@ -2020,6 +2120,13 @@ class RT21Radio(chirp_common.CloneModeRadio):
setattr(obj, setting, int(element.value) - 1)
elif setting == "chnumber" and self.MODEL != "RT86S":
setattr(obj, setting, int(element.value) - 1)
+ elif setting == "chnumber16":
+ setattr(obj, setting, int(element.value) - 1)
+ elif setting == "chgroup":
+ setattr(obj, setting, element.value)
+ obj = self._memobj.settings4
+ setting = "is_pmr"
+ setattr(obj, setting, element.value)
elif setting == "chnumberd":
setattr(obj, setting, not int(element.value))
elif setting == "tail":
@@ -2129,10 +2236,13 @@ class RB26Radio(RT21Radio):
_ranges = [
(0x0000, 0x0320),
]
- _memsize = 0x0320
+ _memsize = 0x0800
def process_mmap(self):
- mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0'}
+ mem_params = {'memcnt': self._upper,
+ 'settings_offset': '0x01F0',
+ 'settings_offset2': '0x031C',
+ }
self._memobj = bitwise.parse(MEM_FORMAT_RB26 % mem_params, self._mmap)
@@ -2158,12 +2268,15 @@ class RB626(RT21Radio):
_gmrs = False
_ranges = [
- (0x0000, 0x0320),
+ (0x0000, 0x0340),
]
- _memsize = 0x0320
+ _memsize = 0x0800
def process_mmap(self):
- mem_params = {'memcnt': self._upper, 'settings_offset': '0x0200'}
+ mem_params = {'memcnt': self._upper,
+ 'settings_offset': '0x0200',
+ 'settings_offset2': '0x033C',
+ }
self._memobj = bitwise.parse(MEM_FORMAT_RB26 % mem_params, self._mmap)
@@ -2276,7 +2389,10 @@ class RB23Radio(RT21Radio):
_memsize = 0x0320
def process_mmap(self):
- mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0'}
+ mem_params = {'memcnt': self._upper,
+ 'settings_offset': '0x01F0',
+ 'settings_offset2': '0x031C',
+ }
self._memobj = bitwise.parse(MEM_FORMAT_RB26 % mem_params, self._mmap)
@@ -2504,7 +2620,10 @@ class RB89Radio(RT21Radio):
_memsize = 0x0340
def process_mmap(self):
- mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0'}
+ mem_params = {'memcnt': self._upper,
+ 'settings_offset': '0x01F0',
+ 'settings_offset2': '0x031C',
+ }
self._memobj = bitwise.parse(MEM_FORMAT_RB26 % mem_params, self._mmap)
@@ -2528,7 +2647,8 @@ class RT86SRadio(RT21Radio):
VALID_BANDS = [(400000000, 520000000)]
_magic = b"PHOGR" + b"\xA7\xB8"
- _fingerprint = [b"P32073" + b"\x00\xFF", ]
+ _fingerprint = [b"P32073" + b"\x00\xFF",
+ b"P32073" + b"\x03\xFF", ]
_upper = 30
_ack_1st_block = False
_skipflags = True
@@ -2543,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 cbbacd6..ac340e3 100644
--- a/chirp/drivers/retevis_rt22.py
+++ b/chirp/drivers/retevis_rt22.py
@@ -19,6 +19,7 @@ import logging
from chirp import chirp_common, directory, memmap
from chirp import bitwise, errors, util
+from chirp import kenwood_tone
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueInteger, RadioSettingValueList, \
RadioSettingValueBoolean, RadioSettings, \
@@ -31,8 +32,8 @@ MEM_FORMAT = """
struct {
lbcd rxfreq[4];
lbcd txfreq[4];
- ul16 rx_tone;
- ul16 tx_tone;
+ ul16 rxtone;
+ ul16 txtone;
u8 unknown1;
u8 unknown3:2,
highpower:1, // Power Level
@@ -133,6 +134,8 @@ def _rt22_enter_programming_mode(radio):
# check if we had EXITO
if exito is False:
+ if not ack:
+ 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)
@@ -342,6 +345,8 @@ class RT22Radio(chirp_common.CloneModeRadio):
_block_size = 0x40
_fileid = [b"P32073", b"P3" + b"\x00\x00\x00" + b"3", b"P3207!",
b"\x00\x00\x00\x00\x00\x00\xF8\xFF"]
+ _tone_model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x2800, pol_mask=0x8000, tone_init=0xFFFF, tone_flag=0x0000)
def get_features(self):
rf = chirp_common.RadioFeatures()
@@ -390,6 +395,8 @@ class RT22Radio(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
do_upload(self)
+ except errors.RadioError:
+ raise
except:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
@@ -400,48 +407,6 @@ class RT22Radio(chirp_common.CloneModeRadio):
def get_raw_memory(self, number):
return repr(self._memobj.memory[number - 1])
- def _get_tone(self, _mem, mem):
- def _get_dcs(val):
- code = int("%03o" % (val & 0x07FF))
- pol = (val & 0x8000) and "R" or "N"
- return code, pol
-
- if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
- tcode, tpol = _get_dcs(_mem.tx_tone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.tx_tone != 0xFFFF:
- mem.rtone = _mem.tx_tone / 10.0
- txmode = "Tone"
- else:
- txmode = ""
-
- if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
- rcode, rpol = _get_dcs(_mem.rx_tone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rx_tone != 0xFFFF:
- mem.ctone = _mem.rx_tone / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- if mem.tmode == "DTCS":
- mem.dtcs_polarity = "%s%s" % (tpol, rpol)
-
- LOG.debug("Got TX %s (%i) RX %s (%i)" %
- (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
-
def get_memory(self, number):
bitpos = (1 << ((number - 1) % 8))
bytepos = ((number - 1) / 8)
@@ -477,7 +442,7 @@ class RT22Radio(chirp_common.CloneModeRadio):
mem.mode = _mem.wide and "FM" or "NFM"
- self._get_tone(_mem, mem)
+ self._tone_model.get_tone(_mem, mem)
mem.power = RT22_POWER_LEVELS[_mem.highpower]
@@ -497,44 +462,6 @@ class RT22Radio(chirp_common.CloneModeRadio):
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- val = int("%i" % code, 8) + 0x2800
- if pol == "R":
- val += 0x8000
- return val
-
- rx_mode = tx_mode = None
- rx_tone = tx_tone = 0xFFFF
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- tx_tone = int(mem.rtone * 10)
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rx_tone = tx_tone = int(mem.ctone * 10)
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- tx_tone = int(mem.rtone * 10)
- if rx_mode == "DTCS":
- rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rx_tone = int(mem.ctone * 10)
-
- _mem.rx_tone = rx_tone
- _mem.tx_tone = tx_tone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
-
def set_memory(self, mem):
bitpos = (1 << ((mem.number - 1) % 8))
bytepos = ((mem.number - 1) / 8)
@@ -567,7 +494,7 @@ class RT22Radio(chirp_common.CloneModeRadio):
_mem.wide = mem.mode == "FM"
- self._set_tone(mem, _mem)
+ self._tone_model.set_tone(mem, _mem)
_mem.highpower = mem.power == RT22_POWER_LEVELS[1]
@@ -588,45 +515,86 @@ class RT22Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("squelch", "Squelch Level",
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 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("tot", "Time-out timer",
RadioSettingValueList(
TIMEOUTTIMER_LIST,
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.")
basic.append(rs)
rs = RadioSetting("voice", "Voice Prompts",
RadioSettingValueList(
VOICE_LIST, current_index=_settings.voice))
+ rs.set_doc(
+ "Selects the language for spoken radio-operation prompts, or "
+ "disables those prompts.")
basic.append(rs)
rs = RadioSetting("pf2key", "PF2 Key",
RadioSettingValueList(
PF2KEY_LIST, current_index=_settings.pf2key))
+ rs.set_doc(
+ "Chooses what the programmable key does when held down: Scan "
+ "steps through the channels looking for activity, Local Alarm "
+ "sounds the alarm on this radio, and Remote Alarm instead sends "
+ "the alarm to the other radios on the channel without sounding "
+ "it here.")
basic.append(rs)
rs = RadioSetting("vox", "Vox",
RadioSettingValueBoolean(_settings.vox))
+ 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("voxgain", "VOX Level",
RadioSettingValueList(
VOX_LIST, current_index=_settings.voxgain))
+ 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("voxdelay", "VOX Delay Time (Old | New)",
RadioSettingValueList(
VOXDELAY_LIST,
current_index=_settings.voxdelay))
+ 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)
rs = RadioSetting("save", "Battery Save",
RadioSettingValueBoolean(_settings.save))
+ 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("beep", "Beep",
RadioSettingValueBoolean(_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)
if self.MODEL != "W31E":
@@ -644,11 +612,18 @@ class RT22Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("embedded_msg.line1", "Embedded Message 1",
RadioSettingValueString(0, 32, _filter(
_message.line1)))
+ rs.set_doc(
+ "Free-form text of up to 32 characters stored in the "
+ "radio, typically used as an owner or service note. The "
+ "radio has no display, so it is never shown on the "
+ "radio itself.")
basic.append(rs)
rs = RadioSetting("embedded_msg.line2", "Embedded Message 2",
RadioSettingValueString(0, 32, _filter(
_message.line2)))
+ rs.set_doc(
+ "Second line of the free-form text stored in the radio.")
basic.append(rs)
return top
diff --git a/chirp/drivers/retevis_rt23.py b/chirp/drivers/retevis_rt23.py
index ad81a2c..99a5fd0 100644
--- a/chirp/drivers/retevis_rt23.py
+++ b/chirp/drivers/retevis_rt23.py
@@ -201,6 +201,8 @@ def _rt23_enter_programming_mode(radio):
# check if we had EXITO
if exito is False:
+ if not ack:
+ 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)
@@ -401,6 +403,8 @@ class RT23Radio(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
do_upload(self)
+ except errors.RadioError:
+ raise
except:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
diff --git a/chirp/drivers/retevis_rt26.py b/chirp/drivers/retevis_rt26.py
index 938bda1..43c1b8c 100644
--- a/chirp/drivers/retevis_rt26.py
+++ b/chirp/drivers/retevis_rt26.py
@@ -180,7 +180,7 @@ def _rt26_enter_programming_mode(radio):
if not ack:
_rt26_exit_programming_mode(radio)
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif ack != CMD_ACK:
LOG.debug("Incorrect response, got this:\n\n" + util.hexprint(ack))
_rt26_exit_programming_mode(radio)
diff --git a/chirp/drivers/retevis_rt76p.py b/chirp/drivers/retevis_rt76p.py
index 30029b7..8818044 100644
--- a/chirp/drivers/retevis_rt76p.py
+++ b/chirp/drivers/retevis_rt76p.py
@@ -220,6 +220,8 @@ def _rt76p_enter_programming_mode(radio):
# check if we had EXITO
if exito is False:
+ if not ack:
+ 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)
@@ -540,35 +542,40 @@ class RT76PRadio(chirp_common.CloneModeRadio):
_mem.set_raw("\x00" * 16)
+ duplex = mem.duplex
+ offset = mem.offset
+ mode = mem.mode
+ power = mem.power
+
if mem.freq in GMRS_FREQS1:
- mem.duplex == ''
- mem.offset = 0
+ duplex = ''
+ offset = 0
elif mem.freq in GMRS_FREQS2:
- mem.duplex == ''
- mem.offset = 0
- mem.mode = "NFM"
- mem.power = self.RT76P_POWER_LEVELS[1]
+ duplex = ''
+ offset = 0
+ mode = "NFM"
+ power = self.RT76P_POWER_LEVELS[1]
elif mem.freq in GMRS_FREQS3:
if mem.duplex == '+':
- mem.offset = 5000000
+ offset = 5000000
else:
- mem.duplex == ''
- mem.offset = 0
+ duplex = ''
+ offset = 0
else:
- mem.duplex = 'off'
- mem.offset = 0
+ duplex = 'off'
+ offset = 0
_mem.rxfreq = mem.freq / 10
- if mem.duplex == "off":
+ if duplex == "off":
for i in range(0, 4):
_mem.txfreq[i].set_raw("\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
+ elif duplex == "split":
+ _mem.txfreq = offset / 10
+ elif duplex == "+":
+ _mem.txfreq = (mem.freq + offset) / 10
+ elif duplex == "-":
+ _mem.txfreq = (mem.freq - offset) / 10
else:
_mem.txfreq = mem.freq / 10
@@ -614,9 +621,8 @@ class RT76PRadio(chirp_common.CloneModeRadio):
_mem.rxtone += 0x69
_mem.scan = mem.skip != "S"
- _mem.narrow = mem.mode == "NFM"
-
- _mem.lowpower = mem.power == self.RT76P_POWER_LEVELS[1]
+ _mem.narrow = mode == "NFM"
+ _mem.lowpower = power == self.RT76P_POWER_LEVELS[1]
for setting in mem.extra:
if setting.get_name() == "scramble_type":
@@ -974,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_rt87.py b/chirp/drivers/retevis_rt87.py
index 0e0eb3e..2d22880 100644
--- a/chirp/drivers/retevis_rt87.py
+++ b/chirp/drivers/retevis_rt87.py
@@ -253,10 +253,14 @@ def _identify(radio):
.format(magic, echo))
ack = radio.pipe.read(2)
- if ack != b"\x06\x30":
+ if not ack:
+ raise errors.RadioNoResponse()
+ elif ack != b"\x06\x30":
raise errors.RadioError("Radio did not ACK first command: %r" %
ack)
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
LOG.exception('')
raise errors.RadioError("Unable to communicate with the radio")
@@ -370,6 +374,8 @@ class Rt87BaseRadio(chirp_common.CloneModeRadio):
"""Upload to radio"""
try:
_upload(self)
+ except errors.RadioError:
+ raise
except:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
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/retevis_rt98.py b/chirp/drivers/retevis_rt98.py
index 9d2524a..f475877 100644
--- a/chirp/drivers/retevis_rt98.py
+++ b/chirp/drivers/retevis_rt98.py
@@ -16,7 +16,7 @@
import struct
import logging
-from chirp import bitwise
+from chirp import bitwise, checksum
from chirp import chirp_common
from chirp import directory
from chirp import errors
@@ -536,13 +536,6 @@ def _echo_write(radio, data):
raise errors.RadioError("Unable to write to radio")
-def _checksum(data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
def _read(radio, length):
try:
data = radio.pipe.read(length)
@@ -601,10 +594,12 @@ def _ident(radio):
radio.pipe.timeout = 1
_echo_write(radio, b"PROGRAM")
response = radio.pipe.read(3)
+ if not response:
+ raise errors.RadioNoResponse()
if response != b"QX\06":
_finish(radio)
LOG.debug("Response was :\n%s" % util.hexprint(response))
- raise errors.RadioError("Radio did not respond. Check connection.")
+ raise errors.RadioError("Unexpected response from radio")
_echo_write(radio, b"\x02")
ver_response = radio.pipe.read(16)
LOG.debug(util.hexprint(ver_response))
@@ -624,7 +619,7 @@ def _send(radio, cmd, addr, length, data=None):
frame = struct.pack(">cHb", cmd, addr, length)
if data:
frame += data
- frame += bytes([_checksum(frame[1:])])
+ frame += bytes([checksum.checksum_8bit(frame[1:])])
frame += b"\x06"
_echo_write(radio, frame)
LOG.debug("Sent:\n%s" % util.hexprint(frame))
@@ -652,7 +647,7 @@ def _send(radio, cmd, addr, length, data=None):
LOG.debug(" Length: %02x/%02x" % (length, _length))
LOG.debug(" Addr: %04x/%04x" % (addr, _addr))
raise errors.RadioError("Radio send unexpected block")
- cs = _checksum(result[1:-2])
+ cs = checksum.checksum_8bit(result[1:-2])
if cs != result[-2]:
_finish(radio)
LOG.debug("Calculated: %02x" % cs)
@@ -1025,69 +1020,74 @@ class Rt98BaseRadio(chirp_common.CloneModeRadio,
_mem.set_raw("\x00" * 32)
+ mode = mem.mode
+ offset = mem.offset
+ freq = mem.freq
+ duplex = mem.duplex
+
# FreeNet and PMR radio types
if _embedded.mode == 0: # PMR or FreeNet
- mem.mode = 'NFM'
- mem.offset = 0
+ mode = 'NFM'
+ offset = 0
# FreeNet
if str(_embedded.radio_type).rstrip("\00") == "RT98V":
if mem.number >= 1 and mem.number <= 6:
FREENET_FREQ = FREENET_FREQS[mem.number - 1]
- mem.freq = FREENET_FREQ
+ freq = FREENET_FREQ
else:
_mem.tx_off = 1
- mem.duplex = 'off'
+ duplex = 'off'
# PMR
if str(_embedded.radio_type).rstrip("\00") == "RT98U":
if mem.number >= 1 and mem.number <= 16:
PMR_FREQ = PMR_FREQS[mem.number - 1]
- mem.freq = PMR_FREQ
+ freq = PMR_FREQ
else:
_mem.tx_off = 1
- mem.duplex = 'off'
+ duplex = 'off'
# set the occupied bitfield
self._memobj.csetflag[cbyte].c[cbit] = 1
# set the scan add bitfield
self._memobj.cskipflag[cbyte].c[cbit] = 0 if (mem.skip == "S") else 1
- _mem.freq = mem.freq / 10 # Convert to low-level frequency
- _mem.offset = mem.offset / 10 # Convert to low-level frequency
+ _mem.freq = freq / 10 # Convert to low-level frequency
+ _mem.offset = offset / 10 # Convert to low-level frequency
# Store the alpha tag
_mem.name = mem.name.ljust(6)[:6] # Store the alpha tag
# Set duplex bitfields
_mem.tx_off = 0
- if mem.duplex == 'off': # handle tx off
+ if duplex == 'off': # handle tx off
_mem.tx_off = 1
- elif mem.duplex == '+':
+ elif duplex == '+':
_mem.duplex = DUPLEX_POSSPLIT
- elif mem.duplex == '-':
+ elif duplex == '-':
_mem.duplex = DUPLEX_NEGSPLIT
- elif mem.duplex == '':
+ elif duplex == '':
_mem.duplex = DUPLEX_NOSPLIT
- elif mem.duplex == 'split':
- diff = mem.offset - mem.freq
+ elif duplex == 'split':
+ diff = offset - freq
_mem.duplex = DUPLEXES.index("-") \
if diff < 0 else DUPLEXES.index("+")
_mem.offset = abs(diff) / 10
else:
LOG.error('%s: set_mem: unhandled duplex: %s' %
- (mem.name, mem.duplex))
+ (mem.name, duplex))
# Set the channel width - remember we promote 20 kHz channels to FM
# on import, so don't handle them here
- if mem.mode == 'FM':
+ if mode == 'FM':
_mem.channel_width = CHANNEL_WIDTH_25kHz
- elif mem.mode == 'NFM':
+ elif mode == 'NFM':
_mem.channel_width = CHANNEL_WIDTH_12d5kHz
else:
LOG.error('%s: set_mem: unhandled mode: %s' % (
- mem.name, mem.mode))
+ mem.name, mode))
# CTCSS Tones and DTCS Codes
((txmode, txtone, txpol),
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/tdh8.py b/chirp/drivers/tdh8.py
index 1ca5b51..0cc753b 100644
--- a/chirp/drivers/tdh8.py
+++ b/chirp/drivers/tdh8.py
@@ -106,8 +106,10 @@ struct {
} settings;
//#seekto 0x0CB8;
-lbcd offseta[4];
-lbcd offsetb[4];
+struct{
+ lbcd a[4];
+ lbcd b[4];
+}vfo_offset;
#seekto 0x0CD8;
struct{
@@ -148,7 +150,7 @@ struct {
lowpower:2,
wide:1,
unused8:1,
- offset:2;
+ dira:2;
u8 unused10;
} vfoa;
@@ -171,7 +173,7 @@ struct {
lowpowerb:2,
wideb:1,
unused8:1,
- offsetb:2;
+ dirb:2;
u8 unused10;
} vfob;
@@ -365,8 +367,10 @@ struct {
} settings;
//#seekto 0x0CB8;
-lbcd offseta[4];
-lbcd offsetb[4];
+struct{
+ lbcd a[4];
+ lbcd b[4];
+}vfo_offset;
#seekto 0x0CD8;
struct{
@@ -472,7 +476,7 @@ struct {
lowpower:2,
wide:1,
unused8:1,
- offset:2;
+ dira:2;
u8 unused10;
} vfoa;
@@ -495,7 +499,7 @@ struct {
lowpowerb:2,
wideb:1,
unused8:1,
- offsetb:2;
+ dirb:2;
u8 unused10;
} vfob;
@@ -589,8 +593,10 @@ struct {
} settings;
//#seekto 0x0CB8;
-lbcd offseta[4];
-lbcd offsetb[4];
+struct {
+lbcd a[4];
+lbcd b[4];
+}vfo_offset;
#seekto 0x0CD8;
struct{
@@ -638,7 +644,7 @@ struct {
lowpower:2,
wide:1,
unused8:1,
- offset:2;
+ dira:2;
u8 unused9;
} vfoa;
@@ -661,7 +667,7 @@ struct {
lowpowerb:2,
wideb:1,
unused8:1,
- offsetb:2;
+ dirb:2;
u8 unused9;
} vfob;
@@ -704,7 +710,9 @@ VFOA_NAME = ["rxfreqa",
"bcl",
"lowpower",
"wide",
- "offset"]
+ "a",
+ "dira",
+ ]
VFOB_NAME = ["rxfreqb",
"txfreq",
@@ -715,7 +723,9 @@ VFOB_NAME = ["rxfreqb",
"bclb",
"lowpowerb",
"wideb",
- "offsetb"]
+ "b",
+ "dirb",
+ ]
TOT_LIST = ["Off", "30S", "60S", "90S", "120S", "150S", "180S", "210S"]
ALARM_LIST = ["On site", "Alarm"]
@@ -751,14 +761,9 @@ PTTID_VALUES = ["Off", "BOT", "EOT", "BOTH"]
BCLOCK_VALUES = ["Off", "On"]
FREQHOP_VALUES = ["Off", "On"]
-# AB CHANNEL
-A_OFFSET = ["Off", "-", "+"]
-A_BAND = ["Wide", "Narrow"]
-A_WORKMODE = ["VFO", "VFO+CH", "CH Mode"]
-
-B_OFFSET = ["Off", "-", "+"]
-B_BAND = ["Wide", "Narrow"]
-B_WORKMODE = ["VFO", "VFO+CH", "CH Mode"]
+# AB VFO CHANNEL
+OFFSET_DIR = ["Off", "-", "+"]
+VFO_WORKMODE = ["VFO", "VFO+CH", "CH Mode"]
# FM
FM_WORKMODE = ["VFO", "CH"]
@@ -827,11 +832,11 @@ def _do_ident(serial, magic, secondack=True):
serial.write(magic)
ack = serial.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != b"\x06":
- if ack:
- # LOG.debug(repr(ack))
- pass
- raise errors.RadioError("Radio did not respond")
+ # LOG.debug(repr(ack))
+ raise errors.RadioError("Radio refused to enter programming mode")
serial.write(b"\x02")
@@ -880,10 +885,16 @@ def _read_block(radio, start, size):
try:
serial.write(cmd)
response = serial.read(5 + size)
+ if not response:
+ if start == 0:
+ raise errors.RadioNoResponse()
+ raise errors.RadioError("Failed to read block at %04x" % start)
if response[:4] != expectedresponse:
raise errors.RadioError("Error reading block %04x." % (start))
block_data = response[4:-1]
+ except errors.RadioError:
+ raise
except Exception:
raise errors.RadioError("Failed to read block at %04x" % start)
@@ -1020,7 +1031,7 @@ class TDH8(chirp_common.CloneModeRadio):
LOG.error('No model match found for ident query %r response %r',
ident, radio_ident)
raise errors.RadioError('Unsupported model')
- raise errors.RadioError('No response from radio')
+ raise errors.RadioNoResponse()
@classmethod
def get_prompts(cls):
@@ -1080,6 +1091,8 @@ class TDH8(chirp_common.CloneModeRadio):
try:
self._mmap = _do_download(self)
self.process_mmap()
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError("Failed to communicate with radio: %s" % e)
@@ -1749,27 +1762,70 @@ class TDH8(chirp_common.CloneModeRadio):
# If the offset is 12.345
# Then the data obtained is [0x45, 0x23, 0x01, 0x00]
offsets = {}
+ dirs = {}
+
+ def _calc_txfreq(rxfreq, offset, dir):
+ # calc tx freq
+ txfreq = 0
+ match dir:
+ case 0: # off
+ txfreq = rxfreq
+ case 1: # minus
+ txfreq = \
+ (int(rxfreq) /
+ 100000 - int(offset) / 100000) * 100000
+ case 2: # plus
+ txfreq = \
+ (int(rxfreq) /
+ 100000 + int(offset) / 100000) * 100000
+ return int(txfreq)
+
+ def _apply_offset_dir(setting, i, obj1, obj2):
+ value = getattr(obj1, setting.get_name())
+ value.set_value(setting.value)
+ # calc tx freq and store
+ obj1.txfreq = _calc_txfreq(
+ getattr(obj1, "rxfreq%s" % i),
+ obj2,
+ getattr(obj1, "dir%s" % i)
+ )
+
for i in ('a', 'b'):
- value = getattr(self._memobj, 'offset%s' % i)
+ value = getattr(self._memobj.vfo_offset, '%s' % i)
if value.get_raw() == b'\xff\xff\xff\xff':
offset = 0
else:
offset = int(value) / 100000
def _apply(setting):
- value = getattr(self._memobj, setting.get_name())
+ value = getattr(self._memobj.vfo_offset,
+ setting.get_name())
if float(setting.value) == 0:
value.fill_raw(b'\xff')
else:
value.set_value(int(setting.value * 100000))
- rs = RadioSetting("offset%s" % i,
+ rs = RadioSetting("%s" % i,
"%s Offset Frequency" % i.upper(),
RadioSettingValueFloat(
0.00000, 59.99750, offset, 0.00001, 5))
rs.set_apply_callback(_apply)
offsets[i] = rs
+ _obj1 = self._memobj.vfoa if i == \
+ 'a' else self._memobj.vfob
+ _obj2 = self._memobj.vfo_offset.a if i == 'a' \
+ else self._memobj.vfo_offset.b
+ _obj3 = self._memobj.vfoa.dira if i == 'a' \
+ else self._memobj.vfob.dirb
+ rs = RadioSetting("dir%s" % i,
+ "%s Offset Direction" % i.upper(),
+ RadioSettingValueList(OFFSET_DIR,
+ current_index=_obj3))
+ rs.set_apply_callback(_apply_offset_dir, i, _obj1, _obj2)
+ dirs[i] = rs
+
abblock.append(offsets['a'])
+ abblock.append(dirs['a'])
try:
self._tx_power[_vfoa.lowpower]
@@ -1784,11 +1840,11 @@ class TDH8(chirp_common.CloneModeRadio):
rs = RadioSetting("wide", "A Band",
RadioSettingValueList(
- A_BAND, current_index=_vfoa.wide))
+ BANDWIDTH_LIST, current_index=_vfoa.wide))
abblock.append(rs)
rs = RadioSetting("bcl", "A Busy Lock",
- RadioSettingValueBoolean(_settings.ablock))
+ RadioSettingValueBoolean(_vfoa.bcl))
abblock.append(rs)
rs = RadioSetting("specialqta", "A Special QT/DQT",
@@ -1798,7 +1854,7 @@ class TDH8(chirp_common.CloneModeRadio):
rs = RadioSetting(
"aworkmode", "A Work Mode",
RadioSettingValueList(
- A_WORKMODE, current_index=_settings.aworkmode))
+ VFO_WORKMODE, current_index=_settings.aworkmode))
abblock.append(rs)
# B channel
@@ -1813,6 +1869,7 @@ class TDH8(chirp_common.CloneModeRadio):
abblock.append(rs)
abblock.append(offsets['b'])
+ abblock.append(dirs['b'])
try:
self._tx_power[_vfob.lowpowerb]
@@ -1827,11 +1884,11 @@ class TDH8(chirp_common.CloneModeRadio):
rs = RadioSetting("wideb", "B Band",
RadioSettingValueList(
- B_BAND, current_index=_vfob.wideb))
+ BANDWIDTH_LIST, current_index=_vfob.wideb))
abblock.append(rs)
rs = RadioSetting("bclb", "B Busy Lock",
- RadioSettingValueBoolean(_settings.bblock))
+ RadioSettingValueBoolean(_vfob.bclb))
abblock.append(rs)
rs = RadioSetting("specialqtb", "B Special QT/DQT",
@@ -1841,7 +1898,7 @@ class TDH8(chirp_common.CloneModeRadio):
rs = RadioSetting(
"bworkmode", "B Work Mode",
RadioSettingValueList(
- B_WORKMODE, current_index=_settings.bworkmode))
+ VFO_WORKMODE, current_index=_settings.bworkmode))
abblock.append(rs)
group.append(fmmode)
@@ -1908,11 +1965,15 @@ class TDH8(chirp_common.CloneModeRadio):
gcode_val = ""
else:
gcode_val = gcode_val[1]
+ try:
+ cur = GROUPCODE.index(gcode_val)
+ except ValueError:
+ cur = len(GROUPCODE)
rs = RadioSetting(
"gcode", "Group Code",
RadioSettingValueList(
GROUPCODE,
- current_index=GROUPCODE.index(gcode_val)))
+ current_index=cur))
dtmf.append(rs)
icode_list = self._memobj.icode.idcode
@@ -2099,8 +2160,8 @@ class TDH8(chirp_common.CloneModeRadio):
def get_settings(self):
try:
return self._get_settings()
- except Exception:
- raise InvalidValueError("Setting Failed!")
+ except Exception as e:
+ raise InvalidValueError("Setting Failed!") from e
def set_settings(self, settings):
@@ -2206,7 +2267,7 @@ class TDH8(chirp_common.CloneModeRadio):
_settings.brightness = 4 - int(element.value)
elif "sync" == name:
_settings.sync = not int(element.value)
- # Channel A
+ # Channel A RX freq
elif "rxfreqa" == setting and element.value.get_mutable():
val = int(str(element.value).replace(
'.', '').ljust(8, '0'))
@@ -2629,8 +2690,9 @@ class TDH8_3rd_Gen(TDH8):
_gmrs = False
_ham = False
_mem_params = (0x1F2F)
- _tx_power = [chirp_common.PowerLevel("Low", watts=2.00),
- chirp_common.PowerLevel("High", watts=5.00)]
+ _tx_power = [chirp_common.PowerLevel("Low", watts=2.0),
+ chirp_common.PowerLevel("Mid", watts=6.0),
+ chirp_common.PowerLevel("High", watts=10.0)]
_roger_list = ["Off", "TONE1", "TONE2"]
_brightness_list = ["1", "2", "3", "4", "5"]
diff --git a/chirp/drivers/tdm11.py b/chirp/drivers/tdm11.py
new file mode 100644
index 0000000..82f5234
--- /dev/null
+++ b/chirp/drivers/tdm11.py
@@ -0,0 +1,921 @@
+# Copyright 2025, 2026 Fred Trimble <chirpdriver@gmail.com>
+# CHIRP driver for TIDRADIO TD-M11 22 FRS and TD-M11 16 PMR446 radios
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+from chirp import (
+ bitwise,
+ chirp_common,
+ directory,
+ errors,
+ memmap,
+)
+
+from chirp.settings import (
+ RadioSetting,
+ RadioSettingGroup,
+ RadioSettings,
+ RadioSettingValueList,
+ RadioSettingValueString,
+ MemSetting,
+)
+
+import logging
+import struct
+from textwrap import dedent
+from datetime import datetime
+
+LOG = logging.getLogger(__name__)
+
+MEM_FORMAT = """
+// memmory channels: 16 bytes each * 22 channels == 352 bytes
+// * 16 channels == 256 bytes
+#seekto 0x0000;
+struct {
+ lbcd rxfreq[4]; // RX freq
+ lbcd txfreq[4]; // TX freq
+ lbcd rxtone[2]; // RX tone
+ lbcd txtone[2]; // TX tone
+ u8 unknown0:2,
+ jumpfreq:1, // 1 bit freq hopping
+ scan:1, // 1 bit scan add
+ txpower:1, // 1 bit TX power
+ narrow:1, // 1 bit bandwidth
+ bcl:2; // 1 bit busy lockout
+ u8 unknown1:3,
+ compand:1, // 1 bit compander
+ scramble:4; // 4 bit scramble
+ u8 unknown2;
+ u8 unknown3;
+} memory[%d];
+
+// settings:
+#seekto 0x0300;
+struct {
+ u8 unknown0:4, // 0x0300
+ squelch:4; // 4 bit squelch level
+ u8 unused1:6, // 0x0301
+ voice:2; // 2 bit voice prompts, 0 Off, 1 Chinese, 2 English
+ u8 channel; // 0x0302 default channel on power up
+ u8 unused2:4, // 0x0303
+ vox:4; // 4 bit vox level
+ u8 unused3:2, // 0x0304
+ tot:6; // 6 bit TX time out timer
+ u8 wxchannel; // 0x0305
+ u8 unused4:4, // 0x0306
+ sleep:4; // 4 bit power saving mode
+ u8 firmware[3]; // 0x0307 3 byte firmware version
+ u8 unknown1; // 0x030a
+ u8 unused5:4, // 0x030b
+ sidekey1:4; //
+ u8 unknown4; // 0x030c
+ u8 unused6:4, // 0x030d
+ sidekey2:4; //
+ u8 unknown5[2]; // 0x030e
+ u8 freqband[4]; // 0x0310 4 byte freb band
+ u8 model; // 0x0314
+ u8 areacode; // 0x0315
+ u8 unknown7[10]; // 0x0316
+ u8 password[6]; // 0x0320 6 byte radio programming mode password
+} settings;
+
+// program time
+#seekto 0x0406;
+struct {
+ u8 time[6]; // [0]msb yr:,[1]lsb yr:,[2]:mon,[3]:day,[4]:hr,[5]:min
+} progtime;
+"""
+
+# Other interesting memory addresses (not used in this driver):
+# u8 superpassword[16] // 0x0400 16 byte super password (use unknown)
+# u8 volume[16] // 0x0410 16 byte volume values (use unknown)
+# u8 powerlow[16] // 0x0420 16 byte low power calibration values
+# u8 powerhigh[16] // 0x0430 16 byte high power calibration values
+# u8 mic[8] // 0x0440 8 byte mic calibration values
+# u8 freqadjust[1] // 0x0448 1 byte frequency calibration value
+# (default value 0x80)
+
+
+CMD_ACK = b'A'
+GET_RADIO_ID = b'\x52\x10\x03\x10'
+NULL_PASSWORD = b'\xff\xff\xff\xff\xff\xff'
+TIMEOUT = 0.5 # base serial timeout in seconds
+TXPOWER_HIGH = 0x01
+TXPOWER_LOW = 0x00
+
+
+def get_default_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_settings = True
+ rf.has_bank = False
+ rf.has_ctone = True
+ rf.has_cross = True
+ rf.has_rx_dtcs = True
+ rf.has_tuning_step = False
+ rf.can_odd_split = True
+ rf.has_name = False
+ rf.valid_name_length = 0
+ rf.valid_characters = self._valid_chars
+ rf.valid_skips = ['', 'S']
+ rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
+ rf.valid_cross_modes = ['Tone->Tone', 'Tone->DTCS', 'DTCS->Tone',
+ '->Tone', '->DTCS', 'DTCS->', 'DTCS->DTCS']
+ rf.valid_power_levels = self._power_levels
+ rf.valid_duplexes = ['', '-', '+', 'split', 'off']
+ rf.valid_modes = ['FM', 'NFM'] # 25 kHz, 12.5 kHz.
+ rf.valid_dtcs_codes = chirp_common.DTCS_CODES
+ rf.memory_bounds = (1, self._upper)
+ rf.valid_tuning_steps = [2.5, 5., 6.25, 8.33, 10., 12.5, 20., 25., 50.]
+ rf.valid_bands = self.VALID_BANDS
+ return rf
+
+
+def _enter_programming_mode(radio, write=False):
+ serial = radio.pipe
+ serial.timeout = TIMEOUT
+
+ if not _test_magic(radio):
+ raise errors.RadioError('Radio didn\'t accept Program Mode')
+
+ try:
+ # if we get an ACK here the radio programming function
+ # is not password protected
+ serial.write(NULL_PASSWORD)
+ ack = serial.read(0x01)
+
+ if not ack:
+ raise errors.RadioNoResponse()
+ if ack == CMD_ACK:
+ LOG.info('Radio Programming function is NOT '
+ 'password protected')
+ else:
+ msg = 'The radio Programming function is '\
+ 'password protected. Use the factory CPS to '\
+ 'remove the password to continue.'
+ raise ValueError(msg)
+
+ except errors.RadioError:
+ raise
+ except ValueError as ex:
+ raise errors.RadioError(ex)
+ except Exception:
+ raise errors.RadioError('Error communicating with radio')
+
+ # if uploading to the radio we have to ask it for its fingerprint first
+ if write:
+ try:
+ # ask radio for fingerprint
+ serial.write(GET_RADIO_ID)
+ ack = serial.read(0x11)
+ if not ack:
+ raise errors.RadioNoResponse()
+ if len(ack) != 0x11:
+ raise errors.RadioError('Error communicating with radio')
+ ack2 = _get_checksum(ack[:-1], 0, 0x10)
+
+ if ack[:-1] in radio._fingerprint and ack[-1] == ack2:
+ LOG.info("Radio fingerprint 0x%s match" % ack[:-1].hex())
+ else:
+ LOG.error("Radio fingerprint 0x%s Mis-match" %
+ radio.ack[:-1].hex())
+ msg = 'Radio Model mismatch'
+ raise ValueError(msg)
+
+ except errors.RadioError:
+ raise
+ except ValueError as ex:
+ raise errors.RadioError(ex)
+
+
+def _exit_programming_mode(radio):
+ serial = radio.pipe
+ serial.timeout = TIMEOUT
+
+ try:
+ serial.write(b'E')
+ except Exception:
+ raise errors.RadioError('Radio refused to exit programming mode')
+
+
+def _test_magic(radio, tries=5):
+ serial = radio.pipe
+ serial.timeout = TIMEOUT / 5 # reduce timeout to speed up detection
+ rv = False
+
+ try:
+ saw_response = False
+ for i in range(1, tries + 1):
+ serial.write(radio._magic)
+ ack = serial.read(0x01)
+ if ack:
+ saw_response = True
+ if ack == CMD_ACK:
+ LOG.info('Radio ack\'ed magic %s '
+ 'during detection' %
+ radio._magic)
+ rv = True
+ break
+ else:
+ LOG.info('Radio didn\'t ack magic %s '
+ 'during detection' %
+ radio._magic)
+ if not saw_response:
+ raise errors.RadioNoResponse()
+ rv = False
+ except errors.RadioError:
+ raise
+ except Exception:
+ raise errors.RadioError('Failed to detect radio after %d try/tries'
+ % i)
+
+ return rv
+
+
+def _get_checksum(data, addr, len):
+ checksum = 0
+ for index in range(0, len):
+ checksum += data[index + addr]
+ return checksum & 0xff # checksum is only low order byte
+
+
+def _read_block(radio, block_addr, size):
+ serial = radio.pipe
+ serial.timeout = TIMEOUT
+
+ cmd = struct.pack('<cHb', b'R', block_addr, size)
+ expectedresponse = b''
+
+ try:
+ serial.write(cmd)
+ response = serial.read(size)
+ if not response:
+ raise errors.RadioNoResponse()
+ if len(response) != size:
+ raise errors.RadioError('Failed to read block at %04x' %
+ block_addr)
+ expectedresponse = serial.read(1) # read 1 byte checksum
+ checksum = _get_checksum(response, 0, size)
+ if checksum != expectedresponse[0]:
+ raise errors.RadioError('Checksum error reading block %04x.' %
+ (block_addr))
+ block_data = response
+
+ except errors.RadioError:
+ raise
+ except Exception:
+ raise errors.RadioError('Failed to read block at %04x' % block_addr)
+
+ return block_data
+
+
+def _write_block(radio, block_addr, size):
+ serial = radio.pipe
+ serial.timeout = TIMEOUT
+
+ cmd = struct.pack('<cH', b'W', block_addr)
+ data = radio.get_mmap()[block_addr:block_addr + size]
+ checksum = _get_checksum(data, 0, size)
+
+ try:
+ serial.write(cmd + data + bytes([checksum]))
+ ack = serial.read(1)
+ if ack != CMD_ACK:
+ raise Exception('No ACK')
+ except Exception:
+ raise errors.RadioError('Failed to send block '
+ 'to radio at %04x' % block_addr)
+
+
+def do_download(radio):
+ LOG.info('Downloading...')
+ # already done by detect_from_serial()
+ # _enter_programming_mode(radio)
+
+ data = b''
+ status = chirp_common.Status()
+ status.msg = 'Cloning from radio'
+ status.max = radio._memsize
+
+ for addr in range(0, radio._memsize, radio.BLOCK_SIZE):
+ status.cur = addr
+ radio.status_fn(status)
+ radio.pipe.log('Reading from address: 0x%04x' % addr)
+ block = _read_block(radio, addr, radio.BLOCK_SIZE)
+ data += block
+
+ radio.pipe.log('Downloaded 0x%04x bytes from radio' % len(data))
+
+ return memmap.MemoryMapBytes(data)
+
+
+def do_upload(radio):
+ LOG.info('Uploading...')
+ _enter_programming_mode(radio, write=True)
+
+ status = chirp_common.Status()
+ status.msg = 'Uploading to radio'
+ status.max = radio._memsize
+ bytesup = 0
+
+ for start_addr, end_addr in radio._ranges:
+ for addr in range(start_addr, end_addr, radio.BLOCK_SIZE_UP):
+ status.cur = addr
+ radio.status_fn(status)
+ radio.pipe.log('Writing to address: 0x%04x' % addr)
+ _write_block(radio, addr, radio.BLOCK_SIZE_UP)
+ bytesup += radio.BLOCK_SIZE_UP
+
+ radio.pipe.log('Uploaded 0x%04x bytes to radio' % bytesup)
+
+
+@directory.register
+class TDM11_22(chirp_common.CloneModeRadio):
+ # ==========
+ # Notice to developers:
+ # The TD-M11 22 for USA FRS/GMRS support in this driver is currently based
+ # on Firmware v0.9.4
+ # ==========
+ # TD-M11 power-on key sequences:
+ # Crack (freq search): Set Ch to 1, power Off, [PTT] + power On
+ # Chan disp, Green LED flashes
+ # Wireless Copy transmit: Set Chan to 2 or 4, power Off, [PTT] + power On
+ # Full disp, Red LED flashes
+ # Wireless Copy receive: Set Chan to 3 or 5, power Off, [PTT] + power On
+ # Full disp, Green LED solid
+ # Change voice prompts: Set Chan to 15, power Off, [PTT] + power On
+ # Voice change is announced
+ # Firmware update mode: [Ch +] + [Ch -] + power On
+ # Disp off, Green LED solid
+ # Have 8 sec to start Fw update
+ # after 8 sec timeout turns on Bluetooth.
+ # (Hold buttons for ~4 sec to improve chance
+ # of Bluetooth activation):
+ # Chan disp w/bluetooth icon, Red LED solid
+ # after Bluetooth paring, Yellow LED solid
+ """TIDRADIO TD-M11 22 FRS"""
+ VENDOR = 'TIDRADIO'
+ MODEL = 'TD-M11'
+ VARIANT = '22 FRS' # USA FRS/GMRS
+ BAUD_RATE = 9600
+ FORMATS = [directory.register_format('%s %s' %
+ (VENDOR, MODEL), '*.mdt')]
+ BLOCK_SIZE = 0x10
+ BLOCK_SIZE_UP = 0x10
+ VALID_BANDS = [(136000000, 174000000), (200000000, 260000000),
+ (350000000, 390000000), (400000000, 520000000),
+ ]
+ _power_levels = [
+ chirp_common.PowerLevel('Low', watts=0.50),
+ chirp_common.PowerLevel('High', watts=2.00)
+ ]
+
+ _upper = 22
+ _mem_params = (_upper)
+ _memsize = 0x0450 # Including calibration data
+ _ranges = [(0x0000, _memsize)]
+
+ _magic = b'STD-M11-' # Firmware v0.9.4
+ _fingerprint = [
+ b'\x00\x40\x00\x52\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
+ ]
+ _mdt_file_header = b'TD-M11-22CLIENT'
+ _mdt_offset = len(_mdt_file_header) # offset of data in OEM .mdt file
+ _valid_chars = chirp_common.CHARSET_ALPHANUMERIC
+ _steps = [5.0, 6.25, 12.5, 25.0]
+ # mem extra lists
+ _bcl_list = ['Off', 'Carrier', 'QT/DTQ']
+ _jumpfreq_list = ['Normal', 'Special']
+ _compand_list = ['Off', 'On']
+ _scramble_list = ['Off'] + ['Scramble %d' % x for x in range(1, 9)]
+ # settings lists
+ _voice_list = ['Off', 'Chinese', 'English']
+ _tot_list = ['Off'] + ['%ds' % x for x in range(15, 315, 15)]
+ _voxlevel_list = ['Off'] + ['%d' % x for x in range(1, 10)]
+ _squelchlevel_list = ['%d' % x for x in range(0, 10)]
+ _sleepmode_list = ['Off'] + ['1:%d' % x for x in range(1, 11)]
+ _sidekey_list = ['None', 'Monitor', 'Scan',
+ 'Alarm', 'Bluetooth', 'Weather']
+ _channel_list = ['%d' % x for x in range(1, _upper + 1)]
+ _wxchannel_list = ['WX %d' % x for x in range(1, 12)]
+ _freqband_list = []
+
+ @classmethod
+ def detect_from_serial(cls, pipe):
+ # iterate potential classes and see which responds first
+ saw_response = False
+ for rclass in cls.detected_models():
+ try:
+ _enter_programming_mode(rclass(pipe))
+ return rclass
+ except errors.RadioNoResponse:
+ pass
+ except errors.RadioError:
+ saw_response = True
+ pass
+ except Exception:
+ raise
+ else: # for
+ if saw_response:
+ raise errors.RadioError('Unexpected response from radio')
+ raise errors.RadioNoResponse()
+
+ def sync_in(self):
+ """Download from radio"""
+ try:
+ data = do_download(self)
+ except errors.RadioError:
+ # Pass through any real errors we raise
+ raise
+ except Exception as ex:
+ # If anything unexpected happens, make sure we log the problem
+ # and raise a RadioError
+ LOG.exception('Unexpected error during download: %s' % ex)
+ raise errors.RadioError('Unexpected error during download: %s'
+ % ex)
+ finally:
+ _exit_programming_mode(self)
+
+ self._mmap = data
+ self.process_mmap()
+
+ def sync_out(self):
+ """Upload to radio"""
+ try:
+ _time = self._memobj.progtime
+ _time.time = self._encode_current_time()
+ except Exception:
+ LOG.warning('image file too short, can\'t update '
+ 'program-time timestamp')
+
+ try:
+ do_upload(self)
+ except errors.RadioError:
+ # Pass through any real errors we raise
+ raise
+ except Exception as ex:
+ # If anything unexpected happens, make sure we log the problem
+ # and raise a RadioError
+ LOG.exception('Unexpected error during upload: %s' % ex)
+ raise errors.RadioError('Unexpected error during upload: %s'
+ % ex)
+ finally:
+ _exit_programming_mode(self)
+
+ def load_mmap(self, filename):
+ if filename.lower().endswith('.mdt'):
+ with open(filename, 'rb') as f:
+
+ if f.read(len(self._mdt_file_header)) != self._mdt_file_header:
+ raise errors.ImageDetectFailed("Unknown file header")
+
+ self._mmap = memmap.MemoryMapBytes(f.read(self._memsize))
+ LOG.info('Loaded TD-M11 .mdt file %s at offset 0x%04x' %
+ (filename, self._mdt_offset))
+ self.process_mmap()
+ else:
+ chirp_common.CloneModeRadio.load_mmap(self, filename)
+
+ def save_mmap(self, filename):
+ if filename.lower().endswith('.mdt'):
+ with open(filename, 'wb') as f:
+ f.write(self._mdt_file_header)
+ f.write(self._mmap.get_packed())
+ LOG.info('Wrote TD-M11 .mdt file % s' % filename)
+ else:
+ chirp_common.CloneModeRadio.save_mmap(self, filename)
+
+ def _decode_tone(self, val):
+ if val == 16665 or val == 0:
+ return '', None, None
+ elif val >= 12000:
+ return 'DTCS', val - 12000, 'R'
+ elif val >= 8000:
+ return 'DTCS', val - 8000, 'N'
+ else:
+ return 'Tone', val / 10.0, None
+
+ def _encode_tone(self, memval, mode, value, pol):
+ if mode == '':
+ memval.fill_raw(b'\xff')
+ elif mode == 'Tone':
+ memval.set_value(int(value * 10))
+ elif mode == 'DTCS':
+ flag = 0x80 if pol == 'N' else 0xC0
+ memval.set_value(value)
+ memval[1].set_bits(flag)
+ else:
+ raise Exception('Internal error: invalid mode ''%s''' % mode)
+
+ def _decode_freqband(self, band):
+ try:
+ s = '%g-%g Mhz' % (
+ float(str(band[1])[-2:] + str(band[0])[-2:]) / 10,
+ float(str(band[3])[-2:] + str(band[2])[-2:]) / 10
+ )
+ except IndexError:
+ s = '(unknown)'
+
+ return s
+
+ def _encode_current_time(self):
+ now = datetime.now()
+ time = [0] * 6
+ time[0] = now.year & 0xff
+ time[1] = now.year >> 8
+ time[2] = now.month
+ time[3] = now.day
+ time[4] = now.hour
+ time[5] = now.minute
+ return time
+
+ def get_settings(self):
+ _settings = self._memobj.settings
+ _time = self._memobj.progtime
+ basic = RadioSettingGroup('basic', 'Settings')
+ group = RadioSettings(basic)
+
+ # format raw firmware ver for display
+ def _fw(version):
+ if bytes(version) == b'\xff\xff\xff':
+ return '(none)'
+
+ ver = 'v'
+ try:
+ for i in version:
+ ver += '%d' % i + '.'
+ LOG.info('Firmware version: %s' % ver[:-1])
+ return ver[:-1]
+ except IndexError:
+ return '(none)'
+
+ # Firmware version, display only
+ rs = RadioSettingValueString(0, 6, _fw(_settings.firmware))
+ rs.set_mutable(False)
+ rset = RadioSetting('settings.firmware', 'Firmware Version', rs)
+ rset.set_doc('Radio Firmware Version (read only)')
+ basic.append(rset)
+
+ # Freq band, display only
+ rs = RadioSettingValueString(0, 32,
+ self._decode_freqband(_settings.freqband))
+ rs.set_mutable(False)
+ rset = RadioSetting('settings.freqband', 'Frequency Band', rs)
+ rset.set_doc('Radio frequency band (read only)')
+ basic.append(rset)
+
+ # format raw date/time for display
+ def _decode_time(time):
+ try:
+ y = time[0] + (time[1] << 8)
+ mo = time[2]
+ d = time[3]
+ h = time[4]
+ mi = time[5]
+ s = '%04d-%02d-%02d %02d:%02d' % (y, mo, d, h, mi)
+ except IndexError:
+ s = '(none)'
+ return s
+
+ # Program time, display only
+ rs = RadioSettingValueString(0, 17,
+ _decode_time(_time.time))
+ rs.set_mutable(False)
+ rset = RadioSetting('progtime.time', 'Program Time', rs)
+ rset.set_doc('Date/Time radio was last programmed (read only)')
+ basic.append(rset)
+
+ # Voice prompts
+ rs = RadioSettingValueList(self._voice_list,
+ current_index=_settings.voice)
+ rset = MemSetting('settings.voice', 'Voice Prompts', rs)
+ rset.set_doc('Radio Voice Prompts spoken language')
+ basic.append(rset)
+
+ # TOT
+ rs = RadioSettingValueList(self._tot_list,
+ current_index=_settings.tot)
+ rset = MemSetting('settings.tot', 'Time Out Timer', rs)
+ rset.set_doc('Radio TX Time Out Timer value')
+ basic.append(rset)
+
+ # VOX level
+ rs = RadioSettingValueList(self._voxlevel_list,
+ current_index=_settings.vox)
+ rset = MemSetting('settings.vox', 'VOX Level', rs)
+ rset.set_doc('Radio VOX Level senesitivity value')
+ basic.append(rset)
+
+ # Squelch level
+ rs = RadioSettingValueList(self._squelchlevel_list,
+ current_index=_settings.squelch)
+ rset = MemSetting('settings.squelch', 'Squelch Level', rs)
+ rset.set_doc('Radio Squelch Level value')
+ basic.append(rset)
+
+ # Sleep mode
+ rs = RadioSettingValueList(self._sleepmode_list,
+ current_index=_settings.sleep)
+ rset = MemSetting('settings.sleep', 'Sleep Mode', rs)
+ rset.set_doc('Radio Sleep Mode power saving ratio value')
+ basic.append(rset)
+
+ # Sidekey 1
+ rs = RadioSettingValueList(self._sidekey_list,
+ current_index=_settings.sidekey1)
+ rset = MemSetting('settings.sidekey1', 'Sidekey 1 Long Pess', rs)
+ rset.set_doc('Radio Sidekey 1 Long Press assigned action value')
+ basic.append(rset)
+
+ # Sidekey 2
+ rs = RadioSettingValueList(self._sidekey_list,
+ current_index=_settings.sidekey2)
+ rset = MemSetting('settings.sidekey2', 'Sidekey 2 Long Press', rs)
+ rset.set_doc('Radio Sidekey 2 Long Press assigned action value')
+ basic.append(rset)
+
+ # Selected default channel (setting not in factory CPS)
+ rs = RadioSettingValueList(self._channel_list,
+ current_index=_settings.channel)
+ rset = MemSetting('settings.channel', 'Default Channel', rs)
+ rset.set_doc('Radio Channel that is selected by Default at power-on')
+ basic.append(rset)
+
+ # Selected default WX channel (setting not in factory CPS)
+ rs = RadioSettingValueList(self._wxchannel_list,
+ current_index=_settings.wxchannel)
+ rset = MemSetting('settings.wxchannel', 'Default WX Channel', rs)
+ rset.set_doc('NOAA Weather Channel that is '
+ 'selected by Default at power-on')
+ basic.append(rset)
+
+ return group
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.experimental = \
+ ('This driver is a BETA version ONLY for the TIDRADIO '
+ 'TD-M11 22 running Firmware v0.9.4\n'
+ '\n'
+ 'Please save an unedited copy of your first successful\n'
+ 'download to a CHIRP Radio Images(*.img) file.\n\n'
+ 'PROCEED AT YOUR OWN RISK!'
+ )
+ rp.pre_download = (dedent("""\
+ 1. Turn radio off.
+ 2. Connect cable to mic/spkr connector.
+ 3. Make sure connector is firmly connected.
+ 4. Turn radio on (volume may need to be set at 100%).
+ 5. Ensure that the radio is tuned to channel with no activity.
+ 6. Click OK to download image from device."""))
+ rp.pre_upload = (dedent("""\
+ 1. Turn radio off.
+ 2. Connect cable to mic/spkr connector.
+ 3. Make sure connector is firmly connected.
+ 4. Turn radio on (volume may need to be set at 100%).
+ 5. Ensure that the radio is tuned to channel with no activity.
+ 6. Click OK to upload image to device."""))
+ return rp
+
+ def get_features(self):
+ rf = get_default_features(self)
+ rf.valid_bands = self.VALID_BANDS
+ rf.valid_modes = ['FM', 'NFM'] # 25kHz, 12.5kHz
+ rf.valid_tuning_steps = self._steps
+ rf.has_name = False
+ return rf
+
+ def get_raw_memory(self, number):
+ return repr(self._memobj.memory[number - 1])
+
+ def get_memory(self, number):
+ """Get the mem representation from the radio image"""
+ _mem = self._memobj.memory[number - 1]
+
+ # Create a high-level memory object to return to the UI
+ mem = chirp_common.Memory()
+
+ # Memory number
+ mem.number = number
+
+ if _mem.get_raw()[:1] == b'\xff':
+ mem.empty = True
+ return mem
+
+ # Freq and offset
+ mem.freq = int(_mem.rxfreq) * 10
+ if mem.freq == 0:
+ mem.empty = True
+ # tx freq can be blank
+ if _mem.txfreq.get_raw() == b'\xff\xff\xff\xff':
+ # TX freq not set
+ mem.offset = 0
+ mem.duplex = 'off'
+ else:
+ # TX freq set
+ offset = (int(_mem.txfreq) * 10) - mem.freq
+ if offset != 0:
+ if chirp_common.is_split(self.get_features().valid_bands,
+ mem.freq, int(_mem.txfreq) * 10):
+ mem.duplex = 'split'
+ mem.offset = int(_mem.txfreq) * 10
+ elif offset < 0:
+ mem.offset = abs(offset)
+ mem.duplex = '-'
+ elif offset > 0:
+ mem.offset = offset
+ mem.duplex = '+'
+ else:
+ mem.offset = 0
+
+ txtone = rxtone = None
+ txtone = self._decode_tone(int(_mem.txtone))
+ rxtone = self._decode_tone(int(_mem.rxtone))
+ chirp_common.split_tone_decode(mem, txtone, rxtone)
+
+ if not _mem.scan:
+ mem.skip = 'S'
+
+ try:
+ mem.power = self._power_levels[_mem.txpower]
+ except IndexError:
+ LOG.error('Channel %d: get_memory: unhandled power level: 0x%02x' %
+ (mem.number, _mem.txpower))
+
+ mem.mode = _mem.narrow and 'NFM' or 'FM'
+
+ mem.extra = RadioSettingGroup('Extra', 'extra')
+
+ # BCL (Busy Channel Lockout)
+ rs = RadioSettingValueList(self._bcl_list,
+ current_index=_mem.bcl)
+ rset = RadioSetting('bcl', 'BCL', rs)
+ rset.set_doc('Busy Channel Lockout')
+ mem.extra.append(rset)
+
+ # Jump Freq
+ rs = RadioSettingValueList(
+ self._jumpfreq_list,
+ current_index=_mem.jumpfreq)
+ rset = RadioSetting('jumpfreq', 'Jump Freq', rs)
+ rset.set_doc('Frequency Jumping/hopping')
+ mem.extra.append(rset)
+
+ # Compand
+ rs = RadioSettingValueList(
+ self._compand_list,
+ current_index=_mem.compand)
+ rset = RadioSetting('compand', 'Compand', rs)
+ rset.set_doc('Audio Compander')
+ mem.extra.append(rset)
+
+ # Scramble
+ rs = RadioSettingValueList(self._scramble_list,
+ current_index=_mem.scramble)
+ rset = RadioSetting('scramble', 'Scramble', rs)
+ rset.set_doc('Voice Scrambler')
+ mem.extra.append(rset)
+
+ return mem
+
+ def set_memory(self, mem):
+ _mem = self._memobj.memory[mem.number - 1]
+
+ if mem.empty:
+ _mem.fill_raw(b'\xff')
+ return
+
+ _mem.fill_raw(b'\x00')
+
+ _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
+
+ txtone, rxtone = chirp_common.split_tone_encode(mem)
+ self._encode_tone(_mem.txtone, *txtone)
+ self._encode_tone(_mem.rxtone, *rxtone)
+
+ _mem.scan = mem.skip != 'S'
+ _mem.narrow = mem.mode == 'NFM'
+
+ try:
+ _mem.txpower = self._power_levels.index(mem.power)
+ except ValueError:
+ LOG.error('Channel %d: set_memory: unhandled power level: %s' %
+ (mem.number, mem.power))
+
+ try:
+ _mem.narrow = self.get_features().valid_modes.index(mem.mode)
+ except IndexError:
+ LOG.error('Channel %d: set_memory: unhandled mode: %s' %
+ (mem.number, mem.mode))
+
+ for setting in mem.extra:
+ setattr(_mem, setting.get_name(), setting.value)
+ if setting.has_apply_callback():
+ # use callbacks on mem.extra
+ # Radiosettings that need postprocessing
+ setting.run_apply_callback()
+
+ def set_settings(self, settings):
+ # apply all Memsettings
+ all_other_settings = settings.apply_to(self._memobj)
+ for setting in all_other_settings:
+ if setting.has_apply_callback():
+ # use callbacks on Radiosettings that need postprocessing
+ setting.run_apply_callback()
+
+ def process_mmap(self):
+ mem_format = MEM_FORMAT % self._mem_params
+ self._memobj = bitwise.parse(mem_format, self._mmap)
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ if filename.lower().endswith('.mdt') and \
+ filedata.startswith(cls._mdt_file_header):
+ return True
+ else:
+ return False
+
+
+@directory.register
+@directory.detected_by(TDM11_22)
+class TDM11_16(TDM11_22):
+ # ==========
+ # Notice to developers:
+ # The TD-M11 16 for EU PMR446 support in this driver is currently based
+ # on Firmware v1.0.3
+ # ==========
+ """TIDRADIO TD-M11 16 PMR"""
+ VENDOR = 'TIDRADIO'
+ MODEL = 'TD-M11'
+ VARIANT = '16 PMR'
+
+ # same freq range as ODMaster allows
+ VALID_BANDS = [(136000000, 174000000), (400000000, 520000000),]
+ _power_levels = [
+ chirp_common.PowerLevel('Low', watts=0.50),
+ chirp_common.PowerLevel('High', watts=2.00)
+ ]
+
+ _upper = 16
+ _mem_params = (_upper)
+
+ _magic = b'STD-M12\xff' # Firmware v1.0.3
+ _fingerprint = [
+ b'\x00\x40\x00\x52\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
+ ]
+ _mdt_file_header = b'TD-M11CLIENT'
+ _mdt_offset = len(_mdt_file_header) # offset of data in OEM .mdt file
+ _steps = [5.0, 6.25, 12.5]
+ _channel_list = ['%d' % x for x in range(1, _upper + 1)]
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.experimental = \
+ ('This driver is a BETA version ONLY for the TIDRADIO '
+ 'TD-M11 16 PMR running Firmware v0.9.5 or v1.0.3\n'
+ '\n'
+ 'Please save an unedited copy of your first successful\n'
+ 'download to a CHIRP Radio Images(*.img) file.\n\n'
+ 'PROCEED AT YOUR OWN RISK!'
+ )
+ return rp
+
+
+@directory.register
+@directory.minorvariant
+@directory.detected_by(TDM11_22)
+class TDM11_16_1(TDM11_16):
+ # ==========
+ # Notice to developers:
+ # The TD-M11 16 for EU PMR446 support in this driver is currently based
+ # on Firmware v0.9.5
+ # ==========
+ """TIDRADIO TD-M11 16 PMR"""
+ VENDOR = 'TIDRADIO'
+ MODEL = 'TD-M11'
+ VARIANT = '16 PMR v0.9.5'
+
+ _magic = b'STD-M11\xff' # Firmware v0.9.5
diff --git a/chirp/drivers/tdxone_tdq8a.py b/chirp/drivers/tdxone_tdq8a.py
index b9082ef..a0fde8b 100644
--- a/chirp/drivers/tdxone_tdq8a.py
+++ b/chirp/drivers/tdxone_tdq8a.py
@@ -190,6 +190,8 @@ def _rawrecv(radio, amount):
msg = "Generic error reading data from radio; check your cable."
raise errors.RadioError(msg)
+ if not data:
+ raise errors.RadioNoResponse()
if len(data) != amount:
msg = "Error reading data from radio: not the amount of data we want."
raise errors.RadioError(msg)
@@ -245,10 +247,11 @@ def _do_ident(radio, magic):
_rawsend(radio, magic)
ack = _rawrecv(radio, 1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != "\x06":
- if ack:
- LOG.debug(repr(ack))
- raise errors.RadioError("Radio did not respond")
+ LOG.debug(repr(ack))
+ raise errors.RadioError("Unexpected response from radio")
_rawsend(radio, "\x02")
@@ -289,7 +292,7 @@ def _ident_radio(radio):
time.sleep(2)
if error:
raise error
- raise errors.RadioError("Radio did not respond")
+ raise errors.RadioNoResponse()
def _download(radio):
@@ -507,7 +510,9 @@ class TDXoneTDQ8A(chirp_common.CloneModeRadio,
"""Upload to radio"""
try:
_upload(self)
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
LOG.exception('Unexpected error during upload')
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/th7800.py b/chirp/drivers/th7800.py
index 237c693..e807ab7 100644
--- a/chirp/drivers/th7800.py
+++ b/chirp/drivers/th7800.py
@@ -568,11 +568,15 @@ def _identify(radio):
try:
radio.pipe.write(b"\x02SPECPR")
ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != b"A":
util.hexprint(ack)
raise errors.RadioError("Radio did not ACK first command: %r"
% ack)
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
raise errors.RadioError("Unable to communicate with the radio")
radio.pipe.write(b"G\x02")
@@ -718,6 +722,8 @@ class TYTTH7800Radio(TYTTH7800Base, chirp_common.CloneModeRadio,
def sync_in(self):
try:
self._mmap = _download(self)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(
"Failed to communicate with the radio: %s" % e)
@@ -726,6 +732,8 @@ class TYTTH7800Radio(TYTTH7800Base, chirp_common.CloneModeRadio,
def sync_out(self):
try:
_upload(self)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(
"Failed to communicate with the radio: %s" % e)
diff --git a/chirp/drivers/th9000.py b/chirp/drivers/th9000.py
index 859e599..344f8d6 100644
--- a/chirp/drivers/th9000.py
+++ b/chirp/drivers/th9000.py
@@ -18,6 +18,7 @@ import logging
from chirp import bitwise
from chirp import chirp_common
+from chirp import checksum
from chirp import directory
from chirp import errors
from chirp import memmap
@@ -431,13 +432,6 @@ def _echo_write(radio, data):
raise errors.RadioError("Unable to write to radio")
-def _checksum(data):
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
def _read(radio, length):
try:
data = radio.pipe.read(length)
@@ -453,27 +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:
- 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")
@@ -483,7 +484,7 @@ def _send(radio, cmd, addr, length, data=None):
frame = struct.pack(">cHb", cmd, addr, length)
if data:
frame += data
- frame += bytes([_checksum(frame[1:])])
+ frame += bytes([checksum.checksum_8bit(frame[1:])])
frame += b"\x06"
_echo_write(radio, frame)
LOG.debug("Sent:\n%s" % util.hexprint(frame))
@@ -508,7 +509,7 @@ def _send(radio, cmd, addr, length, data=None):
LOG.debug(" Length: %02x/%02x" % (length, _length))
LOG.debug(" Addr: %04x/%04x" % (addr, _addr))
raise errors.RadioError("Radio send unexpected block")
- cs = _checksum(result[1:-2])
+ cs = checksum.checksum_8bit(result[1:-2])
if cs != result[-2]:
LOG.debug("Calculated: %02x" % cs)
LOG.debug("Actual: %02x" % result[-2])
@@ -526,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""
@@ -550,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):
@@ -610,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
@@ -1085,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 adf957d..3f378c6 100644
--- a/chirp/drivers/th9800.py
+++ b/chirp/drivers/th9800.py
@@ -249,6 +249,9 @@ class TYTTH9800Base(chirp_common.Radio):
return rf
def process_mmap(self):
+ LOG.debug('Ident info from image:\n%s',
+ util.hexprint(self._mmap[0:self._mmap_offset]))
+
fmt = (self.TH9800_MEM_FORMAT + MEM_FORMAT)
self._memobj = bitwise.parse(
fmt % (self._mmap_offset,
@@ -990,16 +993,25 @@ def _identify(radio):
try:
radio.pipe.write(b"\x02PROGRA")
ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != b"A":
util.hexprint(ack)
raise errors.RadioError("Radio did not ACK first command: %x"
% ord(ack))
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
LOG.debug(util.hexprint(ack))
raise errors.RadioError("Unable to communicate with the radio")
radio.pipe.write(b"M\x02")
ident = radio.pipe.read(16)
+ if len(ident) == 15:
+ # Newer (?) firmware doesn't send the last byte of the model string,
+ # but it's always a 0x00, so add it back for consistency.
+ ident += b'\x00'
+ LOG.debug('Radio sent 15 byte model string; padding for consistency')
radio.pipe.write(b"A")
r = radio.pipe.read(1)
if r != b"A":
@@ -1048,7 +1060,7 @@ def _upload(radio, memsize=0xF400, blocksize=0x80):
raise errors.RadioError(
"Model mismatch: \n%s\n%s" %
(util.hexprint(data),
- util.hexprint(radio._mmap[:radio._mmap_offset])))
+ util.hexprint(radio._mmap[0:radio._mmap_offset])))
# in the factory software they update the last program date when
# they upload, So let's do the same
today = date.today()
@@ -1144,6 +1156,8 @@ class TYTTH9800Radio(TYTTH9800Base, chirp_common.CloneModeRadio,
def sync_in(self):
try:
self._mmap = _download(self)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(
"Failed to communicate with the radio: %s" % e)
@@ -1152,6 +1166,8 @@ class TYTTH9800Radio(TYTTH9800Base, chirp_common.CloneModeRadio,
def sync_out(self):
try:
_upload(self)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(
"Failed to communicate with the radio: %s" % e)
@@ -1236,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 = (
@@ -1255,6 +1265,8 @@ class RetevisMA1Radio(TYTTH9800Base, chirp_common.CloneModeRadio,
def sync_in(self):
try:
self._mmap = _download(self)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(
"Failed to communicate with the radio: %s" % e)
@@ -1263,6 +1275,8 @@ class RetevisMA1Radio(TYTTH9800Base, chirp_common.CloneModeRadio,
def sync_out(self):
try:
_upload(self)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError(
"Failed to communicate with the radio: %s" % e)
diff --git a/chirp/drivers/th_uv3r.py b/chirp/drivers/th_uv3r.py
index 6a02b2f..1f46cda 100644
--- a/chirp/drivers/th_uv3r.py
+++ b/chirp/drivers/th_uv3r.py
@@ -26,9 +26,13 @@ def tyt_uv3r_prep(radio):
try:
radio.pipe.write(b"PROGRAMa")
ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != b"\x06":
raise errors.RadioError("Radio did not ACK first command")
- except:
+ except errors.RadioError:
+ raise
+ except Exception:
raise errors.RadioError("Unable to communicate with the radio")
diff --git a/chirp/drivers/th_uv8000.py b/chirp/drivers/th_uv8000.py
index f9f8da9..3162159 100644
--- a/chirp/drivers/th_uv8000.py
+++ b/chirp/drivers/th_uv8000.py
@@ -319,19 +319,23 @@ def _do_ident(radio):
_rawsend(radio, magic)
ack = _rawrecv(radio, 1)
# LOG.warning("PROGa Ack:" + util.hexprint(ack))
+ if not ack:
+ _exit_program_mode(radio)
+ raise errors.RadioNoResponse()
if ack != b"\x06":
_exit_program_mode(radio)
- if ack:
- LOG.debug(repr(ack))
- raise errors.RadioError("Radio did not respond")
+ LOG.debug(repr(ack))
+ raise errors.RadioError("Unexpected response from radio")
magic = b"PROGRAMb"
_rawsend(radio, magic)
ack = _rawrecv(radio, 1)
+ if not ack:
+ _exit_program_mode(radio)
+ raise errors.RadioNoResponse()
if ack != b"\x06":
_exit_program_mode(radio)
- if ack:
- LOG.debug(repr(ack))
- raise errors.RadioError("Radio did not respond to B")
+ LOG.debug(repr(ack))
+ raise errors.RadioError("Unexpected response from radio")
magic = b"\x02"
_rawsend(radio, magic)
ack = _rawrecv(radio, 1) # s/b: 0x50
@@ -583,6 +587,8 @@ class THUV8000Radio(chirp_common.CloneModeRadio):
try:
_upload(self)
+ except errors.RadioError:
+ raise
except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
diff --git a/chirp/drivers/th_uv88.py b/chirp/drivers/th_uv88.py
index 3ba9dcb..b6943aa 100644
--- a/chirp/drivers/th_uv88.py
+++ b/chirp/drivers/th_uv88.py
@@ -377,13 +377,24 @@ def _do_ident(radio):
# Ident radio
magic = radio._magic0
_rawsend(radio, magic)
- ack = _rawrecv(radio, 36)
+ try:
+ ack = radio.pipe.read(36)
+ except Exception:
+ _exit_program_mode(radio)
+ msg = "Generic error reading data from radio; check your cable."
+ raise errors.RadioError(msg)
+ if not ack:
+ _exit_program_mode(radio)
+ raise errors.RadioNoResponse()
+ if len(ack) != 36:
+ _exit_program_mode(radio)
+ msg = "Error reading from radio: not the amount of data we want."
+ raise errors.RadioError(msg)
if not ack.startswith(radio._fingerprint) or not ack.endswith(b"\xFD"):
_exit_program_mode(radio)
- if ack:
- LOG.debug(repr(ack))
- raise errors.RadioError("Radio did not respond as expected (A)")
+ LOG.debug(repr(ack))
+ raise errors.RadioError("Unexpected response from radio")
return True
@@ -617,6 +628,8 @@ class THUV88Radio(chirp_common.CloneModeRadio):
try:
_upload(self)
+ except errors.RadioError:
+ raise
except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
diff --git a/chirp/drivers/thd72.py b/chirp/drivers/thd72.py
index 65f0628..8717b44 100644
--- a/chirp/drivers/thd72.py
+++ b/chirp/drivers/thd72.py
@@ -283,7 +283,7 @@ class THD72Radio(chirp_common.CloneModeRadio):
except errors.RadioError:
pass
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
def get_special_locations(self):
return sorted(THD72_SPECIAL.keys())
@@ -468,8 +468,11 @@ class THD72Radio(chirp_common.CloneModeRadio):
else:
blocks = [b for b in blocks if b < self._memsize // 256]
- if self.command("0M PROGRAM") != "0M":
- raise errors.RadioError("No response from self")
+ resp = self.command("0M PROGRAM")
+ if not resp:
+ raise errors.RadioNoResponse()
+ if resp != "0M":
+ raise errors.RadioError("Unexpected response to program command")
allblocks = range(self._memsize // 256)
self.pipe.baudrate = 57600
@@ -507,8 +510,11 @@ class THD72Radio(chirp_common.CloneModeRadio):
else:
blocks = [b for b in blocks if b < self._memsize // 256]
- if self.command("0M PROGRAM") != "0M":
- raise errors.RadioError("No response from self")
+ resp = self.command("0M PROGRAM")
+ if not resp:
+ raise errors.RadioNoResponse()
+ if resp != "0M":
+ raise errors.RadioError("Unexpected response to program command")
self.pipe.baudrate = 57600
try:
@@ -550,8 +556,9 @@ class THD72Radio(chirp_common.CloneModeRadio):
r = self.command("ID")
if r.startswith("ID "):
return r.split(" ")[1]
- else:
- raise errors.RadioError("No response to ID command")
+ if not r:
+ raise errors.RadioNoResponse()
+ raise errors.RadioError("Unexpected response to ID command")
def initialize(self, mmap):
mmap.set_raw("\x00\xc8\xb3\x08\x00\x01\x00\x08"
@@ -764,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 ef94047..2ab46e8 100644
--- a/chirp/drivers/thd74.py
+++ b/chirp/drivers/thd74.py
@@ -233,8 +233,11 @@ class THD74Radio(chirp_common.CloneModeRadio,
else:
blocks = [b for b in blocks if b < self._memsize // 256]
- if self.command("0M PROGRAM") != "0M":
- raise errors.RadioError("No response from self")
+ resp = self.command("0M PROGRAM")
+ if not resp:
+ raise errors.RadioNoResponse()
+ if resp != "0M":
+ raise errors.RadioError("Unexpected response to program command")
allblocks = range(self._memsize // 256)
self.pipe.baudrate = 57600
@@ -268,8 +271,11 @@ class THD74Radio(chirp_common.CloneModeRadio,
else:
blocks = [b for b in blocks if b < self._memsize // 256]
- if self.command("0M PROGRAM") != "0M":
- raise errors.RadioError("No response from self")
+ resp = self.command("0M PROGRAM")
+ if not resp:
+ raise errors.RadioNoResponse()
+ if resp != "0M":
+ raise errors.RadioError("Unexpected response to program command")
self.pipe.baudrate = 57600
self.pipe.read(1)
@@ -307,8 +313,9 @@ class THD74Radio(chirp_common.CloneModeRadio,
r = self.command("ID")
if r.startswith("ID "):
return r.split(" ")[1]
- else:
- raise errors.RadioError("No response to ID command")
+ if not r:
+ raise errors.RadioNoResponse()
+ raise errors.RadioError("Unexpected response to ID command")
def _detect_baud(self):
id = None
@@ -331,7 +338,7 @@ class THD74Radio(chirp_common.CloneModeRadio,
elif id:
return id
else:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
def process_mmap(self):
self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
@@ -550,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/thuv1f.py b/chirp/drivers/thuv1f.py
index ab277dc..8b1e309 100644
--- a/chirp/drivers/thuv1f.py
+++ b/chirp/drivers/thuv1f.py
@@ -30,8 +30,10 @@ def uvf1_identify(radio):
"""Do identify handshake with TYT TH-UVF1"""
radio.pipe.write(b"PROG333")
ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != b"\x06":
- raise errors.RadioError("Radio did not respond")
+ raise errors.RadioError("Unexpected response from radio")
radio.pipe.write(b"\x02")
ident = radio.pipe.read(16)
LOG.info("Ident:\n%s" % util.hexprint(ident))
diff --git a/chirp/drivers/tk11.py b/chirp/drivers/tk11.py
new file mode 100644
index 0000000..645abfd
--- /dev/null
+++ b/chirp/drivers/tk11.py
@@ -0,0 +1,2563 @@
+# Copyright 2012 Dan Smith <dsmith@danplanet.com>
+# Copyright 2025 Thibaut Berg <thibaut.berg@hotmail.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 enum
+import logging
+import struct
+
+from chirp import bitwise, checksum
+from chirp import chirp_common, memmap, directory, errors
+from chirp.bitwise import arrayDataElement
+from chirp.chirp_common import CloneModeRadio
+from chirp.settings import (RadioSetting, RadioSettingGroup,
+ RadioSettings, RadioSettingValueList,
+ RadioSettingValueString, RadioSettingValueBoolean,
+ RadioSettingValueInteger, RadioSettingValueFloat,
+ RadioSettingSubGroup)
+
+LOG = logging.getLogger(__name__)
+
+MEM_FORMAT = """
+struct {
+ ul32 rx_freq;
+ ul32 freq_diff;
+ u8 tx_non_standard_1;
+ u8 tx_non_standard_2;
+ u8 rx_qt_type;
+ u8 tx_qt_type;
+ u8 freq_dir;
+ u8 band;
+ u8 step;
+ u8 encrypt;
+ u8 power;
+ u8 busy;
+ u8 reverse;
+ u8 dtmf_decode_flag;
+ u8 ptt_id;
+ u8 mode;
+ u8 scan_list;
+ u8 sq;
+ char name[16];
+ ul32 rx_qt;
+ ul32 tx_qt;
+ u8 unknown[8];
+ ul32 tx_qt2;
+ u8 signal;
+ u8 unknown_2[3];
+} channels[999];
+
+#seekto 0x11000;
+struct {
+ u8 flag;
+} channels_usage[1011];
+
+#seekto 0x12000;
+struct {
+ ul16 vfo_frequency;
+ u8 channel_id;
+ u8 memory_vfo_flag;
+ u8 unknown[4];
+ ul16 frequencies[32];
+} fm;
+
+
+#seekto 0x13000;
+struct {
+ u8 channel_ab;
+ u8 noaa_sq;
+ u8 tx_tot;
+ u8 noaa_scan;
+ u8 keylock;
+ u8 vox_sw;
+ u8 vox_lvl;
+ u8 mic;
+ u8 freq_mode;
+ u8 channel_display_mode;
+ u8 mw_sw_agc;
+ u8 power_save;
+ u8 dual_watch;
+ u8 backlight;
+ ul16 call_ch;
+ u8 beep;
+ u8 key_short1;
+ u8 key_long1;
+ u8 key_short2;
+ u8 key_long2;
+ u8 scan_mode;
+ u8 auto_lock;
+ u8 power_on_screen_mode;
+ u8 alarm_mode;
+ u8 roger_tone;
+ u8 repeater_tail;
+ u8 tail_tone;
+ u8 denoise_sw;
+ u8 denoise_lvl;
+ u8 transpositional_sw;
+ u8 transpositional_lvl;
+ u8 chn_A_volume;
+ u8 chn_B_volume;
+ u8 key_tone_flag;
+ u8 language;
+ u8 noaa_same_decode;
+ u8 noaa_same_event;
+ u8 noaa_same_address;
+ u8 unknown;
+ u8 sbar;
+ u8 brightness;
+ u8 kill_code;
+ u8 dtmf_side_tone;
+ u8 dtmf_decode_rspn;
+ u8 match_tot;
+ u8 match_qt_mode;
+ u8 match_dcs_bit;
+ u8 match_threshold;
+ u8 unknown_2;
+ ul16 cw_pitch_freq;
+ u8 unknown_3[4];
+ ul16 dtmf_separator;
+ ul16 dtmf_group_code;
+ u8 dtmf_reset_time;
+ u8 dtmf_resv4;
+ ul16 dtmf_carry_time;
+ ul16 dtmf_first_code_time;
+ ul16 dtmf_d_code_time;
+ ul16 dtmf_continue_time;
+ ul16 dtmf_interval_time;
+ u8 dtmf_id[8];
+ u8 dtmf_up_code[16];
+ u8 dtmf_down_code[16];
+ u8 unknown_4[16];
+ ul16 tone5_separator;
+ ul16 tone5_group_code;
+ u8 tone5_reset_time;
+ u8 tone5_resv4;
+ ul16 tone5_carry_time;
+ ul16 tone5_first_code_time;
+ u8 tone5_protocol;
+ u8 tone5_resv1;
+ ul16 tone5_single_continue_time;
+ ul16 tone5_single_interval_time;
+ u8 tone5_id[8];
+ u8 tone5_up_code[16];
+ u8 tone5_down_code[16];
+ ul16 tone5_user_freq[15];
+ u8 tone5_revs5[2];
+ char logo_string1[16];
+ char logo_string2[16];
+
+ #seekto 0x14000;
+ // General 2 collapsed to general
+ u8 unknown_5[48];
+ u8 dtmf_kill[8];
+ u8 dtmf_wakeup[8];
+ u8 tone5_kill[8];
+ u8 tone5_wakeup[8];
+ u8 unknown_6[16];
+ u8 device_name[16];
+} general;
+
+#seekto 0x15000;
+struct {
+ ul16 a_id;
+ ul16 b_id;
+ ul16 freq_a_id;
+ ul16 freq_b_id;
+ ul16 channel_a_id;
+ ul16 channel_b_id;
+ ul16 noaa_a_id;
+ ul16 noaa_b_id;
+} channels_idx;
+
+#seekto 0x16000;
+struct {
+ u8 name[16];
+ ul16 prio_1;
+ ul16 prio_2;
+ u8 unknown[4];
+ ul16 channels[48];
+ u8 unknown_2[8];
+} scan_list[32];
+
+#seekto 0x1A000;
+struct {
+ u8 name[16];
+ u8 code_id[8];
+} dtmf_contacts[16];
+
+#seekto 0x1A800;
+struct {
+ u8 name[16];
+ u8 code_id[8];
+} tone5_contacts[16];
+
+#seekto 0x22000;
+struct {
+ u8 address[8];
+ u8 info[32];
+} noaa_decode_addresses[16];
+
+#seekto 0x22280;
+struct {
+ u8 value;
+} noaa_same_events_control[128];
+"""
+
+
+class MemoryAddress:
+ """Memory address"""
+ CHANNELS_USAGE = 0x11000
+ FM = 0x12000
+ GENERAL_SETTINGS = 0x13000
+ GENERAL_2_SETTINGS = 0x14000
+ CHANNELS_IDX = 0x15000
+ DTMF_CONTACTS = 0x1A000
+ SCAN_LIST = 0x16000
+ TONE5 = 0x1A800
+ NOAA_DECODE_ADDRESSES = 0x22000
+ NOAA_SAME_EVENT_CONTROL = 0x22280
+
+
+class ChunkSize:
+ """Chunk size"""
+ SETTINGS = 0xF8
+ SETTINGS_2 = 0x70
+ CHANNELS_IDX = 0x10
+ FM = 0x48
+ DTMF_CONTACTS = 0x180
+ SCAN_LIST = 0x80
+ TONE5_CONTACTS = 0x180
+ NOAA_DECODE_ADDRESSES = 0x28
+ NOAA_SAME_EVENTS_CONTROL = 0x80
+
+
+class MessageType:
+ """Message type"""
+ CONNECT_REQUEST = 0x01F4
+ CONNECT_RESPONSE = 0x01F5
+ MEMORY_READ_REQUEST = 0x01FB
+ MEMORY_READ_RESPONSE = 0x01FC
+ MEMORY_WRITE_REQUEST = 0x1FD
+ MEMORY_WRITE_RESPONSE = 0x1FE
+ REBOOT_REQUEST = 0x5DD
+
+
+MAX_CHUNK_SIZE = 0x200
+MEMORY_LIMIT = 0x23000
+
+# MAGIC_CODE is a 32-bit random number in TK11 CPS.
+# Operations following the connection must use the same magic code as
+# during the connection.
+# A MAGIC_CODE with a fixed value can be used and does not seem to cause
+# any errors but must be the same for every communication with radio.
+MAGIC_CODE = 5
+START_MESSAGE_FLAG = (0xAB, 0xCD)
+END_MESSAGE_FLAG = (0xDC, 0xBA)
+
+CONNECTION_REQUEST = struct.pack('<HHI', MessageType.CONNECT_REQUEST,
+ 0x4, MAGIC_CODE)
+
+CHANNELS_COUNT = 999
+NAME_LENGTH = 0x10
+
+DUPLEXES = ['', '+', '-']
+POWER_LEVELS = [
+ chirp_common.PowerLevel("Low", watts=1),
+ chirp_common.PowerLevel("Middle", watts=5),
+ chirp_common.PowerLevel("High", watts=10),
+]
+
+TONE_MODES = ['', "Tone", "TSQL", "DTCS", "Cross"]
+VALID_CROSS_MODES = ['Tone->DTCS', 'DTCS->Tone', 'DTCS->DTCS', 'Tone->Tone']
+
+TX_FREQUENCIES = [
+ [150000, 1800000], # 0.15 MHz – 1.8 MHz
+ [1800000, 18000000], # 1.8 MHz – 18 MHz
+ [18000000, 32000000], # 18 MHz – 32 MHz
+ [32000000, 76000000], # 32 MHz – 76 MHz
+ [108000000, 136000000], # 108 MHz – 136 MHz
+ [136000000, 174000000], # 136 MHz – 174 MHz
+ [174000000, 350000000], # 174 MHz – 350 MHz
+ [350000000, 400000000], # 350 MHz – 400 MHz
+ [400000000, 470000000], # 400 MHz – 470 MHz
+ [470000000, 580000000], # 470 MHz – 580 MHz
+ [580000000, 760000000], # 580 MHz – 760 MHz
+ [760000000, 1000000000], # 760 MHz – 1000 MHz
+ [1000000000, 1160000000], # 1000 MHz – 1160 MHz
+]
+
+DTMF_TIMES = [str(i) for i in range(30, 1001, 10)]
+DTMF_GROUP_CODES = ["A", "B", "C", "D", "*", "#"]
+DTMF_SEPARATE_CODES = ["Null", "A", "B", "C", "D", "*", "#"]
+
+_5TONE_TIMES = [str(i) for i in range(30, 1001, 10)]
+_5TONE_SINGLE_INTERVAL_TIMES = [str(i) for i in range(0, 1001, 10)]
+_5TONE_PROTOCOLS = ["EIA", "EEA", "CCIR", "ZVEI1", "ZVEI2", "User"]
+_5TONE_GROUP_CODES = ["A", "B", "C", "D", "E"]
+_5TONE_SEPARATE_CODES = ["A", "B", "C", "D", "E"]
+
+NUMERIC_CHARSET = "0123456789"
+
+VALID_TONES = [63.0] + list(chirp_common.TONES)
+
+AVAILABLE_SCAN_LIST = ["None"] + ([str(i) for i in range(1, 33)] +
+ ["Scan all channels"])
+ENCRYPT_LIST = ["Off"] + [str(i) for i in range(1, 11)]
+SQUELCH_LIST = list(range(0, 9))
+MSW_LIST = ['2K', '2.5K', '3K', '3.5K', '4K', '4.5K', '5K']
+
+TOT_LIST = ["Off"] + [str(i) for i in range(1, 11)]
+VOX_MODE = ["Off"] + [str(i) for i in range(1, 11)]
+MIC_MODE = [str(i) for i in range(1, 7)]
+POWER_ON_MODE = ["Off"] + [f"1:{i}" for i in range(1, 5)]
+BACKLIGHT = ["Off", "1", "2", "3", "4", "5", "10", "15", "20",
+ "25", "30", "Always ON"]
+SCAN_MODE = ["TO", "CO", "SE"]
+ALARM_MODE = ["Local alarm", "Remote alarm"]
+RESPOND_MODE = ["OFF", "Remind", "Reply", "Remind & reply"]
+BRIGHTNESS_MODE = [str(i) for i in range(8, 201)]
+
+CHANNELS = ["A", "B"]
+VOLUME = ["0%", "33%", "66%", "100%"]
+CHANNEL_DISPLAY_MODE = ["Frequency", "ID", "Name"]
+REPEATER_TAIL_TONE = ["OFF"] + [str(i) for i in range(100, 1100, 100)]
+REMIND_END_OF_TALK = (["OFF", "Beep tone", "MDC"] +
+ [f"User{i}" for i in range(1, 6)])
+DENOISE = ["OFF"] + [str(i) for i in range(1, 7)]
+TRANSPOSITIONAL = ["OFF"] + [str(i) for i in range(1, 6)]
+
+CH_AB_DISPLAY = [f"CH-{i:02d}" for i in range(1, 1000)]
+
+A_DISPLAY_SPECIAL_COUNT = 11
+A_DISPLAY = ([f"A-F{i:02d}" for i in range(1, A_DISPLAY_SPECIAL_COUNT + 1)] +
+ CH_AB_DISPLAY)
+
+B_DISPLAY_SPECIAL_COUNT = 11
+B_DISPLAY = ([f"B-F{i:02d}" for i in range(1, B_DISPLAY_SPECIAL_COUNT + 1)] +
+ CH_AB_DISPLAY)
+
+PTT_ID_MODES = ['OFF', 'Start', 'End', 'Start & end']
+SIGNAL_MODE = ["DTMF", "5TONE"]
+SIDE_KEY_ACTION = ['None', 'Flashlight', 'Power selection', 'Monitor', 'Scan',
+ 'VOX', 'Alarm', 'FM radio', '1750 MHZ']
+KEY_LOCK_MODE = ["Unlocked", "Locked"]
+BOOT_SCREEN_MODE = ["Fullscreen", "Welcome", "Battery voltage", "Picture",
+ "None"]
+
+FREQUENCY_METER_MODES = ["Normal", "Expert mode", "Auto learning mode"]
+DCS_MODES = ["23bit", "24bit"]
+
+FREQUENCIES = [
+ [150000, 1160000000], # 0.15 MHz – 1160 MHz
+]
+
+CHARSET = "".join([chr(x) for x in range(ord(" "), ord("~") + 1)])
+
+FM_RANGE = (76, 108)
+
+NOAA_SAME_EVENTS = [
+ ("ADR", "Administrative Message"),
+ ("AVA", "Avalanche Watch"),
+ ("AVW", "Avalanche Warning"),
+ ("BLU", "Blue Alert"),
+ ("BWW", "Boil Water Warning"),
+ ("BZW", "Blizzard Warning"),
+ ("CAE", "Child Abduction Emergency"),
+ ("CDW", "Civil Danger Warning"),
+ ("CEM", "Civil Emergency Message"),
+ ("CFA", "Coastal Flood Watch"),
+ ("CFW", "Coastal Flood Warning"),
+ ("DBA", "DAM Watch"),
+ ("DMO", "Practice/Demo Warning"),
+ ("DSW", "Dust Storm Warning"),
+ ("EAN", "Emergency Action Notification"),
+ ("EQW", "Civil Earthquake Warning"),
+ ("EVA", "Evacuation Watch"),
+ ("EVI", "Evacuation Immediate"),
+ ("EWW", "Extreme Wind Warning"),
+ ("FFA", "Flash Flood Watch"),
+ ("FFS", "Flash Flood Statement"),
+ ("FFW", "Flash Flood Warning"),
+ ("FLA", "Flood Watch"),
+ ("FLS", "Flood Statement"),
+ ("FLW", "Flood Warning"),
+ ("FRW", "Fire Warning"),
+ ("FSW", "Flash Freeze Warning"),
+ ("FZW", "Freeze Warning"),
+ ("HLS", "Hurricane Statement"),
+ ("HMW", "Hazardous Materials Warning"),
+ ("HUA", "Hurricane Watch"),
+ ("HUW", "Hurricane Warning"),
+ ("HWA", "High Wind Watch"),
+ ("HWW", "High Wind Warning"),
+ ("IBW", "Iceberg Warning"),
+ ("LAE", "Local Area Emergency"),
+ ("LEW", "Law Enforcement Warning"),
+ ("NAT", "National Audible Test"),
+ ("NIC", "National Information Center"),
+ ("NMN", "Network Message Notification"),
+ ("NPT", "National Periodic Test"),
+ ("NST", "National Silent Test"),
+ ("NUW", "Nuclear Power Plant Warning"),
+ ("POS", "Power Outage Advisory"),
+ ("RHW", "Radiological Hazard Warning"),
+ ("RMT", "Required Monthly Test"),
+ ("RWT", "Required Weekly Test"),
+ ("SMW", "Special Marine Warning"),
+ ("SPS", "Special Weather Statement"),
+ ("SPW", "Shelter In Place Warning"),
+ ("SQW", "Snow Squall Warning"),
+ ("SSA", "Storm Surge Watch"),
+ ("SSW", "Storm Surge Warning"),
+ ("SVA", "Severe Thunderstorm Watch"),
+ ("SVR", "Severe Thunderstorm Warning"),
+ ("SVS", "Severe Weather Statement"),
+ ("TOA", "Tornado Watch"),
+ ("TOE", "911 Telephone Outage Emergency"),
+ ("TOW", "Tornado Warning"),
+ ("TRA", "Tropical Storm Watch"),
+ ("TRW", "Tropical Storm Warning"),
+ ("TSA", "Tsunami Watch"),
+ ("TSW", "Tsunami Warning"),
+ ("TXB", "Transmitter Backup On"),
+ ("TXF", "Transmitter Carrier Off"),
+ ("TXO", "Transmitter Carrier On"),
+ ("TXP", "Transmitter Primary On"),
+ ("VOW", "Volcano Warning"),
+ ("WFA", "Wild Fire Watch"),
+ ("WFW", "Wild Fire Warning"),
+ ("WSA", "Winter Storm Watch"),
+ ("WSW", "Winter Storm Warning"),
+ ("", "Unrecognized Warning"),
+ ("", "Unrecognized Watch"),
+ ("", "Unrecognized Emergency"),
+ ("", "Unrecognized Statement"),
+ ("", "Unrecognized Message"),
+]
+
+
+class Mode(enum.Enum):
+ """Modulation enum"""
+ NFM = 5
+ FM = 0
+ AM = 1
+ LSB = 2
+ USB = 3
+ CW = 4
+
+
+class QTType(enum.Enum):
+ """QT Code type enum"""
+ NONE = 0
+ CTCSS = 1
+ NDCS = 2
+ IDCS = 3
+
+
+class Power(enum.Enum):
+ """Power enum"""
+ LOW = 0
+ MIDDLE = 1
+ HIGH = 2
+
+ @property
+ def level(self):
+ """Get power level"""
+ return {
+ Power.LOW: POWER_LEVELS[0],
+ Power.MIDDLE: POWER_LEVELS[1],
+ Power.HIGH: POWER_LEVELS[2]
+ }[self]
+
+
+def parse_str_from_tk11(data: arrayDataElement, default_str: str = "") -> str:
+ """Parse string from TK11 format to chirp format as str.
+ Remove empty characters."""
+ raw = data.get_raw()
+
+ if not raw or raw[0] == 0xFF:
+ return default_str
+
+ try:
+ return raw.rstrip(b' \x00').decode("ascii")
+ except UnicodeDecodeError:
+ return default_str
+
+
+def parse_str_to_tk11(data: str, length: int = 16) -> list[int]:
+ """Parse string from chirp format to TK11 format.
+ Add empty character until a specific length"""
+ return list(data.ljust(length, "\x00").encode("ascii"))
+
+
+def get_response_code(response) -> int | None:
+ """Get response code or None if the response length is < 2"""
+ if len(response) < 2:
+ return None
+
+ return response[0] | response[1] << 8
+
+
+def content_nor_or(content: bytearray) -> None:
+ """Content nor or.
+ This is a sort of magic obfuscation method.
+ Getting it from TK11 CPS analysis but don't know exactly how it works."""
+ num_array = bytearray([
+ 22, 108, 20, 230, 46, 0x91, 13, 64, 33, 53, 213, 64, 19, 3, 233, 128
+ ])
+
+ for i, byte in enumerate(content):
+ content[i] = byte ^ num_array[i % 16]
+
+
+def byte_nor_or(data: bytes, start_index: int, nor_or_len: int) -> bytes:
+ """byte nor or"""
+ content = bytearray(data[start_index:start_index + nor_or_len])
+
+ content_nor_or(content)
+
+ result = bytearray(data)
+ result[start_index:start_index + nor_or_len] = content
+
+ return bytes(result)
+
+
+def encapsulate_message(buf: bytes) -> bytes:
+ """Encapsulate a message with start and end message flags"""
+ length = len(buf)
+ header_bytes = struct.pack(
+ "<BBH",
+ START_MESSAGE_FLAG[0],
+ START_MESSAGE_FLAG[1],
+ length
+ )
+
+ crc_data = checksum.crc16_xmodem(buf)
+ end_flag_1, end_flag_2 = END_MESSAGE_FLAG
+ ender_bytes = struct.pack("<HBB", crc_data, end_flag_1, end_flag_2)
+
+ data = bytearray()
+ data.extend(header_bytes)
+ data.extend(buf)
+ data.extend(ender_bytes)
+
+ return byte_nor_or(data, 4, length + 2)
+
+
+def create_parameter_read_request(start_address: int, length: int):
+ """Create a parameter read request"""
+ address = 0x080000 + start_address
+ fmt = '<HHIHBBI'
+ msg_type = MessageType.MEMORY_READ_REQUEST
+
+ return struct.pack(fmt, msg_type, 0xC, address, length, 0, 0, MAGIC_CODE)
+
+
+def read_serial(serial, length) -> bytes:
+ """
+ Read exactly `length` bytes from the serial port.
+ Raises RadioError if received data is incomplete or invalid.
+ """
+ serial_data = serial.read(length)
+ serial_data_len = len(serial_data)
+
+ if serial_data_len == 0:
+ raise errors.RadioError(
+ "No data received from the radio. Is it turned ON and "
+ "connected ?")
+
+ if length != serial_data_len:
+ raise errors.RadioError(
+ f"Invalid serial data length: expected {length} bytes, "
+ f"got {serial_data_len}")
+
+ if not is_serial_message_complete(serial_data):
+ raise errors.RadioError("Serial message not complete")
+
+ data_length = serial_data[2] | (serial_data[3] << 8)
+ data = bytearray(serial_data[4:4 + data_length])
+ return byte_nor_or(data, 0, data_length)
+
+
+def is_serial_message_complete(message: bytearray) -> bool:
+ """Check if a message is complete or not"""
+ return (message[0] == START_MESSAGE_FLAG[0]
+ and message[1] == START_MESSAGE_FLAG[1]
+ and message[-2] == END_MESSAGE_FLAG[0]
+ and message[-1] == END_MESSAGE_FLAG[1])
+
+
+def read_memory(serial, start_address, length):
+ """Read TK11 radio memory"""
+ fmt = "<HHIHBBI"
+ msg_type = MessageType.MEMORY_READ_REQUEST
+ address = 0x080000 + start_address
+
+ request = struct.pack(fmt, msg_type, 0xC, address, length, 0, 0,
+ MAGIC_CODE)
+ message = encapsulate_message(request)
+
+ try:
+ serial.flush()
+
+ bytes_written = serial.write(message)
+ if bytes_written == 0:
+ raise errors.RadioError(
+ "Failed to send read memory message to radio")
+
+ # Need to add 20 because the structure of memory read response is:
+ # - 4 bytes for header
+ # - 12 bytes for response content
+ # - 4 bytes for start and end magic numbers
+ serial_response = read_serial(serial, length + 20)
+ resp_code = get_response_code(serial_response)
+
+ if resp_code != MessageType.MEMORY_READ_RESPONSE:
+ text = (f"Failed to read memory response from radio. "
+ f"Invalid response code: {resp_code}")
+ LOG.error(text)
+ raise errors.RadioError(text)
+
+ data = serial_response[12:]
+ except Exception as se:
+ raise errors.RadioError(
+ f"Error with serial, failed to read memory {se}") from se
+
+ return data
+
+
+def memory_write(serial, start_address: int, data: bytearray | bytes) -> bool:
+ """Write data to TK11 memory"""
+ fmt = "<HHIHBBI"
+ msg_type = MessageType.MEMORY_WRITE_REQUEST
+ address = 0x080000 + start_address
+
+ request = struct.pack(fmt, msg_type, 0xC, address, len(data), 0, 0,
+ MAGIC_CODE)
+
+ message_data = bytearray()
+ message_data.extend(request)
+ message_data.extend(data)
+
+ message = encapsulate_message(message_data)
+
+ bytes_written = serial.write(message)
+ if bytes_written == 0:
+ text = "Failed to send memory write message to radio, 0 byte written"
+ LOG.error(text)
+ raise errors.RadioError(text)
+
+ serial_response = read_serial(serial, 16)
+ response_code = get_response_code(serial_response)
+ return response_code == MessageType.MEMORY_WRITE_RESPONSE
+
+
+def dtcs_to_chirp(dtcs: int) -> int:
+ """Convert DTCS to chirp format"""
+ return int(format(dtcs, 'o'))
+
+
+def dtcs_to_tk11(dtcs):
+ """Convert DTCS to tk11 format"""
+ return int(str(dtcs), 8)
+
+
+def nullable_float_fm_freq_validate(value):
+ """Validate nullable float"""
+ if value is None or value == "":
+ return ""
+
+ try:
+ float_val = float(value)
+ except ValueError as ve:
+ raise ValueError("Value is not float or empty") from ve
+
+ if float_val < FM_RANGE[0] or float_val > FM_RANGE[1]:
+ raise ValueError(f"Value is not in range {FM_RANGE}")
+
+ return str(float_val)
+
+
+def do_download(radio):
+ """This is your download function"""
+ serial = radio.pipe
+
+ status = chirp_common.Status()
+ status.cur = 0
+ status.msg = "Connecting to radio"
+ radio.status_fn(status)
+
+ connection_request_message = encapsulate_message(CONNECTION_REQUEST)
+
+ try:
+ serial.write(connection_request_message)
+ except Exception as se:
+ raise errors.RadioError("Error with serial, failed to write "
+ "connection request message") from se
+
+ serial_data = read_serial(serial, 64)
+
+ message_type, _, version = struct.unpack('<HH16s', serial_data[:20])
+
+ if message_type != MessageType.CONNECT_RESPONSE:
+ LOG.error("Invalid radio connection response")
+ raise errors.RadioError("Invalid radio connection response")
+
+ firmware_version = version.split(b'\x00', 1)[0].decode('ascii')
+ radio.metadata = {'tk11_firmware_version': firmware_version}
+ LOG.info("Connected to radio - firmware version : %s",
+ firmware_version)
+
+ memory = bytearray()
+
+ for i in range(0, MEMORY_LIMIT, MAX_CHUNK_SIZE):
+ percent = i * 100 // MEMORY_LIMIT
+ status.msg = f"Reading data from radio {percent}%"
+ status.cur = percent
+ radio.status_fn(status)
+
+ memory.extend(read_memory(serial, i, MAX_CHUNK_SIZE))
+
+ return memmap.MemoryMapBytes(bytes(memory))
+
+
+def do_upload(radio):
+ """Upload chirp data to radio"""
+ status = chirp_common.Status()
+ status.msg = f"Uploading data to {radio.VENDOR} {radio.MODEL}"
+ radio.status_fn(status)
+
+ serial = radio.pipe
+
+ memory = radio.get_mmap()
+ memory_size = len(memory)
+
+ try:
+ for i in range(0, memory_size, MAX_CHUNK_SIZE):
+ percent = i * 100 // memory_size
+ status.msg = f"Writing data from radio {percent}%"
+ status.cur = percent
+ radio.status_fn(status)
+
+ memory_write(serial, i, memory[i:i + MAX_CHUNK_SIZE])
+
+ reboot(serial)
+ except Exception as se:
+ raise errors.RadioError("Failed to write memory") from se
+
+
+def reboot(serial):
+ """Send a request to reboot radio"""
+ try:
+ payload = struct.pack("<HH", MessageType.REBOOT_REQUEST, 0)
+
+ message = encapsulate_message(payload)
+ serial.write(message)
+ except Exception as se:
+ raise errors.RadioError("Error with serial, "
+ "failed to write reboot message") from se
+
+
+def get_channel_frequency_range(frequency: int) -> int | None:
+ """Get channel frequency range"""
+ if frequency == 0:
+ return 0xFF
+
+ channel_frequency_rang = 0
+
+ for f_min, f_max in TX_FREQUENCIES:
+ if f_min > frequency or frequency > f_max:
+ channel_frequency_rang += 1
+ else:
+ break
+
+ return channel_frequency_rang
+
+
+def is_tone_valid(tone):
+ """Return true if tone is valid, false otherwise"""
+ return tone in VALID_TONES
+
+
+def parse_scan_channel_to_tk11(channels, name):
+ if name == "Current channel":
+ return 0x5A5A
+
+ if name == "None":
+ return CHANNELS_COUNT
+
+ channels = [parse_str_from_tk11(c.name)
+ if c.rx_freq != 0 else "" for c in channels]
+
+ try:
+ return channels.index(name)
+ except ValueError:
+ return CHANNELS_COUNT
+
+
+def parse_scan_channel_from_tk11(memory_channels, value, prio_channels):
+ if value == 0x5A5A:
+ return 0
+
+ try:
+ parsed = parse_str_from_tk11(memory_channels[value].name)
+ return prio_channels.index(parsed)
+ except (ValueError, IndexError):
+ return 1
+
+
+def index_to_char(i):
+ if 1 <= i <= 9:
+ return str(i)
+
+ return chr(ord('A') + (i - 10))
+
+
+def get_dcs_from_polarity(polarity):
+ """Return QTType.NDCS.value if polarity == "N"
+ QTType.IDCS.value otherwise"""
+ return QTType.NDCS.value if polarity == "N" else QTType.IDCS.value
+
+
+@directory.register
+class TK11(CloneModeRadio):
+ """Quansheng TK 11"""
+ VENDOR = "Quansheng"
+ MODEL = "TK11"
+ BAUD_RATE = 38400
+
+ # Return information about this radio's features, including
+ # how many memories it has, what bands it supports, etc
+ def get_features(self):
+ """Get radio features"""
+ rf = chirp_common.RadioFeatures()
+ rf.has_bank = False
+ rf.has_settings = True
+ rf.has_rx_dtcs = True
+ rf.has_cross = True
+ rf.has_tuning_step = False
+ rf.has_nostep_tuning = True
+ rf.memory_bounds = (1, CHANNELS_COUNT)
+ rf.valid_bands = FREQUENCIES
+ rf.valid_power_levels = POWER_LEVELS
+ rf.valid_modes = [mode.name for mode in Mode]
+ rf.valid_name_length = NAME_LENGTH
+ rf.valid_duplexes = DUPLEXES
+ rf.valid_characters = CHARSET
+ rf.valid_tmodes = TONE_MODES
+ rf.valid_cross_modes = VALID_CROSS_MODES
+ rf.valid_tones = VALID_TONES
+ rf.valid_skips = []
+
+ return rf
+
+ def set_settings(self, settings):
+ """Set settings"""
+ memory = self._memobj
+
+ settings_root = settings["settings"]
+
+ # Startup
+ startup = settings_root["startup"]
+
+ memory.general.device_name = parse_str_to_tk11(
+ str(startup["device_name"].value))
+
+ memory.general.power_on_screen_mode = int(startup["boot_screen"].value)
+
+ memory.general.logo_string1 = parse_str_to_tk11(
+ str(startup["start_string_1"].value))
+ memory.general.logo_string2 = parse_str_to_tk11(
+ str(startup["start_string_2"].value))
+
+ a_display = int(startup["a_display"].value)
+ if a_display < A_DISPLAY_SPECIAL_COUNT:
+ memory.channels_idx.a_id = CHANNELS_COUNT + a_display
+ else:
+ memory.channels_idx.a_id = a_display - A_DISPLAY_SPECIAL_COUNT
+
+ b_display = int(startup["b_display"].value)
+ if b_display < B_DISPLAY_SPECIAL_COUNT:
+ memory.channels_idx.b_id = CHANNELS_COUNT + b_display
+ else:
+ memory.channels_idx.b_id = b_display - B_DISPLAY_SPECIAL_COUNT
+
+ # Buttons
+ buttons = settings_root["buttons"]
+ memory.general.key_short1 = (
+ int(buttons["side_key_1_short_press"].value))
+ memory.general.key_long1 = int(buttons["side_key_1_long_press"].value)
+ memory.general.key_short2 = (
+ int(buttons["side_key_2_short_press"].value))
+ memory.general.key_long2 = int(buttons["side_key_2_long_press"].value)
+
+ memory.general.keylock = int(buttons["key_lock"].value)
+ memory.general.auto_lock = bool(buttons["auto_lock"].value)
+
+ # General settings
+ general = settings_root["general"]
+ memory.general.tx_tot = int(general["tot"].value)
+
+ vox = int(general["vox"].value)
+ if vox == 0:
+ memory.general.vox_sw = 0
+ memory.general.vox_lvl = 0
+ else:
+ memory.general.vox_sw = 1
+ memory.general.vox_lvl = vox - 1
+
+ memory.general.mic = int(general["microphone"].value)
+ memory.general.beep = bool(general["beep_tone"].value)
+ memory.general.power_save = int(general["power_on_mode"].value)
+ memory.general.backlight = int(general["backlight"].value)
+ memory.general.scan_mode = int(general["scan_mode"].value)
+ memory.general.alarm_mode = int(general["alarm"].value)
+ memory.general.kill_code = bool(general["kill_code"].value)
+ memory.general.dtmf_side_tone = bool(general["side_tone"].value)
+ memory.general.dtmf_decode_rspn = int(general["respond"].value)
+ memory.general.sbar = bool(general["s_bar"].value)
+ memory.general.key_tone_flag = bool(general["voice"].value)
+ memory.general.mw_sw_agc = bool(general["mw_sw_agc"].value)
+ memory.general.brightness = int(general["brightness"].value)
+ memory.general.cw_pitch_freq = int(general["cw_pitch_freq"].value)
+
+ # Channel settings
+ channel = settings_root["channel"]
+
+ memory.general.channel_ab = int(channel["main_channel"].value)
+ memory.general.chn_A_volume = int(channel["a_rx_volume_balance"].value)
+ memory.general.chn_B_volume = int(channel["b_rx_volume_balance"].value)
+ memory.general.freq_mode = bool(channel["vfo_mode"].value)
+ memory.general.channel_display_mode = (
+ int(channel["channel_display_mode"].value))
+ memory.general.repeater_tail = int(channel["repeater_tail_tone"].value)
+ memory.general.call_ch = int(channel["call_channel"].value)
+ memory.general.tail_tone = int(channel["tail_tone"].value)
+ memory.general.dual_watch = int(channel["dual_receive"].value)
+ memory.general.roger_tone = int(channel["remind_eot"].value)
+
+ denoise = int(channel["denoise"].value)
+ if denoise == 0:
+ memory.general.denoise_sw = 0
+ memory.general.denoise_lvl = 0
+ else:
+ memory.general.denoise_sw = 1
+ memory.general.denoise_lvl = denoise - 1
+
+ transpositional = int(channel["transpositional"].value)
+ if transpositional == 0:
+ memory.general.transpositional_sw = 0
+ memory.general.transpositional_lvl = 0
+ else:
+ memory.general.transpositional_sw = 1
+ memory.general.transpositional_lvl = transpositional - 1
+
+ # Match frequency
+ match_frequency = settings_root["match_frequency"]
+
+ memory.general.match_tot = (
+ int(match_frequency["frequency_meter_tot"].value))
+ memory.general.match_qt_mode = (
+ int(match_frequency["frequency_meter_mode"].value))
+ memory.general.match_dcs_bit = int(match_frequency["dcs"].value)
+ memory.general.match_threshold = (
+ int(match_frequency["match_threshold"].value))
+
+ # FM
+ fm = settings_root["fm"]
+
+ memory.fm.vfo_frequency = int(fm["vfo"].value * 10)
+ memory.fm.memory_vfo_flag = int(fm["mode"].value)
+ memory.fm.channel_id = int(fm["channel"].value)
+
+ for i, setting in enumerate(settings["fm_frequencies"]):
+ memory.fm.frequencies[i] = 0xFFFF \
+ if setting.value == "" else int(float(setting.value) * 10)
+
+ # NOAA settings
+ noaa = settings_root["noaa"]
+
+ memory.general.noaa_same_decode = int(noaa["noaa_same_decode"].value)
+ memory.general.noaa_same_event = int(noaa["noaa_same_event"].value)
+ memory.general.noaa_same_address = int(noaa["noaa_same_address"].value)
+ memory.general.noaa_sq = noaa["noaa_sq"].value.get_value()
+ memory.general.noaa_scan = int(noaa["noaa_scan"].value)
+
+ items = noaa["noaa_same_event_control"].items()
+ for i, (name, ev) in enumerate(items):
+ memory.noaa_same_events_control[i].value = int(
+ ev[name + "_checked"].value)
+
+ # DTMF settings
+ self.set_dtmf_settings(memory, settings["dtmf_settings"])
+ self.set_dtmf_contacts(memory,
+ settings["dtmf_settings"]["dtmf_contacts"])
+
+ # Scan list
+ scan_list = settings["scan_list"]
+
+ for group_name, scan_group in scan_list.items():
+ i = int(group_name.split("_")[-1])
+
+ name = str(scan_group[f"{group_name}_name"].value)
+ prio_1_name = str(scan_group[f"{group_name}_prio_channel_1"].value)
+ prio_2_name = str(scan_group[f"{group_name}_prio_channel_2"].value)
+
+ memory.scan_list[i].name = parse_str_to_tk11(name)
+ memory.scan_list[i].prio_1 = parse_scan_channel_to_tk11(
+ memory.channels, prio_1_name)
+ memory.scan_list[i].prio_2 = parse_scan_channel_to_tk11(
+ memory.channels, prio_2_name)
+
+ # 5TONE settings
+ tone5_settings = settings["tone5_settings"]
+ self.set_tone5_settings(memory, tone5_settings)
+ self.set_tone5_contacts(memory, tone5_settings["tone5_contacts"])
+
+ # NOAA Decode Addresses
+ noaa_decode_addresses = settings["noaa_decode_addresses"]
+ for i, (name, group) in enumerate(noaa_decode_addresses.items()):
+ memory.noaa_decode_addresses[i].address = parse_str_to_tk11(
+ str(group[name + "_address"].value), 8)
+ memory.noaa_decode_addresses[i].info = parse_str_to_tk11(
+ str(group[name + "_information"].value), 32)
+
+ @staticmethod
+ def set_dtmf_settings(memory, dtmf_settings):
+ """Set DTMF settings"""
+ memory.general.dtmf_id = parse_str_to_tk11(
+ str(dtmf_settings["local_code"].value), 8)
+ memory.general.dtmf_kill = parse_str_to_tk11(
+ str(dtmf_settings["kill_code"].value), 8)
+ memory.general.dtmf_wakeup = parse_str_to_tk11(
+ str(dtmf_settings["revive_code"].value), 8)
+ memory.general.dtmf_separator = ord(
+ str(dtmf_settings["separate_code"].value))
+ memory.general.dtmf_group_code = ord(
+ str(dtmf_settings["group_code"].value))
+ memory.general.dtmf_reset_time = int(
+ dtmf_settings["auto_reset_time"].value)
+ memory.general.dtmf_up_code = parse_str_to_tk11(
+ str(dtmf_settings["up_code"].value))
+ memory.general.dtmf_down_code = parse_str_to_tk11(
+ str(dtmf_settings["down_code"].value))
+ memory.general.dtmf_carry_time = (
+ dtmf_settings["pre_load_time"].value.get_value())
+ memory.general.dtmf_first_code_time = (
+ dtmf_settings["first_code_persist"].value.get_value())
+ memory.general.dtmf_d_code_time = (
+ dtmf_settings["code_persist_time"].value.get_value())
+ memory.general.dtmf_continue_time = (
+ dtmf_settings["code_continue_time"].value.get_value())
+ memory.general.dtmf_interval_time = (
+ dtmf_settings["code_interval_time"].value.get_value())
+
+ @staticmethod
+ def set_dtmf_contacts(memory, dtmf_contacts):
+ """Set DTMF contacts"""
+ for i, contact in enumerate(memory.dtmf_contacts):
+ group = dtmf_contacts[f"dtmf-contact-{i}"]
+
+ contact.name = parse_str_to_tk11(
+ str(group[f"contact_{i}_name"].value))
+ contact.code_id = parse_str_to_tk11(
+ str(group[f"contact_{i}_id_code"].value), 8)
+
+ @staticmethod
+ def set_tone5_settings(memory, tone5_settings):
+ """Set DTMF settings"""
+ memory.general.tone5_id = parse_str_to_tk11(
+ str(tone5_settings["local_code"].value), 8)
+ memory.general.tone5_kill = parse_str_to_tk11(
+ str(tone5_settings["kill_code"].value), 8)
+ memory.general.tone5_wakeup = parse_str_to_tk11(
+ str(tone5_settings["revive_code"].value), 8)
+ memory.general.tone5_separator = ord(
+ str(tone5_settings["separate_code"].value))
+ memory.general.tone5_group_code = ord(
+ str(tone5_settings["group_code"].value))
+ memory.general.tone5_reset_time = int(
+ tone5_settings["auto_reset_time"].value)
+ memory.general.tone5_up_code = parse_str_to_tk11(
+ str(tone5_settings["up_code"].value))
+ memory.general.tone5_down_code = parse_str_to_tk11(
+ str(tone5_settings["down_code"].value))
+ memory.general.tone5_carry_time = (
+ tone5_settings["pre_load_time"].value.get_value())
+ memory.general.tone5_first_code_time = (
+ tone5_settings["first_code_persist"].value.get_value())
+ memory.general.tone5_first_code_time = (
+ tone5_settings["code_persist_time"].value.get_value())
+ memory.general.tone5_single_continue_time = (
+ tone5_settings["code_continue_time"].value.get_value())
+ memory.general.tone5_single_interval_time = (
+ tone5_settings["code_interval_time"].value.get_value())
+ memory.general.tone5_protocol = int(tone5_settings["protocol"].value)
+
+ # User frequencies
+ frequencies = tone5_settings["tone5_user_frequencies"]
+ for i, user_frequency in enumerate(frequencies):
+ memory.general.tone5_user_freq[i] = int(user_frequency.value)
+
+ @staticmethod
+ def set_tone5_contacts(memory, tone5_contacts):
+ """Set DTMF contacts"""
+ for i, contact in enumerate(memory.tone5_contacts):
+ group = tone5_contacts[f"tone5-contact-{i}"]
+
+ contact.name = parse_str_to_tk11(
+ str(group[f"contact_{i}_name"].value))
+ contact.code_id = parse_str_to_tk11(
+ str(group[f"contact_{i}_id_code"].value), 8)
+
+ def get_settings(self):
+ """Get settings"""
+ memory = self._memobj
+
+ firmware = self.get_firmware_settings_group()
+ settings = self.get_settings_group(memory)
+ dtmf = self.get_dtmf_group(memory)
+ tone5 = self.get_tone5_group(memory)
+ scan_list = self.get_scan_list_group(memory)
+ fm_frequencies = self.get_fm_frequencies_group(memory)
+ noaa_decode_addresses = self.get_noaa_decode_addresses_group(memory)
+
+ return RadioSettings(firmware, settings, scan_list, dtmf,
+ tone5, fm_frequencies, noaa_decode_addresses)
+
+ def get_firmware_settings_group(self):
+ """Get firmware settings"""
+ firmware = RadioSettingGroup("firmware", "Firmware")
+
+ version = self.metadata.get("tk11_firmware_version", "unknown")
+ firmware_value_str = RadioSettingValueString(0, 7, version)
+ firmware_value_str.set_mutable(False)
+
+ firmware_version = RadioSetting("firmware_version", "Version",
+ firmware_value_str)
+
+ firmware.append(firmware_version)
+ return firmware
+
+ @staticmethod
+ def get_scan_list_group(memory):
+ """Get a scan list settings group"""
+ scan_list = RadioSettingGroup("scan_list", "Scan list")
+
+ for i, scan in enumerate(memory.scan_list):
+ sub_group = RadioSettingSubGroup(f"scan_list_{i}",
+ f"Scan list {i + 1}")
+
+ name = RadioSetting(
+ f"scan_list_{i}_name",
+ "Name",
+ RadioSettingValueString(
+ 0,
+ 10,
+ parse_str_from_tk11(scan.name, f"ScanList{i + 1}"),
+ autopad=False
+ )
+ )
+ sub_group.append(name)
+
+ prio_channels = (["Current channel", "None"] +
+ [parse_str_from_tk11(memory.channels[i].name)
+ for i in scan.channels if i != 0xFFFF])
+
+ prio_channel_1 = RadioSetting(
+ f"scan_list_{i}_prio_channel_1",
+ "Prio channel 1",
+ RadioSettingValueList(
+ prio_channels,
+ current_index=parse_scan_channel_from_tk11(
+ memory.channels, int(scan.prio_1), prio_channels)
+ )
+ )
+ sub_group.append(prio_channel_1)
+
+ prio_channel_2 = RadioSetting(
+ f"scan_list_{i}_prio_channel_2",
+ "Prio channel 2",
+ RadioSettingValueList(
+ prio_channels,
+ current_index=parse_scan_channel_from_tk11(
+ memory.channels, int(scan.prio_2), prio_channels)
+ )
+ )
+ sub_group.append(prio_channel_2)
+
+ scan_list.append(sub_group)
+
+ return scan_list
+
+ @staticmethod
+ def get_fm_frequencies_group(memory):
+ """Get fm frequencies settings group"""
+ fm_frequencies = RadioSettingGroup("fm_frequencies",
+ "FM")
+
+ for i, frequency in enumerate(memory.fm.frequencies):
+ setting = RadioSettingValueString(
+ 0,
+ 6,
+ str(frequency / 10) if frequency != 0xFFFF else "",
+ charset=NUMERIC_CHARSET + '.',
+ autopad=False
+ )
+ setting.set_validate_callback(nullable_float_fm_freq_validate)
+
+ name = RadioSetting(f"fm_frequency_{i}", f"Frequency {i + 1}",
+ setting)
+ fm_frequencies.append(name)
+
+ return fm_frequencies
+
+ @staticmethod
+ def get_noaa_decode_addresses_group(memory):
+ """Get NOAA decode addresses group"""
+ noaa_decode_addresses = RadioSettingGroup(
+ "noaa_decode_addresses", "NOAA decode addresses")
+
+ for i, noaa_decode_address in enumerate(memory.noaa_decode_addresses):
+ group = RadioSettingSubGroup(f"noaa_decode_address_{i}",
+ f"NOAA decode address {i + 1}")
+
+ group.append(
+ RadioSetting(
+ f"noaa_decode_address_{i}_address",
+ "NOAA address",
+ RadioSettingValueString(
+ 0,
+ 6,
+ parse_str_from_tk11(noaa_decode_address.address),
+ autopad=False
+ )
+ )
+ )
+
+ group.append(
+ RadioSetting(
+ f"noaa_decode_address_{i}_information",
+ "Information",
+ RadioSettingValueString(
+ 0,
+ 32,
+ parse_str_from_tk11(noaa_decode_address.info),
+ autopad=False
+ )
+ )
+ )
+
+ noaa_decode_addresses.append(group)
+
+ return noaa_decode_addresses
+
+ def get_settings_group(self, memory):
+ settings = RadioSettingGroup("settings", "Settings")
+
+ general = self.general_settings(memory)
+ settings.append(general)
+
+ startup = self.startup_settings(memory)
+ settings.append(startup)
+
+ buttons = self.buttons_settings(memory)
+ settings.append(buttons)
+
+ channel = self.channel_settings(self, memory)
+ settings.append(channel)
+
+ match_frequency = self.match_frequency_settings(memory)
+ settings.append(match_frequency)
+
+ fm = self.fm_settings(memory)
+ settings.append(fm)
+
+ noaa = self.noaa_settings(memory)
+ settings.append(noaa)
+
+ return settings
+
+ def get_dtmf_group(self, memory):
+ dtmf_settings = RadioSettingGroup("dtmf_settings", "DTMF")
+
+ local_code = RadioSetting(
+ "local_code",
+ "Local code",
+ RadioSettingValueString(
+ 0,
+ 3,
+ parse_str_from_tk11(memory.general.dtmf_id),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ dtmf_settings.append(local_code)
+
+ kill_code = RadioSetting(
+ "kill_code",
+ "Kill code",
+ RadioSettingValueString(
+ 0,
+ 5,
+ parse_str_from_tk11(memory.general.dtmf_kill),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ dtmf_settings.append(kill_code)
+
+ revive_code = RadioSetting(
+ "revive_code",
+ "Revive code",
+ RadioSettingValueString(
+ 0,
+ 5,
+ parse_str_from_tk11(memory.general.dtmf_wakeup),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ dtmf_settings.append(revive_code)
+
+ separate_code = RadioSetting(
+ "separate_code",
+ "Separate code",
+ RadioSettingValueList(
+ DTMF_SEPARATE_CODES,
+ current_index=DTMF_SEPARATE_CODES.index(
+ parse_str_from_tk11(memory.general.dtmf_separator))
+ )
+ )
+ dtmf_settings.append(separate_code)
+
+ group_code = RadioSetting(
+ "group_code",
+ "Group code",
+ RadioSettingValueList(
+ DTMF_GROUP_CODES,
+ current_index=DTMF_GROUP_CODES.index(
+ parse_str_from_tk11(memory.general.dtmf_group_code))
+ )
+ )
+ dtmf_settings.append(group_code)
+
+ auto_reset_time = RadioSetting(
+ "auto_reset_time",
+ "Auto reset time",
+ RadioSettingValueInteger(
+ 5,
+ 60,
+ int(memory.general.dtmf_reset_time)
+ )
+ )
+ dtmf_settings.append(auto_reset_time)
+
+ up_code = RadioSetting(
+ "up_code",
+ "Up code",
+ RadioSettingValueString(
+ 0,
+ 14,
+ parse_str_from_tk11(memory.general.dtmf_up_code),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ dtmf_settings.append(up_code)
+
+ down_code = RadioSetting(
+ "down_code",
+ "Down code",
+ RadioSettingValueString(
+ 0,
+ 14,
+ parse_str_from_tk11(memory.general.dtmf_down_code),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ dtmf_settings.append(down_code)
+
+ pre_load_time = RadioSetting(
+ "pre_load_time",
+ "Pre load time (ms)",
+ RadioSettingValueList(
+ DTMF_TIMES,
+ current_index=DTMF_TIMES.index(
+ str(int(memory.general.dtmf_carry_time)))
+ )
+ )
+ dtmf_settings.append(pre_load_time)
+
+ first_code_persist = RadioSetting(
+ "first_code_persist",
+ "First code persist time (ms)",
+ RadioSettingValueList(
+ DTMF_TIMES,
+ current_index=DTMF_TIMES.index(
+ str(int(memory.general.dtmf_first_code_time)))
+ )
+ )
+ dtmf_settings.append(first_code_persist)
+
+ code_persist_time = RadioSetting(
+ "code_persist_time",
+ "Code persist time (ms)",
+ RadioSettingValueList(
+ DTMF_TIMES,
+ current_index=DTMF_TIMES.index(
+ str(int(memory.general.dtmf_d_code_time)))
+ )
+ )
+ dtmf_settings.append(code_persist_time)
+
+ code_continue_time = RadioSetting(
+ "code_continue_time",
+ "Code continue time (ms)",
+ RadioSettingValueList(
+ DTMF_TIMES,
+ current_index=DTMF_TIMES.index(
+ str(int(memory.general.dtmf_continue_time)))
+ )
+ )
+ dtmf_settings.append(code_continue_time)
+
+ code_interval_time = RadioSetting(
+ "code_interval_time",
+ "Code interval time (ms)",
+ RadioSettingValueList(
+ DTMF_TIMES,
+ current_index=DTMF_TIMES.index(
+ str(int(memory.general.dtmf_interval_time)))
+ )
+ )
+ dtmf_settings.append(code_interval_time)
+
+ dtmf_contacts = self.get_dtmf_contacts_group(memory)
+ dtmf_settings.append(dtmf_contacts)
+
+ return dtmf_settings
+
+ @staticmethod
+ def get_dtmf_contacts_group(memory):
+ dtmf_contacts = RadioSettingGroup("dtmf_contacts", "Contacts")
+
+ for i, contact in enumerate(memory.dtmf_contacts):
+ sub_group = RadioSettingSubGroup(f"dtmf-contact-{i}",
+ f"Contact {i + 1}")
+
+ name = RadioSetting(
+ f"contact_{i}_name",
+ "Name",
+ RadioSettingValueString(
+ 0,
+ 8,
+ parse_str_from_tk11(contact.name),
+ autopad=False
+ )
+ )
+ sub_group.append(name)
+
+ id_code = RadioSetting(
+ f"contact_{i}_id_code",
+ "Id code",
+ RadioSettingValueString(
+ 0,
+ 3,
+ parse_str_from_tk11(contact.code_id),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ sub_group.append(id_code)
+
+ dtmf_contacts.append(sub_group)
+
+ return dtmf_contacts
+
+ def get_tone5_group(self, memory):
+ tone5_settings = RadioSettingGroup("tone5_settings", "5Tone")
+
+ local_code = RadioSetting(
+ "local_code",
+ "Local code",
+ RadioSettingValueString(
+ 0,
+ 3,
+ parse_str_from_tk11(memory.general.tone5_id),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ tone5_settings.append(local_code)
+
+ kill_code = RadioSetting(
+ "kill_code",
+ "Kill code",
+ RadioSettingValueString(
+ 0,
+ 5,
+ parse_str_from_tk11(memory.general.tone5_kill),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ tone5_settings.append(kill_code)
+
+ revive_code = RadioSetting(
+ "revive_code",
+ "Revive code",
+ RadioSettingValueString(
+ 0,
+ 5,
+ parse_str_from_tk11(memory.general.tone5_wakeup),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ tone5_settings.append(revive_code)
+
+ separate_code = RadioSetting(
+ "separate_code",
+ "Separate code",
+ RadioSettingValueList(
+ _5TONE_SEPARATE_CODES,
+ current_index=_5TONE_SEPARATE_CODES.index(
+ parse_str_from_tk11(memory.general.tone5_separator))
+ )
+ )
+ tone5_settings.append(separate_code)
+
+ group_code = RadioSetting(
+ "group_code",
+ "Group code",
+ RadioSettingValueList(
+ _5TONE_GROUP_CODES,
+ current_index=_5TONE_GROUP_CODES.index(
+ parse_str_from_tk11(memory.general.tone5_group_code))
+ )
+ )
+ tone5_settings.append(group_code)
+
+ auto_reset_time = RadioSetting(
+ "auto_reset_time",
+ "Auto reset time",
+ RadioSettingValueInteger(
+ 5,
+ 60,
+ int(memory.general.tone5_reset_time)
+ )
+ )
+ tone5_settings.append(auto_reset_time)
+
+ up_code = RadioSetting(
+ "up_code",
+ "Up code",
+ RadioSettingValueString(
+ 0,
+ 14,
+ parse_str_from_tk11(memory.general.tone5_up_code),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ tone5_settings.append(up_code)
+
+ down_code = RadioSetting(
+ "down_code",
+ "Down code",
+ RadioSettingValueString(
+ 0,
+ 14,
+ parse_str_from_tk11(memory.general.tone5_down_code),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ tone5_settings.append(down_code)
+
+ pre_load_time = RadioSetting(
+ "pre_load_time",
+ "Pre load time (ms)",
+ RadioSettingValueList(
+ _5TONE_TIMES,
+ current_index=_5TONE_TIMES.index(
+ str(int(memory.general.tone5_carry_time)))
+ )
+ )
+ tone5_settings.append(pre_load_time)
+
+ first_code_persist = RadioSetting(
+ "first_code_persist",
+ "First code persist time (ms)",
+ RadioSettingValueList(
+ _5TONE_TIMES,
+ current_index=_5TONE_TIMES.index(
+ str(int(memory.general.tone5_first_code_time)))
+ )
+ )
+ tone5_settings.append(first_code_persist)
+
+ code_persist_time = RadioSetting(
+ "code_persist_time",
+ "Code persist time (ms)",
+ RadioSettingValueList(
+ _5TONE_TIMES,
+ current_index=_5TONE_TIMES.index(
+ str(int(memory.general.tone5_first_code_time)))
+ )
+ )
+ tone5_settings.append(code_persist_time)
+
+ code_continue_time = RadioSetting(
+ "code_continue_time",
+ "Code continue time (ms)",
+ RadioSettingValueList(
+ _5TONE_TIMES,
+ current_index=_5TONE_TIMES.index(
+ str(int(memory.general.tone5_single_continue_time)))
+ )
+ )
+ tone5_settings.append(code_continue_time)
+
+ code_interval_time = RadioSetting(
+ "code_interval_time",
+ "Code interval time (ms)",
+ RadioSettingValueList(
+ _5TONE_SINGLE_INTERVAL_TIMES,
+ current_index=_5TONE_SINGLE_INTERVAL_TIMES.index(
+ str(int(memory.general.tone5_single_interval_time)))
+ )
+ )
+ tone5_settings.append(code_interval_time)
+
+ protocol = RadioSetting(
+ "protocol",
+ "Protocol",
+ RadioSettingValueList(
+ _5TONE_PROTOCOLS,
+ current_index=int(memory.general.tone5_protocol)
+ )
+ )
+ tone5_settings.append(protocol)
+
+ _5tone_freq_sub_group = self.get_5tone_frequencies_sub_group(memory)
+ tone5_settings.append(_5tone_freq_sub_group)
+
+ _5tone_contacts = self.get_5tone_contacts_group(memory)
+ tone5_settings.append(_5tone_contacts)
+
+ return tone5_settings
+
+ @staticmethod
+ def get_5tone_frequencies_sub_group(memory):
+ _5tone_user_frequencies = RadioSettingSubGroup(
+ "tone5_user_frequencies", "Frequencies")
+
+ for i in range(len(memory.general.tone5_user_freq) - 1):
+ name = RadioSetting(
+ f"user_{i}_freq",
+ f"User {index_to_char(i + 1)}",
+ RadioSettingValueInteger(
+ 350, 3500, int(memory.general.tone5_user_freq[i]))
+ )
+ _5tone_user_frequencies.append(name)
+
+ return _5tone_user_frequencies
+
+ @staticmethod
+ def get_5tone_contacts_group(memory):
+ _5tone_contacts = RadioSettingGroup("tone5_contacts", "Contacts")
+
+ for i, contact in enumerate(memory.tone5_contacts):
+ sub_group = RadioSettingSubGroup(f"tone5-contact-{i}",
+ f"Contact {i + 1}")
+
+ name = RadioSetting(
+ f"contact_{i}_name",
+ "Name",
+ RadioSettingValueString(
+ 0,
+ 8,
+ parse_str_from_tk11(contact.name),
+ autopad=False
+ )
+ )
+ sub_group.append(name)
+
+ id_code = RadioSetting(
+ f"contact_{i}_id_code",
+ "Id code",
+ RadioSettingValueString(
+ 0,
+ 3,
+ parse_str_from_tk11(contact.code_id),
+ charset=NUMERIC_CHARSET,
+ autopad=False
+ )
+ )
+ sub_group.append(id_code)
+
+ _5tone_contacts.append(sub_group)
+
+ return _5tone_contacts
+
+ def get_channels_name(self):
+ """Get a list of valid channels name"""
+ return [parse_str_from_tk11(c.name)
+ for c in self.get_memory_object().channels
+ if c.rx_freq is not None and c.rx_freq != 0]
+
+ @staticmethod
+ def general_settings(memory):
+ """Get general settings"""
+ general = RadioSettingGroup("general", "General")
+
+ tot = RadioSetting(
+ "tot",
+ "TOT (minute)",
+ RadioSettingValueList(TOT_LIST,
+ current_index=int(memory.general.tx_tot))
+ )
+ general.append(tot)
+
+ vox_level = int(memory.general.vox_lvl)
+ vox_sw = int(memory.general.vox_sw)
+ vox = RadioSetting(
+ "vox",
+ "VOX",
+ RadioSettingValueList(
+ VOX_MODE, current_index=vox_level + 1 if vox_sw != 0 else 0)
+ )
+ general.append(vox)
+
+ microphone = RadioSetting(
+ "microphone",
+ "Microphone",
+ RadioSettingValueList(MIC_MODE,
+ current_index=int(memory.general.mic))
+ )
+ general.append(microphone)
+
+ beep_tone = RadioSetting(
+ "beep_tone",
+ "Beep tone",
+ RadioSettingValueBoolean(bool(memory.general.beep))
+ )
+ general.append(beep_tone)
+
+ power_on_mode = RadioSetting(
+ "power_on_mode",
+ "Power ON mode",
+ RadioSettingValueList(POWER_ON_MODE,
+ current_index=int(memory.general.power_save))
+ )
+ general.append(power_on_mode)
+
+ backlight = RadioSetting(
+ "backlight",
+ "Backlight",
+ RadioSettingValueList(BACKLIGHT,
+ current_index=int(memory.general.backlight))
+ )
+ general.append(backlight)
+
+ scan_mode = RadioSetting(
+ "scan_mode",
+ "Scan mode",
+ RadioSettingValueList(SCAN_MODE,
+ current_index=int(memory.general.scan_mode))
+ )
+ general.append(scan_mode)
+
+ alarm = RadioSetting(
+ "alarm",
+ "Alarm",
+ RadioSettingValueList(ALARM_MODE,
+ current_index=int(memory.general.alarm_mode))
+ )
+ general.append(alarm)
+
+ kill_code = RadioSetting(
+ "kill_code",
+ "Kill code",
+ RadioSettingValueBoolean(
+ bool(memory.general.kill_code)
+ )
+ )
+ general.append(kill_code)
+
+ side_tone = RadioSetting(
+ "side_tone",
+ "Side tone",
+ RadioSettingValueBoolean(
+ bool(memory.general.dtmf_side_tone)
+ )
+ )
+ general.append(side_tone)
+
+ respond = RadioSetting(
+ "respond",
+ "Respond",
+ RadioSettingValueList(
+ RESPOND_MODE,
+ current_index=int(memory.general.dtmf_decode_rspn))
+ )
+ general.append(respond)
+
+ s_bar = RadioSetting(
+ "s_bar",
+ "SBar",
+ RadioSettingValueBoolean(
+ bool(memory.general.sbar)
+ )
+ )
+ general.append(s_bar)
+
+ voice = RadioSetting(
+ "voice",
+ "Voice",
+ RadioSettingValueBoolean(bool(memory.general.key_tone_flag))
+ )
+ general.append(voice)
+
+ mw_sw_agc = RadioSetting(
+ "mw_sw_agc",
+ "MwSw AGC",
+ RadioSettingValueBoolean(bool(memory.general.mw_sw_agc))
+ )
+ general.append(mw_sw_agc)
+
+ brightness = RadioSetting(
+ "brightness",
+ "Brightness",
+ RadioSettingValueInteger(8, 200, int(memory.general.brightness))
+ )
+ general.append(brightness)
+
+ cw_pitch_freq = RadioSetting(
+ "cw_pitch_freq",
+ "CW pitch frequency",
+ RadioSettingValueInteger(
+ 400, 1500, int(memory.general.cw_pitch_freq), 10)
+ )
+ general.append(cw_pitch_freq)
+
+ return general
+
+ @staticmethod
+ def buttons_settings(memory):
+ """Get buttons settings"""
+ buttons = RadioSettingGroup("buttons", "Buttons")
+
+ side_key_1_short_press = RadioSetting(
+ "side_key_1_short_press",
+ "Side key 1 short press",
+ RadioSettingValueList(SIDE_KEY_ACTION,
+ current_index=int(memory.general.key_short1))
+ )
+ buttons.append(side_key_1_short_press)
+
+ side_key_1_long_press = RadioSetting(
+ "side_key_1_long_press",
+ "Side key 1 long press",
+ RadioSettingValueList(SIDE_KEY_ACTION,
+ current_index=int(memory.general.key_long1))
+ )
+ buttons.append(side_key_1_long_press)
+
+ side_key_2_short_press = RadioSetting(
+ "side_key_2_short_press",
+ "Side key 2 short press",
+ RadioSettingValueList(SIDE_KEY_ACTION,
+ current_index=int(memory.general.key_short2))
+ )
+ buttons.append(side_key_2_short_press)
+
+ side_key_2_long_press = RadioSetting(
+ "side_key_2_long_press",
+ "Side key 2 long press",
+ RadioSettingValueList(SIDE_KEY_ACTION,
+ current_index=int(memory.general.key_long2))
+ )
+ buttons.append(side_key_2_long_press)
+
+ key_lock = RadioSetting(
+ "key_lock",
+ "Key lock",
+ RadioSettingValueList(KEY_LOCK_MODE,
+ current_index=int(memory.general.keylock))
+ )
+ buttons.append(key_lock)
+
+ auto_lock = RadioSetting(
+ "auto_lock",
+ "Auto lock",
+ RadioSettingValueBoolean(memory.general.auto_lock)
+ )
+ buttons.append(auto_lock)
+
+ return buttons
+
+ @staticmethod
+ def startup_settings(memory):
+ """Get startup settings"""
+ startup = RadioSettingGroup("startup", "Start up")
+ device_name = RadioSetting(
+ "device_name",
+ "Device name",
+ RadioSettingValueString(
+ 0,
+ 12,
+ parse_str_from_tk11(memory.general.device_name),
+ autopad=False
+ )
+ )
+ startup.append(device_name)
+
+ start_string_1 = RadioSetting(
+ "start_string_1",
+ "Start string 1",
+ RadioSettingValueString(
+ 0,
+ 16,
+ parse_str_from_tk11(memory.general.logo_string1),
+ autopad=False
+ )
+ )
+ startup.append(start_string_1)
+
+ start_string_2 = RadioSetting(
+ "start_string_2",
+ "Start string 2",
+ RadioSettingValueString(
+ 0,
+ 16,
+ parse_str_from_tk11(memory.general.logo_string2),
+ autopad=False
+ )
+ )
+ startup.append(start_string_2)
+
+ boot_screen = RadioSetting(
+ "boot_screen",
+ "Boot screen",
+ RadioSettingValueList(
+ BOOT_SCREEN_MODE,
+ current_index=int(memory.general.power_on_screen_mode)
+ )
+ )
+ startup.append(boot_screen)
+
+ a_display_index = int(memory.channels_idx.a_id)
+ if a_display_index < CHANNELS_COUNT:
+ a_display_index = A_DISPLAY_SPECIAL_COUNT + a_display_index
+ else:
+ a_display_index = a_display_index - CHANNELS_COUNT
+
+ b_display_index = int(memory.channels_idx.b_id)
+ if b_display_index < CHANNELS_COUNT:
+ b_display_index = B_DISPLAY_SPECIAL_COUNT + b_display_index
+ else:
+ b_display_index = b_display_index - CHANNELS_COUNT
+
+ a_display = RadioSetting(
+ "a_display",
+ "A display",
+ RadioSettingValueList(
+ A_DISPLAY,
+ current_index=a_display_index
+ )
+ )
+ startup.append(a_display)
+
+ b_display = RadioSetting(
+ "b_display",
+ "B display",
+ RadioSettingValueList(
+ B_DISPLAY,
+ current_index=b_display_index
+ )
+ )
+ startup.append(b_display)
+
+ return startup
+
+ @staticmethod
+ def channel_settings(radio, memory):
+ """Get channel settings"""
+ channel = RadioSettingGroup("channel", "Channel")
+
+ main_channel = RadioSetting(
+ "main_channel",
+ "Main channel",
+ RadioSettingValueList(
+ CHANNELS,
+ current_index=int(memory.general.channel_ab)
+ )
+ )
+ channel.append(main_channel)
+
+ a_rx_volume_balance = RadioSetting(
+ "a_rx_volume_balance",
+ "Volume RX balance A",
+ RadioSettingValueList(
+ VOLUME,
+ current_index=int(memory.general.chn_A_volume)
+ )
+ )
+ channel.append(a_rx_volume_balance)
+
+ b_rx_volume_balance = RadioSetting(
+ "b_rx_volume_balance",
+ "Volume RX balance B",
+ RadioSettingValueList(
+ VOLUME,
+ current_index=int(memory.general.chn_B_volume)
+ )
+ )
+ channel.append(b_rx_volume_balance)
+
+ vfo_mode = RadioSetting(
+ "vfo_mode",
+ "VFO Mode",
+ RadioSettingValueBoolean(memory.general.freq_mode)
+ )
+ channel.append(vfo_mode)
+
+ channel_display_mode = RadioSetting(
+ "channel_display_mode",
+ "Channel display mode",
+ RadioSettingValueList(
+ CHANNEL_DISPLAY_MODE,
+ current_index=int(memory.general.channel_display_mode)
+ )
+ )
+ channel.append(channel_display_mode)
+
+ repeater_tail_tone = RadioSetting(
+ "repeater_tail_tone",
+ "Repeater tail tone",
+ RadioSettingValueList(
+ REPEATER_TAIL_TONE,
+ current_index=int(memory.general.repeater_tail)
+ )
+ )
+ channel.append(repeater_tail_tone)
+
+ call_ch = int(memory.general.call_ch)
+ call_channel = RadioSetting(
+ "call_channel",
+ "Call channel",
+ RadioSettingValueList(
+ ["Null"] + radio.get_channels_name(),
+ current_index=0
+ if memory.channels_usage[call_ch].flag > len(TX_FREQUENCIES)
+ else call_ch
+ )
+ )
+ channel.append(call_channel)
+
+ tail_tone = RadioSetting(
+ "tail_tone",
+ "Tail tone",
+ RadioSettingValueBoolean(memory.general.tail_tone)
+ )
+ channel.append(tail_tone)
+
+ dual_receive = RadioSetting(
+ "dual_receive",
+ "Dual receive",
+ RadioSettingValueBoolean(memory.general.dual_watch))
+ channel.append(dual_receive)
+
+ remind_eot = RadioSetting(
+ "remind_eot",
+ "Remind end of talk",
+ RadioSettingValueList(
+ REMIND_END_OF_TALK,
+ current_index=int(memory.general.roger_tone)
+ )
+ )
+ channel.append(remind_eot)
+
+ denoise = RadioSetting(
+ "denoise",
+ "Denoise",
+ RadioSettingValueList(
+ DENOISE,
+ current_index=int(memory.general.denoise_lvl) + 1
+ )
+ )
+ channel.append(denoise)
+
+ transpositional = RadioSetting(
+ "transpositional",
+ "Transpositional",
+ RadioSettingValueList(
+ TRANSPOSITIONAL,
+ current_index=int(memory.general.transpositional_lvl) + 1)
+ )
+ channel.append(transpositional)
+
+ return channel
+
+ @staticmethod
+ def match_frequency_settings(memory):
+ """Get match frequency settings"""
+ match_frequency = RadioSettingGroup("match_frequency",
+ "Match frequency")
+
+ frequency_meter_tot = RadioSetting(
+ "frequency_meter_tot",
+ "Frequency meter tot[s]",
+ RadioSettingValueInteger(8, 32, int(memory.general.match_tot))
+ )
+ match_frequency.append(frequency_meter_tot)
+
+ frequency_meter_mode = RadioSetting(
+ "frequency_meter_mode",
+ "Frequency meter mode",
+ RadioSettingValueList(
+ FREQUENCY_METER_MODES,
+ current_index=int(memory.general.match_qt_mode)
+ )
+ )
+ match_frequency.append(frequency_meter_mode)
+
+ dcs = RadioSetting(
+ "dcs",
+ "DCS",
+ RadioSettingValueList(
+ DCS_MODES,
+ current_index=int(memory.general.match_dcs_bit)
+ )
+ )
+ match_frequency.append(dcs)
+
+ match_threshold = RadioSetting(
+ "match_threshold",
+ "QT threshold",
+ RadioSettingValueInteger(10, 200,
+ int(memory.general.match_threshold))
+ )
+ match_frequency.append(match_threshold)
+
+ return match_frequency
+
+ @staticmethod
+ def fm_settings(memory):
+ """Get FM settings"""
+ fm = RadioSettingGroup("fm", "FM")
+
+ vfo_freq_val = int(memory.fm.vfo_frequency) / 10
+ vfo_frequency = vfo_freq_val if (76 <= vfo_freq_val <= 108) else 76
+
+ vfo = RadioSetting("vfo", "VFO", RadioSettingValueFloat(
+ 76, 108, vfo_frequency, precision=1))
+ fm.append(vfo)
+
+ mode = RadioSetting("mode", "Mode", RadioSettingValueList(
+ ["VFO mode", "MR mode"],
+ current_index=int(memory.fm.memory_vfo_flag)
+ ))
+ fm.append(mode)
+
+ channel = RadioSetting("channel", "Channel", RadioSettingValueList(
+ [str(i) for i in range(1, 33)],
+ current_index=int(memory.fm.channel_id))
+ )
+ fm.append(channel)
+
+ return fm
+
+ @staticmethod
+ def noaa_settings(memory):
+ """Get NOAA settings"""
+ noaa = RadioSettingGroup("noaa", "NOAA")
+
+ noaa_same_decode = RadioSetting(
+ "noaa_same_decode",
+ "NOAA SAME decode",
+ RadioSettingValueList(
+ ["Null", "1050Hz", "SAME decode"],
+ current_index=int(memory.general.noaa_same_decode))
+ )
+ noaa.append(noaa_same_decode)
+
+ noaa_same_event = RadioSetting(
+ "noaa_same_event",
+ "NOAA SAME event",
+ RadioSettingValueList(
+ ["Default", "All open", "All off", "User"],
+ current_index=int(memory.general.noaa_same_event)
+ )
+ )
+ noaa.append(noaa_same_event)
+
+ noaa_same_address = RadioSetting(
+ "noaa_same_address",
+ "NOAA SAME address",
+ RadioSettingValueList(
+ ["Single address", "Multiple address", "Any address"],
+ current_index=int(memory.general.noaa_same_address)
+ )
+ )
+ noaa.append(noaa_same_address)
+
+ noaa_sq = RadioSetting(
+ "noaa_sq",
+ "NOAA SAME address",
+ RadioSettingValueInteger(0, 9, int(memory.general.noaa_sq))
+ )
+ noaa.append(noaa_sq)
+
+ noaa_scan = RadioSetting(
+ "noaa_scan",
+ "NOAA search",
+ RadioSettingValueList(["Manual", "Auto"],
+ current_index=int(memory.general.noaa_scan))
+ )
+ noaa.append(noaa_scan)
+
+ noaa_same_event_control = RadioSettingSubGroup(
+ "noaa_same_event_control", "NOAA SAME event control")
+
+ for i, (code, label) in enumerate(NOAA_SAME_EVENTS):
+ group = RadioSettingSubGroup(f"noaa_same_event_control{i}",
+ f"NOAA message {i}")
+
+ code_value = RadioSettingValueString(0, 3, code)
+ code_value.set_mutable(False)
+
+ group.append(RadioSetting(f"noaa_same_event_control{i}_code",
+ "Code", code_value))
+
+ label_value = RadioSettingValueString(0, 100, label)
+ label_value.set_mutable(False)
+
+ group.append(RadioSetting(f"noaa_same_event_control{i}_label",
+ "Label", label_value))
+
+ checked = bool(memory.noaa_same_events_control[i].value)
+ group.append(RadioSetting(f"noaa_same_event_control{i}_checked",
+ "", RadioSettingValueBoolean(checked)))
+
+ noaa_same_event_control.append(group)
+
+ noaa.append(noaa_same_event_control)
+
+ return noaa
+
+ def get_memory_object(self):
+ """Get memory object"""
+ return self._memobj
+
+ def sync_in(self):
+ """Download radio data"""
+ self._mmap = do_download(self)
+ self.process_mmap()
+
+ def sync_out(self):
+ """Upload radio data"""
+ do_upload(self)
+
+ def process_mmap(self):
+ """Convert the raw byte array into a memory object structure"""
+ self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+
+ def get_raw_memory(self, number):
+ """Return a raw representation of the memory object"""
+ return repr(self._memobj.channels[number - 1])
+
+ def get_memory(self, number):
+ """Extract a high-level memory object from the low-level memory map"""
+ channel = self._memobj.channels[number - 1]
+
+ memory = chirp_common.Memory()
+ memory.number = number
+
+ # Need to also check for channels usage because CPS
+ # doesn't delete memory data
+ # It only set the flag to 0xFF to delete a channel
+ if (channel.rx_freq == 0 or
+ self._memobj.channels_usage[number - 1].flag == 0xFF):
+ memory.empty = True
+ return memory
+
+ try:
+ memory.power = Power(channel.power).level
+ except ValueError:
+ memory.power = Power.HIGH.level
+
+ memory.freq = int(channel.rx_freq) * 10
+ memory.offset = int(channel.freq_diff) * 10
+ memory.name = parse_str_from_tk11(channel.name)
+
+ if channel.mode == Mode.FM.value:
+ if channel.band & 15 == 0:
+ memory.mode = Mode.FM.name
+ elif channel.band & 15 == 1:
+ memory.mode = Mode.NFM.name
+ else:
+ memory.mode = Mode(channel.mode).name
+
+ if memory.offset == 0:
+ memory.duplex = ''
+ else:
+ try:
+ duplex = DUPLEXES[int(channel.freq_dir)]
+ memory.duplex = duplex
+
+ if duplex == '':
+ memory.offset = 0
+ except ValueError:
+ memory.offset = 0
+ memory.duplex = ''
+ LOG.error("Unknown frequency direction %s", channel.freq_dir)
+
+ dcs_values = [QTType.NDCS.value, QTType.IDCS.value]
+ if channel.tx_qt_type == QTType.NONE.value == channel.rx_qt_type:
+ memory.tmode = ""
+ elif (channel.tx_qt_type == QTType.CTCSS.value
+ and channel.rx_qt_type == QTType.NONE.value):
+ memory.tmode = "Tone"
+
+ tx_tone = int(channel.tx_qt) / 10
+ if not is_tone_valid(tx_tone):
+ tx_tone = VALID_TONES[0]
+
+ memory.rtone = tx_tone
+ elif (channel.tx_qt_type == QTType.CTCSS.value
+ and channel.rx_qt_type == QTType.CTCSS.value
+ and channel.tx_qt == channel.rx_qt):
+ memory.tmode = "TSQL"
+
+ tx_tone = int(channel.tx_qt) / 10
+ if not is_tone_valid(tx_tone):
+ tx_tone = VALID_TONES[0]
+
+ memory.ctone = tx_tone
+ memory.rtone = tx_tone
+ elif (channel.tx_qt_type in dcs_values
+ and channel.rx_qt_type in dcs_values
+ and channel.tx_qt == channel.rx_qt):
+ tx_dtcs = int(dtcs_to_chirp(int(channel.tx_qt)))
+
+ tx_polarity = "N" if channel.tx_qt_type == QTType.NDCS.value \
+ else "R"
+ rx_polarity = "N" if channel.rx_qt_type == QTType.NDCS.value \
+ else "R"
+ memory.dtcs_polarity = tx_polarity + rx_polarity
+
+ memory.tmode = "DTCS"
+ memory.dtcs = tx_dtcs
+ else:
+ tx_mode = ""
+ rx_mode = ""
+
+ tx_polarity = "N"
+ rx_polarity = "N"
+
+ if channel.tx_qt_type == QTType.CTCSS.value:
+ tx_mode = "Tone"
+
+ tx_tone = int(channel.tx_qt) / 10
+ if not is_tone_valid(tx_tone):
+ tx_tone = VALID_TONES[0]
+
+ memory.rtone = tx_tone
+ elif channel.tx_qt_type in dcs_values:
+ tx_mode = "DTCS"
+ tx_polarity = "N" if channel.tx_qt_type == QTType.NDCS.value \
+ else "R"
+ memory.dtcs = int(dtcs_to_chirp(int(channel.tx_qt)))
+
+ if channel.rx_qt_type == QTType.CTCSS.value:
+ rx_mode = "Tone"
+
+ rx_tone = int(channel.rx_qt) / 10
+ if not is_tone_valid(rx_tone):
+ rx_tone = VALID_TONES[0]
+
+ memory.ctone = rx_tone
+ elif channel.rx_qt_type in dcs_values:
+ rx_mode = "DTCS"
+ rx_polarity = "N" if channel.rx_qt_type == QTType.NDCS.value \
+ else "R"
+ memory.rx_dtcs = int(dtcs_to_chirp(int(channel.rx_qt)))
+
+ memory.tmode = "Cross"
+
+ memory.cross_mode = f"{tx_mode}->{rx_mode}"
+ memory.dtcs_polarity = tx_polarity + rx_polarity
+
+ memory.extra = RadioSettingGroup("Extra", "extra")
+
+ msw = RadioSetting("msw", "MSW", RadioSettingValueList(
+ MSW_LIST, current_index=int(channel.band >> 4)))
+ memory.extra.append(msw)
+
+ squelch = RadioSetting("squelch", "Squelch", RadioSettingValueList(
+ SQUELCH_LIST, current_index=int(channel.sq)))
+ memory.extra.append(squelch)
+
+ scan_list = RadioSetting(
+ "scan_list",
+ "Scan List",
+ RadioSettingValueList(AVAILABLE_SCAN_LIST,
+ current_index=int(channel.scan_list) + 1
+ if channel.scan_list != 0xFF else 0)
+ )
+ memory.extra.append(scan_list)
+
+ encrypt = RadioSetting("encrypt", "Encrypt", RadioSettingValueList(
+ ENCRYPT_LIST, current_index=int(channel.encrypt))
+ )
+ memory.extra.append(encrypt)
+
+ busy_lock = RadioSetting("busy_lock", "Busy lock",
+ RadioSettingValueBoolean(bool(channel.busy)))
+ memory.extra.append(busy_lock)
+
+ signaling_decode = RadioSetting("signaling_decode", "Signaling decode",
+ RadioSettingValueBoolean(
+ bool(channel.dtmf_decode_flag))
+ )
+ memory.extra.append(signaling_decode)
+
+ signal = RadioSetting("signal", "Signal", RadioSettingValueList(
+ SIGNAL_MODE, current_index=int(channel.signal)))
+ memory.extra.append(signal)
+
+ rs = RadioSetting("ptt_id", "PTT ID", RadioSettingValueList(
+ PTT_ID_MODES, current_index=int(channel.ptt_id)))
+ memory.extra.append(rs)
+
+ return memory
+
+ def set_memory(self, memory):
+ """Store details about a high-level memory to the memory map"""
+ chan_index = memory.number - 1
+
+ self._memobj.channels_usage[chan_index].flag = (
+ get_channel_frequency_range(int(memory.freq)))
+
+ channel = self._memobj.channels[chan_index]
+
+ if memory.empty:
+ channel.fill_raw(b"\x00")
+ return
+
+ channel.rx_freq = memory.freq // 10
+
+ is_mode_nfm = memory.mode == Mode.NFM.name
+
+ # 0 = 25K
+ # 1 = 12.5K
+ band_index = 1 if is_mode_nfm else 0
+ msw_index = int(self.get_extra_or_default(memory, "msw", 0))
+
+ channel.mode = Mode.FM.value if is_mode_nfm \
+ else Mode[memory.mode].value
+
+ channel.band = band_index | (msw_index << 4)
+
+ if memory.power is None:
+ channel.power = Power.LOW.level
+ else:
+ channel.power = Power[str(memory.power).upper()].value
+
+ if memory.name is not None:
+ channel.name = parse_str_to_tk11(memory.name, 16)
+
+ match memory.duplex:
+ case '':
+ channel.freq_dir = 0
+ channel.freq_diff = 0
+ case '+':
+ channel.freq_dir = 1
+ channel.freq_diff = int(memory.offset / 10)
+ case '-':
+ channel.freq_dir = 2
+ channel.freq_diff = int(memory.offset / 10)
+
+ scan_list = int(self.get_extra_or_default(memory, "scan_list", "0"))
+
+ channel.scan_list = 0xFF if scan_list == 0 else scan_list - 1
+ channel.encrypt = int(self.get_extra_or_default(memory, "encrypt", 0))
+ channel.sq = int(self.get_extra_or_default(memory, "squelch", 4))
+ channel.busy = int(self.get_extra_or_default(memory, "busy_lock", 0))
+ channel.dtmf_decode_flag = (
+ int(self.get_extra_or_default(memory, "signaling_decode", 0)))
+ channel.signal = int(self.get_extra_or_default(memory, "signal", 0))
+ channel.ptt_id = int(self.get_extra_or_default(memory, "ptt_id", 0))
+
+ match memory.tmode:
+ case "":
+ channel.tx_qt_type = QTType.NONE.value
+ channel.tx_qt = 0
+
+ channel.rx_qt_type = QTType.NONE.value
+ channel.rx_qt = 0
+ case "Tone":
+ channel.tx_qt_type = QTType.CTCSS.value
+ channel.tx_qt = int(memory.rtone * 10)
+
+ channel.rx_qt_type = QTType.NONE.value
+ channel.rx_qt = 0
+ case "TSQL":
+ tone = int(memory.ctone * 10)
+
+ channel.tx_qt_type = QTType.CTCSS.value
+ channel.tx_qt = tone
+
+ channel.rx_qt_type = QTType.CTCSS.value
+ channel.rx_qt = tone
+ case "DTCS":
+ tx_polarity = memory.dtcs_polarity[0].upper()
+ rx_polarity = memory.dtcs_polarity[1].upper()
+
+ channel.tx_qt_type = get_dcs_from_polarity(tx_polarity)
+ channel.rx_qt_type = get_dcs_from_polarity(rx_polarity)
+
+ channel.tx_qt = dtcs_to_tk11(memory.dtcs)
+ channel.rx_qt = dtcs_to_tk11(memory.dtcs)
+ case "Cross":
+ tx_mode, rx_mode = memory.cross_mode.split("->", 1)
+
+ if tx_mode == "Tone":
+ channel.tx_qt_type = QTType.CTCSS.value
+ channel.tx_qt = int(memory.rtone * 10)
+ elif tx_mode == "DTCS":
+ tx_polarity = memory.dtcs_polarity[0].upper()
+ channel.tx_qt_type = get_dcs_from_polarity(tx_polarity)
+ channel.tx_qt = dtcs_to_tk11(memory.dtcs)
+
+ if rx_mode == "Tone":
+ channel.rx_qt_type = QTType.CTCSS.value
+ channel.rx_qt = int(memory.ctone * 10)
+ elif rx_mode == "DTCS":
+ rx_polarity = memory.dtcs_polarity[1].upper()
+ channel.rx_qt_type = get_dcs_from_polarity(rx_polarity)
+ channel.rx_qt = dtcs_to_tk11(memory.rx_dtcs)
+
+ @staticmethod
+ def get_extra_or_default(memory, key, default):
+ """Get extra value or default value"""
+ if key in memory.extra and memory.extra[key] is not None:
+ return memory.extra[key].value
+
+ return default
diff --git a/chirp/drivers/tk270.py b/chirp/drivers/tk270.py
index c4b664f..b13d0b9 100644
--- a/chirp/drivers/tk270.py
+++ b/chirp/drivers/tk270.py
@@ -166,6 +166,8 @@ def handshake(radio, msg="", full=False):
# receive ACK
ack = rawrecv(radio, 1)
# check ACK
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != ACK_CMD:
# close_radio(radio)
mesg = "Handshake failed: " + msg
@@ -377,6 +379,8 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa
def sync_out(self):
"""Upload to radio"""
# Get the data ready for upload
+ if self._memobj is None:
+ self.process_mmap()
try:
self._prep_data()
except Exception as e:
@@ -645,11 +649,7 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa
self.encode_tone(_mem.tx_tone, txmode, txtone, txpol)
self.encode_tone(_mem.rx_tone, rxmode, rxtone, rxpol)
- # power, default power is high, as the low is configurable via a key
- if mem.power is None:
- mem.power = POWER_LEVELS[1]
-
- _mem.power = POWER_LEVELS.index(mem.power)
+ _mem.power = POWER_LEVELS.index(mem.power or POWER_LEVELS[1])
# skip
self.set_scan(mem.number - 1, mem.skip)
diff --git a/chirp/drivers/tk280.py b/chirp/drivers/tk280.py
index 1221cb6..a744d3c 100644
--- a/chirp/drivers/tk280.py
+++ b/chirp/drivers/tk280.py
@@ -15,12 +15,14 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import collections
+import abc
import itertools
import logging
import struct
import time
from chirp import chirp_common, directory, memmap, errors, util, bitwise
+from chirp import checksum
from chirp.settings import RadioSettingGroup, RadioSetting, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueString, RadioSettingValueInteger, \
@@ -625,14 +627,6 @@ def _close_radio(radio):
LOG.error('Failed to close radio: %s' % e)
-def _checksum(data):
- """the radio block checksum algorithm"""
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
def _make_frame(cmd, addr):
"""Pack the info in the format it likes"""
return struct.pack(">BH", cmd[0], addr)
@@ -664,6 +658,8 @@ def _open_radio(radio, status):
else:
break
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != ACK_CMD:
raise errors.RadioError('Failed to put radio into programming mode')
@@ -719,10 +715,10 @@ def read_block(pipe):
block = b'\xFF' * BLOCK_SIZE
else:
block = pipe.read(BLOCK_SIZE)
- checksum = pipe.read(1)
- calc = _checksum(block)
- if calc != checksum[0] and cmd != b'Z':
- LOG.debug('Checksum %i does not match %i', calc, checksum[0])
+ cs = pipe.read(1)
+ calc = checksum.checksum_8bit(block)
+ if calc != cs[0] and cmd != b'Z':
+ LOG.debug('Checksum %i does not match %i', calc, cs[0])
raise errors.RadioError('Checksum reading block from radio')
exchange_ack(pipe)
return block
@@ -769,7 +765,7 @@ def do_upload(radio):
if data == EMPTY_BLOCK:
frame = _make_frame(b'Z', block) + b'\xFF'
else:
- cs = _checksum(data)
+ cs = checksum.checksum_8bit(data)
frame = _make_frame(b'W', block) + data + bytes([cs])
radio.pipe.write(frame)
try:
@@ -781,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/tk690.py b/chirp/drivers/tk690.py
index a248f41..df40541 100644
--- a/chirp/drivers/tk690.py
+++ b/chirp/drivers/tk690.py
@@ -22,6 +22,7 @@ import logging
import struct
from chirp import chirp_common, directory, memmap, errors, util, bitwise
+from chirp import checksum
from chirp.settings import RadioSettingGroup, RadioSetting, RadioSettings, \
RadioSettingValueBoolean, RadioSettingValueList, RadioSettingValueString, \
RadioSettingValueMap, RadioSettingValueInteger
@@ -211,14 +212,6 @@ def _close_radio(radio):
raise errors.RadioError("Serial Connection Error while closing radio")
-def _checksum(data):
- """the radio block checksum algorithm"""
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
def _make_framel(cmd, addr):
"""Pack the info in the format it likes"""
# x52 x0F (x0380-x0400)
@@ -262,7 +255,7 @@ def _recvl(radio):
# Data block is W + Data(128) + CS
rcs = rxdata[-1]
data = rxdata[1:-1]
- ccs = _checksum(data)
+ ccs = checksum.checksum_8bit(data)
if rcs != ccs:
msg = "Block Checksum Error! real %02x, calculated %02x" % \
@@ -311,9 +304,10 @@ def _open_radio(radio):
ack = radio.pipe.read(10)
if ack == ACK_CMD:
pass
- elif ack.endswith(b'\xb5\x15\xc5m\xf5\x95\x01') or ack == b'':
- raise errors.RadioError("No response response from radio,"
- " Is it connected and powered on?")
+ elif ack == b'':
+ raise errors.RadioNoResponse()
+ elif ack.endswith(b'\xb5\x15\xc5m\xf5\x95\x01'):
+ raise errors.RadioError('Unexpected response from radio')
else:
raise errors.RadioError("Radio didn't acknowledge program mode.")
@@ -422,7 +416,7 @@ def do_upload(radio):
short = True
else:
# normal
- cs = _checksum(data)
+ cs = checksum.checksum_8bit(data)
sdata = _make_framel(b"W", addr) + data + bytes([cs])
radio.pipe.write(sdata)
diff --git a/chirp/drivers/tk760.py b/chirp/drivers/tk760.py
index 50b1601..69c73fe 100644
--- a/chirp/drivers/tk760.py
+++ b/chirp/drivers/tk760.py
@@ -214,8 +214,10 @@ def open_radio(radio):
# in between the flush and the start of the magic. Consider it successful
# if we see ACK anywhere in the response
resp = rawrecv(radio, 256)
+ if not resp:
+ raise errors.RadioNoResponse()
if ACK_CMD not in resp:
- raise errors.RadioError('Radio did not respond to program mode')
+ raise errors.RadioError('Unexpected response to program mode')
# 0x02 Means "show me your ident"
rawsend(radio, b"\x02")
@@ -387,6 +389,8 @@ class Kenwood_M60_Radio(chirp_common.CloneModeRadio,
"""Download from radio"""
try:
self._mmap = do_download(self)
+ except errors.RadioError:
+ raise
except Exception as e:
LOG.exception('Failed to download: %s', e)
rawsend(self, b'E')
@@ -405,6 +409,8 @@ class Kenwood_M60_Radio(chirp_common.CloneModeRadio,
# do the upload
try:
do_upload(self)
+ except errors.RadioError:
+ raise
except Exception as e:
LOG.exception('Failed to upload: %s', e)
rawsend(self, b'E')
@@ -644,11 +650,7 @@ class Kenwood_M60_Radio(chirp_common.CloneModeRadio,
self.encode_tone(_tone.tx_tone, txmode, txtone, txpol)
self.encode_tone(_tone.rx_tone, rxmode, rxtone, rxpol)
- # power, default power is low
- if mem.power is None:
- mem.power = POWER_LEVELS[0]
-
- _ch.power = POWER_LEVELS.index(mem.power)
+ _ch.power = POWER_LEVELS.index(mem.power or POWER_LEVELS[0])
# wide/marrow
_ch.wide = MODES.index(mem.mode)
diff --git a/chirp/drivers/tk760g.py b/chirp/drivers/tk760g.py
index 66380d1..c61c9c5 100644
--- a/chirp/drivers/tk760g.py
+++ b/chirp/drivers/tk760g.py
@@ -18,6 +18,7 @@ import struct
import time
from chirp import chirp_common, directory, memmap, errors, util, bitwise
+from chirp import checksum
from chirp.settings import RadioSettingGroup, RadioSetting, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueString, RadioSettingValueInteger, \
@@ -362,14 +363,6 @@ def _close_radio(radio):
_raw_send(radio, b"E")
-def _checksum(data):
- """the radio block checksum algorithm"""
- cs = 0
- for byte in data:
- cs += byte
- return cs % 256
-
-
def _make_frame(cmd, addr):
"""Pack the info in the format it likes"""
return struct.pack(">BH", ord(cmd), addr)
@@ -417,7 +410,7 @@ def _recv(radio):
# when the RX block has two bytes and the first is \x5A
# then the block is all \xFF
if not cmd:
- raise errors.RadioError('No response from radio')
+ raise errors.RadioNoResponse()
elif cmd == b'Z':
# Empty "zero" block
_raw_recv(radio, 1)
@@ -432,7 +425,7 @@ def _recv(radio):
rxdata = _raw_recv(radio, BLOCK_SIZE + 1)
rcs = rxdata[-1]
data = rxdata[:-1]
- ccs = _checksum(data)
+ ccs = checksum.checksum_8bit(data)
if rcs != ccs:
_close_radio(radio)
@@ -462,6 +455,9 @@ def _open_radio(radio, status):
_raw_send(radio, b"PROGRAM")
ack = _raw_recv(radio, 1)
+ if not ack:
+ _close_radio(radio)
+ raise errors.RadioNoResponse()
if ack != ACK_CMD:
_close_radio(radio)
LOG.debug("Radio did not accept PROGRAM command")
@@ -584,7 +580,7 @@ def do_upload(radio):
if data == EMPTY_BLOCK:
frame = _make_frame(b"Z", addr) + b"\xFF"
else:
- cs = _checksum(data)
+ cs = checksum.checksum_8bit(data)
frame = _make_frame(b"W", addr) + data + bytes([cs])
_raw_send(radio, frame)
@@ -859,6 +855,8 @@ class Kenwood_Series_60G(chirp_common.CloneModeRadio,
# chirp signature on the eprom ;-)
sign = b"Chirp"
self._fill(0xbb, sign)
+ if self._memobj is None:
+ self.process_mmap()
try:
self._prep_data()
@@ -1073,12 +1071,7 @@ class Kenwood_Series_60G(chirp_common.CloneModeRadio,
except IndexError:
_mem.name[i] = "\x20"
- # power
- # default power is low
- if mem.power is None:
- mem.power = POWER_LEVELS[0]
-
- _mem.power = POWER_LEVELS.index(mem.power)
+ _mem.power = POWER_LEVELS.index(mem.power or POWER_LEVELS[0])
# wide/marrow
_mem.wide = MODES.index(mem.mode)
@@ -1593,20 +1586,20 @@ class TK378G_Radios(Kenwood_Series_60G):
@directory.register
class TK372G_Radios(Kenwood_Series_60G):
- """Kenwood TK-372 Radio [K/E/M/NE]"""
+ """Kenwood TK-372G Radio [K/K2/K3/K4]"""
MODEL = "TK-372G"
TYPE = b"P3720"
VARIANTS = {
- b"P3720\x06\xff": (32, 450, 470, "K"),
- b"P3720\x07\xff": (32, 470, 490, "K1"),
- b"P3720\x08\xff": (32, 490, 512, "K2"),
- b"P3720\x09\xff": (32, 403, 430, "K3")
+ b"P3720\x06\xfb": (32, 450, 470, "K"),
+ b"P3720\x07\xfb": (32, 470, 490, "K2"),
+ b"P3720\x08\xfb": (32, 490, 512, "K3"),
+ b"P3720\x09\xfb": (32, 403, 430, "K4")
}
@directory.register
class TK370G_Radios(Kenwood_Series_60G):
- """Kenwood TK-370 Radio [K/E/M/NE]"""
+ """Kenwood TK-370G Radio [K/E/M/NE]"""
MODEL = "TK-370G"
TYPE = b"P3700"
VARIANTS = {
diff --git a/chirp/drivers/tk8102.py b/chirp/drivers/tk8102.py
index 575b289..60272dc 100644
--- a/chirp/drivers/tk8102.py
+++ b/chirp/drivers/tk8102.py
@@ -18,6 +18,7 @@ import struct
from chirp import chirp_common, directory, memmap, errors, util
from chirp import bitwise
+from chirp import kenwood_tone
from chirp.settings import RadioSettingGroup, RadioSetting
from chirp.settings import RadioSettingValueBoolean, RadioSettingValueList
from chirp.settings import RadioSettingValueString, RadioSettings
@@ -29,8 +30,8 @@ MEM_FORMAT = """
struct {
lbcd rx_freq[4];
lbcd tx_freq[4];
- ul16 rx_tone;
- ul16 tx_tone;
+ ul16 rxtone;
+ ul16 txtone;
u8 signaling:2,
unknown1:3,
bcl:1,
@@ -200,6 +201,8 @@ class KenwoodTKx102Radio(chirp_common.CloneModeRadio):
BAUD_RATE = 9600
_memsize = 0x410
+ _tone_model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x2800, pol_mask=0x8000, tone_init=0xFFFF, tone_flag=0x0000)
def get_features(self):
rf = chirp_common.RadioFeatures()
@@ -250,45 +253,6 @@ class KenwoodTKx102Radio(chirp_common.CloneModeRadio):
def get_raw_memory(self, number):
return repr(self._memobj.memory[number - 1])
- def _get_tone(self, _mem, mem):
- def _get_dcs(val):
- code = int("%03o" % (val & 0x07FF))
- pol = (val & 0x8000) and "R" or "N"
- return code, pol
-
- if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
- tcode, tpol = _get_dcs(_mem.tx_tone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.tx_tone != 0xFFFF:
- mem.rtone = _mem.tx_tone / 10.0
- txmode = "Tone"
- else:
- txmode = ""
-
- if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
- rcode, rpol = _get_dcs(_mem.rx_tone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rx_tone != 0xFFFF:
- mem.ctone = _mem.rx_tone / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- if mem.tmode == "DTCS":
- mem.dtcs_polarity = "%s%s" % (tpol, rpol)
-
def get_memory(self, number):
_mem = self._memobj.memory[number - 1]
@@ -310,7 +274,7 @@ class KenwoodTKx102Radio(chirp_common.CloneModeRadio):
else:
mem.offset = 0
- self._get_tone(_mem, mem)
+ self._tone_model.get_tone(_mem, mem)
mem.power = POWER_LEVELS[_mem.highpower]
mem.mode = MODES[_mem.wide]
mem.skip = not _mem.scan and "S" or ""
@@ -338,44 +302,6 @@ class KenwoodTKx102Radio(chirp_common.CloneModeRadio):
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- val = int("%i" % code, 8) + 0x2800
- if pol == "R":
- val += 0xA000
- return val
-
- rx_mode = tx_mode = None
- rx_tone = tx_tone = 0xFFFF
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- tx_tone = int(mem.rtone * 10)
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rx_tone = tx_tone = int(mem.ctone * 10)
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- tx_tone = int(mem.rtone * 10)
- if rx_mode == "DTCS":
- rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rx_tone = int(mem.ctone * 10)
-
- _mem.rx_tone = rx_tone
- _mem.tx_tone = tx_tone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
-
def set_memory(self, mem):
_mem = self._memobj.memory[mem.number - 1]
@@ -393,7 +319,7 @@ class KenwoodTKx102Radio(chirp_common.CloneModeRadio):
else:
_mem.tx_freq = mem.freq / 10
- self._set_tone(mem, _mem)
+ self._tone_model.set_tone(mem, _mem)
_mem.highpower = mem.power == POWER_LEVELS[1]
_mem.wide = mem.mode == "FM"
diff --git a/chirp/drivers/tk8160.py b/chirp/drivers/tk8160.py
index 879df69..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;
@@ -127,14 +127,14 @@ _KEYS = [
'Key Lock',
'Talk Around',
'Scan',
- 'Scan Add',
- '?',
+ 'Scan Del/Add',
+ 'Emergency',
'AUX',
'Horn Alert',
'Scrambler',
'Display Character',
'OST',
- '?', # 0D
+ 'Direct Ch', # 0D
'?', # 0E
'?', # 0F
'?', # 10
@@ -145,14 +145,14 @@ _KEYS = [
'2-Tone',
'Call 1',
'Call 2',
- 'Selcall',
+ '?', # 18
'Public Address',
'Squelch Level',
- '?',
+ 'Selcall', # 1B
'Status',
'Selcall+Status',
'?', # 1E
- '?', # 1F
+ 'Channel Entry', # 1F
'?', # 20
'?', # 21
'?', # 22
@@ -164,26 +164,69 @@ _KEYS = [
'Volume Up',
'Volume Down',
'None',
- ]
+]
+
+VALID_KEY_SELECTION = [
+ 'Zone Up',
+ 'Zone Down',
+ 'Monitor',
+ 'Key Lock',
+ 'Talk Around',
+ 'Scan',
+ 'Scan Del/Add',
+ 'AUX',
+ 'Horn Alert',
+ 'Scrambler',
+ 'Display Character',
+ 'OST',
+ 'Channel Up',
+ 'Channel Down',
+ 'Brightness',
+ '2-Tone',
+ 'Call 1',
+ 'Call 2',
+ 'Selcall',
+ 'Public Address',
+ 'Squelch Level',
+ 'Status',
+ 'Selcall+Status',
+ 'Squelch Off',
+ 'Monitor Momentary',
+ 'Squelch Off Momentary',
+ 'Send the GPS',
+ 'Volume Up',
+ 'Volume Down',
+ 'None',
+]
-KEYS = {i: key for i, key in enumerate(_KEYS)
- if not key.startswith('?')}
+KEYS = {i: key for i, key in enumerate(_KEYS) if key in VALID_KEY_SELECTION}
KEY_NAMES = {
+ 'Left Up': 'leftup',
+ 'Left Down': 'leftdn',
+ 'Right Up': 'rightup',
+ 'Right Down': 'rightdn',
+ 'S': 'skey',
'A': 'akey',
'B': 'bkey',
'C': 'ckey',
- 'S': 'skey',
'Triangle': 'triangle',
- 'Right Up': 'rightup',
- 'Right Down': 'rightdn',
- 'Left Up': 'leftup',
- 'Left Down': 'leftdn',
}
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)
@@ -258,21 +301,28 @@ 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):
VENDOR = 'Kenwood'
FORMATS = [directory.register_format('Kenwood KPG-99D', '*.dat')]
_memsize = 0x4000
+ _channels = 128
+ _power_levels = POWER_LEVELS
+ _has_zones = True
+ _has_memory_extras = True
+ _mem_format = mem_format
def sync_in(self):
try:
@@ -286,7 +336,7 @@ class TKx160Radio(chirp_common.CloneModeRadio):
def sync_out(self):
try:
- self._mmap = do_upload(self)
+ do_upload(self)
except errors.RadioError:
raise
except Exception as e:
@@ -294,7 +344,10 @@ class TKx160Radio(chirp_common.CloneModeRadio):
raise errors.RadioError('Failed to communicate with radio')
def process_mmap(self):
- self._memobj = bitwise.parse(mem_format, self._mmap)
+ self._memobj = bitwise.parse(self._mem_format, self._mmap)
+
+ if not self._has_zones:
+ self._zone = 1
@classmethod
def match_model(cls, filedata, filename):
@@ -303,11 +356,11 @@ class TKx160Radio(chirp_common.CloneModeRadio):
def get_features(self):
rf = chirp_common.RadioFeatures()
- rf.memory_bounds = (1, 128)
+ rf.memory_bounds = (1, self._channels)
rf.has_ctone = True
rf.has_cross = True
rf.has_bank = False
- rf.has_sub_devices = not self.VARIANT
+ rf.has_sub_devices = not self.VARIANT and self._has_zones
rf.has_dynamic_subdevices = rf.has_sub_devices
rf.has_tuning_step = False
rf.has_rx_dtcs = True
@@ -323,7 +376,7 @@ class TKx160Radio(chirp_common.CloneModeRadio):
rf.valid_bands = self.VALID_BANDS
rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC
rf.valid_name_length = 8
- rf.valid_power_levels = list(reversed(POWER_LEVELS))
+ rf.valid_power_levels = list(reversed(self._power_levels))
rf.valid_skips = ['', 'S']
return rf
@@ -511,12 +564,54 @@ class TKx160Radio(chirp_common.CloneModeRadio):
chirp_common.split_tone_decode(m, txtone, rxtone)
m.name = str(_mem.name).rstrip()
- m.power = POWER_LEVELS[int(_mem.highpower)]
+ m.power = self._power_levels[int(_mem.highpower)]
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:
@@ -524,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]
@@ -556,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
@@ -578,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()}
@@ -667,3 +769,132 @@ class TK8160RadioM(TKx160Radio):
MODEL = 'TK-8160M'
VALID_BANDS = [(400000000, 520000000)]
_model = b'M67- D'
+
+
+mem_format_7162 = mem_format + """
+
+#seekto 0x17e5;
+struct {
+ u8 tot;
+ u8 tot_pre;
+ u8 tot_rekey;
+ u8 tot_reset;
+ u8 sql;
+} settings;
+"""
+
+_POWER_LEVELS_7162 = [
+ chirp_common.PowerLevel('Low', watts=5),
+ chirp_common.PowerLevel('High', watts=25),
+]
+VALID_KEY_SELECTION_7162 = [
+ 'None', 'Monitor', 'Key Lock', 'Talk Around', 'Scan', 'Scan Del/Add',
+ 'AUX', 'Horn Alert', 'Scrambler', 'Direct Ch', 'Channel Up',
+ 'Channel Down', 'Call 1', 'Call 2', 'Loan Worker', 'Squelch Level',
+ 'Channel Entry', 'Squelch Off', 'Monitor Momentary',
+ 'Squelch Off Momentary', 'Volume Up', 'Volume Down',
+]
+VALID_KEY_SELECTION_7162_TRIANGLE = VALID_KEY_SELECTION_7162 + ['Emergency']
+KEYS_7162 = {
+ i: key
+ for i, key in enumerate(_KEYS)
+ if key in VALID_KEY_SELECTION_7162_TRIANGLE
+}
+
+
+@directory.register
+class TK7162Radio(TKx160Radio):
+ FORMATS = [directory.register_format('Kenwood KPG-99D(E)', '*.dat')]
+ MODEL = 'TK-7162'
+ VALID_BANDS = [(136000000, 174000000)]
+ _model = b'M7162\x00'
+ _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:
+ _settings = self._memobj.settings
+ _keys = self._memobj.keys
+
+ keys = settings.RadioSettingGroup('keys', 'Keys')
+
+ SEL_ID_LOOKUP = {
+ n: i for i, n in enumerate(VALID_KEY_SELECTION_7162_TRIANGLE)}
+
+ for desc, name in KEY_NAMES.items():
+ # radio_idx -> key_name -> sel_idx
+ options = (VALID_KEY_SELECTION_7162_TRIANGLE if name == "triangle"
+ else VALID_KEY_SELECTION_7162)
+
+ keys.append(settings.RadioSetting(
+ name, desc, settings.RadioSettingValueList(
+ options=options,
+ current_index=SEL_ID_LOOKUP[
+ KEYS_7162[int(getattr(_keys, name))]])))
+
+ # General settings
+ gen = settings.RadioSettingGroup('general', 'General Settings')
+
+ gen.append(settings.RadioSetting(
+ 'tot', 'Time Out Timer (s)',
+ settings.RadioSettingValueList(
+ options=[str(t * 15) for t in range(1, 41)]
+ + [str(600 + t * 60) for t in range(1, 11)],
+ current_index=_settings.tot)))
+
+ gen.append(settings.RadioSetting(
+ 'tot_pre', 'TOT Pre-alert (s)',
+ settings.RadioSettingValueList(
+ options=['OFF'] + [str(t) for t in range(1, 11)],
+ current_index=_settings.tot_pre)))
+
+ gen.append(settings.RadioSetting(
+ 'tot_rekey', 'TOT Rekey Time (s)',
+ settings.RadioSettingValueList(
+ options=['OFF'] + [str(t) for t in range(1, 61)],
+ current_index=_settings.tot_rekey)))
+
+ gen.append(settings.RadioSetting(
+ 'tot_reset',
+ 'TOT Reset Time (s)',
+ settings.RadioSettingValueList(
+ options=['OFF'] + [str(t) for t in range(1, 16)],
+ current_index=_settings.tot_reset)))
+
+ gen.append(settings.RadioSetting(
+ 'sql',
+ 'Squelch Level',
+ settings.RadioSettingValueInteger(
+ minval=0,
+ maxval=9,
+ current=_settings.sql)))
+
+ return settings.RadioSettings(gen, keys)
+
+ def set_settings(self, _settings):
+ settings_map = {
+ "general": self._memobj.settings,
+ "keys": self._memobj.keys,
+ }
+
+ SEL_ID = {
+ i: n for i, n in enumerate(VALID_KEY_SELECTION_7162_TRIANGLE)
+ }
+ KEYS_7162_LOOKUP = {
+ n: i for i, n in KEYS_7162.items()
+ }
+
+ for group in _settings:
+ group_name = group.get_name()
+ _mem = settings_map[group_name]
+
+ if group_name == "keys":
+ for element in group:
+ # sel_idx -> key_name -> radio_idx
+ setattr(_mem, element.get_name(),
+ KEYS_7162_LOOKUP[SEL_ID[int(element.value)]])
+ else:
+ for element in group:
+ setattr(_mem, element.get_name(), int(element.value))
diff --git a/chirp/drivers/tk8180.py b/chirp/drivers/tk8180.py
index d644933..0805a23 100644
--- a/chirp/drivers/tk8180.py
+++ b/chirp/drivers/tk8180.py
@@ -13,12 +13,14 @@
# 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 enum
+import abc
import struct
import time
import logging
from collections import OrderedDict
-from chirp import chirp_common, directory, memmap, errors, util
+from chirp import chirp_common, directory, memmap, errors, util, checksum
from chirp import bitwise
from chirp.drivers import tk280
from chirp.settings import MemSetting, RadioSettingValueInvertedBoolean
@@ -138,8 +140,8 @@ u8 keypad_type; // ff=none 30=12-key
u8 keypad_op;
u8 lsk_unknown1:5,
list_selector_key:1,
- lsk_unknown2:3;
-#seekto 0x05C0;
+ lsk_unknown2:2;
+#seekto 0x05B0;
// side1 primary 0x5C0
// S 0x5C8
// A 0x5D0
@@ -158,9 +160,12 @@ u8 lsk_unknown1:5,
struct button {
u8 primary;
u8 secondary;
- u8 unknown[6]; // These all change for some of the more advanced ones
+ u8 hold;
+ u8 primary_alt; // primary code when primary is 0xFF
+ ul16 holdtime;
+ ul16 alwaysff;
};
-struct button buttons[26];
+struct button buttons[28];
#seekto 0x0A00;
ul16 zone_starts[128];
@@ -168,7 +173,7 @@ ul16 zone_starts[128];
struct zoneinfo {
u8 number;
u8 zonetype;
- u8 unknown1[2];
+ ul16 flagoffset;
u8 count;
char name[12];
u8 unknown2[2];
@@ -205,8 +210,8 @@ struct memory {
u8 unknown4;
};
-#seekto 0xC570; // Fixme
-u8 skipflags[64];
+#seekto 0xC570;
+lbit skipflags[512];
"""
@@ -218,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)])
@@ -229,7 +237,8 @@ MIN_VOL_PRESET = {'Preset': 0x30,
'Lowest Limit': 0x31}
MIN_VOL_PRESET_REV = {v: k for k, v in MIN_VOL_PRESET.items()}
-SUBLCD = ['Zone Number', 'CH/GID Number', 'OSD List Number']
+SUBLCD = ['Zone Number', 'CH/GID Number', 'OSD List Number',
+ 'Signal Strength Indicator']
CLOCKFMT = ['12H', '24H']
DATEFMT = ['Day/Month', 'Month/Day']
MICSENSE = ['On']
@@ -258,33 +267,41 @@ BATTWARN_SETTINGS = {
'Always with Beep': 0x32,
}
# The buttons in memory are not logically arranged for display and sorting
-# would do weird things, so map them manually here
+# would do weird things, so map them manually here. Most of the buttons are
+# the same between portable and mobile. The model-specific ones are below.
BUTTONS = {
- 'Side 1 / Triangle': 0,
- 'Side 2': 5,
- 'S': 1,
- 'A': 2,
- 'B': 3,
- 'C': 4,
- # Skip 2
- 'Top Aux': 8,
- 'DTMF 0': 9,
- 'DTMF 1': 10,
- 'DTMF 2': 11,
- 'DTMF 3': 12,
- 'DTMF 4': 13,
- 'DTMF 5': 14,
- 'DTMF 6': 15,
- 'DTMF 7': 16,
- 'DTMF 8': 17,
- 'DTMF 9': 18,
- 'DTMF *': 19,
- 'DTMF #': 20,
- 'Mic PF1': 24,
- 'Mic PF2': 25,
+ 'S': 3,
+ 'A': 4,
+ 'B': 5,
+ 'C': 6,
+ 'DTMF #': 22,
+ 'DTMF *': 21,
+ 'DTMF 0': 11,
+ 'DTMF 1': 12,
+ 'DTMF 2': 13,
+ 'DTMF 3': 14,
+ 'DTMF 4': 15,
+ 'DTMF 5': 16,
+ 'DTMF 6': 17,
+ 'DTMF 7': 18,
+ 'DTMF 8': 19,
+ 'DTMF 9': 20,
+}
+BUTTONS_PORTABLE = {
+ 'Side 1': 2,
+ 'Side 2': 7,
+ 'Top Aux': 10,
+ 'Mic PF1': 26,
+ 'Mic PF2': 27,
+}
+BUTTONS_MOBILE = {
+ 'Left Arrow Up': 0,
+ 'Left Arrow Down': 1,
+ 'Triangle': 2,
+ 'Square': 7,
+ 'Right Up Arrow': 8,
+ 'Right Down Arrow': 9,
}
-# IDs of the buttons that can only be primary
-PRIMARY_ONLY = [0x0E, 0x10, 0x21, 0x2B, 0x3F, 0x4B, 0x4C]
BUTTON_FUNCTIONS = {
'None': 0xFF,
'2-tone': 0x00,
@@ -309,29 +326,39 @@ BUTTON_FUNCTIONS = {
'Display Character': 0x1E,
'Fixed Volume': 0x20,
'Function': 0x21,
- 'LCD Brightness': 0x27,
'Monitor': 0x2A,
'Monitor Momentary': 0x2B,
+ 'Tone off': 0x2C,
+ 'OST': 0x2D,
+ 'Priority-channel Select': 0x2F,
'Transceiver Password': 0x32,
+ 'Scan': 0x33,
+ 'Scan Add/Delete': 0x34,
'Squelch Level': 0x3D,
'Squelch Off': 0x3E,
'Squelch Off (momentary)': 0x3F,
'Talk Around': 0x42,
'Telephone Disconnect': 0x43,
- 'Zone Down': 0x4B,
+ 'Zone Down': 0x4A,
'Zone Up': 0x4C,
'CH/GID Recall': 0x4E,
}
# These are only available on the portable transceiver
PORTABLE_BUTTON_FUNCTIONS = {
'AUX': 0x05,
+ 'Key Lock': 0x25, # This actually triggers on mobile, but doesn't lock
'Lamp': 0x26,
'Low TX Power': 0x28,
}
# These are only available on the mobile transceiver
MOBILE_BUTTON_FUNCTIONS = {
- 'Zone Down': 0x4A, # Different on mobile?
+ 'LCD Brightness': 0x27,
+ 'Volume Down': 0x44,
+ 'Volume Up': 0x46,
}
+ALL_FUNCTION_REV = {v: k for k, v in (BUTTON_FUNCTIONS |
+ PORTABLE_BUTTON_FUNCTIONS |
+ MOBILE_BUTTON_FUNCTIONS).items()}
KNOB_MODE = {
'None': 0xFF,
'Group': 0x30,
@@ -340,6 +367,7 @@ KNOB_MODE = {
KEYPAD_TYPE = {
'None': 0xFF,
'12-key': 0x30,
+ # Note there is a 16-key option on mobile
}
KEYPAD_OP = {
'None': 0xFF,
@@ -356,6 +384,252 @@ 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'])
+
+
+class ButtonSetting(MemSetting):
+ """Setting for a button function.
+
+ This is required because the button function structure is complex with
+ multiple fields that are interdependent.
+ """
+ def __init__(self, key_index, button_struct, disposition, key, functions):
+ self._key_index = key_index
+ self._disposition = disposition
+ current_fn = int(getattr(button_struct,
+ disposition.name.lower()))
+ if current_fn == 0xFF and disposition == ButtonDisposition.PRIMARY:
+ # Sometimes the primary slot is 0xFF and the real function is
+ # stored in the alternate spot (?)
+ current_fn = int(getattr(button_struct, 'primary_alt'))
+
+ try:
+ cur_option = ALL_FUNCTION_REV[current_fn]
+ except KeyError:
+ LOG.warning('Invalid function value 0x%02x for button %s %s',
+ current_fn, key, disposition)
+ cur_option = ALL_FUNCTION_REV[0xFF]
+ super().__init__('button_%s_%s' % (
+ key, disposition.name.lower()),
+ key,
+ RadioSettingValueMap(functions.items(),
+ user_option=cur_option))
+
+ def apply_to_memobj(self, memobj):
+ i = self._key_index
+ if self._disposition == ButtonDisposition.PRIMARY:
+ # Primary keys always get set in the primary slot. If there
+ # is a hold function set, then the handler for that setting will
+ # move us to the primary_alt slot (requires proper ordering!)
+ memobj.buttons[i].primary = int(self.value)
+ memobj.buttons[i].primary_alt = 0xFF
+ elif self._disposition == ButtonDisposition.SECONDARY:
+ memobj.buttons[i].secondary = int(self.value)
+ elif self._disposition == ButtonDisposition.HOLD:
+ memobj.buttons[i].hold = int(self.value)
+ if int(self.value) != 0xFF:
+ # If a hold is set, we need to use the alternate arrangement,
+ # where primary is set to 0xFF and the alternate primary slot
+ # is set to the primary function.
+ memobj.buttons[i].primary_alt = memobj.buttons[i].primary
+ memobj.buttons[i].primary = 0xFF
+ elif int(memobj.buttons[i].primary_alt) != 0xFF:
+ # If a hold is NOT set, we need to make sure any stashed
+ # primary_alt is moved back to the actual primary slot
+ memobj.buttons[i].primary = memobj.buttons[i].primary_alt
+ memobj.buttons[i].primary_alt = 0xFF
+
+
def decode_dtmf(array):
return ''.join('%x%x' % (int(i) & 0x0F, (int(i) & 0xF0) >> 4)
for i in array if i != 0xFF)
@@ -405,10 +679,14 @@ def do_ident(radio):
send(radio, b'PROGRAM')
ack = radio.pipe.read(1)
LOG.debug('Read %r from radio' % ack)
+ 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')
@@ -416,6 +694,8 @@ def do_ident(radio):
LOG.debug('Radio ident is %r' % ident)
radio.pipe.write(b'\x06')
ack = radio.pipe.read(1)
+ if not ack:
+ raise errors.RadioNoResponse()
if ack != b'\x06':
raise errors.RadioError('Radio refused program mode')
if ident[:6] not in (radio._model,):
@@ -427,13 +707,6 @@ def do_ident(radio):
raise errors.RadioError('Unsupported radio model %s' % model)
-def checksum_data(data):
- _chksum = 0
- for byte in data:
- _chksum = (_chksum + byte) & 0xFF
- return _chksum
-
-
def do_download(radio):
do_ident(radio)
@@ -461,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()
@@ -471,7 +744,7 @@ def do_download(radio):
if len(chksum) != 1:
LOG.error('Checksum was %r' % chksum)
raise errors.RadioError('Radio sent invalid checksum')
- _chksum = checksum_data(chunk)
+ _chksum = checksum.checksum_8bit(chunk)
if chunk and _chksum != ord(chksum):
LOG.error(
@@ -521,12 +794,12 @@ def do_upload(radio):
for block in range(0, 0xBF + 1):
addr = block * 0x100
chunk = bytes(radio._mmap[addr:addr + 0x100])
- if all(byte == b'\xff' for byte in chunk):
+ if all(byte == 0xFF for byte in chunk):
send(radio, make_frame('Z', block, b'\xFF'))
else:
radio.pipe.log('Sending block %i' % block)
- checksum = checksum_data(chunk)
- send(radio, make_frame('W', block, chunk + bytes([checksum])))
+ cs = checksum.checksum_8bit(chunk)
+ send(radio, make_frame('W', block, chunk + bytes([cs])))
ack = radio.pipe.read(1)
if ack != b'\x06':
@@ -565,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'
@@ -573,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"""
@@ -586,6 +896,20 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
self._dat_header = (b'KPG89D\xFF\xFF\xFF\xFFV1.61' + self._model +
(b'\xFF' * 11) + (b'\xFF' * 32))
+ def _action_ost_standard(self):
+ for i, t in enumerate(chirp_common.TONES[:40]):
+ self._memobj.ost_tones[i].name = ('%6.1f' % t).ljust(12)
+ self._memobj.ost_tones[i].rxtone = t * 10
+ self._memobj.ost_tones[i].txtone = t * 10
+
+ def _action_ost_gmrs(self):
+ tones = list(chirp_common.TONES[:41])
+ tones.remove(69.3)
+ for i, t in enumerate(tones):
+ self._memobj.ost_tones[i].name = '%2i %7.1f' % (i + 1, t)
+ self._memobj.ost_tones[i].rxtone = t * 10
+ self._memobj.ost_tones[i].txtone = t * 10
+
def sync_in(self):
try:
data = do_download(self)
@@ -602,6 +926,9 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
def sync_out(self):
try:
do_upload(self)
+ except errors.RadioError:
+ reset(self)
+ raise
except Exception as e:
reset(self)
LOG.exception('General failure')
@@ -685,87 +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
-
- 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(asbytes=False))
- dest_zoneinfo.count = count
-
- for dest_i in range(0, min(count, old_count)):
- dest[dest_i].set_raw(source[dest_i].get_raw(asbytes=False))
- 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
-
- 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(asbytes=False)
- 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):
@@ -810,26 +1057,23 @@ 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
- def _get_raw_memory(self, number):
+ def _get_index_of_memory(self, number):
+ """Return the index of memory number in this zone"""
for i in range(0, self.raw_zoneinfo.count):
if self.raw_memories[i].number == number:
- return self.raw_memories[i]
- return None
+ return i
+ raise ValueError('Memory %i not mapped' % number)
+
+ def _get_raw_memory(self, number):
+ """Get the raw memory structure of a memory by number"""
+ try:
+ index = self._get_index_of_memory(number)
+ return self.raw_memories[index]
+ except ValueError:
+ return None
def get_raw_memory(self, number):
return repr(self._get_raw_memory(number))
@@ -903,9 +1147,9 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
mem.duplex = 'split'
mem.offset = int(_mem.tx_freq) * 10
- skipbyte = self._memobj.skipflags[(mem.number - 1) // 8]
- skipbit = skipbyte & (1 << (mem.number - 1) % 8)
- mem.skip = skipbit and 'S' or ''
+ scan_index = (self.raw_zoneinfo.flagoffset +
+ self._get_index_of_memory(number) - 1)
+ mem.skip = 'S' if int(self._memobj.skipflags[scan_index]) else ''
mem.extra = RadioSettingGroup('extra', 'Extra')
mem.extra.append(MemSetting(
@@ -997,11 +1241,9 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
_mem.rx_step = tk280.choose_step(step_lookup, int(_mem.rx_freq) * 10)
_mem.tx_step = tk280.choose_step(step_lookup, int(_mem.tx_freq) * 10)
- skipbyte = self._memobj.skipflags[(mem.number - 1) // 8]
- if mem.skip == 'S':
- skipbyte |= (1 << (mem.number - 1) % 8)
- else:
- skipbyte &= ~(1 << (mem.number - 1) % 8)
+ scan_index = (self.raw_zoneinfo.flagoffset +
+ self._get_index_of_memory(mem.number) - 1)
+ self._memobj.skipflags[scan_index] = int(mem.skip == 'S')
for setting in mem.extra:
setting.apply_to_memobj(_mem)
@@ -1206,20 +1448,21 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
settings = self._memobj.settings
group = RadioSettingSubGroup('common3', 'Common 3')
- rs = MemSetting('settings.battsave', 'Battery Save',
- RadioSettingValueMap(BATTSAVE_SETTINGS.items(),
- settings.battsave))
- group.append(rs)
+ if self.is_portable:
+ rs = MemSetting('settings.battsave', 'Battery Save',
+ RadioSettingValueMap(BATTSAVE_SETTINGS.items(),
+ settings.battsave))
+ group.append(rs)
- rs = MemSetting('settings.battwarn', 'Battery Warning',
- RadioSettingValueMap(BATTWARN_SETTINGS.items(),
- settings.battwarn))
- group.append(rs)
+ rs = MemSetting('settings.battwarn', 'Battery Warning',
+ RadioSettingValueMap(BATTWARN_SETTINGS.items(),
+ settings.battwarn))
+ group.append(rs)
- rs = MemSetting('settings.battstatus', 'Battery Status',
- RadioSettingValueInvertedBoolean(
- not settings.battstatus))
- group.append(rs)
+ rs = MemSetting('settings.battstatus', 'Battery Status',
+ RadioSettingValueInvertedBoolean(
+ not settings.battstatus))
+ group.append(rs)
rs = MemSetting('settings.pttid_type', 'PTTID Type',
RadioSettingValueMap(PTTID_TYPES.items(),
@@ -1338,84 +1581,26 @@ 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 = MOBILE_BUTTON_FUNCTIONS
+ model_functions = BUTTON_FUNCTIONS | MOBILE_BUTTON_FUNCTIONS
+ button_defs = BUTTONS | BUTTONS_MOBILE
else:
- model_functions = PORTABLE_BUTTON_FUNCTIONS
-
- pri_functions = BUTTON_FUNCTIONS | model_functions
- sec_functions = (
- {k: v for k, v in (model_functions | BUTTON_FUNCTIONS).items()
- if v not in PRIMARY_ONLY})
+ model_functions = BUTTON_FUNCTIONS | PORTABLE_BUTTON_FUNCTIONS
+ button_defs = BUTTONS | BUTTONS_PORTABLE
group = RadioSettingGroup('keys', 'Keys')
pri = RadioSettingSubGroup('primary', 'Primary')
sec = RadioSettingSubGroup('secondary', 'Secondary')
+ hold = RadioSettingSubGroup('hold', 'Hold')
+ holdtime = RadioSettingSubGroup('holdtime', 'Hold Time')
buttons = self._memobj.buttons
- rs = MemSetting('selector_knob', 'Selector Knob',
- RadioSettingValueMap(KNOB_MODE.items(),
- self._memobj.selector_knob))
- group.append(rs)
+ if not self.is_mobile:
+ rs = MemSetting('selector_knob', 'Selector Knob',
+ RadioSettingValueMap(KNOB_MODE.items(),
+ self._memobj.selector_knob))
+ group.append(rs)
rs = MemSetting('keypad_type', 'Keypad Type',
RadioSettingValueMap(KEYPAD_TYPE.items(),
@@ -1432,18 +1617,42 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
not self._memobj.list_selector_key))
group.append(rs)
- for key, index in BUTTONS.items():
- rs = MemSetting('buttons[%i].primary' % index, key,
- RadioSettingValueMap(pri_functions.items(),
- buttons[index].primary))
+ for key, index in button_defs.items():
+ rs = ButtonSetting(index, buttons[index],
+ ButtonDisposition.PRIMARY,
+ key, model_functions)
pri.append(rs)
- rs = MemSetting('buttons[%i].secondary' % index, key,
- RadioSettingValueMap(sec_functions.items(),
- buttons[index].secondary))
+ rs = ButtonSetting(index, buttons[index],
+ ButtonDisposition.SECONDARY,
+ key, model_functions)
+ rs.set_doc('The function triggered when Function+%s is '
+ 'pressed' % key)
sec.append(rs)
+
+ rs = ButtonSetting(index, buttons[index],
+ ButtonDisposition.HOLD,
+ key, model_functions)
+ rs.set_doc('The function triggered when %s is held' % key)
+ hold.append(rs)
+
+ try:
+ curhold = int(self._memobj.buttons[index].holdtime)
+ curhold = max(100, min(curhold, 5000))
+ except Exception:
+ LOG.warning('Invalid value for button %s:%i hold time',
+ key, index)
+ curhold = 1000
+ rs = MemSetting('buttons[%i].holdtime' % index, key,
+ RadioSettingValueInteger(100, 5000, 1000, 100))
+ rs.set_doc('Amount of hold time required to trigger '
+ '(milliseconds)')
+ holdtime.append(rs)
+
group.append(pri)
group.append(sec)
+ group.append(hold)
+ group.append(holdtime)
return group
@@ -1567,3 +1776,11 @@ class KenwoodTK7180ERadio(KenwoodTKx180Radio):
MODEL = 'TK-7180E'
VALID_BANDS = [(136000000, 174000000)]
_model = b'M7189$'
+
+
+# E is technicallly 400-470
+@directory.register
+class KenwoodTK3180ERadio(KenwoodTKx180Radio):
+ MODEL = 'TK-3180E'
+ VALID_BANDS = [(400000000, 520000000)]
+ _model = b'P3189\x27'
diff --git a/chirp/drivers/tmd710.py b/chirp/drivers/tmd710.py
index 8768039..8f85243 100644
--- a/chirp/drivers/tmd710.py
+++ b/chirp/drivers/tmd710.py
@@ -71,23 +71,25 @@ def _command(ser, cmd, rsplen, w8t=0.01):
rsplen is expected response char count, NOT incl prefix and term
If rsplen = 0 then do not0 read after write """
ser.write(cmd)
- LOG.debug(" Out %4i ->: %s" % (len(cmd), util.hexprint(cmd[0: 32])))
time.sleep(w8t)
result = b""
if rsplen > 0: # read response
result = ser.read(rsplen)
- LOG.debug(" In %4i <-: %s" % (len(result),
- util.hexprint(result[0: 32])))
return result
def _connect_radio(radio):
"""Determine baud rate and verify radio on-line"""
- global BAUD
+ status = chirp_common.Status()
+ status.msg = 'Probing baud rate of radio'
+ _update_status(radio, status)
xid = "D710" + radio.SHORT
- resp = kenwood_live.KenwoodLiveRadio().get_id(radio.pipe)
- BAUD = radio.pipe.baudrate # As detected by kenwood_live
- LOG.debug("Got [%s] at %i Baud." % (resp, BAUD))
+ resp = kenwood_live.KenwoodLiveRadio(None).get_id(radio.pipe)
+ # If we are running at 9600 baud (the default), then the default
+ # timeout of 250ms is too short for some clone-mode responses. 1s should
+ # always be enough.
+ radio.pipe.timeout = 1
+ LOG.debug("Got [%s] at %i Baud." % (resp, radio.pipe.baudrate))
resp = resp[3:] # Strip "ID " prefix
if len(resp) > 2: # Got something from "ID"
if resp == xid: # Good comms
@@ -95,14 +97,15 @@ def _connect_radio(radio):
else:
stx = "Radio responded as %s, not %s." % (resp, xid)
raise errors.RadioError(stx)
- raise errors.RadioError("No response from radio")
+ if resp:
+ raise errors.RadioError("Unexpected response from radio")
+ raise errors.RadioNoResponse()
def _update_status(self, status, step=1):
""" Increment status bar """
status.cur += step
self.status_fn(status)
- return
def _val_list(setting, opts, obj, atrb, fix=0, ndx=-1):
@@ -116,7 +119,6 @@ def _val_list(setting, opts, obj, atrb, fix=0, ndx=-1):
setattr(obj[ndx], atrb, value)
else:
setattr(obj, atrb, value)
- return
class KenwoodTMx710Radio(chirp_common.CloneModeRadio):
@@ -203,6 +205,12 @@ class KenwoodTMx710Radio(chirp_common.CloneModeRadio):
LOG.exception('Unexpected error during download')
raise errors.RadioError('Unexpected error communicating '
'with the radio')
+ finally:
+ try:
+ resp = _command(self.pipe, b"E", 0, W8S)
+ except Exception:
+ pass
+
self._mmap = memmap.MemoryMapBytes(data)
self.process_mmap()
@@ -211,12 +219,19 @@ class KenwoodTMx710Radio(chirp_common.CloneModeRadio):
try:
_connect_radio(self)
self._write_mem()
+ except errors.RadioError:
+ raise
except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
LOG.exception('Unexpected error during upload')
raise errors.RadioError('Unexpected error communicating '
'with the radio')
+ finally:
+ try:
+ resp = _command(self.pipe, b"E", 0, W8S)
+ except Exception:
+ pass
def process_mmap(self):
"""Process the mem map into the mem object"""
@@ -393,8 +408,6 @@ class KenwoodTMx710Radio(chirp_common.CloneModeRadio):
_mem.tmode = 0x0a
if mem.tmode == "DTCS":
_mem.tmode = 0x09
- if mem.duplex == "n/a": # Not valid
- mem.duplex = ""
_mem.duplex = TMD710_DUPLEX.index(mem.duplex)
_mem.offset = mem.offset
_mem.tstep = TMD710_STEPS.index(mem.tuning_step)
@@ -416,7 +429,6 @@ class KenwoodTMx710Radio(chirp_common.CloneModeRadio):
setattr(_mem, "splitstep", val)
else:
setattr(_mem, ext.get_name(), ext.value)
- return
def get_settings(self):
"""Translate the MEM_FORMAT structs into settings in the UI"""
@@ -458,7 +470,6 @@ class KenwoodTMx710Radio(chirp_common.CloneModeRadio):
setattr(obj, atrb, value)
else:
setattr(obj[ndx], atrb, value)
- return
def _mhz_val(setting, obj, atrb, ndx=-1, ndy=-1):
""" Callback to set freq back to Hz """
@@ -472,7 +483,6 @@ class KenwoodTMx710Radio(chirp_common.CloneModeRadio):
setattr(obj[ndx].progvfo[ndy], stx[1], vx)
else:
setattr(obj[ndx], atrb, vx)
- return
def _char_to_str(chrx):
""" Remove ff pads from char array """
@@ -493,7 +503,6 @@ class KenwoodTMx710Radio(chirp_common.CloneModeRadio):
raise errors.RadioError(sx)
str2 = str1.ljust(6, chr(255)) # pad to 6 with ff's
setattr(obj, atrb, str2)
- return
def _pad_str(setting, lenstr, padchr, obj, atrb, ndx=-1):
""" pad string to lenstr with padchr """
@@ -503,7 +512,6 @@ class KenwoodTMx710Radio(chirp_common.CloneModeRadio):
setattr(obj, atrb, str2)
else:
setattr(obj[ndx], atrb, str2)
- return
# ===== BASIC GROUP =====
sx = _char_to_str(_com.comnt)
@@ -1234,7 +1242,6 @@ class KenwoodTMx710Radio(chirp_common.CloneModeRadio):
except Exception:
LOG.debug(element.get_name())
raise
- return
@classmethod
def match_model(cls, fdata, fyle):
@@ -1532,7 +1539,6 @@ class KenwoodTMD710Radio(KenwoodTMx710Radio):
def _read_mem(radio):
""" Load the memory map """
- global BAUD
status = chirp_common.Status()
status.cur = 0
val = 0
@@ -1544,7 +1550,6 @@ class KenwoodTMD710Radio(KenwoodTMx710Radio):
data = ""
- radio.pipe.baudrate = BAUD
cmc = b"0M PROGRAM" + TERM
resp0 = _command(radio.pipe, cmc, 3, W8S)
junk = radio.pipe.read(16) # flushit
@@ -1554,7 +1559,6 @@ class KenwoodTMD710Radio(KenwoodTMx710Radio):
resp0 = _command(radio.pipe, cmc, 260, W8S)
junk = _command(radio.pipe, ACK, 1, W8S)
if len(resp0) < 260:
- junk = _command(radio.pipe, b"E", 2, W8S)
sx = "Block 0x%x read error: " % bkx
sx += "Got %i bytes, expected 260." % len(resp0)
LOG.error(sx)
@@ -1577,14 +1581,10 @@ class KenwoodTMD710Radio(KenwoodTMx710Radio):
data += resp0[4:]
junk = _command(radio.pipe, ACK, 1, W8S)
_update_status(radio, status)
- # Exit Prog mode, no TERM
- resp = _command(radio.pipe, b"E", 2, W8S) # Rtns 06 0d
- radio.pipe.baudrate = BAUD
return data
def _write_mem(radio):
""" PROG MCP Blocks Send """
- global BAUD
# UI progress
status = chirp_common.Status()
status.cur = 0
@@ -1596,7 +1596,6 @@ class KenwoodTMD710Radio(KenwoodTMx710Radio):
radio.status_fn(status)
imgadr = 0
- radio.pipe.baudrate = BAUD
resp0 = _command(radio.pipe, b"0M PROGRAM" + TERM, 3, W8S)
# Read block 0 magic header thingy, save it
cmc = b"R" + bytes([0, 0, 4])
@@ -1659,9 +1658,6 @@ class KenwoodTMD710Radio(KenwoodTMx710Radio):
LOG.error("Mht0 Write error at 00 00 04 , no ACK.")
sx = "Radio failed to acknowledge upload packet!"
raise errors.RadioError(sx)
- # Write E to Exit PROG mode
- resp = _command(radio.pipe, b"E", 2, W8S)
- return
@directory.register
@@ -1971,7 +1967,6 @@ class KenwoodTMD710GRadio(KenwoodTMx710Radio):
def _read_mem(radio):
""" Load the memory map """
- global BAUD
status = chirp_common.Status()
status.cur = 0
val = 0
@@ -1983,7 +1978,6 @@ class KenwoodTMD710GRadio(KenwoodTMx710Radio):
data = b""
- radio.pipe.baudrate = BAUD
resp0 = radio.pipe.read(16) # flush
cmc = b"0M PROGRAM" + TERM
resp0 = _command(radio.pipe, cmc, 3, W8S)
@@ -1999,7 +1993,6 @@ class KenwoodTMD710GRadio(KenwoodTMx710Radio):
radio._make_command(b'R', addr, 0),
radio._packet_size[blkn], W8S)
if len(resp0) < radio._packet_size[blkn]:
- junk = _command(radio.pipe, b"E", 0, W8S)
lb = len(resp0)
xb = radio._packet_size[blkn]
sx = "Block 0x%x, 0x%x read error: " % (blkn, bkx)
@@ -2015,14 +2008,10 @@ class KenwoodTMD710GRadio(KenwoodTMx710Radio):
else:
data += resp0[5:] # skip cmd echo
_update_status(radio, status) # UI Update
- # Exit Prog mode, no TERM
- resp = _command(radio.pipe, b"E", 0, W8S)
- radio.pipe.baudrate = BAUD
return data
def _write_mem(radio):
""" PROG MCP Blocks Send """
- global BAUD
# UI progress
status = chirp_common.Status()
status.cur = 0
@@ -2034,7 +2023,6 @@ class KenwoodTMD710GRadio(KenwoodTMx710Radio):
radio.status_fn(status)
imgadr = 0
- radio.pipe.baudrate = BAUD
resp0 = _command(radio.pipe, b"0M PROGRAM" + TERM, 3, W8S)
radio.pipe.baudrate = 57600
LOG.debug("Switching to 57600 baud upload.")
@@ -2066,7 +2054,7 @@ class KenwoodTMD710GRadio(KenwoodTMx710Radio):
data = radio.get_mmap()[imgadr:imgadr + 256]
cmc = radio._make_command(b'W', addr, 0, data)
- resp0 = _command(radio.pipe, cmc, 6, W8S)
+ resp0 = _command(radio.pipe, cmc, 1, W8S)
if bkx > 0 and resp0 != ACK:
LOG.error("Packet 0x%x Write error, no ACK!" % bkx)
sx = "Radio failed to acknowledge upload. "
@@ -2082,7 +2070,3 @@ class KenwoodTMD710GRadio(KenwoodTMx710Radio):
resp0 = _command(radio.pipe, cmc, 1, W8S)
cmc = radio._make_command(b'Z', radio._block_addr[0], 1, mht0[0:1])
resp0 = _command(radio.pipe, cmc, 16, W8S)
- # Write E to Exit PROG mode
- resp = _command(radio.pipe, b"E", 0, W8S)
- radio.pipe.baudrate = BAUD
- return
diff --git a/chirp/drivers/tmv71.py b/chirp/drivers/tmv71.py
index 03e0ef3..2524680 100644
--- a/chirp/drivers/tmv71.py
+++ b/chirp/drivers/tmv71.py
@@ -35,6 +35,7 @@ class TMV71ARadio(chirp_common.CloneModeRadio):
return rf
def _detect_baud(self):
+ saw_response = False
for baud in [9600, 19200, 38400, 57600]:
self.pipe.baudrate = baud
self.pipe.write("\r\r")
@@ -43,10 +44,15 @@ class TMV71ARadio(chirp_common.CloneModeRadio):
id = tmv71_ll.get_id(self.pipe)
LOG.info("Radio %s at %i baud" % (id, baud))
return True
+ except errors.RadioNoResponse:
+ pass
except errors.RadioError:
+ saw_response = True
pass
- raise errors.RadioError("No response from radio")
+ if saw_response:
+ raise errors.RadioError("Unexpected response from radio")
+ raise errors.RadioNoResponse()
def get_raw_memory(self, number):
return util.hexprint(tmv71_ll.get_raw_mem(self._mmap, number))
diff --git a/chirp/drivers/tmv71_ll.py b/chirp/drivers/tmv71_ll.py
index 5236361..8bbd551 100644
--- a/chirp/drivers/tmv71_ll.py
+++ b/chirp/drivers/tmv71_ll.py
@@ -65,8 +65,9 @@ def get_id(s):
r = command(s, "ID")
if r.startswith("ID "):
return r.split(" ")[1]
- else:
- raise errors.RadioError("No response to ID command")
+ if not r:
+ raise errors.RadioNoResponse()
+ raise errors.RadioError("Unexpected response to ID command")
EXCH_R = "R\x00\x00\x00"
@@ -105,8 +106,11 @@ def write_block(s, block, map):
def download(radio):
- if command(radio.pipe, "0M PROGRAM") != "0M":
- raise errors.RadioError("No response from radio")
+ resp = command(radio.pipe, "0M PROGRAM")
+ if not resp:
+ raise errors.RadioNoResponse()
+ if resp != "0M":
+ raise errors.RadioError("Unexpected response to program command")
data = ""
for i in range(0, 0x7F):
@@ -124,8 +128,11 @@ def download(radio):
def upload(radio):
- if command(radio.pipe, "0M PROGRAM") != "0M":
- raise errors.RadioError("No response from radio")
+ resp = command(radio.pipe, "0M PROGRAM")
+ if not resp:
+ raise errors.RadioNoResponse()
+ if resp != "0M":
+ raise errors.RadioError("Unexpected response to program command")
for i in range(0, 0x7F):
r = write_block(radio.pipe, i, radio._mmap)
diff --git a/chirp/drivers/ts2000.py b/chirp/drivers/ts2000.py
index d60ff25..b40d985 100644
--- a/chirp/drivers/ts2000.py
+++ b/chirp/drivers/ts2000.py
@@ -192,6 +192,7 @@ class TS2000Radio(KenwoodLiveRadio):
r1 = self.command(self.pipe,
*self._cmd_set_memory(memory.number, spec))
if not iserr(r1):
+ memory = memory.dupe()
memory.name = memory.name.rstrip()
self._memcache[memory.number] = memory
diff --git a/chirp/drivers/ts480.py b/chirp/drivers/ts480.py
index 8f7288f..022bd84 100644
--- a/chirp/drivers/ts480.py
+++ b/chirp/drivers/ts480.py
@@ -154,14 +154,19 @@ def _connect_radio(radio):
junk = radio.pipe.read(256)
radio.pipe.timeout = STIMEOUT
+ saw_response = False
for bd in bauds:
radio.pipe.baudrate = bd
BAUD = bd
radio.pipe.write(";")
radio.pipe.write(";")
resp = radio.pipe.read(16)
+ if resp:
+ saw_response = True
radio.pipe.write("ID;")
resp = radio.pipe.read(16)
+ if resp:
+ saw_response = True
if resp.find(radio.ID) >= 0: # Good comms
resp = command(radio.pipe, "AI0", 0, W8L)
return
@@ -169,7 +174,9 @@ def _connect_radio(radio):
msg = "Radio reported as model %s, not %s!" % \
(RADIO_IDS[resp], radio.MODEL)
raise errors.RadioError(msg)
- raise errors.RadioError("No response from radio")
+ if saw_response:
+ raise errors.RadioError("Unexpected response from radio")
+ raise errors.RadioNoResponse()
def read_str(radio, trm=";"):
@@ -553,6 +560,8 @@ class TS480_CRadio(chirp_common.CloneModeRadio):
_connect_radio(self)
_write_mem(self)
_write_sets(self)
+ except errors.RadioError:
+ raise
except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
diff --git a/chirp/drivers/ts590.py b/chirp/drivers/ts590.py
index 00ed03b..3a7ea8d 100644
--- a/chirp/drivers/ts590.py
+++ b/chirp/drivers/ts590.py
@@ -187,14 +187,19 @@ def _connect_radio(radio):
junk = radio.pipe.read(256)
radio.pipe.timeout = STIMEOUT
+ saw_response = False
for bd in bauds:
radio.pipe.baudrate = bd
BAUD = bd
radio.pipe.write(";")
radio.pipe.write(";")
resp = radio.pipe.read(4)
+ if resp:
+ saw_response = True
radio.pipe.write("ID;")
resp = radio.pipe.read(6)
+ if resp:
+ saw_response = True
if resp == radio.ID: # Good comms
resp = command(radio.pipe, "AI0", 0, W8L)
@@ -203,7 +208,9 @@ def _connect_radio(radio):
msg = "Radio reported as model %s, not %s!" % \
(RADIO_IDS[resp], radio.MODEL)
raise errors.RadioError(msg)
- raise errors.RadioError("No response from radio")
+ if saw_response:
+ raise errors.RadioError("Unexpected response from radio")
+ raise errors.RadioNoResponse()
def read_str(radio, trm=";"):
@@ -714,6 +721,8 @@ class TS590Radio(chirp_common.CloneModeRadio):
_connect_radio(self)
_write_mem(self)
_write_sets(self)
+ except errors.RadioError:
+ raise
except Exception:
# If anything unexpected happens, make sure we raise
# a RadioError and log the problem
@@ -1638,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/ts850.py b/chirp/drivers/ts850.py
index 8f832cd..bdeaba5 100644
--- a/chirp/drivers/ts850.py
+++ b/chirp/drivers/ts850.py
@@ -117,6 +117,10 @@ class TS850Radio(KenwoodLiveRadio):
"Number must be between 0 and %i" % self._upper)
if memory.number > 90:
+ # This is not a good solution here, but this driver was
+ # designed in such a way that not doing a dupe and using an
+ # actual Memory() would require quite a bit more change.
+ memory = memory.dupe()
if memory.duplex == TS850_DUPLEX[0]:
memory.duplex = TS850_DUPLEX[1]
memory.offset = memory.freq
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 6e67dcc..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]
@@ -1027,16 +1027,27 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
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(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)
rs = RadioSetting("scode", "PTT ID Code",
RadioSettingValueList(PTTIDCODE_LIST,
current_index=_mem.scode))
+ rs.set_doc(
+ "Selects which of the 15 programmed DTMF PTT-ID codes this "
+ "channel transmits. Edit the code itself under DTMF Settings.")
mem.extra.append(rs)
immutable = []
@@ -1200,16 +1211,32 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("squelch", "Carrier Squelch Level",
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 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(
+ "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(
+ "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":
@@ -1218,35 +1245,58 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
# by the wrong name for the UV-6.
rs = RadioSetting("autolk", "Vox",
RadioSettingValueBoolean(_settings.autolk))
+ 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.")
advanced.append(rs)
if self.MODEL != "UV-6":
rs = RadioSetting("abr", "Backlight Timeout",
RadioSettingValueInteger(0, 24, _settings.abr))
+ rs.set_doc(
+ "Sets how many seconds the display backlight remains on "
+ "after a key press or radio activity. 0 disables the "
+ "automatic backlight.")
basic.append(rs)
rs = RadioSetting("tdr", "Dual Watch",
RadioSettingValueBoolean(_settings.tdr))
+ 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.")
advanced.append(rs)
if self.MODEL == "UV-6":
rs = RadioSetting("tdrch", "Dual Watch Channel",
RadioSettingValueList(
TDRCH_LIST, current_index=_settings.tdrch))
+ rs.set_doc(
+ "Selects the memory channel monitored by the Dual "
+ "Watch function.")
advanced.append(rs)
rs = RadioSetting("tdrab", "Dual Watch TX Priority",
RadioSettingValueBoolean(_settings.tdrab))
+ rs.set_doc(
+ "Selects which side has transmit priority while Dual Watch "
+ "is enabled.")
advanced.append(rs)
else:
rs = RadioSetting("tdrab", "Dual Watch TX Priority",
RadioSettingValueList(
TDRAB_LIST, current_index=_settings.tdrab))
+ rs.set_doc(
+ "Selects which side has transmit priority while Dual Watch "
+ "is enabled.")
advanced.append(rs)
if self.MODEL == "UV-6":
rs = RadioSetting("alarm", "Alarm Sound",
RadioSettingValueBoolean(_settings.alarm))
+ rs.set_doc(
+ "Enables or disables the alarm sound.")
advanced.append(rs)
if _settings.almod > 0x02:
@@ -1256,120 +1306,203 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("almod", "Alarm Mode",
RadioSettingValueList(
ALMOD_LIST, current_index=val))
+ rs.set_doc(
+ "Chooses how the alarm function operates when the CALL button "
+ "is held: Site, Tone, or Code.")
advanced.append(rs)
rs = RadioSetting("beep", "Beep",
RadioSettingValueBoolean(_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("timeout", "Timeout Timer",
RadioSettingValueList(
TIMEOUT_LIST, current_index=_settings.timeout))
+ 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)
if ((self._is_orig() and self._my_version() < 251) or
(self.MODEL in ["TI-F8+", "TS-T9+"])):
rs = RadioSetting("voice", "Voice",
RadioSettingValueBoolean(_settings.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.")
advanced.append(rs)
else:
rs = RadioSetting("voice", "Voice",
RadioSettingValueList(
VOICE_LIST, current_index=_settings.voice))
+ rs.set_doc(
+ "Selects the language for spoken radio-operation prompts, "
+ "or disables those prompts.")
advanced.append(rs)
rs = RadioSetting("screv", "Scan Resume",
RadioSettingValueList(
RESUME_LIST, current_index=_settings.screv))
+ rs.set_doc(
+ "Controls what scanning does after finding a signal. TO resumes "
+ "after a preset time, CO resumes after the signal disappears, "
+ "and SE stops scanning on the detected frequency or channel.")
advanced.append(rs)
if self.MODEL != "UV-6":
rs = RadioSetting("mdfa", "Display Mode (A)",
RadioSettingValueList(
MODE_LIST, current_index=_settings.mdfa))
+ 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("mdfb", "Display Mode (B)",
RadioSettingValueList(
MODE_LIST, current_index=_settings.mdfb))
+ 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)
rs = RadioSetting("bcl", "Busy Channel Lockout",
RadioSettingValueBoolean(_settings.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.")
advanced.append(rs)
if self.MODEL != "UV-6":
rs = RadioSetting("autolk", "Automatic Key Lock",
RadioSettingValueBoolean(_settings.autolk))
+ rs.set_doc(
+ "Automatically locks the keypad to prevent accidental "
+ "changes. Hold the # key to unlock the keypad.")
advanced.append(rs)
rs = RadioSetting("fmradio", "Broadcast FM Radio",
RadioSettingValueBoolean(_settings.fmradio))
+ rs.set_doc(
+ "Allows or blocks use of the 65-108 MHz broadcast FM receiver "
+ "from the radio's CALL button.")
advanced.append(rs)
if self.MODEL != "UV-6":
rs = RadioSetting("wtled", "Standby LED Color",
RadioSettingValueList(
COLOR_LIST, current_index=_settings.wtled))
+ rs.set_doc(
+ "Selects the display backlight color while the radio is in "
+ "standby, or turns that standby illumination off.")
basic.append(rs)
rs = RadioSetting("rxled", "RX LED Color",
RadioSettingValueList(
COLOR_LIST, current_index=_settings.rxled))
+ rs.set_doc(
+ "Selects the display backlight color used while receiving, "
+ "or turns receive illumination off.")
basic.append(rs)
rs = RadioSetting("txled", "TX LED Color",
RadioSettingValueList(
COLOR_LIST, current_index=_settings.txled))
+ rs.set_doc(
+ "Selects the display backlight color used while "
+ "transmitting, or turns transmit illumination off.")
basic.append(rs)
if isinstance(self, BaofengUV82Radio):
rs = RadioSetting("roger", "Roger Beep (TX)",
RadioSettingValueBoolean(_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("rogerrx", "Roger Beep (RX)",
RadioSettingValueList(
ROGERRX_LIST,
current_index=_settings.rogerrx))
+ rs.set_doc(
+ "Selects whether the radio sounds an end-of-reception tone "
+ "for the A or B display, or disables it.")
basic.append(rs)
else:
rs = RadioSetting("roger", "Roger Beep",
RadioSettingValueBoolean(_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("ste", "Squelch Tail Eliminate (HT to HT)",
RadioSettingValueBoolean(_settings.ste))
+ rs.set_doc(
+ "Transmits a special end-of-transmission signal intended to "
+ "reduce the squelch burst heard by another compatible handheld. "
+ "The manual recommends disabling this for repeater operation.")
advanced.append(rs)
rs = RadioSetting("rpste", "Squelch Tail Eliminate (repeater)",
RadioSettingValueList(
RPSTE_LIST, current_index=_settings.rpste))
+ rs.set_doc(
+ "Selects the squelch-tail elimination setting used for "
+ "communication through a compatible repeater. Use OFF when the "
+ "repeater does not support this feature.")
advanced.append(rs)
rs = RadioSetting("rptrl", "STE Repeater Delay",
RadioSettingValueList(
STEDELAY_LIST, current_index=_settings.rptrl))
+ rs.set_doc(
+ "Sets the delay before repeater squelch-tail elimination is "
+ "applied. Match this timing to the repeater; use OFF when the "
+ "feature is not required.")
advanced.append(rs)
if self.MODEL != "UV-6":
rs = RadioSetting("reset", "RESET Menu",
RadioSettingValueBoolean(_settings.reset))
+ rs.set_doc(
+ "Controls whether the radio's front-panel RESET menu is "
+ "available. This does not reset the radio by itself.")
advanced.append(rs)
rs = RadioSetting("menu", "All Menus",
RadioSettingValueBoolean(_settings.menu))
+ rs.set_doc(
+ "Controls access to the full front-panel menu. Disabling it "
+ "can prevent users from changing programmed settings on the "
+ "radio.")
advanced.append(rs)
if self.MODEL == "F-11":
# this is an F-11 only feature
rs = RadioSetting("vfomrlock", "VFO/MR Button",
RadioSettingValueBoolean(_settings.vfomrlock))
+ rs.set_doc(
+ "Controls whether the VFO/MR button can switch between "
+ "frequency and memory-channel modes.")
advanced.append(rs)
if isinstance(self, BaofengUV82Radio):
# this is a UV-82C only feature
rs = RadioSetting("vfomrlock", "VFO/MR Switching (UV-82C only)",
RadioSettingValueBoolean(_settings.vfomrlock))
+ rs.set_doc(
+ "Controls whether the VFO/MR button can switch between "
+ "frequency and memory-channel modes.")
advanced.append(rs)
if self.MODEL == "UV-82HP":
@@ -1377,18 +1510,25 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting(
"vfomrlock", "VFO/MR Switching (BTech UV-82HP only)",
RadioSettingValueBoolean(_settings.vfomrlock))
+ rs.set_doc(
+ "Controls whether the VFO/MR button can switch between "
+ "frequency and memory-channel modes.")
advanced.append(rs)
if isinstance(self, BaofengUV82Radio):
# this is an UV-82C only feature
rs = RadioSetting("singleptt", "Single PTT (UV-82C only)",
RadioSettingValueBoolean(_settings.singleptt))
+ rs.set_doc(
+ "Makes the dual PTT controls operate as a single PTT.")
advanced.append(rs)
if self.MODEL == "UV-82HP":
# this is an UV-82HP only feature
rs = RadioSetting("singleptt", "Single PTT (BTech UV-82HP only)",
RadioSettingValueBoolean(_settings.singleptt))
+ rs.set_doc(
+ "Makes the dual PTT controls operate as a single PTT.")
advanced.append(rs)
if self.MODEL == "UV-82HP":
@@ -1397,6 +1537,8 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
"tdrch", "Tone Burst Frequency (BTech UV-82HP only)",
RadioSettingValueList(
RTONE_LIST, current_index=_settings.tdrch))
+ rs.set_doc(
+ "Selects the tone-burst frequency sent for repeater access.")
advanced.append(rs)
def set_range_flag(setting):
@@ -1409,6 +1551,10 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("allrange", "Range Override Parameter",
RadioSettingValueString(0, 12, "Default"))
+ rs.set_doc(
+ "Service override for supported-frequency checks during upload. "
+ "Leave this at Default unless you fully understand the radio's "
+ "hardware limits and the legal limits for your location.")
rs.set_apply_callback(set_range_flag)
advanced.append(rs)
@@ -1428,6 +1574,10 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
RadioSettingValueList(
PONMSG_LIST,
current_index=_settings.ponmsg))
+ rs.set_doc(
+ "Chooses the startup display: Full shows the normal "
+ "full-screen test, while Message shows the two programmed "
+ "Power-On Message lines.")
other.append(rs)
if self.MODEL != "UV-6":
@@ -1437,26 +1587,42 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("displayab", "Display",
RadioSettingValueList(
AB_LIST, current_index=_settings.displayab))
+ rs.set_doc(
+ "Selects whether display line A or B is the active line for "
+ "tuning and other front-panel operations.")
workmode.append(rs)
rs = RadioSetting("workmode", "VFO/MR Mode",
RadioSettingValueList(
WORKMODE_LIST,
current_index=_settings.workmode))
+ rs.set_doc(
+ "Selects the operating mode used at startup: Frequency "
+ "(VFO) mode for direct tuning, or Channel (MR) mode for "
+ "programmed memories.")
workmode.append(rs)
rs = RadioSetting("keylock", "Keypad Lock",
RadioSettingValueBoolean(_settings.keylock))
+ rs.set_doc(
+ "Sets the current keypad-lock state. Hold the # key on the "
+ "radio to lock or unlock the keypad.")
workmode.append(rs)
rs = RadioSetting("wmchannel.mrcha", "MR A Channel",
RadioSettingValueInteger(0, 127,
_wmchannel.mrcha))
+ rs.set_doc(
+ "Selects the memory channel shown on display line A when "
+ "the radio is in Channel (MR) mode.")
workmode.append(rs)
rs = RadioSetting("wmchannel.mrchb", "MR B Channel",
RadioSettingValueInteger(0, 127,
_wmchannel.mrchb))
+ rs.set_doc(
+ "Selects the memory channel shown on display line B when "
+ "the radio is in Channel (MR) mode.")
workmode.append(rs)
def my_validate(value):
@@ -1473,28 +1639,51 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
obj.freq[i] = value % 10
value /= 10
- val1a = RadioSettingValueString(0, 10,
- bfc.bcd_decode_freq(_vfoa.freq))
+ try:
+ vafreq = bfc.bcd_decode_freq(_vfoa.freq)
+ except Exception as e:
+ LOG.exception('Failed to decode VFO A frequency: %s', e)
+ vafreq = e
+
+ val1a = RadioSettingValueString(0, 10, vafreq)
val1a.set_validate_callback(my_validate)
rs = RadioSetting("vfoa.freq", "VFO A Frequency", val1a)
+ rs.set_doc(
+ "Sets the receive frequency shown on display line A in "
+ "Frequency (VFO) mode.")
rs.set_apply_callback(apply_freq, _vfoa)
workmode.append(rs)
- val1b = RadioSettingValueString(0, 10,
- bfc.bcd_decode_freq(_vfob.freq))
+ try:
+ vbfreq = bfc.bcd_decode_freq(_vfob.freq)
+ except Exception as e:
+ LOG.exception('Failed to decode VFO B frequency: %s', e)
+ vbfreq = e
+ val1b = RadioSettingValueString(0, 10, vbfreq)
val1b.set_validate_callback(my_validate)
rs = RadioSetting("vfob.freq", "VFO B Frequency", val1b)
+ rs.set_doc(
+ "Sets the receive frequency shown on display line B in "
+ "Frequency (VFO) mode.")
rs.set_apply_callback(apply_freq, _vfob)
workmode.append(rs)
rs = RadioSetting("vfoa.sftd", "VFO A Shift",
RadioSettingValueList(
SHIFTD_LIST, current_index=_vfoa.sftd))
+ 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.")
workmode.append(rs)
rs = RadioSetting("vfob.sftd", "VFO B Shift",
RadioSettingValueList(
SHIFTD_LIST, current_index=_vfob.sftd))
+ 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.")
workmode.append(rs)
def convert_bytes_to_offset(bytes):
@@ -1513,6 +1702,10 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
0, 10, convert_bytes_to_offset(_vfoa.offset))
rs = RadioSetting("vfoa.offset",
"VFO A Offset (0.0-999.999)", val1a)
+ 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.")
rs.set_apply_callback(apply_offset, _vfoa)
workmode.append(rs)
@@ -1520,6 +1713,10 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
0, 10, convert_bytes_to_offset(_vfob.offset))
rs = RadioSetting("vfob.offset",
"VFO B Offset (0.0-999.999)", val1b)
+ 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.")
rs.set_apply_callback(apply_offset, _vfob)
workmode.append(rs)
@@ -1532,6 +1729,9 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
RadioSettingValueList(
TXPOWER3_LIST,
current_index=val))
+ rs.set_doc(
+ "Selects VFO A's transmitter power. Use the lowest "
+ "power that provides reliable communication.")
workmode.append(rs)
if _vfob.txpower3 > 0x02:
@@ -1542,59 +1742,98 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
RadioSettingValueList(
TXPOWER3_LIST,
current_index=val))
+ rs.set_doc(
+ "Selects VFO B's transmitter power. Use the lowest "
+ "power that provides reliable communication.")
workmode.append(rs)
else:
rs = RadioSetting("vfoa.txpower", "VFO A Power",
RadioSettingValueList(
TXPOWER_LIST,
current_index=_vfoa.txpower))
+ rs.set_doc(
+ "Selects VFO A's transmitter power. The UV-5R manual "
+ "lists High as approximately 4 W and Low as 1 W.")
workmode.append(rs)
rs = RadioSetting("vfob.txpower", "VFO B Power",
RadioSettingValueList(
TXPOWER_LIST,
current_index=_vfob.txpower))
+ rs.set_doc(
+ "Selects VFO B's transmitter power. The UV-5R manual "
+ "lists High as approximately 4 W and Low as 1 W.")
workmode.append(rs)
rs = RadioSetting("vfoa.widenarr", "VFO A Bandwidth",
RadioSettingValueList(
BANDWIDTH_LIST,
current_index=_vfoa.widenarr))
+ 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.")
workmode.append(rs)
rs = RadioSetting("vfob.widenarr", "VFO B Bandwidth",
RadioSettingValueList(
BANDWIDTH_LIST,
current_index=_vfob.widenarr))
+ 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.")
workmode.append(rs)
rs = RadioSetting("vfoa.scode", "VFO A PTT-ID",
RadioSettingValueList(
PTTIDCODE_LIST, current_index=_vfoa.scode))
+ rs.set_doc(
+ "Selects which of the 15 programmed DTMF PTT-ID codes VFO A "
+ "uses. Edit the code itself under DTMF Settings.")
workmode.append(rs)
rs = RadioSetting("vfob.scode", "VFO B PTT-ID",
RadioSettingValueList(
PTTIDCODE_LIST, current_index=_vfob.scode))
+ rs.set_doc(
+ "Selects which of the 15 programmed DTMF PTT-ID codes VFO B "
+ "uses. Edit the code itself under DTMF Settings.")
workmode.append(rs)
if not self._is_orig():
rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
RadioSettingValueList(
STEP291_LIST, current_index=_vfoa.step))
+ 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.")
workmode.append(rs)
rs = RadioSetting("vfob.step", "VFO B Tuning Step",
RadioSettingValueList(
STEP291_LIST, current_index=_vfob.step))
+ 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.")
workmode.append(rs)
else:
rs = RadioSetting("vfoa.step", "VFO A Tuning Step",
RadioSettingValueList(
STEP_LIST, current_index=_vfoa.step))
+ 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.")
workmode.append(rs)
rs = RadioSetting("vfob.step", "VFO B Tuning Step",
RadioSettingValueList(
STEP_LIST, current_index=_vfob.step))
+ 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.")
workmode.append(rs)
dtmf = RadioSettingGroup("dtmf", "DTMF Settings")
@@ -1623,6 +1862,10 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
val.set_charset(dtmfchars)
rs = RadioSetting("pttid/%i.code" % i,
"PTT ID Code %i" % (i + 1), val)
+ rs.set_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))
def apply_code(setting, obj):
code = []
@@ -1642,6 +1885,10 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
val = RadioSettingValueString(0, 5, _code, False)
val.set_charset(dtmfcharsani)
rs = RadioSetting("ani.code", "ANI Code", val)
+ rs.set_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.")
def apply_code(setting, obj):
code = []
@@ -1657,6 +1904,9 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("ani.aniid", "ANI ID",
RadioSettingValueList(PTTID_LIST,
current_index=_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.")
dtmf.append(rs)
_codeobj = self._memobj.ani.alarmcode
@@ -1664,6 +1914,9 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
val = RadioSettingValueString(0, 3, _code, False)
val.set_charset(dtmfchars)
rs = RadioSetting("ani.alarmcode", "Alarm Code", val)
+ rs.set_doc(
+ "Programs the three-character DTMF code transmitted when the "
+ "alarm is used in Code mode.")
def apply_code(setting, obj):
alarmcode = []
@@ -1680,6 +1933,11 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
"dtmfst", "DTMF Sidetone",
RadioSettingValueList(
DTMFST_LIST, current_index=_settings.dtmfst))
+ rs.set_doc(
+ "Chooses which transmitted DTMF tones are also heard through "
+ "the radio speaker. OFF mutes all; DT-ST sounds manually keyed "
+ "tones; ANI-ST sounds automatic ANI/PTT-ID tones; DT+ANI sounds "
+ "both.")
dtmf.append(rs)
if _ani.dtmfon > 0xC3:
@@ -1689,6 +1947,9 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)",
RadioSettingValueList(DTMFSPEED_LIST,
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.")
dtmf.append(rs)
if _ani.dtmfoff > 0xC3:
@@ -1698,10 +1959,17 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)",
RadioSettingValueList(DTMFSPEED_LIST,
current_index=val))
+ rs.set_doc(
+ "Sets the silent gap between transmitted DTMF tones. Increase "
+ "this if the receiving system cannot separate adjacent digits.")
dtmf.append(rs)
rs = RadioSetting("pttlt", "PTT ID Delay",
RadioSettingValueInteger(0, 50, _settings.pttlt))
+ 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.")
dtmf.append(rs)
try:
@@ -1727,11 +1995,15 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
val = RadioSettingValueString(0, 7, _filter(_msg.line1))
val.set_mutable(False)
rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val)
+ rs.set_doc(
+ "Read-only firmware identification stored in the radio.")
other.append(rs)
val = RadioSettingValueString(0, 7, _filter(_msg.line2))
val.set_mutable(False)
rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val)
+ rs.set_doc(
+ "Read-only firmware identification stored in the radio.")
other.append(rs)
_msg = self._memobj.sixpoweron_msg
@@ -1739,21 +2011,31 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
val.set_mutable(False)
rs = RadioSetting("sixpoweron_msg.line1",
"6+Power-On Message 1", val)
+ rs.set_doc(
+ "Read-only alternate startup text stored in newer radios.")
other.append(rs)
val = RadioSettingValueString(0, 7, _filter(_msg.line2))
val.set_mutable(False)
rs = RadioSetting("sixpoweron_msg.line2",
"6+Power-On Message 2", val)
+ rs.set_doc(
+ "Read-only alternate startup text stored in newer radios.")
other.append(rs)
_msg = self._memobj.poweron_msg
rs = RadioSetting("poweron_msg.line1", "Power-On Message 1",
RadioSettingValueString(
0, 7, _filter(_msg.line1)))
+ rs.set_doc(
+ "First line of the custom startup text shown when Power-On "
+ "Message is set to Message.")
other.append(rs)
rs = RadioSetting("poweron_msg.line2", "Power-On Message 2",
RadioSettingValueString(
0, 7, _filter(_msg.line2)))
+ rs.set_doc(
+ "Second line of the custom startup text shown when Power-On "
+ "Message is set to Message.")
other.append(rs)
if self._is_orig():
@@ -1766,16 +2048,27 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
"VHF Lower Limit (MHz)",
RadioSettingValueInteger(1, 1000,
vhf_limit.lower))
+ rs.set_doc(
+ "Sets the radio's lower VHF transmit limit in MHz. Keep this "
+ "within the hardware range and frequencies where you are "
+ "authorized to transmit.")
other.append(rs)
rs = RadioSetting("%s.vhf.upper" % limit,
"VHF Upper Limit (MHz)",
RadioSettingValueInteger(1, 1000,
vhf_limit.upper))
+ rs.set_doc(
+ "Sets the radio's upper VHF transmit limit in MHz. Keep this "
+ "within the hardware range and frequencies where you are "
+ "authorized to transmit.")
other.append(rs)
rs = RadioSetting("%s.vhf.enable" % limit, "VHF TX Enabled",
RadioSettingValueBoolean(vhf_limit.enable))
+ rs.set_doc(
+ "Enables transmission in the configured VHF range. Disable it "
+ "to make the VHF range receive-only.")
other.append(rs)
uhf_limit = getattr(self._memobj, limit).uhf
@@ -1783,14 +2076,25 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
"UHF Lower Limit (MHz)",
RadioSettingValueInteger(1, 1000,
uhf_limit.lower))
+ rs.set_doc(
+ "Sets the radio's lower UHF transmit limit in MHz. Keep this "
+ "within the hardware range and frequencies where you are "
+ "authorized to transmit.")
other.append(rs)
rs = RadioSetting("%s.uhf.upper" % limit,
"UHF Upper Limit (MHz)",
RadioSettingValueInteger(1, 1000,
uhf_limit.upper))
+ rs.set_doc(
+ "Sets the radio's upper UHF transmit limit in MHz. Keep this "
+ "within the hardware range and frequencies where you are "
+ "authorized to transmit.")
other.append(rs)
rs = RadioSetting("%s.uhf.enable" % limit, "UHF TX Enabled",
RadioSettingValueBoolean(uhf_limit.enable))
+ rs.set_doc(
+ "Enables transmission in the configured UHF range. Disable it "
+ "to make the UHF range receive-only.")
other.append(rs)
def _get_service_settings(self):
@@ -1809,6 +2113,11 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
RadioSettingValueInteger(
0, 123,
getattr(_obj, "sql%i" % (index))))
+ rs.set_doc(
+ "Service calibration threshold for %s squelch level "
+ "%i. Change only when calibrating the receiver with "
+ "appropriate test equipment." %
+ (band.upper(), index))
service.append(rs)
return service
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 b212d8b..b9b33d1 100644
--- a/chirp/drivers/uvb5.py
+++ b/chirp/drivers/uvb5.py
@@ -175,11 +175,16 @@ struct {
def do_ident(radio):
radio.pipe.timeout = 3
radio.pipe.write(b"\x05PROGRAM")
+ saw_response = False
for x in range(10):
ack = radio.pipe.read(1)
+ if ack:
+ saw_response = True
if ack == b'\x06':
break
else:
+ if not saw_response:
+ raise errors.RadioNoResponse()
raise errors.RadioError("Radio did not ack programming mode")
radio.pipe.write(b"\x02")
ident = radio.pipe.read(8)
@@ -483,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 c2fd7d9..4a76edc 100644
--- a/chirp/drivers/uvk5.py
+++ b/chirp/drivers/uvk5.py
@@ -1,4 +1,5 @@
# Quansheng UV-K5 driver (c) 2023 Jacek Lipkowski <sq5bpf@lipkowski.org>
+# Quansheng UV-K1 driver (c) 2025 Thibaut Berg <thibaut.berg@hotmail.com>
#
# based on template.py Copyright 2012 Dan Smith <dsmith@danplanet.com>
#
@@ -29,6 +30,7 @@ import struct
import logging
from chirp import chirp_common, directory, bitwise, memmap, errors, util
+from chirp import checksum
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueInteger, RadioSettingValueString, \
@@ -45,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;
@@ -86,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];
@@ -192,9 +209,7 @@ u8 enscramble;
} lock;
#seekto 0xf50;
-struct {
-char name[16];
-} channelname[200];
+struct channelname channelname[200];
#seekto 0x1c00;
struct {
@@ -364,30 +379,13 @@ def xorarr(data: bytes):
return ret
-def calculate_crc16_xmodem(data: bytes):
- """
- if this crc was used for communication to AND from the radio, then it
- would be a measure to increase reliability.
- but it's only used towards the radio, so it's for further obfuscation
- """
- poly = 0x1021
- crc = 0x0
- for byte in data:
- crc = crc ^ (byte << 8)
- for _ in range(8):
- crc = crc << 1
- if crc & 0x10000:
- crc = (crc ^ poly) & 0xFFFF
- return crc & 0xFFFF
-
-
def _send_command(serport, data: bytes):
"""Send a command to UV-K5 radio"""
serport.log("Sending command (unobfuscated) len=0x%4.4x:\n%s" % (
len(data), util.hexprint(data)))
- crc = calculate_crc16_xmodem(data)
- data2 = data + struct.pack("<H", crc)
+ crc_data = checksum.crc16_xmodem(data)
+ data2 = data + struct.pack("<H", crc_data)
command = struct.pack(">HBB", 0xabcd, len(data), 0) + \
xorarr(data2) + \
@@ -402,7 +400,7 @@ def _send_command(serport, data: bytes):
def _receive_reply(serport):
header = serport.read(4)
if not header:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
elif len(header) != 4:
LOG.warning("Header short read: [%s] len=%i",
util.hexprint(header), len(header))
@@ -506,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)
@@ -527,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)
@@ -551,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)
@@ -570,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"
@@ -617,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
@@ -918,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):
@@ -1908,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:
@@ -1959,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)
@@ -2001,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
@@ -2024,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.',
+ '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.
@@ -2098,11 +2159,6 @@ class UVK5RestrictedRadio(UVK5RadioBase):
raise errors.RadioError(
_('Upload is disabled due to unsupported firmware version'))
- def get_memory(self, n):
- mem = super().get_memory(n)
- mem.immutable = dir(mem)
- return mem
-
def set_memory(self, m):
raise errors.InvalidValueError(
_('Memories are read-only due to unsupported firmware version'))
@@ -2110,3 +2166,36 @@ class UVK5RestrictedRadio(UVK5RadioBase):
def set_settings(self, settings):
raise errors.InvalidValueError(
_('Settings are read-only due to unsupported firmware version'))
+
+ def validate_memory(self, mem):
+ return [chirp_common.ValidationError(
+ _('This image is read-only due to being from a radio with '
+ 'unsupported firmware'))]
+
+
+@directory.register
+class UVK1Radio(UVK5RadioBase):
+ VENDOR = "Quansheng"
+ MODEL = "UV-K1"
+
+ @classmethod
+ def k5_approve_firmware(cls, firmware):
+ # The first released OEM firmware version is 7.03.01
+ # For the moment, the driver version is limited 7.03.XX
+ # No information is available about the future firmware releases,
+ # so for safety, the versions are limited.
+ # Version management is supposed to be standardized, and only minor
+ # changes may occur in the firmware which should not break this driver.
+
+ return firmware.startswith("7.03.")
+
+ def get_features(self):
+ # The first driver version includes only memory programming,
+ # settings provided by uv-k5 base implementation are disabled
+ features = super().get_features()
+ features.has_settings = False
+
+ return features
+
+ def get_settings(self):
+ return []
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/uvk5_egzumer.py b/chirp/drivers/uvk5_egzumer.py
index 4ec5a23..f8014b5 100644
--- a/chirp/drivers/uvk5_egzumer.py
+++ b/chirp/drivers/uvk5_egzumer.py
@@ -656,11 +656,11 @@ class UVK5RadioEgzumer(uvk5.UVK5RadioBase):
_mem.AM_fix = element.value
# mic_bar
- elif elname == "mem.mic_bar":
+ elif elname == "mic_bar":
_mem.mic_bar = element.value
# Batterie txt
- elif elname == "_mem.battery_text":
+ elif elname == "battery_text":
_mem.battery_text = element.value
# Tail tone elimination
diff --git a/chirp/drivers/vgc.py b/chirp/drivers/vgc.py
index e92b1c5..09a3f20 100644
--- a/chirp/drivers/vgc.py
+++ b/chirp/drivers/vgc.py
@@ -373,6 +373,9 @@ def _rawrecv(radio, amount):
msg = "Generic error reading data from radio; check your cable."
raise errors.RadioError(msg)
+ if not data:
+ _exit_program_mode(radio)
+ raise errors.RadioNoResponse()
if len(data) != amount:
_exit_program_mode(radio)
msg = "Error reading data from radio: not the amount of data we want."
diff --git a/chirp/drivers/vx1.py b/chirp/drivers/vx1.py
new file mode 100644
index 0000000..1ff504a
--- /dev/null
+++ b/chirp/drivers/vx1.py
@@ -0,0 +1,1271 @@
+# Copyright 2026 Don Barber <don@dgb3.net>, N3LP
+#
+# 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/>.
+
+# -*- coding: utf-8 -*-
+
+# This is a CHIRP driver for the Yaesu VX-1r radio, released circa 1997.
+# Please refer to the manual for the peculiarities of this radio
+# such as the 8 bands and the difference between Configuration Group 1 and 2.
+
+# Base Device (VX-1R): Linear layout matching radio memory order
+# - Memory 1-170: All Configuration Group 2 (CG2) memories
+# - Memory 171-250: All Configuration Group 1 (CG1) memories
+# - Memory 251-260: All BC memories
+# - Global radio settings
+#
+# Sub-Device "CG1" (VX-1R CG1):
+# - Regular memories 1-52: Map to base device 179-230
+# - L/U scan limits 53-72: Map to base device 231-250 (L1/U1 through \
+# L10/U10)
+# - Home channels 73-80: Map to base device 171-178 (H-FM through \
+# H-ACT2)
+#
+# Sub-Device "CG2" (VX-1R CG2):
+# - Regular memories 1-142: Map to base device 9-150
+# - L/U scan limits 143-162: Map to base device 151-170 (L1/U1 through \
+# L10/U10)
+# - Home channels 163-170: Map to base device 1-8 (H-FM through \
+# H-ACT2)
+#
+# Sub-Device "BC" (VX-1R BC):
+# - Regular memories 1-10: Map to base device 251-260 (broadcast band \
+# presets)
+
+# The driver uses sub-devices to organize memories into logical groups.
+# Regular memories use standard numbering, while scan limits and home
+# channels appear as special channels with descriptive names.
+
+# If you find yourself with a radio that is in a state where it will not
+# accept a clone-in, try doing a factory reset. Do this by holding [M/V]
+# and [AR] as you power on the radio. When "INI? F" appears, press [FW]
+# to reset the radio.
+# This will reset all your memories; you may want to download your old
+# memories first so you can copy them over to the new fresh image.
+
+from chirp.drivers import yaesu_clone
+from chirp import chirp_common, directory, bitwise, errors
+from chirp.settings import RadioSetting, RadioSettingGroup, \
+ RadioSettingValueBoolean, RadioSettingValueList, \
+ RadioSettingValueInteger, RadioSettingValueString, RadioSettings
+import logging
+
+LOG = logging.getLogger(__name__)
+
+MEM_FORMAT = """
+#seekto 0x0000;
+// Must match radio's current active mode
+// for clone in to be accepted.
+u8 match_mode;
+
+// Mode byte with bit fields
+u8 fixed_bits:2, // Always 0xC0 (bits 7-6)
+ wide_rx:1, // bit 5
+ cellular_rx:1, // bit 4
+ wide_tx:1, // bit 3
+ country:3; // bits 2-0
+
+#seekto 0x0002;
+u8 band;
+
+#seekto 0x0007;
+u8 ars:1, atmd:1, resume:1, scnl:1, beep:1, bclo:1, bsyled:1, unknown0:1;
+u8 rxsave:3, apo:3, lamp:2;
+u8 bell:3, unknown1a:1, lock:3, lk:1;
+u8 montc:1, dialm:1, tot:3, smtmd:1, artsbp:2;
+u8 unknown2a:1, cwid:1, grp:1, unknown2b:5;
+
+#seekto 0x000e;
+u8 dtmfm:4, unknown3:4;
+
+#seekto 0x000f;
+u8 volume;
+u8 squelch;
+
+#seekto 0x0011;
+struct {
+ lbcd rx_freq[3];
+ lbcd offset[3];
+ u8 skip:1,
+ name_flag:1, // 0=display frequency, 1=display alpha name
+ mode:2,
+ shift:2,
+ selcal:2;
+ u8 unknown:3,
+ power:1,
+ clk_shift:1,
+ step:3;
+ u8 unknown2:2,
+ ctcss:6;
+ u8 dcs;
+ u8 name[6];
+} current;
+
+#seekto 0x00a0;
+u8 checksum1;
+
+#seekto 0x00f1;
+struct {
+ lbcd rx_freq[3];
+ lbcd offset[3];
+ u8 skip:1,
+ name_flag:1, // 0=display frequency, 1=display alpha name
+ mode:2,
+ shift:2,
+ selcal:2;
+ u8 unknown:3,
+ power:1,
+ clk_shift:1,
+ step:3;
+ u8 unknown2:2,
+ ctcss:6;
+ u8 dcs;
+ u8 name[6];
+} smart_search[31];
+
+#seekto 0x02f1;
+u8 cwid_text[9]; // 8 chars max + stop byte (0x3d)
+
+#seekto 0x0311;
+struct {
+ u8 freq[2];
+ u8 name[6]; // BC VFO has 6-byte name like other memories
+} bc_vfo;
+
+#seekto 0x0321;
+struct {
+ lbcd rx_freq[3];
+ lbcd offset[3];
+ u8 skip:1,
+ name_flag:1, // 0=display frequency, 1=display alpha name
+ mode:2,
+ shift:2,
+ selcal:2;
+ u8 unknown:3,
+ power:1,
+ clk_shift:1,
+ step:3;
+ u8 unknown2:2,
+ ctcss:6;
+ u8 dcs;
+ u8 name[6];
+} vfos[8];
+
+#seekto 0x03a1;
+u8 priority_channel;
+
+#seekto 0x03d1;
+struct {
+ lbcd rx_freq[3];
+ u8 unknown;
+ u8 skip:1,
+ name_flag:1, // 0=display frequency, 1=display alpha name
+ mode:2,
+ shift:2,
+ selcal:2;
+ u8 unknown2:3,
+ power:1,
+ clk_shift:1,
+ step:3;
+ u8 name[6];
+} cg2_memory[170];
+
+#seekto 0x0bd1;
+struct {
+ lbcd rx_freq[3];
+ lbcd offset[3];
+ u8 skip:1,
+ name_flag:1, // 0=display frequency, 1=display alpha name
+ mode:2,
+ shift:2,
+ selcal:2;
+ u8 unknown:3,
+ power:1,
+ clk_shift:1,
+ step:3;
+ u8 unknown2:2,
+ ctcss:6;
+ u8 dcs;
+ u8 name[6];
+} cg1_memory[80];
+
+#seekto 0x10d1;
+lbit band_mask[2048]; // Interleaved CG2 and CG1 band masks
+ // (little-endian bits)
+
+#seekto 0x11f1;
+struct {
+ u8 freq[2]; // BC band uses different frequency encoding
+ u8 name[6]; // BC band has 6-byte name like other memories
+} bc_memory[10];
+
+#seekto 0x1251;
+struct {
+ u8 dtmf[16];
+} autodialer[8];
+
+#seekto 0x12d1;
+u8 checksum2;
+"""
+
+# Band frequency ranges (in Hz)
+BAND_RANGES = [
+ (76000000, 108000000, 0), # FM broadcast
+ (108000000, 137000000, 1), # AIR
+ (137000000, 170000000, 2), # V-HAM
+ (170000000, 222000000, 3), # VHF-TV
+ (222000000, 420000000, 4), # ACT1
+ (420000000, 470000000, 5), # U-HAM
+ (470000000, 800000000, 6), # UHF-TV
+ (800000000, 999000000, 7), # ACT2
+]
+
+# VX-1R: FM-N=FM (12.5kHz), FM-W=WFM (broadcast), AM
+MODES = ["FM", "WFM", "AM"]
+TMODES = ["", "Tone", "TSQL", "DTCS"]
+DUPLEX = ["", "-", "+", "split"]
+STEPS = [5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0, 100.0]
+# Power levels stated are when plugged in.
+# When not plugged in, these become .5 and .05, respectively.
+POWER_LEVELS = [chirp_common.PowerLevel("Lo", watts=0.2),
+ chirp_common.PowerLevel("Hi", watts=1)]
+# Base device uses linear memory layout with no special channels
+SPECIALS = ()
+
+# VX-1R character set
+VX1_CHARSET = (
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ ()+-=*/ΔΥΣ|-?%&_$¥\\﹨<>█∪⌋▆")
+
+# DTMF character set
+DTMF_CHARSET = "0123456789ABCD*#"
+
+
+def _decode_dtmf(mem):
+ """Decode 16-byte DTMF memory to string"""
+ dtmf = ""
+ for i in range(16):
+ byte = mem[i]
+ if byte == 0x3d: # Stop byte
+ break
+ if byte == 0x28: # Pause
+ dtmf += "-"
+ elif byte < len(DTMF_CHARSET):
+ dtmf += DTMF_CHARSET[byte]
+ return dtmf
+
+
+def _encode_dtmf(dtmf_str):
+ """Encode string to 16-byte DTMF memory"""
+ encoded = []
+ for i in range(16):
+ if i < len(dtmf_str):
+ char = dtmf_str[i].upper()
+ if char == '-':
+ encoded.append(0x28)
+ elif char in DTMF_CHARSET:
+ encoded.append(DTMF_CHARSET.index(char))
+ else:
+ encoded.append(0x3d) # Invalid = stop
+ break
+ else:
+ encoded.append(0x3d) # Stop byte
+ return encoded
+
+
+def _decode_name(mem):
+ """Decode 6-byte VX-1R name to string"""
+ name = ""
+ for i in range(6):
+ if mem[i] == 0x3f:
+ break
+ if mem[i] < len(VX1_CHARSET):
+ name += VX1_CHARSET[mem[i]]
+ else:
+ name += " "
+ return name.rstrip()
+
+
+def _decode_cwid(mem):
+ """Decode 9-byte CW ID to string, stop byte is 0x3d"""
+ name = ""
+ for i in range(9):
+ if mem[i] == 0x3d: # Stop byte for CW ID
+ break
+ if mem[i] < len(VX1_CHARSET):
+ name += VX1_CHARSET[mem[i]]
+ else:
+ name += " "
+ return name.rstrip()
+
+
+def _encode_cwid(name):
+ """Encode string to 9-byte CW ID, max 8 chars, stop byte is 0x3d"""
+ encoded = []
+ name = name[:8] # Limit to 8 characters
+
+ # Encode the name characters
+ for char in name:
+ char = char.upper()
+ try:
+ encoded.append(VX1_CHARSET.index(char))
+ except ValueError:
+ encoded.append(VX1_CHARSET.index('_')) # Unknown = underscore
+
+ # Add stop byte
+ encoded.append(0x3d)
+
+ # Pad to 9 bytes with zeros
+ while len(encoded) < 9:
+ encoded.append(0x00)
+
+ return encoded
+
+
+def _encode_name(name, length=6):
+ """Encode string to VX-1R name (default 6 bytes, or specify length)"""
+ encoded = []
+ for i in range(length):
+ if i < len(name):
+ char = name[i].upper()
+ try:
+ encoded.append(VX1_CHARSET.index(char))
+ except ValueError:
+ # Unknown = underscore
+ encoded.append(VX1_CHARSET.index('_'))
+ else:
+ encoded.append(0x3f) # Empty/padding
+ return encoded
+
+
+class VX1Checksum(yaesu_clone.YaesuChecksum):
+ """VX-1R Checksum at 0x12d1: (-sum) & 0xff"""
+
+ def get_calculated(self, mmap):
+ mmap = self._asbytes(mmap)
+ cs = 0
+ for i in range(self._start, self._stop + 1):
+ cs += mmap[i][0]
+ result = (-cs) & 0xff
+ return result
+
+
+class VX1Checksum2(yaesu_clone.YaesuChecksum):
+ """VX-1R Checksum at 0x00a0: sum & 0xff"""
+
+ def get_calculated(self, mmap):
+ mmap = self._asbytes(mmap)
+ cs = 0
+ for i in range(self._start, self._stop + 1):
+ cs += mmap[i][0]
+ result = cs & 0xff
+ return result
+
+
+@directory.register
+class VX1Radio(yaesu_clone.YaesuCloneModeRadio):
+ """Yaesu VX-1R"""
+ BAUD_RATE = 9600
+ VENDOR = "Yaesu"
+ MODEL = "VX-1"
+ VARIANT = ""
+
+ _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
+
+ # VX-1R uses 0x21 instead of standard 0x06 ACK
+ _cmd_ack = 0x21
+
+ def _checksums(self):
+ return [VX1Checksum2(0x0001, 0x009f, 0x00a0),
+ VX1Checksum(0x0001, 0x12d0, 0x12d1)]
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.pre_download = _(
+ "1. Turn radio off.\n"
+ "2. Connect cable to MIC/SP jack.\n"
+ "3. Press and hold [FW] while turning radio on to put into "
+ "CLONE mode.\n"
+ "4. Press OK on chirp prompt.\n"
+ "5. <b>After clicking OK</b>, press the [DWN] button on radio "
+ "to send image. The radio will say CLN OUT while downloading.\n")
+ rp.pre_upload = _(
+ "1. Turn radio off.\n"
+ "2. Connect cable to MIC/SP jack.\n"
+ "3. Press and hold [FW] while turning radio on to put into "
+ "CLONE mode.\n"
+ "4. Press [UP] button on radio. The radio will say CLN IN.\n"
+ "5. <b>After radio says CLN IN</b>, press OK on chirp prompt "
+ "to upload.\n")
+ return rp
+
+ def sync_out(self):
+
+ # 9600 8N1 baud for 4818 bytes = 5.02 seconds
+ self.pipe.timeout = 7
+ try:
+ return super().sync_out()
+ except Exception as e:
+ # Some firmware versions of the VX1 seem to put out extra
+ # 0x00 bytes before sending the ack byte.
+ # I suspect these were processing debug statements left in by
+ # accident and removed in later firmwares.
+ if "Radio did not ack block" in str(e):
+ buf = self.pipe.read(1)
+ if buf and buf[0] == self._cmd_ack:
+ status = chirp_common.Status()
+ status.msg = "Cloning to radio"
+ status.max = 100
+ status.cur = 100
+ self.status_fn(status)
+ return
+ raise
+
+ def _get_band_index(self, freq):
+ """Determine which band a frequency belongs to"""
+ for low, high, band_idx in BAND_RANGES:
+ if low <= freq < high:
+ return band_idx
+ return None
+
+ def _get_extra(self, _mem, mem):
+ """Get extra settings for memory"""
+ # Always create RadioSettingGroup to override default empty list
+ mem.extra = RadioSettingGroup("extra", "Extra")
+
+ # Display mode (frequency vs alpha name)
+ if hasattr(_mem, 'name_flag'):
+ rs = RadioSetting("name_flag", "Display Mode",
+ RadioSettingValueList(
+ ["Frequency", "Alpha Name"],
+ current_index=_mem.name_flag))
+ mem.extra.append(rs)
+
+ # Only CG1 and CG2 have clk_shift
+ if hasattr(_mem, 'clk_shift'):
+ rs = RadioSetting("clk_shift", "Clock Shift",
+ RadioSettingValueBoolean(_mem.clk_shift))
+ mem.extra.append(rs)
+
+ def _set_extra(self, _mem, mem):
+ """Set extra settings for memory"""
+ if mem.extra and hasattr(mem.extra, '__iter__'):
+ for setting in mem.extra:
+ if hasattr(_mem, setting.get_name()):
+ setattr(_mem, setting.get_name(), setting.value)
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_bank = False
+ rf.has_ctone = False
+ rf.has_dtcs_polarity = False
+ rf.has_settings = True
+ rf.has_sub_devices = self.VARIANT == ""
+ rf.valid_modes = MODES
+ rf.valid_tmodes = TMODES
+ rf.valid_tuning_steps = STEPS
+ rf.valid_duplexes = DUPLEX
+ rf.valid_tones = list(chirp_common.OLD_TONES)
+ rf.memory_bounds = (1, 260) # Linear: CG1(80) + CG2(170) + BC(10)
+ rf.valid_bands = [(500000, 999000000)]
+ rf.valid_skips = ["", "S"]
+ rf.valid_power_levels = POWER_LEVELS
+ rf.valid_name_length = 6
+ rf.valid_characters = VX1_CHARSET
+ rf.valid_special_chans = SPECIALS
+ rf.can_odd_split = True
+ return rf
+
+ def get_sub_devices(self):
+ return [VX1RadioCG1(self._mmap), VX1RadioCG2(self._mmap),
+ VX1RadioBC(self._mmap)]
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+
+ def get_settings(self):
+ _settings = self._memobj
+
+ basic = RadioSettingGroup("basic", "Basic")
+ top = RadioSettings(basic)
+
+ # Match mode byte
+ # The radio needs this to match the current mode of the radio,
+ # which can be seen as bytes 0 and 1 of a clone in.
+ val = RadioSettingValueString(
+ 2, 2, f"{int(_settings.match_mode):02X}", autopad=False,
+ charset="0123456789ABCDEFabcdef")
+ val.set_mutable(False)
+ rs = RadioSetting("match_mode", "Match Mode", val)
+ rs.set_doc("The radio will only accept this image if this byte "
+ "matches its current settings. If the radio resets to "
+ "CLONE on first byte received during CLONE IN, then "
+ "instead download a new fresh image from the radio "
+ "and copy the needed memories into that.")
+ basic.append(rs)
+
+ # Region/TX expansion mode
+ val = RadioSettingValueList(
+ ["FreeBand", "UK", "Unknown (2)", "USA", "Unknown (4)",
+ "Germany", "Europe", "Unknown (7)"],
+ current_index=int(_settings.country))
+ val.set_mutable(False)
+ rs = RadioSetting("country", "Country", val)
+ # If you know what country codes 2, 4, or 7 represent, either
+ # contact me or submit a pull request.
+ rs.set_doc("This is read only as modifying it can cause the radio "
+ "to reject future clone-ins.")
+ basic.append(rs)
+
+ val = RadioSettingValueBoolean(bool(_settings.wide_tx))
+ val.set_mutable(False)
+ rs = RadioSetting("wide_tx", "Wide TX", val)
+ rs.set_doc("This is read only as modifying it can cause the radio "
+ "to reject future clone-ins.")
+ basic.append(rs)
+
+ val = RadioSettingValueBoolean(bool(_settings.cellular_rx))
+ val.set_mutable(False)
+ rs = RadioSetting("cellular_rx", "Cellular RX", val)
+ rs.set_doc("This is read only as modifying it can cause the radio "
+ "to reject future clone-ins.")
+ basic.append(rs)
+
+ val = RadioSettingValueBoolean(bool(_settings.wide_rx))
+ val.set_mutable(False)
+ rs = RadioSetting("wide_rx", "Wide RX", val)
+ rs.set_doc("This is read only as modifying it can cause the radio "
+ "to reject future clone-ins.")
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "band", "Current Band",
+ RadioSettingValueList(
+ ["BCBAND", "FM", "AIR", "VHF-HAM", "VHF-TV", "ACT1",
+ "UHF-HAM", "UHF-TV", "ACT2"],
+ current_index=_settings.band))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "apo", "Auto Power Off",
+ RadioSettingValueList(
+ ["Off", "30min", "1hr", "3hr", "5hr", "8hr"],
+ current_index=_settings.apo))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "ars", "Auto Repeater Shift",
+ RadioSettingValueBoolean(_settings.ars))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "atmd", "Auto Mode",
+ RadioSettingValueBoolean(_settings.atmd))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "artsbp", "ARTS Beep",
+ RadioSettingValueList(
+ ["Off", "In Range", "All"],
+ current_index=_settings.artsbp))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "beep", "Keypad Beep",
+ RadioSettingValueBoolean(_settings.beep))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "bclo", "Busy Channel Lockout",
+ RadioSettingValueBoolean(_settings.bclo))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "bell", "Bell",
+ RadioSettingValueList(
+ ["Off", "1 Ring", "3 Ring", "5 Ring", "8 Ring", "Repeat"],
+ current_index=_settings.bell))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "bsyled", "Busy LED",
+ RadioSettingValueBoolean(_settings.bsyled))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "cwid", "CW ID",
+ RadioSettingValueBoolean(_settings.cwid))
+ basic.append(rs)
+
+ # CW ID text (8 characters max, 9th byte is stop byte)
+ cwid_str = _decode_cwid(_settings.cwid_text)
+ rs = RadioSetting(
+ "cwid_text", "CW ID Text",
+ RadioSettingValueString(0, 8, cwid_str, autopad=False))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "dialm", "Dial Mode",
+ RadioSettingValueList(
+ ["Frequency", "Volume/Squelch"],
+ current_index=_settings.dialm))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "grp", "Configuration Group",
+ RadioSettingValueList(
+ ["Group 1", "Group 2"],
+ current_index=_settings.grp))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "priority_channel", "Priority Channel",
+ RadioSettingValueInteger(1, 250, _settings.priority_channel))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "lamp", "Lamp",
+ RadioSettingValueList(
+ ["Key", "5 sec", "Toggle"],
+ current_index=_settings.lamp))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "lk", "Lock",
+ RadioSettingValueBoolean(_settings.lk))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "lock", "Lock Mode",
+ RadioSettingValueList(
+ ["Off", "Key", "Dial", "Key+Dial", "PTT",
+ "Key+PTT", "Dial+PTT", "All"],
+ current_index=_settings.lock))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "montc", "Monitor/TCall",
+ RadioSettingValueList(
+ ["Monitor", "Tone Calling"],
+ current_index=_settings.montc))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "resume", "Scan Resume",
+ RadioSettingValueList(
+ ["5 Second Hold", "Carrier Drop"],
+ current_index=_settings.resume))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "rxsave", "RX Battery Save",
+ RadioSettingValueList(
+ ["Off", "0.2s", "0.3s", "0.5s", "1s", "2s"],
+ current_index=_settings.rxsave))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "scnl", "Scan Lamp",
+ RadioSettingValueBoolean(_settings.scnl))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "smtmd", "Smart Search",
+ RadioSettingValueList(
+ ["Single", "Continuous"],
+ current_index=_settings.smtmd))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "tot", "Time-Out Timer",
+ RadioSettingValueList(
+ ["Off", "1min", "2min", "5min", "10min"],
+ current_index=_settings.tot))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "dtmfm", "DTMF Memory",
+ RadioSettingValueList(
+ ["DTMF-1", "DTMF-2", "DTMF-3", "DTMF-4", "DTMF-5",
+ "DTMF-6", "DTMF-7", "DTMF-8"],
+ current_index=_settings.dtmfm))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "volume", "Volume",
+ RadioSettingValueInteger(0, 31, _settings.volume))
+ basic.append(rs)
+
+ rs = RadioSetting(
+ "squelch", "Squelch",
+ RadioSettingValueList(
+ ["Auto", "Open", "1", "2", "3", "4", "5", "6", "7", "8",
+ "9", "10"],
+ current_index=_settings.squelch))
+ basic.append(rs)
+
+ # DTMF autodialer memories
+ dtmf = RadioSettingGroup("dtmf", "DTMF Autodialer")
+ top.append(dtmf)
+
+ for i in range(8):
+ dtmf_str = _decode_dtmf(_settings.autodialer[i].dtmf)
+ rs = RadioSetting(
+ "autodialer_%d" % i, "DTMF-%d" % (i + 1),
+ RadioSettingValueString(0, 16, dtmf_str, False,
+ 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
+ try:
+ if element.get_name() == "match_mode":
+ self._memobj.match_mode = \
+ int(element.value.get_value(), 16)
+ elif element.get_name() == "cwid_text":
+ self._memobj.cwid_text = _encode_cwid(str(element.value))
+ elif element.get_name().startswith("autodialer_"):
+ idx = int(element.get_name().split("_")[1])
+ self._memobj.autodialer[idx].dtmf = \
+ _encode_dtmf(str(element.value))
+ else:
+ setattr(self._memobj, element.get_name(), element.value)
+ except Exception:
+ LOG.debug(element.get_name())
+ raise
+
+ # Mirror configuration data from 0x1-0x11 to 0x301-0x310
+ for i in range(1, 0x11): # 16 bytes (0x1 through 0x10)
+ self._mmap[0x300 + i] = self._mmap[i]
+
+
+class VX1RadioCG1(VX1Radio):
+ """VX-1R Configuration Group 1"""
+ VARIANT = "CG1"
+
+ # Regular memories, then L/U pairs, then home channels
+ SPECIAL_MEMORIES = {
+ "L1": 53, "U1": 54,
+ "L2": 55, "U2": 56,
+ "L3": 57, "U3": 58,
+ "L4": 59, "U4": 60,
+ "L5": 61, "U5": 62,
+ "L6": 63, "U6": 64,
+ "L7": 65, "U7": 66,
+ "L8": 67, "U8": 68,
+ "L9": 69, "U9": 70,
+ "L10": 71, "U10": 72,
+ "H-FM": 73,
+ "H-AIR": 74,
+ "H-V-HAM": 75,
+ "H-VHF-TV": 76,
+ "H-ACT1": 77,
+ "H-U-HAM": 78,
+ "H-UHF-TV": 79,
+ "H-ACT2": 80,
+ }
+ SPECIAL_MEMORIES_REV = dict(
+ zip(SPECIAL_MEMORIES.values(), SPECIAL_MEMORIES.keys()))
+
+ def get_features(self):
+ rf = super().get_features()
+ rf.has_sub_devices = False
+ rf.has_settings = False
+ # 52 regular memories to make room for 20 L/U
+ rf.memory_bounds = (1, 52)
+ rf.valid_special_chans = list(self.SPECIAL_MEMORIES.keys())
+ rf.valid_bands = [(1700000, 999000000)] # CG1: 1.7 MHz - 999 MHz
+ return rf
+
+ def get_memory(self, number):
+ is_string = isinstance(number, str)
+ if is_string:
+ # Special channel by name - convert to number
+ number = self.SPECIAL_MEMORIES[number]
+
+ if number <= 72:
+ # Regular and L/U memories: 1-72 map to cg1_idx 8-79
+ cg1_idx = number + 7
+ else:
+ # Home channels: 73-80 map to cg1_idx 0-7
+ cg1_idx = number - 73
+
+ # Handle CG1 memory structure directly
+ _mem = self._memobj.cg1_memory[cg1_idx]
+
+ mem = chirp_common.Memory()
+ mem.number = number
+ if is_string or number > 52:
+ mem.extd_number = self.SPECIAL_MEMORIES_REV[number]
+
+ # Check if memory is empty
+ if isinstance(_mem.get_raw()[0], int):
+ first_byte = _mem.get_raw()[0]
+ else:
+ first_byte = ord(_mem.get_raw()[0])
+
+ if first_byte == 0xff:
+ mem.empty = True
+ self._get_extra(_mem, mem)
+ return mem
+
+ try:
+ mem.freq = chirp_common.fix_rounded_step(int(_mem.rx_freq) * 1000)
+ except errors.InvalidDataError:
+ mem.freq = int(_mem.rx_freq) * 1000
+ mem.name = _decode_name(_mem.name)
+ mem.mode = MODES[_mem.mode] if _mem.mode < len(MODES) else MODES[0]
+ mem.skip = "S" if _mem.skip else ""
+ mem.power = POWER_LEVELS[_mem.power]
+ mem.tuning_step = STEPS[_mem.step]
+
+ # CG1 has offset/tone fields
+ mem.duplex = DUPLEX[_mem.shift]
+ mem.offset = int(_mem.offset) * 1000
+ mem.tmode = TMODES[_mem.selcal] if _mem.selcal < len(
+ TMODES) else ""
+ if mem.tmode and mem.tmode != "":
+ if _mem.ctcss < len(chirp_common.OLD_TONES):
+ mem.rtone = mem.ctone = chirp_common.OLD_TONES[_mem.ctcss]
+ if _mem.dcs < len(chirp_common.DTCS_CODES):
+ mem.dtcs = chirp_common.DTCS_CODES[_mem.dcs]
+
+ self._get_extra(_mem, mem)
+
+ # Default clk_shift to disabled for CG1 memories
+ if hasattr(mem, 'extra') and mem.extra:
+ for setting in mem.extra:
+ if (setting.get_name() == 'clk_shift' and
+ setting.value is not False):
+ setting.value = False # Force to disabled
+
+ return mem
+
+ def set_memory(self, mem):
+ number = mem.number
+ if isinstance(number, str):
+ # Convert string to number
+ number = self.SPECIAL_MEMORIES[mem.number]
+
+ # Map CG1 subdevice number to cg1_idx
+ if number <= 72:
+ # Regular and L/U memories: 1-72 map to cg1_idx 8-79
+ cg1_idx = number + 7
+ else:
+ # Home channels: 73-80 map to cg1_idx 0-7
+ cg1_idx = number - 73
+
+ # Handle CG1 memory structure directly
+ _mem = self._memobj.cg1_memory[cg1_idx]
+
+ if mem.empty:
+ # Set only first byte to 0xff for empty memory
+ offset = 0x0bd1 + cg1_idx * 16
+ self._mmap[offset] = 0xff
+ return
+
+ _mem.rx_freq = int(mem.freq / 1000)
+ _mem.name = _encode_name(mem.name)
+ _mem.mode = MODES.index(mem.mode)
+ _mem.skip = 1 if mem.skip == "S" else 0
+ _mem.power = POWER_LEVELS.index(mem.power) if mem.power else 1
+ _mem.step = STEPS.index(mem.tuning_step)
+
+ # Set defaults
+ _mem.clk_shift = 0
+ _mem.name_flag = 1 if mem.name else 0
+
+ # Set extra fields (may override defaults)
+ self._set_extra(_mem, mem)
+
+ # CG1 has offset/tone fields
+ _mem.shift = DUPLEX.index(mem.duplex)
+ _mem.offset = mem.offset / 1000
+ _mem.selcal = TMODES.index(mem.tmode)
+ try:
+ _mem.ctcss = chirp_common.OLD_TONES.index(mem.rtone)
+ except ValueError:
+ _mem.ctcss = 0
+ try:
+ _mem.dcs = chirp_common.DTCS_CODES.index(mem.dtcs)
+ except ValueError:
+ _mem.dcs = 0
+
+ # Update band mask for CG1 memory (skip home channels)
+ if cg1_idx >= 8: # Only update band mask for non-home channels
+ band_idx = self._get_band_index(mem.freq)
+ if band_idx is not None:
+ # CG1 band mask: offset by 176 bits (22 bytes) from CG2,
+ # +8 to skip band byte
+ base_offset = 176 + 8
+ adjusted_idx = cg1_idx - 8
+ for b in range(8):
+ bit_idx = base_offset + b * 256 + adjusted_idx
+ if b == band_idx:
+ self._memobj.band_mask[bit_idx] = 1
+ else:
+ self._memobj.band_mask[bit_idx] = 0
+
+ def erase_memory(self, number):
+ # Map CG1 subdevice number to cg1_idx
+ if number <= 72:
+ cg1_idx = number + 7
+ else:
+ cg1_idx = number - 73
+
+ offset = 0x0bd1 + cg1_idx * 16
+ self._mmap[offset] = 0xff
+
+ # Clear band mask for CG1 memory (skip home channels)
+ if cg1_idx >= 8: # Only clear band mask for non-home channels
+ base_offset = 176 + 8
+ adjusted_idx = cg1_idx - 8
+ for b in range(8):
+ bit_idx = base_offset + b * 256 + adjusted_idx
+ self._memobj.band_mask[bit_idx] = 0
+
+
+class VX1RadioCG2(VX1Radio):
+ """VX-1R Configuration Group 2"""
+ VARIANT = "CG2"
+
+ # Regular memories, then L/U pairs, then home channels
+ SPECIAL_MEMORIES = {
+ "L1": 143, "U1": 144,
+ "L2": 145, "U2": 146,
+ "L3": 147, "U3": 148,
+ "L4": 149, "U4": 150,
+ "L5": 151, "U5": 152,
+ "L6": 153, "U6": 154,
+ "L7": 155, "U7": 156,
+ "L8": 157, "U8": 158,
+ "L9": 159, "U9": 160,
+ "L10": 161, "U10": 162,
+ "H-FM": 163,
+ "H-AIR": 164,
+ "H-V-HAM": 165,
+ "H-VHF-TV": 166,
+ "H-ACT1": 167,
+ "H-U-HAM": 168,
+ "H-UHF-TV": 169,
+ "H-ACT2": 170,
+ }
+ SPECIAL_MEMORIES_REV = dict(
+ zip(SPECIAL_MEMORIES.values(), SPECIAL_MEMORIES.keys()))
+
+ def get_features(self):
+ rf = super().get_features()
+ rf.has_sub_devices = False
+ rf.has_settings = False
+ # 142 regular memories to make room for 20 L/U
+ rf.memory_bounds = (1, 142)
+ rf.valid_special_chans = list(self.SPECIAL_MEMORIES.keys())
+ # CG2 memories support standard repeater shifts but not custom offsets
+ rf.has_offset = False # No custom offset amounts
+ rf.valid_duplexes = ["", "-", "+"] # Standard repeater shifts only
+ rf.can_odd_split = False # No split mode (no offset field)
+ rf.valid_bands = [(1700000, 999000000)] # CG2: 1.7 MHz - 999 MHz
+ # CG2 supports tone modes but not custom tone frequencies
+ rf.valid_tmodes = TMODES
+ rf.has_ctone = False
+ rf.has_dtcs = False
+ rf.valid_tones = [] # Hide tone frequency columns
+ rf.valid_dtcs_codes = [] # Hide DTCS code columns
+ return rf
+
+ def get_memory(self, number):
+ is_string = isinstance(number, str)
+ if is_string:
+ # Special channel by name - convert to number
+ number = self.SPECIAL_MEMORIES[number]
+
+ if number <= 162:
+ # Regular and L/U memories: 1-162 map to cg2_idx 8-169
+ cg2_idx = number + 7
+ else:
+ # Home channels: 163-170 map to cg2_idx 0-7
+ cg2_idx = number - 163
+
+ # Handle CG2 memory structure directly
+ _mem = self._memobj.cg2_memory[cg2_idx]
+
+ mem = chirp_common.Memory()
+ mem.number = number
+ if is_string or number > 142:
+ mem.extd_number = self.SPECIAL_MEMORIES_REV[number]
+
+ # Check if memory is empty
+ if isinstance(_mem.get_raw()[0], int):
+ first_byte = _mem.get_raw()[0]
+ else:
+ first_byte = ord(_mem.get_raw()[0])
+
+ if first_byte == 0xff:
+ mem.empty = True
+ self._get_extra(_mem, mem)
+ return mem
+
+ try:
+ mem.freq = chirp_common.fix_rounded_step(int(_mem.rx_freq) * 1000)
+ except errors.InvalidDataError:
+ mem.freq = int(_mem.rx_freq) * 1000
+ mem.name = _decode_name(_mem.name)
+ mem.mode = MODES[_mem.mode] if _mem.mode < len(MODES) else MODES[0]
+ mem.skip = "S" if _mem.skip else ""
+ mem.power = POWER_LEVELS[_mem.power]
+ mem.tuning_step = STEPS[_mem.step]
+
+ # CG2 has duplex field but no offset field (uses standard repeater
+ # shifts)
+ mem.duplex = DUPLEX[_mem.shift] if _mem.shift < len(DUPLEX) else ""
+ # Calculate standard repeater offset based on frequency and duplex
+ if mem.duplex in ["-", "+"]:
+ if mem.freq >= 420000000: # UHF band
+ mem.offset = 5000000 # 5 MHz
+ elif mem.freq >= 144000000: # VHF band
+ mem.offset = 600000 # 600 kHz
+ else:
+ mem.offset = 0
+ else:
+ mem.offset = 0
+ mem.tmode = TMODES[_mem.selcal] if _mem.selcal < len(TMODES) else ""
+
+ self._get_extra(_mem, mem)
+
+ return mem
+
+ def set_memory(self, mem):
+ if isinstance(mem.number, str):
+ # Convert string to number
+ number = self.SPECIAL_MEMORIES[mem.number]
+ else:
+ number = mem.number
+
+ # Map CG2 subdevice number to cg2_idx
+ if number <= 162:
+ # Regular and L/U memories: 1-162 map to cg2_idx 8-169
+ cg2_idx = number + 7
+ else:
+ # Home channels: 163-170 map to cg2_idx 0-7
+ cg2_idx = number - 163
+
+ # Handle CG2 memory structure directly
+ _mem = self._memobj.cg2_memory[cg2_idx]
+
+ if mem.empty:
+ # Set only first byte to 0xff for empty memory
+ offset = 0x03d1 + cg2_idx * 12
+ self._mmap[offset] = 0xff
+ return
+
+ _mem.rx_freq = int(mem.freq / 1000)
+ _mem.name = _encode_name(mem.name)
+ _mem.mode = MODES.index(mem.mode)
+ _mem.skip = 1 if mem.skip == "S" else 0
+ _mem.power = POWER_LEVELS.index(mem.power) if mem.power else 1
+ _mem.step = STEPS.index(mem.tuning_step)
+
+ # Set defaults
+ _mem.clk_shift = 0
+ _mem.name_flag = 1 if mem.name else 0
+
+ # Set extra fields (may override defaults)
+ self._set_extra(_mem, mem)
+
+ # CG2 supports standard repeater shifts
+ _mem.shift = DUPLEX.index(mem.duplex) if mem.duplex in DUPLEX else 0
+ _mem.selcal = TMODES.index(mem.tmode) if mem.tmode in TMODES else 0
+
+ # Update band mask for CG2 memory (skip home channels)
+ if cg2_idx >= 8: # Only update band mask for non-home channels
+ band_idx = self._get_band_index(mem.freq)
+ if band_idx is not None:
+ # CG2 band mask: base offset +8 to skip band byte
+ base_offset = 8
+ adjusted_idx = cg2_idx - 8
+ for b in range(8):
+ bit_idx = base_offset + b * 256 + adjusted_idx
+ if b == band_idx:
+ self._memobj.band_mask[bit_idx] = 1
+ else:
+ self._memobj.band_mask[bit_idx] = 0
+
+ def erase_memory(self, number):
+ # Map CG2 subdevice number to cg2_idx
+ if number <= 162:
+ cg2_idx = number + 7
+ else:
+ cg2_idx = number - 163
+
+ offset = 0x03d1 + cg2_idx * 12
+ self._mmap[offset] = 0xff
+
+ # Clear band mask for CG2 memory (skip home channels)
+ if cg2_idx >= 8: # Only clear band mask for non-home channels
+ base_offset = 8
+ adjusted_idx = cg2_idx - 8
+ for b in range(8):
+ bit_idx = base_offset + b * 256 + adjusted_idx
+ self._memobj.band_mask[bit_idx] = 0
+
+ def validate_memory(self, mem):
+ msgs = super().validate_memory(mem)
+
+ # CG2 supports tone modes but not custom tone frequencies
+ if mem.tmode in ("Tone", "TSQL"):
+ if mem.rtone != 88.5:
+ msgs.append(chirp_common.ValidationWarning(
+ "CG2 does not support custom tone frequencies"))
+ if mem.ctone != 88.5:
+ msgs.append(chirp_common.ValidationWarning(
+ "CG2 does not support custom tone frequencies"))
+
+ return msgs
+
+
+class VX1RadioBC(VX1Radio):
+ """VX-1R Broadcast Band"""
+ VARIANT = "BC"
+
+ def get_features(self):
+ rf = super().get_features()
+ rf.has_sub_devices = False
+ rf.has_settings = False
+ rf.memory_bounds = (1, 10) # 10 memories (no separate home channel)
+ rf.valid_special_chans = []
+ # BC band is AM-only with no advanced features
+ rf.valid_modes = ["AM"]
+ rf.has_offset = False
+ rf.has_ctone = False
+ rf.has_dtcs = False
+ rf.valid_duplexes = [""]
+ rf.valid_tmodes = [""]
+ rf.valid_tones = []
+ rf.valid_dtcs_codes = []
+ rf.valid_skips = [""]
+ rf.can_odd_split = False # BC doesn't support any duplex modes
+ rf.valid_bands = [(500000, 1700000)] # BC band: 0.5-1.7 MHz
+ return rf
+
+ def get_memory(self, number):
+ # BC sub-device: memory 1-10 maps to base device 251-260
+ base_number = number + 250
+
+ # Handle BC memory structure directly
+ bc_idx = base_number - 251
+ _mem = self._memobj.bc_memory[bc_idx]
+
+ mem = chirp_common.Memory()
+ mem.number = number
+
+ # Check if memory is empty
+ first_byte = _mem.freq[0]
+ if first_byte == 0xff:
+ mem.empty = True
+ return mem
+
+ # BC band memories use special frequency encoding
+ freq_mhz = 0.5 + (_mem.freq[0] * (1.2 / 254.0))
+ mem.freq = int(freq_mhz * 1000000 + 0.5)
+ mem.name = _decode_name(_mem.name)
+ mem.mode = "AM"
+ mem.skip = ""
+ mem.power = POWER_LEVELS[0]
+ # Always display 5.0 kHz step (STEPS[0]) for UI consistency
+ mem.tuning_step = 5.0
+ mem.duplex = ""
+ mem.offset = 0
+
+ return mem
+
+ def set_memory(self, mem):
+ # BC sub-device: memory 1-10 maps to base device 251-260
+ base_number = mem.number + 250
+ bc_idx = base_number - 251
+ _mem = self._memobj.bc_memory[bc_idx]
+
+ if mem.empty:
+ # Set only first byte to 0xff for empty memory
+ _mem.freq[0] = 0xff
+ return
+
+ # BC band memories use special frequency encoding
+ freq_mhz = mem.freq / 1000000.0
+ byte_val = int((freq_mhz - 0.5) / (1.2 / 254.0) + 0.5)
+ byte_val = min(max(byte_val, 0), 0xfe)
+ _mem.freq[0] = byte_val
+ _mem.freq[1] = 0x40 # Set tuning step to 0x40
+
+ _mem.name = _encode_name(mem.name)
+ # BC band is always AM mode, no other fields to set
+
+ def erase_memory(self, number):
+ # BC sub-device: memory 1-10 maps to base device 251-260
+ base_number = number + 250
+ bc_idx = base_number - 251
+ offset = 0x11f1 + bc_idx * 8
+ self._mmap[offset] = 0xff
+
+ def validate_memory(self, mem):
+ msgs = []
+
+ # BC band only supports AM mode
+ if mem.mode != "AM":
+ mem.mode = "AM"
+ msgs.append(chirp_common.ValidationWarning(
+ "BC band only supports AM mode"))
+
+ # BC band frequency range: 0.5-1.7 MHz with limited precision
+ if mem.freq < 500000 or mem.freq > 1700000:
+ mem.freq = max(500000, min(1700000, mem.freq))
+ msgs.append(chirp_common.ValidationWarning(
+ "BC band frequency adjusted to valid range (0.5-1.7 MHz)"))
+
+ # Round frequency to nearest encodable value for BC band
+ freq_mhz = mem.freq / 1000000.0
+ byte_val = int((freq_mhz - 0.5) / (1.2 / 254.0) + 0.5)
+ byte_val = min(max(byte_val, 0), 0xfe)
+ # Calculate the actual encodable frequency
+ actual_freq_mhz = 0.5 + (byte_val * (1.2 / 254.0))
+ actual_freq = int(actual_freq_mhz * 1000000 + 0.5) # Round to Hz
+ if mem.freq != actual_freq:
+ mem.freq = actual_freq
+ # Note: No warning - frequency rounding is expected in BC band
+
+ # BC band doesn't support duplex
+ if mem.duplex:
+ mem.duplex = ""
+ msgs.append(chirp_common.ValidationWarning(
+ "Duplex not supported for BC band"))
+
+ # BC band doesn't support tones
+ if mem.tmode and mem.tmode != "":
+ mem.tmode = ""
+ msgs.append(chirp_common.ValidationWarning(
+ "Tone modes not supported for BC band"))
+
+ return msgs
diff --git a/chirp/drivers/vx150.py b/chirp/drivers/vx150.py
new file mode 100644
index 0000000..a71b60f
--- /dev/null
+++ b/chirp/drivers/vx150.py
@@ -0,0 +1,778 @@
+# Copyright 2024 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/>.
+
+# Driver for the Vertex Standard VX-150 VHF handheld radio.
+#
+# The radio communicates at 9600 baud using the ft7800-style protocol:
+# ACK after every 32-byte chunk (not after each logical block). Image is
+# 5353 bytes: 8-byte header + 167×32-byte body blocks + 1 checksum byte.
+#
+# Model bytes (offset 0x0000): 0x0A 0x01 0x04 0x00 0x01 0x24
+
+import logging
+import time
+
+from chirp.drivers import yaesu_clone
+from chirp import bitwise, chirp_common, directory, errors, memmap
+from chirp.settings import RadioSetting, RadioSettingGroup, RadioSettings, \
+ RadioSettingValueBoolean, RadioSettingValueList, RadioSettingValueString
+
+LOG = logging.getLogger(__name__)
+
+ACK = b'\x06'
+
+
+def _send(ser, data):
+ for i in data:
+ ser.write(bytes([i]))
+ time.sleep(0.002)
+ echo = ser.read(len(data))
+ if echo != data:
+ raise errors.RadioError("Error reading echo (Bad cable?)")
+
+
+def _download(radio):
+ data = b""
+
+ chunk = b""
+ for _ in range(0, 30):
+ chunk += radio.pipe.read(radio._block_lengths[0])
+ if chunk:
+ break
+
+ if len(chunk) != radio._block_lengths[0]:
+ raise errors.RadioError("Failed to read header (%i)" % len(chunk))
+ data += chunk
+ _send(radio.pipe, ACK)
+
+ for i in range(0, radio._block_lengths[1], radio._block_size):
+ chunk = radio.pipe.read(radio._block_size)
+ data += chunk
+ if len(chunk) != radio._block_size:
+ break
+ time.sleep(0.01)
+ _send(radio.pipe, ACK)
+ if radio.status_fn:
+ status = chirp_common.Status()
+ status.max = radio.get_memsize()
+ status.cur = i + len(chunk)
+ status.msg = "Cloning from radio"
+ radio.status_fn(status)
+
+ data += radio.pipe.read(1)
+ _send(radio.pipe, ACK)
+
+ return memmap.MemoryMapBytes(data)
+
+
+# Channel memory layout — 16 bytes per channel, starting at 0x07D8.
+#
+# Full 16-byte pattern of an unprogrammed channel
+_EMPTY_CHANNEL = (b'\x00\x01\x00\x44\x00\x00\x60\x00'
+ b'\x0c\x00\x00\x00\xaa\x00\x02\x00')
+
+# Byte 0 — flags:
+# bit 7 : active (0=masked or empty, 1=active)
+# bit 6 : skip (0=no skip, 1=skip)
+# bits 5-4 : unknown
+# bits 3-2 : duplex (0=simplex, 2=neg offset, 3=pos offset)
+# bits 1-0 : tmode (0=none, 1=Tone, 2=TSQL, 3=DTCS)
+#
+# Bytes 1-3 — frequency (custom BCD):
+# byte 1 bit 7,6 : 2.5 kHz increments.
+# byte 1 bits 6-0 : band indicator (always 0x01 for 2 m)
+# byte 2 : BCD, 10-kHz digits (e.g. 0x52 → 52 → 520 kHz)
+# byte 3 : BCD, MHz digits above 100 (e.g. 0x46 → 46 → 146 MHz)
+#
+# Byte 8 : CTCSS tone index (chirp_common.TONES)
+# Byte 9 : DCS code index (chirp_common.DTCS_CODES)
+#
+# Bytes 4-7, 10-15 : not yet decoded.
+
+MEM_FORMAT = """
+#seekto 0x0013;
+u8 step;
+
+#seekto 0x0026;
+struct {
+ u8 mem_only:1,
+ unknown1:5,
+ power:2;
+} settings3;
+
+#seekto 0x0049;
+struct {
+ u8 unknown1:2,
+ tx_led:1,
+ unknown2:1,
+ scan_lamp:1,
+ ars:1,
+ scan_resume:2;
+ u8 bclo:1,
+ edge_beep:1,
+ key_beep:1,
+ arts_interval:1,
+ tx_save:1,
+ rx_save:3;
+ u8 unknown4a:1,
+ dtmf_speed:1,
+ smt_mod:1,
+ ani_on:1,
+ unknown5:1,
+ apo:3;
+ u8 unknown5b:6,
+ arts_bp:2;
+ u8 unknown6:3,
+ rev_hm:1,
+ moni_tcall:1,
+ bell:3;
+ u8 unknown7:5,
+ lamp:3;
+ u8 unknown8:5,
+ tot:3;
+ u8 lock_mode;
+ u8 unknown9[3];
+ u8 dtmf_delay;
+} settings2;
+
+#seekto 0x0056;
+struct {
+ u8 p1_key;
+ u8 p2_key;
+} p_keys;
+
+struct channel {
+ u8 active:1,
+ skip:1,
+ unknown1:2,
+ duplex:2,
+ tmode:2;
+ u8 sub_khz:2,
+ unknown_flags:5,
+ band:1;
+ bbcd freq_khz;
+ bbcd freq_mhz;
+ u8 unknown2:2,
+ narrow:1,
+ clock_shift:1,
+ unknown3:4;
+ u8 unknown4;
+ bbcd offset_low;
+ bbcd offset_high;
+ u8 tone;
+ u8 dtcs;
+ u8 unknown5[6];
+};
+
+struct channel home;
+
+u8 cwid[16];
+u8 ani[16];
+struct {
+ u8 digits[16];
+} dtmf[9];
+
+#seekto 0x0150;
+struct {
+ u8 name[7];
+ u8 show_name;
+} names[199];
+
+struct {
+ u8 name[7];
+ u8 show_name;
+} limit_names[10];
+
+struct channel memory[199];
+
+struct channel limits[10];
+"""
+
+# Character set: index → character. 0x00-0x09 = '0'-'9', 0x0A-0x23 = 'A'-'Z'
+# 0xFF = empty/pad.
+CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ ()+-=*/ΔγΣ|"
+
+DTMF_CHARSET = "0123456789ABCDEF"
+SPECIALS = ["Home", "L1", "L2", "L3", "L4", "L5", "U1", "U2", "U3", "U4", "U5"]
+
+P_KEY_LIST = [
+ "1: ALPHA",
+ "2: ARS",
+ "3: RPT",
+ "4: SHIFT",
+ "5: V-SPLIT",
+ "6: STEP",
+ "7: RESUME",
+ "8: SCN LMP",
+ "9: RX SAVE",
+ "10: TX SAVE",
+ "11: APO",
+ "12: TRX LED",
+ "13: ARTS",
+ "14: ARTS BP",
+ "15: AR ITVL",
+ "16: KEY BP",
+ "17: EDGE BP",
+ "18: BELL",
+ "19: MON/TCL",
+ "20: REV/HM",
+ "21: LMP MOD",
+ "22: TOT",
+ "23: BCLO",
+ "24: CLK SFT",
+ "25: SQL TYP",
+ "26: TN SET",
+ "27: DCS SET",
+ "28: DTMF",
+ "29: CW ID",
+ "30: S SRCH",
+ "31: SMT MOD",
+ "32: LK MODE",
+ "33: NAR/WID",
+ "34: DTMF SP",
+ "35: DT DLY",
+ "36: ANI",
+ "37: BATT",
+ "38: SKIP",
+]
+
+STEP_LIST = ["5.0", "10.0", "12.5", "15.0", "20.0", "25.0", "50.0"]
+POWER_LIST = ["Low", "Mid", "High"]
+SCAN_RESUME_LIST = ["5 Seconds", "Busy", "Hold"]
+SCAN_LAMP_LIST = ["Off", "On"]
+RX_SAVE_LIST = ["Off", "0.2 sec", "0.3 sec", "0.5 sec", "1 sec", "2 sec"]
+APO_LIST = ["Off", "30 Min", "1 Hour", "3 Hour", "5 Hour", "8 Hour"]
+ARTS_BP_LIST = ["Off", "In Range", "Always"]
+ARTS_INTERVAL_LIST = ["25 Sec", "15 Sec"]
+BELL_LIST = ["Off", "1", "3", "5", "8", "Repeat"]
+MONI_TCALL_LIST = ["Monitor", "T.Call"]
+REV_HM_LIST = ["REV", "Home"]
+LAMP_LIST = ["Key", "5 Sec", "Toggle"]
+TOT_LIST = ["Off", "1 Min", "2.5 Min", "5 Min", "10 Min"]
+
+# duplex field value → CHIRP duplex string
+DUPLEX_MAP = {0: "", 2: "-", 3: "+"}
+DUPLEX_REV = {"": 0, "-": 2, "+": 3}
+
+# tmode field value → CHIRP tmode string
+TMODE_MAP = {0: "", 1: "Tone", 2: "TSQL", 3: "DTCS"}
+TMODE_REV = {"": 0, "Tone": 1, "TSQL": 2, "DTCS": 3}
+
+
+def _decode_str(raw_bytes, charset):
+ """Decode a FF-terminated byte array using charset."""
+ s = ""
+ for b in raw_bytes:
+ b = int(b)
+ if b == 0xFF:
+ break
+ if b < len(charset):
+ s += charset[b]
+ return s
+
+
+def _encode_str(s, charset, length):
+ """Encode a string to a fixed-length byte list using charset, FF-padded."""
+ result = []
+ for c in s[:length]:
+ if c in charset:
+ result.append(charset.index(c))
+ else:
+ result.append(0xFF)
+ result += [0xFF] * (length - len(result))
+ return result
+
+
+def _upload(radio):
+ """Upload image to VX-150.
+
+ Mirror of ft7800._download: the radio ACKs each 32-byte body block but
+ does NOT ACK the 8-byte header (asymmetric vs. download direction).
+ """
+ mmap = radio.get_mmap().get_byte_compatible()
+
+ # Header (8 bytes) — send, then wait for the radio to ACK it
+ _send(radio.pipe, mmap[0:8])
+ if radio.pipe.read(1) != ACK:
+ raise errors.RadioError("Radio did not ack header")
+
+ # Body (5344 bytes) in 32-byte blocks — radio ACKs each
+ cur = 8
+ body_end = 8 + radio._block_lengths[1]
+ while cur < body_end:
+ length = min(radio._block_size, body_end - cur)
+ _send(radio.pipe, mmap[cur:cur + length])
+ if radio.pipe.read(1) != ACK:
+ raise errors.RadioError("Radio did not ack block at %i" % cur)
+ cur += length
+ time.sleep(0.05)
+ if radio.status_fn:
+ status = chirp_common.Status()
+ status.cur = cur
+ status.max = radio.get_memsize()
+ status.msg = "Cloning to radio"
+ radio.status_fn(status)
+
+ # Checksum (1 byte) — send last
+ _send(radio.pipe, mmap[cur:cur + 1])
+
+
+@directory.register
+class VX150Radio(yaesu_clone.YaesuCloneModeRadio):
+ """Vertex Standard VX-150"""
+ VENDOR = "Yaesu"
+ MODEL = "VX-150"
+ BAUD_RATE = 9600
+
+ # Confirmed from a real radio dump. Binary header, not ASCII like most
+ # Yaesu/Vertex models. Bytes: 0x0A 0x01 0x04 0x00 0x01 0x24
+ _model = b"\x0a\x01\x04\x00\x01\x24"
+
+ # 8-byte header + 167×32-byte body + 1 checksum byte
+ _memsize = 5353
+ _block_lengths = [8, 5344, 1]
+ _block_size = 32
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.pre_download = _(
+ "1. Turn radio off.\n"
+ "2. Connect clone cable to the MIC/SP jack.\n"
+ "3. Press and hold [PTT] and [Lamp] while turning the radio on.\n"
+ "4. Rotate the dial to select \"CLONE\", then press [F].\n"
+ " (\"CLONE\" will appear on the display)\n"
+ "5. <b>After clicking OK</b>, hold [PTT] briefly to transmit.\n"
+ " (\"SENDING\" will appear on the display)\n")
+ rp.pre_upload = _(
+ "1. Turn radio off.\n"
+ "2. Connect clone cable to the MIC/SP jack.\n"
+ "3. Press and hold [PTT] and [Lamp] while turning the radio on.\n"
+ "4. Rotate the dial to select \"CLONE\", then press [F].\n"
+ " (\"CLONE\" will appear on the display)\n"
+ "5. Press [MONI] to receive.\n"
+ " (\"SAVING\" will appear on the display)\n")
+ return rp
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.memory_bounds = (1, 199)
+ rf.valid_bands = [(136000000, 174000000)]
+ rf.valid_modes = ["FM", "NFM"]
+ rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS"]
+ rf.valid_duplexes = ["", "-", "+"]
+ rf.valid_skips = ["", "S"]
+ rf.valid_name_length = 7
+ rf.valid_characters = CHARSET
+ rf.valid_special_chans = SPECIALS
+ rf.valid_tones = chirp_common.OLD_TONES
+ rf.valid_tuning_steps = list(chirp_common.COMMON_TUNING_STEPS) + [12.5]
+ rf.has_ctone = False
+ rf.has_dtcs_polarity = False
+ rf.has_bank = False
+ rf.has_settings = True
+ rf.has_tuning_step = False
+ return rf
+
+ def sync_in(self):
+ try:
+ self._mmap = _download(self)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ raise errors.RadioError("Failed to communicate with radio: %s" % e)
+ if len(self._mmap) != self._memsize:
+ raise errors.RadioError(
+ "Expected %i bytes but got %i" % (
+ self._memsize, len(self._mmap)))
+ self.process_mmap()
+
+ def _checksums(self):
+ # Sum of all bytes 0x0000–0x14E7, stored at 0x14E8
+ return [yaesu_clone.YaesuChecksum(0x0000, self._memsize - 2)]
+
+ def sync_out(self):
+ self.update_checksums()
+ try:
+ _upload(self)
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ raise errors.RadioError("Failed to communicate with radio: %s" % e)
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
+
+ def get_raw_memory(self, number):
+ if number == "Home":
+ return repr(self._memobj.home)
+ if isinstance(number, str):
+ return repr(self._memobj.limits[SPECIALS.index(number) - 1])
+ return repr(self._memobj.memory[number - 1])
+
+ def get_memory(self, number):
+ if number == "Home":
+ raw = self._memobj.home
+ raw_name = None
+ mem = chirp_common.Memory()
+ mem.extd_number = "Home"
+ elif isinstance(number, str):
+ idx = SPECIALS.index(number) - 1
+ raw = self._memobj.limits[idx]
+ raw_name = self._memobj.limit_names[idx]
+ mem = chirp_common.Memory()
+ mem.extd_number = number
+ else:
+ raw = self._memobj.memory[number - 1]
+ raw_name = self._memobj.names[number - 1]
+ mem = chirp_common.Memory(number)
+
+ if number == "Home":
+ offset = 0x0058
+ elif isinstance(number, str):
+ offset = 0x1448 + (SPECIALS.index(number) - 1) * 16
+ else:
+ offset = 0x07d8 + (number - 1) * 16
+ raw16 = bytes(self._mmap.get_byte_compatible()[offset:offset + 16])
+ if raw16 == _EMPTY_CHANNEL:
+ mem.empty = True
+ return mem
+
+ mem.freq = ((100 + int(raw.freq_mhz)) * 1_000_000
+ + int(raw.freq_khz) * 10_000
+ + int(raw.sub_khz) * 2_500)
+ mem.skip = "S" if raw.skip else ""
+ mem.mode = "NFM" if raw.narrow else "FM"
+ mem.duplex = DUPLEX_MAP.get(int(raw.duplex), "")
+ mem.offset = (int(raw.offset_high) * 1_000_000 +
+ int(raw.offset_low) * 10_000)
+ mem.tmode = TMODE_MAP.get(int(raw.tmode), "")
+
+ tone_idx = int(raw.tone)
+ if tone_idx < len(chirp_common.OLD_TONES):
+ mem.rtone = chirp_common.OLD_TONES[tone_idx]
+ mem.ctone = mem.rtone
+
+ dtcs_idx = int(raw.dtcs)
+ if dtcs_idx < len(chirp_common.DTCS_CODES):
+ mem.dtcs = chirp_common.DTCS_CODES[dtcs_idx]
+
+ if raw_name is not None:
+ name = ""
+ for byte in raw_name.name:
+ b = int(byte)
+ if b == 0xFF:
+ break
+ if b < len(CHARSET):
+ name += CHARSET[b]
+ mem.name = name.rstrip()
+
+ mem.extra = RadioSettingGroup("extra", "Extra")
+ mem.extra.append(RadioSetting(
+ "masked", "Masked",
+ RadioSettingValueBoolean(not bool(raw.active))))
+ mem.extra.append(RadioSetting(
+ "clock_shift", "Clock Shift",
+ RadioSettingValueBoolean(bool(raw.clock_shift))))
+
+ return mem
+
+ def get_settings(self):
+ _settings2 = self._memobj.settings2
+ _settings3 = self._memobj.settings3
+
+ basic = RadioSettingGroup("basic", "Basic")
+ top = RadioSettings(basic)
+
+ basic.append(RadioSetting(
+ "mem_only", "Memory Only Mode",
+ RadioSettingValueBoolean(bool(_settings3.mem_only))))
+
+ basic.append(RadioSetting(
+ "power", "Power Level",
+ RadioSettingValueList(
+ POWER_LIST, current_index=int(_settings3.power))))
+
+ basic.append(RadioSetting(
+ "ars", "2: Auto Repeater Shift",
+ RadioSettingValueBoolean(bool(_settings2.ars))))
+
+ basic.append(RadioSetting(
+ "step", "6: Tuning Step (kHz)",
+ RadioSettingValueList(
+ STEP_LIST, current_index=int(self._memobj.step))))
+
+ basic.append(RadioSetting(
+ "scan_resume", "7: Scan Resume",
+ RadioSettingValueList(
+ SCAN_RESUME_LIST, current_index=int(_settings2.scan_resume))))
+
+ basic.append(RadioSetting(
+ "scan_lamp", "8: Scan Lamp",
+ RadioSettingValueList(
+ SCAN_LAMP_LIST, current_index=int(_settings2.scan_lamp))))
+
+ basic.append(RadioSetting(
+ "rx_save", "9: RX Save",
+ RadioSettingValueList(
+ RX_SAVE_LIST, current_index=int(_settings2.rx_save))))
+
+ basic.append(RadioSetting(
+ "tx_save", "10: TX Save",
+ RadioSettingValueBoolean(bool(_settings2.tx_save))))
+
+ basic.append(RadioSetting(
+ "apo", "11: Auto Power Off",
+ RadioSettingValueList(
+ APO_LIST, current_index=int(_settings2.apo))))
+
+ basic.append(RadioSetting(
+ "tx_led", "12: TX LED",
+ RadioSettingValueBoolean(not bool(_settings2.tx_led))))
+
+ basic.append(RadioSetting(
+ "arts_bp", "14: ARTS Beep",
+ RadioSettingValueList(
+ ARTS_BP_LIST, current_index=int(_settings2.arts_bp))))
+
+ basic.append(RadioSetting(
+ "arts_interval", "15: ARTS Interval",
+ RadioSettingValueList(
+ ARTS_INTERVAL_LIST,
+ current_index=int(_settings2.arts_interval))))
+
+ basic.append(RadioSetting(
+ "key_beep", "16: Key Beep",
+ RadioSettingValueBoolean(bool(_settings2.key_beep))))
+
+ basic.append(RadioSetting(
+ "edge_beep", "17: Edge Beep",
+ RadioSettingValueBoolean(bool(_settings2.edge_beep))))
+
+ basic.append(RadioSetting(
+ "bell", "18: Bell (CTCSS)",
+ RadioSettingValueList(
+ BELL_LIST, current_index=int(_settings2.bell))))
+
+ basic.append(RadioSetting(
+ "moni_tcall", "19: MONI Button",
+ RadioSettingValueList(
+ MONI_TCALL_LIST, current_index=int(_settings2.moni_tcall))))
+
+ basic.append(RadioSetting(
+ "rev_hm", "20: REV(HM) Key",
+ RadioSettingValueList(
+ REV_HM_LIST, current_index=int(_settings2.rev_hm))))
+
+ basic.append(RadioSetting(
+ "lamp", "21: Lamp Mode",
+ RadioSettingValueList(
+ LAMP_LIST, current_index=int(_settings2.lamp))))
+
+ basic.append(RadioSetting(
+ "tot", "22: Time-Out Timer",
+ RadioSettingValueList(
+ TOT_LIST, current_index=int(_settings2.tot))))
+
+ basic.append(RadioSetting(
+ "bclo", "23: Busy Channel Lockout",
+ RadioSettingValueBoolean(bool(_settings2.bclo))))
+
+ basic.append(RadioSetting(
+ "smt_mod", "31: Smart Search Mode",
+ RadioSettingValueList(
+ ["Single", "Continue"],
+ current_index=int(_settings2.smt_mod))))
+
+ basic.append(RadioSetting(
+ "lock_mode", "32: Lock Mode",
+ RadioSettingValueList(
+ ["Key", "Dial", "K+D", "PTT", "K+P", "D+P", "All"],
+ current_index=int(_settings2.lock_mode) - 1)))
+
+ basic.append(RadioSetting(
+ "dtmf_speed", "34: DTMF Speed",
+ RadioSettingValueList(
+ ["50ms", "100ms"], current_index=int(_settings2.dtmf_speed))))
+
+ DTMF_DELAY_LIST = ["450ms", "750ms"]
+ DTMF_DELAY_MAP = [0xD3, 0xB5]
+ basic.append(RadioSetting(
+ "dtmf_delay", "35: DTMF Delay",
+ RadioSettingValueList(
+ DTMF_DELAY_LIST,
+ current_index=DTMF_DELAY_MAP.index(
+ int(_settings2.dtmf_delay)))))
+
+ basic.append(RadioSetting(
+ "ani_on", "36: ANI",
+ RadioSettingValueBoolean(bool(_settings2.ani_on))))
+
+ _p_keys = self._memobj.p_keys
+ basic.append(RadioSetting(
+ "p1_key", "P1 Key",
+ RadioSettingValueList(
+ P_KEY_LIST, current_index=int(_p_keys.p1_key) - 1)))
+
+ basic.append(RadioSetting(
+ "p2_key", "P2 Key",
+ RadioSettingValueList(
+ P_KEY_LIST, current_index=int(_p_keys.p2_key) - 1)))
+
+ ani = RadioSettingGroup("ani", "ANI")
+ top.append(ani)
+ ani_str = _decode_str(self._memobj.ani, DTMF_CHARSET)
+ ani.append(RadioSetting(
+ "ani", "ANI Code",
+ RadioSettingValueString(0, 16, ani_str, False, DTMF_CHARSET)))
+
+ cwid = RadioSettingGroup("cwid", "CW ID")
+ top.append(cwid)
+ cwid_str = _decode_str(self._memobj.cwid, CHARSET)
+ cwid.append(RadioSetting(
+ "cwid", "CW ID",
+ RadioSettingValueString(0, 16, cwid_str, False, CHARSET)))
+
+ dtmf = RadioSettingGroup("dtmf", "DTMF")
+ top.append(dtmf)
+ for i in range(9):
+ dtmf_str = _decode_str(self._memobj.dtmf[i].digits, DTMF_CHARSET)
+ dtmf.append(RadioSetting(
+ "dtmf_%d" % (i + 1), "D%d" % (i + 1),
+ RadioSettingValueString(0, 16, dtmf_str, False, DTMF_CHARSET)))
+
+ return top
+
+ def set_settings(self, uisettings):
+ _settings2 = self._memobj.settings2
+ _settings3 = self._memobj.settings3
+
+ for element in uisettings:
+ if not isinstance(element, RadioSetting):
+ self.set_settings(element)
+ continue
+ if not element.changed():
+ continue
+ name = element.get_name()
+ if name in ("mem_only", "power"):
+ setattr(_settings3, name, element.value)
+ elif name == "step":
+ self._memobj.step = element.value
+ elif name == "tx_led":
+ _settings2.tx_led = not bool(element.value)
+ elif name in ("scan_resume", "scan_lamp", "ars", "rx_save",
+ "tx_save", "apo", "ani_on", "dtmf_speed", "bclo",
+ "edge_beep", "key_beep", "arts_interval", "arts_bp",
+ "bell", "moni_tcall", "rev_hm", "lamp", "tot",
+ "smt_mod"):
+ setattr(_settings2, name, element.value)
+ elif name == "ani":
+ self._memobj.ani = _encode_str(
+ str(element.value), DTMF_CHARSET, 16)
+ elif name == "cwid":
+ self._memobj.cwid = _encode_str(
+ str(element.value), CHARSET, 16)
+ elif name == "lock_mode":
+ _settings2.lock_mode = int(element.value) + 1
+ elif name == "dtmf_delay":
+ _settings2.dtmf_delay = [0xD3, 0xB5][int(element.value)]
+ elif name in ("p1_key", "p2_key"):
+ setattr(self._memobj.p_keys, name, int(element.value) + 1)
+ elif name.startswith("dtmf_"):
+ i = int(name.split("_")[1]) - 1
+ self._memobj.dtmf[i].digits = _encode_str(
+ str(element.value), DTMF_CHARSET, 16)
+
+ def set_memory(self, mem):
+ number = mem.extd_number or mem.number
+ if number == "Home":
+ raw = self._memobj.home
+ raw_name = None
+ elif isinstance(number, str):
+ idx = SPECIALS.index(number) - 1
+ raw = self._memobj.limits[idx]
+ raw_name = self._memobj.limit_names[idx]
+ else:
+ raw = self._memobj.memory[number - 1]
+ raw_name = self._memobj.names[number - 1]
+
+ if mem.empty:
+ raw.set_raw(bytes(_EMPTY_CHANNEL))
+ if raw_name is not None:
+ for i in range(7):
+ raw_name.name[i] = 0xFF
+ raw_name.show_name = 0xFF
+ return
+
+ # Frequency
+ freq_hz = mem.freq
+ mhz = freq_hz // 1_000_000
+ remainder = freq_hz % 1_000_000
+ khz_10 = remainder // 10_000
+ sub_khz = (remainder % 10_000) // 2_500
+ raw.freq_mhz = mhz - 100
+ raw.freq_khz = khz_10
+ raw.sub_khz = sub_khz
+ raw.band = 1
+
+ # Byte 0 flags
+ raw.skip = 1 if mem.skip == "S" else 0
+ raw.duplex = DUPLEX_REV.get(mem.duplex, 0)
+ raw.tmode = TMODE_REV.get(mem.tmode, 0)
+
+ # Byte 4: mode and clock shift
+ raw.narrow = 1 if mem.mode == "NFM" else 0
+ clock_shift = 0
+ masked = False
+ if mem.extra:
+ for setting in mem.extra:
+ sname = setting.get_name()
+ if sname == "clock_shift":
+ clock_shift = int(bool(setting.value))
+ elif sname == "masked":
+ masked = bool(setting.value)
+ raw.clock_shift = clock_shift
+ raw.active = 0 if masked else 1
+
+ # Byte 5: always 0x10 in programmed channels
+ raw.unknown4 = 0x10
+
+ # Offset
+ offset_hz = mem.offset
+ raw.offset_high = offset_hz // 1_000_000
+ raw.offset_low = (offset_hz % 1_000_000) // 10_000
+
+ # Tone / DCS
+ raw.tone = (chirp_common.OLD_TONES.index(mem.rtone)
+ if mem.rtone in chirp_common.OLD_TONES else 0)
+ raw.dtcs = (chirp_common.DTCS_CODES.index(mem.dtcs)
+ if mem.dtcs in chirp_common.DTCS_CODES else 0)
+
+ # Bytes 10-15: constant across all programmed channels
+ for i, b in enumerate([0x00, 0x00, 0xaa, 0x00, 0x02, 0x00]):
+ raw.unknown5[i] = b
+
+ # Name
+ if raw_name is not None:
+ name = mem.name.rstrip()
+ encoded = _encode_str(name, CHARSET, 7)
+ for i in range(7):
+ raw_name.name[i] = encoded[i]
+ raw_name.show_name = 0x00 if name else 0xFF
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ # New driver — images are identified by the metadata sidecar
+ return False
diff --git a/chirp/drivers/vx3.py b/chirp/drivers/vx3.py
index 4d0d94f..3a989c0 100644
--- a/chirp/drivers/vx3.py
+++ b/chirp/drivers/vx3.py
@@ -398,7 +398,7 @@ class VX3Radio(yaesu_clone.YaesuCloneModeRadio):
rf.valid_modes = list(set(MODES))
rf.valid_tmodes = list(TMODES)
rf.valid_duplexes = list(DUPLEX)
- rf.valid_tuning_steps = list(STEPS)
+ rf.valid_tuning_steps = list(STEPS + [8.33])
rf.valid_bands = [(500000, 999000000)]
rf.valid_skips = ["", "S", "P"]
rf.valid_power_levels = POWER_LEVELS
@@ -411,7 +411,7 @@ class VX3Radio(yaesu_clone.YaesuCloneModeRadio):
return rf
def get_raw_memory(self, number):
- return repr(self._memobj.memory[number])
+ return repr(self._memobj.memory[number-1])
def get_memory(self, number):
_mem = self._memobj.memory[number-1]
@@ -491,7 +491,10 @@ class VX3Radio(yaesu_clone.YaesuCloneModeRadio):
_mem.mode = MODES.index(mem.mode)
_mem.txnarrow = False
_mem.dcs = chirp_common.DTCS_CODES.index(mem.dtcs)
- _mem.tune_step = STEPS.index(mem.tuning_step)
+ try:
+ _mem.tune_step = STEPS.index(mem.tuning_step)
+ except ValueError:
+ _mem.tune_step = 0
if mem.power == POWER_LEVELS[1]: # Low
_mem.power = 0x00
else: # Default to High
diff --git a/chirp/drivers/vx8.py b/chirp/drivers/vx8.py
index b3e0306..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
@@ -152,7 +152,7 @@ struct {
struct {
u8 unknown1a:2,
half_deviation:1, // This is not really right, maybe auto?
- unknown1b:5;
+ unknown1b:5; // Something related to 6.25kHz?
u8 mode:2,
duplex:2,
tune_step:4;
@@ -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]
@@ -697,6 +708,16 @@ class VX8Radio(yaesu_clone.YaesuCloneModeRadio):
else:
flag.nosubvfo = False # Available in both VFOs
+ # This seems to be something the radio requires to properly resolve
+ # 6.25kHz channels. The radio sets this when you store such a channel
+ # and if it's not set this way the radio is actually way off on
+ # frequency, even though the display shows the proper thing.
+ if (chirp_common.is_6_25(mem.freq) and
+ not chirp_common.is_5_0(mem.freq)):
+ _mem.unknown1b = 0x05
+ else:
+ _mem.unknown1b = 0x00
+
_mem.freq = int(mem.freq / 1000)
_mem.offset = int(mem.offset / 1000)
_mem.tone = chirp_common.TONES.index(mem.rtone)
diff --git a/chirp/drivers/wouxun.py b/chirp/drivers/wouxun.py
index 3d0b170..9ce7098 100644
--- a/chirp/drivers/wouxun.py
+++ b/chirp/drivers/wouxun.py
@@ -22,7 +22,9 @@ from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettingValueInteger, RadioSettingValueString, \
RadioSettingValueFloat, RadioSettings
+from chirp.drivers import wouxun_common
from chirp.drivers.wouxun_common import wipe_memory, do_download, do_upload
+from chirp import kenwood_tone
LOG = logging.getLogger(__name__)
@@ -70,13 +72,20 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio,
valid_freq = [(136000000, 175000000), (216000000, 520000000)]
+ _tone_model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x2800,
+ pol_mask=0x8000,
+ tone_init=0xFFFF,
+ tone_flag=0x0000,
+ dcs_enc_base=8)
+
_MEM_FORMAT = """
#seekto 0x0010;
struct {
lbcd rx_freq[4];
lbcd tx_freq[4];
- ul16 rx_tone;
- ul16 tx_tone;
+ ul16 rxtone;
+ ul16 txtone;
u8 _3_unknown_1:4,
bcl:1,
_3_unknown_2:3;
@@ -243,7 +252,7 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio,
util.hexprint(resp))
return
if len(resp) == 0:
- raise Exception("Radio not responding")
+ raise errors.RadioNoResponse()
else:
raise Exception("Unable to identify radio")
@@ -725,50 +734,6 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio,
def get_raw_memory(self, number):
return repr(self._memobj.memory[number - 1])
- def _get_tone(self, _mem, mem):
- def _get_dcs(val):
- code = int("%03o" % (val & 0x07FF))
- pol = (val & 0x8000) and "R" or "N"
- return code, pol
-
- tpol = False
- if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
- tcode, tpol = _get_dcs(_mem.tx_tone)
- mem.dtcs = tcode
- txmode = "DTCS"
- elif _mem.tx_tone != 0xFFFF:
- mem.rtone = _mem.tx_tone / 10.0
- txmode = "Tone"
- else:
- txmode = ""
-
- rpol = False
- if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
- rcode, rpol = _get_dcs(_mem.rx_tone)
- mem.rx_dtcs = rcode
- rxmode = "DTCS"
- elif _mem.rx_tone != 0xFFFF:
- mem.ctone = _mem.rx_tone / 10.0
- rxmode = "Tone"
- else:
- rxmode = ""
-
- if txmode == "Tone" and not rxmode:
- mem.tmode = "Tone"
- elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
- mem.tmode = "TSQL"
- elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
- mem.tmode = "DTCS"
- elif rxmode or txmode:
- mem.tmode = "Cross"
- mem.cross_mode = "%s->%s" % (txmode, rxmode)
-
- # always set it even if no dtcs is used
- mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")
-
- LOG.debug("Got TX %s (%i) RX %s (%i)" %
- (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
-
def _is_txinh(self, _mem):
return _mem.tx_freq.get_raw() == b"\xFF\xFF\xFF\xFF"
@@ -808,7 +773,7 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio,
if not _mem.iswide:
mem.mode = "NFM"
- self._get_tone(_mem, mem)
+ self._tone_model.get_tone(_mem, mem)
mem.power = self.POWER_LEVELS[not _mem.power_high]
@@ -832,44 +797,6 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio,
return mem
- def _set_tone(self, mem, _mem):
- def _set_dcs(code, pol):
- val = int("%i" % code, 8) + 0x2800
- if pol == "R":
- val += 0x8000
- return val
-
- rx_mode = tx_mode = None
- rx_tone = tx_tone = 0xFFFF
-
- if mem.tmode == "Tone":
- tx_mode = "Tone"
- rx_mode = None
- tx_tone = int(mem.rtone * 10)
- elif mem.tmode == "TSQL":
- rx_mode = tx_mode = "Tone"
- rx_tone = tx_tone = int(mem.ctone * 10)
- elif mem.tmode == "DTCS":
- tx_mode = rx_mode = "DTCS"
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- rx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
- elif mem.tmode == "Cross":
- tx_mode, rx_mode = mem.cross_mode.split("->")
- if tx_mode == "DTCS":
- tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
- elif tx_mode == "Tone":
- tx_tone = int(mem.rtone * 10)
- if rx_mode == "DTCS":
- rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
- elif rx_mode == "Tone":
- rx_tone = int(mem.ctone * 10)
-
- _mem.rx_tone = rx_tone
- _mem.tx_tone = tx_tone
-
- LOG.debug("Set TX %s (%i) RX %s (%i)" %
- (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
-
def _set_split_duplex(self, _mem, mem):
_mem.splitdup = mem.duplex == "split"
@@ -900,7 +827,7 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio,
_mem.skip = mem.skip != "S"
_mem.iswide = mem.mode != "NFM"
- self._set_tone(mem, _mem)
+ self._tone_model.set_tone(mem, _mem)
if mem.power:
_mem.power_high = not self.POWER_LEVELS.index(mem.power)
@@ -948,8 +875,8 @@ class KGUV6DRadio(KGUVD1PRadio):
struct {
lbcd rx_freq[4];
lbcd tx_freq[4];
- ul16 rx_tone;
- ul16 tx_tone;
+ ul16 rxtone;
+ ul16 txtone;
u8 _3_unknown_1:4,
bcl:1,
_3_unknown_2:3;
@@ -1051,8 +978,8 @@ class KGUV6DRadio(KGUVD1PRadio):
struct {
lbcd rx_freq[4];
lbcd tx_freq[4];
- ul16 rx_tone;
- ul16 tx_tone;
+ ul16 rxtone;
+ ul16 txtone;
u8 _3_unknown_3:4,
bcl:1,
_3_unknown_4:3;
@@ -1475,8 +1402,8 @@ class KG816Radio(KGUVD1PRadio, chirp_common.ExperimentalRadio):
struct {
lbcd rx_freq[4];
lbcd tx_freq[4];
- ul16 rx_tone;
- ul16 tx_tone;
+ ul16 rxtone;
+ ul16 txtone;
u8 _3_unknown_1:4,
bcl:1,
_3_unknown_2:3;
@@ -1613,8 +1540,8 @@ class KG805GRadio(KGUVD1PRadio):
struct {
lbcd rx_freq[4];
lbcd tx_freq[4];
- ul16 rx_tone;
- ul16 tx_tone;
+ ul16 rxtone;
+ ul16 txtone;
u8 _3_unknown_1:4,
bcl:1,
_3_unknown_2:3;
diff --git a/chirp/drivers/yaesu_clone.py b/chirp/drivers/yaesu_clone.py
index 83d8c8b..8d8a1fc 100644
--- a/chirp/drivers/yaesu_clone.py
+++ b/chirp/drivers/yaesu_clone.py
@@ -24,13 +24,13 @@ LOG = logging.getLogger(__name__)
CMD_ACK = 0x06
-def _safe_read(pipe, count):
+def _safe_read(pipe, count, cmd_ack=CMD_ACK):
buf = bytes(b"")
first = True
for _i in range(0, 60):
buf += pipe.read(count - len(buf))
if buf:
- if first and buf[0] == CMD_ACK:
+ if first and buf[0] == cmd_ack:
buf = buf[1:] # Chew an echo'd ack if using a 2-pin cable
first = False
if len(buf) == count:
@@ -38,10 +38,11 @@ def _safe_read(pipe, count):
return buf
-def _chunk_read(pipe, count, status_fn):
+def _chunk_read(pipe, count, status_fn, cmd_ack=CMD_ACK):
timer = time.time()
block = 32
data = bytes(b"")
+ had_data = False
while len(data) < count:
# Don't read past the end of our block if we're not on a 32-byte
# boundary
@@ -49,12 +50,15 @@ def _chunk_read(pipe, count, status_fn):
chunk = pipe.read(chunk_size)
if chunk:
timer = time.time()
+ had_data = True
data += chunk
- if data[0] == CMD_ACK:
+ if data[0] == cmd_ack:
data = data[1:] # Chew an echo'd ack if using a 2-pin cable
if time.time() - timer > 2:
# It's been two seconds since we last saw data from the radio,
# so it's time to give up.
+ if not had_data:
+ raise errors.RadioNoResponse()
raise errors.RadioError("Timed out reading from radio")
status = chirp_common.Status()
status.msg = "Cloning from radio"
@@ -79,12 +83,12 @@ def __clone_in(radio):
for block in radio._block_lengths:
blocks += 1
if blocks == len(radio._block_lengths):
- chunk = _chunk_read(pipe, block, radio.status_fn)
+ chunk = _chunk_read(pipe, block, radio.status_fn, radio._cmd_ack)
else:
- chunk = _safe_read(pipe, block)
- pipe.write(bytes([CMD_ACK]))
+ chunk = _safe_read(pipe, block, radio._cmd_ack)
+ pipe.write(bytes([radio._cmd_ack]))
if not chunk:
- raise errors.RadioError("No response from radio")
+ raise errors.RadioNoResponse()
if blocks == 1:
LOG.debug('ID block: %s' % util.hexprint(chunk))
if radio.status_fn:
@@ -103,6 +107,8 @@ def __clone_in(radio):
def _clone_in(radio):
try:
return __clone_in(radio)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError("Failed to communicate with the radio: %s" % e)
@@ -126,34 +132,38 @@ def _chunk_write(pipe, data, status_fn, block):
def __clone_out(radio):
pipe = radio.pipe
block_lengths = radio._block_lengths
- total_written = 0
def _status():
status = chirp_common.Status()
status.msg = "Cloning to radio"
- status.max = block_lengths[0] + block_lengths[1] + block_lengths[2]
- status.cur = total_written
+ status.max = sum(block_lengths)
+ status.cur = pos
radio.status_fn(status)
start = time.time()
blocks = 0
pos = 0
+ _status()
+ num_blocks = len(radio._block_lengths)
mmap = radio.get_mmap().get_byte_compatible()
for block in radio._block_lengths:
blocks += 1
- if blocks != len(radio._block_lengths):
+ if blocks != num_blocks or num_blocks == 1:
LOG.debug("Sending %i-%i" % (pos, pos+block))
pipe.write(mmap[pos:pos+block])
buf = pipe.read(1)
- if buf and buf[0] != CMD_ACK:
+ if buf and buf[0] != radio._cmd_ack:
buf = pipe.read(block)
- if not buf or buf[-1] != CMD_ACK:
+ if not buf:
+ raise errors.RadioNoResponse()
+ if buf[-1] != radio._cmd_ack:
raise Exception("Radio did not ack block %i" % blocks)
else:
_chunk_write(pipe, mmap[pos:],
radio.status_fn, radio._block_size)
pos += block
+ _status()
pipe.read(pos) # Chew the echo if using a 2-pin cable
@@ -163,6 +173,8 @@ def __clone_out(radio):
def _clone_out(radio):
try:
return __clone_out(radio)
+ except errors.RadioError:
+ raise
except Exception as e:
raise errors.RadioError("Failed to communicate with the radio: %s" % e)
@@ -223,6 +235,7 @@ class YaesuCloneModeRadio(chirp_common.CloneModeRadio):
"""Base class for all Yaesu clone-mode radios"""
_block_lengths = [8, 65536]
_block_size = 8
+ _cmd_ack = CMD_ACK
VENDOR = "Yaesu"
_model = b"ABCDE"
diff --git a/chirp/errors.py b/chirp/errors.py
index a2dc82f..8a6455e 100644
--- a/chirp/errors.py
+++ b/chirp/errors.py
@@ -17,6 +17,7 @@ import enum
class Reasons(enum.Enum):
+ NO_RESPONSE = "No response from radio"
NO_CONNECTION_K1 = "No response from radio. Check connector and cabling!"
FIXED_BANKS = "This radio has fixed banks and does not allow reassignment"
@@ -76,6 +77,16 @@ class RadioNoContactLikelyK1(SpecificRadioError):
CODE = Reasons.NO_CONNECTION_K1
+class RadioNoResponse(SpecificRadioError):
+ """A radio that provided no response to a command."""
+ CODE = Reasons.NO_RESPONSE
+
+
class RadioFixedBanks(SpecificRadioError):
"""A radio that has fixed banks and cannot be changed."""
CODE = Reasons.FIXED_BANKS
+
+
+class FrozenMemoryError(TypeError):
+ """An attempt was made to modify a frozen memory."""
+ pass
diff --git a/chirp/import_logic.py b/chirp/import_logic.py
index 6455690..b4d8cab 100644
--- a/chirp/import_logic.py
+++ b/chirp/import_logic.py
@@ -70,11 +70,13 @@ def ensure_has_calls(radio, memory):
def _import_freq(dst_radio, _srcrf, mem):
- dst_bands = dst_radio.get_features().valid_bands
+ dst_rf = dst_radio.get_features()
+ dst_bands = dst_rf.valid_bands
if not any(lo <= mem.freq <= hi for (lo, hi) in dst_bands):
raise DestNotCompatible(
- _('Frequency %s is out of supported range') % (
- chirp_common.format_freq(mem.freq)))
+ _('Frequency %s is out of supported ranges %s') % (
+ chirp_common.format_freq(mem.freq),
+ dst_rf.concise_bands))
# Filter the name according to the destination's rules
@@ -138,9 +140,19 @@ def _import_tone(dst_radio, srcrf, mem):
# ctone). If we're importing to or from radios with differing models,
# do the conversion here.
- if srcrf.has_ctone and not dstrf.has_ctone:
+ if mem.tmode == "":
+ pass
+ elif srcrf.has_ctone and not dstrf.has_ctone:
# If copying from a radio with separate rtone/ctone to a radio
# without, and the tmode is TSQL, then use the ctone value
+ if mem.rtone not in dstrf.valid_tones:
+ raise DestNotCompatible(
+ "Destination does not support tone frequency %s" %
+ mem.rtone)
+ if mem.ctone not in dstrf.valid_tones:
+ raise DestNotCompatible(
+ "Destination does not support tone frequency %s" %
+ mem.ctone)
if mem.tmode == "TSQL":
mem.rtone = mem.ctone
elif not srcrf.has_ctone and dstrf.has_ctone:
@@ -278,7 +290,11 @@ def import_mem(dst_radio, src_features, src_mem, overrides={}, mem_cls=None):
cur_mem = dst_radio.get_memory(dst_mem.number)
dst_radio.check_set_memory_immutable_policy(cur_mem, dst_mem)
- msgs = dst_radio.validate_memory(dst_mem)
+ try:
+ msgs = dst_radio.validate_memory(chirp_common.FrozenMemory(dst_mem))
+ except errors.FrozenMemoryError as e:
+ raise DestNotCompatible(str(e))
+
errs = [x for x in msgs if isinstance(x, chirp_common.ValidationError)]
if errs:
raise DestNotCompatible(", ".join(errs))
diff --git a/chirp/kenwood_tone.py b/chirp/kenwood_tone.py
new file mode 100644
index 0000000..0806deb
--- /dev/null
+++ b/chirp/kenwood_tone.py
@@ -0,0 +1,256 @@
+#
+# Copyright 2026 Dan Smith (chirp@f.danplanet.com)
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+class KenwoodToneModel:
+ """
+ Common tone handling model for Kenwood (and knock-off) radios.
+
+ This provides generalized handling for a tone/dcs encoding scheme that
+ originated on Kenwood radios in the 1990s and has been widely copied by
+ other radio manufacturers.
+
+ Typically CTCSS tones are stored as the frequency in Hertz, multiplied by
+ 10, and sometimes with a flag bit set (tone_flag). Some radios store it as
+ a base-10 integer. For example:
+ 103.5 Hz * 10 becomes 1035, which is then stored as 0x040B.
+
+ Other radios store this as a binary-coded decimal (BCD) number, where each
+ decimal digit (0–9) is represented by a fixed 4-bit binary sequence. An
+ equivalent way of thinking of it is storing a number in hexadecimal and
+ ignoring digits A-F. For example:
+ 103.5 Hz * 10 becomes 1035, which is then stored as 0x1035.
+
+ The method of storage depends on numerical base (tone_enc_base) used for
+ encoding and decoding.
+
+ DCS codes are stored as either octal, decimal, or BCD (dcs_enc_base).
+ For example, DCS 031 can be stored as 0x0019 octal, 0x001F decimal, or
+ 0x0031 BCD / hexadecimal.
+
+ There can be one or more flag bits (dcs_base) set to indicate that it's
+ DCS. Reverse polarity is indicated by another flag bit (pol_mask).
+ Finally, a completely disabled tone/code field is often indicated by
+ 0x0000 or 0xFFFF (tone_init).
+
+ Note that this requires your radio's memory structure to have u16 or ul16
+ fields named exactly "rxtone" and "txtone".
+
+ :param dcs_base: Base value for DCS tones (e.g., 0x4000, 0x2800, 0x8000)
+ :param pol_mask: Bitmask for polarity (e.g., 0x2000, 0x8000, 0x4000)
+ :param tone_init: Initial value for uninitialized tones (0x0000, 0xFFFF)
+ :param tone_flag: Flag to indicate a CTCSS tone (0x0000 or 0x8000)
+ :param dcs_enc_base: Numerical base for DCS encoding (8, 10, or 16)
+ :param tone_enc_base: Numerical base for Tone encoding (10 or 16)
+ """
+
+ def __init__(self, dcs_base, pol_mask, tone_init=0x0000, tone_flag=0x8000,
+ dcs_enc_base=8, tone_enc_base=10):
+ self.dcs_base = int(dcs_base)
+ self.pol_mask = int(pol_mask)
+ self.tone_init = int(tone_init)
+ self.tone_flag = int(tone_flag)
+ assert dcs_enc_base in (8, 10, 16), (
+ "DCS encoding base must be 8, 10, or 16"
+ )
+ self.dcs_enc_base = int(dcs_enc_base)
+ assert tone_enc_base in (10, 16), (
+ "Tone encoding base must be 10 or 16"
+ )
+ self.tone_enc_base = int(tone_enc_base)
+
+ def _get_tone_val(self, tone_val):
+ """
+ Convert a binary tone value to a tuple of (code, polarity).
+
+ :param tone_val: Binary tone value from radio memory
+ :return: Tuple of (code, polarity) or (None, None) if no tone
+ """
+ if tone_val == 0xFFFF or tone_val == 0x0000:
+ return None, None
+
+ code = pol = None
+ if (tone_val & self.dcs_base) == self.dcs_base:
+ if self.dcs_enc_base == 8:
+ code = int("%03o" % (tone_val & 0x07FF))
+ elif self.dcs_enc_base == 10:
+ code = int("%03i" % (tone_val & 0x07FF))
+ elif self.dcs_enc_base == 16:
+ code = int("%03x" % (tone_val & 0x07FF))
+ pol = (tone_val & self.pol_mask) and "R" or "N"
+ else:
+ if self.tone_enc_base == 10:
+ code = (tone_val & 0x7FFF) / 10.0
+ elif self.tone_enc_base == 16:
+ code = float("%04x" % (tone_val & 0x7FFF)) / 10.0
+ return code, pol
+
+ def _set_tone_val(self, code, pol):
+ """
+ Convert a tone code and polarity to a binary value.
+
+ :param code: Tone code (integer for DCS, float for CTCSS)
+ :param pol: Polarity string ("N" or "R") or None for CTCSS
+ :return: Binary tone value
+ """
+ if code is None:
+ return 0x0000
+
+ if pol is not None:
+ val = int("%i" % code, self.dcs_enc_base) | self.dcs_base
+ if pol == "R":
+ val += self.pol_mask
+ return val
+ else:
+ freq = int(round(code * 10))
+ return int("%i" % freq, self.tone_enc_base) + self.tone_flag
+
+ def set_tone(self, mem, _mem):
+ """
+ Set tone values for a memory channel based on UI settings.
+
+ :param mem: Memory channel object from UI
+ :param _mem: Radio memory object
+ """
+ rx_mode = tx_mode = None
+ rxtone = txtone = self.tone_init
+
+ if mem.tmode == "Tone":
+ tx_mode = "Tone"
+ rx_mode = None
+ txtone = self._set_tone_val(mem.rtone, None)
+ elif mem.tmode == "TSQL":
+ rx_mode = tx_mode = "Tone"
+ rxtone = txtone = self._set_tone_val(mem.ctone, None)
+ elif mem.tmode == "DTCS":
+ tx_mode = rx_mode = "DTCS"
+ txtone = self._set_tone_val(mem.dtcs, mem.dtcs_polarity[0])
+ rxtone = self._set_tone_val(mem.dtcs, mem.dtcs_polarity[1])
+ elif mem.tmode == "Cross":
+ tx_mode, rx_mode = mem.cross_mode.split("->")
+ if tx_mode == "DTCS":
+ txtone = self._set_tone_val(mem.dtcs, mem.dtcs_polarity[0])
+ elif tx_mode == "Tone":
+ txtone = self._set_tone_val(mem.rtone, None)
+ if rx_mode == "DTCS":
+ rxtone = self._set_tone_val(mem.rx_dtcs, mem.dtcs_polarity[1])
+ elif rx_mode == "Tone":
+ rxtone = self._set_tone_val(mem.ctone, None)
+
+ _mem.rxtone = rxtone
+ _mem.txtone = txtone
+
+ def get_tone(self, _mem, mem):
+ """
+ Get tone settings from radio memory into UI memory object.
+
+ :param _mem: Radio memory object
+ :param mem: Memory channel object for UI
+ """
+ txtone = _mem.txtone
+ tcode, tpol = self._get_tone_val(txtone)
+ if tcode is not None:
+ if tpol is not None:
+ mem.dtcs = tcode
+ txmode = "DTCS"
+ else:
+ mem.rtone = tcode
+ txmode = "Tone"
+ else:
+ txmode = ""
+
+ rxtone = _mem.rxtone
+ rcode, rpol = self._get_tone_val(rxtone)
+ if rcode is not None:
+ if rpol is not None:
+ mem.rx_dtcs = rcode
+ rxmode = "DTCS"
+ else:
+ mem.ctone = rcode
+ rxmode = "Tone"
+ else:
+ rxmode = ""
+
+ if txmode == "Tone" and not rxmode:
+ mem.tmode = "Tone"
+ elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
+ mem.tmode = "TSQL"
+ elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
+ mem.tmode = "DTCS"
+ elif rxmode or txmode:
+ mem.tmode = "Cross"
+ mem.cross_mode = "%s->%s" % (txmode, rxmode)
+ else:
+ mem.tmode = ""
+
+ mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")
+
+
+def parse_qtdqt(selcall):
+ """Parse a standard "selcall" mode string.
+
+ This parses strings like 'D023N', 'D032R' and '103.5' into parts for
+ use with CHIRP.
+
+ :param selcall: A string like '', '103.5', or 'D023N'
+ :returns: (mode, val, pol) where:
+ - mode is one of: '', 'Tone', 'DTCS'
+ - val is the integer DTCS code or float tone frequency (ex: 023, 103.5)
+ - pol is the DTCS polarity ('N' or 'R') or '' for tone/CSQ
+ """
+ selcall = selcall or ''
+ selcall = selcall.upper().strip()
+ if selcall.startswith('D'):
+ try:
+ val = int(selcall[1:4])
+ pol = selcall[4]
+ if pol == 'I':
+ pol = 'R'
+ return 'DTCS', val, pol
+ except (ValueError, IndexError):
+ raise ValueError(
+ 'DCS value must be in the form "D023N"')
+ elif selcall:
+ try:
+ val = float(selcall)
+ return 'Tone', val, ''
+ except ValueError:
+ raise ValueError(
+ 'Tone value must be in the form "103.5"')
+ else:
+ return '', None, None
+
+
+def format_qtdqt(mode, val, pol):
+ """Format a CHIRP tone spec into a standard 'selcall' string.
+
+ This takes a standard CHIRP (mode, val, pol) tuple and returns a string
+ like is used in several manufacturer's software (i.e. 'D023N', '103.5').
+
+ :param mode: Either '', 'Tone', or 'DTCS'
+ :param val: A float one frequency (103.5) or integer DTCS code (023)
+ :param pol: A DTCS polarity ('N' or 'R')
+ :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
+ else:
+ return ''
diff --git a/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo b/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo
index 36570a8..2b9f136 100644
--- a/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/cs/LC_MESSAGES/CHIRP.mo b/chirp/locale/cs/LC_MESSAGES/CHIRP.mo
new file mode 100644
index 0000000..d934113
--- /dev/null
+++ b/chirp/locale/cs/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/de/LC_MESSAGES/CHIRP.mo b/chirp/locale/de/LC_MESSAGES/CHIRP.mo
index d1c26f0..3a4817a 100644
--- a/chirp/locale/de/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/de/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/el/LC_MESSAGES/CHIRP.mo b/chirp/locale/el/LC_MESSAGES/CHIRP.mo
index c7852e6..59217a3 100644
--- a/chirp/locale/el/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/el/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/es/LC_MESSAGES/CHIRP.mo b/chirp/locale/es/LC_MESSAGES/CHIRP.mo
index 85c8a4e..f0ece33 100644
--- a/chirp/locale/es/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/es/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/fr/LC_MESSAGES/CHIRP.mo b/chirp/locale/fr/LC_MESSAGES/CHIRP.mo
index 61f4a0a..aba9e4a 100644
--- a/chirp/locale/fr/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/fr/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/it/LC_MESSAGES/CHIRP.mo b/chirp/locale/it/LC_MESSAGES/CHIRP.mo
index 6799e3c..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/ja_JP/LC_MESSAGES/CHIRP.mo b/chirp/locale/ja_JP/LC_MESSAGES/CHIRP.mo
index e28969a..8b26595 100644
--- a/chirp/locale/ja_JP/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/ja_JP/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/pl/LC_MESSAGES/CHIRP.mo b/chirp/locale/pl/LC_MESSAGES/CHIRP.mo
index 1f23eca..acba41b 100644
--- a/chirp/locale/pl/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/pl/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/pt_BR/LC_MESSAGES/CHIRP.mo b/chirp/locale/pt_BR/LC_MESSAGES/CHIRP.mo
index a4c4697..603bf1d 100644
--- a/chirp/locale/pt_BR/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/pt_BR/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 57288bf..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/ru/LC_MESSAGES/CHIRP.mo b/chirp/locale/ru/LC_MESSAGES/CHIRP.mo
index d978c35..7b39bab 100644
--- a/chirp/locale/ru/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/ru/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/locale/tr_TR/LC_MESSAGES/CHIRP.mo b/chirp/locale/tr_TR/LC_MESSAGES/CHIRP.mo
index 083176a..16e86c5 100644
--- a/chirp/locale/tr_TR/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/tr_TR/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/locale/zh_CN/LC_MESSAGES/CHIRP.mo b/chirp/locale/zh_CN/LC_MESSAGES/CHIRP.mo
index a3aca06..80c8e7e 100644
--- a/chirp/locale/zh_CN/LC_MESSAGES/CHIRP.mo
+++ b/chirp/locale/zh_CN/LC_MESSAGES/CHIRP.mo
Binary files differ
diff --git a/chirp/platform.py b/chirp/platform.py
index 9cc816e..db872d3 100644
--- a/chirp/platform.py
+++ b/chirp/platform.py
@@ -182,6 +182,9 @@ class UnixPlatform(Platform):
return ver
+ def is_ble_serial(self, serial):
+ return serial.port.startswith('/tmp/ttyBLE')
+
class Win32Platform(Platform):
"""A platform module suitable for Windows systems"""
@@ -230,6 +233,48 @@ class Win32Platform(Platform):
return vers.get(pform,
"Win32 (Unknown %i.%i:%i)" % (pform, sub, build))
+ def is_ble_serial(self, serial):
+ import winreg
+
+ max_ports = 255
+ key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
+ r'HARDWARE\DEVICEMAP\SERIALCOMM')
+ devices = {}
+ for i in range(max_ports):
+ try:
+ # device is something like \Device\com0com24
+ # name is something like COM12
+ device, name, _ = winreg.EnumValue(key, i)
+ devices[name] = device
+ except EnvironmentError:
+ break
+
+ LOG.debug('All device/name pairs: %s' % devices)
+
+ try:
+ # ble-serial names its device BLE, so find it
+ ble_device = devices['BLE']
+ except KeyError:
+ LOG.debug('No BLE device found')
+ return False
+
+ # The pair device appears to always be \Device\com0com14 if
+ # the BLE device is \Device\com0com24
+ pair_device = list(ble_device)
+ # Change 2 to 1 to get the first device of the pair
+ pair_device[-2] = '1'
+ pair_device = ''.join(pair_device)
+ LOG.debug('Found BLE device %s, guessing pair is %s' % (
+ device, pair_device))
+ try:
+ pair_name = dict(((v, k) for k, v in devices.items()))[pair_device]
+ except KeyError:
+ LOG.debug('Pair device not found!')
+ else:
+ LOG.info('BLE pair device is %s' % pair_name)
+
+ return serial.port == pair_name
+
def _get_platform(basepath):
if os.name == "nt":
diff --git a/chirp/settings.py b/chirp/settings.py
index 622ee4d..2954385 100644
--- a/chirp/settings.py
+++ b/chirp/settings.py
@@ -52,6 +52,9 @@ class RadioSettingValue:
def initialize(self):
"""Initialize this value to the stashed value"""
+ if isinstance(self._preinit_current, Exception):
+ # This was communicated as an error during loading
+ return
assert self._current is None and self._preinit_current is not None
self.set_value(self._preinit_current)
self._preinit_current = None
@@ -389,6 +392,10 @@ class RadioSettingValueMap(RadioSettingValueList):
option"""
return self._mem_vals[self._options.index(self.get_value())]
+ def get_selection(self):
+ """Get the user option selected"""
+ return self._current
+
def __trunc__(self):
"""Return memory value that matches current user option"""
index = self._options.index(self._current)
@@ -423,6 +430,16 @@ class RadioSettings(list):
items = [str(self[i]) for i in range(0, len(self))]
return "\n".join(items)
+ def __getitem__(self, key):
+ if isinstance(key, int):
+ return super().__getitem__(key)
+
+ for element in self:
+ if element.get_name() == key:
+ return element
+
+ raise KeyError(f"Invalid key {key}")
+
def walk(self):
"""Iterate over all the RadioSettings in this tree
@@ -445,7 +462,6 @@ class RadioSettings(list):
"""
non_mem_settings = []
for setting in self.walk():
- print("Walking %r" % setting)
if isinstance(setting, MemSetting):
setting.apply_to_memobj(memobj)
else:
@@ -751,9 +767,13 @@ class MemSetting(RadioSetting):
if isinstance(self.value, RadioSettingValueBoolean):
value = self.value._mem_vals[int(value)]
- obj = memobj
- elements = self._path.split('.')
- for element in elements[:-1]:
+ self.set_by_path(memobj, self._path, value)
+
+ @staticmethod
+ def set_by_path(obj, path, value):
+ """Traverse obj according to path and set the value at the leaf"""
+ elements = path.split('.')
+ for element in elements:
if '[' in element:
# foo[i] syntax
name, index = element.split('[', 1)
@@ -761,4 +781,4 @@ class MemSetting(RadioSetting):
obj = obj[int(index.replace(']', ''))]
else:
obj = getattr(obj, element)
- setattr(obj, elements[-1], value)
+ obj.set_value(value)
diff --git a/chirp/share/chirp.desktop b/chirp/share/chirp.desktop
index bd71605..a88eada 100644
--- a/chirp/share/chirp.desktop
+++ b/chirp/share/chirp.desktop
@@ -11,3 +11,4 @@ MimeType=x-scheme-handler/chirp
Categories=Utility;HamRadio
Keywords=Hamradio;Programming;Handheld;Radio;Amateur;Programmer
StartupNotify=true
+StartupWMClass=chirpw
diff --git a/chirp/share/welcome_screen_de.png b/chirp/share/welcome_screen_de.png
new file mode 100644
index 0000000..f75b50a
--- /dev/null
+++ b/chirp/share/welcome_screen_de.png
Binary files differ
diff --git a/chirp/share/welcome_screen_pt_BR.png b/chirp/share/welcome_screen_pt_BR.png
new file mode 100644
index 0000000..7abcfe1
--- /dev/null
+++ b/chirp/share/welcome_screen_pt_BR.png
Binary files differ
diff --git a/chirp/sources/amsats.py b/chirp/sources/amsats.py
new file mode 100644
index 0000000..836ce45
--- /dev/null
+++ b/chirp/sources/amsats.py
@@ -0,0 +1,281 @@
+"""AMSAT and SatNOGS data sources"""
+
+import logging
+import re
+import requests
+
+from chirp import chirp_common
+from chirp import errors
+from chirp.sources import base
+
+LOG = logging.getLogger(__name__)
+
+DATA_URL = ('https://raw.githubusercontent.com/palewire/'
+ 'amateur-satellite-database/main/data/'
+ 'amsat-active-frequencies.json')
+SATNOGS_SATS_URL = 'https://db.satnogs.org/api/satellites/?status=alive'
+SATNOGS_TRANS_URL = ('https://db.satnogs.org/api/transmitters/'
+ '?alive=True&status=active')
+
+
+class RadioAmateurSatellites(base.NetworkResultRadio):
+ """Radio Amateur Satellite database (AMSAT active frequencies)"""
+ VENDOR = 'Radio Amateur'
+ MODEL = 'Satellites'
+
+ def get_label(self):
+ return 'Radio Amateur Satellites'
+
+ def item_to_memory(self, item):
+ """Convert a JSON item to a Memory object"""
+ mem = chirp_common.Memory()
+
+ # Satellite name and NORAD ID
+ name = item.get('name', 'Unknown')
+ norad_id = item.get('norad_id', 'Unknown')
+ mem.name = name[:16] # Most radios have limited name length
+
+ # Frequencies
+ # The JSON can have Multiple frequencies separated by / or -
+ # We'll take the first one for now, or handle ranges if possible.
+ # Downlink is the primary frequency for listening.
+ downlink_str = item.get('downlink')
+ if not downlink_str:
+ LOG.debug('No downlink for %s, skipping', name)
+ return None
+
+ # Simplistic parsing of the first frequency in the string
+ try:
+ # Handle cases like "436.270/10473.350" or "145.850-145.950"
+ first_freq = downlink_str.replace('/', ' ').replace('-', ' ')
+ first_freq = first_freq.split()[0]
+ # Remove asterisks or other markers
+ first_freq = ''.join(c for c in first_freq
+ if c.isdigit() or c == '.')
+ mem.freq = chirp_common.parse_freq(first_freq)
+ except (ValueError, IndexError, errors.InvalidDataError) as e:
+ LOG.warning('Unable to parse downlink freq %r for %s: %s',
+ downlink_str, name, e)
+ return None
+
+ # Uplink for Duplex
+ uplink_str = item.get('uplink')
+ if uplink_str:
+ try:
+ first_uplink = uplink_str.replace('/', ' ').replace('-', ' ')
+ first_uplink = first_uplink.split()[0]
+ first_uplink = ''.join(c for c in first_uplink
+ if c.isdigit() or c == '.')
+ tx_freq = chirp_common.parse_freq(first_uplink)
+ if tx_freq > 0:
+ chirp_common.split_to_offset(mem, mem.freq, tx_freq)
+ except (ValueError, IndexError, errors.InvalidDataError) as e:
+ LOG.debug('Unable to parse uplink freq %r for %s: %s',
+ uplink_str, name, e)
+
+ # Mode parsing
+ mode_str = (item.get('mode') or '').upper()
+ if 'FM' in mode_str:
+ mem.mode = 'FM'
+ elif 'SSB' in mode_str or 'LINEAR' in mode_str:
+ mem.mode = 'USB' # Satellites typically use USB
+ elif 'CW' in mode_str:
+ mem.mode = 'CW'
+ else:
+ mem.mode = 'FM' # Default to FM for wide compatibility
+
+ # Tone parsing (basic)
+ if 'CTCSS' in mode_str:
+ # Try to find something like "67.0Hz"
+ match = re.search(r'(\d+\.?\d*)\s*HZ', mode_str)
+ if match:
+ mem.rtone = float(match.group(1))
+ mem.tmode = 'Tone'
+
+ # Comment field with relevant info
+ # Remove NORAD:<id> as it is not useful info for most users
+ mem.comment = 'Mode:%s' % item.get('mode', 'Unknown')
+ if item.get('satnogs_id'):
+ mem.comment += ' Info: https://db.satnogs.org/satellite/%s' % \
+ norad_id
+
+ mem.comment = mem.comment.strip()
+ return mem
+
+ def do_fetch(self, status, params):
+ status.send_status('Downloading satellite data...', 10)
+
+ try:
+ resp = requests.get(DATA_URL, headers=base.HEADERS, timeout=30)
+ resp.raise_for_status()
+ data = resp.json()
+ except Exception as e:
+ LOG.exception('Failed to download satellite data: %s', e)
+ status.send_fail('Failed to download data: %s' % e)
+ return
+
+ status.send_status('Parsing data...', 50)
+
+ i = 0
+ for item in data:
+ try:
+ mem = self.item_to_memory(item)
+ if mem:
+ mem.number = i
+ self._memories.append(mem)
+ i += 1
+ except Exception as e:
+ LOG.warning('Failed to convert satellite %s: %s',
+ item.get('name'), e)
+ continue
+
+ if not self._memories:
+ status.send_fail('No valid satellite frequencies found!')
+ return
+
+ status.send_status('Done', 100)
+ status.send_end()
+
+
+class SatNOGS(base.NetworkResultRadio):
+ """SatNOGS database source"""
+ VENDOR = 'SatNOGS'
+ MODEL = 'DB'
+
+ def get_label(self):
+ return 'SatNOGS DB'
+
+ def item_to_memory(self, item):
+ """Convert a SatNOGS transmitter item to a Memory object"""
+ mem = chirp_common.Memory()
+
+ # Satellite info is pre-merged into the item in do_fetch
+ sat = item.get('_satellite', {})
+ sat_name = sat.get('name', 'Unknown')
+ trans_desc = item.get('description', '')
+
+ if trans_desc:
+ mem.name = ('%s %s' % (sat_name, trans_desc))[:16].strip()
+ else:
+ mem.name = sat_name[:16]
+
+ # Frequency (downlink_low is in Hz)
+ freq_hz = item.get('downlink_low')
+ if not freq_hz:
+ return None
+ mem.freq = int(freq_hz)
+
+ # Uplink/Duplex
+ uplink_hz = item.get('uplink_low')
+ if uplink_hz:
+ tx_freq = int(uplink_hz)
+ if tx_freq > 0:
+ chirp_common.split_to_offset(mem, mem.freq, tx_freq)
+
+ # Mode mapping
+ orig_mode = (item.get('mode') or '').upper()
+ mem.mode = 'FM' # Default
+ if orig_mode == 'FMN':
+ mem.mode = 'NFM'
+ elif orig_mode == 'DSB':
+ mem.mode = 'AM' # DSB is a form of AM
+ elif orig_mode in chirp_common.MODES:
+ mem.mode = orig_mode
+ elif 'FM' in orig_mode:
+ mem.mode = 'FM'
+ elif 'USB' in orig_mode or 'LINEAR' in orig_mode:
+ mem.mode = 'USB'
+ elif 'LSB' in orig_mode:
+ mem.mode = 'LSB'
+ elif 'CW' in orig_mode:
+ mem.mode = 'CW'
+ elif any(m in orig_mode for m in [
+ 'PSK', 'FSK', 'MSK', 'GMSK', 'GFSK', 'LORA',
+ 'AFSK', 'APT', 'SSTV', 'DVB', 'AHRPT']):
+ mem.mode = 'DIG'
+
+ # Comment
+ norad_id = sat.get('norad_cat_id', 'Unknown')
+ # Only include mode if it's not natively handled or if it's specialized
+ if mem.mode in ['DIG', 'AM'] and orig_mode != mem.mode:
+ mem.comment = 'Mode:%s Type:%s' % (
+ item.get('mode', 'Unknown'), item.get('type', 'Unknown'))
+ else:
+ mem.comment = 'Type:%s' % item.get('type', 'Unknown')
+
+ mem.comment += ' Info: https://db.satnogs.org/satellite/%s' % norad_id
+
+ return mem
+
+ def _fetch_all(self, status, url, label):
+ """Fetch all pages of results from a paginated API"""
+ results = []
+ next_url = url
+ page = 1
+
+ while next_url:
+ status.send_status('Fetching %s (page %i)...' % (label, page),
+ len(results) % 100)
+ try:
+ resp = requests.get(next_url, headers=base.HEADERS, timeout=30)
+ resp.raise_for_status()
+ data = resp.json()
+
+ # SatNOGS API uses DRF pagination
+ if isinstance(data, dict) and 'results' in data:
+ results.extend(data['results'])
+ next_url = data.get('next')
+ else:
+ results.extend(data)
+ next_url = None
+ page += 1
+ except Exception as e:
+ LOG.exception('Failed to fetch %s: %s', label, e)
+ break
+ return results
+
+ def do_fetch(self, status, params):
+ filter_modes = params.get('modes', [])
+
+ status.send_status('Downloading SatNOGS satellites...', 5)
+ satellites = self._fetch_all(status, SATNOGS_SATS_URL, 'satellites')
+
+ status.send_status('Downloading SatNOGS transmitters...', 50)
+ transmitters = self._fetch_all(status, SATNOGS_TRANS_URL,
+ 'transmitters')
+
+ status.send_status('Processing data...', 90)
+
+ # Index satellites by sat_id
+ sat_map = {s['sat_id']: s for s in satellites}
+
+ i = 0
+ for trans in transmitters:
+ sat_id = trans.get('sat_id')
+ if sat_id not in sat_map:
+ continue
+
+ trans['_satellite'] = sat_map[sat_id]
+
+ # Filter by mode if requested
+ if filter_modes:
+ mode = (trans.get('mode') or '').upper()
+ if not any(fm in mode for fm in filter_modes):
+ continue
+
+ try:
+ mem = self.item_to_memory(trans)
+ if mem:
+ mem.number = i
+ self._memories.append(mem)
+ i += 1
+ except Exception:
+ LOG.exception('Failed to convert SatNOGS entry')
+ continue
+
+ if not self._memories:
+ status.send_fail('No valid SatNOGS frequencies found!')
+ return
+
+ status.send_status('Done', 100)
+ status.send_end()
diff --git a/chirp/sources/base.py b/chirp/sources/base.py
index 8e6f7e1..0075251 100644
--- a/chirp/sources/base.py
+++ b/chirp/sources/base.py
@@ -7,7 +7,7 @@ from chirp import errors
LOG = logging.getLogger(__name__)
HEADERS = {
- 'User-Agent': 'chirp/%s Python %i.%i.%i %s' % (
+ 'User-Agent': 'CHIRP/%s Python %i.%i.%i %s' % (
CHIRP_VERSION,
sys.version_info.major, sys.version_info.minor, sys.version_info.micro,
sys.platform),
diff --git a/chirp/wxui/fips.py b/chirp/sources/fips.py
index df3ae3e..df3ae3e 100644
--- a/chirp/wxui/fips.py
+++ b/chirp/sources/fips.py
diff --git a/chirp/sources/repeaterbook.py b/chirp/sources/repeaterbook.py
index 0260cb2..ca0862e 100644
--- a/chirp/sources/repeaterbook.py
+++ b/chirp/sources/repeaterbook.py
@@ -2,6 +2,7 @@ import datetime
import glob
import json
import logging
+import lzma
import math
import os
@@ -11,7 +12,7 @@ from chirp import chirp_common
from chirp import errors
from chirp import platform as chirp_platform
from chirp.sources import base
-from chirp.wxui import fips
+from chirp.sources import fips
LOG = logging.getLogger(__name__)
@@ -80,13 +81,20 @@ class RepeaterBook(base.NetworkResultRadio):
def get_label(self):
return 'RepeaterBook'
+ @staticmethod
+ def get_resource_name(service, country, state):
+ if country not in STATES:
+ # Hack around the translated "All" string in the UI
+ state = 'all'
+ return 'rb%s-%s-%s.json' % (service,
+ country.lower().replace(' ', '_'),
+ state.lower().replace(' ', '_'))
+
def get_data(self, status, country, state, service):
# Ideally we would be able to pull the whole database, but right
# now this is limited to 3500 results, so we need to filter and
# cache by state to stay under that limit.
- fn = 'rb%s-%s-%s.json' % (service,
- country.lower().replace(' ', '_'),
- state.lower().replace(' ', '_'))
+ fn = self.get_resource_name(service, country, state)
db_dir = chirp_platform.get_platform().config_file('repeaterbook')
try:
os.mkdir(db_dir)
@@ -111,38 +119,59 @@ class RepeaterBook(base.NetworkResultRadio):
LOG.debug('RepeaterBook database %s too old: %s',
fn, modified_dt)
- params = {'country': country,
- 'stype': service}
- if country in NA_COUNTRIES:
- export = 'export.php'
- else:
- export = 'exportROW.php'
- if country in STATES:
- params['state'] = state
-
- r = requests.get('https://www.repeaterbook.com/api/%s' % export,
- headers=base.HEADERS,
- params=params,
- stream=True)
- if r.status_code != 200:
+ try:
+ with open(data_file, 'rb') as f:
+ data = json.loads(f.read())
+ etag = data.get('ETag')
+ except Exception as e:
+ LOG.warning('Failed to load cached data from %s: %s',
+ data_file, e)
+ etag = None
+
+ headers = dict(base.HEADERS)
+ if etag:
+ headers['If-None-Match'] = etag
+ try:
+ r = requests.get('https://data.chirpmyradio.com/rb/%s.xz' % fn,
+ headers=headers,
+ stream=True)
+ except requests.exceptions.RequestException as e:
+ LOG.warning('Failed to fetch data from RepeaterBook: %s' % e)
if modified:
+ # If we have a cached file, it's better than nothing so use
+ # it since the server was not contactable
status.send_status('Using cached data', 50)
+ return data_file
+ if r.status_code == 304:
+ status.send_status('Using cached data', 50)
+ LOG.debug('Server reports no changes so marking our cache '
+ 'as current')
+ os.utime(data_file, None)
+ status.send_status('Complete', 50)
+ return data_file
+ elif r.status_code != 200:
+ if modified:
+ # If we have a cached file, it's better than nothing, so use
+ # it since the server refused.
+ status.send_status('Using cached data', 50)
+ return data_file
status.send_fail('Got error code %i (%s) from server' % (
r.status_code, r.reason))
LOG.error('Repeaterbook query %r returned %i (%s)',
r.url, r.status_code, r.reason)
return
- tmp = data_file + '.tmp'
+
chunk_size = 8192
probable_end = 3 << 20
counter = 0
data = b''
- with open(tmp, 'wb') as f:
- for chunk in r.iter_content(chunk_size=chunk_size):
- f.write(chunk)
- data += chunk
- counter += len(chunk)
- status.send_status('Downloading', counter / probable_end * 50)
+ decomp = lzma.LZMADecompressor(format=lzma.FORMAT_XZ)
+ for chunk in r.iter_content(chunk_size=chunk_size):
+ chunk = decomp.decompress(chunk)
+ data += chunk
+ counter += len(chunk)
+ status.send_status('Downloading', counter / probable_end * 50)
+
try:
results = json.loads(data)
except Exception as e:
@@ -153,6 +182,16 @@ class RepeaterBook(base.NetworkResultRadio):
status.send_fail('RepeaterBook returned invalid response')
return
+ try:
+ results['ETag'] = r.headers.get('ETag')
+ tmp = data_file + '.tmp'
+ with open(tmp, 'wb') as f:
+ f.write(json.dumps(results).encode('utf-8'))
+ except Exception as e:
+ LOG.exception('Failed to write data to %s: %s' % (tmp, e))
+ status.send_fail('Failed to write RepeaterBook data to disk')
+ return
+
if results['count']:
try:
os.rename(tmp, data_file)
@@ -394,7 +433,6 @@ ROW_COUNTRIES = [
"Liechtenstein",
"Lithuania",
"Luxembourg",
- "Macedonia",
"Malaysia",
"Malta",
"Moldova",
@@ -404,6 +442,7 @@ ROW_COUNTRIES = [
"Netherlands",
"New Zealand",
"Nicaragua",
+ "North Macedonia",
"Norway",
"Oman",
"Panama",
@@ -413,7 +452,7 @@ ROW_COUNTRIES = [
"Poland",
"Portugal",
"Romania",
- "Russian Federation",
+ "Russia",
"Saint Kitts and Nevis",
"Saint Vincent and the Grenadines",
"San Marino",
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 854bbfa..e316b03 100644
--- a/chirp/wxui/__init__.py
+++ b/chirp/wxui/__init__.py
@@ -11,6 +11,7 @@ from chirp import logger
LOG = logging.getLogger(__name__)
CONF = None
+logging.captureWarnings(True)
def developer_mode(enabled=None):
@@ -39,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
@@ -48,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
@@ -112,15 +113,15 @@ def chirpmain():
'other profile data'))
if sys.platform == 'linux':
desktop = parser.add_mutually_exclusive_group()
- parser.add_argument('--no-linux-gdk-backend', action='store_true',
- help='Do not force GDK_BACKEND=x11')
- 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')
+ 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=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)
@@ -136,10 +137,10 @@ def chirpmain():
config._CONFIG = config.ChirpConfig(args.config_dir)
CONF = config.get()
- # wxGTK on Wayland seems to have problems. Override GDK_BACKEND to
- # use X11, unless we were asked not to.
- # NOTE this needs to happen before we import wx to be effective!
- if sys.platform == 'linux' and not args.no_linux_gdk_backend:
+ if sys.platform == 'linux' and args.compat_linux_gdk_backend:
+ # wxGTK on Wayland seems to have problems in some versions or
+ # environments. Override GDK_BACKEND to use X11, if we were asked to.
+ # NOTE this needs to happen before we import wx to be effective!
os.putenv('GDK_BACKEND', 'x11')
import wx
diff --git a/chirp/wxui/accessibility.py b/chirp/wxui/accessibility.py
new file mode 100644
index 0000000..cd9342e
--- /dev/null
+++ b/chirp/wxui/accessibility.py
@@ -0,0 +1,429 @@
+# Copyright 2026 Deniz Sincar <denizsincar29@gmail.com>
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 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/>.
+"""Screen reader accessibility helpers for wx.grid.Grid and
+wx.propgrid.PropertyGrid.
+
+Both controls paint their own rows/cells instead of using one native
+child window per item, so under MSAA/IAccessible they expose a single
+ROLE_SYSTEM_CLIENT/PANE object for the whole control with no children:
+arrow-key navigation between rows is otherwise completely silent for
+screen reader users.
+
+An earlier version of this fix (see PR #1597) spoke each row directly
+through prismatoid (ethindp/prism) whenever the row changed. That
+worked, but it bypassed the OS accessibility layer entirely, so it
+fought with the narration wx already produces natively for the
+surrounding UI (tab control, panel labels, etc) -- two voices talking
+over each other -- and, on macOS, spoke constantly for every user
+regardless of whether a screen reader was even running, since nothing
+gated it on assistive technology actually being active.
+
+This version does the same job the way any native control does: by
+implementing wx.Accessible so the grid answers IAccessible queries
+(name/value/role/state/focused child) truthfully, and by calling
+wx.Accessible.NotifyEvent() when the focused row/cell changes so
+Windows re-queries it. No screen-reader-specific package or manual
+speech call is involved anywhere in this module -- wx.Accessible and
+NotifyEvent are both part of wxPython itself.
+
+Caveat: wx.Accessible is only implemented for MSW (see the wxWidgets
+docs for wx.Accessible -- "Availability: Only available for MSW").
+On other platforms attach_grid_accessible()/attach_propgrid_accessible()
+still set a plain accessible name (which GTK/Cocoa do surface) but
+install no per-row bridging, so this specifically fixes Windows/NVDA
+and does not attempt -- and does not risk regressing anything -- on
+Linux or macOS. That matches the double/forced-narration report in
+PR #1597, which was on macOS, a platform this module now does nothing
+extra on.
+"""
+
+import logging
+
+import wx
+
+from chirp.wxui import config
+
+LOG = logging.getLogger(__name__)
+
+CONF = config.get()
+
+
+def _accessible_supported():
+ """Probe whether wx.Accessible actually works on this platform.
+
+ wx.Accessible exists as a class attribute on every platform (it's
+ part of the Phoenix bindings), but it's only *implemented* for
+ MSW: on GTK/Cocoa builds ``wx.Accessible()`` raises
+ NotImplementedError from the underlying C++ the moment you try to
+ construct one, even though ``hasattr(wx, 'Accessible')`` is True
+ there too. So we have to actually try instantiating it rather than
+ checking for the attribute.
+ """
+ if CONF.get_bool('disable_accessibility', 'state', default=False):
+ return False
+ accessible_cls = getattr(wx, 'Accessible', None)
+ if accessible_cls is None:
+ return False
+ try:
+ accessible_cls()
+ except NotImplementedError:
+ return False
+ return True
+
+
+# Real per-row screen reader support (wx.Accessible) only works on
+# Windows builds of wxWidgets/wxPython; see _accessible_supported().
+HAS_ACCESSIBLE = _accessible_supported()
+
+
+def _acc_state(*names):
+ """OR together wx.ACC_STATE_SYSTEM_<NAME> flags looked up by name.
+
+ Looked up defensively (rather than hardcoded as integers) since
+ only a handful of these are documented for wxPython and the exact
+ set available can vary by version; a name that isn't present in
+ this build is simply skipped instead of raising.
+ """
+ value = 0
+ for name in names:
+ value |= getattr(wx, 'ACC_STATE_SYSTEM_' + name, 0)
+ return value
+
+
+def _notify(event_name, window, child_id):
+ """Tell the OS a virtual child's focus/selection/value changed.
+
+ This is the piece that makes screen readers re-query our
+ wx.Accessible object on their own, instead of us pushing speech
+ ourselves. No-op if wx.Accessible isn't available on this platform
+ or this wxPython build doesn't expose the named event constant.
+ """
+ if not HAS_ACCESSIBLE:
+ return
+ event_type = getattr(wx, event_name, None)
+ if event_type is None:
+ LOG.debug('wx.%s not available in this wxPython build', event_name)
+ return
+ try:
+ wx.Accessible.NotifyEvent(event_type, window,
+ wx.OBJID_CLIENT, child_id)
+ except Exception:
+ LOG.debug('NotifyEvent failed', exc_info=True)
+
+
+def _notify_focus(window, child_id):
+ _notify('ACC_EVENT_OBJECT_FOCUS', window, child_id)
+ _notify('ACC_EVENT_OBJECT_SELECTION', window, child_id)
+
+
+def _notify_value_change(window, child_id):
+ _notify('ACC_EVENT_OBJECT_VALUECHANGE', window, child_id)
+
+
+class GridAccessible(wx.Accessible):
+ """wx.Accessible for a wx.grid.Grid's grid window.
+
+ Exposes one virtual child per cell (1-based childId, row-major, as
+ IAccessible requires) whose name is built from the column header
+ and current cell text, so a screen reader reads it the same way it
+ would any other table/list control.
+ """
+
+ def __init__(self, grid):
+ super().__init__()
+ self.grid = grid # the wx.grid.Grid, not GetGridWindow()
+
+ def _row_col(self, child_id):
+ cols = self.grid.GetNumberCols()
+ if child_id < 1 or cols <= 0:
+ return None
+ row, col = divmod(child_id - 1, cols)
+ if row >= self.grid.GetNumberRows():
+ return None
+ return row, col
+
+ def GetChildCount(self):
+ return (wx.ACC_OK,
+ self.grid.GetNumberRows() * self.grid.GetNumberCols())
+
+ def GetChild(self, childId):
+ if childId == 0:
+ return wx.ACC_OK, self
+ # A plain int childId with no wx.Accessible of its own is a
+ # "simple element" per the wx.Accessible docs.
+ return wx.ACC_OK, None
+
+ def GetName(self, childId):
+ if childId == 0:
+ return wx.ACC_OK, self.grid.GetGridWindow().GetName()
+ cell = self._row_col(childId)
+ if not cell:
+ return wx.ACC_FAIL, ''
+ row, col = cell
+ header = self.grid.GetColLabelValue(col)
+ value = self.grid.GetCellValue(row, col) or _('empty')
+ return wx.ACC_OK, _('%s %s, row %d') % (header, value, row + 1)
+
+ def GetValue(self, childId):
+ cell = self._row_col(childId)
+ if not cell:
+ return wx.ACC_OK, ''
+ row, col = cell
+ return wx.ACC_OK, self.grid.GetCellValue(row, col)
+
+ def GetRole(self, childId):
+ if childId == 0:
+ return wx.ACC_OK, wx.ROLE_SYSTEM_TABLE
+ return wx.ACC_OK, wx.ROLE_SYSTEM_CELL
+
+ def GetState(self, childId):
+ state = _acc_state('FOCUSABLE', 'SELECTABLE')
+ if childId == 0:
+ return wx.ACC_OK, state
+ cell = self._row_col(childId)
+ if not cell:
+ return wx.ACC_FAIL, 0
+ if cell == (self.grid.GetGridCursorRow(),
+ self.grid.GetGridCursorCol()):
+ state |= _acc_state('FOCUSED', 'SELECTED')
+ return wx.ACC_OK, state
+
+ def GetFocus(self):
+ row = self.grid.GetGridCursorRow()
+ col = self.grid.GetGridCursorCol()
+ cols = self.grid.GetNumberCols()
+ if row < 0 or col < 0 or cols <= 0:
+ return wx.ACC_OK, self
+ return wx.ACC_OK, row * cols + col + 1
+
+ def GetLocation(self, elementId):
+ window = self.grid.GetGridWindow()
+ if elementId == 0:
+ return wx.ACC_OK, window.GetScreenRect()
+ cell = self._row_col(elementId)
+ if not cell:
+ return wx.ACC_FAIL, wx.Rect()
+ row, col = cell
+ rect = self.grid.CellToRect(row, col)
+ rect.SetPosition(window.ClientToScreen(rect.GetTopLeft()))
+ return wx.ACC_OK, rect
+
+
+def attach_grid_accessible(grid, name=None):
+ """Give a wx.grid.Grid a real per-cell accessible tree.
+
+ Binds EVT_GRID_SELECT_CELL to notify Windows of the new focused
+ cell so screen readers announce cell navigation on their own --
+ no speech is pushed by this code.
+ """
+ window = grid.GetGridWindow()
+ if name:
+ window.SetName(name)
+ if not HAS_ACCESSIBLE:
+ return None
+
+ try:
+ accessible = GridAccessible(grid)
+ except NotImplementedError:
+ # Belt-and-suspenders: _accessible_supported() already probed
+ # this at import time, but if it's ever wrong for some build
+ # we still shouldn't crash grid construction over it.
+ return None
+ window.SetAccessible(accessible)
+
+ def _on_select_cell(event):
+ event.Skip()
+ cols = grid.GetNumberCols()
+ if cols <= 0:
+ return
+ child_id = event.GetRow() * cols + event.GetCol() + 1
+ _notify_focus(window, child_id)
+
+ grid.Bind(wx.grid.EVT_GRID_SELECT_CELL, _on_select_cell)
+ return accessible
+
+
+class PropertyGridAccessible(wx.Accessible):
+ """wx.Accessible for a wx.propgrid.PropertyGrid.
+
+ Exposes one virtual child per visible row (1-based childId, in
+ display order) so screen readers get a real name/value/role/state
+ for each property instead of the single opaque pane
+ wx.propgrid.PropertyGrid otherwise reports.
+
+ speech_fn(prop) -> str, if given, overrides the default
+ "<label> <value>" rendering (e.g. to add type/locked/unspecified
+ wording); it is only used for GetName(), the accessible name is
+ what screen readers read on focus.
+ """
+
+ def __init__(self, pg, speech_fn=None):
+ super().__init__()
+ self.pg = pg
+ self.speech_fn = speech_fn
+
+ def _visible_props(self):
+ it = self.pg.GetIterator()
+ props = []
+ while not it.AtEnd():
+ props.append(it.GetProperty())
+ it.Next()
+ return props
+
+ def _prop_for_child(self, childId):
+ if childId < 1:
+ return None
+ props = self._visible_props()
+ if childId > len(props):
+ return None
+ return props[childId - 1]
+
+ def GetChildCount(self):
+ return wx.ACC_OK, len(self._visible_props())
+
+ def GetChild(self, childId):
+ if childId == 0:
+ return wx.ACC_OK, self
+ return wx.ACC_OK, None
+
+ def GetName(self, childId):
+ if childId == 0:
+ return wx.ACC_OK, self.pg.GetName()
+ prop = self._prop_for_child(childId)
+ if prop is None:
+ return wx.ACC_FAIL, ''
+ if self.speech_fn:
+ return wx.ACC_OK, self.speech_fn(prop)
+ if prop.IsCategory():
+ return wx.ACC_OK, _('Group: %s') % prop.GetLabel()
+ label = prop.GetLabel() or prop.GetName()
+ return wx.ACC_OK, '%s %s' % (label, prop.GetValueAsString())
+
+ def GetValue(self, childId):
+ prop = self._prop_for_child(childId)
+ if prop is None or prop.IsCategory():
+ return wx.ACC_OK, ''
+ return wx.ACC_OK, prop.GetValueAsString()
+
+ def GetRole(self, childId):
+ if childId == 0:
+ return wx.ACC_OK, wx.ROLE_SYSTEM_LIST
+ prop = self._prop_for_child(childId)
+ if prop is not None and prop.IsCategory():
+ return wx.ACC_OK, wx.ROLE_SYSTEM_GROUPING
+ if isinstance(prop, wx.propgrid.BoolProperty):
+ return wx.ACC_OK, wx.ROLE_SYSTEM_CHECKBUTTON
+ if isinstance(prop, wx.propgrid.EnumProperty):
+ return wx.ACC_OK, wx.ROLE_SYSTEM_COMBOBOX
+ return wx.ACC_OK, wx.ROLE_SYSTEM_LISTITEM
+
+ def GetState(self, childId):
+ state = _acc_state('FOCUSABLE', 'SELECTABLE')
+ if childId == 0:
+ return wx.ACC_OK, state
+ prop = self._prop_for_child(childId)
+ if prop is None:
+ return wx.ACC_FAIL, 0
+ if prop is self.pg.GetSelectedProperty():
+ state |= _acc_state('FOCUSED', 'SELECTED')
+ if isinstance(prop, wx.propgrid.BoolProperty) and prop.GetValue():
+ state |= _acc_state('CHECKED')
+ if not prop.IsEnabled():
+ state |= _acc_state('UNAVAILABLE')
+ return wx.ACC_OK, state
+
+ def GetFocus(self):
+ prop = self.pg.GetSelectedProperty()
+ if prop is None:
+ return wx.ACC_OK, self
+ props = self._visible_props()
+ try:
+ return wx.ACC_OK, props.index(prop) + 1
+ except ValueError:
+ return wx.ACC_OK, self
+
+ def GetDescription(self, childId):
+ """Exposed via the OS accessibility layer (e.g. NVDA's "report
+ object description" command) instead of being pushed as speech
+ on a hijacked F1 key press."""
+ prop = self._prop_for_child(childId) if childId else None
+ if prop is None:
+ return wx.ACC_OK, ''
+ return wx.ACC_OK, prop.GetHelpString() or ''
+
+
+def attach_propgrid_accessible(pg, name, speech_fn=None):
+ """Give a wx.propgrid.PropertyGrid a real per-row accessible tree.
+
+ Binds EVT_PG_SELECTED to notify Windows of the newly focused row
+ so screen readers announce it on their own.
+ """
+ pg.SetName(name)
+ if not HAS_ACCESSIBLE:
+ return None
+
+ try:
+ accessible = PropertyGridAccessible(pg, speech_fn=speech_fn)
+ except NotImplementedError:
+ return None
+ pg.SetAccessible(accessible)
+
+ def _on_selected(event):
+ event.Skip()
+ prop = event.GetProperty()
+ if prop is None:
+ return
+ props = accessible._visible_props()
+ try:
+ child_id = props.index(prop) + 1
+ except ValueError:
+ return
+ _notify_focus(pg, child_id)
+
+ pg.Bind(wx.propgrid.EVT_PG_SELECTED, _on_selected)
+ return accessible
+
+
+def notify_propgrid_value_change(pg, accessible, prop):
+ """Tell Windows a property's value changed mid-edit (e.g. arrowing
+ through an open EnumProperty combo box, or toggling a checkbox),
+ so screen readers pick up the pending value the same way they'd
+ pick up a committed one. No-op if accessible attachment failed."""
+ if accessible is None:
+ return
+ props = accessible._visible_props()
+ try:
+ child_id = props.index(prop) + 1
+ except ValueError:
+ return
+ _notify_value_change(pg, child_id)
+
+
+# Screen reader accessibility for wx.propgrid.PropertyGrid lives in
+# chirp/wxui/accessibility.py (wx.Accessible-based; see that module's
+# docstring for why it replaced an earlier prismatoid-based approach).
+# enable_propgrid_a11y() is kept as a thin compatibility wrapper since
+# radioinfo.py's read-only PropertyGrid pages don't have RadioSetting
+# objects backing them the way ChirpSettingGrid's pages do.
+def enable_propgrid_a11y(pg, accessible_name):
+ """Give a wx.propgrid.PropertyGrid basic screen reader feedback.
+
+ For grids backed by RadioSetting objects, see ChirpSettingGrid,
+ which passes a richer speech_fn (type/locked/unspecified wording,
+ in-progress edit announcements, F1 description lookup) to
+ accessibility.attach_propgrid_accessible() directly instead of
+ going through this wrapper.
+ """
+ return attach_propgrid_accessible(pg, accessible_name)
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 d5250aa..f99a394 100644
--- a/chirp/wxui/bugreport.py
+++ b/chirp/wxui/bugreport.py
@@ -34,10 +34,14 @@ from chirp import platform as chirp_platform
from chirp.wxui import common
from chirp.wxui import config
from chirp.wxui import serialtrace
+from chirp.wxui import report
+
_ = wx.GetTranslation
CONF = config.get()
-BASE = CONF.get('baseurl', 'chirpmyradio') or 'https://www.chirpmyradio.com'
+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()
@@ -146,10 +150,11 @@ class BugReportContext:
self.chirpmain = chirpmain
self.editor = chirpmain.current_editorset
self.session = requests.Session()
- self.session.headers = {
- 'User-Agent': 'CHIRP/%s' % CHIRP_VERSION,
+ report.ensure_session()
+ self.session.headers = dict(report.SESSION.headers)
+ self.session.headers.update({
'Referer': 'https://chirpmyradio.com/projects/chirp/issues/new',
- }
+ })
def get_page(self, name, cls):
if not hasattr(self, 'page_%s' % name):
@@ -248,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)
@@ -366,12 +371,15 @@ class NewBugInfo(BugReportPage):
INST = _('Enter information about the bug including a short but '
'meaningful subject and information about the radio model '
'(if applicable) in question. In the next step you will have '
- 'a chance to add more details about the problem.')
+ 'a chance to add more details about the problem. '
+ 'Before proceeding, please search for duplicate issues!')
def _build(self, vbox):
self.context.bugsubj = self.context.bugmodel = None
+ self.searched_dupes = None
+
panel = wx.Panel(self)
- vbox.Add(panel, 1, border=20, flag=wx.EXPAND)
+ vbox.Add(panel, 0, border=20, flag=wx.EXPAND | wx.BOTTOM)
grid = wx.FlexGridSizer(2, 5, 0)
grid.AddGrowableCol(1)
panel.SetSizer(grid)
@@ -382,6 +390,7 @@ class NewBugInfo(BugReportPage):
self.subj = wx.TextCtrl(panel)
self.subj.SetMaxLength(100)
self.subj.Bind(wx.EVT_TEXT, self.validate_next)
+ self.subj.SetFocus()
grid.Add(self.subj, 1, border=20,
flag=wx.EXPAND | wx.RIGHT | wx.LEFT)
@@ -398,8 +407,30 @@ class NewBugInfo(BugReportPage):
self.context.editor._radio.VENDOR,
self.context.editor._radio.MODEL))
+ hbox = wx.BoxSizer(wx.HORIZONTAL)
+ panel = wx.Panel(self)
+ panel.SetSizer(hbox)
+ self.searched_dupes = wx.CheckBox(
+ panel, label=_('I have'))
+ self.searched_dupes.Bind(wx.EVT_CHECKBOX, self.validate_next)
+ hbox.AddStretchSpacer(1)
+ hbox.Add(self.searched_dupes, 0)
+ hbox.Add(
+ wx.adv.HyperlinkCtrl(
+ panel,
+ label=_('searched for duplicate issues'),
+ 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)
+
+ vbox.Add(panel, 0, border=20, flag=wx.EXPAND | wx.BOTTOM)
+
def _validate_next(self):
- return len(self.subj.GetValue()) > 10
+ return (len(self.subj.GetValue()) > 10 and
+ self.searched_dupes.GetValue())
def validate_success(self, *a):
self.context.bugsubj = self.subj.GetValue()
@@ -562,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)
@@ -702,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/clone.py b/chirp/wxui/clone.py
index 9ccba59..d226d71 100644
--- a/chirp/wxui/clone.py
+++ b/chirp/wxui/clone.py
@@ -50,7 +50,8 @@ def is_prolific_warning(string):
def get_model_label(rclass):
detected = ','.join(set([
detected_value(rclass, m)
- for m in rclass.detected_models(include_self=False)]))
+ for m in rclass.detected_models(include_self=False)
+ if not m.is_minor_variant()]))
if len(detected) > (32 - 5):
detected = 'others'
return detected
diff --git a/chirp/wxui/common.py b/chirp/wxui/common.py
index d2c4710..b6c3aa4 100644
--- a/chirp/wxui/common.py
+++ b/chirp/wxui/common.py
@@ -33,12 +33,33 @@ from chirp import errors
from chirp import logger
from chirp import platform as chirp_platform
from chirp import settings
+from chirp.wxui import accessibility
from chirp.wxui import config
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()
@@ -201,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:
@@ -211,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))
@@ -372,11 +441,28 @@ class ChirpSettingGrid(wx.Panel):
self._group = settinggroup
self._settings = {}
self._needs_reload = False
+ # (prop_name, spoken text) for a value the user is in the middle
+ # of choosing (arrowing through an open EnumProperty combo box,
+ # toggling a checkbox) but hasn't committed yet. Consulted by
+ # _property_speech() so the accessible name reflects the pending
+ # value rather than the last-committed one; see _check_change().
+ self._pending_value = None
self.pg = wx.propgrid.PropertyGrid(
self,
style=wx.propgrid.PG_SPLITTER_AUTO_CENTER |
wx.propgrid.PG_BOLD_MODIFIED)
+ # wx.propgrid.PropertyGrid does not expose a usable per-row
+ # accessibility tree (the whole grid reports as a single
+ # ROLE_SYSTEM_CLIENT/PANE object with all row text concatenated),
+ # so arrow-key navigation is otherwise silent for screen reader
+ # users. accessibility.attach_propgrid_accessible() gives it a
+ # real wx.Accessible-backed per-row tree instead (Windows only;
+ # see chirp/wxui/accessibility.py), using self._property_speech()
+ # for each row's accessible name.
+ self._accessible = accessibility.attach_propgrid_accessible(
+ self.pg, _('Settings: %s') % settinggroup.get_shortname(),
+ speech_fn=self._property_speech)
self.pg.Bind(wx.propgrid.EVT_PG_CHANGED, self._pg_changed)
self.pg.Bind(wx.EVT_MOTION, self._mouseover)
@@ -385,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)
@@ -403,7 +489,11 @@ class ChirpSettingGrid(wx.Panel):
tip = None
if prop:
setting = self.get_setting_by_name(prop.GetName())
- if isinstance(setting.value, settings.RadioSettingValueString):
+ # FIXME: Indexed properties will have their INDEX_CHAR replaced
+ # here and thus won't match the actual setting name, so we'll
+ # get None here. Avoid a trace for now, but this needs fixing.
+ if setting and isinstance(setting.value,
+ settings.RadioSettingValueString):
tip = setting.__doc__ or ''
if setting.value.maxlength == setting.value._minlength:
extra = '%i characters' % setting.value.maxlength
@@ -416,6 +506,114 @@ class ChirpSettingGrid(wx.Panel):
event.GetEventObject().SetToolTip(tip)
+ def _value_as_speech(self, prop, raw_value=None):
+ """Render a property's value as something worth speaking.
+
+ If raw_value is given (a wx.propgrid 'pending' value, as found on
+ EVT_PG_CHANGING events, where for an EnumProperty this is the
+ integer index rather than display text) it is used instead of the
+ property's current committed value. This lets callers announce a
+ value the user is in the process of selecting, before they've
+ confirmed it with Enter/Tab/focus-out.
+ """
+ if isinstance(prop, wx.propgrid.BoolProperty):
+ value = prop.GetValue() if raw_value is None else raw_value
+ return _('checked') if value else _('unchecked')
+ elif isinstance(prop, wx.propgrid.EnumProperty):
+ if raw_value is None:
+ return prop.GetValueAsString()
+ setting = self.get_setting_by_name(prop.GetName())
+ choices = setting and self._choices.get(setting.get_name())
+ try:
+ return choices[raw_value] if choices else str(raw_value)
+ except (IndexError, TypeError):
+ return str(raw_value)
+ elif raw_value is not None:
+ return str(raw_value)
+ return prop.GetValueAsString()
+
+ def _property_type_label(self, prop):
+ """Return a short, translated description of a property's editor
+ type (checkbox/number/list/text), or None if not applicable.
+
+ wx.propgrid.PropertyGrid gives screen readers no indication of
+ what kind of control a row is (this information is normally
+ conveyed visually by the editor widget shown when the row is
+ focused), so we speak it explicitly as part of _announce_property.
+ """
+ if isinstance(prop, wx.propgrid.BoolProperty):
+ return _('checkbox')
+ elif isinstance(prop, wx.propgrid.EnumProperty):
+ return _('list')
+ elif isinstance(prop, (wx.propgrid.IntProperty,
+ wx.propgrid.FloatProperty)):
+ return _('number')
+ elif isinstance(prop, wx.propgrid.StringProperty):
+ return _('text')
+ return None
+
+ def _property_state_label(self, prop, setting):
+ """Return a short, translated description of a property's state
+ (locked/unspecified), or None if there's nothing notable to say.
+
+ This mirrors the visual-only cues the grid otherwise uses (grey
+ text for disabled rows, a yellow background for unspecified
+ values), neither of which reaches a screen reader user.
+ """
+ if prop.IsValueUnspecified():
+ return _('unspecified')
+ if not prop.IsEnabled():
+ return _('locked')
+ return None
+
+ def _property_speech(self, prop):
+ """Build the accessible name for a property row.
+
+ Used as the speech_fn for accessibility.attach_propgrid_accessible()
+ -- returned text becomes the row's wx.Accessible name, which is
+ what screen readers read on navigation, via NotifyEvent rather
+ than a manual speech call (see chirp/wxui/accessibility.py).
+
+ Categories get just their name, since they're headings rather
+ than editable fields. Ordinary properties are rendered as
+ '<name> <value>, <type>, <state>', omitting the type/state
+ segments when there's nothing notable to add so the common case
+ stays short.
+ """
+ if prop.IsCategory():
+ return _('Group: %s') % prop.GetLabel()
+
+ setting = self.get_setting_by_name(prop.GetName())
+ label = prop.GetLabel()
+ if not label:
+ # Properties belonging to a multi-value setting (RadioSetting
+ # with more than one value) have their visible label cleared
+ # in _add_items() since the shared name is shown once on the
+ # category row above them instead. Reconstruct something
+ # useful to say by falling back to the setting's name and,
+ # if there's more than one sibling value, the position within
+ # the group, e.g. 'Squelch Level 2' rather than just repeating
+ # the bare setting name for every row.
+ base = setting and setting.get_shortname() or prop.GetName()
+ if setting and len(setting.keys()) > 1:
+ index = int(prop.GetName().rsplit(INDEX_CHAR, 1)[-1])
+ label = '%s %d' % (base, index + 1)
+ else:
+ label = base
+ if self._pending_value and self._pending_value[0] == prop.GetName():
+ value = self._pending_value[1]
+ else:
+ value = self._value_as_speech(prop)
+
+ parts = ['%s %s' % (label, value)]
+ type_label = self._property_type_label(prop)
+ if type_label:
+ parts.append(type_label)
+ state_label = self._property_state_label(prop, setting)
+ if state_label:
+ parts.append(state_label)
+ return ', '.join(parts)
+
def _add_items(self, group, parent=None):
def append(item):
if parent:
@@ -459,6 +657,11 @@ class ChirpSettingGrid(wx.Panel):
if len(element.keys()) > 1:
editor.SetLabel('')
editor.Enable(value.get_mutable())
+ # Native PGProperty help string, surfaced to screen
+ # readers via wx.Accessible.GetDescription() (e.g. NVDA's
+ # "report object description" command) instead of a
+ # hijacked F1 key press pushing speech directly.
+ editor.SetHelpString((element.__doc__ or '').strip())
append(editor)
self._settings[element.get_name()] = element
if editor.IsValueUnspecified():
@@ -482,6 +685,23 @@ class ChirpSettingGrid(wx.Panel):
LOG.error('Got change event for unknown setting %s' % (
event.GetPropertyName()))
return
+ # EVT_PG_CHANGING fires for every pending value the user lands on
+ # while editing (e.g. each item highlighted while arrowing through
+ # an open EnumProperty combo box, or toggling a BoolProperty's
+ # checkbox), even before the change is committed with Enter/Tab.
+ # The editor sub-widget that briefly gets focus here (an
+ # OwnerDrawnComboBox, a checkbox, ...) reports its raw wx class
+ # name to screen readers instead of the setting it belongs to, and
+ # selecting a different item inside it is otherwise silent.
+ # Record the pending value so _property_speech() reflects it, then
+ # notify Windows the accessible value changed -- same idea as
+ # _property_speech announcing committed values on row-to-row
+ # navigation, but via NotifyEvent instead of a direct speech call.
+ prop = event.GetProperty()
+ self._pending_value = (
+ prop.GetName(), self._value_as_speech(prop, event.GetValue()))
+ accessibility.notify_propgrid_value_change(
+ self.pg, self._accessible, prop)
warning = setting.get_warning(event.GetValue())
if warning:
r = wx.MessageBox(warning, _('WARNING!'),
@@ -777,8 +997,8 @@ def expose_logs(level, root, label, maxlen=128, parent=None,
try:
yield
except Exception as e:
- LOG.warning('Failure while capturing logs (showing=%s): %s',
- show_on_raise, e)
+ LOG.exception('Failure while capturing logs (showing=%s): %s',
+ show_on_raise, e)
error = e
finally:
lines = list(itertools.chain.from_iterable(x.get_history()
diff --git a/chirp/wxui/config.py b/chirp/wxui/config.py
index 73948ab..eff9329 100644
--- a/chirp/wxui/config.py
+++ b/chirp/wxui/config.py
@@ -161,7 +161,7 @@ class ChirpConfigProxy:
if val is None:
return default
else:
- return val == "True"
+ return val.lower() == 'true'
def set_bool(self, key, value, section=None):
self.set(key, str(bool(value)), section)
diff --git a/chirp/wxui/developer.py b/chirp/wxui/developer.py
index d40b89b..bdc5da8 100644
--- a/chirp/wxui/developer.py
+++ b/chirp/wxui/developer.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 datetime
import functools
import logging
import os
@@ -403,6 +404,8 @@ class ChirpBrowserPanel(wx.lib.scrolledpanel.ScrolledPanel):
editor = ChirpIntegerEditor(self, obj, labelfmt=labelfmt)
elif isinstance(obj, bitwise.structDataElement):
self._parent.add_sub_panel(name, obj, self)
+ elif isinstance(obj, bitwise.bcdDataElement):
+ editor = ChirpBCDEditor(self, obj)
if editor:
self.add_editor(name, editor)
self._initialized = True
@@ -610,8 +613,18 @@ class IssueModuleLoader:
issue = r.json()['issue']
allowed_states = ['New', 'In Progress', 'Resolved', 'Incomplete',
'Blocked']
+ if issue['status']['is_closed']:
+ # If it was closed in the last two weeks, consider the case where
+ # a user is waiting for the next build
+ recently_closed = (
+ datetime.datetime.fromisoformat(issue['closed_on'][:-1]) >
+ (datetime.datetime.now() - datetime.timedelta(days=14)))
+ else:
+ recently_closed = False
valid = (issue['status']['name'] in allowed_states
- and not issue['status']['is_closed'])
+ and not issue['status']['is_closed']) or recently_closed
+ LOG.debug('Issue valid=%s recently_closed=%s state=%s' % (
+ valid, recently_closed, issue['status']['name']))
if not valid:
LOG.warning('Issue %i is in state %s', issue_num, issue['status'])
raise IsssueModuleLoadError(
diff --git a/chirp/wxui/main.py b/chirp/wxui/main.py
index b7380d7..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
@@ -908,6 +909,17 @@ class ChirpMain(wx.Frame):
self.Bind(wx.EVT_MENU, self._menu_query_mapy73pl, query_mapy73pl_item)
source_menu.Append(query_mapy73pl_item)
+ query_amsat_item = wx.MenuItem(
+ source_menu, wx.NewId(),
+ 'Radio Amateur Satellites (GitHub Mirror)')
+ self.Bind(wx.EVT_MENU, self._menu_query_amsats, query_amsat_item)
+ source_menu.Append(query_amsat_item)
+
+ query_satnogs_item = wx.MenuItem(source_menu, wx.NewId(),
+ 'SatNOGS DB (Direct API)')
+ self.Bind(wx.EVT_MENU, self._menu_query_satnogs, query_satnogs_item)
+ source_menu.Append(query_satnogs_item)
+
radio_menu.Append(wx.MenuItem(radio_menu, wx.ID_SEPARATOR))
auto_edits = wx.MenuItem(radio_menu, wx.NewId(),
@@ -1358,7 +1370,7 @@ class ChirpMain(wx.Frame):
else:
i_index = len(formats)
formats.insert(i_index,
- (_('All supported formats|') +
+ (_('All supported formats') + '|' +
';'.join(all_extensions)))
wildcard = '|'.join(formats)
with wx.FileDialog(self, _('Open a file'),
@@ -1696,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
@@ -1961,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 = _(
@@ -1973,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():
@@ -2074,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)
@@ -2100,6 +2138,12 @@ GNU General Public License for more details."""
def _menu_query_mapy73pl(self, event):
self._do_network_query(query_sources.Mapy73PlQueryDialog)
+ def _menu_query_amsats(self, event):
+ self._do_network_query(query_sources.RadioAmateurSatellitesQueryDialog)
+
+ def _menu_query_satnogs(self, event):
+ self._do_network_query(query_sources.SatNOGSQueryDialog)
+
def display_update_notice(version):
LOG.info('Server reports %s is latest' % version)
diff --git a/chirp/wxui/memedit.py b/chirp/wxui/memedit.py
index d36891d..faaa427 100644
--- a/chirp/wxui/memedit.py
+++ b/chirp/wxui/memedit.py
@@ -15,6 +15,7 @@
import contextlib
import functools
+import itertools
import logging
import pickle
import secrets
@@ -33,6 +34,7 @@ from chirp.drivers import generic_csv
from chirp import errors
from chirp import import_logic
from chirp import settings
+from chirp.wxui import accessibility
from chirp.wxui import config
from chirp.wxui import common
from chirp.wxui import developer
@@ -40,6 +42,7 @@ from chirp.wxui import memquery
_ = wx.GetTranslation
LOG = logging.getLogger(__name__)
+
CONF = config.get()
WX_GTK = 'gtk' in wx.version().lower()
TX_WORKFLOW_ID = wx.NewId()
@@ -71,10 +74,10 @@ class ChirpGridTable(wx.grid.GridStringTable):
# underlying data store.
# The list of values we actually sort is a tuple of:
# (empty, value, location)
- # Where the empty flag is conditionally negated based on our sort
- # order. That convoluted scheme makes us always sort empty values at
- # the bottom instead of the top of the list, which is what a human
- # will want.
+ # We do that to iterate the whole grid once, collecting the data we
+ # need, and then enter it into a mapping in order putting the non-
+ # empty values first, followed by the empties so that the sorted non-
+ # empty rows are always bunched at the top of the grid.
def sortable_value(val):
return self._col_defs[col].get_sortable_value(val)
@@ -83,16 +86,19 @@ class ChirpGridTable(wx.grid.GridStringTable):
self._rowmap = {x: x for x in range(0, self.GetRowsCount())}
else:
sorted_values = sorted((
- (asc != bool(
- super(ChirpGridTable, self).GetValue(
- realrow, col).strip()),
+ (bool(super(ChirpGridTable, self).GetValue(realrow, 0)),
sortable_value(
super(ChirpGridTable, self).GetValue(realrow, col)),
realrow)
for realrow in range(0, self.GetRowsCount())),
- reverse=not asc)
- self._rowmap = dict((i, mapping[-1])
- for i, mapping in enumerate(sorted_values))
+ reverse=not asc)
+
+ self._rowmap = dict(
+ (i, mapping[-1])
+ for i, mapping in enumerate(
+ itertools.chain(
+ [x for x in sorted_values if x[0]],
+ [x for x in sorted_values if not x[0]])))
self._rowmap_rev = {v: k for k, v in self._rowmap.items()}
def GetValue(self, row, col):
@@ -107,6 +113,11 @@ class ChirpMemoryGrid(wx.grid.Grid, glr.GridWithLabelRenderersMixin):
wx.grid.Grid.__init__(self, *a, **k)
self.SetColLabelSize(wx.grid.GRID_AUTOSIZE)
glr.GridWithLabelRenderersMixin.__init__(self)
+ # Give the grid a real per-cell wx.Accessible tree (Windows only;
+ # see chirp/wxui/accessibility.py) so screen readers announce
+ # column header + cell value + row on navigation, instead of the
+ # single opaque pane wx.grid.Grid otherwise reports.
+ accessibility.attach_grid_accessible(self, _('Memory List'))
class ChirpRowLabelRenderer(glr.GridDefaultRowLabelRenderer):
@@ -202,7 +213,7 @@ class ChirpMemoryColumn(object):
@property
def valid(self):
- if self._name in ['freq', 'rtone', 'txfreq']:
+ if self._name in ['freq', 'txfreq']:
return True
to_try = ['has_%s', 'valid_%ss', 'valid_%ses', 'valid_%s_levels']
for thing in to_try:
@@ -211,6 +222,9 @@ class ChirpMemoryColumn(object):
except KeyError:
pass
+ if self._name in ('rtone', 'ctone'):
+ return bool(self._features.valid_tones)
+
if '.' in self._name:
# Assume extra fields are always valid
return True
@@ -996,6 +1010,11 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
self._memory_rclick)
self._grid.Bind(wx.grid.EVT_GRID_CELL_BEGIN_DRAG, self._memory_drag)
self.Bind(wx.EVT_KEY_DOWN, self._keyboard_overrides)
+ # Bind key events on the inner grid window so the context-menu key
+ # (WXK_WINDOWS_MENU / Apps key) and Shift+F10 reach our handler even
+ # though focus lives inside the grid widget rather than on the panel.
+ self._grid.GetGridWindow().Bind(wx.EVT_KEY_DOWN,
+ self._keyboard_overrides)
row_labels = self._grid.GetGridRowLabelWindow()
row_labels.Bind(wx.EVT_LEFT_DOWN, self._row_click)
row_labels.Bind(wx.EVT_LEFT_UP, self._row_click)
@@ -1053,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."""
@@ -1146,9 +1165,37 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
# wx.grid.Grid() can do it.
# https://github.com/wxWidgets/wxWidgets/issues/22625
self.cb_copy(cut=False)
+ elif event.GetKeyCode() == wx.WXK_WINDOWS_MENU or (
+ event.GetKeyCode() == wx.WXK_F10 and event.ShiftDown()):
+ # Apps key or Shift+F10: open the context menu at the cursor cell.
+ # EVT_GRID_CELL_RIGHT_CLICK never fires for keyboard users, so we
+ # handle it here instead. Both the panel binding and the inner
+ # grid-window binding point here, ensuring the event is caught
+ # regardless of which sub-window holds focus.
+ self._show_context_menu_at_cursor()
else:
event.Skip()
+ def _show_context_menu_at_cursor(self):
+ """Open the right-click context menu at the focused grid cell.
+
+ _memory_rclick() uses event.GetRow() which is only valid for actual
+ mouse events. This method calls the same menu-building logic but
+ substitutes the keyboard cursor position, so keyboard users (including
+ screen reader users) get full access to all context-menu actions via
+ the Apps key or Shift+F10.
+ """
+ row = self._grid.GetGridCursorRow()
+ if row < 0:
+ return
+ # Build a fake event-like object that satisfies _memory_rclick's
+ # use of GetRow(), then delegate to the shared menu builder.
+
+ class _FakeGridEvent:
+ def GetRow(self_):
+ return row
+ self._memory_rclick(_FakeGridEvent())
+
def _row_click(self, event):
# In order to override the drag-to-multi-select behavior of the base
# grid, we need to basically reimplement what happens when a user
@@ -1209,12 +1256,17 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
# Enough motion to consider this a drag motion
self._dragging_rows = None
return self._memory_drag(event)
+ else:
+ # Required for normal header mechanics to work
+ event.Skip()
def _colheader_mouseover(self, event):
x, y = self._grid.CalcUnscrolledPosition(event.GetX(), event.GetY())
_row, cell = self._grid.XYToCell(x, y)
col = self._col_defs[cell]
event.GetEventObject().SetToolTip(col.doc or None)
+ # Required for normal header mechanics to work (i.e. resize)
+ event.Skip()
def _memory_drag(self, event):
data = self.cb_copy_getdata()
@@ -1524,6 +1576,19 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
self._memory_cache[row] = memory
+ try:
+ darkmode = wx.SystemSettings.GetAppearance().IsDark()
+ except AttributeError:
+ # Older wxPython doesn't have GetAppearance(), so just assume light
+ darkmode = False
+ if darkmode:
+ immutable_color = wx.SystemSettings.GetColour(
+ wx.SYS_COLOUR_GRAYTEXT)
+ else:
+ # This is a very light gray that looks good in light mode, but
+ # makes dark mode (light font) very hard to read.
+ immutable_color = (0xF5, 0xF5, 0xF5, 0xFF)
+
# Build a list of coldef names that are immutable extras for this
# memory
immutable_extras = ['extra.%s' % setting.get_name()
@@ -1539,7 +1604,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
self._grid.SetReadOnly(row, col,
immutable or not self.editable)
if immutable:
- color = (0xF5, 0xF5, 0xF5, 0xFF)
+ color = immutable_color
else:
color = self._default_cell_bg_color
self._grid.SetCellBackgroundColour(row, col, color)
@@ -1630,7 +1695,8 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
# Use a FrozenMemory for the actual set to catch potential attempts
# to modify the memory during set_memory().
- self.do_radio(set_cb, 'set_memory', chirp_common.FrozenMemory(mem))
+ self.do_radio(set_cb, 'set_memory',
+ chirp_common.FrozenMemory(mem, strict=False))
def erase_memory(self, number, refresh=True):
"""Erase a memory in the radio and refresh our view on success"""
@@ -1976,7 +2042,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
# Try to validate these changes with the radio before we go to store
# them, as now is the best time to present an error to the user.
warnings, errors = chirp_common.split_validation_msgs(
- self._radio.validate_memory(mem))
+ self._radio.validate_memory(chirp_common.FrozenMemory(mem)))
if errors:
LOG.warning('Memory failed validation: %r', mem)
wx.MessageBox(_('Invalid edit: %s') % '; '.join(errors),
@@ -2299,7 +2365,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
for row in rows]
with ChirpMemPropDialog(self, memories) as d:
if d.ShowModal() == wx.ID_OK:
- memories = d._memories
+ memories = d.memories
else:
return
@@ -2394,8 +2460,11 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
'source': self.GetId()}
data = wx.DataObjectComposite()
memdata = wx.CustomDataObject(common.CHIRP_DATA_MEMORY)
- data.Add(memdata)
- memdata.SetData(pickle.dumps(payload))
+ try:
+ memdata.SetData(pickle.dumps(payload))
+ data.Add(memdata)
+ except Exception as e:
+ LOG.exception('Failed to get native memory for paste: %s', e)
if portable:
strfmt = chirp_common.mem_to_text(mems[0])
textdata = wx.TextDataObject(strfmt)
@@ -2539,7 +2608,8 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
else:
mem = import_logic.import_mem(self._radio, srcrf, mem)
warns, errs = chirp_common.split_validation_msgs(
- self._radio.validate_memory(mem))
+ self._radio.validate_memory(
+ chirp_common.FrozenMemory(mem)))
errormsgs.extend([(mem, e) for e in errs])
errormsgs.extend([(mem, w) for w in warns])
@@ -2740,7 +2810,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
max_memory = 999
for row in reversed(selected):
m = self._memory_cache[row]
- if not m.extd_number:
+ if isinstance(m.number, int) and m.number >= 0:
max_memory = m.number
break
r = generic_csv.CSVRadio(None, max_memory=max_memory)
@@ -2749,7 +2819,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
r.erase_memory(0)
for row in selected:
m = self._memory_cache[row]
- if m.extd_number:
+ if not isinstance(m.number, int) or m.number < 0:
# We don't export specials
continue
if not m.empty:
@@ -2848,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'))
@@ -2950,6 +3020,8 @@ class ChirpMemPropDialog(wx.Dialog):
def _validate_memories(self):
for mem in self._memories:
+ if mem.empty:
+ continue
msgs = self._radio.validate_memory(mem)
if msgs:
wx.MessageBox(_('Invalid edit: %s') % '; '.join(msgs),
@@ -2966,3 +3038,7 @@ class ChirpMemPropDialog(wx.Dialog):
return
self.EndModal(button_id)
+
+ @property
+ def memories(self):
+ return [x for x in self._memories if not x.empty]
diff --git a/chirp/wxui/query_sources.py b/chirp/wxui/query_sources.py
index c4df553..af61321 100644
--- a/chirp/wxui/query_sources.py
+++ b/chirp/wxui/query_sources.py
@@ -31,6 +31,7 @@ from chirp.sources import repeaterbook
from chirp.sources import przemienniki_net
from chirp.sources import przemienniki_eu
from chirp.sources import mapy73pl
+from chirp.sources import amsats
from chirp.wxui import common
from chirp.wxui import config
@@ -449,6 +450,7 @@ class RepeaterBookQueryDialog(QuerySourceDialog):
states = repeaterbook.STATES[country]
except KeyError:
self._state.SetItems([_('All')])
+ self._state.SetStringSelection(_('All'))
self._state.Enable(False)
self._cached.Enable(False)
return
@@ -1223,3 +1225,95 @@ class RRQueryDialog(QuerySourceDialog):
# CA
return {'zipcounty': '%s' % self._ca_county_id,
'country': 'CA'}
+
+
+class RadioAmateurSatellitesQueryDialog(QuerySourceDialog):
+ NAME = 'Radio Amateur Satellites (GitHub Mirror)'
+
+ def get_info(self):
+ return _(
+ "This source provides a curated list of active amateur radio\n"
+ "satellites, mirrored from the JE9PEL database via GitHub.\n"
+ "It is a stable, simplified list of popular frequencies.")
+
+ def get_link(self):
+ return 'https://db.satnogs.org'
+
+ def build(self):
+ vbox = wx.BoxSizer(wx.VERTICAL)
+ self.SetSizer(vbox)
+ return vbox
+
+ def do_query(self):
+ self.result_radio = amsats.RadioAmateurSatellites()
+ super().do_query()
+
+ def get_params(self):
+ return {}
+
+
+class SatNOGSQueryDialog(QuerySourceDialog):
+ NAME = 'SatNOGS DB (Direct API)'
+ _modes = ['FM', 'FMN', 'USB', 'LSB', 'CW', 'AM', 'DSB', 'BPSK', 'QPSK',
+ 'GMSK', 'GFSK', 'FSK', 'AFSK', 'MSK', 'LoRa', 'APT', 'SSTV',
+ 'DVB', 'AHRPT']
+
+ def get_info(self):
+ return _(
+ "SatNOGS DB provides a live, community-maintained database\n"
+ "of satellite transmitter information. This source queries\n"
+ "the SatNOGS API directly for the most granular and\n"
+ "up-to-date transmitter data.")
+
+ def get_link(self):
+ return 'https://db.satnogs.org'
+
+ def build(self):
+ vbox = wx.BoxSizer(wx.VERTICAL)
+ self.SetSizer(vbox)
+
+ panel = wx.Panel(self)
+ vbox.Add(panel, 1, flag=wx.EXPAND | wx.ALL, border=10)
+ grid = wx.FlexGridSizer(2, 5, 0)
+ grid.AddGrowableCol(1)
+ panel.SetSizer(grid)
+
+ self._limit_modes = CONF.get('modes', 'satnogs').split(',') if \
+ CONF.get('modes', 'satnogs') else []
+ self._modefilter = wx.CheckBox(panel, label=_('Only certain modes'))
+ self._modefilter.SetValue(bool(self._limit_modes))
+ self.Bind(wx.EVT_CHECKBOX, self._select_modes, self._modefilter)
+
+ label = wx.StaticText(panel, label=_('Limit Modes'))
+ grid.Add(label, border=20, flag=wx.ALIGN_CENTER | wx.RIGHT | wx.LEFT)
+ grid.Add(self._modefilter, 1, border=20,
+ flag=wx.EXPAND | wx.RIGHT | wx.LEFT)
+
+ return vbox
+
+ def _select_modes(self, event):
+ if not self._modefilter.IsChecked():
+ self._limit_modes = []
+ CONF.set('modes', '', 'satnogs')
+ return
+
+ d = wx.MultiChoiceDialog(self, _('Select Modes to Import'), _('Modes'),
+ choices=self._modes)
+
+ # Pre-select based on current config
+ d.SetSelections([i for i, mode in enumerate(self._modes)
+ if mode in self._limit_modes])
+
+ r = d.ShowModal()
+ if r == wx.ID_CANCEL or not d.GetSelections():
+ self._modefilter.SetValue(bool(self._limit_modes))
+ else:
+ self._limit_modes = [self._modes[i] for i in d.GetSelections()]
+ CONF.set('modes', ','.join(self._limit_modes), 'satnogs')
+
+ def do_query(self):
+ self.result_radio = amsats.SatNOGS()
+ super().do_query()
+
+ def get_params(self):
+ return {'modes': self._limit_modes}
diff --git a/chirp/wxui/radioinfo.py b/chirp/wxui/radioinfo.py
index db4f24c..90c05c3 100644
--- a/chirp/wxui/radioinfo.py
+++ b/chirp/wxui/radioinfo.py
@@ -18,9 +18,20 @@ import wx.propgrid
from chirp.drivers import icf
from chirp import util
+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)
@@ -42,6 +53,7 @@ class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor):
def _add_features_group(self):
pg = wx.propgrid.PropertyGrid(
self, style=wx.propgrid.PG_SPLITTER_AUTO_CENTER)
+ accessibility.enable_propgrid_a11y(pg, _('Radio Info: Features'))
self._group_control.AddPage(pg, _('Features'))
for key in self._features._valid_map.keys():
@@ -59,7 +71,8 @@ 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'))
try:
@@ -85,7 +98,8 @@ 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')
attrs = dict(self._radio._icf_data)
@@ -112,7 +126,8 @@ 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
# don't dump the whole mem_extra blob in here
diff --git a/chirp/wxui/report.py b/chirp/wxui/report.py
index c42dfd4..25b26a5 100644
--- a/chirp/wxui/report.py
+++ b/chirp/wxui/report.py
@@ -26,6 +26,7 @@ except ImportError:
wx = None
from chirp import CHIRP_VERSION
+from chirp.sources import base
from chirp.wxui import config
CONF = config.get()
@@ -75,6 +76,8 @@ def ensure_session():
'X-CHIRP-UUID': CONF.get('seat', 'state'),
'X-CHIRP-Environment': get_environment(),
}
+ for k, v in SESSION.headers.items():
+ base.HEADERS[k] = v
def with_session(fn):
diff --git a/chirp/wxui/serialtrace.py b/chirp/wxui/serialtrace.py
index 9939195..f50485f 100644
--- a/chirp/wxui/serialtrace.py
+++ b/chirp/wxui/serialtrace.py
@@ -14,11 +14,13 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import datetime
+import functools
import logging
import os
import serial
import tempfile
import time
+import warnings
from chirp import util
from chirp.wxui import config
@@ -57,16 +59,78 @@ def purge_trace_files(keep=10):
LOG.error('Failed to remove old trace file %s: %s', fn, e)
+def calculate_baud_time(serial, size):
+ """Calculate the time in milliseconds required to transfer size bytes"""
+ cps = serial.baudrate / (1 + # start bit
+ serial.stopbits +
+ serial.bytesize +
+ (serial.parity and 1 or 0))
+ return size / cps * 1000
+
+
+def warn_timeout(f):
+ @functools.wraps(f)
+ def wrapper(self, *a, **k):
+ try:
+ size = a[0]
+ except IndexError:
+ size = k.get('size', 1)
+ required_time = calculate_baud_time(self, size)
+ write_required_time = write_of = 0
+ if self.last_write:
+ write_at, write_of = self.last_write
+ # The last operation was a write and it should require this much
+ # time to complete
+ write_required_time = calculate_baud_time(self, write_of)
+ # If not enough time has passed to finish the write, calculate
+ # remaining
+ write_required_time -= max(time.monotonic() - write_at, 0)
+ required_time += write_required_time
+ if self.timeout is not None and required_time > (self.timeout * 1000):
+ warnings.warn(
+ ('Read of %i bytes requires %ims at %i baud, '
+ 'but timeout is %ims (accounting for %i written bytes '
+ 'in %ims)') % (
+ size, required_time, self.baudrate, self.timeout * 1000,
+ write_of, write_required_time))
+ self.log('timeout %ims less than required %ims '
+ 'for read of %i bytes at %i baud (%ims remaining '
+ 'for %i bytes written)' % (
+ self.timeout * 1000,
+ required_time,
+ size,
+ self.baudrate,
+ write_required_time,
+ write_of))
+ return f(self, *a, **k)
+ return wrapper
+
+
class SerialTrace(serial.Serial):
def __init__(self, *a, **k):
self.__tracef = None
+ self.__last_write = None
super().__init__(*a, **k)
+ @property
+ 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')
@@ -80,6 +144,7 @@ class SerialTrace(serial.Serial):
self.__tracef = None
def write(self, data):
+ self.__last_write = (time.monotonic(), len(data))
super().write(data)
if self.__tracef:
try:
@@ -90,7 +155,9 @@ class SerialTrace(serial.Serial):
LOG.error('Failed to write to serial trace file: %s' % e)
self.__tracef = None
+ @warn_timeout
def read(self, size=1):
+ self.__last_write = None
data = super().read(size)
if self.__tracef:
try:
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/requirements.txt b/requirements.txt
index b32109a..347b75d 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,3 +1,10 @@
+# These are the requirements for the versions of wxPython (and others)
+# that match the binary builds. They're specific to the versions of the base
+# platforms that we build on. They may be older than what you want for building
+# from source on a later version. Since we focus on those binary builds,
+# please do not propose changes to this that would take them out of sync with
+# the build system or file bugs about these being wrong for your specific
+# situation.
wxPython>=4.0,<4.2.0 ; platform_system=="Linux" # See https://github.com/wxWidgets/Phoenix/issues/2225
wxPython==4.2.0 ; platform_system!="Linux"
pyserial
diff --git a/setup.py b/setup.py
index 0ec1180..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='20251108',
+ 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/__pycache__/test_clone.cpython-310-pytest-7.1.3.pyc b/tests/__pycache__/test_clone.cpython-310-pytest-7.1.3.pyc
index 4f44f20..ace50ac 100644
--- a/tests/__pycache__/test_clone.cpython-310-pytest-7.1.3.pyc
+++ b/tests/__pycache__/test_clone.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc b/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc
index ff627da..4dbcb70 100644
--- a/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc
+++ b/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc
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/Bajeton_BJ7800.img b/tests/images/Bajeton_BJ7800.img
new file mode 100644
index 0000000..f32eb89
--- /dev/null
+++ b/tests/images/Bajeton_BJ7800.img
Binary files differ
diff --git a/tests/images/Baofeng_BF-V12D.img b/tests/images/Baofeng_BF-V12D.img
new file mode 100644
index 0000000..0782091
--- /dev/null
+++ b/tests/images/Baofeng_BF-V12D.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_GM-21.img b/tests/images/Baofeng_GM-21.img
new file mode 100644
index 0000000..ffac7b5
--- /dev/null
+++ b/tests/images/Baofeng_GM-21.img
Binary files differ
diff --git a/tests/images/Baofeng_MP31.img b/tests/images/Baofeng_MP31.img
new file mode 100644
index 0000000..4811a69
--- /dev/null
+++ b/tests/images/Baofeng_MP31.img
Binary files differ
diff --git a/tests/images/Baofeng_UV-28Plus.img b/tests/images/Baofeng_UV-28Plus.img
new file mode 100644
index 0000000..65fd125
--- /dev/null
+++ b/tests/images/Baofeng_UV-28Plus.img
Binary files differ
diff --git a/tests/images/Baofeng_UV-5G_Mini.img b/tests/images/Baofeng_UV-5G_Mini.img
new file mode 100644
index 0000000..d59b8a8
--- /dev/null
+++ b/tests/images/Baofeng_UV-5G_Mini.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/Baofeng_UV-5RM_Plus.img b/tests/images/Baofeng_UV-5RM_Plus.img
new file mode 100644
index 0000000..a4c00f2
--- /dev/null
+++ b/tests/images/Baofeng_UV-5RM_Plus.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-2730E.img b/tests/images/Icom_IC-2730E.img
new file mode 100644
index 0000000..25c017e
--- /dev/null
+++ b/tests/images/Icom_IC-2730E.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/Kenwood_TK-7162.img b/tests/images/Kenwood_TK-7162.img
new file mode 100644
index 0000000..c2a2285
--- /dev/null
+++ b/tests/images/Kenwood_TK-7162.img
Binary files differ
diff --git a/tests/images/Quansheng_TK11.img b/tests/images/Quansheng_TK11.img
new file mode 100644
index 0000000..00935df
--- /dev/null
+++ b/tests/images/Quansheng_TK11.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/Radioddity_DB40-G.img b/tests/images/Radioddity_DB40-G.img
new file mode 100644
index 0000000..fbab8fd
--- /dev/null
+++ b/tests/images/Radioddity_DB40-G.img
Binary files differ
diff --git a/tests/images/Radioddity_GM-30_Plus.img b/tests/images/Radioddity_GM-30_Plus.img
new file mode 100644
index 0000000..628513d
--- /dev/null
+++ b/tests/images/Radioddity_GM-30_Plus.img
Binary files differ
diff --git a/tests/images/Radioddity_GM-30_Pro.img b/tests/images/Radioddity_GM-30_Pro.img
new file mode 100644
index 0000000..99a220b
--- /dev/null
+++ b/tests/images/Radioddity_GM-30_Pro.img
Binary files differ
diff --git a/tests/images/Radioddity_GS-10B.img b/tests/images/Radioddity_GS-10B.img
new file mode 100644
index 0000000..cf10658
--- /dev/null
+++ b/tests/images/Radioddity_GS-10B.img
Binary files differ
diff --git a/tests/images/Radioddity_MU-5.img b/tests/images/Radioddity_MU-5.img
new file mode 100644
index 0000000..695f3b1
--- /dev/null
+++ b/tests/images/Radioddity_MU-5.img
Binary files differ
diff --git a/tests/images/Radtel_RT-880G.img b/tests/images/Radtel_RT-880G.img
new file mode 100644
index 0000000..f54e84e
--- /dev/null
+++ b/tests/images/Radtel_RT-880G.img
Binary files differ
diff --git a/tests/images/Radtel_RT-920.img b/tests/images/Radtel_RT-920.img
index 7f6afe0..9b7fd6c 100644
--- a/tests/images/Radtel_RT-920.img
+++ b/tests/images/Radtel_RT-920.img
Binary files differ
diff --git a/tests/images/Retevis_C2.img b/tests/images/Retevis_C2.img
new file mode 100644
index 0000000..4d86aad
--- /dev/null
+++ b/tests/images/Retevis_C2.img
Binary files differ
diff --git a/tests/images/Retevis_HA2.img b/tests/images/Retevis_HA2.img
new file mode 100644
index 0000000..35a065d
--- /dev/null
+++ b/tests/images/Retevis_HA2.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_RB626.img b/tests/images/Retevis_RB626.img
index c4cb38a..6d348f5 100644
--- a/tests/images/Retevis_RB626.img
+++ b/tests/images/Retevis_RB626.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_RT21H.img b/tests/images/Retevis_RT21H.img
new file mode 100644
index 0000000..c9e62b1
--- /dev/null
+++ b/tests/images/Retevis_RT21H.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/TIDRADIO_TD-H8-HAM_G3.img b/tests/images/TIDRADIO_TD-H8-HAM_G3.img
new file mode 100644
index 0000000..a376cfd
--- /dev/null
+++ b/tests/images/TIDRADIO_TD-H8-HAM_G3.img
Binary files differ
diff --git a/tests/images/TIDRADIO_TD-M11_16_PMR.img b/tests/images/TIDRADIO_TD-M11_16_PMR.img
new file mode 100644
index 0000000..5101ca1
--- /dev/null
+++ b/tests/images/TIDRADIO_TD-M11_16_PMR.img
Binary files differ
diff --git a/tests/images/TIDRADIO_TD-M11_22_FRS.img b/tests/images/TIDRADIO_TD-M11_22_FRS.img
new file mode 100644
index 0000000..bcd3e01
--- /dev/null
+++ b/tests/images/TIDRADIO_TD-M11_22_FRS.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/Wouxun_KG-XS20G.img b/tests/images/Wouxun_KG-XS20G.img
new file mode 100644
index 0000000..52544ca
--- /dev/null
+++ b/tests/images/Wouxun_KG-XS20G.img
Binary files differ
diff --git a/tests/images/Wouxun_KG-XS20G_Plus.img b/tests/images/Wouxun_KG-XS20G_Plus.img
new file mode 100644
index 0000000..43f1946
--- /dev/null
+++ b/tests/images/Wouxun_KG-XS20G_Plus.img
Binary files differ
diff --git a/tests/images/Wouxun_KG-XS20H.img b/tests/images/Wouxun_KG-XS20H.img
new file mode 100644
index 0000000..1262396
--- /dev/null
+++ b/tests/images/Wouxun_KG-XS20H.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/Yaesu_VX-1.img b/tests/images/Yaesu_VX-1.img
new file mode 100644
index 0000000..9fa087c
--- /dev/null
+++ b/tests/images/Yaesu_VX-1.img
Binary files differ
diff --git a/tests/images/Yaesu_VX-150.img b/tests/images/Yaesu_VX-150.img
new file mode 100644
index 0000000..7b4b974
--- /dev/null
+++ b/tests/images/Yaesu_VX-150.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_clone.py b/tests/test_clone.py
index cb41bfb..cd29f17 100644
--- a/tests/test_clone.py
+++ b/tests/test_clone.py
@@ -16,9 +16,19 @@ class SerialException(Exception):
class SerialNone(serialtrace.SerialTrace):
+ def __init__(self, *a, **k):
+ super().__init__(*a, **k)
+ self.port = '/dev/ttyUSB0'
+
def flush(self):
pass
+ def reset_input_buffer(self):
+ pass
+
+ def reset_output_buffer(self):
+ pass
+
def inWaiting(self):
return len(self.read(256))
@@ -108,12 +118,12 @@ class TestCaseClone(base.DriverTest):
self.radio._mmap = orig_mmap
self.radio.status_fn = lambda s: True
- msg = ('Clone should have failed and raised an exception '
+ msg = ('Clone in should have failed and raised an exception '
'that inherits from RadioError')
with self.assertRaises(errors.RadioError, msg=msg):
self.radio.sync_in()
- msg = ('Clone should have failed and raised an exception '
+ msg = ('Clone out should have failed and raised an exception '
'that inherits from RadioError')
with self.assertRaises(errors.RadioError, msg=msg):
self.radio.sync_out()
diff --git a/tests/test_edges.py b/tests/test_edges.py
index d41970a..5af449a 100644
--- a/tests/test_edges.py
+++ b/tests/test_edges.py
@@ -37,6 +37,10 @@ class TestCaseEdges(base.DriverTest):
n = self.radio.get_memory(m.number)
self.assertEqualMem(m, n)
+ def test_set_does_not_modify_input(self):
+ m = self.get_mem()
+ self.radio.set_memory(chirp_common.FrozenMemory(m))
+
def test_bandedges(self):
m = self.get_mem()
min_step = min(self.rf.has_tuning_step and
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_amsats.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_amsats.cpython-310-pytest-7.1.3.pyc
new file mode 100644
index 0000000..19f4e7c
--- /dev/null
+++ b/tests/unit/__pycache__/test_amsats.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_btech_docs.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_btech_docs.cpython-310-pytest-7.1.3.pyc
new file mode 100644
index 0000000..6481c23
--- /dev/null
+++ b/tests/unit/__pycache__/test_btech_docs.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_checksum.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_checksum.cpython-310-pytest-7.1.3.pyc
new file mode 100644
index 0000000..bb67dc8
--- /dev/null
+++ b/tests/unit/__pycache__/test_checksum.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_chirp_common.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_chirp_common.cpython-310-pytest-7.1.3.pyc
index 21ab85f..979001d 100644
--- a/tests/unit/__pycache__/test_chirp_common.cpython-310-pytest-7.1.3.pyc
+++ b/tests/unit/__pycache__/test_chirp_common.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_crc.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_crc.cpython-310-pytest-7.1.3.pyc
new file mode 100644
index 0000000..dea72ba
--- /dev/null
+++ b/tests/unit/__pycache__/test_crc.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_import_logic.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_import_logic.cpython-310-pytest-7.1.3.pyc
index 7c7c6ac..2afcd30 100644
--- a/tests/unit/__pycache__/test_import_logic.cpython-310-pytest-7.1.3.pyc
+++ b/tests/unit/__pycache__/test_import_logic.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
new file mode 100644
index 0000000..10eaf8d
--- /dev/null
+++ b/tests/unit/__pycache__/test_kenwood_tone.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc
index 9c51168..1b89b3e 100644
--- a/tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc
+++ b/tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_retevis_ra25.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_retevis_ra25.cpython-310-pytest-7.1.3.pyc
new file mode 100644
index 0000000..686e9d6
--- /dev/null
+++ b/tests/unit/__pycache__/test_retevis_ra25.cpython-310-pytest-7.1.3.pyc
Binary files differ
diff --git a/tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc
index 16f0c98..4058c8d 100644
--- a/tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc
+++ b/tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc
Binary files 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_amsats.py b/tests/unit/test_amsats.py
new file mode 100644
index 0000000..d985a6e
--- /dev/null
+++ b/tests/unit/test_amsats.py
@@ -0,0 +1,112 @@
+import unittest
+from unittest import mock
+from chirp.sources import amsats
+
+
+class TestAmsatsSatNOGS(unittest.TestCase):
+ def setUp(self):
+ self.satnogs = amsats.SatNOGS()
+
+ def test_item_to_memory_mode_mapping(self):
+ test_cases = [
+ ('FMN', 'NFM'),
+ ('DSB', 'AM'),
+ ('AM', 'AM'),
+ ('CW', 'CW'),
+ ('USB', 'USB'),
+ ('LSB', 'LSB'),
+ ('GMSK', 'DIG'),
+ ('GFSK', 'DIG'),
+ ('MSK', 'DIG'),
+ ('BPSK', 'DIG'),
+ ('DVB-S2', 'DIG'),
+ ('AHRPT', 'DIG'),
+ ('LoRa', 'DIG'),
+ ('SSTV', 'DIG'),
+ ]
+
+ for orig_mode, expected_mode in test_cases:
+ item = {
+ 'downlink_low': 435000000,
+ 'mode': orig_mode,
+ 'type': 'Transmitter',
+ '_satellite': {'name': 'TestSat', 'norad_cat_id': '12345'}
+ }
+ mem = self.satnogs.item_to_memory(item)
+ self.assertEqual(mem.mode, expected_mode,
+ f"Failed mapping {orig_mode}")
+
+ # Check comment for non-native modes
+ if expected_mode in ['DIG', 'AM'] and orig_mode != expected_mode:
+ self.assertIn(f"Mode:{orig_mode}", mem.comment)
+
+ # Check for fixed URL
+ self.assertIn("https://db.satnogs.org/satellite/12345",
+ mem.comment)
+ # Check for removed NORAD: prefix
+ self.assertFalse(mem.comment.startswith("NORAD:"))
+
+ def test_item_to_memory_native_mode_redundancy(self):
+ # Native modes shouldn't have "Mode:XXX" in comment
+ item = {
+ 'downlink_low': 145000000,
+ 'mode': 'FM',
+ 'type': 'Transmitter',
+ '_satellite': {'name': 'TestSat', 'norad_cat_id': '54321'}
+ }
+ mem = self.satnogs.item_to_memory(item)
+ self.assertEqual(mem.mode, 'FM')
+ self.assertNotIn("Mode:FM", mem.comment)
+
+ @mock.patch('chirp.sources.amsats.SatNOGS._fetch_all')
+ def test_do_fetch_filtering(self, mock_fetch):
+ # Setup mocks
+ mock_fetch.side_effect = [
+ # Satellites
+ [{'sat_id': 'SAT1', 'name': 'Sat 1', 'norad_cat_id': '1'}],
+ # Transmitters
+ [
+ {'sat_id': 'SAT1', 'mode': 'FM', 'downlink_low': 100},
+ {'sat_id': 'SAT1', 'mode': 'GMSK', 'downlink_low': 200},
+ {'sat_id': 'SAT1', 'mode': None, 'downlink_low': 300},
+ ],
+ # Satellites second call
+ [{'sat_id': 'SAT1', 'name': 'Sat 1', 'norad_cat_id': '1'}],
+ # Transmitters second call
+ [
+ {'sat_id': 'SAT1', 'mode': 'FM', 'downlink_low': 100},
+ {'sat_id': 'SAT1', 'mode': 'GMSK', 'downlink_low': 200},
+ {'sat_id': 'SAT1', 'mode': None, 'downlink_low': 300},
+ ]
+ ]
+
+ # Test FM filter
+ status = mock.MagicMock()
+ self.satnogs.do_fetch(status, {'modes': ['FM']})
+ self.assertEqual(len(self.satnogs._memories), 1)
+ self.assertEqual(self.satnogs._memories[0].mode, 'FM')
+
+ # Reset and test GMSK filter
+ self.satnogs._memories = []
+ self.satnogs.do_fetch(status, {'modes': ['GMSK']})
+ self.assertEqual(len(self.satnogs._memories), 1)
+ self.assertEqual(self.satnogs._memories[0].mode, 'DIG')
+
+
+class TestAmsatsRadioAmateur(unittest.TestCase):
+ def test_item_to_memory_restyling(self):
+ ra_sat = amsats.RadioAmateurSatellites()
+ item = {
+ 'name': 'Sat1',
+ 'norad_id': '123',
+ 'satnogs_id': '123',
+ 'downlink': '145.800',
+ 'mode': 'FM',
+ }
+ mem = ra_sat.item_to_memory(item)
+ self.assertEqual(mem.mode, 'FM')
+ self.assertIn("https://db.satnogs.org/satellite/123", mem.comment)
+ self.assertFalse(mem.comment.startswith("NORAD:"))
+ # RadioAmateurSatellites still has Mode: in comment as per my
+ # implementation
+ self.assertIn("Mode:FM", mem.comment)
diff --git a/tests/unit/test_btech_docs.py b/tests/unit/test_btech_docs.py
new file mode 100644
index 0000000..5606064
--- /dev/null
+++ b/tests/unit/test_btech_docs.py
@@ -0,0 +1,26 @@
+import os
+
+from chirp.drivers import btech
+
+
+def test_kt8900_models_all_detailed_settings_have_docs():
+ image = os.path.join(os.path.dirname(__file__),
+ "..", "images", "QYT_KT8900D.img")
+ models = (
+ (btech.KT9800, "pre-alert"),
+ (btech.KT8900D, "powers the radio off"),
+ )
+
+ for radio_cls, apo_text in models:
+ radio = radio_cls(image)
+ radio.get_features()
+ settings = list(radio.get_settings().walk())
+ settings.extend(radio.get_memory(0).extra.walk())
+
+ missing = [setting.get_name() for setting in settings
+ if not setting.__doc__]
+ apo = next(setting for setting in settings
+ if setting.get_name() == "settings.apo")
+
+ assert not missing, radio_cls.MODEL
+ assert apo_text in apo.__doc__
diff --git a/tests/unit/test_checksum.py b/tests/unit/test_checksum.py
new file mode 100644
index 0000000..0387a10
--- /dev/null
+++ b/tests/unit/test_checksum.py
@@ -0,0 +1,25 @@
+import unittest
+
+from chirp import checksum
+
+
+class TestCRC(unittest.TestCase):
+ def test_crc16_xmodem(self):
+ data = b"123456789"
+ expected_crc = 0x31C3 # Known CRC-16/XMODEM for this data
+ self.assertEqual(checksum.crc16_xmodem(data), expected_crc)
+
+ def test_crc16_ibm_rev(self):
+ data = b"123456789"
+ expected_crc = 0xBB3D # Known CRC for this data
+ self.assertEqual(checksum.crc16_ibm_rev(data), expected_crc)
+
+ def test_checksum_8bit(self):
+ data = b"123456789"
+ expected_checksum = 221 # Known checksum for this data
+ self.assertEqual(checksum.checksum_8bit(data), expected_checksum)
+
+ def test_checksum_xor(self):
+ data = b"123456789"
+ expected_checksum = 49 # Known XOR checksum for this data
+ self.assertEqual(checksum.checksum_xor(data), expected_checksum)
diff --git a/tests/unit/test_chirp_common.py b/tests/unit/test_chirp_common.py
index e4c2556..4b7cda5 100644
--- a/tests/unit/test_chirp_common.py
+++ b/tests/unit/test_chirp_common.py
@@ -72,11 +72,9 @@ class TestUtilityFunctions(base.BaseTest):
self.assertTrue(chirp_common.is_version_newer('daily-20180101'))
def test_from_Hz(self):
- # FIXME: These are wrong! Adding them here purely to test the
- # python3 conversion, but they should be fixed.
- self.assertEqual(140, chirp_common.from_GHz(14000000001))
- self.assertEqual(140, chirp_common.from_MHz(14000001))
- self.assertEqual(140, chirp_common.from_kHz(14001))
+ self.assertEqual(140, chirp_common.from_GHz(140000000001))
+ self.assertEqual(140, chirp_common.from_MHz(140000001))
+ self.assertEqual(140, chirp_common.from_kHz(140001))
def test_mem_to_from_csv(self):
mem1 = chirp_common.Memory()
@@ -562,10 +560,10 @@ class TestStepFunctions(base.BaseTest):
chirp_common.fix_rounded_step(146520000))
def test_fix_rounded_step_833(self):
- # 108.008 should be aligned to 8.33kHz step
+ # 118.008 should be aligned to 8.33kHz step
self.assertEqual(
- int(108000000 + (25000 / 3)),
- chirp_common.fix_rounded_step(chirp_common.to_MHz(108.008)))
+ int(118000000 + (25000 / 3)),
+ chirp_common.fix_rounded_step(chirp_common.to_MHz(118.008)))
# 108.0 MHz should be left unchanged as it is 25kHz-aligned
self.assertFalse(chirp_common.is_8_33(
@@ -590,6 +588,45 @@ class TestStepFunctions(base.BaseTest):
chirp_common.fix_rounded_step,
chirp_common.to_MHz(146.008333))
+ # Using a channel name should be aligned to the actual frequency
+ self.assertEqual(
+ int(132050000),
+ chirp_common.fix_rounded_step(chirp_common.to_MHz(132.055)))
+ self.assertEqual(
+ int(132050000) + (25000 // 3),
+ chirp_common.fix_rounded_step(chirp_common.to_MHz(132.060)))
+ self.assertEqual(
+ int(132050000) + (25000 // 3) * 2,
+ chirp_common.fix_rounded_step(chirp_common.to_MHz(132.065)))
+ self.assertEqual(
+ int(132075000),
+ chirp_common.fix_rounded_step(chirp_common.to_MHz(132.080)))
+
+ # This is not valid
+ self.assertRaisesRegex(errors.InvalidDataError,
+ 'Aircraft frequencies must be aligned.*',
+ chirp_common.fix_rounded_step,
+ chirp_common.to_MHz(132.070))
+
+ def test_fix_rounded_step_833_examples(self):
+ # https://ukradiotransmissions.wordpress.com/2019/02/06/new-8-33khz-airband-channel-spacing-frequencies-a-conversion-chart-and-explanation/
+ cases = [
+ (132005000, 132000000),
+ (132010000, 132008300),
+ (132015000, 132016600),
+ (132030000, 132025000),
+ (132035000, 132033300),
+ (132040000, 132041600),
+ (132055000, 132050000),
+ (132060000, 132058300),
+ (132065000, 132066600),
+ (132080000, 132075000),
+ (132085000, 132083300),
+ (132090000, 132091600),
+ ]
+ for channel, freq in cases:
+ pass
+
class TestImageMetadata(base.BaseTest):
def test_make_metadata(self):
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_import_logic.py b/tests/unit/test_import_logic.py
index 9a39fe3..22a6140 100644
--- a/tests/unit/test_import_logic.py
+++ b/tests/unit/test_import_logic.py
@@ -24,7 +24,7 @@ class FakeRadio(chirp_common.Radio):
def get_features(self):
rf = chirp_common.RadioFeatures()
- rf.valid_bands = [(100000000, 500000000)]
+ rf.valid_bands = [(100000000, 500000000), (601150000, 800050000)]
rf.valid_power_levels = self.POWER_LEVELS
rf.valid_tmodes = self.TMODES
rf.valid_modes = self.MODES
@@ -159,9 +159,11 @@ class ImportFieldTests(base.BaseTest):
def test_import_freq(self):
mem = chirp_common.Memory()
mem.freq = 10
- self.assertRaises(import_logic.DestNotCompatible,
- import_logic._import_freq,
- FakeRadio(None), None, mem)
+ self.assertRaisesRegex(
+ import_logic.DestNotCompatible,
+ '.*supported ranges 100-500MHz, 601.15-800.05MHz',
+ import_logic._import_freq,
+ FakeRadio(None), None, mem)
def test_import_name(self):
mem = chirp_common.Memory()
@@ -265,6 +267,36 @@ class ImportFieldTests(base.BaseTest):
import_logic._import_tone(radio, src_rf, mem)
self.assertEqual(mem.rtone, 100.0)
+ def test_import_tone_invalid_none(self):
+ radio = FakeRadio(None)
+ radio.HAS_CTONE = False
+ src_rf = chirp_common.RadioFeatures()
+ mem = chirp_common.Memory()
+ mem.tmode = ''
+ mem.rtone = 99.9
+ import_logic._import_tone(radio, src_rf, mem)
+ # test passes if there is no exception
+
+ def test_import_tone_invalid_rtone(self):
+ radio = FakeRadio(None)
+ radio.HAS_CTONE = False
+ src_rf = chirp_common.RadioFeatures()
+ mem = chirp_common.Memory()
+ mem.tmode = 'TSQL'
+ mem.rtone = 99.9
+ self.assertRaises(import_logic.DestNotCompatible,
+ import_logic._import_tone, radio, src_rf, mem)
+
+ def test_import_tone_invalid_ctone(self):
+ radio = FakeRadio(None)
+ radio.HAS_CTONE = False
+ src_rf = chirp_common.RadioFeatures()
+ mem = chirp_common.Memory()
+ mem.tmode = 'TSQL'
+ mem.ctone = 99.9
+ self.assertRaises(import_logic.DestNotCompatible,
+ import_logic._import_tone, radio, src_rf, mem)
+
def test_import_dtcs_diffA_dtcs(self):
radio = FakeRadio(None)
src_rf = chirp_common.RadioFeatures()
@@ -358,6 +390,7 @@ class ImportFieldTests(base.BaseTest):
import_logic._import_duplex(radio, None, mem)
self.assertEqual('', mem.duplex)
+ @mock.patch('chirp.chirp_common.FrozenMemory')
@mock.patch('chirp.import_logic._import_name')
@mock.patch('chirp.import_logic._import_power')
@mock.patch('chirp.import_logic._import_tone')
@@ -366,7 +399,7 @@ class ImportFieldTests(base.BaseTest):
@mock.patch('chirp.import_logic._import_duplex')
def _test_import_mem(self, errors,
mock_duplex, mock_mode, mock_dtcs, mock_tone,
- mock_power, mock_name):
+ mock_power, mock_name, mock_frozen):
radio = FakeRadio(None)
src_rf = chirp_common.RadioFeatures()
mem = chirp_common.Memory()
@@ -377,7 +410,8 @@ class ImportFieldTests(base.BaseTest):
with mock.patch.object(radio, 'validate_memory') as mock_val:
mock_val.return_value = errors
import_logic.import_mem(radio, src_rf, mem)
- mock_val.assert_called_once_with(mem)
+ mock_val.assert_called_once_with(mock_frozen.return_value)
+ mock_frozen.assert_called_once_with(mem)
mock_dupe.assert_called_once_with()
mock_duplex.assert_called_once_with(radio, src_rf, mem)
diff --git a/tests/unit/test_kenwood_tone.py b/tests/unit/test_kenwood_tone.py
new file mode 100644
index 0000000..9496f8c
--- /dev/null
+++ b/tests/unit/test_kenwood_tone.py
@@ -0,0 +1,2193 @@
+from tests.unit import base
+from chirp import chirp_common
+from chirp import kenwood_tone
+
+
+class MockMemory:
+ def __init__(self):
+ self.rxtone = 0x0000
+ self.txtone = 0x0000
+
+
+class TestKenwoodToneModelInit(base.BaseTest):
+ def test_init_valid_params(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000)
+ self.assertEqual(model.dcs_base, 0x4000)
+ self.assertEqual(model.pol_mask, 0x2000)
+ self.assertEqual(model.tone_init, 0x0000)
+ self.assertEqual(model.tone_flag, 0x8000)
+ self.assertEqual(model.dcs_enc_base, 8)
+ self.assertEqual(model.tone_enc_base, 10)
+
+ def test_init_custom_params(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x2800, pol_mask=0x8000,
+ tone_init=0xFFFF, tone_flag=0x0000,
+ dcs_enc_base=10, tone_enc_base=16)
+ self.assertEqual(model.dcs_base, 0x2800)
+ self.assertEqual(model.pol_mask, 0x8000)
+ self.assertEqual(model.tone_init, 0xFFFF)
+ self.assertEqual(model.tone_flag, 0x0000)
+ self.assertEqual(model.dcs_enc_base, 10)
+ self.assertEqual(model.tone_enc_base, 16)
+
+ def test_init_invalid_dcs_enc_base(self):
+ with self.assertRaises(AssertionError):
+ kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, dcs_enc_base=15)
+
+ def test_init_invalid_tone_enc_base(self):
+ with self.assertRaises(AssertionError):
+ kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_enc_base=15)
+
+
+class TestGetToneVal(base.BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.model_8_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000)
+ self.model_10_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=10)
+ self.model_16_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=16)
+ self.model_8_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ tone_enc_base=16)
+ self.model_10_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=10, tone_enc_base=16)
+ self.model_16_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=16, tone_enc_base=16)
+
+ def test_get_tone_val_zero_8_10(self):
+ code, pol = self.model_8_10._get_tone_val(0x0000)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_zero_10_10(self):
+ code, pol = self.model_10_10._get_tone_val(0x0000)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_zero_16_10(self):
+ code, pol = self.model_16_10._get_tone_val(0x0000)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_zero_8_16(self):
+ code, pol = self.model_8_16._get_tone_val(0x0000)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_zero_10_16(self):
+ code, pol = self.model_10_16._get_tone_val(0x0000)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_zero_16_16(self):
+ code, pol = self.model_16_16._get_tone_val(0x0000)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ffff_8_10(self):
+ code, pol = self.model_8_10._get_tone_val(0xFFFF)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ffff_10_10(self):
+ code, pol = self.model_10_10._get_tone_val(0xFFFF)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ffff_16_10(self):
+ code, pol = self.model_16_10._get_tone_val(0xFFFF)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ffff_8_16(self):
+ code, pol = self.model_8_16._get_tone_val(0xFFFF)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ffff_10_16(self):
+ code, pol = self.model_10_16._get_tone_val(0xFFFF)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ffff_16_16(self):
+ code, pol = self.model_16_16._get_tone_val(0xFFFF)
+ self.assertIsNone(code)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_8_10(self):
+ code, pol = self.model_8_10._get_tone_val(885 + 0x8000)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_10_10(self):
+ code, pol = self.model_10_10._get_tone_val(885 + 0x8000)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_16_10(self):
+ code, pol = self.model_16_10._get_tone_val(885 + 0x8000)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_8_16(self):
+ code, pol = self.model_8_16._get_tone_val(0x0885)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_10_16(self):
+ code, pol = self.model_10_16._get_tone_val(0x0885)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_16_16(self):
+ code, pol = self.model_16_16._get_tone_val(0x0885)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_no_flag_8_10(self):
+ code, pol = self.model_8_10._get_tone_val(885)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_no_flag_10_10(self):
+ code, pol = self.model_10_10._get_tone_val(885)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_no_flag_16_10(self):
+ code, pol = self.model_16_10._get_tone_val(885)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_no_flag_8_16(self):
+ code, pol = self.model_8_16._get_tone_val(0x0885)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_no_flag_10_16(self):
+ code, pol = self.model_10_16._get_tone_val(0x0885)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_ctcss_no_flag_16_16(self):
+ code, pol = self.model_16_16._get_tone_val(0x0885)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_get_tone_val_dcs_normal_polarity_8_10(self):
+ code, pol = self.model_8_10._get_tone_val(0x4000 + 0o023)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_normal_polarity_10_10(self):
+ code, pol = self.model_10_10._get_tone_val(0x4000 + 23)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_normal_polarity_16_10(self):
+ code, pol = self.model_16_10._get_tone_val(0x4000 + 0x023)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_normal_polarity_8_16(self):
+ code, pol = self.model_8_16._get_tone_val(0x4000 + 0o023)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_normal_polarity_10_16(self):
+ code, pol = self.model_10_16._get_tone_val(0x4000 + 23)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_normal_polarity_16_16(self):
+ code, pol = self.model_16_16._get_tone_val(0x4000 + 0x023)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_reverse_polarity_8_10(self):
+ code, pol = self.model_8_10._get_tone_val(0x4000 + 0o023 + 0x2000)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "R")
+
+ def test_get_tone_val_dcs_reverse_polarity_10_10(self):
+ code, pol = self.model_10_10._get_tone_val(0x4000 + 23 + 0x2000)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "R")
+
+ def test_get_tone_val_dcs_reverse_polarity_16_10(self):
+ code, pol = self.model_16_10._get_tone_val(0x4000 + 0x023 + 0x2000)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "R")
+
+ def test_get_tone_val_dcs_reverse_polarity_8_16(self):
+ code, pol = self.model_8_16._get_tone_val(0x4000 + 0o023 + 0x2000)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "R")
+
+ def test_get_tone_val_dcs_reverse_polarity_10_16(self):
+ code, pol = self.model_10_16._get_tone_val(0x4000 + 23 + 0x2000)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "R")
+
+ def test_get_tone_val_dcs_reverse_polarity_16_16(self):
+ code, pol = self.model_16_16._get_tone_val(0x4000 + 0x023 + 0x2000)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "R")
+
+ def test_get_tone_val_dcs_octal_encoding_large_code_8_10(self):
+ code, pol = self.model_8_10._get_tone_val(0x4000 + 0o754)
+ self.assertEqual(code, 754)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_octal_encoding_large_code_10_10(self):
+ code, pol = self.model_10_10._get_tone_val(0x4000 + 754)
+ self.assertEqual(code, 754)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_octal_encoding_large_code_16_10(self):
+ code, pol = self.model_16_10._get_tone_val(0x4000 + 0x754)
+ self.assertEqual(code, 754)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_octal_encoding_large_code_8_16(self):
+ code, pol = self.model_8_16._get_tone_val(0x4000 + 0o754)
+ self.assertEqual(code, 754)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_octal_encoding_large_code_10_16(self):
+ code, pol = self.model_10_16._get_tone_val(0x4000 + 754)
+ self.assertEqual(code, 754)
+ self.assertEqual(pol, "N")
+
+ def test_get_tone_val_dcs_octal_encoding_large_code_16_16(self):
+ code, pol = self.model_16_16._get_tone_val(0x4000 + 0x754)
+ self.assertEqual(code, 754)
+ self.assertEqual(pol, "N")
+
+
+class TestSetToneVal(base.BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.model_8_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000)
+ self.model_10_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=10)
+ self.model_16_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=16)
+ self.model_8_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ tone_enc_base=16)
+ self.model_10_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=10, tone_enc_base=16)
+ self.model_16_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=16, tone_enc_base=16)
+
+ def test_set_tone_val_none_8_10(self):
+ val = self.model_8_10._set_tone_val(None, None)
+ self.assertEqual(val, 0x0000)
+
+ def test_set_tone_val_none_10_10(self):
+ val = self.model_10_10._set_tone_val(None, None)
+ self.assertEqual(val, 0x0000)
+
+ def test_set_tone_val_none_16_10(self):
+ val = self.model_16_10._set_tone_val(None, None)
+ self.assertEqual(val, 0x0000)
+
+ def test_set_tone_val_none_8_16(self):
+ val = self.model_8_16._set_tone_val(None, None)
+ self.assertEqual(val, 0x0000)
+
+ def test_set_tone_val_none_10_16(self):
+ val = self.model_10_16._set_tone_val(None, None)
+ self.assertEqual(val, 0x0000)
+
+ def test_set_tone_val_none_16_16(self):
+ val = self.model_16_16._set_tone_val(None, None)
+ self.assertEqual(val, 0x0000)
+
+ def test_set_tone_val_ctcss_8_10(self):
+ val = self.model_8_10._set_tone_val(88.5, None)
+ self.assertEqual(val, 885 + 0x8000)
+
+ def test_set_tone_val_ctcss_10_10(self):
+ val = self.model_10_10._set_tone_val(88.5, None)
+ self.assertEqual(val, 885 + 0x8000)
+
+ def test_set_tone_val_ctcss_16_10(self):
+ val = self.model_16_10._set_tone_val(88.5, None)
+ self.assertEqual(val, 885 + 0x8000)
+
+ def test_set_tone_val_ctcss_8_16(self):
+ val = self.model_8_16._set_tone_val(88.5, None)
+ self.assertEqual(val, 0x8885)
+
+ def test_set_tone_val_ctcss_10_16(self):
+ val = self.model_10_16._set_tone_val(88.5, None)
+ self.assertEqual(val, 0x8885)
+
+ def test_set_tone_val_ctcss_16_16(self):
+ val = self.model_16_16._set_tone_val(88.5, None)
+ self.assertEqual(val, 0x8885)
+
+ def test_set_tone_val_ctcss_no_flag_8_10(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_flag=0x0000)
+ val = model._set_tone_val(88.5, None)
+ self.assertEqual(val, 885)
+
+ def test_set_tone_val_ctcss_no_flag_10_10(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_flag=0x0000,
+ dcs_enc_base=10)
+ val = model._set_tone_val(88.5, None)
+ self.assertEqual(val, 885)
+
+ def test_set_tone_val_ctcss_no_flag_16_10(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_flag=0x0000,
+ dcs_enc_base=16)
+ val = model._set_tone_val(88.5, None)
+ self.assertEqual(val, 885)
+
+ def test_set_tone_val_ctcss_no_flag_8_16(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_flag=0x0000,
+ tone_enc_base=16)
+ val = model._set_tone_val(88.5, None)
+ self.assertEqual(val, 0x0885)
+
+ def test_set_tone_val_ctcss_no_flag_10_16(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_flag=0x0000,
+ dcs_enc_base=10, tone_enc_base=16)
+ val = model._set_tone_val(88.5, None)
+ self.assertEqual(val, 0x0885)
+
+ def test_set_tone_val_ctcss_no_flag_16_16(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_flag=0x0000,
+ dcs_enc_base=16, tone_enc_base=16)
+ val = model._set_tone_val(88.5, None)
+ self.assertEqual(val, 0x0885)
+
+ def test_set_tone_val_dcs_normal_8_10(self):
+ val = self.model_8_10._set_tone_val(23, "N")
+ self.assertEqual(val, 0x4000 + 0o023)
+
+ def test_set_tone_val_dcs_normal_10_10(self):
+ val = self.model_10_10._set_tone_val(23, "N")
+ self.assertEqual(val, 0x4000 + 23)
+
+ def test_set_tone_val_dcs_normal_16_10(self):
+ val = self.model_16_10._set_tone_val(23, "N")
+ self.assertEqual(val, 0x4000 + 0x023)
+
+ def test_set_tone_val_dcs_normal_8_16(self):
+ val = self.model_8_16._set_tone_val(23, "N")
+ self.assertEqual(val, 0x4000 + 0o023)
+
+ def test_set_tone_val_dcs_normal_10_16(self):
+ val = self.model_10_16._set_tone_val(23, "N")
+ self.assertEqual(val, 0x4000 + 23)
+
+ def test_set_tone_val_dcs_normal_16_16(self):
+ val = self.model_16_16._set_tone_val(23, "N")
+ self.assertEqual(val, 0x4000 + 0x023)
+
+ def test_set_tone_val_dcs_reverse_8_10(self):
+ val = self.model_8_10._set_tone_val(23, "R")
+ self.assertEqual(val, 0x4000 + 0o023 + 0x2000)
+
+ def test_set_tone_val_dcs_reverse_10_10(self):
+ val = self.model_10_10._set_tone_val(23, "R")
+ self.assertEqual(val, 0x4000 + 23 + 0x2000)
+
+ def test_set_tone_val_dcs_reverse_16_10(self):
+ val = self.model_16_10._set_tone_val(23, "R")
+ self.assertEqual(val, 0x4000 + 0x023 + 0x2000)
+
+ def test_set_tone_val_dcs_reverse_8_16(self):
+ val = self.model_8_16._set_tone_val(23, "R")
+ self.assertEqual(val, 0x4000 + 0o023 + 0x2000)
+
+ def test_set_tone_val_dcs_reverse_10_16(self):
+ val = self.model_10_16._set_tone_val(23, "R")
+ self.assertEqual(val, 0x4000 + 23 + 0x2000)
+
+ def test_set_tone_val_dcs_reverse_16_16(self):
+ val = self.model_16_16._set_tone_val(23, "R")
+ self.assertEqual(val, 0x4000 + 0x023 + 0x2000)
+
+
+class TestSetTone(base.BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.model_8_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000)
+ self.model_10_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=10)
+ self.model_16_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=16)
+ self.model_8_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ tone_enc_base=16)
+ self.model_10_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=10, tone_enc_base=16)
+ self.model_16_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=16, tone_enc_base=16)
+
+ def _make_mem(self, **kwargs):
+ mem = chirp_common.Memory()
+ for key, value in kwargs.items():
+ setattr(mem, key, value)
+ return mem
+
+ def test_set_tone_empty_8_10(self):
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0x0000)
+ self.assertEqual(_mem.txtone, 0x0000)
+
+ def test_set_tone_empty_10_10(self):
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0x0000)
+ self.assertEqual(_mem.txtone, 0x0000)
+
+ def test_set_tone_empty_16_10(self):
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0x0000)
+ self.assertEqual(_mem.txtone, 0x0000)
+
+ def test_set_tone_empty_8_16(self):
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0x0000)
+ self.assertEqual(_mem.txtone, 0x0000)
+
+ def test_set_tone_empty_10_16(self):
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0x0000)
+ self.assertEqual(_mem.txtone, 0x0000)
+
+ def test_set_tone_empty_16_16(self):
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0x0000)
+ self.assertEqual(_mem.txtone, 0x0000)
+
+ def test_set_tone_tone_mode_8_10(self):
+ mem = self._make_mem(tmode="Tone", rtone=100.0)
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(100.0 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, 0x0000)
+
+ def test_set_tone_tone_mode_10_10(self):
+ mem = self._make_mem(tmode="Tone", rtone=100.0)
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(100.0 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, 0x0000)
+
+ def test_set_tone_tone_mode_16_10(self):
+ mem = self._make_mem(tmode="Tone", rtone=100.0)
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(100.0 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, 0x0000)
+
+ def test_set_tone_tone_mode_8_16(self):
+ mem = self._make_mem(tmode="Tone", rtone=100.0)
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9000)
+ self.assertEqual(_mem.rxtone, 0x0000)
+
+ def test_set_tone_tone_mode_10_16(self):
+ mem = self._make_mem(tmode="Tone", rtone=100.0)
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9000)
+ self.assertEqual(_mem.rxtone, 0x0000)
+
+ def test_set_tone_tone_mode_16_16(self):
+ mem = self._make_mem(tmode="Tone", rtone=100.0)
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9000)
+ self.assertEqual(_mem.rxtone, 0x0000)
+
+ def test_set_tone_tsql_mode_8_10(self):
+ mem = self._make_mem(tmode="TSQL", ctone=107.2)
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(107.2 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_tsql_mode_10_10(self):
+ mem = self._make_mem(tmode="TSQL", ctone=107.2)
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(107.2 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_tsql_mode_16_10(self):
+ mem = self._make_mem(tmode="TSQL", ctone=107.2)
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(107.2 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_tsql_mode_8_16(self):
+ mem = self._make_mem(tmode="TSQL", ctone=107.2)
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9072)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_tsql_mode_10_16(self):
+ mem = self._make_mem(tmode="TSQL", ctone=107.2)
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9072)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_tsql_mode_16_16(self):
+ mem = self._make_mem(tmode="TSQL", ctone=107.2)
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9072)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_dtcs_mode_8_10(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NR")
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0o023)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0o023 + 0x2000)
+
+ def test_set_tone_dtcs_mode_10_10(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NR")
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 23)
+ self.assertEqual(_mem.rxtone, 0x4000 + 23 + 0x2000)
+
+ def test_set_tone_dtcs_mode_16_10(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NR")
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0x023)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0x023 + 0x2000)
+
+ def test_set_tone_dtcs_mode_8_16(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NR")
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0o023)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0o023 + 0x2000)
+
+ def test_set_tone_dtcs_mode_10_16(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NR")
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 23)
+ self.assertEqual(_mem.rxtone, 0x4000 + 23 + 0x2000)
+
+ def test_set_tone_dtcs_mode_16_16(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NR")
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0x023)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0x023 + 0x2000)
+
+ def test_set_tone_dtcs_mode_nn_8_10(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0o023)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0o023)
+
+ def test_set_tone_dtcs_mode_nn_10_10(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 23)
+ self.assertEqual(_mem.rxtone, 0x4000 + 23)
+
+ def test_set_tone_dtcs_mode_nn_16_10(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0x023)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0x023)
+
+ def test_set_tone_dtcs_mode_nn_8_16(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0o023)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0o023)
+
+ def test_set_tone_dtcs_mode_nn_10_16(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 23)
+ self.assertEqual(_mem.rxtone, 0x4000 + 23)
+
+ def test_set_tone_dtcs_mode_nn_16_16(self):
+ mem = self._make_mem(tmode="DTCS", dtcs=23, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0x023)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0x023)
+
+ def test_set_tone_cross_tone_tone_8_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->Tone",
+ rtone=100.0, ctone=107.2)
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(100.0 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_cross_tone_tone_10_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->Tone",
+ rtone=100.0, ctone=107.2)
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(100.0 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_cross_tone_tone_16_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->Tone",
+ rtone=100.0, ctone=107.2)
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(100.0 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_cross_tone_tone_8_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->Tone",
+ rtone=100.0, ctone=107.2)
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9000)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_cross_tone_tone_10_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->Tone",
+ rtone=100.0, ctone=107.2)
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9000)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_cross_tone_tone_16_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->Tone",
+ rtone=100.0, ctone=107.2)
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9000)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_cross_tone_dtcs_8_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->DTCS",
+ rtone=100.0, rx_dtcs=25,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(100.0 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0o025)
+
+ def test_set_tone_cross_tone_dtcs_10_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->DTCS",
+ rtone=100.0, rx_dtcs=25,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(100.0 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 25)
+
+ def test_set_tone_cross_tone_dtcs_16_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->DTCS",
+ rtone=100.0, rx_dtcs=25,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, int(100.0 * 10) + 0x8000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0x025)
+
+ def test_set_tone_cross_tone_dtcs_8_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->DTCS",
+ rtone=100.0, rx_dtcs=25,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0o025)
+
+ def test_set_tone_cross_tone_dtcs_10_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->DTCS",
+ rtone=100.0, rx_dtcs=25,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 25)
+
+ def test_set_tone_cross_tone_dtcs_16_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="Tone->DTCS",
+ rtone=100.0, rx_dtcs=25,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x9000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0x025)
+
+ def test_set_tone_cross_dtcs_tone_8_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->Tone",
+ dtcs=23, ctone=107.2,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0o023)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_cross_dtcs_tone_10_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->Tone",
+ dtcs=23, ctone=107.2,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 23)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_cross_dtcs_tone_16_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->Tone",
+ dtcs=23, ctone=107.2,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0x023)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_cross_dtcs_tone_8_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->Tone",
+ dtcs=23, ctone=107.2,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0o023)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_cross_dtcs_tone_10_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->Tone",
+ dtcs=23, ctone=107.2,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 23)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_cross_dtcs_tone_16_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->Tone",
+ dtcs=23, ctone=107.2,
+ dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0x023)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_cross_dtcs_dtcs_8_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->DTCS",
+ dtcs=23, rx_dtcs=25,
+ dtcs_polarity="RN")
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0o023 + 0x2000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0o025)
+
+ def test_set_tone_cross_dtcs_dtcs_10_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->DTCS",
+ dtcs=23, rx_dtcs=25,
+ dtcs_polarity="RN")
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 23 + 0x2000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 25)
+
+ def test_set_tone_cross_dtcs_dtcs_16_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->DTCS",
+ dtcs=23, rx_dtcs=25,
+ dtcs_polarity="RN")
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0x023 + 0x2000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0x025)
+
+ # Show that the tone_bcd flag doesn't interfere with DCS parsing.
+ def test_set_tone_cross_dtcs_dtcs_8_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->DTCS",
+ dtcs=23, rx_dtcs=25,
+ dtcs_polarity="RN")
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0o023 + 0x2000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0o025)
+
+ def test_set_tone_cross_dtcs_dtcs_10_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->DTCS",
+ dtcs=23, rx_dtcs=25,
+ dtcs_polarity="RN")
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 23 + 0x2000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 25)
+
+ def test_set_tone_cross_dtcs_dtcs_16_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="DTCS->DTCS",
+ dtcs=23, rx_dtcs=25,
+ dtcs_polarity="RN")
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x4000 + 0x023 + 0x2000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0x025)
+
+ def test_set_tone_cross_none_tone_8_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->Tone",
+ ctone=107.2)
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_cross_none_tone_10_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->Tone",
+ ctone=107.2)
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_cross_none_tone_16_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->Tone",
+ ctone=107.2)
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, int(107.2 * 10) + 0x8000)
+
+ def test_set_tone_cross_none_tone_8_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->Tone",
+ ctone=107.2)
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_cross_none_tone_10_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->Tone",
+ ctone=107.2)
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_cross_none_tone_16_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->Tone",
+ ctone=107.2)
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, 0x9072)
+
+ def test_set_tone_cross_none_dtcs_8_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->DTCS",
+ rx_dtcs=25, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0o025)
+
+ def test_set_tone_cross_none_dtcs_10_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->DTCS",
+ rx_dtcs=25, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 25)
+
+ def test_set_tone_cross_none_dtcs_16_10(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->DTCS",
+ rx_dtcs=25, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0x025)
+
+ def test_set_tone_cross_none_dtcs_8_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->DTCS",
+ rx_dtcs=25, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0o025)
+
+ def test_set_tone_cross_none_dtcs_10_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->DTCS",
+ rx_dtcs=25, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 25)
+
+ def test_set_tone_cross_none_dtcs_16_16(self):
+ mem = self._make_mem(tmode="Cross", cross_mode="->DTCS",
+ rx_dtcs=25, dtcs_polarity="NN")
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ self.assertEqual(_mem.txtone, 0x0000)
+ self.assertEqual(_mem.rxtone, 0x4000 + 0x025)
+
+ def test_set_tone_with_tone_init_ffff_8_10(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_init=0xFFFF)
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ model.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0xFFFF)
+ self.assertEqual(_mem.txtone, 0xFFFF)
+
+ def test_set_tone_with_tone_init_ffff_10_10(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_init=0xFFFF,
+ dcs_enc_base=10)
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ model.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0xFFFF)
+ self.assertEqual(_mem.txtone, 0xFFFF)
+
+ def test_set_tone_with_tone_init_ffff_16_10(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_init=0xFFFF,
+ dcs_enc_base=16)
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ model.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0xFFFF)
+ self.assertEqual(_mem.txtone, 0xFFFF)
+
+ def test_set_tone_with_tone_init_ffff_8_16(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_init=0xFFFF,
+ tone_enc_base=16)
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ model.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0xFFFF)
+ self.assertEqual(_mem.txtone, 0xFFFF)
+
+ def test_set_tone_with_tone_init_ffff_10_16(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_init=0xFFFF,
+ dcs_enc_base=10, tone_enc_base=16)
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ model.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0xFFFF)
+ self.assertEqual(_mem.txtone, 0xFFFF)
+
+ def test_set_tone_with_tone_init_ffff_16_16(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_init=0xFFFF,
+ dcs_enc_base=16, tone_enc_base=16)
+ mem = self._make_mem(tmode="")
+ _mem = MockMemory()
+ model.set_tone(mem, _mem)
+ self.assertEqual(_mem.rxtone, 0xFFFF)
+ self.assertEqual(_mem.txtone, 0xFFFF)
+
+
+class TestGetTone(base.BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.model_8_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000)
+ self.model_10_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=10)
+ self.model_16_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=16)
+ self.model_8_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ tone_enc_base=16)
+ self.model_10_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=10, tone_enc_base=16)
+ self.model_16_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=16, tone_enc_base=16)
+
+ def test_get_tone_empty_8_10(self):
+ _mem = MockMemory()
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "")
+
+ def test_get_tone_empty_10_10(self):
+ _mem = MockMemory()
+ mem = chirp_common.Memory()
+ self.model_10_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "")
+
+ def test_get_tone_empty_16_10(self):
+ _mem = MockMemory()
+ mem = chirp_common.Memory()
+ self.model_16_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "")
+
+ def test_get_tone_empty_8_16(self):
+ _mem = MockMemory()
+ mem = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "")
+
+ def test_get_tone_empty_10_16(self):
+ _mem = MockMemory()
+ mem = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "")
+
+ def test_get_tone_empty_16_16(self):
+ _mem = MockMemory()
+ mem = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "")
+
+ def test_get_tone_tone_mode_8_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(100.0 * 10) + 0x8000
+ _mem.rxtone = 0x0000
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Tone")
+ self.assertEqual(mem.rtone, 100.0)
+
+ def test_get_tone_tone_mode_10_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(100.0 * 10) + 0x8000
+ _mem.rxtone = 0x0000
+ mem = chirp_common.Memory()
+ self.model_10_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Tone")
+ self.assertEqual(mem.rtone, 100.0)
+
+ def test_get_tone_tone_mode_16_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(100.0 * 10) + 0x8000
+ _mem.rxtone = 0x0000
+ mem = chirp_common.Memory()
+ self.model_16_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Tone")
+ self.assertEqual(mem.rtone, 100.0)
+
+ def test_get_tone_tone_mode_8_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9000
+ _mem.rxtone = 0x0000
+ mem = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Tone")
+ self.assertEqual(mem.rtone, 100.0)
+
+ def test_get_tone_tone_mode_10_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9000
+ _mem.rxtone = 0x0000
+ mem = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Tone")
+ self.assertEqual(mem.rtone, 100.0)
+
+ def test_get_tone_tone_mode_16_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9000
+ _mem.rxtone = 0x0000
+ mem = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Tone")
+ self.assertEqual(mem.rtone, 100.0)
+
+ def test_get_tone_tsql_mode_8_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(107.2 * 10) + 0x8000
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "TSQL")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_tsql_mode_10_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(107.2 * 10) + 0x8000
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_10_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "TSQL")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_tsql_mode_16_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(107.2 * 10) + 0x8000
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_16_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "TSQL")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_tsql_mode_8_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9072
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "TSQL")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_tsql_mode_10_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9072
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "TSQL")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_tsql_mode_16_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9072
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "TSQL")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_dtcs_mode_8_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0o023
+ _mem.rxtone = 0x4000 + 0o023
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.dtcs_polarity, "NN")
+
+ def test_get_tone_dtcs_mode_10_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 23
+ _mem.rxtone = 0x4000 + 23
+ mem = chirp_common.Memory()
+ self.model_10_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.dtcs_polarity, "NN")
+
+ def test_get_tone_dtcs_mode_16_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0x023
+ _mem.rxtone = 0x4000 + 0x023
+ mem = chirp_common.Memory()
+ self.model_16_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.dtcs_polarity, "NN")
+
+ def test_get_tone_dtcs_mode_8_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0o023
+ _mem.rxtone = 0x4000 + 0o023
+ mem = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.dtcs_polarity, "NN")
+
+ def test_get_tone_dtcs_mode_10_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 23
+ _mem.rxtone = 0x4000 + 23
+ mem = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.dtcs_polarity, "NN")
+
+ def test_get_tone_dtcs_mode_16_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0x023
+ _mem.rxtone = 0x4000 + 0x023
+ mem = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.dtcs_polarity, "NN")
+
+ def test_get_tone_dtcs_with_polarity_8_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0o023 + 0x2000
+ _mem.rxtone = 0x4000 + 0o023
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs_polarity, "RN")
+
+ def test_get_tone_dtcs_with_polarity_10_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 23 + 0x2000
+ _mem.rxtone = 0x4000 + 23
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs_polarity, "RN")
+
+ def test_get_tone_dtcs_with_polarity_16_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0x023 + 0x2000
+ _mem.rxtone = 0x4000 + 0x023
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs_polarity, "RN")
+
+ def test_get_tone_dtcs_with_polarity_8_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0o023 + 0x2000
+ _mem.rxtone = 0x4000 + 0o023
+ mem = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs_polarity, "RN")
+
+ def test_get_tone_dtcs_with_polarity_10_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 23 + 0x2000
+ _mem.rxtone = 0x4000 + 23
+ mem = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs_polarity, "RN")
+
+ def test_get_tone_dtcs_with_polarity_16_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0x023 + 0x2000
+ _mem.rxtone = 0x4000 + 0x023
+ mem = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "DTCS")
+ self.assertEqual(mem.dtcs_polarity, "RN")
+
+ def test_get_tone_cross_tone_tone_8_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(100.0 * 10) + 0x8000
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->Tone")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_tone_tone_10_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(100.0 * 10) + 0x8000
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->Tone")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_tone_tone_16_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(100.0 * 10) + 0x8000
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->Tone")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_tone_tone_8_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9000
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->Tone")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_tone_tone_10_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9000
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->Tone")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_tone_tone_16_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9000
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->Tone")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_tone_dtcs_8_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(100.0 * 10) + 0x8000
+ _mem.rxtone = 0x4000 + 0o025
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->DTCS")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_tone_dtcs_10_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(100.0 * 10) + 0x8000
+ _mem.rxtone = 0x4000 + 25
+ mem = chirp_common.Memory()
+ self.model_10_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->DTCS")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_tone_dtcs_16_10(self):
+ _mem = MockMemory()
+ _mem.txtone = int(100.0 * 10) + 0x8000
+ _mem.rxtone = 0x4000 + 0x025
+ mem = chirp_common.Memory()
+ self.model_16_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->DTCS")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_tone_dtcs_8_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9000
+ _mem.rxtone = 0x4000 + 0o025
+ mem = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->DTCS")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_tone_dtcs_10_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9000
+ _mem.rxtone = 0x4000 + 25
+ mem = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->DTCS")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_tone_dtcs_16_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x9000
+ _mem.rxtone = 0x4000 + 0x025
+ mem = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "Tone->DTCS")
+ self.assertEqual(mem.rtone, 100.0)
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_dtcs_tone_8_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0o023
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "DTCS->Tone")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_dtcs_tone_10_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 23
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_10_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "DTCS->Tone")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_dtcs_tone_16_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0x023
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_16_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "DTCS->Tone")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_dtcs_tone_8_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0o023
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "DTCS->Tone")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_dtcs_tone_10_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 23
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "DTCS->Tone")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_dtcs_tone_16_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x4000 + 0x023
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "DTCS->Tone")
+ self.assertEqual(mem.dtcs, 23)
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_none_tone_8_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->Tone")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_none_tone_10_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_10_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->Tone")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_none_tone_16_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = int(107.2 * 10) + 0x8000
+ mem = chirp_common.Memory()
+ self.model_16_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->Tone")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_none_tone_8_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->Tone")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_none_tone_10_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->Tone")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_none_tone_16_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = 0x9072
+ mem = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->Tone")
+ self.assertEqual(mem.ctone, 107.2)
+
+ def test_get_tone_cross_none_dtcs_8_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = 0x4000 + 0o025
+ mem = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->DTCS")
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_none_dtcs_10_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = 0x4000 + 25
+ mem = chirp_common.Memory()
+ self.model_10_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->DTCS")
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_none_dtcs_16_10(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = 0x4000 + 0x025
+ mem = chirp_common.Memory()
+ self.model_16_10.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->DTCS")
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_none_dtcs_8_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = 0x4000 + 0o025
+ mem = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->DTCS")
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_none_dtcs_10_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = 0x4000 + 25
+ mem = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->DTCS")
+ self.assertEqual(mem.rx_dtcs, 25)
+
+ def test_get_tone_cross_none_dtcs_16_16(self):
+ _mem = MockMemory()
+ _mem.txtone = 0x0000
+ _mem.rxtone = 0x4000 + 0x025
+ mem = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, mem)
+ self.assertEqual(mem.tmode, "Cross")
+ self.assertEqual(mem.cross_mode, "->DTCS")
+ self.assertEqual(mem.rx_dtcs, 25)
+
+
+class TestRoundTrip(base.BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.model_8_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000)
+ self.model_10_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=10)
+ self.model_16_10 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=16)
+ self.model_8_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ tone_enc_base=16)
+ self.model_10_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=10, tone_enc_base=16)
+ self.model_16_16 = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000,
+ dcs_enc_base=16, tone_enc_base=16)
+
+ def _round_trip_8_10(self, mem):
+ _mem = MockMemory()
+ self.model_8_10.set_tone(mem, _mem)
+ result = chirp_common.Memory()
+ self.model_8_10.get_tone(_mem, result)
+ return result
+
+ def _round_trip_10_10(self, mem):
+ _mem = MockMemory()
+ self.model_10_10.set_tone(mem, _mem)
+ result = chirp_common.Memory()
+ self.model_10_10.get_tone(_mem, result)
+ return result
+
+ def _round_trip_16_10(self, mem):
+ _mem = MockMemory()
+ self.model_16_10.set_tone(mem, _mem)
+ result = chirp_common.Memory()
+ self.model_16_10.get_tone(_mem, result)
+ return result
+
+ def _round_trip_8_16(self, mem):
+ _mem = MockMemory()
+ self.model_8_16.set_tone(mem, _mem)
+ result = chirp_common.Memory()
+ self.model_8_16.get_tone(_mem, result)
+ return result
+
+ def _round_trip_10_16(self, mem):
+ _mem = MockMemory()
+ self.model_10_16.set_tone(mem, _mem)
+ result = chirp_common.Memory()
+ self.model_10_16.get_tone(_mem, result)
+ return result
+
+ def _round_trip_16_16(self, mem):
+ _mem = MockMemory()
+ self.model_16_16.set_tone(mem, _mem)
+ result = chirp_common.Memory()
+ self.model_16_16.get_tone(_mem, result)
+ return result
+
+ def test_round_trip_empty_8_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = ""
+ result = self._round_trip_8_10(mem)
+ self.assertEqual(result.tmode, "")
+
+ def test_round_trip_empty_10_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = ""
+ result = self._round_trip_10_10(mem)
+ self.assertEqual(result.tmode, "")
+
+ def test_round_trip_empty_16_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = ""
+ result = self._round_trip_16_10(mem)
+ self.assertEqual(result.tmode, "")
+
+ def test_round_trip_empty_8_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = ""
+ result = self._round_trip_8_16(mem)
+ self.assertEqual(result.tmode, "")
+
+ def test_round_trip_empty_10_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = ""
+ result = self._round_trip_10_16(mem)
+ self.assertEqual(result.tmode, "")
+
+ def test_round_trip_empty_16_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = ""
+ result = self._round_trip_16_16(mem)
+ self.assertEqual(result.tmode, "")
+
+ def test_round_trip_tone_8_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Tone"
+ mem.rtone = 100.0
+ result = self._round_trip_8_10(mem)
+ self.assertEqual(result.tmode, "Tone")
+ self.assertEqual(result.rtone, 100.0)
+
+ def test_round_trip_tone_10_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Tone"
+ mem.rtone = 100.0
+ result = self._round_trip_10_10(mem)
+ self.assertEqual(result.tmode, "Tone")
+ self.assertEqual(result.rtone, 100.0)
+
+ def test_round_trip_tone_16_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Tone"
+ mem.rtone = 100.0
+ result = self._round_trip_16_10(mem)
+ self.assertEqual(result.tmode, "Tone")
+ self.assertEqual(result.rtone, 100.0)
+
+ def test_round_trip_tone_8_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Tone"
+ mem.rtone = 100.0
+ result = self._round_trip_8_16(mem)
+ self.assertEqual(result.tmode, "Tone")
+ self.assertEqual(result.rtone, 100.0)
+
+ def test_round_trip_tone_10_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Tone"
+ mem.rtone = 100.0
+ result = self._round_trip_10_16(mem)
+ self.assertEqual(result.tmode, "Tone")
+ self.assertEqual(result.rtone, 100.0)
+
+ def test_round_trip_tone_16_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Tone"
+ mem.rtone = 100.0
+ result = self._round_trip_16_16(mem)
+ self.assertEqual(result.tmode, "Tone")
+ self.assertEqual(result.rtone, 100.0)
+
+ def test_round_trip_tsql_8_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "TSQL"
+ mem.ctone = 107.2
+ result = self._round_trip_8_10(mem)
+ self.assertEqual(result.tmode, "TSQL")
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_tsql_10_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "TSQL"
+ mem.ctone = 107.2
+ result = self._round_trip_10_10(mem)
+ self.assertEqual(result.tmode, "TSQL")
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_tsql_16_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "TSQL"
+ mem.ctone = 107.2
+ result = self._round_trip_16_10(mem)
+ self.assertEqual(result.tmode, "TSQL")
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_tsql_8_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "TSQL"
+ mem.ctone = 107.2
+ result = self._round_trip_8_16(mem)
+ self.assertEqual(result.tmode, "TSQL")
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_tsql_10_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "TSQL"
+ mem.ctone = 107.2
+ result = self._round_trip_10_16(mem)
+ self.assertEqual(result.tmode, "TSQL")
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_tsql_16_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "TSQL"
+ mem.ctone = 107.2
+ result = self._round_trip_16_16(mem)
+ self.assertEqual(result.tmode, "TSQL")
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_dtcs_8_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "DTCS"
+ mem.dtcs = 23
+ mem.dtcs_polarity = "NR"
+ result = self._round_trip_8_10(mem)
+ self.assertEqual(result.tmode, "DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.dtcs_polarity, "NR")
+
+ def test_round_trip_dtcs_10_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "DTCS"
+ mem.dtcs = 23
+ mem.dtcs_polarity = "NR"
+ result = self._round_trip_10_10(mem)
+ self.assertEqual(result.tmode, "DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.dtcs_polarity, "NR")
+
+ def test_round_trip_dtcs_16_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "DTCS"
+ mem.dtcs = 23
+ mem.dtcs_polarity = "NR"
+ result = self._round_trip_16_10(mem)
+ self.assertEqual(result.tmode, "DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.dtcs_polarity, "NR")
+
+ def test_round_trip_dtcs_8_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "DTCS"
+ mem.dtcs = 23
+ mem.dtcs_polarity = "NR"
+ result = self._round_trip_8_16(mem)
+ self.assertEqual(result.tmode, "DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.dtcs_polarity, "NR")
+
+ def test_round_trip_dtcs_10_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "DTCS"
+ mem.dtcs = 23
+ mem.dtcs_polarity = "NR"
+ result = self._round_trip_10_16(mem)
+ self.assertEqual(result.tmode, "DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.dtcs_polarity, "NR")
+
+ def test_round_trip_dtcs_16_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "DTCS"
+ mem.dtcs = 23
+ mem.dtcs_polarity = "NR"
+ result = self._round_trip_16_16(mem)
+ self.assertEqual(result.tmode, "DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.dtcs_polarity, "NR")
+
+ def test_round_trip_cross_tone_tone_8_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "Tone->Tone"
+ mem.rtone = 100.0
+ mem.ctone = 107.2
+ result = self._round_trip_8_10(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "Tone->Tone")
+ self.assertEqual(result.rtone, 100.0)
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_cross_tone_tone_10_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "Tone->Tone"
+ mem.rtone = 100.0
+ mem.ctone = 107.2
+ result = self._round_trip_10_10(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "Tone->Tone")
+ self.assertEqual(result.rtone, 100.0)
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_cross_tone_tone_16_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "Tone->Tone"
+ mem.rtone = 100.0
+ mem.ctone = 107.2
+ result = self._round_trip_16_10(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "Tone->Tone")
+ self.assertEqual(result.rtone, 100.0)
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_cross_tone_tone_8_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "Tone->Tone"
+ mem.rtone = 100.0
+ mem.ctone = 107.2
+ result = self._round_trip_8_16(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "Tone->Tone")
+ self.assertEqual(result.rtone, 100.0)
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_cross_tone_tone_10_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "Tone->Tone"
+ mem.rtone = 100.0
+ mem.ctone = 107.2
+ result = self._round_trip_10_16(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "Tone->Tone")
+ self.assertEqual(result.rtone, 100.0)
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_cross_tone_tone_16_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "Tone->Tone"
+ mem.rtone = 100.0
+ mem.ctone = 107.2
+ result = self._round_trip_16_16(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "Tone->Tone")
+ self.assertEqual(result.rtone, 100.0)
+ self.assertEqual(result.ctone, 107.2)
+
+ def test_round_trip_cross_dtcs_dtcs_8_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "DTCS->DTCS"
+ mem.dtcs = 23
+ mem.rx_dtcs = 25
+ mem.dtcs_polarity = "RN"
+ result = self._round_trip_8_10(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "DTCS->DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.rx_dtcs, 25)
+ self.assertEqual(result.dtcs_polarity, "RN")
+
+ def test_round_trip_cross_dtcs_dtcs_10_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "DTCS->DTCS"
+ mem.dtcs = 23
+ mem.rx_dtcs = 25
+ mem.dtcs_polarity = "RN"
+ result = self._round_trip_10_10(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "DTCS->DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.rx_dtcs, 25)
+ self.assertEqual(result.dtcs_polarity, "RN")
+
+ def test_round_trip_cross_dtcs_dtcs_16_10(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "DTCS->DTCS"
+ mem.dtcs = 23
+ mem.rx_dtcs = 25
+ mem.dtcs_polarity = "RN"
+ result = self._round_trip_16_10(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "DTCS->DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.rx_dtcs, 25)
+ self.assertEqual(result.dtcs_polarity, "RN")
+
+ def test_round_trip_cross_dtcs_dtcs_8_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "DTCS->DTCS"
+ mem.dtcs = 23
+ mem.rx_dtcs = 25
+ mem.dtcs_polarity = "RN"
+ result = self._round_trip_8_16(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "DTCS->DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.rx_dtcs, 25)
+ self.assertEqual(result.dtcs_polarity, "RN")
+
+ def test_round_trip_cross_dtcs_dtcs_10_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "DTCS->DTCS"
+ mem.dtcs = 23
+ mem.rx_dtcs = 25
+ mem.dtcs_polarity = "RN"
+ result = self._round_trip_10_16(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "DTCS->DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.rx_dtcs, 25)
+ self.assertEqual(result.dtcs_polarity, "RN")
+
+ def test_round_trip_cross_dtcs_dtcs_16_16(self):
+ mem = chirp_common.Memory()
+ mem.tmode = "Cross"
+ mem.cross_mode = "DTCS->DTCS"
+ mem.dtcs = 23
+ mem.rx_dtcs = 25
+ mem.dtcs_polarity = "RN"
+ result = self._round_trip_16_16(mem)
+ self.assertEqual(result.tmode, "Cross")
+ self.assertEqual(result.cross_mode, "DTCS->DTCS")
+ self.assertEqual(result.dtcs, 23)
+ self.assertEqual(result.rx_dtcs, 25)
+ self.assertEqual(result.dtcs_polarity, "RN")
+
+
+class TestParseQtdqt(base.BaseTest):
+ def test_parse_empty_string(self):
+ mode, val, pol = kenwood_tone.parse_qtdqt("")
+ self.assertEqual(mode, "")
+ self.assertIsNone(val)
+ self.assertIsNone(pol)
+
+ def test_parse_none(self):
+ mode, val, pol = kenwood_tone.parse_qtdqt(None)
+ self.assertEqual(mode, "")
+ self.assertIsNone(val)
+ self.assertIsNone(pol)
+
+ def test_parse_tone(self):
+ mode, val, pol = kenwood_tone.parse_qtdqt("103.5")
+ self.assertEqual(mode, "Tone")
+ self.assertEqual(val, 103.5)
+ self.assertEqual(pol, "")
+
+ def test_parse_tone_whitespace(self):
+ mode, val, pol = kenwood_tone.parse_qtdqt(" 103.5 ")
+ self.assertEqual(mode, "Tone")
+ self.assertEqual(val, 103.5)
+ self.assertEqual(pol, "")
+
+ def test_parse_dcs_normal(self):
+ mode, val, pol = kenwood_tone.parse_qtdqt("D023N")
+ self.assertEqual(mode, "DTCS")
+ self.assertEqual(val, 23)
+ self.assertEqual(pol, "N")
+
+ def test_parse_dcs_reverse(self):
+ mode, val, pol = kenwood_tone.parse_qtdqt("D032R")
+ self.assertEqual(mode, "DTCS")
+ 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")
+ self.assertEqual(val, 23)
+ self.assertEqual(pol, "N")
+
+ def test_parse_dcs_invalid_format(self):
+ with self.assertRaises(ValueError) as ctx:
+ kenwood_tone.parse_qtdqt("D23N")
+ self.assertIn("D023N", str(ctx.exception))
+
+ def test_parse_dcs_invalid_code(self):
+ with self.assertRaises(ValueError) as ctx:
+ kenwood_tone.parse_qtdqt("DABCN")
+ self.assertIn("D023N", str(ctx.exception))
+
+ def test_parse_tone_invalid(self):
+ with self.assertRaises(ValueError) as ctx:
+ kenwood_tone.parse_qtdqt("abc")
+ self.assertIn("103.5", str(ctx.exception))
+
+
+class TestFormatQtdqt(base.BaseTest):
+ def test_format_dcs(self):
+ result = kenwood_tone.format_qtdqt("DTCS", 23, "N")
+ self.assertEqual(result, "D023N")
+
+ def test_format_dcs_reverse(self):
+ result = kenwood_tone.format_qtdqt("DTCS", 32, "R")
+ self.assertEqual(result, "D032I")
+
+ def test_format_tone(self):
+ result = kenwood_tone.format_qtdqt("Tone", 103.5, "")
+ self.assertEqual(result, "103.5")
+
+ def test_format_empty(self):
+ result = kenwood_tone.format_qtdqt("", None, "")
+ self.assertEqual(result, "")
+
+
+class TestDifferentParameterSets(base.BaseTest):
+ def test_dcs_base_0x2800(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x2800, pol_mask=0x8000)
+ code, pol = model._get_tone_val(0x2800 + 0o023)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "N")
+
+ code, pol = model._get_tone_val(0x2800 + 0o023 + 0x8000)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "R")
+
+ def test_dcs_base_0x8000(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x8000, pol_mask=0x4000)
+ code, pol = model._get_tone_val(0x8000 + 0o023)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "N")
+
+ code, pol = model._get_tone_val(0x8000 + 0o023 + 0x4000)
+ self.assertEqual(code, 23)
+ self.assertEqual(pol, "R")
+
+ def test_tone_flag_0x0000(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, tone_flag=0x0000)
+ val = model._set_tone_val(88.5, None)
+ self.assertEqual(val, 885)
+
+ code, pol = model._get_tone_val(885)
+ self.assertEqual(code, 88.5)
+ self.assertIsNone(pol)
+
+ def test_decimal_dcs_encoding(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, dcs_enc_base=10)
+ val = model._set_tone_val(123, "N")
+ self.assertEqual(val, 0x4000 + 123)
+
+ code, pol = model._get_tone_val(0x4000 + 123)
+ self.assertEqual(code, 123)
+ self.assertEqual(pol, "N")
+
+ code, pol = model._get_tone_val(0x4000 + 123 + 0x2000)
+ self.assertEqual(code, 123)
+ self.assertEqual(pol, "R")
+
+ def test_bcd_dcs_encoding(self):
+ model = kenwood_tone.KenwoodToneModel(
+ dcs_base=0x4000, pol_mask=0x2000, dcs_enc_base=16)
+ val = model._set_tone_val(123, "N")
+ self.assertEqual(val, 0x4123)
+
+ code, pol = model._get_tone_val(0x4123)
+ self.assertEqual(code, 123)
+ self.assertEqual(pol, "N")
+
+ code, pol = model._get_tone_val(0x4123 + 0x2000)
+ self.assertEqual(code, 123)
+ self.assertEqual(pol, "R")
diff --git a/tests/unit/test_repeaterbook.py b/tests/unit/test_repeaterbook.py
index 57532fa..48c250a 100644
--- a/tests/unit/test_repeaterbook.py
+++ b/tests/unit/test_repeaterbook.py
@@ -1,5 +1,6 @@
import datetime
import json
+import lzma
import os
import shutil
import tempfile
@@ -9,6 +10,7 @@ from unittest import mock
import pytest
from chirp import chirp_common
+from chirp.sources import base
from chirp.sources import repeaterbook
@@ -172,23 +174,25 @@ class TestRepeaterbook(unittest.TestCase):
with mock.patch('requests.get') as mock_get:
mock_get.return_value.status_code = 200
mock_get.return_value.iter_content.return_value = [b'foo']
+ mock_get.return_value.headers = {'ETag': 'foo'}
status = mock.MagicMock()
r = rb.get_data(status, 'US', 'OR', '')
self.assertIsNone(r)
files = os.listdir(os.path.join(self.tempdir,
'repeaterbook'))
- # Make sure we only wrote one file and that it is a tempfile
- # not one we will find as a data file later
- self.assertEqual(1, len(files))
- self.assertTrue(files[0].endswith('tmp'))
+ # Make sure we never wrote the bad data to file
+ self.assertEqual(0, len(files))
status.send_fail.assert_called()
def test_get_data_no_results(self):
+ comp = lzma.LZMACompressor(format=lzma.FORMAT_XZ)
+ fake_data = comp.compress(json.dumps({'count': 0}).encode())
+ fake_data += comp.flush()
rb = repeaterbook.RepeaterBook()
with mock.patch('requests.get') as mock_get:
mock_get.return_value.status_code = 200
- mock_get.return_value.iter_content.return_value = [json.dumps(
- {'count': 0}).encode()]
+ mock_get.return_value.iter_content.return_value = [fake_data]
+ mock_get.return_value.headers = {'ETag': 'foo'}
status = mock.MagicMock()
r = rb.get_data(status, 'US', 'OR', '')
self.assertIsNone(r)
@@ -202,11 +206,14 @@ class TestRepeaterbook(unittest.TestCase):
files = os.listdir(self.tempdir)
# Make sure we started with no data files
self.assertEqual(0, len(files))
+ comp = lzma.LZMACompressor(format=lzma.FORMAT_XZ)
+ fake_data = comp.compress(json.dumps({'count': 1}).encode())
+ fake_data += comp.flush()
rb = repeaterbook.RepeaterBook()
with mock.patch('requests.get') as mock_get:
mock_get.return_value.status_code = 200
- mock_get.return_value.iter_content.return_value = [json.dumps(
- {'count': 1}).encode()]
+ mock_get.return_value.iter_content.return_value = [fake_data]
+ mock_get.return_value.headers = {'ETag': 'foo'}
status = mock.MagicMock()
r = rb.get_data(status, 'US', 'OR', '')
self.assertIsNotNone(r)
@@ -254,3 +261,34 @@ class TestRepeaterbook(unittest.TestCase):
'United States', 'Oregon', '')
# Cache file is 45 days old, we should re-fetch
mock_get.assert_called()
+
+ def test_get_data_honors_etag(self):
+ os.mkdir(os.path.join(self.tempdir, 'repeaterbook'))
+ cache_file = os.path.join(self.tempdir,
+ 'repeaterbook',
+ os.path.basename(self.testfile))
+ with open(cache_file, 'w') as f:
+ f.write(json.dumps({'ETag': 'foo'}))
+ rb = repeaterbook.RepeaterBook()
+ with mock.patch('requests.get') as mock_get:
+ mock_get.return_value.status_code = 304
+ real_timedelta = datetime.timedelta
+ real_datetime = datetime.datetime
+
+ future = datetime.datetime.now() + datetime.timedelta(days=45)
+ with mock.patch.object(repeaterbook, 'datetime') as mock_dt:
+ mock_dt.datetime.fromtimestamp = real_datetime.fromtimestamp
+ mock_dt.timedelta = real_timedelta
+ mock_dt.datetime.now.return_value = future
+ r = rb.get_data(mock.MagicMock(),
+ 'United States', 'Oregon', '')
+ # Cache file is 45 days old, we should re-fetch, but the server
+ # said it was unchanged, so we should use the cache
+ mock_get.assert_called()
+ self.assertEqual(cache_file, r)
+ expected_headers = dict(base.HEADERS)
+ expected_headers['If-None-Match'] = 'foo'
+ mock_get.assert_called_once_with(
+ mock.ANY,
+ headers=expected_headers,
+ stream=True)
diff --git a/tests/unit/test_retevis_ra25.py b/tests/unit/test_retevis_ra25.py
new file mode 100644
index 0000000..9e32dba
--- /dev/null
+++ b/tests/unit/test_retevis_ra25.py
@@ -0,0 +1,132 @@
+import os
+import unittest
+
+from chirp import memmap
+from chirp.drivers import retevis_ra25
+
+
+class TestRA25SqlMode(unittest.TestCase):
+ """Test sql_mode (Signal/Squelch Mode) feature for RA25/779UV"""
+
+ def setUp(self):
+ test_image = os.path.join(os.path.dirname(__file__),
+ '..', 'images', 'Retevis_RA25.img')
+ self.radio = retevis_ra25.RA25UVRadio(None)
+ with open(test_image, 'rb') as f:
+ self.radio._mmap = memmap.MemoryMapBytes(f.read())
+ self.radio.process_mmap()
+
+ def test_sql_mode_not_in_memory_extra(self):
+ """sql_mode setting should NOT be present in mem.extra"""
+ mem = self.radio.get_memory(1)
+ setting_names = [s.get_name() for s in mem.extra]
+ self.assertNotIn('sql_mode', setting_names)
+
+ def test_sql_mode_raw_values(self):
+ """sql_mode raw values should be 0 (SQ) or 1 (CT/DCS)"""
+ _mem = self.radio._memobj.memory[0]
+
+ # Test setting to 0 (SQ)
+ _mem.sql_mode = 0
+ self.assertEqual(int(_mem.sql_mode), 0)
+
+ # Test setting to 1 (CT/DCS)
+ _mem.sql_mode = 1
+ self.assertEqual(int(_mem.sql_mode), 1)
+
+ def test_sql_mode_adjacent_fields_intact(self):
+ """Modifying sql_mode should not corrupt adjacent fields"""
+ _mem = self.radio._memobj.memory[0]
+
+ # Store original values
+ orig_tone_id = int(_mem.tone_id)
+ orig_bcl = int(_mem.busychannellockout)
+
+ # Modify sql_mode
+ _mem.sql_mode = 1
+ _mem.sql_mode = 0
+
+ # Verify adjacent fields unchanged
+ self.assertEqual(int(_mem.tone_id), orig_tone_id)
+ self.assertEqual(int(_mem.busychannellockout), orig_bcl)
+
+ def test_sql_mode_in_vfo(self):
+ """VFO struct should also have sql_mode field"""
+ for i in [0, 1]:
+ _vfo = self.radio._memobj.vfo[i]
+ # Should be accessible without error
+ _ = int(_vfo.sql_mode)
+
+ def test_sql_mode_set_from_tmode_empty(self):
+ """sql_mode should be 0 (SQ) when tmode is empty"""
+ mem = self.radio.get_memory(1)
+ mem.tmode = ""
+ self.radio.set_memory(mem)
+
+ _mem = self.radio._memobj.memory[0]
+ self.assertEqual(int(_mem.sql_mode), 0)
+
+ def test_sql_mode_set_from_tmode_tone(self):
+ """sql_mode should be 0 (SQ) when tmode is Tone (TX only)"""
+ mem = self.radio.get_memory(1)
+ mem.tmode = "Tone"
+ mem.rtone = 88.5
+ self.radio.set_memory(mem)
+
+ _mem = self.radio._memobj.memory[0]
+ self.assertEqual(int(_mem.sql_mode), 0)
+
+ def test_sql_mode_set_from_tmode_tsql(self):
+ """sql_mode should be 1 (CT/DCS) when tmode is TSQL"""
+ mem = self.radio.get_memory(1)
+ mem.tmode = "TSQL"
+ mem.ctone = 88.5
+ self.radio.set_memory(mem)
+
+ _mem = self.radio._memobj.memory[0]
+ self.assertEqual(int(_mem.sql_mode), 1)
+
+ def test_sql_mode_set_from_tmode_dtcs(self):
+ """sql_mode should be 1 (CT/DCS) when tmode is DTCS"""
+ mem = self.radio.get_memory(1)
+ mem.tmode = "DTCS"
+ mem.dtcs = 23
+ self.radio.set_memory(mem)
+
+ _mem = self.radio._memobj.memory[0]
+ self.assertEqual(int(_mem.sql_mode), 1)
+
+ def test_sql_mode_set_from_cross_with_rx_tone(self):
+ """sql_mode should be 1 (CT/DCS) when Cross mode has RX tone"""
+ mem = self.radio.get_memory(1)
+ mem.tmode = "Cross"
+ mem.cross_mode = "Tone->Tone"
+ mem.rtone = 88.5
+ mem.ctone = 100.0
+ self.radio.set_memory(mem)
+
+ _mem = self.radio._memobj.memory[0]
+ self.assertEqual(int(_mem.sql_mode), 1)
+
+ def test_sql_mode_set_from_cross_with_rx_dtcs(self):
+ """sql_mode should be 1 (CT/DCS) when Cross mode has RX DTCS"""
+ mem = self.radio.get_memory(1)
+ mem.tmode = "Cross"
+ mem.cross_mode = "Tone->DTCS"
+ mem.rtone = 88.5
+ mem.rx_dtcs = 23
+ self.radio.set_memory(mem)
+
+ _mem = self.radio._memobj.memory[0]
+ self.assertEqual(int(_mem.sql_mode), 1)
+
+ def test_sql_mode_set_from_cross_without_rx_tone(self):
+ """sql_mode should be 0 (SQ) when Cross mode has no RX tone"""
+ mem = self.radio.get_memory(1)
+ mem.tmode = "Cross"
+ mem.cross_mode = "DTCS->"
+ mem.dtcs = 23
+ self.radio.set_memory(mem)
+
+ _mem = self.radio._memobj.memory[0]
+ self.assertEqual(int(_mem.sql_mode), 0)
diff --git a/tests/unit/test_serialtrace.py b/tests/unit/test_serialtrace.py
index 22e8403..cce7a71 100644
--- a/tests/unit/test_serialtrace.py
+++ b/tests/unit/test_serialtrace.py
@@ -1,5 +1,6 @@
import unittest
from unittest import mock
+import warnings
from chirp.wxui import serialtrace
@@ -77,3 +78,47 @@ class TestSerialTrace(unittest.TestCase):
# Before we are closed, the trace file should have been abandoned
self.assertIsNone(trace._SerialTrace__tracef)
+
+ @mock.patch('tempfile.NamedTemporaryFile')
+ @mock.patch('serial.Serial.open')
+ @mock.patch('serial.Serial.write')
+ @mock.patch('serial.Serial.read')
+ def test_timeout_warning(self, mock_read, mock_write, mock_open, mock_tf):
+ mock_tf.return_value.writelines.side_effect = [None]
+ trace = serialtrace.SerialTrace(timeout=0.01, baudrate=9600)
+ trace.open()
+ with self.assertWarns(Warning) as cm:
+ # 2000 bytes takes about 2s, so 0.01s timeout should warn
+ trace.read(2000)
+ self.assertIn('requires', str(cm.warning))
+
+ @mock.patch('tempfile.NamedTemporaryFile')
+ @mock.patch('serial.Serial.open')
+ @mock.patch('serial.Serial.write')
+ @mock.patch('serial.Serial.read')
+ def test_timeout_no_warning(self, mock_read, mock_write, mock_open,
+ mock_tf):
+ mock_tf.return_value.writelines.side_effect = [None]
+ trace = serialtrace.SerialTrace(timeout=2, baudrate=9600)
+ trace.open()
+ warnings.resetwarnings()
+ with warnings.catch_warnings(record=True) as w:
+ # 1000 bytes takes about 1s, so 2s timeout should yield no warning
+ trace.read(1000)
+ self.assertTrue(len(w) == 0)
+
+ @mock.patch('tempfile.NamedTemporaryFile')
+ @mock.patch('serial.Serial.open')
+ @mock.patch('serial.Serial.write')
+ @mock.patch('serial.Serial.read')
+ def test_timeout_write_read_warning(self, mock_read, mock_write, mock_open,
+ mock_tf):
+ mock_tf.return_value.writelines.side_effect = [None]
+ trace = serialtrace.SerialTrace(timeout=2, baudrate=9600)
+ trace.open()
+ with warnings.catch_warnings(record=True) as w:
+ # If we do a write before the read, the time to complete the write
+ # should be accounted for in the read timeout calculation
+ trace.write(b'f' * 1000)
+ trace.read(1000)
+ self.assertIn('1000 written bytes in 1145ms', str(w[0].message))
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 9273912..5b8887c 100755
--- a/tools/check_commit.sh
+++ b/tools/check_commit.sh
@@ -17,28 +17,29 @@ git log --pretty=oneline --no-merges --abbrev-commit ${BASE}..
echo
git diff ${BASE}.. -- '*.py' | grep '^+' > added_lines
+git diff ${BASE}.. -- 'chirp/drivers/*.py' | grep '^+' > driver_lines
-if grep -E '(from|import).*six' added_lines; then
- fail No new uses of future
+if grep -E '\<(from|import)\>.*\<six\>' added_lines; then
+ fail No new uses of six
fi
-if grep -E '\wsix\w' added_lines; then
+if grep -E '\<six\>' added_lines; then
fail No new uses of six
fi
-if grep -E '(from|import).*builtins' added_lines; then
+if grep -E '\<(from|import)\>.*builtins' added_lines; then
fail No new uses of future
fi
-if grep -E '\wfuture\w' added_lines; then
+if grep -E '\<future\>' added_lines; then
fail No new uses of future
fi
-if grep -E '(from|import).*past(?!e)' added_lines; then
+if grep -E '\<(from|import)\>.*\<past\>' added_lines; then
fail Use of past library not allowed
fi
-if grep -E 'MemoryMap\(' added_lines; then
+if grep -E '\<MemoryMap\(' added_lines; then
fail New uses of MemoryMap should be MemoryMapBytes
fi
@@ -46,7 +47,7 @@ if grep -E "[^_]_\([^\"']" added_lines; then
fail 'Translated strings must be literals!'
fi
-if grep -E "eval\(" added_lines; then
+if grep -E "\<eval\(" added_lines; then
fail 'Use of eval() is dangerous and not permitted!'
fi
@@ -73,15 +74,26 @@ done
# fail 'New drivers should not have match_model() implemented as it is not needed'
#fi
-if grep -E '\Wprint\(' added_lines; then
+if grep -E '\<print\(' added_lines; then
fail 'Do not use print()'
fi
+if grep -E '\<(from|import)\>.*wx' driver_lines; then
+ fail 'Drivers may not import GUI components or manipulate the GUI'
+fi
+
+if grep -E '(subprocess|webbrowser)' driver_lines; then
+ fail 'Drivers may not spawn external commands'
+fi
+
if git log ${BASE}.. --merges | grep .; then
fail Please do not include merge commits in your PR
fi
make -C chirp/locale clean all >/dev/null 2>&1
+if [ $? -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.
#