summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDave Hibberd <hibby@debian.org>2026-08-20 23:11:02 +0100
committerDave Hibberd <hibby@debian.org>2026-08-20 23:11:02 +0100
commit5f4fe8ab00a12060662e5df0fc8855f0488de35d (patch)
tree95a7d9b81673c059b18a1e551079104050b4ca11
parentdff1a610625ebe7841fca01e20ca6d86b65ee4d0 (diff)
New upstream version 20260814upstream/20260814
-rw-r--r--PKG-INFO2
-rw-r--r--chirp.egg-info/PKG-INFO2
-rw-r--r--chirp.egg-info/SOURCES.txt71
-rw-r--r--chirp/__init__.py2
-rw-r--r--chirp/bandplan_iaru_r1.py33
-rw-r--r--chirp/bitwise.py176
-rw-r--r--chirp/bitwise_grammar.py6
-rw-r--r--chirp/checksum.py64
-rw-r--r--chirp/chirp_common.py147
-rw-r--r--chirp/cli/main.py2
-rw-r--r--chirp/directory.py15
-rw-r--r--chirp/drivers/__init__.py52
-rw-r--r--chirp/drivers/alinco.py10
-rw-r--r--chirp/drivers/alinco_dr735t.py6
-rw-r--r--chirp/drivers/anytone.py12
-rw-r--r--chirp/drivers/anytone778uv.py30
-rw-r--r--chirp/drivers/anytone_ht.py16
-rw-r--r--chirp/drivers/anytone_iii.py14
-rw-r--r--chirp/drivers/ap510.py2
-rw-r--r--chirp/drivers/ar8200.py1695
-rw-r--r--chirp/drivers/baofeng_common.py27
-rw-r--r--chirp/drivers/baofeng_digital.py65
-rw-r--r--chirp/drivers/baofeng_uv17.py2
-rw-r--r--chirp/drivers/baofeng_uv17Pro.py510
-rw-r--r--chirp/drivers/bf_t1.py6
-rw-r--r--chirp/drivers/bf_t8.py8
-rw-r--r--chirp/drivers/boblov_x3plus.py2
-rw-r--r--chirp/drivers/btech.py729
-rw-r--r--chirp/drivers/ft1d.py421
-rw-r--r--chirp/drivers/ft4.py26
-rw-r--r--chirp/drivers/ft450d.py56
-rw-r--r--chirp/drivers/ft50.py12
-rw-r--r--chirp/drivers/ft60.py10
-rw-r--r--chirp/drivers/ft7100.py2
-rw-r--r--chirp/drivers/ft7800.py275
-rw-r--r--chirp/drivers/ft817.py6
-rw-r--r--chirp/drivers/ft90.py10
-rw-r--r--chirp/drivers/ftlx011.py775
-rw-r--r--chirp/drivers/ftm350.py8
-rw-r--r--chirp/drivers/ga510.py30
-rw-r--r--chirp/drivers/generic_csv.py14
-rw-r--r--chirp/drivers/h777.py145
-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/ic2730.py26
-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/icq7.py5
-rw-r--r--chirp/drivers/ict8.py2
-rw-r--r--chirp/drivers/iradio_common.py56
-rw-r--r--chirp/drivers/iradio_uv_5118.py88
-rw-r--r--chirp/drivers/iradio_uv_5118plus.py81
-rw-r--r--chirp/drivers/kenwood_d7.py16
-rw-r--r--chirp/drivers/kenwood_live.py12
-rw-r--r--chirp/drivers/kg935g.py270
-rw-r--r--chirp/drivers/kguv8d.py111
-rw-r--r--chirp/drivers/kguv8dplus.py113
-rw-r--r--chirp/drivers/kguv8e.py116
-rw-r--r--chirp/drivers/kguv920pa.py120
-rw-r--r--chirp/drivers/kguv980p.py118
-rw-r--r--chirp/drivers/kguv9dplus.py111
-rw-r--r--chirp/drivers/kyd.py93
-rw-r--r--chirp/drivers/kyd_IP620.py93
-rw-r--r--chirp/drivers/leixen.py11
-rw-r--r--chirp/drivers/lt725uv.py37
-rw-r--r--chirp/drivers/mml_jc8810.py23
-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.py6
-rw-r--r--chirp/drivers/radtel_rt490.py2
-rw-r--r--chirp/drivers/radtel_rt880g.py2315
-rw-r--r--chirp/drivers/radtel_rt900.py2429
-rw-r--r--chirp/drivers/radtel_t18.py68
-rw-r--r--chirp/drivers/retevis_c2.py1349
-rw-r--r--chirp/drivers/retevis_h777v4.py350
-rw-r--r--chirp/drivers/retevis_ha1g.py1779
-rw-r--r--chirp/drivers/retevis_ha2.py1290
-rw-r--r--chirp/drivers/retevis_ra25.py49
-rw-r--r--chirp/drivers/retevis_ra86.py21
-rw-r--r--chirp/drivers/retevis_ra87.py12
-rw-r--r--chirp/drivers/retevis_rb15.py38
-rw-r--r--chirp/drivers/retevis_rb17p.py2
-rw-r--r--chirp/drivers/retevis_rb28.py6
-rw-r--r--chirp/drivers/retevis_rt1.py2
-rw-r--r--chirp/drivers/retevis_rt21.py154
-rw-r--r--chirp/drivers/retevis_rt22.py143
-rw-r--r--chirp/drivers/retevis_rt23.py23
-rw-r--r--chirp/drivers/retevis_rt26.py2
-rw-r--r--chirp/drivers/retevis_rt76p.py48
-rw-r--r--chirp/drivers/retevis_rt87.py29
-rw-r--r--chirp/drivers/retevis_rt98.py58
-rw-r--r--chirp/drivers/tdh8.py436
-rw-r--r--chirp/drivers/tdm11.py921
-rw-r--r--chirp/drivers/tdxone_tdq8a.py34
-rw-r--r--chirp/drivers/th7800.py10
-rw-r--r--chirp/drivers/th9000.py14
-rw-r--r--chirp/drivers/th9800.py861
-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.py21
-rw-r--r--chirp/drivers/thd74.py21
-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.py21
-rw-r--r--chirp/drivers/tk690.py20
-rw-r--r--chirp/drivers/tk760.py14
-rw-r--r--chirp/drivers/tk760g.py88
-rw-r--r--chirp/drivers/tk8102.py88
-rw-r--r--chirp/drivers/tk8160.py203
-rw-r--r--chirp/drivers/tk8180.py324
-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.py11
-rw-r--r--chirp/drivers/ts850.py4
-rw-r--r--chirp/drivers/uv5r.py312
-rw-r--r--chirp/drivers/uvb5.py5
-rw-r--r--chirp/drivers/uvk5.py76
-rw-r--r--chirp/drivers/uvk5_egzumer.py4
-rw-r--r--chirp/drivers/vgc.py22
-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.py12
-rw-r--r--chirp/drivers/vxa700.py319
-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.py251
-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.mobin90821 -> 94556 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 -> 87412 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/zh_CN/LC_MESSAGES/CHIRP.mobin75039 -> 72931 bytes
-rw-r--r--chirp/platform.py45
-rw-r--r--chirp/settings.py36
-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/US Aviation Frequencies.csv56
-rw-r--r--chirp/wxui/__init__.py13
-rw-r--r--chirp/wxui/accessibility.py429
-rw-r--r--chirp/wxui/bugreport.py65
-rw-r--r--chirp/wxui/clone.py5
-rw-r--r--chirp/wxui/common.py172
-rw-r--r--chirp/wxui/config.py2
-rw-r--r--chirp/wxui/developer.py18
-rw-r--r--chirp/wxui/main.py19
-rw-r--r--chirp/wxui/memedit.py136
-rw-r--r--chirp/wxui/query_sources.py94
-rw-r--r--chirp/wxui/radioinfo.py5
-rw-r--r--chirp/wxui/report.py3
-rw-r--r--chirp/wxui/serialtrace.py57
-rw-r--r--requirements.txt7
-rw-r--r--setup.py2
-rw-r--r--tests/__pycache__/base.cpython-310.pycbin5375 -> 5465 bytes
-rw-r--r--tests/__pycache__/test_brute_force.cpython-310-pytest-7.1.3.pycbin6661 -> 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/base.py10
-rw-r--r--tests/driver_xfails.yaml36
-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_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-5RM_Plus.imgbin0 -> 33857 bytes
-rw-r--r--tests/images/Icom_IC-2730E.imgbin0 -> 21493 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/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-900.imgbin0 -> 62249 bytes
-rw-r--r--tests/images/Radtel_RT-900_BT.imgbin0 -> 62257 bytes
-rw-r--r--tests/images/Radtel_RT-910.imgbin0 -> 62249 bytes
-rw-r--r--tests/images/Radtel_RT-910_BT.imgbin0 -> 62257 bytes
-rw-r--r--tests/images/Radtel_RT-920.imgbin0 -> 62433 bytes
-rw-r--r--tests/images/Retevis_C2.imgbin0 -> 17593 bytes
-rw-r--r--tests/images/Retevis_HA1G.imgbin0 -> 55545 bytes
-rw-r--r--tests/images/Retevis_HA1UV.imgbin0 -> 55569 bytes
-rw-r--r--tests/images/Retevis_HA2.imgbin0 -> 72265 bytes
-rw-r--r--tests/images/Retevis_MA1.imgbin0 -> 65485 bytes
-rw-r--r--tests/images/Retevis_RB626.imgbin969 -> 2245 bytes
-rw-r--r--tests/images/Retevis_RT21H.imgbin0 -> 401 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/Vertex_Standard_FTL-2011.imgbin589 -> 0 bytes
-rw-r--r--tests/images/Vertex_Standard_VXA-700.imgbin4096 -> 0 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_VX-1.imgbin0 -> 5079 bytes
-rw-r--r--tests/images/Yaesu_VX-150.imgbin0 -> 5538 bytes
-rw-r--r--tests/test_brute_force.py4
-rw-r--r--tests/test_clone.py14
-rw-r--r--tests/test_edges.py4
-rw-r--r--tests/unit/__pycache__/test_amsats.cpython-310-pytest-7.1.3.pycbin0 -> 3222 bytes
-rw-r--r--tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pycbin18843 -> 22655 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.pycbin33055 -> 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_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 -> 60864 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/test_amsats.py112
-rw-r--r--tests/unit/test_bitwise.py114
-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.py85
-rw-r--r--tests/unit/test_import_logic.py46
-rw-r--r--tests/unit/test_kenwood_tone.py2187
-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
-rwxr-xr-xtools/check_commit.sh27
246 files changed, 27115 insertions, 4402 deletions
diff --git a/PKG-INFO b/PKG-INFO
index bf281ef..61f065e 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 2.4
Name: chirp
-Version: 20250912
+Version: 20260814
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 bf281ef..61f065e 100644
--- a/chirp.egg-info/PKG-INFO
+++ b/chirp.egg-info/PKG-INFO
@@ -1,6 +1,6 @@
Metadata-Version: 2.4
Name: chirp
-Version: 20250912
+Version: 20260814
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 8ec7a33..bdec280 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,6 +43,7 @@ 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_uv17.py
@@ -73,7 +76,6 @@ chirp/drivers/ft817.py
chirp/drivers/ft818.py
chirp/drivers/ft857.py
chirp/drivers/ft90.py
-chirp/drivers/ftlx011.py
chirp/drivers/ftm3200d.py
chirp/drivers/ftm350.py
chirp/drivers/ftm7250d.py
@@ -119,6 +121,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
@@ -141,12 +144,18 @@ chirp/drivers/mml_jc8810.py
chirp/drivers/mursv1.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
@@ -163,6 +172,7 @@ chirp/drivers/retevis_rt87.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
@@ -178,6 +188,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
@@ -203,6 +214,8 @@ chirp/drivers/uvb5.py
chirp/drivers/uvk5.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
@@ -211,11 +224,11 @@ chirp/drivers/vx510.py
chirp/drivers/vx6.py
chirp/drivers/vx7.py
chirp/drivers/vx8.py
-chirp/drivers/vxa700.py
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 +255,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 +294,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
@@ -360,6 +377,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 +389,22 @@ 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_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 +427,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
@@ -445,6 +470,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 +500,18 @@ 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/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,10 +523,21 @@ 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
tests/images/Retevis_RA25.img
@@ -539,6 +582,7 @@ tests/images/Retevis_RT16.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
@@ -573,7 +617,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
@@ -586,8 +633,6 @@ tests/images/TYT_TH-UVF8D.img
tests/images/TYT_TH9000_144.img
tests/images/Talkpod_A36plus.img
tests/images/Talkpod_A36plus_8w.img
-tests/images/Vertex_Standard_FTL-2011.img
-tests/images/Vertex_Standard_VXA-700.img
tests/images/WACCOM_MINI-8900.img
tests/images/Wouxun_KG-1000G.img
tests/images/Wouxun_KG-1000G_Plus.img
@@ -610,6 +655,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
@@ -643,6 +691,8 @@ tests/images/Yaesu_FT3D_R.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
@@ -659,9 +709,12 @@ 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
@@ -669,12 +722,14 @@ tests/unit/test_directory.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
@@ -685,22 +740,28 @@ 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_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
diff --git a/chirp/__init__.py b/chirp/__init__.py
index 31b111c..91f0eb5 100644
--- a/chirp/__init__.py
+++ b/chirp/__init__.py
@@ -1 +1 @@
-CHIRP_VERSION = "next-20250912"
+CHIRP_VERSION = "next-20260814"
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 e595f1b..a8e69ad 100644
--- a/chirp/bitwise.py
+++ b/chirp/bitwise.py
@@ -41,6 +41,10 @@
# u8 foo;
# u16 bar;
# } baz; /* Structure with u8 and u16 */
+# union {
+# u16 whole;
+# bbcd digits[2];
+# }; /* Union where all elements occupy the same memory */
#
# Example directives:
#
@@ -111,12 +115,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):
@@ -147,21 +150,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'):
@@ -288,7 +306,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])
@@ -337,6 +356,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)
@@ -348,8 +369,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")
@@ -706,8 +726,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)
@@ -737,13 +756,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):
@@ -760,8 +783,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()
@@ -779,13 +804,24 @@ 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)
class structDataElement(DataElement):
def __repr__(self):
- s = "struct {" + os.linesep
+ return self._make_repr('struct')
+
+ def _make_repr(self, typename):
+ s = typename + " {" + os.linesep
for prop in self._keys:
s += " %15s: %s%s" % (prop, repr(self._generators[prop]),
os.linesep)
@@ -887,6 +923,20 @@ class structDataElement(DataElement):
yield key, self._generators[key]
+class unionDataElement(structDataElement):
+ def __repr__(self):
+ return self._make_repr('union')
+
+ def set_union_size(self, size):
+ # We don't know the size of the union until we have processed the first
+ # member, so allow this to be set after creation.
+ assert (size % 8 == 0)
+ self.__dict__['_size'] = size
+
+ def size(self):
+ return self._size
+
+
def parse_count(string):
if string.startswith('0x'):
return int(string, 16)
@@ -1073,6 +1123,51 @@ class Processor:
else:
raise Exception("Internal error: What is `%s'?" % struct[0][0])
+ def parse_union(self, union):
+ deftype = union[-1]
+ block = union[:-1]
+ union_size = 0
+ tmp = self._generators
+
+ if deftype[0] == "array":
+ name = deftype[1][0][1]
+ count = parse_count(deftype[1][1][1])
+ elif deftype[0] == "symbol":
+ name = deftype[1]
+ count = 1
+
+ result = arrayDataElement(self._offset)
+ for i in range(0, count):
+ start_of_union_offset = self._offset
+ self._generators = element = unionDataElement(
+ self._data,
+ start_of_union_offset,
+ name=name)
+ for t, d in block:
+ self._offset = start_of_union_offset
+ if t not in ("definition", "struct", "union"):
+ raise ParseError("Not supported in union: %s" % t)
+ self.parse_statement(t, d)
+ size = self._offset - start_of_union_offset
+ if union_size == 0:
+ union_size = size
+ elif union_size != size:
+ LOG.error('Union member size mismatch parsing %s', name)
+ raise ParseError('Union members must be the same size '
+ '(found %i, expected %i)' % (size,
+ union_size))
+ element.set_union_size(union_size * 8)
+ if union_size == 0:
+ raise ParseError('Empty union %r is not valid' % name)
+ # Increment the offset only past the end of the union
+ self._offset = start_of_union_offset + union_size
+ result.append(element)
+
+ self._generators = tmp
+ if count == 1:
+ result = result[0]
+ self._generators[name] = result
+
def assert_negative_seek(self, message):
warnings.warn(message, DeprecationWarning, stacklevel=6)
@@ -1097,14 +1192,19 @@ class Processor:
LOG.debug("%s: %i (0x%08X)" %
(value[1:-1], self._offset, self._offset))
+ def parse_statement(self, type_, data):
+ if type_ == "struct":
+ self.parse_struct(data)
+ elif type_ == "definition":
+ self.parse_defn(data)
+ elif type_ == "directive":
+ self.parse_directive(data)
+ elif type_ == "union":
+ self.parse_union(data)
+
def parse_block(self, lang):
for t, d in lang:
- if t == "struct":
- self.parse_struct(d)
- elif t == "definition":
- self.parse_defn(d)
- elif t == "directive":
- self.parse_directive(d)
+ self.parse_statement(t, d)
def parse(self, lang):
self._lines = {}
diff --git a/chirp/bitwise_grammar.py b/chirp/bitwise_grammar.py
index 934efa9..0500a64 100644
--- a/chirp/bitwise_grammar.py
+++ b/chirp/bitwise_grammar.py
@@ -75,7 +75,7 @@ def directive():
def _block_inner():
- return -2, [definition, struct, directive]
+ return -2, [definition, struct, union, directive]
def _block():
@@ -94,6 +94,10 @@ def struct():
return keyword("struct"), [struct_defn, struct_decl], ";"
+def union():
+ return keyword("union"), _block, [array, symbol], ";"
+
+
def _language():
return _block_inner
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 2a7d6f7..324abdf 100644
--- a/chirp/chirp_common.py
+++ b/chirp/chirp_common.py
@@ -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):
@@ -1751,7 +1798,7 @@ def is_2_5(freq):
def is_8_33(freq):
"""Returns True if @freq is reachable by a 8.33 kHz step"""
- return (freq % 25000) in [0, 8330, 16660]
+ return (freq % 25000) in [8330, 8333, 16660, 16666]
def is_1_0(freq):
@@ -1789,11 +1836,67 @@ def required_step(freq, allowed=None):
"tuning step for %s" % format_freq(freq))
+def is_airband(freq):
+ """Returns True if @freq is in the airband range"""
+ return in_range(freq, [(to_MHz(108), to_MHz(137))])
+
+
def fix_rounded_step(freq):
"""Some radios imply the last bit of 12.5 kHz and 6.25 kHz step
frequencies. Take the base @freq and return the corrected one"""
allowed = [12.5, 6.25]
+ 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. 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
+ 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
+
try:
required_step(freq + 500, allowed=allowed)
return freq + 500
@@ -1860,32 +1963,32 @@ def name16(name, just_upper=False):
def to_GHz(val):
"""Convert @val in GHz to Hz"""
- return val * 1000000000
+ return int(val * 1000000000)
def to_MHz(val):
"""Convert @val in MHz to Hz"""
- return val * 1000000
+ return int(val * 1000000)
def to_kHz(val):
"""Convert @val in kHz to Hz"""
- return val * 1000
+ return int(val * 1000)
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):
@@ -2137,3 +2240,19 @@ def in_range(freq, ranges):
if lo <= freq <= hi:
return True
return False
+
+
+def is_split(bands, freq1, freq2):
+ """Check if two freqs are in the same band from a list of bands
+ Returns False if the two freqs are in the same band (not split)
+ or True if they are in separate bands (split)"""
+
+ # determine if the two freqs are in the same band
+ for low, high in bands:
+ if freq1 >= low and freq1 <= high and \
+ freq2 >= low and freq2 <= high:
+ # if the two freqs are on the same Band this is not a split
+ return False
+
+ # if you get here is because the freq pairs are split
+ return True
diff --git a/chirp/cli/main.py b/chirp/cli/main.py
index 473ceee..9dd0d0b 100644
--- a/chirp/cli/main.py
+++ b/chirp/cli/main.py
@@ -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 e6073f5..59a764a 100644
--- a/chirp/drivers/__init__.py
+++ b/chirp/drivers/__init__.py
@@ -23,13 +23,13 @@ from chirp.drivers import ft2d
from chirp.drivers import ft60
from chirp.drivers import ft70
from chirp.drivers import ft7100
-from chirp.drivers import ft7800
+from chirp.drivers import tk760g
from chirp.drivers import ft8100
from chirp.drivers import ft817
from chirp.drivers import ft818
from chirp.drivers import ft857
from chirp.drivers import ft90
-from chirp.drivers import ftlx011
+from chirp.drivers import ft7800
from chirp.drivers import ftm3200d
from chirp.drivers import ftm350
from chirp.drivers import ftm7250d
@@ -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,7 +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 __init__
+from chirp.drivers import tdh8
from chirp.drivers import bjuv55
from chirp.drivers import rh5r_v2
from chirp.drivers import tdxone_tdq8a
@@ -127,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 tk760g
+from chirp.drivers import alinco
from chirp.drivers import tk8102
from chirp.drivers import tk8160
from chirp.drivers import tk8180
@@ -151,33 +151,43 @@ from chirp.drivers import vx510
from chirp.drivers import vx6
from chirp.drivers import vx7
from chirp.drivers import vx8
-from chirp.drivers import vxa700
+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_uv17Pro
from chirp.drivers import iradio_uv_5118plus
+from chirp.drivers import retevis_ha1g
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 mml_jc8810
+from chirp.drivers import retevis_ra25
from chirp.drivers import icf520
-from chirp.drivers import tdh8
+from chirp.drivers import retevis_ra86
+from chirp.drivers import retevis_ra87
from chirp.drivers import tk280
-from chirp.drivers import baofeng_uv17
from chirp.drivers import uvk5
-from chirp.drivers import retevis_ra25
-from chirp.drivers import radtel_rt620
+from chirp.drivers import ar8200
+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 baofeng_digital
+from chirp.drivers import uvk5_egzumer
+from chirp.drivers import radtel_rt620
+from chirp.drivers import retevis_c2
from chirp.drivers import ts790e
+from chirp.drivers import retevis_ha2
from chirp.drivers import icm710
-from chirp.drivers import tk690
+from chirp.drivers import vx1
+from chirp.drivers import baofeng_digital
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 radioddity_db40g
+from chirp.drivers import radioddity_gm30
+from chirp.drivers import kenwood_d7
+from chirp.drivers import radtel_rt880g
from chirp.drivers import retevis_h777v4
-from chirp.drivers import baofeng_uv17Pro
-from chirp.drivers import retevis_ra86
-__all__ = ['anytone', 'btech', 'anytone778uv', 'anytone_ht', 'anytone_iii', 'baofeng_common', 'baofeng_uv3r', 'baofeng_wp970i', 'bf_t1', 'bf_t8', 'boblov_x3plus', 'fake', 'fd268', 'ft1500m', 'ft1802', 'ft1d', 'ft2800', 'ft2900', 'ft4', 'ft450d', 'ft50', 'ft2d', 'ft60', 'ft70', 'ft7100', 'ft7800', 'ft8100', 'ft817', 'ft818', 'ft857', 'ft90', 'ftlx011', 'ftm3200d', 'ftm350', 'ftm7250d', 'ga510', 'generic_csv', 'generic_tpe', 'gmrsuv1', 'gmrsv2', 'h777', 'hf90', 'hg_uv98', 'alinco', 'bj9900', 'ic2100', 'hobbypcb', 'ic208', 'ic2300', 'ic2720', 'ic2200', 'ic2730', 'ic2820', 'ic9x_ll', 'ic9x', 'ic9x_icf', 'icf', 'ic9x_icf_ll', 'icomciv', 'icp7', 'icq7', 'ict8', 'icv80', 'ict70', 'ict7h', 'icv86', 'id51', 'icx90', 'icw32', 'icx8x', 'id31', 'id5100', 'id51plus', 'id800', 'id880', 'idrp', 'kg935g', 'kguv8d', 'iradio_uv_5118', 'kenwood_hmk', 'kenwood_itm', 'kenwood_live', 'kguv8e', 'kyd', 'kguv8dplus', 'kguv920pa', 'kguv980p', 'kguv9dplus', 'lt725uv', 'kyd_IP620', 'leixen', 'mursv1', 'puxing', 'ap510', 'puxing_px888k', 'radioddity_r2', 'radtel_t18', 'retevis_rb15', 'retevis_rb17p', 'retevis_rb28', 'retevis_rt1', 'retevis_rt21', 'retevis_rt22', 'retevis_rt23', 'retevis_rt26', 'retevis_rt76p', 'retevis_rt87', 'retevis_rt98', '__init__', 'bjuv55', 'rh5r_v2', 'tdxone_tdq8a', 'template', 'tg_uv2p', 'th350', 'th7800', 'th9000', 'th9800', 'th_uv3r', 'th_uv3r25', 'th_uv8000', 'th_uv88', 'th_uvf8d', 'thd72', 'thd74', 'thuv1f', 'tk270', 'tk3140', 'tk760', 'tk760g', 'tk8102', 'tk8160', 'tk8180', 'tmd710', 'tmv71', 'tmv71_ll', 'ts2000', 'ts480', 'ts590', 'ts850', 'uv5r', 'uv5x3', 'uv6r', 'uvb5', 'vgc', 'vx170', 'vx2', 'vx3', 'vx5', 'vx510', 'vx6', 'vx7', 'vx8', 'vxa700', 'wouxun', 'wouxun_common', 'kenwood_d7', 'iradio_uv_5118plus', 'ksun_m6', 'retevis_ra87', 'uvk5_egzumer', 'tk481', 'ict10', 'radioddity_gm30', 'mml_jc8810', 'icf520', 'tdh8', 'tk280', 'baofeng_uv17', 'uvk5', 'retevis_ra25', 'radtel_rt620', 'radtel_rt490', 'baofeng_digital', 'ts790e', 'icm710', 'tk690', 'alinco_dr735t', 'yaesu_clone', 'retevis_h777v4', 'baofeng_uv17Pro', 'retevis_ra86']
+from chirp.drivers import iradio_common
+from chirp.drivers import radtel_rt900
+__all__ = ['anytone', 'btech', 'anytone778uv', 'anytone_ht', 'anytone_iii', 'baofeng_common', 'baofeng_uv3r', 'baofeng_wp970i', 'bf_t1', 'bf_t8', 'boblov_x3plus', 'fake', 'fd268', 'ft1500m', 'ft1802', 'ft1d', 'ft2800', 'ft2900', 'ft4', 'ft450d', 'ft50', 'ft2d', 'ft60', 'ft70', 'ft7100', 'tk760g', 'ft8100', 'ft817', 'ft818', 'ft857', 'ft90', 'ft7800', 'ftm3200d', 'ftm350', 'ftm7250d', 'ga510', 'generic_csv', 'generic_tpe', 'gmrsuv1', 'gmrsv2', 'h777', 'hf90', 'hg_uv98', 'tk11', 'bj9900', 'ic2100', 'hobbypcb', 'ic208', 'ic2300', 'ic2720', 'ic2200', 'ic2730', 'ic2820', 'ic9x_ll', 'ic9x', 'ic9x_icf', 'icf', 'ic9x_icf_ll', 'icomciv', 'icp7', 'icq7', 'ict8', 'icv80', 'ict70', 'ict7h', 'icv86', 'id51', 'icx90', 'icw32', 'icx8x', 'id31', 'id5100', 'id51plus', 'id800', 'id880', 'idrp', 'kg935g', 'kguv8d', 'iradio_uv_5118', 'kenwood_hmk', 'kenwood_itm', 'kenwood_live', 'kguv8e', 'kyd', 'kguv8dplus', 'kguv920pa', 'kguv980p', 'kguv9dplus', 'lt725uv', 'kyd_IP620', 'leixen', 'mursv1', 'puxing', 'ap510', 'puxing_px888k', 'radioddity_r2', 'radtel_t18', 'retevis_rb15', 'retevis_rb17p', 'retevis_rb28', 'retevis_rt1', 'retevis_rt21', 'retevis_rt22', 'retevis_rt23', 'retevis_rt26', 'retevis_rt76p', 'retevis_rt87', 'retevis_rt98', 'tdh8', 'bjuv55', 'rh5r_v2', 'tdxone_tdq8a', 'template', 'tg_uv2p', 'th350', 'th7800', 'th9000', 'th9800', 'th_uv3r', 'th_uv3r25', 'th_uv8000', 'th_uv88', 'th_uvf8d', 'thd72', 'thd74', 'thuv1f', 'tk270', 'tk3140', 'tk760', 'alinco', 'tk8102', 'tk8160', 'tk8180', 'tmd710', 'tmv71', 'tmv71_ll', 'ts2000', 'ts480', 'ts590', 'ts850', 'uv5r', 'uv5x3', 'uv6r', 'uvb5', 'vgc', 'vx170', 'vx2', 'vx3', 'vx5', 'vx510', 'vx6', 'vx7', 'vx8', '__init__', 'wouxun', 'wouxun_common', 'baofeng_uv17Pro', 'iradio_uv_5118plus', 'retevis_ha1g', 'ksun_m6', 'tk481', 'ict10', 'retevis_ra25', 'icf520', 'retevis_ra86', 'retevis_ra87', 'tk280', 'uvk5', 'ar8200', 'baofeng_uv17', 'yaesu_clone', 'tdm11', 'radtel_rt490', 'uvk5_egzumer', 'radtel_rt620', 'retevis_c2', 'ts790e', 'retevis_ha2', 'icm710', 'vx1', 'baofeng_digital', 'alinco_dr735t', 'mml_jc8810', 'tk690', 'vx150', 'radioddity_db40g', 'radioddity_gm30', 'kenwood_d7', 'radtel_rt880g', 'retevis_h777v4', 'iradio_common', 'radtel_rt900']
diff --git a/chirp/drivers/alinco.py b/chirp/drivers/alinco.py
index a53eaf1..02809b7 100644
--- a/chirp/drivers/alinco.py
+++ b/chirp/drivers/alinco.py
@@ -99,7 +99,7 @@ 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)
@@ -156,7 +156,7 @@ class AlincoStyleRadio(chirp_common.CloneModeRadio):
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)
@@ -426,7 +426,7 @@ class DR135Radio(DRx35Radio):
_model = b"DR135"
_memsize = 4096
- _range = [(118000000, 173000000)]
+ _range = [(118000000, 174000000)]
@classmethod
def match_model(cls, filedata, filename):
@@ -541,7 +541,7 @@ 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')
@@ -649,7 +649,7 @@ 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")
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 c09af07..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
@@ -966,6 +967,7 @@ class AnyTone778UVBase(chirp_common.CloneModeRadio,
_mem.name = mem.name.ljust(self.NAME_LENGTH)[:self.NAME_LENGTH]
# Set duplex bitfields
+ _mem.tx_off = 0
if mem.duplex == '+':
_mem.duplex = DUPLEX_POSSPLIT
elif mem.duplex == '-':
@@ -975,15 +977,13 @@ class AnyTone778UVBase(chirp_common.CloneModeRadio,
elif mem.duplex == 'split':
# TODO: this is an unverified punt!
_mem.duplex = DUPLEX_ODDSPLIT
+ elif mem.duplex == 'off':
+ # handle tx off
+ _mem.tx_off = 1
else:
LOG.error('%s: set_mem: unhandled duplex: %s' %
(mem.name, mem.duplex))
- # handle tx off
- _mem.tx_off = 0
- if mem.duplex == 'off':
- _mem.tx_off = 1
-
# Set the channel width - remember we promote 20 kHz channels to FM
# on import
# , so don't handle them here
@@ -1075,7 +1075,7 @@ class AnyTone778UVBase(chirp_common.CloneModeRadio,
else:
LOG.error('%s: unhandled cross RX mode: %s' % (
mem.name, mem.cross_mode))
- else:
+ elif mem.tmode:
LOG.error('%s: Unhandled tmode/cross %s/%s.' %
(mem.name, mem.tmode, mem.cross_mode))
LOG.debug('%s: tmode=%s, cross=%s, rtone=%f, ctone=%f' % (
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..d4024a6 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])
@@ -1127,7 +1121,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)
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..44747ff
--- /dev/null
+++ b/chirp/drivers/ar8200.py
@@ -0,0 +1,1695 @@
+# 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':
+ mode = [mode[1] for mode in self._MODES
+ if mode[0] == memory.extra['am']][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':
+ mode = [mode[1] for mode in self._MODES
+ if mode[0] == memory.extra['am']][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':
+ mode = [mode[1] for mode in self._MODES
+ if mode[0] == memory.extra['am']][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 953ce6b..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):
@@ -434,21 +436,6 @@ def _upload(radio):
radio.status_fn(status)
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
-
-
def bcd_decode_freq(bytes):
real_freq = 0
for byte in bytes:
@@ -544,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]
@@ -567,8 +554,8 @@ class BaofengCommonHT(chirp_common.CloneModeRadio,
# TX freq set
offset = (int(_mem.txfreq) * 10) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.txfreq) * 10):
+ 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:
diff --git a/chirp/drivers/baofeng_digital.py b/chirp/drivers/baofeng_digital.py
index 39eba04..89614f9 100644
--- a/chirp/drivers/baofeng_digital.py
+++ b/chirp/drivers/baofeng_digital.py
@@ -484,3 +484,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_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 65b9955..3aa5819 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
@@ -788,61 +806,67 @@ 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)
+
+ KEY_SETTINGS = [
+ ("_has_skey1_short", "settings.key1short", "Skey1 Short",
+ "key1short", apply_key1short),
+ ("_has_skey1_long", "settings.key1long", "Skey1 Long",
+ "key1long", apply_key1long),
+ ("_has_skey2_short", "settings.key2short", "Skey2 Short",
+ "key2short", apply_key2short),
+ ("_has_skey2_long", "settings.key2long", "Skey2 Long",
+ "key2long", apply_key2long),
+ ]
+
+ for flag, path, label, attr, apply_cb 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_apply_callback(apply_cb, _mem.settings)
+ basic.append(rs)
if self._has_skey_disable:
rs = RadioSetting("settings.skdisable", "Side Key Disable",
@@ -919,6 +943,12 @@ 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))
+ basic.append(rs)
+
rs = RadioSetting("settings.fmenable", "Disable FM radio",
RadioSettingValueBoolean(_mem.settings.fmenable))
basic.append(rs)
@@ -1256,12 +1286,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')))
@@ -1308,8 +1339,8 @@ class UV17Pro(bfc.BaofengCommonHT):
else:
offset = (int(_mem.txfreq) * 10) - freq
if offset != 0:
- if bfc._split(self.get_features(), freq, int(
- _mem.txfreq) * 10):
+ if chirp_common.is_split(self.get_features().valid_bands,
+ freq, int(_mem.txfreq) * 10):
duplex = "split"
offset = int(_mem.txfreq) * 10
elif offset < 0:
@@ -1346,7 +1377,7 @@ 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")
@@ -1366,6 +1397,13 @@ class UV17Pro(bfc.BaofengCommonHT):
current_index=scode))
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(
@@ -1386,13 +1424,6 @@ class UV17Pro(bfc.BaofengCommonHT):
RadioSettingValueBoolean(_mem.fhss))
mem.extra.append(rs)
- if self.MODEL == "K6":
- rs = RadioSetting("scramble", "Scramble",
- RadioSettingValueList(
- self.SCRAMBLE_LIST,
- current_index=_mem.scramble))
- mem.extra.append(rs)
-
mem.name = str(name).replace('\xFF', ' ').replace('\x00', ' ').rstrip()
def _get_raw_memory(self, number):
@@ -1506,7 +1537,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 +1563,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 +1701,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 +1748,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 +1775,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 +1800,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 +1816,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 +1836,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 +1849,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 +1926,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 +2054,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 +2358,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 +2388,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 {
@@ -2228,3 +2502,43 @@ class UV5RMini(UV17Pro):
rs = RadioSetting("downcode.code", "Down Code", val)
rs.set_apply_callback(self.apply_code, self._memobj.downcode, 16)
dtmfe.append(rs)
+
+
+@directory.register
+class 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..6c9a6aa 100644
--- a/chirp/drivers/boblov_x3plus.py
+++ b/chirp/drivers/boblov_x3plus.py
@@ -526,7 +526,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 bc9b75c..b7dc55a 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
@@ -642,21 +595,6 @@ def _decode_ranges(low, high):
return (ilow, ihigh)
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
-
-
class BTechMobileCommon(chirp_common.CloneModeRadio,
chirp_common.ExperimentalRadio):
"""BTECH's UV-5001 and alike radios"""
@@ -680,7 +618,6 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
_upper = 199
_magic = MSTRING
_fileid = []
- _id2 = False
btech3 = False
_gmrs = False
@@ -858,8 +795,8 @@ class BTechMobileCommon(chirp_common.CloneModeRadio,
# TX freq set
offset = (int(_mem.txfreq) * 10) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.txfreq) * 10):
+ 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:
@@ -897,15 +834,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
@@ -914,18 +861,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 = []
@@ -1130,15 +1087,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":
@@ -1155,6 +1122,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":
@@ -1168,20 +1139,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":
@@ -1209,26 +1199,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 \
@@ -1241,43 +1248,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"]:
@@ -1294,6 +1326,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)
@@ -1340,6 +1375,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
@@ -1348,6 +1386,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:
@@ -1355,12 +1395,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:
@@ -1368,12 +1413,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:
@@ -1381,12 +1431,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:
@@ -1394,18 +1449,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:
@@ -1413,6 +1477,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:
@@ -1549,26 +1616,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:
@@ -1587,6 +1669,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:
@@ -1594,6 +1680,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)
@@ -1603,17 +1694,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:
@@ -1621,12 +1724,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":
@@ -1645,6 +1756,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:
@@ -1695,40 +1809,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
@@ -1742,11 +1880,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"):
@@ -1786,12 +1930,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:
@@ -1811,12 +1961,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:
@@ -1835,6 +1991,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
@@ -1842,69 +2001,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):
@@ -1963,6 +2161,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)
@@ -1973,6 +2173,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)
@@ -1982,6 +2184,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)
@@ -1993,6 +2198,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)
@@ -2000,17 +2208,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:
@@ -2018,6 +2238,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):
@@ -2039,6 +2263,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)
@@ -2047,6 +2275,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)
@@ -2055,6 +2287,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)
@@ -2065,6 +2301,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:
@@ -2072,6 +2312,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)
@@ -2079,6 +2323,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)
@@ -2086,40 +2334,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:
@@ -2127,38 +2396,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:
@@ -2166,6 +2456,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:
@@ -2173,22 +2466,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:
@@ -2196,42 +2502,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:
@@ -2239,12 +2570,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:
@@ -2282,6 +2619,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)
@@ -2293,6 +2633,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)
@@ -2311,12 +2654,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:
@@ -2328,6 +2678,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:
@@ -2339,6 +2692,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):
@@ -2369,6 +2725,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
@@ -2377,6 +2736,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(
@@ -2384,6 +2746,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)
@@ -2392,30 +2757,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(
@@ -2423,6 +2803,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)
@@ -2431,30 +2814,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(
@@ -2462,6 +2860,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)
@@ -2471,6 +2872,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)
@@ -2480,6 +2883,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)
@@ -2489,6 +2895,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)
@@ -2498,6 +2907,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)
@@ -2507,6 +2919,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)
@@ -2528,6 +2943,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)
@@ -2542,6 +2960,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)
@@ -2556,6 +2977,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:
@@ -2567,6 +2991,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:
@@ -2578,6 +3005,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
@@ -2613,6 +3043,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:
@@ -2630,6 +3063,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)
@@ -2648,6 +3084,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)
@@ -2713,6 +3153,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)
@@ -2721,6 +3164,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)
@@ -2729,6 +3175,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)
@@ -2737,6 +3186,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)
@@ -2747,6 +3199,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(
@@ -2754,6 +3209,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(
@@ -2761,6 +3219,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(
@@ -2768,6 +3229,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(
@@ -2775,6 +3239,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(
@@ -2782,6 +3249,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
@@ -2793,6 +3263,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...")
@@ -2806,6 +3279,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(
@@ -2821,6 +3297,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.")
@@ -2835,6 +3314,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.")
@@ -2851,6 +3333,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.")
@@ -2865,6 +3350,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.")
@@ -2887,6 +3375,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
@@ -2900,6 +3391,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
@@ -2913,6 +3407,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):
@@ -2944,6 +3441,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)
@@ -2954,6 +3454,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)
@@ -2970,6 +3473,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.")
@@ -3012,6 +3518,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:
@@ -3031,6 +3540,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:
@@ -3051,6 +3563,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:
@@ -3076,6 +3591,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 d0e9632..05ae55d 100644
--- a/chirp/drivers/ft1d.py
+++ b/chirp/drivers/ft1d.py
@@ -1,6 +1,6 @@
# Copyright 2010 Dan Smith <dsmith@danplanet.com>
# Copyright 2014 Angus Ainslie <angus@akkea.ca>
-# Copyright 2023 Declan Rieb <WD5EQY@arrl.net>
+# Copyright 2023,2025 Declan Rieb <WD5EQY@arrl.net>
# Sections of digital settings applied from ft70.py, thus
# Copyright 2017 Nicolas Pike <nick@zbm2.com>
#
@@ -27,13 +27,14 @@ from chirp import memmap
from chirp.settings import RadioSettingGroup, RadioSetting, RadioSettings, \
RadioSettingValueInteger, RadioSettingValueString, \
RadioSettingValueList, RadioSettingValueBoolean, \
- InvalidValueError
+ InvalidValueError, RadioSettingSubGroup
from chirp import util
LOG = logging.getLogger(__name__)
-MEM_SETTINGS_FORMAT = """
-#seekto 0x047e;
+SETTINGS_FORMAT = """
+// Settings
+#seekto 0x047E;
struct {
u8 unknown1;
u8 flag;
@@ -43,18 +44,41 @@ struct {
} message;
} opening_message;
-#seekto 0x049a;
+// Settings
+#seekto 0x049A;
struct {
u8 vfo_a;
u8 vfo_b;
} squelch;
-#seekto 0x04c1;
+// GM / Digital
+#seekto 0x04BA;
struct {
- u8 beep;
-} beep_select;
+ u8 unknown:3,
+ scan_resume:5; // 52 SCN.RSM
+ u8 unknown1:3,
+ dw_resume_interval:5; // 22 DW RSM
+ u8 unknown2;
+ u8 unknown3:3,
+ apo:5; // 02 APO
+ u8 unknown4:6,
+ gm_ring:2; // 24 GM RNG
+ u8 temp_cf; // Placeholder as not found
+ } first_settings;
-#seekto 0x04ce;
+// GM / Digital
+// already at 0x04c0;
+// Caution: overloaded at 04c1! only location in FORMATs.
+// Old = beep_select.beep, new is beep_settings.beep_select.
+struct {
+ u8 unknown1:5,
+ beep_level:3; // 05 BEP.LVL
+ u8 unknown2:6,
+ beep_select:2; // 04 BEEP
+ } beep_settings;
+
+// Settings
+#seekto 0x04CE;
struct {
u8 lcd_dimmer; // 14 DIMMER
u8 dtmf_delay; // 18 DT DLY
@@ -102,12 +126,14 @@ struct {
dw_rt:1; // 23 DW RVT;
} scan_settings;
-#seekto 0x54a;
+// Settings
+#seekto 0x054A;
struct {
u16 in_use;
} bank_used[24];
-#seekto 0x064a;
+// Settings
+#seekto 0x064A;
struct {
u8 unknown0[4];
u8 frequency_band;
@@ -151,33 +177,34 @@ struct {
u8 checksum;
} vfo_info[6];
+// Settings
#seekto 0x%(dtmadd)04X; // FT-1D:0e4a, FT2D:094a
struct {
u8 memory[16];
} dtmf[10];
+// Settings
#seekto 0x0EFE;
struct {
u8 unknown[2];
u8 name[16];
} bank_info[24];
-
-#seekto 0x154a;
-// These "channels" seem to actually be a structure:
-// first five bits are flags
-// 0 Unused (1=entry is unused)
-// 1 SW Broadcast
-// 2 VHF Marine
-// 3 WX (weather)
-// 4 ? a mode? ?
-// 11 bits of index into frequency tables
-//
-struct {
- u16 channel[100];
-} bank_members[24];
"""
MEM_FORMAT = """
+// This FORMAT is used in FT-xD, FTM-3200D and FTM-7250D
+// It relies on defined integer for memnum (number of memories)
+// Memory: memory-flags structure used in Yaesu FT-xD, et. al.
+struct flagslot {
+ u8 nosubvfo:1,
+ unknown:3,
+ pskip:1,
+ skip:1,
+ used:1,
+ valid:1;
+};
+
+// Memory: memory structure used in FT-xD
struct memslot {
u8 unknown0:2,
mode_alt:1, // mode for FTM-3200D
@@ -204,29 +231,42 @@ struct memslot {
automode:1,
unknown9:3;
};
-#seekto 0x2D4A;
-struct memslot memory[%(memnum)d];
-struct memslot Skip[99];
-struct memslot PMS[100];
-#seekto 0x10ca;
+
+// Memory n.b., Unneeded for FTM-3200 and FTM-7250, but needs memslot
+#seekto 0x10CA;
struct memslot Home[11];
-struct flagslot {
- u8 nosubvfo:1,
- unknown:3,
- pskip:1,
- skip:1,
- used:1,
- valid:1;
-};
-#seekto 0x280A;
+// Settings n.b., these are unused in FTM-3200 and FTM-7250,
+// But are needed for spacing!
+#seekto 0x154A;
+// These "channels" seem to actually be a structure:
+// first five bits are flags
+// 0 Unused (1=entry is unused)
+// 1 SW Broadcast
+// 2 VHF Marine
+// 3 WX (weather)
+// 4 ? a mode? ?
+// 11 bits of index into frequency tables
+//
+struct {
+ u16 channel[100];
+} bank_members[24];
+
+// Memory: had unneeded 0x280A
struct flagslot flag[%(memnum)d];
struct flagslot flagskp[99];
struct flagslot flagPMS[100];
+
+// Memory
+#seekto 0x2D4A;
+struct memslot memory[%(memnum)d];
+struct memslot Skip[99];
+struct memslot PMS[100];
"""
-MEM_APRS_FORMAT = """
-#seekto 0xbeca;
+DIGITAL_FORMAT = """
+// APRS
+#seekto 0xBECA;
struct {
u8 rx_baud;
u8 custom_symbol;
@@ -344,11 +384,75 @@ struct {
vibrate_bln:6;
} aprs;
-#seekto 0xc26a;
+// APRS
+#seekto 0xC26A;
struct {
char padded_string[60];
} aprs_beacon_status_txt[5];
+// GM / Digital
+#seekto 0xCED0;
+struct {
+ char callsign[10]; // 63 MYCALL
+ u16 charset; // character set ID
+ } my_call;
+
+// GM / Digital
+#seekto 0xCF30;
+struct {
+ u8 unknown0;
+ u8 unknown1;
+ u8 unknown2;
+ u8 unknown3;
+ u8 unknown4;
+ u8 unknown5;
+ u8 unknown6;
+ u8 digital_popup; // 15 DIG.POP
+ } digital_settings_more;
+
+// GM / Digital
+#seekto 0xCF7C;
+struct {
+ u8 unknown0:6,
+ ams_tx_mode:2; // AMS TX Mode
+ u8 unknown1;
+ u8 unknown2:7,
+ standby_beep:1; // 07 BEP.STB
+ u8 unknown3;
+ u8 unknown4:6,
+ gm_ring:2; // 24 GM RNG
+ u8 unknown5;
+ u8 rx_dg_id; // RX DG-ID
+ u8 tx_dg_id; // TX DG-ID
+ u8 unknown6:7,
+ vw_mode:1; // 16 DIG VW
+ u8 unknown7;
+ } digital_settings;
+
+// Backtrack
+#seekto 0xDF06;
+struct {
+ u8 status; // 01 full 08 empty
+ u8 reserved0; // 00
+ bbcd year; // 17
+ bbcd mon; // 06
+ bbcd day; // 01
+ u8 reserved1; // 06
+ bbcd hour; // 21
+ bbcd min; // xx
+ u8 reserved2; // 00
+ u8 reserved3; // 00
+ char NShemi[1];
+ char lat[3];
+ char lat_min[2];
+ char lat_dec_sec[4];
+ char WEhemi[1];
+ char lon[3];
+ char lon_min[2];
+ char lon_dec_sec[4];
+} backtrack[3];
+
+// APRS
#seekto 0xFECA;
struct {
bbcd date[3];
@@ -371,7 +475,7 @@ struct {
u16 unknown10;
} aprs_beacon_meta[60];
-#seekto 0x1064A;
+// APRS Had unneeded 0x10641
struct {
char dst_callsign[9];
char path[30];
@@ -380,7 +484,8 @@ struct {
char body[134];
} aprs_beacon_pkt[60];
-#seekto 0x137c4;
+// APRS
+#seekto 0x137C4;
struct {
u8 flag;
char dst_callsign[6];
@@ -388,110 +493,15 @@ struct {
char path_and_body[66];
u8 unknown[70];
} aprs_message_pkt[60];
-"""
-
-MEM_BACKTRACK_FORMAT = """
-#seekto 0xdf06;
-struct {
- u8 status; // 01 full 08 empty
- u8 reserved0; // 00
- bbcd year; // 17
- bbcd mon; // 06
- bbcd day; // 01
- u8 reserved1; // 06
- bbcd hour; // 21
- bbcd min; // xx
- u8 reserved2; // 00
- u8 reserved3; // 00
- char NShemi[1];
- char lat[3];
- char lat_min[2];
- char lat_dec_sec[4];
- char WEhemi[1];
- char lon[3];
- char lon_min[2];
- char lon_dec_sec[4];
-} backtrack[3];
-"""
-
-MEM_GM_FORMAT = """
-#seekto 0x04ba;
-struct {
- u8 unknown:3,
- scan_resume:5; // 52 SCN.RSM
- u8 unknown1:3,
- dw_resume_interval:5; // 22 DW RSM
- u8 unknown2;
- u8 unknown3:3,
- apo:5; // 02 APO
- u8 unknown4:6,
- gm_ring:2; // 24 GM RNG
- u8 temp_cf; // Placeholder as not found
- } first_settings;
-
-#seekto 0x04c0;
-struct {
- u8 unknown1:5,
- beep_level:3; // 05 BEP.LVL
- u8 unknown2:6,
- beep_select:2; // 04 BEEP
- } beep_settings;
-
-#seekto 0x04ed;
-struct {
- u8 unknown1:1,
- unknown2:1,
- unknown3:1,
- unknown4:1,
- unknown5:1,
- unknown6:1,
- unknown7:1,
- unknown8:1;
- } test_bit_field;
-
-#seekto 0x0ced0;
-struct {
- char callsign[10]; // 63 MYCALL
- u16 charset; // character set ID
- } my_call;
-
-#seekto 0xCF30;
-struct {
- u8 unknown0;
- u8 unknown1;
- u8 unknown2;
- u8 unknown3;
- u8 unknown4;
- u8 unknown5;
- u8 unknown6;
- u8 digital_popup; // 15 DIG.POP
- } digital_settings_more;
-
-#seekto 0xCF7C;
-struct {
- u8 unknown0:6,
- ams_tx_mode:2; // AMS TX Mode
- u8 unknown1;
- u8 unknown2:7,
- standby_beep:1; // 07 BEP.STB
- u8 unknown3;
- u8 unknown4:6,
- gm_ring:2; // 24 GM RNG
- u8 unknown5;
- u8 rx_dg_id; // RX DG-ID
- u8 tx_dg_id; // TX DG-ID
- u8 unknown6:7,
- vw_mode:1; // 16 DIG VW
- u8 unknown7;
- } digital_settings;
-
-#seekto 0x1d6d3;
+// GM / Digital
+#seekto 0x1D6D3;
struct {
char message[32];
} GM[10];
-#seekto 0x1ddca;
+// GM / Digital
+#seekto 0x1DDCA;
struct {
struct {
char name[16];
@@ -506,7 +516,8 @@ struct {
} WiresX_settings;
"""
-MEM_CHECKSUM_FORMAT = """
+CHECKSUM_FORMAT = """
+// Checksum
#seekto 0x1FDC9;
u8 checksum;
"""
@@ -903,9 +914,8 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
return rp
def process_mmap(self):
- mem_format = MEM_SETTINGS_FORMAT + MEM_FORMAT + MEM_APRS_FORMAT + \
- MEM_GM_FORMAT + MEM_BACKTRACK_FORMAT + MEM_CHECKSUM_FORMAT
- self._memobj = bitwise.parse(mem_format % self._mem_params, self._mmap)
+ _mf = SETTINGS_FORMAT + MEM_FORMAT + DIGITAL_FORMAT + CHECKSUM_FORMAT
+ self._memobj = bitwise.parse(_mf % self._mem_params, self._mmap)
def get_features(self):
rf = chirp_common.RadioFeatures()
@@ -939,8 +949,9 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
yaesu_clone.YaesuChecksum(0x0000, 0x1FDC9)]
@staticmethod
- def _add_ff_pad(val, length):
- return val.ljust(length, b"\xFF")[:length]
+ def _add_ff_pad(val: str, length: int) -> str:
+ _fill = b'\xff' if isinstance(val, bytes | bytearray) else '\xff'
+ return val.ljust(length, _fill)[:length]
@classmethod
def _strip_ff_pads(cls, messages):
@@ -1045,10 +1056,7 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
mem.offset = int(_mem.offset) * 1000
mem.rtone = mem.ctone = chirp_common.TONES[_mem.tone]
self._get_tmode(mem, _mem)
- if mem.duplex is None:
- mem.duplex = DUPLEX[""]
- else:
- mem.duplex = DUPLEX[_mem.duplex]
+ mem.duplex = DUPLEX[_mem.duplex] if _mem.duplex else ""
if mem.duplex == "split":
mem.offset = chirp_common.fix_rounded_step(mem.offset)
mem.mode = self._decode_mode(_mem)
@@ -1819,7 +1827,7 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
mycalle = RadioSettingValueString(0, 10, mycallstr, False,
charset=self._MYCALL_CHR_SET)
rs = RadioSetting('mycall.callsign',
- 'MYCALL (10 uppercase chars)', mycalle)
+ 'MYCALL', mycalle)
rs.set_apply_callback(self.apply_mycall, mycall)
menu.append(rs)
@@ -1907,66 +1915,37 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
# WiresX settings
wxc = self._memobj.WiresX_settings
- for i in range(0, 5):
- cname = "WiresX_settings.Category[%d].name" % (i + 1)
- c = ''
- for j in range(0, 16):
- s = wxc.Category[i].name[j]
- if int(s) != 0xff:
- c = c + str(s)
+ for i in range(5):
+ WXCmenu = RadioSettingSubGroup(
+ f"WiresX_settings.Category[{i}].RoomsPerCategory",
+ f"Category{i + 1} Rooms")
+ WXmenu.append(WXCmenu)
+
+ cname = f"WiresX_settings.Category[{i}].name"
+ c = str(wxc.Category[i].name).rstrip('\xff').ljust(16)
val = RadioSettingValueString(0, 16, c)
- rs = RadioSetting(cname, "Category %d" % (i+1), val)
- rs.set_apply_callback(self.apply_WiresX_category,
- wxc.Category[i].name)
- WXmenu.append(rs)
+ rs = RadioSetting(cname, f"Category {i+1: 2d} Name", val)
+ WXCmenu.append(rs)
r = wxc.RoomsPerCategory[i]
- rn = False
- for j in range(0, 20):
- idn = "0"
- if int(r.Rooms[j].ID[1]) != 0xff:
- idn = r.Rooms[j].ID
- rn = False
- elif rn:
- break
- elif j > 0:
- rn = True
- val = RadioSettingValueInteger(0, 99999, int(str(idn)))
- vname = "WiresX_settings.RoomsperCategory%s" \
- "Rooms[%d].ID" % (i, j)
- rs = RadioSetting(vname, " Room ID%2s (5 numerals)" %
- (j+1), val)
- rs.set_apply_callback(self.apply_WiresX_roomid,
- r.Rooms[j])
- WXmenu.append(rs)
- cn = ''
- for l in range(0, 16):
- s = r.Rooms[j].name[l]
- if int(s) != 0xff:
- cn = cn + str(s)
- val = RadioSettingValueString(0, 16, str(cn))
- cname = "WiresX_settings.RoomsperCategory%s" \
- "Rooms[%d].name" % (i, j)
- rs = RadioSetting(cname, " Room Name%2s (16 chars)" %
- (j+1), val)
- rs.set_apply_callback(self.apply_WiresX_roomname,
- r.Rooms[j])
- WXmenu.append(rs)
+ for j in range(20):
+ cn = str(r.Rooms[j].name).strip('\xff').ljust(16)
+ val = RadioSettingValueString(0, 16, cn)
+ cname = f"WiresX_settings.RoomsPerCategory[{i}]."\
+ f"Rooms[{j}].name"
+ dname = f"Category {i + 1} Room{j + 1: 02d}"
+ rs = RadioSetting(cname, dname + ' Designation', val)
+
+ WXCmenu.append(rs)
+ idn = str(r.Rooms[j].ID).strip('\xff').ljust(5)
+ val = RadioSettingValueString(0, 5, idn)
+ vname = f"WiresX_settings.RoomsPerCategory[{i}].Rooms[{j}].ID"
+ rs = RadioSetting(vname, dname + " YSF Number",
+ val)
+ WXCmenu.append(rs)
pass
return topmenu
- def apply_WiresX_category(cls, setting, obj):
- val = setting.value.get_value()
- setattr(obj, "name", val)
-
- def apply_WiresX_roomid(self, setting, obj):
- val = setting.value.get_value()
- obj.ID = self.zero_pad(val, 5)
-
- def apply_WiresX_roomname(cls, setting, obj):
- val = setting.value.get_value()
- obj.name = str(val)
-
def _get_dtmf_settings(self):
menu = RadioSettingGroup("dtmf_settings", "DTMF")
dtmf = self._memobj.scan_settings
@@ -2032,12 +2011,12 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
rs = RadioSetting("scan_settings.lamp", "Lamp", val)
menu.append(rs)
- beep_select = self._memobj.beep_select
+ beep_select = self._memobj.beep_settings.beep_select
val = RadioSettingValueList(
self._BEEP_SELECT,
- current_index=beep_select.beep)
- rs = RadioSetting("beep_select.beep", "Beep Select", val)
+ current_index=beep_select)
+ rs = RadioSetting("beep_settings.beep_select", "Beep Select", val)
menu.append(rs)
opening_message = self._memobj.opening_message
@@ -2054,7 +2033,7 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
return menu
- def _decode_opening_message(self, opening_message):
+ def _decode_opening_message(self, opening_message) -> RadioSetting:
msg = ""
for i in opening_message.message.padded_yaesu:
if i == 0xFF:
@@ -2409,7 +2388,7 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
def apply_ff_padded_string(cls, setting, obj):
# FF pad.
val = setting.value.get_value()
- max_len = getattr(obj, "padded_string").size() / 8
+ max_len = getattr(obj, "padded_string").size() // 8
val = str(val).rstrip()
setattr(obj, "padded_string", cls._add_ff_pad(val, max_len))
@@ -2463,13 +2442,13 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
LOG.error("Setting %s is not in the memory map: %s" %
(element.get_name(), e))
except Exception:
- LOG.debug(element.get_name())
+ LOG.debug(f'Trouble setting "{element.get_name()}"')
raise
def apply_ff_padded_yaesu(cls, setting, obj):
# FF pad yaesus custom string format.
rawval = setting.value.get_value()
- max_len = getattr(obj, "padded_yaesu").size() / 8
+ max_len = getattr(obj, "padded_yaesu").size() // 8
rawval = str(rawval).rstrip()
val = [CHARSET.index(x) for x in rawval]
for x in range(len(val), max_len):
@@ -2518,37 +2497,37 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio):
def apply_bt_lat(cls, setting, obj):
val = setting.value.get_value()
- val = cls.backtrack_zero_pad(val, 3)
+ val = cls.zero_pad(val, 3)
setattr(obj, "lat", val)
def apply_bt_lat_min(cls, setting, obj):
val = setting.value.get_value()
- val = cls.backtrack_zero_pad(val, 2)
+ val = cls.zero_pad(val, 2)
setattr(obj, "lat_min", val)
def apply_bt_lat_dec_sec(cls, setting, obj):
val = setting.value.get_value()
- val = cls.backtrack_zero_pad(val, 4)
+ val = cls.zero_pad(val, 4)
setattr(obj, "lat_dec_sec", val)
def apply_bt_lon(cls, setting, obj):
val = setting.value.get_value()
- val = cls.backtrack_zero_pad(val, 3)
+ val = cls.zero_pad(val, 3)
setattr(obj, "lon", val)
def apply_bt_lon_min(cls, setting, obj):
val = setting.value.get_value()
- val = cls.backtrack_zero_pad(val, 2)
+ val = cls.zero_pad(val, 2)
setattr(obj, "lon_min", val)
def apply_bt_lon_dec_sec(cls, setting, obj):
val = setting.value.get_value()
- val = cls.backtrack_zero_pad(val, 4)
+ val = cls.zero_pad(val, 4)
setattr(obj, "lon_dec_sec", val)
diff --git a/chirp/drivers/ft4.py b/chirp/drivers/ft4.py
index 6b463ff..56c276f 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,9 +277,17 @@ 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()
+ raise errors.RadioError("No response from radio")
+ if len(response) != response_len:
+ raise errors.RadioError("Incomplete response from radio")
else:
response = b""
ack = pipe.read(1)
+ if not ack:
+ raise errors.RadioError("No response from radio")
if ack != b'\x06':
if retry < 5:
LOG.debug("retry: " + str(retry))
@@ -295,8 +308,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)
@@ -765,6 +780,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 +790,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)
@@ -1220,6 +1239,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)
diff --git a/chirp/drivers/ft450d.py b/chirp/drivers/ft450d.py
index 2f96ccf..2550b04 100644
--- a/chirp/drivers/ft450d.py
+++ b/chirp/drivers/ft450d.py
@@ -457,6 +457,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 +568,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 +649,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 +724,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 +768,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 +785,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.")
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..0c2c5eb 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)
diff --git a/chirp/drivers/ft7800.py b/chirp/drivers/ft7800.py
index 750e2c5..c446b1a 100644
--- a/chirp/drivers/ft7800.py
+++ b/chirp/drivers/ft7800.py
@@ -21,7 +21,7 @@ from chirp.drivers import yaesu_clone
from chirp import chirp_common, memmap, directory, bitwise, errors
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueList, RadioSettingValueBoolean, \
- RadioSettingValueString, RadioSettings
+ RadioSettingValueString, RadioSettings, RadioSettingValueFloat
from collections import defaultdict
@@ -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)
@@ -248,6 +259,30 @@ def set_freq(freq, obj, field):
return freq
+def _decode_chars(inarr):
+ LOG.debug("@_decode_chars, type: %s" % type(inarr))
+ LOG.debug(inarr)
+ outstr = ""
+ for i in inarr:
+ if i == 0xFF:
+ break
+ outstr += CHARSET[i & 0x7F]
+ return outstr.rstrip()
+
+
+def _encode_chars(instr, length=16):
+ LOG.debug("@_encode_chars, type: %s" % type(instr))
+ LOG.debug(instr)
+ outarr = []
+ instr = str(instr)
+ for i in range(length):
+ if i < len(instr):
+ outarr.append(CHARSET.index(instr[i]))
+ else:
+ outarr.append(0xFF)
+ return outarr
+
+
class FTx800Radio(yaesu_clone.YaesuCloneModeRadio):
"""Base class for FT-7800,7900,8800,8900 radios"""
BAUD_RATE = 9600
@@ -557,28 +592,6 @@ class FT7800Radio(FTx800Radio):
self._wipe_memory_banks(memory)
FTx800Radio.set_memory(self, memory)
- def _decode_chars(self, inarr):
- LOG.debug("@_decode_chars, type: %s" % type(inarr))
- LOG.debug(inarr)
- outstr = ""
- for i in inarr:
- if i == 0xFF:
- break
- outstr += CHARSET[i & 0x7F]
- return outstr.rstrip()
-
- def _encode_chars(self, instr, length=16):
- LOG.debug("@_encode_chars, type: %s" % type(instr))
- LOG.debug(instr)
- outarr = []
- instr = str(instr)
- for i in range(length):
- if i < len(instr):
- outarr.append(CHARSET.index(instr[i]))
- else:
- outarr.append(0xFF)
- return outarr
-
def get_settings(self):
_settings = self._memobj.settings
basic = RadioSettingGroup("basic", "Basic")
@@ -722,7 +735,7 @@ class FT7800Radio(FTx800Radio):
_arts_cwid = self._memobj.arts_cwid
cwid = RadioSettingValueString(
- 0, 16, self._decode_chars(_arts_cwid.get_value()))
+ 0, 16, _decode_chars(_arts_cwid.get_value()))
cwid.set_charset(CHARSET)
arts.append(RadioSetting("arts_cwid", "CW ID", cwid))
@@ -791,7 +804,7 @@ class FT7800Radio(FTx800Radio):
continue
if setting == "arts_cwid":
oldval = self._memobj.arts_cwid
- newval = self._encode_chars(newval.get_value(), 6)
+ newval = _encode_chars(newval.get_value(), 6)
self._memobj.arts_cwid = newval
continue
# normal settings
@@ -804,6 +817,60 @@ class FT7800Radio(FTx800Radio):
raise
+MEM_FORMAT_8800_COMMON = """
+#seekto 0x0009;
+struct {
+ bbcd vfo_left[3];
+} current_state;
+
+#seekto 0x0032;
+struct {
+ u8 ukn32;
+ u8 main:1,
+ ukn33_a:1,
+ ars:1,
+ ukn33_b:2,
+ vfo_band_edge:1,
+ ukn33_c:2;
+ u8 ukn34;
+ u8 ukn35;
+ u8 ukn36;
+ u8 ukn37;
+ u8 ukn38;
+ u8 ukn39;
+ u8 apo;
+ u8 ukn3b;
+ u8 ukn3c_a:3,
+ arts_mode:1,
+ ukn3c_b:2,
+ lockt:2;
+ u8 prog_p1;
+ u8 prog_p2;
+ u8 prog_p3;
+ u8 prog_p4;
+ u8 ukn41;
+ u8 ukn42;
+ u8 arts_cwid_enable:1,
+ lock:1,
+ ukn43:4,
+ backlight:2;
+ u8 ukn44a:2,
+ beep:1,
+ ukn44b:1,
+ key_mod:1,
+ ukn44c:3;
+ u8 ukn45a:3,
+ mute:2,
+ ukn45b:3;
+ u8 ukn46a:3,
+ mic:1,
+ ukn56b:4;
+ u8 ukn47;
+ u8 arts_cwid[6];
+
+} settings;
+"""
+
MEM_FORMAT_8800 = """
#seekto 0x%X;
struct {
@@ -896,6 +963,7 @@ class FT8800Radio(FTx800Radio):
rf.has_sub_devices = self.VARIANT == ""
rf.has_bank = True
rf.memory_bounds = (1, 512)
+ rf.has_settings = True
return rf
def get_sub_devices(self):
@@ -911,8 +979,10 @@ class FT8800Radio(FTx800Radio):
def process_mmap(self):
if not self._memstart:
+ self._memobj = bitwise.parse(MEM_FORMAT_8800_COMMON, self._mmap)
return
+ # Memory format for the sub devices
self._memobj = bitwise.parse(MEM_FORMAT_8800 % (self._memstart,
self._bankstart),
self._mmap)
@@ -926,7 +996,7 @@ class FT8800Radio(FTx800Radio):
val = 0
for i in _mem.name[2:6]:
val <<= 2
- val |= ((i & 0xC0) >> 6)
+ val |= (i & 0xC0) >> 6
return (val * 5) * 10000
@@ -970,13 +1040,159 @@ class FT8800Radio(FTx800Radio):
_mem.am = False
_mem.wid_nar = mem.mode == "NFM"
+ def get_settings(self):
+ _settings = self._memobj.settings
+ _cs = self._memobj.current_state
+ basic = RadioSettingGroup("basic", "Basic")
+ dtmf = RadioSettingGroup("dtmf", "DTMF")
+ arts = RadioSettingGroup("arts", "ARTS")
+ prog = RadioSettingGroup("prog", "Programmable Buttons")
+
+ top = RadioSettings(basic, dtmf, arts, prog)
+
+ basic.append(RadioSetting(
+ "apo", "APO time (hrs)",
+ RadioSettingValueList(
+ ["off"] + ["%0.1f" % (t / 60.0)
+ for t in range(30, 750, 30)],
+ current_index=_settings.apo)))
+
+ basic.append(RadioSetting("beep", "Beep: Key",
+ RadioSettingValueBoolean(_settings.beep)))
+ basic.append(RadioSetting("main", "Main: active device",
+ RadioSettingValueList(
+ ["Right", "Left"],
+ current_index=_settings.main)))
+ basic.append(RadioSetting("backlight", "Backlight",
+ RadioSettingValueList(
+ ["off", "dim 1", "dim 2", "dim 3"],
+ current_index=_settings.backlight)))
+ basic.append(RadioSetting("vfo_band_edge",
+ "BAND: VFO remain within band",
+ RadioSettingValueList(
+ ["BND. ON", "BND. OFF"],
+ current_index=_settings.vfo_band_edge)))
+ # 123.455 -> 0812345
+ # 999.9875 -> 1299998
+ # 155.2875 -> 1215528
+ # 108.0000 -> 0010800
+ basic.append(RadioSetting("vfo_left", "VFO: left",
+ RadioSettingValueFloat(
+ 0, 9**20, int(_cs.vfo_left) / 100)))
+ basic.append(RadioSetting("key_mod",
+ ("key functions for “right” band function "
+ "switches"),
+ RadioSettingValueList(
+ ["KEY1", "KEY2"],
+ current_index=_settings.key_mod)))
+ basic.append(RadioSetting("lock", "Lock: key/button",
+ RadioSettingValueBoolean(_settings.lock)))
+ basic.append(RadioSetting("lockt", "Lock: PTT",
+ RadioSettingValueList(
+ ["OFF", "BAND_R", "BAND_L", "BOTH"],
+ current_index=_settings.lockt)))
+ basic.append(RadioSetting("mute", "Audio Mute",
+ RadioSettingValueList(
+ ["OFF", "TX", "RX", "TX/RX"],
+ current_index=_settings.mute)))
+ basic.append(RadioSetting("mic", "Mic: type",
+ RadioSettingValueList(
+ ["MH-42", "MH-48"],
+ current_index=_settings.mic)))
+
+ # arts tab
+ arts.append(RadioSetting("arts_mode", "ARTS beep",
+ RadioSettingValueList(
+ ["off", "in range", "always"],
+ current_index=_settings.arts_mode)))
+ arts.append(RadioSetting("arts_cwid_enable", "CW ID Enable",
+ RadioSettingValueBoolean(
+ _settings.arts_cwid_enable)))
+ cwid = RadioSettingValueString(0, 16,
+ _decode_chars(
+ _settings.arts_cwid.get_value()))
+ cwid.set_charset(CHARSET)
+ arts.append(RadioSetting("arts_cwid", "CW ID", cwid))
+
+ # Prog buttons
+ opts = [
+ "Repeater",
+ "Priority",
+ "Low",
+ "Tone",
+ "MHz",
+ "Reverse",
+ "Home",
+ "Band",
+ "VFO/MR",
+ "Scan",
+ "Sql Off",
+ "TCall (1750Hz)",
+ ]
+
+ for n in range(1, 5):
+ prog.append(
+ RadioSetting(
+ f"prog_p{n}", f"P{n}",
+ RadioSettingValueList(
+ opts,
+ current_index=getattr(_settings, f"prog_p{n}") - 26)))
+
+ return top
+
+ 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:
+ _settings = self._memobj.settings
+ _cs = self._memobj.current_state
+ setting = element.get_name()
+ newval = element.value
+
+ if setting.startswith("vfo_"):
+ setattr(_cs, setting, newval * 100)
+ continue
+
+ if setting == "arts_cwid":
+ oldval = _settings.arts_cwid
+ newval = _encode_chars(newval.get_value(), 6)
+ _settings.arts_cwid = newval
+ continue
+
+ if setting.startswith("prog_p"):
+ setattr(_settings, setting, newval + 26)
+ continue
+
+ # normal settings
+ oldval = getattr(_settings, setting)
+
+ LOG.debug("Setting %s(%s) <= %s" % (setting, oldval, newval))
+
+ setattr(_settings, setting, newval)
+
+ except Exception:
+ LOG.debug(element.get_name())
+ raise
+
class FT8800RadioLeft(FT8800Radio):
"""Yaesu FT-8800 Left VFO subdevice"""
+
VARIANT = "Left"
_memstart = 0x0948
_bankstart = 0x4BC8
+ def get_features(self):
+ rf = super().get_features()
+ rf.has_settings = False
+ return rf
+
class FT8800RadioRight(FT8800Radio):
"""Yaesu FT-8800 Right VFO subdevice"""
@@ -984,6 +1200,11 @@ class FT8800RadioRight(FT8800Radio):
_memstart = 0x2948
_bankstart = 0x4BC8
+ def get_features(self):
+ rf = super().get_features()
+ rf.has_settings = False
+ return rf
+
MEM_FORMAT_8900 = """
#seekto 0x0708;
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/ftlx011.py b/chirp/drivers/ftlx011.py
deleted file mode 100644
index 3b1c1c2..0000000
--- a/chirp/drivers/ftlx011.py
+++ /dev/null
@@ -1,775 +0,0 @@
-# Copyright 2019 Pavel Milanes, CO7WT <pavelmc@gmail.com>
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 2 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-import logging
-import time
-
-from chirp import chirp_common, directory, memmap, errors, bitwise
-from chirp.settings import RadioSettingGroup, RadioSetting, \
- RadioSettingValueBoolean, RadioSettingValueList, \
- RadioSettings
-
-LOG = logging.getLogger(__name__)
-
-# SAMPLE MEM DUMP as sent from the radios
-
-# FTL-1011
-# 0x000000 52 f0 16 90 04 08 38 c0 00 00 00 01 00 00 00 ff |R.....8.........|
-# 0x000010 20 f1 00 20 00 00 00 20 04 47 25 04 47 25 00 00 | .. ... .G%.G%..|
-
-# FTL-2011
-# 0x000000: 50 90 21 40 04 80 fc 40 00 00 00 01 00 00 00 ff |P.!@...@........|
-# 0x000010: 20 f1 00 0b 00 00 00 0b 14 51 70 14 45 70 00 00 |.........Qp.Ep..|
-
-
-MEM_FORMAT = """
-u8 rid; // Radio Identification
-
-struct {
-u8 scan_time:4, // Scan timer per channel: 0-15 (5-80msec in 5msec steps)
- unknownA:4;
-bbcd if[2]; // Radio internal IF, depending on model (16.90, 21.40, 45.10, 47.90)
-u8 chcount; // how many channels are programmed
-u8 scan_resume:1, // Scan sesume: 0 = 0.5 seconds, 1 = Carrier
- priority_during_scan:1, // Priority during scan: 0 = enabled, 1 = disabled
- priority_speed:1, // Priority speed: 0 = slow, 1 = fast
- monitor:1, // Monitor: 0 = enabled, 1 = disabled
- off_hook:1, // Off hook: 0 = enabled, 1 = disabled
- home_channel:1, // Home Channel: 0 = Scan Start ch, 1 = Priority 1ch
- talk_back:1, // Talk Back: 0 = enabled, 1 = disabled
- tx_carrier_delay:1; // TX carrier delay: 1 = enabled, 0 = disabled
-u8 tot:4, // Time out timer: 16 values (0.0-7.5 in 0.5s step)
- tot_resume:2, // Time out timer resume: 3, 2, 1, 0 => 0s, 6s, 20s, 60s
- unknownB:2;
-u8 a_key:2, // A key function: resume: 0-3: Talkaround, High/Low, Call, Accessory
- unknownC:6;
-u8 pch1; // Priority channel 1
-u8 pch2; // Priority channel 1
-} settings;
-
-#seekto 0x010;
-struct {
- u8 notx:1, // 0 = Tx possible, 1 = Tx disabled
- empty:1, // 0 = channel enabled, 1 = channed empty
- tot:1, // 0 = tot disabled, 1 = tot enabled
- power:1, // 0 = high, 1 = low
- bclo_cw:1, // 0 = disabled, 1 = Busy Channel Lock out by carrier
- bclo_tone:1, // 0 = disabled, 1 = Busy Channel Lock out by tone (set rx tone)
- skip:1, // 0 = scan enabled, 1 = skip on scanning
- unknownA0:1;
- u8 chname;
- u8 rx_tone[2]; // empty value is \x00\x0B / disabled is \x00\x00
- u8 unknown4;
- u8 unknown5;
- u8 tx_tone[2]; // empty value is \x00\x0B / disabled is \x00\x00
- bbcd rx_freq[3]; // RX freq
- bbcd tx_freq[3]; // TX freq
- u8 unknownA[2];
-} memory[24];
-
-//#seekto 0x0190;
-char filename[11];
-
-#seekto 0x19C;
-u8 checksum;
-"""
-
-MEM_SIZE = 0x019C
-POWER_LEVELS = [chirp_common.PowerLevel("High", watts=50),
- chirp_common.PowerLevel("Low", watts=5)]
-DTCS_CODES = chirp_common.DTCS_CODES
-SKIP_VALUES = ["", "S"]
-LIST_BCL = ["OFF", "Carrier", "Tone"]
-LIST_SCAN_RESUME = ["0.5 seconds", "Carrier drop"]
-LIST_SCAN_TIME = ["%s ms" % x for x in range(5, 85, 5)]
-LIST_SCAN_P_SPEED = ["Slow", "Fast"]
-LIST_HOME_CHANNEL = ["Scan Start ch", "Priority 1ch"]
-LIST_TOT = ["Off"] + ["%.1f s" % (x/10.0) for x in range(5, 80, 5)]
-# 3, 2, 1, 0 => 0 s, 6 s, 20 s, 60 s
-LIST_TOT_RESUME = ["60 s", "20 s", "6 s", "0 s"]
-LIST_A_KEY = ["Talkaround", "High/Low", "Call", "Accessory"]
-LIST_PCH = [] # dynamic, as depends on channel list.
-# make a copy of the tones, is not funny to work with this directly
-TONES = list(chirp_common.TONES)
-# this old radios has not the full tone ranges in CST
-invalid_tones = (
- 69.3,
- 159.8,
- 165.5,
- 171.3,
- 177.3,
- 183.5,
- 189.9,
- 196.6,
- 199.5,
- 206.5,
- 229.1,
- 245.1)
-
-# remove invalid tones
-for tone in invalid_tones:
- try:
- TONES.remove(tone)
- except:
- pass
-
-
-def _set_serial(radio):
- """Set the serial protocol settings"""
- radio.pipe.timeout = 10
- radio.pipe.parity = "N"
- radio.pipe.baudrate = 9600
-
-
-def _checksum(data):
- """the radio block checksum algorithm"""
- cs = 0
- for byte in data:
- cs += byte
-
- return cs % 256
-
-
-def _update_cs(radio):
- """Update the checksum on the mmap"""
- payload = radio.get_mmap().get_packed()[:-1]
- cs = _checksum(payload)
- radio._mmap[MEM_SIZE - 1] = cs
-
-
-def _do_download(radio):
- """ The download function """
- # Get the whole 413 bytes (0x019D) bytes one at a time with plenty of time
- # to get to the user's pace
-
- # set serial discipline
- _set_serial(radio)
-
- # UI progress
- status = chirp_common.Status()
- status.cur = 0
- status.max = MEM_SIZE
- status.msg = " Press A to clone. "
- radio.status_fn(status)
-
- data = b""
- for i in range(0, MEM_SIZE):
- a = radio.pipe.read(1)
- if len(a) == 0:
- # error, no received data
- if len(data) != 0:
- # received some data, not the complete stream
- msg = "Just %02i bytes of the %02i received, try again." % \
- (len(data), MEM_SIZE)
- else:
- # timeout, please retry
- msg = "No data received, try again."
-
- raise errors.RadioError(msg)
-
- data += a
- # UI Update
- status.cur = len(data)
- radio.status_fn(status)
-
- if len(data) != MEM_SIZE:
- msg = "Incomplete data, we need %02i but got %02i bytes." % \
- (MEM_SIZE, len(data))
- raise errors.RadioError(msg)
-
- if data[-1] != _checksum(data[:-1]):
- msg = "Bad checksum, please try again."
- raise errors.RadioError(msg)
-
- return data
-
-
-def _do_upload(radio):
- """The upload function"""
- # set serial discipline
- _set_serial(radio)
-
- # UI progress
- status = chirp_common.Status()
-
- # 10 seconds timeout
- status.cur = 0
- status.max = 100
- status.msg = " Quick, press MON on the radio to start. "
- radio.status_fn(status)
-
- for byte in range(0, 100):
- status.cur = byte
- radio.status_fn(status)
- time.sleep(0.1)
-
- # real upload if user don't cancel the timeout
- status.cur = 0
- status.max = MEM_SIZE
- status.msg = " Cloning to radio... "
- radio.status_fn(status)
-
- # send data
- data = radio.get_mmap().get_packed()
-
- # this radio has a trick, the EEPROM is an ancient SPI one, so it needs
- # some time to write, so we send every byte and then allow
- # a 0.01 seg to complete the write from the MCU to the SPI EEPROM
- c = 0
- for byte in data:
- radio.pipe.write(byte)
- time.sleep(0.01)
-
- # UI Update
- status.cur = c
- radio.status_fn(status)
-
- # counter
- c = c + 1
-
-
-def _model_match(cls, data):
- """Use a experimental guess to determine if the radio you just
- downloaded or the img you opened is for this model"""
-
- # It's hard to tell when this radio is really this radio.
- # I use the first byte, that appears to be the ID and the IF settings
-
- radiod = [data[0], data[2:4]]
- return cls.finger == radiod
-
-
-def bcd_to_int(data):
- """Convert an array of bcdDataElement like \x12
- into an int like 12"""
- value = 0
- a = (data & 0xF0) >> 4
- b = data & 0x0F
- value = (a * 10) + b
- return value
-
-
-def int_to_bcd(data):
- """Convert a int like 94 to 0x94"""
- data, lsb = divmod(data, 10)
- data, msb = divmod(data, 10)
- res = (msb << 4) + lsb
- return res
-
-
-class ftlx011(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
- """Vertex FTL1011/2011/7011 4/8/12/24 channels"""
- VENDOR = "Vertex Standard"
- _memsize = MEM_SIZE
- _upper = 0
- _range = []
- finger = [] # two elements rid & IF
-
- @classmethod
- def get_prompts(cls):
- rp = chirp_common.RadioPrompts()
- rp.experimental = \
- ('This is a experimental driver, use it on your own risk.\n'
- '\n'
- 'This driver is just for the 4/12/24 channels variants of '
- 'these radios, 99 channel variants are not supported yet.\n'
- '\n'
- 'The 99 channel versions appears to use another mem layout.\n'
- )
- rp.pre_download = _(
- "Please follow this steps carefully:\n"
- "1 - Turn on your radio\n"
- "2 - Connect the interface cable to your radio.\n"
- "3 - Click the button on this window to start download\n"
- " (Radio will beep and led will flash)\n"
- "4 - Then press the \"A\" button in your radio to start"
- " cloning.\n"
- " (At the end radio will beep)\n")
- rp.pre_upload = _(
- "Please follow this steps carefully:\n"
- "1 - Turn on your radio\n"
- "2 - Connect the interface cable to your radio\n"
- "3 - Click the button on this window to start download\n"
- " (you may see another dialog, click ok)\n"
- "4 - Radio will beep and led will flash\n"
- "5 - You will get a 10 seconds timeout to press \"MON\" before\n"
- " data upload start\n"
- "6 - If all goes right radio will beep at end.\n"
- "After cloning remove the cable and power cycle your radio to\n"
- "get into normal mode.\n")
- return rp
-
- def get_features(self):
- """Return information about this radio's features"""
- rf = chirp_common.RadioFeatures()
- rf.has_settings = True
- rf.has_bank = False
- rf.has_tuning_step = False
- rf.has_name = False
- rf.has_offset = True
- rf.has_mode = True
- rf.has_dtcs = True
- rf.has_rx_dtcs = True
- rf.has_dtcs_polarity = False
- rf.has_ctone = True
- rf.has_cross = True
- rf.valid_duplexes = ["", "-", "+", "off"]
- rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
- rf.valid_cross_modes = [
- "Tone->Tone",
- "DTCS->DTCS",
- "DTCS->",
- "->DTCS"]
- rf.valid_dtcs_codes = DTCS_CODES
- rf.valid_skips = SKIP_VALUES
- rf.valid_modes = ["FM"]
- rf.valid_power_levels = POWER_LEVELS
- # rf.valid_tuning_steps = [5.0]
- rf.valid_bands = [self._range]
- rf.memory_bounds = (1, self._upper)
- return rf
-
- def sync_in(self):
- """Do a download of the radio eeprom"""
- try:
- data = _do_download(self)
- except Exception as e:
- raise errors.RadioError("Failed to communicate with radio:\n %s" % e)
-
- # match model
- if _model_match(self, data) is False:
- raise errors.RadioError("Incorrect radio model")
-
- self._mmap = memmap.MemoryMapbytes(data)
- self.process_mmap()
-
- # set the channel count from the radio eeprom
- self._upper = data[4]
-
- def sync_out(self):
- """Do an upload to the radio eeprom"""
- # update checksum
- _update_cs(self)
-
- # sanity check, match model
- data = self.get_mmap()
- if len(data) != MEM_SIZE:
- raise errors.RadioError("Wrong radio image? Size miss match.")
-
- if _model_match(self, data) is False:
- raise errors.RadioError("Wrong image? Fingerprint miss match")
-
- try:
- _do_upload(self)
- except Exception as e:
- msg = "Failed to communicate with radio:\n%s" % e
- raise errors.RadioError(msg)
-
- def process_mmap(self):
- """Process the memory object"""
- 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.memory[number])
-
- def _decode_tone(self, mem, rx=True):
- """Parse the tone data to decode from mem tones are encoded like this
- CTCS: mapped [0x80...0xa5] = [67.0...250.3]
- DTCS: mixed [0x88, 0x23] last is BCD and first is the 100 power - 88
-
- It return: ((''|DTCS|Tone), Value (None|###), None)"""
- mode = ""
- tone = None
-
- # get the tone depending of rx or tx
- if rx:
- t = mem.rx_tone
- else:
- t = mem.tx_tone
-
- tMSB = t[0]
- tLSB = t[1]
-
- # no tone at all
- if (tMSB == 0 and tLSB < 128):
- return ('', None, None)
-
- # extract the tone info
- if tMSB == 0x00:
- # CTCS
- mode = "Tone"
- try:
- tone = TONES[tLSB - 128]
- except IndexError:
- LOG.debug("Error decoding a CTCS tone")
- pass
- else:
- # DTCS
- mode = "DTCS"
- try:
- tone = ((tMSB - 0x88) * 100) + bcd_to_int(tLSB)
- except IndexError:
- LOG.debug("Error decoding a DTCS tone")
- pass
-
- return (mode, tone, None)
-
- def _encode_tone(self, mem, mode, value, pol, rx=True):
- """Parse the tone data to encode from UI to mem
- CTCS: mapped [0x80...0xa5] = [67.0...250.3]
- DTCS: mixed [0x88, 0x23] last is BCD and first is the 100 power - 88
- """
-
- # array to pass
- tone = [0x00, 0x00]
-
- # which mod
- if mode == "DTCS":
- tone[0] = int(value / 100) + 0x88
- tone[1] = int_to_bcd(value % 100)
-
- if mode == "Tone":
- # CTCS
- tone[1] = TONES.index(value) + 128
-
- # set it
- if rx:
- mem.rx_tone = tone
- else:
- mem.tx_tone = tone
-
- def get_memory(self, number):
- """Extract a memory object from the memory map"""
- # Get a low-level memory object mapped to the image
- _mem = self._memobj.memory[number - 1]
- # Create a high-level memory object to return to the UI
- mem = chirp_common.Memory()
- # number
- mem.number = number
-
- # empty
- if bool(_mem.empty) is True:
- mem.empty = True
- return mem
-
- # rx freq
- mem.freq = int(_mem.rx_freq) * 1000
-
- # power
- mem.power = POWER_LEVELS[int(_mem.power)]
-
- # checking if tx freq is disabled
- if bool(_mem.notx) is True:
- mem.duplex = "off"
- mem.offset = 0
- else:
- tx = int(_mem.tx_freq) * 1000
- if tx == mem.freq:
- mem.offset = 0
- mem.duplex = ""
- else:
- mem.duplex = mem.freq > tx and "-" or "+"
- mem.offset = abs(tx - mem.freq)
-
- # skip
- mem.skip = SKIP_VALUES[_mem.skip]
-
- # tone data
- rxtone = txtone = None
- rxtone = self._decode_tone(_mem)
- txtone = self._decode_tone(_mem, False)
- chirp_common.split_tone_decode(mem, txtone, rxtone)
-
- # this radio has a primitive mode to show the channel number on a 7-segment
- # two digit LCD, we will use channel number
- # we will use a trick to show the numbers < 10 with a space not a zero in front
- chname = int_to_bcd(mem.number)
- if mem.number < 10:
- # convert to F# as BCD
- chname = mem.number + 240
-
- _mem.chname = chname
-
- # Extra
- mem.extra = RadioSettingGroup("extra", "Extra")
-
- # bcl preparations: ["OFF", "Carrier", "Tone"]
- bcls = 0
- if _mem.bclo_cw:
- bcls = 1
- if _mem.bclo_tone:
- bcls = 2
-
- bcl = RadioSetting("bclo", "Busy channel lockout",
- RadioSettingValueList(LIST_BCL,
- current_index=bcls))
- mem.extra.append(bcl)
-
- # return mem
- return mem
-
- def set_memory(self, mem):
- """Store details about a high-level memory to the memory map
- This is called when a user edits a memory in the UI"""
- # Get a low-level memory object mapped to the image
- _mem = self._memobj.memory[mem.number - 1]
-
- # Empty memory
- _mem.empty = mem.empty
- if mem.empty:
- _mem.rx_freq = _mem.tx_freq = 0
- return
-
- # freq rx
- _mem.rx_freq = mem.freq / 1000
-
- # power, # default power level is high
- _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
-
- # freq tx
- if mem.duplex == "+":
- _mem.tx_freq = (mem.freq + mem.offset) / 1000
- elif mem.duplex == "-":
- _mem.tx_freq = (mem.freq - mem.offset) / 1000
- elif mem.duplex == "off":
- _mem.notx = 1
- _mem.tx_freq = _mem.rx_freq
- else:
- _mem.tx_freq = mem.freq / 1000
-
- # scan add property
- _mem.skip = SKIP_VALUES.index(mem.skip)
-
- # tone data
- ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
- chirp_common.split_tone_encode(mem)
-
- # validate tone data from here
- if rxmode == "Tone" and rxtone in invalid_tones:
- msg = "The tone %s Hz is not valid for this radio" % rxtone
- raise errors.UnsupportedToneError(msg)
-
- if txmode == "Tone" and txtone in invalid_tones:
- msg = "The tone %s Hz is not valid for this radio" % txtone
- raise errors.UnsupportedToneError(msg)
-
- if rxmode == "DTCS" and rxtone not in DTCS_CODES:
- msg = "The digital tone %s is not valid for this radio" % rxtone
- raise errors.UnsupportedToneError(msg)
-
- if txmode == "DTCS" and txtone not in DTCS_CODES:
- msg = "The digital tone %s is not valid for this radio" % txtone
- raise errors.UnsupportedToneError(msg)
-
- self._encode_tone(_mem, rxmode, rxtone, rxpol)
- self._encode_tone(_mem, txmode, txtone, txpol, False)
-
- # this radio has a primitive mode to show the channel number on a 7-segment
- # two digit LCD, we will use channel number
- # we will use a trick to show the numbers < 10 with a space not a zero in front
- chname = int_to_bcd(mem.number)
- if mem.number < 10:
- # convert to F# as BCD
- chname = mem.number + 240
-
- def _zero_settings():
- _mem.bclo_cw = 0
- _mem.bclo_tone = 0
-
- # extra settings
- if len(mem.extra) > 0:
- # there are setting, parse
- LOG.debug("Extra-Setting supplied. Setting them.")
- # Zero them all first so any not provided by model don't
- # stay set
- _zero_settings()
- for setting in mem.extra:
- if setting.get_name() == "bclo":
- sw = LIST_BCL.index(str(setting.value))
- if sw == 0:
- # empty
- _zero_settings()
- if sw == 1:
- # carrier
- _mem.bclo_cw = 1
- if sw == 2:
- # tone
- _mem.bclo_tone = 1
- # activate the tone
- _mem.rx_tone = [0x00, 0x80]
- else:
- # reset extra settings
- _zero_settings()
-
- _mem.chname = chname
-
- return mem
-
- def get_settings(self):
- _settings = self._memobj.settings
- basic = RadioSettingGroup("basic", "Basic Settings")
- group = RadioSettings(basic)
-
- # ## Basic Settings
- scanr = RadioSetting("scan_resume", "Scan resume by",
- RadioSettingValueList(
- LIST_SCAN_RESUME, current_index=_settings.scan_resume))
- basic.append(scanr)
-
- scant = RadioSetting("scan_time", "Scan time per channel",
- RadioSettingValueList(
- LIST_SCAN_TIME, current_index=_settings.scan_time))
- basic.append(scant)
-
- LIST_PCH = ["%s" % x for x in range(1, _settings.chcount + 1)]
- pch1 = RadioSetting("pch1", "Priority channel 1",
- RadioSettingValueList(
- LIST_PCH, current_index=_settings.pch1))
- basic.append(pch1)
-
- pch2 = RadioSetting("pch2", "Priority channel 2",
- RadioSettingValueList(
- LIST_PCH, current_index=_settings.pch2))
- basic.append(pch2)
-
- scanp = RadioSetting("priority_during_scan", "Disable priority during scan",
- RadioSettingValueBoolean(_settings.priority_during_scan))
- basic.append(scanp)
-
- scanps = RadioSetting("priority_speed", "Priority scan speed",
- RadioSettingValueList(
- LIST_SCAN_P_SPEED, current_index=_settings.priority_speed))
- basic.append(scanps)
-
- oh = RadioSetting("off_hook", "Off Hook", # inverted
- RadioSettingValueBoolean(not _settings.off_hook))
- basic.append(oh)
-
- tb = RadioSetting("talk_back", "Talk Back", # inverted
- RadioSettingValueBoolean(not _settings.talk_back))
- basic.append(tb)
-
- tot = RadioSetting("tot", "Time out timer",
- RadioSettingValueList(
- LIST_TOT, current_index=_settings.tot))
- basic.append(tot)
-
- totr = RadioSetting("tot_resume", "Time out timer resume guard",
- RadioSettingValueList(
- LIST_TOT_RESUME, current_index=_settings.tot_resume))
- basic.append(totr)
-
- ak = RadioSetting("a_key", "A Key function",
- RadioSettingValueList(
- LIST_A_KEY, current_index=_settings.a_key))
- basic.append(ak)
-
- monitor = RadioSetting("monitor", "Monitor", # inverted
- RadioSettingValueBoolean(not _settings.monitor))
- basic.append(monitor)
-
- homec = RadioSetting("home_channel", "Home Channel is",
- RadioSettingValueList(
- LIST_HOME_CHANNEL, current_index=_settings.home_channel))
- basic.append(homec)
-
- txd = RadioSetting("tx_carrier_delay", "Talk Back",
- RadioSettingValueBoolean(_settings.tx_carrier_delay))
- basic.append(txd)
-
- return group
-
- def set_settings(self, uisettings):
- _settings = self._memobj.settings
-
- for element in uisettings:
- if not isinstance(element, RadioSetting):
- self.set_settings(element)
- continue
- if not element.changed():
- continue
-
- try:
- name = element.get_name()
- value = element.value
-
- obj = getattr(_settings, name)
- if name in ["off_hook", "talk_back", "monitor"]:
- setattr(_settings, name, not value)
- else:
- setattr(_settings, name, value)
-
- LOG.debug("Setting %s: %s" % (name, value))
- except Exception:
- LOG.debug(element.get_name())
- raise
-
- @classmethod
- def match_model(cls, filedata, filename):
- match_size = False
- match_model = False
-
- # testing the file data size
- if len(filedata) == cls._memsize:
- match_size = True
-
- # testing the firmware fingerprint, this experimental
- try:
- match_model = _model_match(cls, filedata)
- except Exception:
- match_model = False
-
- return match_size and match_model
-
-
-@directory.register
-class ftl1011(ftlx011):
- """Vertex FTL-1011"""
- MODEL = "FTL-1011"
- _memsize = MEM_SIZE
- _upper = 4
- _range = [44000000, 56000000]
- finger = [b"\x52", b"\x16\x90"]
-
-
-@directory.register
-class ftl2011(ftlx011):
- """Vertex FTL-2011"""
- MODEL = "FTL-2011"
- _memsize = MEM_SIZE
- _upper = 24
- _range = [134000000, 174000000]
- finger = [b"\x50", b"\x21\x40"]
-
-
-@directory.register
-class ftl7011(ftlx011):
- """Vertex FTL-7011"""
- MODEL = "FTL-7011"
- _memsize = MEM_SIZE
- _upper = 24
- _range = [400000000, 512000000]
- finger = [b"\x54", b"\x47\x90"]
-
-
-@directory.register
-class ftl8011(ftlx011):
- """Vertex FTL-8011"""
- MODEL = "FTL-8011"
- _memsize = MEM_SIZE
- _upper = 24
- _range = [400000000, 512000000]
- finger = [b"\x5c", b"\x45\x10"]
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 ed1de4d..2d50a4e 100644
--- a/chirp/drivers/generic_csv.py
+++ b/chirp/drivers/generic_csv.py
@@ -84,9 +84,10 @@ class CSVRadio(chirp_common.FileBackedRadio):
"Comment": (str, "comment"),
}
- def _blank(self, setDefault=False):
+ def _blank(self, setDefault=False, max_memory=999):
self.errors = []
- self.memories = [chirp_common.Memory(i, True) for i in range(0, 1000)]
+ self.memories = [chirp_common.Memory(i, True)
+ for i in range(0, max_memory + 1)]
if (setDefault):
self.memories[0].empty = False
self.memories[0].freq = 146010000
@@ -96,7 +97,7 @@ class CSVRadio(chirp_common.FileBackedRadio):
def clear(self):
self.memories = []
- def __init__(self, pipe):
+ def __init__(self, pipe, max_memory=999):
chirp_common.FileBackedRadio.__init__(self, None)
self.memories = []
self.file_has_rTone = None # Set in load(), used in _clean_tmode()
@@ -105,12 +106,11 @@ class CSVRadio(chirp_common.FileBackedRadio):
# Persistence for comment lines
# List of tuples of (previous_memory, comment)
self._comments = []
-
self._filename = pipe
if self._filename and os.path.exists(self._filename):
self.load()
else:
- self._blank(True)
+ self._blank(True, max_memory=max_memory)
def get_features(self):
rf = chirp_common.RadioFeatures()
@@ -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/h777.py b/chirp/drivers/h777.py
index 0586fd0..699fb54 100644
--- a/chirp/drivers/h777.py
+++ b/chirp/drivers/h777.py
@@ -27,6 +27,22 @@ from chirp.settings import RadioSetting, RadioSettingGroup, \
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 +60,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 +119,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 +147,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 +209,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__,
@@ -446,6 +449,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 while the channel is busy emits an '
+ 'alert tone and inhibits the transmitter')
mem.extra.append(rs)
if self._has_scramble:
rs = RadioSetting("beatshift", "Beat Shift(scramble)",
@@ -505,16 +511,23 @@ class H777Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("voiceprompt", "Voice prompt",
RadioSettingValueBoolean(_settings.voiceprompt))
+ rs.set_doc('Announces channel changes and operations by voice')
basic.append(rs)
rs = RadioSetting("voicelanguage", "Voice language",
RadioSettingValueList(
VOICE_LIST,
current_index=_settings.voicelanguage))
+ rs.set_doc('Language used for the voice prompts (Chinese or English)')
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 +540,17 @@ class H777Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("vox", "VOX",
RadioSettingValueBoolean(_settings.vox))
+ rs.set_doc('Voice Operated Transmit keys the transmitter when you '
+ 'speak into the microphone, eliminating the need to '
+ 'press PTT')
basic.append(rs)
rs = RadioSetting("voxlevel", "VOX level",
RadioSettingValueInteger(
1, self.MAX_VOXLEVEL, _settings.voxlevel + 1))
+ rs.set_doc('VOX gain sensitivity. If set too sensitive the radio '
+ 'keys up on background noise; if not sensitive enough it '
+ 'will not pick up your voice')
basic.append(rs)
rs = RadioSetting("voxinhibitonrx", "Inhibit VOX on receive",
@@ -554,6 +573,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 +583,31 @@ 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('When enabled, the radio emits a short tone when you '
+ 'select a channel that has nothing programmed')
basic.append(rs)
rs = RadioSetting("settings2.batterysaver", "Battery saver",
RadioSettingValueBoolean(
self._memobj.settings2.batterysaver))
+ rs.set_doc('Reduces battery power used when no signal is being '
+ 'received. Activates automatically about 10 seconds '
+ 'after the last received signal or operation')
basic.append(rs)
rs = RadioSetting("settings2.squelchlevel", "Squelch level",
RadioSettingValueInteger(
0, 9, self._memobj.settings2.squelchlevel))
+ rs.set_doc('Mutes the speaker when no signal is present so that you '
+ 'only hear sound when a signal is received. Higher '
+ 'levels require a stronger signal to unmute')
basic.append(rs)
if self._has_sidekey:
@@ -591,6 +623,9 @@ class H777Radio(chirp_common.CloneModeRadio):
RadioSettingValueList(
TIMEOUTTIMER_LIST,
current_index=self._memobj.settings2.timeouttimer))
+ rs.set_doc('Limits the maximum length of a single transmission to '
+ 'prevent overheating the radio. An alert sounds when the '
+ 'limit is reached')
basic.append(rs)
return top
@@ -656,6 +691,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 +797,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):
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/ic2730.py b/chirp/drivers/ic2730.py
index 6bb643b..d901464 100644
--- a/chirp/drivers/ic2730.py
+++ b/chirp/drivers/ic2730.py
@@ -1352,3 +1352,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/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/icq7.py b/chirp/drivers/icq7.py
index 60f9fcd..a5fdce3 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
@@ -189,7 +189,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/ict8.py b/chirp/drivers/ict8.py
index 37484e5..cc6dbbb 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)
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 48acc0b..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,22 +260,7 @@ def do_upload(radio):
radio.status_fn(status)
_write_block(radio, addr, radio.BLOCK_SIZE)
- _exit_programming_mode(radio)
-
-
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
+ exit_programming_mode(radio.pipe, radio.magic_exit)
class IradioUV5118(chirp_common.CloneModeRadio):
@@ -324,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)
@@ -469,8 +417,8 @@ class IradioUV5118(chirp_common.CloneModeRadio):
# TX freq set
offset = (int(_mem.txfreq) * 10) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.txfreq) * 10):
+ 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:
diff --git a/chirp/drivers/iradio_uv_5118plus.py b/chirp/drivers/iradio_uv_5118plus.py
index 497e1af..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,22 +298,7 @@ def do_upload(radio):
radio.status_fn(status)
_write_block(radio, addr, radio.BLOCK_SIZE)
- _exit_programming_mode(radio)
-
-
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
+ exit_programming_mode(radio.pipe, radio.magic_exit)
class IradioUV5118plus(chirp_common.CloneModeRadio):
@@ -359,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)
@@ -436,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
@@ -507,8 +460,8 @@ class IradioUV5118plus(chirp_common.CloneModeRadio):
# TX freq set
offset = (int(_mem.txfreq) * 10) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.txfreq) * 10):
+ 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:
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_live.py b/chirp/drivers/kenwood_live.py
index 52475bc..772253b 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)))
diff --git a/chirp/drivers/kg935g.py b/chirp/drivers/kg935g.py
index 51157de..20a35ef 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]
@@ -1639,70 +1644,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 +1690,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 +1709,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 +2471,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 +2499,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..cda0378 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,6 +303,14 @@ 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
@@ -309,31 +318,28 @@ class KGUV8ERadio(chirp_common.CloneModeRadio,
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)
@@ -394,7 +400,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 +537,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 +572,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 +580,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 +609,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..4211a6d 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
@@ -526,6 +437,15 @@ class KGUV920PARadio(chirp_common.CloneModeRadio,
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,24 +455,26 @@ 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:])])
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:])
+ _cs += checksum.checksum_8bit(_packet)
_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)
@@ -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..630dff8 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;
@@ -1098,6 +1099,9 @@ class KGUV9DPlusRadio(chirp_common.CloneModeRadio,
_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 +1119,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])
@@ -1172,7 +1178,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 +1386,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 +1462,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 +1476,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 +1530,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..9135946 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):
diff --git a/chirp/drivers/lt725uv.py b/chirp/drivers/lt725uv.py
index 0b2219a..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
@@ -406,21 +411,6 @@ def model_match(cls, data):
return False
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # Determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # If the two freqs are on the same Band this is not a split
- return False
-
- # If you get here is because the freq pairs are split
- return True
-
-
@directory.register
class LT725UV(chirp_common.CloneModeRadio):
"""LUITON LT-725UV Radio"""
@@ -565,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')
@@ -583,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]
@@ -607,7 +599,8 @@ class LT725UV(chirp_common.CloneModeRadio):
elif int(_mem.rxfreq) == int(_mem.txfreq):
mem.duplex = ""
mem.offset = 0
- elif _split(self.get_features(), mem.freq, int(_mem.txfreq) * 10):
+ elif chirp_common.is_split(self.get_features().valid_bands,
+ mem.freq, int(_mem.txfreq) * 10):
mem.duplex = "split"
mem.offset = int(_mem.txfreq) * 10
else:
diff --git a/chirp/drivers/mml_jc8810.py b/chirp/drivers/mml_jc8810.py
index 1ba0a5d..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)
@@ -405,21 +407,6 @@ def do_upload(radio):
_exit_programming_mode(radio)
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
-
-
class JC8810base(chirp_common.CloneModeRadio):
"""MML JC-8810"""
VENDOR = "MML"
@@ -507,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
@@ -539,8 +528,8 @@ class JC8810base(chirp_common.CloneModeRadio):
# TX freq set
offset = (int(_mem.txfreq) * 10) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.txfreq) * 10):
+ 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:
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..0845ac6 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')
diff --git a/chirp/drivers/radtel_rt490.py b/chirp/drivers/radtel_rt490.py
index 8729954..6353b86 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)
diff --git a/chirp/drivers/radtel_rt880g.py b/chirp/drivers/radtel_rt880g.py
new file mode 100644
index 0000000..cd38fad
--- /dev/null
+++ b/chirp/drivers/radtel_rt880g.py
@@ -0,0 +1,2315 @@
+# 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
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ # This radio has always been post-metadata, so never do
+ # old-school detection
+ return False
diff --git a/chirp/drivers/radtel_rt900.py b/chirp/drivers/radtel_rt900.py
new file mode 100644
index 0000000..52ac148
--- /dev/null
+++ b/chirp/drivers/radtel_rt900.py
@@ -0,0 +1,2429 @@
+# 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
+# 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
+
+from chirp import (
+ bitwise,
+ chirp_common,
+ directory,
+ errors,
+ memmap,
+ util,
+)
+
+from chirp.settings import (
+ RadioSetting,
+ RadioSettingGroup,
+ RadioSettingSubGroup,
+ RadioSettings,
+ RadioSettingValueBoolean,
+ RadioSettingValueInvertedBoolean,
+ RadioSettingValueInteger,
+ RadioSettingValueList,
+ RadioSettingValueString,
+ RadioSettingValueMap,
+ MemSetting,
+ InvalidValueError,
+)
+from textwrap import dedent
+from chirp.drivers import (
+ baofeng_uv17Pro,
+ mml_jc8810,
+ 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
+ lbcd txfreq[4]; // 4-7
+ ul16 rxtone; // 8-9
+ ul16 txtone; // A-B
+ u8 unknown1:4, // C
+ scode:4; // Signaling
+ u8 unknown2:6, // D
+ pttid:2; // PTT-ID
+ u8 scramble:6, // Scramble
+ txpower:2; // Power Level 0 = H, 1 = L, 2 = M
+ u8 unknown4:1, // F
+ narrow:1, // Bandwidth 0 = Wide, 1 = Narrow
+ encrypt:2, // Encrypt
+ bcl:1, // BCL
+ scan:1, // Scan 0 = Skip, 1 = Scan
+ am_modulation:1, // Per chan AM modulation
+ 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];
+
+// vfo settings, 32 bytes
+struct vfo {
+ u8 freq[8]; // vfo freq
+ ul16 rxtone; // coded RX CTCSS/DTC tone
+ ul16 txtone; // coded TX CTCSS/DTC tone
+ u8 unknown0[2];
+ u8 unknown1:2,
+ sftd:2, // offset direction, 0 == OFF, 1 == +, 2 == -
+ scode:4; // scode 0-15
+ u8 unknown2;
+ u8 unknown3:3,
+ scramble:3, // 0b0 == OFF, 0b100 == ON
+ txpower:2; // TX power, 0b0 == HIGH, 0b1 == Middle,
+ // 0b2 == LOW
+ u8 unknown5:1,
+ widenarr:1, // Bandwidth, 0b0 == WIDE, 0b1 == NARROW
+ voicepri:2, // Voice privacy encryption, 0b00 == OFF,
+ // 0b01 == ENCRY1, 2 == ENCRY2, 0b11 == ENCRY3
+ unknown6:2,
+ rxmod:1, // RX Modulation, 0b0 == FM, 0b1 == AM
+ unknown7:1;
+ u8 unknown8;
+ u8 step; // vfo tuning step size index: 0 == 2.5K, ...
+ // 6 == 50K, 7 == 8.33K: 0x8013, 0x8033
+ u8 offset[6]; // TX freq offset: 0x814, 0x834
+ u8 unknown9[6];
+};
+
+#seekto 0x8000; // vfo a & b
+struct {
+ struct vfo a;
+ struct vfo b;
+} vfo;
+
+#seekto 0x9000;
+struct {
+ u8 unused:4, // 9000
+ sql:4; // Squelch Level
+ u8 unused_9001:6, // 9001
+ save:2; // Battery Save
+ u8 unused_9002:4, // 9002
+ vox:4; // VOX Level
+ u8 unused_9003:4, // 9003
+ abr:4; // Auto BackLight
+ u8 unused_9004:7, // 9004
+ tdr:1; // TDR
+ u8 unused_9005:5, // 9005
+ tot:3; // Time-out Timer
+ u8 unused_9006:7, // 9006
+ beep:1; // Beep
+ u8 unused_9007:7, // 9007
+ voice:1; // Voice Prompt
+ u8 unused_9008:7, // 9008
+ language:1; // Language
+ u8 unused_9009:6, // 9009
+ dtmfst:2; // DTMF ST
+ u8 unused_900a:6, // 900A
+ screv:2; // Scan Mode
+ u8 unused_900B:4, // 900B
+ pttid:4; // PTT-ID
+ u8 unused_900c:5, // 900C
+ pttlt:3; // PTT Delay
+ u8 unused_900d:6, // 900D
+ mdfa:2; // Channel_A Display
+ u8 unused_900e:6, // 900E
+ mdfb:2; // Channel_B Display
+ u8 busy_lock; // Busy Lock
+ u8 unused_9010:4, // 9010
+ autolk:4; // Key Auto Lock
+ u8 unused_9011:6, // 9011
+ almode:2; // Alarm Mode
+ u8 unused_9012:7, // 9012
+ alarmsound:1; // Alarm Sound
+ u8 unused_9013:6, // 9013
+ dualtx:2; // Dual TX
+ u8 unused_9014:7, // 9014
+ ste:1; // Tail Noise Clear
+ u8 unused_9015:4, // 9015
+ rpste:4; // RPT Noise Clear
+ u8 unused_9016:4, // 9016
+ rptrl:4; // RPT Noise Delay
+ u8 unused_9017:6, // 9017
+ roger:2; // Roger
+ u8 tx_ab; // TX A/B
+ u8 unused_9019:7, // 9019
+ fmradio:1; // FM Radio
+ u8 unused_901a1:3, // 901A
+ vfomrb:1, // WorkMode B
+ unused_901a2:3, //
+ vfomra:1; // WorkMode A
+ u8 unused_901b:7, // 901B
+ kblock:1; // KB Lock
+ u8 unused_901c:7, // 901C
+ ponmsg:1; // Power On Msg
+ u8 bluetooth; // Bluetooth ON/OFF
+ u8 unused_901e:6, // 901E
+ tone:2; // Pilot
+ u8 unknown_901f; // 901F
+ u8 unused_9020:4, // 9020
+ voxd:4; // VOX Delay
+ u8 unused_9021:4, // 9021
+ menuquit:4; // Menu Auto Quit
+ u8 unused_9022:7, // 9022
+ tailcode:1; // Tail Code (RT-470L)
+ u8 unknown_9023; // 9023
+ u8 single_mode ; // 9024 Single Mode (RT-900 BT)
+ u8 unknown_9025; // 9025 Always 0x01 on all RT-900 variants
+ u8 unknown_9026; // 9026
+ u8 unknown_9027; // 9027
+ 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_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)
+ u8 am_mode ; // 9030 AM Mode (RT-900)
+ u8 noise_reduction; // 9031 NOISE REDUCTION
+ u8 unknown_9032; // 9032
+ u8 unknown_9033; // 9033
+ u8 fm_interrupt; // 9034
+ u8 unknown_9035; // 9035
+ u8 unknown_9036; // 9036
+ u8 unknown_9037; // 9037
+ u8 unknown_9038; // 9038
+ u8 unknown_9039; // 9039
+ u8 unknown_903a; // 903a
+ u8 unknown_903b; // 903b
+ u8 dis_s_table; // 903b DIS S TABLE (A36plus 8w)
+} settings;
+
+#seekto 0xA006;
+struct {
+ u8 unknown_A006; // A006
+ u8 unused_a007:5, // A007
+ dtmfon:3; // DTMF Speed (on time)
+ u8 unused_a008:5, // A008
+ dtmfoff:3; // DTMF Speed (off time)
+} dtmf;
+
+#seekto 0xA020;
+struct {
+ u8 code[6]; // 6-character DTMF PTT-IDs
+ u8 unused[10];
+} pttid[15];
+
+#seekto 0xD000; // radio operationg mode
+struct {
+ u8 radio_mode;
+} opmode;
+
+"""
+
+CMD_ACK = b"\x06"
+DTCS = tuple(sorted(chirp_common.DTCS_CODES + (645,)))
+DTMF_CHARS = "0123456789 *#ABCD"
+
+TXPOWER_HIGH = 0x00
+TXPOWER_MID = 0x01
+TXPOWER_LOW = 0x02
+
+ABR_LIST = ["On", "5 seconds", "10 seconds", "15 seconds", "20 seconds",
+ "30 seconds", "1 minute", "2 minutes", "3 minutes"]
+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", "DT-ST", "ANI-ST", "DT+ANI"]
+DUALTX_LIST = ["Off", "A", "B"]
+LANGUAGE_LIST = ["English", "Chinese"]
+MDF_LIST = ["Name", "Frequency", "Channel"]
+MENUQUIT_LIST = ["%s seconds" % x for x in range(5, 55, 5)] + ["60 seconds"]
+OFF1TO9_LIST = ["Off"] + ["%s" % x for x in range(1, 10)]
+PONMSG_LIST = ["Logo", "Voltage"]
+PTTID_LIST = ["Off", "BOT", "EOT", "Both"]
+PTTIDCODE_LIST = ["%s" % x for x in range(1, 16)]
+PTTLT_LIST = ["None", "100 ms"] + \
+ ["%s ms" % x for x in range(200, 1200, 200)]
+QTSAVE_LIST = ["All", "TX", "RX"]
+ROGER_LIST = ["OFF", "BEEP", "TONE1200"]
+RPSTE_LIST = ["Off"] + ["%s ms" % x for x in range(100, 1100, 100)]
+SAVE_LIST = ["Off", "Normal Mode", "Super Mode", "Deep Mode"]
+SCREV_LIST = ["Time (TO)", "Carrier (CO)", "Search (SE)"]
+TONE_LIST = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"]
+TOT_LIST = ["Off", "15S", "30S", "45S", "60S",
+ "75S"]
+VOXD_LIST = ["%s seconds" % str(x / 10) for x in range(5, 21)]
+WORKMODE_LIST = ["VFO Mode", "Channel Mode"]
+
+
+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 = True
+ rf.valid_name_length = 12
+ 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 = DTCS
+ 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):
+ serial = radio.pipe
+ mml_jc8810._enter_programming_mode(radio)
+
+ try:
+ ident = serial.read(8)
+ serial.write(radio._cryptsetup)
+ ack = serial.read(1)
+ if ack != CMD_ACK:
+ raise errors.RadioError("Error setting up encryption")
+ except Exception:
+ raise errors.RadioError("Error communicating with radio")
+ if ident not in radio._fingerprint2:
+ LOG.debug(util.hexprint(ident))
+ raise errors.RadioError("Radio returned unknown secondary"
+ " identification string")
+
+
+def _exit_programming_mode(radio):
+ mml_jc8810._exit_programming_mode(radio)
+
+
+def _read_block(radio, block_addr, block_size):
+ serial = radio.pipe
+
+ cmd = struct.pack(">cHb", b'R', block_addr, block_size)
+ expectedresponse = b"R" + cmd[1:]
+
+ try:
+ serial.write(cmd)
+ response = serial.read(4 + block_size)
+ if response[:4] != expectedresponse:
+ raise Exception("Error reading block %04x." % (block_addr))
+
+ block_data = response[4:]
+ except Exception:
+ raise errors.RadioError("Failed to read block at %04x" % block_addr)
+
+ if block_addr >= 0xf000:
+ return block_data
+ else:
+ return baofeng_uv17Pro._crypt(1, block_data)
+
+
+def _write_block(radio, block_addr, block_size):
+ serial = radio.pipe
+
+ cmd = struct.pack(">cHb", b'W', block_addr, block_size)
+ data = radio.get_mmap()[block_addr:block_addr + block_size]
+ if block_addr < 0xf000:
+ data = baofeng_uv17Pro._crypt(1, data)
+
+ try:
+ serial.write(cmd + data)
+ if serial.read(1) != CMD_ACK:
+ raise Exception("No ACK")
+ except Exception:
+ raise errors.RadioError("Failed to send block "
+ "to radio at %04x" % block_addr)
+
+
+def do_download(radio):
+ LOG.debug("Downloading...")
+ _enter_programming_mode(radio)
+
+ data = b""
+
+ status = chirp_common.Status()
+ status.msg = "Cloning from radio"
+
+ status.cur = 0
+ status.max = radio._memsize
+
+ for addr in range(0, radio._memsize, radio.BLOCK_SIZE):
+ status.cur = addr + radio.BLOCK_SIZE
+ radio.status_fn(status)
+
+ block = _read_block(radio, addr, radio.BLOCK_SIZE)
+ data += block
+
+ radio.pipe.log('Sending request for %04x' % addr)
+
+ return memmap.MemoryMapBytes(data)
+
+
+def do_upload(radio):
+ LOG.debug("Uploading...")
+ status = chirp_common.Status()
+ status.msg = "Uploading to radio"
+
+ _enter_programming_mode(radio)
+
+ status.cur = 0
+ # calc actual upload size
+ for r in radio._ranges:
+ status.max += (r[1] - r[0]) + 1
+
+ for start_addr, end_addr in radio._ranges:
+ for addr in range(start_addr, end_addr, radio.BLOCK_SIZE_UP):
+ status.cur = addr + radio.BLOCK_SIZE_UP
+ radio.status_fn(status)
+ radio.pipe.log('Sending address %04x' % addr)
+ _write_block(radio, addr, radio.BLOCK_SIZE_UP)
+
+
+@directory.register
+class RT900BT(chirp_common.CloneModeRadio):
+ # ==========
+ # Notice to developers:
+ # The RT-900 BT support in this driver is currently based upon V1.20P
+ # firmware.
+ # ==========
+ """Radtel RT-900 BT 999"""
+ VENDOR = "Radtel"
+ MODEL = "RT-900_BT"
+ BAUD_RATE = 57600
+ BLOCK_SIZE = 0x40
+ BLOCK_SIZE_UP = 0x40
+
+ VALID_BANDS = [(18000000, 1000000000)]
+ _AIRBAND = (108000000, 136975000)
+ _MIL_AIRBAND = (225000000, 399950000)
+ _AIRBANDS = [_AIRBAND] # + [_MIL_AIRBAND]
+ # secret Power-ON + PTT + <key-press> combos for some modes:
+ # 8: Super
+ # OK: GMRS
+ # EXIT: Factory
+ # 2: 144-146/430-440
+ _RADIO_MODE_MAP = [
+ ("Default", 0xff), ("GMRS", 0xa5),
+ ("PMR", 0x66), ("144-146/430-440", 0x55),
+ ("Super", 0x56), ("Factory", 0x00),
+ ("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),
+ ]
+
+ SKEY_LIST = ["Radio",
+ "TX Power",
+ "Scan",
+ "Search",
+ "NOAA",
+ "SOS",
+ "Switch AM/FM",
+ "Bluetooth",]
+ SKEY_SP_LIST = SKEY_LIST
+
+ _upper = 999 # fw 1.20 expands from 512 to 999 channels_steps,
+ _mem_params = (_upper # number of channels
+ )
+
+ _magic = b"PROGRAMBT80U"
+ _fingerprint = [b"\x01\x36\x01\x80\x04\x00\x05\x20",
+ b"\x01\x00\x01\x80\x04\x00\x05\x20",
+ ] # fw V1.20P for RT-900 BT
+ _fingerprint2 = [b"\x02\x00\x02\x60\x01\x03\x30\x04",
+ ] # fw V1.20P for RT-900 BT
+ _cryptsetup = (b'SEND \x01\x01\x00\x00\x00\x00\x00\x00\x00\x00' +
+ b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
+
+ _ranges = [
+ (0x0000, 0x7CE0), # FW V1.20P,
+ # 0x7CE0 equals 999 channels of 32 bytes each
+ # 999 * 32 = 0x7ce0
+ (0x8000, 0x8040),
+ (0x9000, 0x9040),
+ (0xA000, 0xA140),
+ (0xD000, 0xD040), # Radio mode hidden setting
+ ]
+
+ _calibration = (0xF000, 0xF250) # Calibration data
+ _memsize = 0xF250 # Including calibration data
+
+ _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 = 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),]
+ _bandwidth_list = ["Wide (25 KHz)", "Narrow (12.5 KHz)"]
+ _offset_list = ["Off", "+", "-"]
+ _rx_modulation_list = ["FM", "AM"]
+ _scode_list = ["%s" % x for x in range(1, 16)]
+ _voicepri_list = ["Off", "ENCRY1", "ENCRY2", "ENCRY3"]
+ _scramble_map = [("Off", 0x00), ("On", 0x04)]
+
+ _code_list_ctcss = ["%2.1fHz" % x for x in sorted(chirp_common.TONES)]
+ _code_list_ctcss.insert(0, "Off")
+ _dcs = tuple(sorted(chirp_common.DTCS_CODES + (645,)))
+ _code_list_dcsn = ["D%03iN" % x for x in _dcs]
+ _code_list_dcsi = ["D%03iI" % x for x in _dcs]
+ _code_list = _code_list_ctcss + _code_list_dcsn + _code_list_dcsi
+
+ def sync_in(self):
+ """Download from radio"""
+ try:
+ data = do_download(self)
+ except errors.RadioError:
+ # Pass through any real errors we raise
+ raise
+ except Exception:
+ # If anything unexpected happens, make sure we raise
+ # a RadioError and log the problem
+ LOG.exception('Unexpected error during download')
+ raise errors.RadioError('Unexpected error communicating '
+ 'with the radio')
+ finally:
+ _exit_programming_mode(self)
+
+ self._mmap = data
+ self.process_mmap()
+
+ def sync_out(self):
+ """Upload to radio"""
+ try:
+ do_upload(self)
+ except errors.RadioError:
+ raise
+ except Exception:
+ # If anything unexpected happens, make sure we raise
+ # a RadioError and log the problem
+ LOG.exception('Unexpected error during upload')
+ raise errors.RadioError('Unexpected error communicating '
+ 'with the radio')
+ finally:
+ _exit_programming_mode(self)
+
+ def get_settings(self):
+ _dtmf = self._memobj.dtmf
+ _settings = self._memobj.settings
+ _radio_mode = self._memobj.opmode.radio_mode
+ basic = RadioSettingGroup("basic", "Basic Settings")
+ group = RadioSettings(basic)
+
+ # 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: 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 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)
+
+ 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", 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")
+ group.append(dtmf)
+
+ def apply_code(setting, obj, length):
+ code = []
+ for j in range(0, length):
+ try:
+ code.append(DTMF_CHARS.index(str(setting.value)[j]))
+ except IndexError:
+ code.append(0xFF)
+ obj.code = code
+
+ 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, 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], 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.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.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")
+ group.append(spec)
+
+ # secret radio mode setting (no menu). PTT + 8 for Super Mode
+ rs = RadioSettingValueMap(self._RADIO_MODE_MAP, _radio_mode)
+ rset = MemSetting("opmode.radio_mode", "Radio Operating Mode", rs)
+ rset.set_warning(
+ 'This should only be used to change the operating MODE of your '
+ 'radio if you understand the legalities and implications of '
+ 'doing so. The change may enable the radio to transmit on '
+ 'frequencies it is not Type Accepted to do and may be in '
+ 'violation of FCC and other governing agency regulations.\n\n'
+ 'It may make your saved image files incompatible with the radio '
+ 'and non-usable until you change the radio MODE back to the '
+ 'MODE in effect when the image file was saved. After the '
+ 'changed image is uploaded, the radio may have to turned OFF '
+ '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:
+ # Menu 46: Noise reduction
+ 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=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=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=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"]:
+ # Menu 50: AM/FM Mode
+ 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 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
+ abblock = RadioSettingGroup("abblock", "VFO A/B Channel")
+ spec.append(abblock)
+
+ vfo = self._memobj.vfo
+
+ # 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
+ )
+ 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
+ achannel = RadioSettingSubGroup("achannel", "VFO A Channel")
+ abblock.append(achannel)
+
+ # Work Mode A
+ 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
+ def freq_validate(value):
+ _radio_mode = self._memobj.opmode.radio_mode
+ _vhf_lower = 0.0
+ _uhf_upper = 0.0
+ if _radio_mode in [0x00, 0x56, 0xff]: # Factory,Super,Default
+ _vhf_lower = 18.0
+ else:
+ _vhf_lower = 108.0
+ _vhf_upper = 299.99875
+ _uhf_lower = 300.0
+ if _radio_mode in [0x00, 0x56]: # Factory,Super
+ _uhf_upper = 999.99875
+ else:
+ _uhf_upper = 519.99875
+
+ value = chirp_common.parse_freq(value)
+ msg = ("Can't be less than %i.0000")
+ if value < _vhf_lower * 1000000:
+ raise InvalidValueError(msg % _vhf_lower)
+ msg = ("Can't be between %i.9975-%i.0000")
+ if _vhf_upper * 1000000 <= value and \
+ value < _uhf_lower * 1000000:
+ raise InvalidValueError(msg % (_vhf_upper - 1, _uhf_lower))
+ msg = ("Can't be greater than %i.9975")
+ if value > _uhf_upper * 1000000:
+ raise InvalidValueError(msg % (_uhf_upper - 1))
+
+ return chirp_common.format_freq(value)
+
+ def apply_freq(setting, obj):
+ value = chirp_common.parse_freq(str(setting.value)) / 10
+ for i in range(7, -1, -1):
+ obj.freq[i] = value % 10
+ value /= 10
+
+ rs = RadioSettingValueString(0, 10, bfc.bcd_decode_freq(vfo.a.freq))
+ 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
+ rs = RadioSettingValueList(self._code_list,
+ current_index=self._code_list.index
+ (self.decode(vfo.a.rxtone)))
+ 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
+ rs = RadioSettingValueList(self._code_list,
+ current_index=self._code_list.index
+ (self.decode(vfo.a.txtone)))
+ 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)
+ rs = RadioSettingValueList(self._voicepri_list,
+ 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):
+ real_offset = 0
+ for byte in bytes:
+ real_offset = (real_offset * 10) + byte
+ return chirp_common.format_freq(real_offset * 1000)
+
+ def apply_offset(setting, obj):
+ value = chirp_common.parse_freq(str(setting.value)) / 1000
+ for i in range(5, -1, -1):
+ obj.offset[i] = value % 10
+ value /= 10
+
+ # Menu 26: Offset
+ rs = RadioSettingValueString(0, 10,
+ 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
+ if self._has_am_per_channel:
+ 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
+ bchannel = RadioSettingSubGroup("bchannel", "VFO B Channel")
+ abblock.append(bchannel)
+
+ # Work Mode B
+ 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
+ rs = RadioSettingValueString(0, 10,
+ bfc.bcd_decode_freq(vfo.b.freq))
+ 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
+ rs = RadioSettingValueList(self._code_list,
+ current_index=self._code_list.index
+ (self.decode(vfo.b.rxtone)))
+ 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
+ rs = RadioSettingValueList(self._code_list,
+ current_index=self._code_list.index
+ (self.decode(vfo.b.txtone)))
+ 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)
+ rs = RadioSettingValueList(self._voicepri_list,
+ 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
+ rs = RadioSettingValueString(0, 10,
+ 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
+ if self._has_am_per_channel:
+ 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
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.experimental = \
+ ('This driver is a beta version ONLY for the RT-900 BT'
+ ' running Firmware V.1.20P.\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 _decode_tone(self, memval):
+ """Parse the tone data to decode from memval, it returns:
+ Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
+ pol = None
+ if memval in [0, 0xFFFF]:
+ return "", None, None
+ elif memval >= 0x0258:
+ a = memval / 10.0
+ return "Tone", a, pol
+ else:
+ if memval > 0x69:
+ index = memval - 0x6A
+ pol = "R"
+ else:
+ index = memval - 1
+ pol = "N"
+ tone = DTCS[index]
+ return "DTCS", tone, pol
+
+ def _encode_tone(self, mem, memval, mode, value, pol):
+ """Parse the tone data to encode from UI to mem"""
+ match mode:
+ case "" | None:
+ memval.fill_raw(b"\x00")
+ case "Tone" | "TSQL":
+ memval.set_value(int(value * 10))
+ case "DTCS":
+ try:
+ index = DTCS.index(value)
+ if pol == "N":
+ index += 1
+ else:
+ index += 0x6A
+ memval.set_value(index)
+ except ValueError:
+ msg = "DTCS Code '%d' is not supported" % value
+ LOG.error(msg)
+ raise errors.RadioError(msg)
+ case _:
+ raise Exception("Internal error: invalid mode '%s'" % mode)
+
+ def decode(self, code):
+ """decode radio stored VFO tone code into human readable form"""
+ if code in [0, 0xffff]:
+ tone = 'Off' # Off
+ elif code >= 0x0258: # CTCSS
+ tone = "%2.1fHz" % (int(code) / 10.0)
+ elif code <= 0x0258: # DCS
+ if code > 0x69: # inverse
+ index = code - 0x6a
+ dtcs_pol = 'I'
+ else: # normal
+ index = code - 1
+ dtcs_pol = 'N'
+ tone = 'D' + "%03i" % (self._dcs[index]) + dtcs_pol
+ else:
+ msg = "Invalid tone code from radio: %s" % hex(code)
+ LOG.exception(msg)
+ raise InvalidValueError(msg)
+
+ return tone
+
+ def apply_vfo_tone(self, setting, obj, which):
+ """encode VFO tone from UI into radio storable tone code
+ and apply to mem"""
+ mem = getattr(obj, which)
+ try:
+ tone = self._code_list[int(setting.value)]
+ if tone == "Off":
+ code = 0
+ elif tone.endswith('Hz'): # CTCSS
+ code = int(float(tone[0:tone.index('Hz')]) * 10)
+ elif tone.startswith('D'): # DCS
+ index = self._dcs.index(int(tone[1:4]))
+ if tone.endswith('I'): # inverse
+ code = index + 0x6a
+ elif tone.endswith('N'): # normal
+ code = index + 1
+ except (IndexError, ValueError):
+ msg = "Unknown CTCSS/DTC tone: %s" % tone
+ LOG.exception(msg)
+ raise InvalidValueError(msg)
+
+ mem.set_value(code)
+
+ def get_features(self):
+ rf = get_default_features(self)
+ rf.valid_bands = self.VALID_BANDS
+ rf.valid_modes = ["FM", "NFM", "AM", "NAM"] # 25kHz, 12.5kHz, AM, NAM
+ 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]
+
+ # 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
+
+ for char in _mem.name:
+ if str(char) == "\xFF":
+ char = " " # may have 0xFF mid-name
+ mem.name += str(char)
+ mem.name = mem.name.rstrip().replace('\x00', '')
+
+ txtone = rxtone = None
+ txtone = self._decode_tone(_mem.txtone)
+ rxtone = self._decode_tone(_mem.rxtone)
+ chirp_common.split_tone_decode(mem, txtone, rxtone)
+
+ if not _mem.scan:
+ mem.skip = "S"
+
+ _levels = self.POWER_LEVELS
+
+ if _mem.txpower == TXPOWER_HIGH:
+ mem.power = _levels[0]
+ elif _mem.txpower == TXPOWER_MID:
+ mem.power = _levels[1]
+ elif _mem.txpower == TXPOWER_LOW:
+ mem.power = _levels[2]
+ else:
+ LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
+ (mem.name, _mem.txpower))
+
+ mem.mode = _mem.narrow and "NFM" or "FM"
+
+ if chirp_common.in_range(
+ mem.freq, self._AIRBANDS
+ ) or _mem.am_modulation == 0b1:
+ mem.mode = _mem.narrow and "NAM" or 'AM'
+
+ mem.extra = RadioSettingGroup("Extra", "extra")
+
+ # Encryption
+ rs = RadioSettingValueList(
+ self._voicepri_list,
+ current_index=_mem.encrypt
+ )
+ rset = RadioSetting("encrypt", "Voice Privacy", rs)
+ mem.extra.append(rset)
+
+ # Scramble
+ rs = RadioSettingValueMap(self._scramble_map, _mem.scramble)
+ rset = RadioSetting("scramble", "Scramble", rs)
+ mem.extra.append(rset)
+
+ # 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
+
+ def set_memory(self, mem):
+ _mem = self._memobj.memory[mem.number - 1]
+
+ if mem.empty:
+ _mem.fill_raw(b"\xff")
+ return
+
+ _mem.set_raw("\x00" * 16 + "\xff" * 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
+
+ _namelength = self.get_features().valid_name_length
+ for i in range(_namelength):
+ try:
+ _mem.name[i] = mem.name[i]
+ except IndexError:
+ _mem.name[i] = "\xff"
+
+ txmode = rxmode = ''
+ txval = rxval = 0
+ txpol = rxpol = None
+ ((txmode, txval, txpol),
+ (rxmode, rxval, rxpol)) = chirp_common.split_tone_encode(mem)
+
+ self._encode_tone(mem, _mem.txtone, txmode, txval, txpol)
+ self._encode_tone(mem, _mem.rxtone, rxmode, rxval, rxpol)
+
+ _mem.scan = mem.skip != "S"
+ _mem.narrow = mem.mode == "NFM"
+
+ _levels = self.POWER_LEVELS
+ if mem.power is None:
+ _mem.txpower = TXPOWER_HIGH
+ elif mem.power == _levels[0]:
+ _mem.txpower = TXPOWER_HIGH
+ elif mem.power == _levels[1]:
+ _mem.txpower = TXPOWER_MID
+ elif mem.power == _levels[2]:
+ _mem.txpower = TXPOWER_LOW
+ else:
+ LOG.error('%s: set_mem: unhandled power level: %s' %
+ (mem.name, mem.power))
+
+ match mem.mode:
+ case 'AM': # radio allows AM per channel
+ _mem.am_modulation = 0b1
+ _mem.narrow = 0b0
+ case "NAM": # radio allows narrow AM per channel
+ _mem.am_modulation = 0b1
+ _mem.narrow = 0b1
+ case 'FM':
+ _mem.am_modulation = 0b0
+ _mem.narrow = 0b0
+ case 'NFM':
+ _mem.am_modulation = 0b0
+ _mem.narrow = 0b1
+
+ for setting in mem.extra:
+ 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 = []
+ in_range = chirp_common.in_range
+ AM_mode = 'AM' in mem.mode
+
+ if in_range(mem.freq, self._AIRBANDS) and not AM_mode:
+ msgs.append(chirp_common.ValidationMessage(
+ _('Frequency in this range requires AM mode')))
+ return msgs + super().validate_memory(mem)
+
+ 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)
+
+
+@directory.register
+class RT900(RT900BT):
+ # ==========
+ # Notice to developers:
+ # The RT-900 support in this driver is currently based upon stock
+ # factory firmware, V0.14P
+ # ==========
+
+ """Radtel RT-900 (without Bluetooth)"""
+ VENDOR = "Radtel"
+ MODEL = "RT-900"
+
+ _has_bt_denoise = False
+ _has_am_per_channel = False
+ _has_am_switch = not _has_am_per_channel
+ _has_single_mode = False
+ _has_hf = False
+
+ _upper = 999 # fw V1.14P expands from 512 to 999 channels
+
+ SKEY_LIST = ["FM Radio",
+ "TX Power Level",
+ "Scan",
+ "Search",
+ "NOAA Weather",
+ "SOS",
+ "Flashlight" # Not used in BT model
+ ]
+ SKEY_SP_LIST = SKEY_LIST
+
+ def get_features(self):
+ rf = super().get_features()
+ # So far no firmware update to test new range availability yet
+ # rf.valid_bands = [(18000000, 1000000000)]
+ return rf
+
+ @classmethod
+ def get_prompts(cls):
+ rp = super().get_prompts()
+ rp.experimental = \
+ ('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'
+ 'PROCEED AT YOUR OWN RISK!'
+ )
+ return rp
+
+
+@directory.register
+class RT910BT(RT900BT):
+ # ==========
+ # Notice to developers:
+ # 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"""
+ VENDOR = "Radtel"
+ MODEL = "RT-910_BT"
+
+ SKEY_LIST = ["Radio",
+ "TX Power",
+ "Scan",
+ "Search",
+ "NOAA",
+ "SOS",
+ "Spectrum"]
+ SKEY_SP_LIST = SKEY_LIST + ["PTTB"]
+
+ _upper = 960 # fw V0.24P supports 960 channels
+
+ _mem_params = (_upper, # number of channels
+ )
+ _ranges = [
+ (0x0000, 0x7800), # 15 zones of 64 frequencies,
+ # equals 960 channels of 32 bytes each
+ # 15 * 64 * 32 = 0x7800
+ (0x8000, 0x8040),
+ (0x9000, 0x9040),
+ (0xA000, 0xA140),
+ (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
+
+ def get_bank_model(self):
+ return chirp_common.StaticBankModel(self, banks=15)
+
+ def get_features(self):
+ rf = super().get_features()
+ rf.has_bank = True # Firmware V0.24P supports 15
+ # "static zones" of 64 frequencies
+ rf.valid_tuning_steps = self._steps
+ return rf
+
+ @classmethod
+ def get_prompts(cls):
+ rp = super().get_prompts()
+ rp.experimental = \
+ ('This driver is a beta version for the RT-910 BT'
+ ' 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'
+ 'PROCEED AT YOUR OWN RISK!'
+ )
+ return rp
+
+
+@directory.register
+class RT910(RT910BT):
+ # ==========
+ # Notice to developers:
+ # 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 960 (without Bluetooth)"""
+ VENDOR = "Radtel"
+ MODEL = "RT-910"
+
+ _upper = 960 # fw V0.11 supports 960 channels
+
+ _mem_params = (_upper, # number of channels
+ )
+ _ranges = [
+ (0x0000, 0x7800), # 15 zones of 64 frequencies,
+ # equals 960 channels of 32 bytes each
+ # 15 * 64 * 32 = 0x7800
+ (0x8000, 0x8040),
+ (0x9000, 0x9040),
+ (0xA000, 0xA140),
+ (0xD000, 0xD040) # Radio mode hidden setting
+ ]
+
+ _has_bt_denoise = False
+ _has_am_per_channel = True
+ _has_am_switch = not _has_am_per_channel
+ _has_single_mode = True
+ _has_hf = False
+
+ def get_bank_model(self):
+ 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.11\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
+
+
+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.18
+ # firmware with 10 banks/zones of 99 channels.
+ # ==========
+ """Radtel RT-920"""
+ VENDOR = "Radtel"
+ MODEL = "RT-920"
+
+ _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]
+
+ SKEY_LIST = ["Radio",
+ "TX Power",
+ "Scan",
+ "Search",
+ "NOAA",
+ "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 = 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
+ (0x8000, 0x8040),
+ (0x9000, 0x9040),
+ (0xB000, 0xB400), # FM, AM, HF frequencies
+ (0xC000, 0xC400), # FM, AM, HF names
+ (0xA000, 0xA140),
+ (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=self._banks)
+
+ def get_features(self):
+ rf = super().get_features()
+ # 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 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..396f650 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")
@@ -563,6 +563,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 this channel while another station is "
+ "already using it. 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 +734,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 radio keeps opening 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 +761,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 +794,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. Useful on a radio without a display, "
+ "but it can be intrusive in quiet surroundings.")
basic.append(rs)
elif self.MODEL == "RT15":
rs = RadioSetting("voiceprompt", "Voice prompts",
@@ -789,6 +815,11 @@ class T18Radio(chirp_common.CloneModeRadio):
rs = RadioSetting("batterysaver", "Battery saver",
RadioSettingValueBoolean(_settings.batterysaver))
+ rs.set_doc(
+ "Cuts standby power consumption by dozing the receiver once no "
+ "signal has been received for a few seconds. It considerably "
+ "extends battery life, at the cost of occasionally clipping the "
+ "first moment of an incoming transmission.")
basic.append(rs)
if self.MODEL not in ["RB29",
@@ -799,6 +830,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 +1025,70 @@ 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, on a scale of 1 to 5. Too "
+ "sensitive a setting keys the transmitter on the noise "
+ "around the radio, too insensitive a setting fails to pick "
+ "up your voice. Only has an effect when VOX is enabled.")
basic.append(rs)
if self.MODEL == "RB29" or self.MODEL == "RB629":
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
new file mode 100644
index 0000000..8fc308c
--- /dev/null
+++ b/chirp/drivers/retevis_ha1g.py
@@ -0,0 +1,1779 @@
+# 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 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
+import math
+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,
+ RadioSettingValueList,
+ RadioSettingValueString,
+ RadioSettings,
+ RadioSettingValueBoolean,
+ RadioSettingValueFloat)
+
+
+LOG = logging.getLogger(__name__)
+
+SERIAL_TIMEOUT = 1.0
+
+
+MEM_DEFINITIONS = """
+struct radioinfo {
+ u8 modelnumber[32];
+ u8 hardwareversion[2];
+ u8 serialno[16];
+ ul32 freqmin;
+ ul32 freqmax;
+ u8 rev_1;
+ u8 saleterr;
+ u8 radiomode;
+ u8 rev[7];
+};
+
+struct dataver {
+ u8 dataver[2];
+ u8 softver[4];
+ u8 rev[4];
+};
+
+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 {
+ u8 readpwd[8];
+ u8 writepwd[8];
+ u8 poweronpwd[8];
+ u8 squelch:4,
+ rev_1:4;
+ u8 powersavingdelaytime:4,
+ powersavingmode:4;
+ u8 tk1_short;
+ u8 tk1_long;
+ u8 sk1_short;
+ u8 sk1_long;
+ u8 sk2_short;
+ u8 sk2_long;
+ u8 longtime;
+ u8 chknoblock:1,
+ sidekeylock:1,
+ panellock:1,
+ rev_2:3,
+ autoormanuallock:1,
+ keylockswitch:1;
+ u8 wxscan:1,
+ agc:1,
+ rtcreport:1,
+ displaybatterylevel:1,
+ batterlevelreport:1,
+ lowbattery:1,
+ stunmode:2;
+ u8 voiceprompts:1,
+ touchtone:1,
+ txpermittone:1,
+ channelmode:1,
+ screenlight:1,
+ rogerbeep:1,
+ rev_3:2;
+ ul16 poweron_type_1:4,
+ homepoweronzone_1:12;
+ ul16 homepoweronch_1;
+ u8 relaytaildelay;
+ u8 radioid[10];
+ u8 radioname[16];
+ u8 micmain;
+ u8 agcmain:4,
+ agcthreshold:4;
+ u8 scenemode;
+ u8 autooff;
+ u8 menuouttime;
+ u8 voxthreshold:4,
+ voxdelaytime:4;
+ u8 rev_4:1,
+ homeselect:3,
+ homeindex:2,
+ chdisplay:2;
+ ul16 poweron_type_2:4,
+ homepoweronzone_2:12;
+ ul16 homepoweronch_2;
+ ul16 homepoweronzone_3;
+ ul16 homepoweronch_3;
+ ul16 freqstep;
+ u8 language;
+ u8 backlightbrightness:4,
+ backlighttime:4;
+ u8 wxch;
+ u8 calltone;
+ u8 rev_5:5,
+ homechtype_3:1,
+ homechtype_2:1,
+ homechtype_1:1;
+ u8 spreadspectrummode;
+ u8 salezone;
+ u8 tailsoundeliminationsfre:7,
+ tailsoundeliminationswitch:1;
+ u8 singletone;
+ u8 scanlist;
+ u8 rev_6[6];
+} settings;
+
+#seekto 0xc0;
+struct zoneinfo zoneinfo;
+
+#seekto 0x0D42;
+struct {
+ ul16 chnum;
+ ul16 chindex[1027];
+} channeldata;
+
+#seekto 0x154a;
+struct {
+ char alias[14];
+ u8 chmode:4,
+ chpro:4;
+ u8 fixedpower:1,
+ fixedbandwidth:1,
+ tailelimination: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,
+ companding:1,
+ scramble:1,
+ offlineorreversal:2,
+ rev_3:3;
+ u8 voxthreshold:4,
+ voxdelaytime:4;
+ u8 autoscan:1,
+ scanlist:7;
+ u8 alarmlist;
+ u8 rev_4:2,
+ pttidtype:2,
+ dtmfsignalinglist:4;
+ ul16 dtmfcallid;
+ u8 reserve[3];
+} channels[1027];
+
+#seekto 0xb5c2;
+struct scaninfo scans;
+
+#seekto 0xc3e4;
+struct vfoscaninfo vfoscans;
+
+#seekto 0xc444;
+struct alarminfo alarms;
+
+#seekto 0xc848;
+struct dtmfinfo dtmfinfos;
+
+"""
+
+
+class HandshakeStatuses(Enum):
+ Normal = 0
+ Wrong = 1
+ PwdWrong = 3
+ RadioWrong = 4
+ NoResponse = 5
+
+
+DTMFCHARSET = "0123456789ABCDabcd#*"
+NAMECHARSET = chirp_common.CHARSET_ALPHANUMERIC + "-/;,._!? *#@$%&+=/<>~(){}]'"
+SPECIAL_MEMORIES = {"VFOA": -2, "VFOB": -1}
+MODES = ["NFM", "FM", "AM"]
+POWER_LEVELS = [
+ chirp_common.PowerLevel("Low", watts=5),
+ chirp_common.PowerLevel("High", watts=50)]
+TIMEOUTTIMER_LIST = [{"name": "%ss" % (x * 5), "id": x}
+ for x in range(1, 64, 1)]
+TOTPERMISSIONS_LIST = ["Always", "CTCSS/DCS Match",
+ "Channel Free", "Receive Only"]
+SQUELCHLEVEL_LIST = ["AlwaysOpen", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
+AUTOSCAN_LIST = ["OFF", "Auto Scan System"]
+OFFLINE_REVERSAL_LIST = ["OFF", "Freq Reversal", "Talk Around"]
+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": "Prog PTT", "id": 31}]
+FREQ_STEP_List = [
+ {"name": "2.5kHz", "id": 2500},
+ {"name": "5kHz", "id": 5000},
+ {"name": "6.25kHz", "id": 6250},
+ {"name": "8.33kHz", "id": 8330},
+ {"name": "10kHz", "id": 10000},
+ {"name": "12.5kHz", "id": 12500},
+ {"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:
+ 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"))
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.error(f"download error: {e}")
+ raise errors.RadioError("Unknown error communicating with radio")
+ finally:
+ exit_programming_mode(self)
+
+
+def do_upload(self):
+ error_map = {
+ HandshakeStatuses.RadioWrong: "Radio model mismatch",
+ HandshakeStatuses.PwdWrong: "Radio is password protected"}
+ try:
+ 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"))
+ except errors.RadioError:
+ raise
+ except Exception as e:
+ LOG.error(f"upload error: {e}")
+ raise errors.RadioError("Unknown error communicating with radio")
+ finally:
+ exit_programming_mode(self)
+
+
+def handshake(self, serial):
+ databytes = b""
+ max_retries = 15
+ retry_delay = 0.05
+ for num in range(max_retries):
+ flag, databytes = exchange_block_with_radio(
+ 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 validate_connection_handshake(self, dataByte: bytes):
+ success_status = b"\x00\x01"
+ pwd_faild_flag = 1
+ if dataByte[14:16] != success_status:
+ return HandshakeStatuses.Wrong
+ if dataByte[20] == pwd_faild_flag:
+ return HandshakeStatuses.PwdWrong
+ radioType = dataByte[20: 20 + len(self.current_model)]
+ model_bytes = self.current_model.encode("ascii")
+ if radioType == model_bytes:
+ return HandshakeStatuses.Normal
+ else:
+ return HandshakeStatuses.RadioWrong
+
+
+def exchange_block_with_radio(
+ send_byte: bytes, serial_conn, chunk_size=1050
+) -> tuple[bool, bytes]:
+ serial_conn.write(send_byte)
+ new_bytes = serial_conn.read(chunk_size)
+ if validate_packet(new_bytes):
+ return True, new_bytes
+ return False, new_bytes
+
+
+def validate_packet(current_packet_Byte: bytes, chunk_size=1024):
+ byteLen = len(current_packet_Byte)
+ if byteLen <= 13:
+ LOG.debug(f"Packet too short: {byteLen} bytes")
+ return False
+ """
+ I noticed Retevis has another model
+ that sends 250 bytes per packet,
+ and the total packet count calculation is different.
+ So I added this piece of code to handle
+ that case and make it reusable later.
+ """
+ packet_count = 256 if chunk_size > 255 else chunk_size+1
+ """
+ I noticed that bytes [12:13] always equal len(current_page_byte) - 17.
+ By adding this length check, we can filter out garbage data
+ before it even gets to the CRC calculation - should give us a nice
+ performance boost!
+ """
+ data_len = (current_packet_Byte[12] - 6
+ if current_packet_Byte[12] > 6 else 0)
+ data_len += current_packet_Byte[13] * packet_count
+ if byteLen - 17 < data_len:
+ LOG.debug(f"Packet too short: {byteLen} bytes")
+ return False
+ crcBytes = current_packet_Byte[-3:-1]
+ crcStr = calculate_crc16(current_packet_Byte[:-3])
+ return crcBytes == crcStr
+
+
+def get_handshake_bytes(currentModel):
+ handshake_flag = 0
+ send_packet_index = 0
+ send_packet_count = 1
+ data_code = 0 # 0-write
+ return get_send_packet_bytes(
+ handshake_flag, send_packet_index, data_code, send_packet_count,
+ currentModel.encode("ascii").ljust(41, b'\x00'))
+
+
+def get_read_current_packet_bytes(self, item: int, serial, status):
+ packet_count = 1
+ packet_index = 0
+ item_bytes = b""
+ send_packet_index = 0
+ send_packet_count = 1
+ data_code = 2 # 0-write 2-read
+ while packet_index < packet_count:
+ flag, new_data_bytes = exchange_block_with_radio(
+ get_send_packet_bytes(item, send_packet_index,
+ data_code, send_packet_count,
+ struct.pack("<H", packet_index)),
+ serial, self.read_packet_len)
+ if (not flag
+ or (len(new_data_bytes) > 14 and new_data_bytes[14] != item)):
+ raise errors.RadioError("radio reported failure")
+ if packet_index == 0:
+ packet_count, = struct.unpack("<H", new_data_bytes[18:20])
+ status.cur += len(new_data_bytes)
+ self.status_fn(status)
+ item_bytes += new_data_bytes[20:-3]
+ packet_index += 1
+ return item_bytes
+
+
+def write_item_current_page_bytes(self, serial, item_Bytes: bytes,
+ item: int, status):
+ if not item_Bytes:
+ raise ValueError("item_bytes cannot be empty")
+ packet_len = self.write_page_len
+ packet_count = math.ceil(len(item_Bytes) / packet_len)
+ data_code = 0 # 0-write 2-read
+ if packet_count == 0:
+ return True
+ for i in range(0, packet_count):
+ current_packet_bytes = get_send_packet_bytes(
+ item, i, data_code, packet_count,
+ item_Bytes[i * packet_len: (i + 1) * packet_len])
+ flag, new_data_bytes = exchange_block_with_radio(
+ current_packet_bytes,
+ serial, self.read_packet_len)
+ if (not flag
+ or (len(new_data_bytes) > 14 and new_data_bytes[14] != item)):
+ raise errors.RadioError("radio reported failure")
+ status.cur += len(current_packet_bytes)
+ self.status_fn(status)
+
+
+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
+ """
+ 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):
+ serial = self.pipe
+ """
+ exiting read/write mode and reboot radio
+ """
+ reboot_sign = 111
+ packet_index = 0
+ data_code = 0 # 0-write 2-read
+ packet_count = 1
+ data_buffer = b'\x00'
+ try:
+ serial.write(get_send_packet_bytes(reboot_sign,
+ packet_index, data_code,
+ packet_count, data_buffer))
+ except Exception as e:
+ LOG.debug(
+ f"Radio refused to exit programming mode:{e}")
+ raise errors.RadioError(
+ "Radio refused to exit programming mode")
+
+
+def get_send_packet_bytes(data_type: int, packet_index: int,
+ data_code: int, packet_count: int,
+ data_buffer: bytes):
+ data_len = len(data_buffer)
+ data_part = struct.pack(f'<12sHBBHH{data_len}s',
+ b"RDTP\x01\x00\x00\x00\x00\x00\x00\x00",
+ data_len + 6,
+ data_type & 0xFF,
+ data_code & 0xFF, # 0-write 2-read
+ packet_index & 0xFFFF,
+ packet_count & 0xFFFF,
+ data_buffer)
+ return data_part + calculate_crc16(data_part) + b"\xff"
+
+
+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):
+ mem.extra = RadioSettingGroup("Extra", "extra")
+ mem.extra.append(
+ RadioSetting(
+ "tottime",
+ "TOT",
+ RadioSettingValueList(
+ get_namedict_by_items(TIMEOUTTIMER_LIST),
+ current_index=(_mem.tottime - 1))))
+ mem.extra.append(
+ RadioSetting(
+ "totpermissions",
+ "TX Permissions",
+ RadioSettingValueList(TOTPERMISSIONS_LIST,
+ current_index=_mem.totpermissions)))
+ mem.extra.append(
+ RadioSetting(
+ "rxsqlmode",
+ "Squelch Level",
+ RadioSettingValueList(SQUELCHLEVEL_LIST,
+ current_index=_mem.rxsqlmode)))
+ mem.extra.append(
+ RadioSetting(
+ "autoscan",
+ "Auto Scan System",
+ RadioSettingValueList(AUTOSCAN_LIST,
+ 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,
+ current_index=_mem.offlineorreversal)))
+ mem.extra.append(
+ RadioSetting(
+ "vox", "VOX",
+ RadioSettingValueBoolean(_mem.vox)))
+ mem.extra.append(
+ RadioSetting(
+ "companding", "Compander",
+ RadioSettingValueBoolean(_mem.companding)))
+ mem.extra.append(
+ RadioSetting("scramble", "Scramble",
+ RadioSettingValueBoolean(_mem.scramble)))
+ ch_index_dict = get_ch_index(self)
+ if ch_index not in ch_index_dict:
+ mem.freq = 0
+ mem.empty = True
+ return mem
+ mem.freq = _mem.rxfreq
+ mem.name = self.filter_name(str(_mem.alias).rstrip())
+ tx_freq = _mem.txfreq
+ if mem.freq == 0:
+ mem.empty = True
+ return mem
+ if mem.freq == 0xFFFFFFFF:
+ mem.freq = 0
+ mem.empty = True
+ return mem
+ 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 = 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
+ 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 = POWER_LEVELS[(1 if _mem.power == 2 else 0)]
+ if ch_index < 2:
+ mem.immutable += ["name"]
+ return mem
+
+
+def get_model_info(self, model_info):
+ rs_value = RadioSettingValueString(0, 20, self.current_model)
+ rs_value.set_mutable(False)
+ rs = RadioSetting("modelinfo.Machinecode", "Machine Code", rs_value)
+ model_info.append(rs)
+ rs_value = RadioSettingValueString(
+ 0, 100,
+ "136.00000-174.00000, 400.00000-480.00000")
+ rs_value.set_mutable(False)
+ 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
+ opts = ["Low", "Normal", "Strengthen"]
+ common.append(RadioSetting(
+ "settings.micmain", "Mic Main",
+ RadioSettingValueList(opts, current_index=_settings.micmain)))
+ 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(get_radiosetting_by_key(self, _settings,
+ "calltone", "Call Tone",
+ _settings.calltone, opts_dict))
+ common.append(
+ get_radiosetting_by_key(
+ self, _settings, "freqstep", "Frequency Step",
+ _settings.freqstep, FREQ_STEP_List))
+ 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(
+ get_radiosetting_by_key(
+ self, _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(
+ get_radiosetting_by_key(
+ self, _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(
+ get_radiosetting_by_key(
+ self, _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(
+ get_radiosetting_by_key(
+ self, _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(
+ get_radiosetting_by_key(
+ self, _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=get_band_selection(
+ _settings.homeselect, _settings.homeindex)))
+ rs.set_apply_callback(
+ 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_dict = self.get_scan_item_list()
+ common.append(
+ get_radiosetting_by_key(
+ self, _settings, "scanlist", "Enable Scan List",
+ _settings.scanlist, opts_dict))
+ short_dict = SIDE_KEY_LIST[:12]
+ common.append(
+ get_radiosetting_by_key(
+ self, _settings, "tk1_short", "Top Key Short Press",
+ _settings.tk1_short, short_dict))
+ common.append(
+ get_radiosetting_by_key(
+ self, _settings, "tk1_long", "Top Key Long Press",
+ _settings.tk1_long, short_dict))
+ common.append(
+ get_radiosetting_by_key(
+ self, _settings, "sk1_short", "Short Press Side Key 1",
+ _settings.sk1_short, short_dict))
+ common.append(
+ get_radiosetting_by_key(
+ self, _settings, "sk1_long", "Long Press Side Key 1",
+ _settings.sk1_long, SIDE_KEY_LIST))
+ common.append(
+ get_radiosetting_by_key(
+ self, _settings, "sk2_short", "Short Press Side Key 2",
+ _settings.sk2_short, short_dict))
+ common.append(
+ get_radiosetting_by_key(
+ self, _settings, "sk2_long", "Long Press Side Key 2",
+ _settings.sk2_long, 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)))
+ common.append(
+ RadioSetting(
+ "settings.tailsoundeliminationswitch",
+ "Tail Elimination Switch",
+ RadioSettingValueBoolean(_settings.tailsoundeliminationswitch)))
+ common.append(
+ RadioSetting(
+ "settings.rogerbeep", "Roger Beep",
+ RadioSettingValueBoolean(_settings.rogerbeep)))
+ 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)))
+
+
+def get_dtmf_setting(self, dtmf):
+ _dtmf_comm = self._memobj.dtmfinfos.dtmfcomm
+ opts = ["OFF"] + ["%ss" % x for x in range(1, 16, 1)]
+ dtmf.append(
+ RadioSetting(
+ "dtmfsetting.autoresettime",
+ "Auto Reset Time",
+ RadioSettingValueList(opts,
+ current_index=_dtmf_comm.autoresettime)))
+ opts = [{"name": "Stun TX", "id": 1}, {"name": "Stun TX/RX", "id": 2}]
+ dtmf.append(
+ get_radiosetting_by_key(
+ self, _dtmf_comm, "stunmode",
+ "Stun Type", _dtmf_comm.stunmode, opts))
+ opts = ["300ms", "550ms", "800ms", "1050ms"]
+ dtmf.append(
+ RadioSetting(
+ "dtmfsetting.codedelaytime", "Digit Delay",
+ RadioSettingValueList(opts,
+ current_index=_dtmf_comm.codedelaytime)))
+ opts = ["OFF", "BOT", "EOT", "Both"]
+ dtmf.append(
+ RadioSetting(
+ "dtmfsetting.pttidtype", "PTT ID Type",
+ RadioSettingValueList(opts,
+ current_index=_dtmf_comm.pttidtype)))
+ dtmf.append(
+ RadioSetting(
+ "dtmfsetting.showani", "Show ANI",
+ RadioSettingValueBoolean(_dtmf_comm.showani)))
+ dtmf.append(
+ RadioSetting(
+ "dtmfsetting.sidetone", "Side Tone",
+ RadioSettingValueBoolean(_dtmf_comm.sidetone)))
+ dtmf.append(
+ RadioSetting(
+ "dtmfsetting.callid", "Call ID",
+ RadioSettingValueString(
+ 0, 10,
+ "".join(filter(_dtmf_comm.callid, DTMFCHARSET, 10, True)),
+ False, DTMFCHARSET)))
+ dtmf.append(
+ RadioSetting(
+ "dtmfsetting.stunid", "Stun ID",
+ RadioSettingValueString(
+ 0, 10,
+ "".join(filter(_dtmf_comm.stunid, DTMFCHARSET, 10, True)),
+ False, DTMFCHARSET)))
+ dtmf.append(
+ RadioSetting(
+ "dtmfsetting.revive", "Revive ID",
+ RadioSettingValueString(
+ 0, 10,
+ "".join(filter(_dtmf_comm.revive, DTMFCHARSET, 10, True)),
+ False, DTMFCHARSET)))
+ dtmf.append(
+ RadioSetting(
+ "dtmfsetting.bot", "BOT",
+ RadioSettingValueString(
+ 0, 16,
+ "".join(filter(_dtmf_comm.bot, DTMFCHARSET, 16, True)),
+ False, DTMFCHARSET)))
+ dtmf.append(
+ RadioSetting(
+ "dtmfsetting.eot", "EOT",
+ RadioSettingValueString(
+ 0, 16,
+ "".join(filter(_dtmf_comm.eot, DTMFCHARSET, 16, True)),
+ False, DTMFCHARSET)))
+
+
+def get_vfo_scan(self, vfoscan):
+ _vfo_scan = self._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", "Starting Frequency"]
+ vfoscan.append(
+ RadioSetting(
+ "vfoscan.startcondition", "Start Condition",
+ RadioSettingValueList(opts,
+ current_index=_vfo_scan.startcondition)))
+
+ freq_start = from_MHz(_vfo_scan.vhffreq_start)
+ vfoscan.append(
+ RadioSetting(
+ "vfoscan.vhffreq_start", "Start Frequency",
+ RadioSettingValueFloat(108, 480, freq_start, 0.00001, 5)))
+
+ freq_end = from_MHz(_vfo_scan.vhffreq_end)
+ vfoscan.append(
+ RadioSetting(
+ "vfoscan.vhffreq_end", "End Frequency",
+ RadioSettingValueFloat(108, 480, freq_end, 0.00001, 5)))
+
+
+def _set_memory(self, mem, _mem, ch_index):
+ ch_index_dict = get_ch_index(self)
+ rx_freq = get_ch_rxfreq(mem)
+ flag = ch_index not in ch_index_dict and rx_freq != 0
+ if rx_freq != 0xFFFFFFFF and flag:
+ 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:
+ return
+ _mem.rxfreq = rx_freq
+ _mem.alias = mem.name.ljust(14)
+ txfrq = (int(rx_freq - mem.offset)
+ if mem.duplex == "-" and mem.offset > 0
+ else (int(rx_freq + mem.offset)
+ if mem.duplex == "+" and mem.offset > 0
+ else rx_freq))
+ _mem.txfreq = txfrq
+ _mem.bandwidth = 3 if mem.mode == "FM" else 1
+ if mem.power in POWER_LEVELS:
+ _mem.power = 2 if 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
+ rxtone_value = int(rxtone * 10)
+ _mem.rxctc = rxtone_value
+ elif rxmode == "DTCS":
+ _mem.rxctcvaluetype = rxpol == "R" and 3 or 2
+ oct_value = int(str(rxtone), 8)
+ _mem.rxctc = oct_value
+ else:
+ _mem.rxctcvaluetype = 0
+ if txmode == "Tone":
+ _mem.txctcvaluetype = 1
+ txtone_value = int(txtone * 10)
+ _mem.txctc = txtone_value
+ elif txmode == "DTCS":
+ _mem.txctcvaluetype = txpol == "R" and 3 or 2
+ oct_value = int(str(txtone), 8)
+ _mem.txctc = oct_value
+ else:
+ _mem.txctcvaluetype = 0
+ for setting in mem.extra:
+ 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
+
+
+def get_radiosetting_by_key(self, _setting, item_key,
+ item_display_name, item_value,
+ opts_dict, callback=None):
+ opts = get_namedict_by_items(opts_dict)
+ item = RadioSetting(
+ item_key, item_display_name,
+ RadioSettingValueList(
+ 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)
+ return item
+
+
+def get_namedict_by_items(items):
+ return [x["name"] for x in items]
+
+
+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):
+ item_value = get_item_by_name(items, set_item.value)
+ setattr(obj, name, item_value)
+
+
+def get_item_by_name(items, name):
+ return next(
+ (item["id"] for item in items if item["name"] == name),
+ items[0]["id"] if items else 0)
+
+
+def get_band_selection(band_value, band_index):
+ return (
+ (3 if band_value >= 3 else 1)
+ if band_index >= 1
+ else (2 if band_value >= 3 else 0))
+
+
+def get_ch_index(self):
+ if self._ch_cache is None:
+ ch_data = self._memobj.channeldata
+ self._ch_cache = []
+ seen = set()
+ for i in range(ch_data.chnum):
+ ch_index = int(ch_data.chindex[i])
+ if ch_index != 0xFFFF and ch_index not in seen:
+ seen.add(ch_index)
+ self._ch_cache.append(ch_index)
+ return self._ch_cache
+
+
+def set_ch_index(self, ch_index_list):
+ if not isinstance(ch_index_list, list):
+ raise TypeError("ch_index must be a list")
+ ch_index_list = sorted(int(x) for x in ch_index_list)
+ _ch_data = self._memobj.channeldata
+ ch_num = len(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(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()
+
+
+def get_ch_rxfreq(mem):
+ if mem.empty:
+ return 0
+ ch_freq = (mem.freq // 10) * 10
+ if mem.freq == 0:
+ return mem.freq
+ elif mem.freq < 108000000:
+ ch_freq = 108000000
+ elif mem.freq > 174000000 and mem.freq < 400000000:
+ ch_freq = 174000000
+ elif mem.freq > 480000000:
+ ch_freq = 480000000
+ return ch_freq
+
+
+def set_band_selection(set_item, obj,
+ opts, home_select_field_name,
+ home_index_field_name):
+ value = opts.index(set_item.value)
+ value_mapping = {3: (1, 3), 2: (0, 3), 1: (1, 2), 0: (0, 1)}
+ home_index, home_select = value_mapping.get(value, (0, 1))
+ setattr(obj, home_index_field_name, home_index)
+ setattr(obj, home_select_field_name, home_select)
+
+
+def filter(s, char_set, max_length=10, is_upper=False):
+ s_ = ""
+ input_len = len(s)
+ for i in range(0, min(max_length, input_len)):
+ c = str(s[i])
+ if is_upper:
+ c = c.upper()
+ s_ += c if c in char_set else ""
+ 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"""
+
+ VENDOR = "Retevis"
+ MODEL = "HA1G"
+ BAUD_RATE = 115200
+ 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()
+ rf.valid_special_chans = sorted(SPECIAL_MEMORIES.keys())
+ rf.memory_bounds = (1, 256) # Channel range
+ rf.has_ctone = True
+ rf.has_rx_dtcs = True
+ rf.has_dtcs = True
+ rf.has_cross = True
+ 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
+ rf.valid_skips = []
+ rf.valid_tuning_steps = []
+ rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + "".join(
+ c for c in "-/;,._!? *#@$%&+=/<>~(){}]'"
+ if c not in chirp_common.CHARSET_UPPER_NUMERIC)
+ rf.has_settings = True
+ rf.valid_modes = MODES
+ rf.valid_power_levels = POWER_LEVELS
+ rf.has_comment = True
+ rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
+ rf.valid_cross_modes = [
+ "Tone->Tone",
+ "Tone->DTCS",
+ "DTCS->Tone",
+ "->Tone",
+ "->DTCS",
+ "DTCS->",
+ "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_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:
+ 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)
+
+ def sync_out(self):
+ """Upload to radio"""
+ 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
+ if isinstance(number, str):
+ mem.extd_number = number
+ ch_index = 0 if number == "VFOA" else 1
+ mem.number = len(self._memobj.channels) + ch_index + 1
+ elif number > len(self._memobj.channels):
+ mem.extd_number = (
+ number - len(self._memobj.channels) == 1 and "VFOA" or "VFOB")
+ number = mem.extd_number
+ ch_index = 0 if number == "VFOA" else 1
+ else:
+ ch_index = number + 2
+ mem.number = number
+ _mem = self._memobj.channels[ch_index]
+ mem = _get_memory(self, mem, _mem, ch_index)
+ if ch_index > 2 and ch_index < 33:
+ mem.immutable = ["empty", "freq", "duplex", "offset"]
+ if ch_index >= 10 and ch_index < 17:
+ mem.immutable += ["mode", "power"]
+ return mem
+
+ def set_memory(self, mem):
+ ch_index = 0
+ if mem.number > len(self._memobj.channels):
+ ch_index = 0 if mem.extd_number == "VFOA" else 1
+ else:
+ ch_index = mem.number + 2
+ _mem = self._memobj.channels[ch_index]
+ if ch_index < 33 and mem.freq == 0:
+ return
+ _set_memory(self, mem, _mem, ch_index)
+
+ def get_raw_memory(self, number):
+ if isinstance(number, str):
+ ch_index = 0 if number == "VFOA" else 1
+ else:
+ ch_index = number + 2
+ _mem = self._memobj.channels[ch_index]
+ return repr(_mem)
+
+ def get_settings(self):
+ ModelInfo = RadioSettingGroup("info", "Model Information")
+ common = RadioSettingGroup("basic", "Common Settings")
+ dtmf = RadioSettingGroup("dtmfe", "DTMF Settings")
+ vfoscan = RadioSettingGroup("vfoscan", "VFO Scan")
+ setmode = RadioSettings(ModelInfo, common, dtmf, vfoscan)
+ try:
+ get_model_info(self, ModelInfo)
+ get_common_setting(self, common)
+ get_dtmf_setting(self, dtmf)
+ get_vfo_scan(self, vfoscan)
+ 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:]
+ _settings = self._memobj.settings
+ setattr(_settings, name, value)
+ elif name.startswith("dtmfsetting."):
+ name = name[12:]
+ _dtmfcomm = self._memobj.dtmfinfos.dtmfcomm
+ if (name in ["callid", "stunid", "revive"]):
+ value = filter(value, DTMFCHARSET, 10, True)
+ value = value.ljust(10, "\x00")
+ elif name in ["bot", "eot"]:
+ value = filter(value, 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 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):
+ """Retevis HA1UV"""
+
+ MODEL = "HA1UV"
+ current_model = "HA1UV"
+
+ def get_features(self):
+ rf = super().get_features()
+ rf.memory_bounds = (1, 1024) # Channel range
+ return rf
+
+ def validate_memory(self, mem):
+ return super().validate_memory(mem)
+
+ def get_memory(self, number):
+ mem = chirp_common.Memory()
+ ch_index = 0
+ if isinstance(number, str):
+ mem.extd_number = number
+ ch_index = 0 if number == "VFOA" else 1
+ mem.number = len(self._memobj.channels) + ch_index + 1
+ elif number > len(self._memobj.channels):
+ mem.extd_number = (
+ number - len(self._memobj.channels) == 1 and "VFOA" or "VFOB")
+ number = mem.extd_number
+ ch_index = 0 if number == "VFOA" else 1
+ else:
+ ch_index = number + 2
+ mem.number = number
+ _mem = self._memobj.channels[ch_index]
+ return _get_memory(self, mem, _mem, ch_index)
+
+ def set_memory(self, mem):
+ ch_index = 0
+ if mem.number > len(self._memobj.channels):
+ ch_index = 0 if mem.extd_number == "VFOA" else 1
+ else:
+ ch_index = mem.number + 2
+ _mem = self._memobj.channels[ch_index]
+ if ch_index < 2 and mem.freq == 0:
+ return
+ _set_memory(self, mem, _mem, ch_index)
+ LOG.debug("Setting %i(%s)" % (mem.number, mem.extd_number))
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..8d8c93a 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)
diff --git a/chirp/drivers/retevis_ra86.py b/chirp/drivers/retevis_ra86.py
index c0e1087..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")
@@ -238,21 +238,6 @@ def do_upload(radio):
_exit_programming_mode(radio)
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
-
-
@directory.register
class RA86Radio(chirp_common.CloneModeRadio):
"""RETEVIS RA86"""
@@ -409,8 +394,8 @@ class RA86Radio(chirp_common.CloneModeRadio):
# TX freq set
offset = (int(_mem.txfreq)) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.txfreq)):
+ if chirp_common.is_split(self.get_features().valid_bands,
+ mem.freq, int(_mem.txfreq)):
mem.duplex = "split"
mem.offset = int(_mem.txfreq)
elif offset < 0:
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 a2bd607..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:")
@@ -280,21 +275,6 @@ def do_upload(radio):
_rb15_exit_programming_mode(radio)
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
-
-
class RB15RadioBase(chirp_common.CloneModeRadio):
"""RETEVIS RB15 BASE"""
VENDOR = "Retevis"
@@ -359,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
@@ -490,8 +472,8 @@ class RB15RadioBase(chirp_common.CloneModeRadio):
# TX freq set
offset = (int(_mem.txfreq) * 10) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.txfreq) * 10):
+ 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:
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..4e13023 100644
--- a/chirp/drivers/retevis_rb28.py
+++ b/chirp/drivers/retevis_rb28.py
@@ -168,7 +168,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")
@@ -377,7 +377,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')
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_rt21.py b/chirp/drivers/retevis_rt21.py
index 662a377..f0c05b1 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;
"""
@@ -555,6 +564,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"]
@@ -645,7 +655,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 +893,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 +1082,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 +1307,7 @@ class RT21Radio(chirp_common.CloneModeRadio):
if mem.empty:
if self.MODEL in ["RB23",
"RB26",
+ "RB626",
"RT40B",
"RT76",
"RT86",
@@ -1519,6 +1539,7 @@ class RT21Radio(chirp_common.CloneModeRadio):
if self.MODEL in ["AR-63",
"RB23",
"RB26",
+ "RB626",
"RT19",
"RT40B",
"RT76",
@@ -1527,11 +1548,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 +1613,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 +1644,7 @@ class RT21Radio(chirp_common.CloneModeRadio):
if self.MODEL in ["RB23",
"RB26",
+ "RB626",
"RT86",
"RB89",
"RT86S",
@@ -1687,8 +1717,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 +1736,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 +1779,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 +2078,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 +2194,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 +2226,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 +2347,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 +2578,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 +2605,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
diff --git a/chirp/drivers/retevis_rt22.py b/chirp/drivers/retevis_rt22.py
index cbbacd6..7930a81 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 radio keeps opening 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(
+ "Announces the channel number out loud in the selected language "
+ "each time you change channel. Useful on a radio without a "
+ "display. Off silences the announcements.")
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. OFF disables VOX.")
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 dozing the receiver once no "
+ "signal has been received for a few seconds. It considerably "
+ "extends battery life, at the cost of occasionally clipping the "
+ "first moment of an incoming transmission.")
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 434aac6..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)
@@ -338,21 +340,6 @@ def model_match(cls, data):
return False
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
-
-
@directory.register
class RT23Radio(chirp_common.CloneModeRadio):
"""RETEVIS RT23"""
@@ -416,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
@@ -499,8 +488,8 @@ class RT23Radio(chirp_common.CloneModeRadio):
# TX freq set
offset = (int(_mem.txfreq) * 10) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.txfreq) * 10):
+ 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:
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..db928af 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":
diff --git a/chirp/drivers/retevis_rt87.py b/chirp/drivers/retevis_rt87.py
index a1d476f..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")
@@ -317,21 +321,6 @@ def _upload(radio):
radio.pipe.write(b"E")
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
-
-
class Rt87BaseRadio(chirp_common.CloneModeRadio):
VENDOR = "Retevis"
MODEL = "RT87 Base"
@@ -385,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
@@ -491,8 +482,8 @@ class Rt87BaseRadio(chirp_common.CloneModeRadio):
# TX freq set
offset = (int(_mem.tx_freq) * 10) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.tx_freq) * 10):
+ if chirp_common.is_split(self.get_features().valid_bands,
+ mem.freq, int(_mem.tx_freq) * 10):
mem.duplex = "split"
mem.offset = int(_mem.tx_freq) * 10
elif offset < 0:
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/tdh8.py b/chirp/drivers/tdh8.py
index 5c2916a..0cc753b 100644
--- a/chirp/drivers/tdh8.py
+++ b/chirp/drivers/tdh8.py
@@ -106,14 +106,10 @@ struct {
} settings;
//#seekto 0x0CB8;
-struct {
- u8 ofseta[4];
-} aoffset;
-
-//#seekto 0x0CBC;
-struct {
- u8 ofsetb[4];
-} boffset;
+struct{
+ lbcd a[4];
+ lbcd b[4];
+}vfo_offset;
#seekto 0x0CD8;
struct{
@@ -154,7 +150,7 @@ struct {
lowpower:2,
wide:1,
unused8:1,
- offset:2;
+ dira:2;
u8 unused10;
} vfoa;
@@ -177,7 +173,7 @@ struct {
lowpowerb:2,
wideb:1,
unused8:1,
- offsetb:2;
+ dirb:2;
u8 unused10;
} vfob;
@@ -371,14 +367,10 @@ struct {
} settings;
//#seekto 0x0CB8;
-struct {
- u8 ofseta[4];
-} aoffset;
-
-//#seekto 0x0CBC;
-struct {
- u8 ofsetb[4];
-} boffset;
+struct{
+ lbcd a[4];
+ lbcd b[4];
+}vfo_offset;
#seekto 0x0CD8;
struct{
@@ -484,7 +476,7 @@ struct {
lowpower:2,
wide:1,
unused8:1,
- offset:2;
+ dira:2;
u8 unused10;
} vfoa;
@@ -507,7 +499,7 @@ struct {
lowpowerb:2,
wideb:1,
unused8:1,
- offsetb:2;
+ dirb:2;
u8 unused10;
} vfob;
@@ -602,13 +594,9 @@ struct {
//#seekto 0x0CB8;
struct {
- u8 ofseta[4];
-} aoffset;
-
-//#seekto 0x0CBC;
-struct {
- u8 ofsetb[4];
-} boffset;
+lbcd a[4];
+lbcd b[4];
+}vfo_offset;
#seekto 0x0CD8;
struct{
@@ -656,7 +644,7 @@ struct {
lowpower:2,
wide:1,
unused8:1,
- offset:2;
+ dira:2;
u8 unused9;
} vfoa;
@@ -679,7 +667,7 @@ struct {
lowpowerb:2,
wideb:1,
unused8:1,
- offsetb:2;
+ dirb:2;
u8 unused9;
} vfob;
@@ -722,7 +710,9 @@ VFOA_NAME = ["rxfreqa",
"bcl",
"lowpower",
"wide",
- "offset"]
+ "a",
+ "dira",
+ ]
VFOB_NAME = ["rxfreqb",
"txfreq",
@@ -733,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"]
@@ -769,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"]
@@ -801,18 +788,12 @@ H3_LIST = ["TD-H3", "TD-H3-HAM", "TD-H3-GMRS"]
GMRS_FREQS = bandplan_na.ALL_GMRS_FREQS
-NOAA_FREQS = [162550000, 162400000, 162475000, 162425000, 162450000,
- 162500000, 162525000, 161650000, 161775000, 161750000,
- 162000000]
-
-HAM_GMRS_NAME = ["NOAA 1", "NOAA 2", "NOAA 3", "NOAA 4", "NOAA 5", "NOAA 6",
- "NOAA 7", "NOAA 8", "NOAA 9", "NOAA 10", "NOAA 11"]
-
ALL_MODEL = H8_LIST + H3_LIST + ["RT-730"]
-TD_H8 = b"\x50\x56\x4F\x4A\x48\x1C\x14"
-TD_H3 = b"\x50\x56\x4F\x4A\x48\x5C\x14"
-RT_730 = b"\x50\x47\x4F\x4A\x48\xC3\x44"
+TD_H8 = b'PVOJH\x1c\x14'
+TD_H3 = b'PVOJH\x5c\x14'
+RT_730 = b'PGOJH\xc3D'
+TD_H8_G3 = b'PVOJH<\x14'
def _do_status(radio, block):
@@ -851,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")
@@ -904,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)
@@ -1025,12 +1012,26 @@ class TDH8(chirp_common.CloneModeRadio):
@classmethod
def detect_from_serial(cls, pipe):
- ident = _do_ident(pipe, cls._idents[0])
- for rclass in cls.detected_models():
- if rclass.ident_mode == ident:
- return rclass
- LOG.error('No model match found for %r', ident)
- raise errors.RadioError('Unsupported model')
+ # Build a list of unique idents and the classes that go with each
+ uniq_idents = {}
+ for cls in cls.detected_models():
+ uniq_idents.setdefault(cls._idents[0], [])
+ uniq_idents[cls._idents[0]].append(cls)
+
+ # Try each ident and if one matches then determine the appropriate
+ # class to use
+ for ident, classes in uniq_idents.items():
+ try:
+ radio_ident = _do_ident(pipe, ident)
+ except errors.RadioError:
+ continue
+ for rclass in classes:
+ if rclass.ident_mode == radio_ident:
+ return rclass
+ LOG.error('No model match found for ident query %r response %r',
+ ident, radio_ident)
+ raise errors.RadioError('Unsupported model')
+ raise errors.RadioNoResponse()
@classmethod
def get_prompts(cls):
@@ -1090,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)
@@ -1173,9 +1176,6 @@ class TDH8(chirp_common.CloneModeRadio):
mem.name += str(char)
mem.name = mem.name.rstrip()
- if self.ident_mode != b'P31183\xff\xff' and \
- (mem.number >= 189 and mem.number <= 199):
- mem.name = HAM_GMRS_NAME[mem.number - 200]
# tmode
lin2 = int(_mem.rxtone)
@@ -1221,20 +1221,6 @@ class TDH8(chirp_common.CloneModeRadio):
'duplex', 'offset']
elif mem.number >= 31 and mem.number <= 54:
mem.offset = 5000000
- elif mem.number >= 189 and mem.number <= 199:
- ham_freqs = NOAA_FREQS[mem.number - 189]
- mem.freq = ham_freqs
- mem.immutable = ['name', 'power', 'duplex', 'freq',
- 'rx_dtcs', 'vfo', 'tmode', 'empty',
- 'offset', 'rtone', 'ctone', 'dtcs',
- 'dtcs_polarity', 'cross_mode']
- elif self._ham:
- if mem.number >= 189 and mem.number <= 199:
- ham_freqs = NOAA_FREQS[mem.number - 189]
- mem.freq = ham_freqs
- mem.immutable = ['name', 'power', 'freq', 'rx_dtcs', 'vfo',
- 'tmode', 'empty', 'offset', 'rtone', 'ctone',
- 'dtcs', 'dtcs_polarity', 'cross_mode']
# other function
# pttid
@@ -1362,18 +1348,14 @@ class TDH8(chirp_common.CloneModeRadio):
self._memobj.scanadd[mem.number - 1] = mem.skip != 'S'
for setting in mem.extra:
- if (self.ident_mode == b'P31185\xff\xff' or
- self.ident_mode == b'P31184\xff\xff') and \
+ if self.ident_mode == b'P31184\xff\xff' and \
mem.number >= 189 and mem.number <= 199:
if setting.get_name() == 'pttid':
- setting.value = 'Off'
- setattr(_mem, setting.get_name(), setting.value)
+ setattr(_mem, setting.get_name(), 0)
elif setting.get_name() == 'bcl':
- setting.value = 'Off'
- setattr(_mem, setting.get_name(), setting.value)
+ setattr(_mem, setting.get_name(), 0)
elif setting.get_name() == 'freqhop':
- setting.value = 'Off'
- setattr(_mem, setting.get_name(), setting.value)
+ setattr(_mem, setting.get_name(), 0)
else:
setattr(_mem, setting.get_name(), setting.value)
@@ -1397,8 +1379,6 @@ class TDH8(chirp_common.CloneModeRadio):
def _get_settings(self):
_settings = self._memobj.settings
_press = self._memobj.press
- _aoffset = self._memobj.aoffset
- _boffset = self._memobj.boffset
_vfoa = self._memobj.vfoa
_vfob = self._memobj.vfob
if self.MODEL != "RT-730":
@@ -1781,27 +1761,71 @@ class TDH8(chirp_common.CloneModeRadio):
# Offset
# If the offset is 12.345
# Then the data obtained is [0x45, 0x23, 0x01, 0x00]
- a_set_val = _aoffset.ofseta
- a_set_list = len(_aoffset.ofseta) - 1
- real_val = ''
- for i in range(a_set_list, -1, -1):
- real_val += str(a_set_val[i])[2:]
- if real_val == "FFFFFFFF":
- rs = RadioSetting("ofseta", "A Offset Frequency",
- RadioSettingValueString(0, 7, ""))
+ 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.vfo_offset, '%s' % i)
+ if value.get_raw() == b'\xff\xff\xff\xff':
+ offset = 0
+ else:
+ offset = int(value) / 100000
- else:
- real_val = int(real_val)
- real_val = "%i.%05i" % (real_val / 100000, real_val % 100000)
- rs = RadioSetting("ofseta", "A Offset Frequency",
- RadioSettingValueFloat(
- 0.00000, 59.99750, real_val, 0.00001, 5))
- abblock.append(rs)
+ def _apply(setting):
+ 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", "A Offset",
- RadioSettingValueList(
- A_OFFSET, current_index=_vfoa.offset))
- abblock.append(rs)
+ 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]
@@ -1816,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",
@@ -1830,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
@@ -1844,30 +1868,8 @@ class TDH8(chirp_common.CloneModeRadio):
rs = RadioSetting("rxfreqb", "B Channel - Frequency", val1a)
abblock.append(rs)
- # Offset frequency
- # If the offset is 12.345
- # Then the data obtained is [0x45, 0x23, 0x01, 0x00]
- # Need to use the following anonymous function to process data
- b_set_val = _boffset.ofsetb
- b_set_list = len(_boffset.ofsetb) - 1
- real_val = ''
- for i in range(b_set_list, -1, -1):
- real_val += str(b_set_val[i])[2:]
- if real_val == "FFFFFFFF":
- rs = RadioSetting("ofsetb", "B Offset Frequency",
- RadioSettingValueString(0, 7, " "))
- else:
- real_val = int(real_val)
- real_val = "%i.%05i" % (real_val / 100000, real_val % 100000)
- rs = RadioSetting("ofsetb", "B Offset Frequency",
- RadioSettingValueFloat(
- 0.00000, 59.99750, real_val, 0.00001, 5))
- abblock.append(rs)
-
- rs = RadioSetting("offsetb", "B Offset",
- RadioSettingValueList(
- B_OFFSET, current_index=_vfob.offsetb))
- abblock.append(rs)
+ abblock.append(offsets['b'])
+ abblock.append(dirs['b'])
try:
self._tx_power[_vfob.lowpowerb]
@@ -1882,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",
@@ -1896,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)
@@ -1963,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
@@ -2154,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):
@@ -2166,8 +2172,6 @@ class TDH8(chirp_common.CloneModeRadio):
_settings = self._memobj.settings
_press = self._memobj.press
- _aoffset = self._memobj.aoffset
- _boffset = self._memobj.boffset
_vfoa = self._memobj.vfoa
_vfob = self._memobj.vfob
_fmmode = self._memobj.fmmode
@@ -2199,15 +2203,9 @@ class TDH8(chirp_common.CloneModeRadio):
elif name in VFOA_NAME:
obj = _vfoa
setting = element.get_name()
- elif name == "ofseta":
- obj = _aoffset
- setting = element.get_name()
elif name in VFOB_NAME:
obj = _vfob
setting = element.get_name()
- elif name == "ofsetb":
- obj = _boffset
- setting = element.get_name()
elif "block" in name:
obj = _fmmode
setting = element.get_name()
@@ -2269,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'))
@@ -2284,40 +2282,6 @@ class TDH8(chirp_common.CloneModeRadio):
"136.00000-174.00000 or 400.00000-520.00000 "
"or enabled in settings")
raise InvalidValueError(msg)
-
- elif "ofseta" == setting and element.value.get_mutable():
- if '.' in str(element.value):
- val = str(element.value).replace(' ', '')
- if len(
- val[val.index(".") + 1:]
- ) >= 1 and int(val[val.index(".") + 1:]
- ) != 0:
- val = '00' + val.replace('.', '')
- else:
- val = '0' + val.replace('.', '')
- val = val.ljust(8, '0')
- lenth_val = 0
- list_val = []
- else:
- val = '0' + str(element.value).replace(' ', '')
- val = val.ljust(8, '0')
- lenth_val = 0
- list_val = []
- if (int(val) >= 0 and int(val) <= 5999750):
- if int(val) == 0:
- _aoffset.ofseta = [0xFF, 0xFF, 0xFF, 0xFF]
- else:
- while lenth_val < (len(val)):
- list_val.insert(
- 0, val[lenth_val:lenth_val + 2])
- lenth_val += 2
- for i in range(len(list_val)):
- list_val[i] = int(list_val[i], 16)
- _aoffset.ofseta = list_val
- else:
- msg = ("Offset must be between 0.00000-59.99750")
- raise InvalidValueError(msg)
-
# B channel
elif "rxfreqb" == setting and element.value.get_mutable():
val = 0
@@ -2335,40 +2299,6 @@ class TDH8(chirp_common.CloneModeRadio):
"or enabled in settings")
raise InvalidValueError(msg)
# setattr(obj, setting, val)
-
- elif "ofsetb" == setting and element.value.get_mutable():
- if '.' in str(element.value):
- val = str(element.value).replace(' ', '')
- if len(val[val.index(".") + 1:]
- ) >= 1 and int(val[val.index(".") + 1:]
- ) != 0:
- val = '00' + \
- str(element.value).replace('.', '')
- else:
- val = '0' + str(element.value).replace('.', '')
- val = val.ljust(8, '0')
- lenth_val = 0
- list_val = []
- else:
- val = '0' + str(element.value).replace(' ', '')
- val = val.ljust(8, '0')
- lenth_val = 0
- list_val = []
- if (int(val) >= 0 and int(val) <= 5999750):
- if int(val) == 0:
- _boffset.ofsetb = [0xFF, 0xFF, 0xFF, 0xFF]
- else:
- while lenth_val < (len(val)):
- list_val.insert(
- 0, val[lenth_val:lenth_val + 2])
- lenth_val += 2
- for i in range(len(list_val)):
- list_val[i] = int(list_val[i], 16)
- _boffset.ofsetb = list_val
- else:
- msg = ("Offset must be between 0.00000-59.99750")
- raise InvalidValueError(msg)
-
# FM
elif "block" in name:
num = int(name[-2:], 10)
@@ -2720,7 +2650,7 @@ class TDH3_GMRS(TDH3):
msgs = super().validate_memory(mem)
if 31 <= mem.number <= 54 and mem.freq not in GMRS_FREQS:
msgs.append(chirp_common.ValidationError(
- "The frequency in channels 31-54 must be between"
+ "The frequency in channels 31-54 must be between "
"462.55000-462.72500 in 0.025 increments."))
return msgs
@@ -2742,3 +2672,77 @@ class RT730(TDH8):
def process_mmap(self):
self._memobj = bitwise.parse(MEM_FORMAT_RT730, self._mmap)
+
+
+@directory.register
+@directory.detected_by(TDH8)
+class TDH8_3rd_Gen(TDH8):
+ VENDOR = "TIDRADIO"
+ MODEL = "TD-H8"
+ VARIANT = 'G3'
+ _memsize = 0x1fef
+ _ranges_main = [(0x0000, 0x1fef)]
+ _idents = [TD_H8_G3]
+ _txbands = [(136000000, 600000000)]
+ _rxbands = [(18000000, 107999000), (108000000, 136000000)]
+ _aux_block = True
+ _tri_power = True
+ _gmrs = False
+ _ham = False
+ _mem_params = (0x1F2F)
+ _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"]
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(MEM_FORMAT_H3, self._mmap)
+
+
+@directory.register
+@directory.detected_by(TDH8)
+class TDH8_3rd_Gen_HAM(TDH8_3rd_Gen):
+ VENDOR = "TIDRADIO"
+ MODEL = "TD-H8-HAM"
+ ident_mode = b'P31185\xff\xff'
+ _ham = True
+ _txbands = [(144000000, 149000000), (420000000, 451000000)]
+ _rxbands = [(18000000, 107999000), (108000000, 136000000),
+ (149990000, 419990000), (451000000, 600000000)]
+ _tx220 = [(222000000, 225000000)]
+ # leave out 219-220 sub-band because this radio doesn't do
+ # fixed digital message forwarding
+ # tx350 and tx500 bands unknown; add them if you are in a
+ # legal locale and know their correct range
+
+ def get_tx_bands(self):
+ _settings = self._memobj.settings
+ bands = []
+ bands.extend(self._txbands)
+ if _settings.tx220:
+ bands.extend(self._tx220)
+ return bands
+
+
+@directory.register
+@directory.detected_by(TDH8)
+class TDH8_3rd_Gen_GMRS(TDH8_3rd_Gen):
+ VENDOR = "TIDRADIO"
+ MODEL = "TD-H8-GMRS"
+ ident_mode = b'P31184\xff\xff'
+ _gmrs = True
+ _txbands = [(136000000, 175000000), (400000000, 521000000)]
+
+ def validate_memory(self, mem):
+ msgs = super().validate_memory(mem)
+ if 31 <= mem.number <= 54 and mem.freq not in GMRS_FREQS:
+ msgs.append(chirp_common.ValidationError(
+ "The frequency in channels 31-54 must be between "
+ "462.55000-462.72500 in 0.025 increments."))
+ if mem.duplex not in ('', '+', 'off') or (
+ mem.duplex == '+' and mem.offset != 5000000):
+ msgs.append(chirp_common.ValidationError(
+ "Channels in this range must be GMRS frequencies and "
+ "either simplex or +5MHz offset"))
+ return msgs
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 7543961..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):
@@ -406,21 +409,6 @@ def model_match(cls, data):
return False
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
-
-
@directory.register
class TDXoneTDQ8A(chirp_common.CloneModeRadio,
chirp_common.ExperimentalRadio):
@@ -522,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')
@@ -562,8 +552,8 @@ class TDXoneTDQ8A(chirp_common.CloneModeRadio,
# TX freq set
offset = (int(_mem.txfreq) * 10) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.txfreq) * 10):
+ 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:
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..65b0525 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)
@@ -466,6 +460,8 @@ def _ident(radio):
# check if we had EXITO
if exito is False:
+ if not response:
+ raise errors.RadioNoResponse()
msg = "The radio did not accept program mode after five tries.\n"
msg += "Check you interface cable and power cycle your radio."
raise errors.RadioError(msg)
@@ -483,7 +479,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 +504,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/th9800.py b/chirp/drivers/th9800.py
index 5155ec7..b22ab21 100644
--- a/chirp/drivers/th9800.py
+++ b/chirp/drivers/th9800.py
@@ -1,6 +1,7 @@
# Copyright 2014 Tom Hayward <tom@tomh.us>
# Copyright 2014 Jens Jensen <af5mi@yahoo.com>
# Copyright 2014 James Lee N1DDK <jml@jmlzone.com>
+# Copyright 2025 Jim Unroe KC9HI <rock.unroe@gmail.com> add Retevis MA1 support
#
# 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
@@ -27,43 +28,9 @@ from datetime import date
LOG = logging.getLogger(__name__)
-TH9800_MEM_FORMAT = """
-struct mem {
- lbcd rx_freq[4];
- lbcd tx_freq[4];
- lbcd ctcss[2];
- lbcd dtcs[2];
- u8 power:2,
- BeatShift:1,
- unknown0a:2,
- display:1, // freq=0, name=1
- scan:2;
- u8 fmdev:2, // wide=00, mid=01, narrow=10
- scramb:1,
- compand:1,
- emphasis:1,
- unknown1a:2,
- sqlmode:1; // carrier, tone
- u8 rptmod:2, // off, -, +
- reverse:1,
- talkaround:1,
- step:4;
- u8 dtcs_pol:2,
- bclo:2,
- unknown3:2,
- tmode:2;
- lbcd offset[4];
- u8 hsdtype:2, // off, 2-tone, 5-tone, dtmf
- unknown5a:1,
- am:1,
- unknown5b:4;
- u8 unknown6[3];
- char name[6];
- u8 empty[2];
-};
-
+MEM_FORMAT = """
#seekto 0x%04X;
-struct mem memory[800];
+struct mem memory[%d];
#seekto 0x%04X;
struct {
@@ -73,12 +40,23 @@ struct {
#seekto 0x%04X;
struct {
+ u8 unk0xdb07_7:1,
+ vox:3,
+ unk0xdb07_1:3,
+ txanc:1;
+ u8 unk0xdb08[8];
+ u8 unk0xdb10[16];
u8 unk0xdc20:5,
left_sql:3;
u8 apo;
- u8 unk0xdc22:5,
- backlight:3;
- u8 unk0xdc23;
+ u8 unk0xdc22:4,
+ backlight:4;
+ u8 mdf:1, //bit 7 is mdf 0=freq, 1=name
+ unk0xdc23_5:2,
+ dtmf_keylock:1,
+ auto_brightness:1,
+ repeater_mode:2,
+ unk0xdc23_0:1;
u8 beep:1,
keylock:1,
pttlock:2,
@@ -87,7 +65,7 @@ struct {
right_func_key:1;
u8 tbst_freq:2,
ani_display:1,
- unk0xdc25_4:1,
+ non_subvoice_tail:1,
mute_mode:2,
unk0xdc25_10:2;
u8 auto_xfer:1,
@@ -97,12 +75,11 @@ struct {
unk0xdc26_210:3;
u8 unk0xdc27_76543:5,
scan_mode:1,
- unk0xdc27_1:1,
- scan_resume:1;
+ scan_resume:2;
u16 scramb_freq;
u16 scramb_freq1;
u8 exit_delay;
- u8 unk0xdc2d;
+ u8 mic_gain;
u8 unk0xdc2e:5,
right_sql:3;
u8 unk0xdc2f:4,
@@ -119,6 +96,11 @@ struct {
u8 p2;
u8 p3;
u8 p4;
+ u8 pnl_band;
+ u8 pnl_ctrl;
+ u8 pnl_m;
+ u8 unk0xdcef;
+ char screen_text[6];
} settings;
#seekto 0x%04X;
@@ -148,24 +130,14 @@ struct {
"""
-BLANK_MEMORY = "\xFF" * 8 + "\x00\x10\x23\x00\xC0\x08\x06\x00" \
- "\x00\x00\x76\x00\x00\x00" + "\xFF" * 10
DTCS_POLARITY = ["NN", "RN", "NR", "RR"]
-SCAN_MODES = ["", "S", "P"]
-MODES = ["WFM", "FM", "NFM"]
-TMODES = ["", "Tone", "TSQL", "DTCS"]
-POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5.00),
- chirp_common.PowerLevel("Mid2", watts=10.00),
- chirp_common.PowerLevel("Mid1", watts=20.00),
- chirp_common.PowerLevel("High", watts=50.00)]
-BUSY_LOCK = ["off", "Carrier", "2 tone"]
-MICKEYFUNC = ["None", "SCAN", "SQL.OFF", "TCALL", "PPTR", "PRI", "LOW", "TONE",
- "MHz", "REV", "HOME", "BAND", "VFO/MR"]
SQLPRESET = ["Off", "2", "5", "9", "Full"]
BANDS = ["30 MHz", "50 MHz", "60 MHz", "108 MHz", "150 MHz", "250 MHz",
"350 MHz", "450 MHz", "850 MHz"]
STEPS = [2.5, 5.0, 6.25, 7.5, 8.33, 10.0, 12.5,
15.0, 20.0, 25.0, 30.0, 50.0, 100.0]
+HSDTYPE = ["Off", "2 Tone", "5 Tone", "DTMF"]
+PTTIDMODE = ["Off", "PTTID1", "PTTID2", "PTTID3", "PTTID4", "5 Tone"]
def isValidDate(month, day, year):
@@ -200,6 +172,57 @@ class TYTTH9800Base(chirp_common.Radio):
"""Base class for TYT TH-9800"""
VENDOR = "TYT"
+ _upper = 800
+
+ TH9800_MEM_FORMAT = """
+ struct mem {
+ lbcd rx_freq[4];
+ lbcd tx_freq[4];
+ lbcd ctcss[2];
+ lbcd dtcs[2];
+ u8 power:2,
+ BeatShift:1,
+ unknown0a:2,
+ display:1, // freq=0, name=1
+ scan:2;
+ u8 fmdev:2, // wide=00, mid=01, narrow=10
+ scramb:1,
+ compand:1,
+ emphasis:1,
+ unknown1a:2,
+ sqlmode:1; // carrier, tone
+ u8 rptmod:2, // off, -, +
+ reverse:1,
+ talkaround:1,
+ step:4;
+ u8 dtcs_pol:2,
+ bclo:2,
+ unknown3:2,
+ tmode:2;
+ lbcd offset[4];
+ u8 hsdtype:2, // off, 2-tone, 5-tone, dtmf
+ unknown5a:1,
+ am:1,
+ unknown5b:4;
+ u8 unknown6[3];
+ char name[6];
+ u8 empty[2];
+ };
+ """
+
+ BLANK_MEMORY = "\xFF" * 8 + "\x00\x10\x23\x00\xC0\x08\x06\x00" \
+ "\x00\x00\x76\x00\x00\x00" + "\xFF" * 10
+ SCAN_MODES = ["", "S", "P"]
+ MODES = ["WFM", "FM", "NFM"]
+ TMODES = ["", "Tone", "TSQL", "DTCS"]
+ POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5.00),
+ chirp_common.PowerLevel("Mid2", watts=10.00),
+ chirp_common.PowerLevel("Mid1", watts=20.00),
+ chirp_common.PowerLevel("High", watts=50.00)]
+ BUSY_LOCK = ["off", "Carrier", "2 tone"]
+ MICKEYFUNC = ["None", "SCAN", "SQL.OFF", "TCALL", "PPTR", "PRI", "LOW",
+ "TONE", "MHz", "REV", "HOME", "BAND", "VFO/MR"]
+
def get_features(self):
rf = chirp_common.RadioFeatures()
rf.memory_bounds = (1, 800)
@@ -208,9 +231,9 @@ class TYTTH9800Base(chirp_common.Radio):
rf.valid_tuning_steps = STEPS
rf.can_odd_split = True
rf.valid_duplexes = ["", "-", "+", "split", "off"]
- rf.valid_tmodes = TMODES
+ rf.valid_tmodes = self.TMODES
rf.has_ctone = False
- rf.valid_power_levels = POWER_LEVELS
+ rf.valid_power_levels = self.POWER_LEVELS
rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + "#*-+"
rf.valid_bands = [(26000000, 33000000),
(47000000, 54000000),
@@ -219,17 +242,25 @@ class TYTTH9800Base(chirp_common.Radio):
(350000000, 399995000),
(400000000, 512000000),
(750000000, 950000000)]
- rf.valid_skips = SCAN_MODES
- rf.valid_modes = MODES + ["AM"]
+ rf.valid_skips = self.SCAN_MODES
+ rf.valid_modes = self.MODES + ["AM"]
rf.valid_name_length = 6
rf.has_settings = True
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(
- TH9800_MEM_FORMAT %
- (self._mmap_offset, self._scanlimits_offset, self._settings_offset,
- self._chan_active_offset, self._info_offset), self._mmap)
+ fmt % (self._mmap_offset,
+ self._upper,
+ self._scanlimits_offset,
+ self._settings_offset,
+ self._chan_active_offset,
+ self._info_offset
+ ), self._mmap)
def get_active(self, banktype, num):
"""get active flag for channel active,
@@ -256,6 +287,39 @@ class TYTTH9800Base(chirp_common.Radio):
else:
bank[index] &= ~mask
+ def decode_tone(self, val, tmode):
+ """Parse the tone data to decode from mem, it returns:
+ Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
+ if tmode == 0x00:
+ return '', None, None
+
+ val = int(val)
+ if tmode == 0x03:
+ a = val
+ return 'DTCS', a, 'R'
+ elif tmode == 0x02:
+ a = val
+ return 'DTCS', a, 'N'
+ else:
+ a = val / 10.0
+ return 'Tone', a, None
+
+ def encode_tone(self, memval, mode, value, pol, tmodeval):
+ """Parse the tone data to encode from UI to mem"""
+ if mode == '':
+ memval[0].set_raw(0xFF)
+ memval[1].set_raw(0xFF)
+ tmodeval.set_value(0x00)
+ elif mode == 'Tone':
+ memval.set_value(int(value * 10))
+ tmodeval.set_value(0x01)
+ elif mode == 'DTCS':
+ tmodev = 0x02 if pol == 'N' else 0x03
+ memval.set_value(value)
+ tmodeval.set_value(tmodev)
+ else:
+ raise Exception("Internal error: invalid mode `%s'" % mode)
+
def get_raw_memory(self, number):
return repr(self._memobj.memory[number - 1])
@@ -286,14 +350,19 @@ class TYTTH9800Base(chirp_common.Radio):
mem.duplex = "+"
mem.offset = txfreq - mem.freq
- mem.dtcs_polarity = DTCS_POLARITY[_mem.dtcs_pol]
+ if self.MODEL == "MA1":
+ rxtone = txtone = None
+ txtone = self.decode_tone(_mem.tx_tone, _mem.tx_tmode)
+ rxtone = self.decode_tone(_mem.rx_tone, _mem.rx_tmode)
+ chirp_common.split_tone_decode(mem, txtone, rxtone)
+ else:
+ mem.dtcs_polarity = DTCS_POLARITY[_mem.dtcs_pol]
- mem.tmode = TMODES[int(_mem.tmode)]
- mem.ctone = mem.rtone = int(_mem.ctcss) / 10.0
- mem.dtcs = int(_mem.dtcs)
+ mem.tmode = self.TMODES[int(_mem.tmode)]
+ mem.ctone = mem.rtone = int(_mem.ctcss) / 10.0
+ mem.dtcs = int(_mem.dtcs)
- mem.name = str(_mem.name)
- mem.name = mem.name.replace("\xFF", " ").rstrip()
+ mem.name = self.filter_name(str(_mem.name).rstrip('\x00\x20\xFF'))
if not self.get_active("scan_enable", number):
mem.skip = "S"
@@ -302,30 +371,59 @@ class TYTTH9800Base(chirp_common.Radio):
else:
mem.skip = ""
- mem.mode = _mem.am and "AM" or MODES[int(_mem.fmdev)]
-
- mem.power = POWER_LEVELS[_mem.power]
+ if self.MODEL == "MA1":
+ if _mem.am:
+ mem.mode = 'AM'
+ elif _mem.fmdev == self.CHANNEL_WIDTH_25kHz:
+ mem.mode = 'FM'
+ elif _mem.fmdev == self.CHANNEL_WIDTH_20kHz:
+ LOG.info(
+ '%s: get_mem: promoting 20 kHz channel width to 25 kHz' %
+ mem.name)
+ mem.mode = 'FM'
+ elif _mem.fmdev == self.CHANNEL_WIDTH_12d5kHz:
+ mem.mode = 'NFM'
+ else:
+ LOG.error('%s: get_mem: unhandled channel width: 0x%02x' %
+ (mem.name, _mem.fmdev))
+ else:
+ mem.mode = _mem.am and "AM" or self.MODES[int(_mem.fmdev)]
+
+ if self.MODEL == "MA1":
+ if _mem.power == self.TXPOWER_LOW:
+ mem.power = self.POWER_LEVELS[0]
+ elif _mem.power == self.TXPOWER_MED:
+ mem.power = self.POWER_LEVELS[1]
+ elif _mem.power == self.TXPOWER_HIGH:
+ mem.power = self.POWER_LEVELS[2]
+ else:
+ LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
+ (mem.name, _mem.power))
+ else:
+ mem.power = self.POWER_LEVELS[_mem.power]
mem.tuning_step = STEPS[_mem.step]
mem.extra = RadioSettingGroup("extra", "Extra")
- opts = ["Frequency", "Name"]
- display = RadioSetting(
- "display", "Display",
- RadioSettingValueList(opts, current_index=_mem.display))
- mem.extra.append(display)
+ if not self.MODEL == "MA1":
+ opts = ["Frequency", "Name"]
+ display = RadioSetting(
+ "display", "Display",
+ RadioSettingValueList(opts, current_index=_mem.display))
+ mem.extra.append(display)
bclo = RadioSetting(
"bclo", "Busy Lockout",
- RadioSettingValueList(BUSY_LOCK, current_index=_mem.bclo))
+ RadioSettingValueList(self.BUSY_LOCK, current_index=_mem.bclo))
bclo.set_doc("Busy Lockout")
mem.extra.append(bclo)
- emphasis = RadioSetting(
- "emphasis", "Emphasis",
- RadioSettingValueBoolean(bool(_mem.emphasis)))
- emphasis.set_doc("Boosts 300 Hz to 2500 Hz mic response")
- mem.extra.append(emphasis)
+ if not self.MODEL == "MA1":
+ emphasis = RadioSetting(
+ "emphasis", "Emphasis",
+ RadioSettingValueBoolean(bool(_mem.emphasis)))
+ emphasis.set_doc("Boosts 300 Hz to 2500 Hz mic response")
+ mem.extra.append(emphasis)
compand = RadioSetting(
"compand", "Compand",
@@ -351,6 +449,21 @@ class TYTTH9800Base(chirp_common.Radio):
scramb.set_doc("Frequency inversion Scramble")
mem.extra.append(scramb)
+ if self.MODEL == "MA1":
+ hsdtype = RadioSetting(
+ "hsdtype", "Option Signaling",
+ RadioSettingValueList(
+ HSDTYPE, current_index=_mem.hsdtype))
+ hsdtype.set_doc("Option Signaling")
+ mem.extra.append(hsdtype)
+
+ pttid_mode = RadioSetting(
+ "pttid_mode", "PTTID Mode",
+ RadioSettingValueList(
+ PTTIDMODE, current_index=_mem.pttid_mode))
+ pttid_mode.set_doc("PTTID Mode")
+ mem.extra.append(pttid_mode)
+
return mem
def set_memory(self, mem):
@@ -360,47 +473,64 @@ class TYTTH9800Base(chirp_common.Radio):
self.set_active("chan_active", mem.number, not mem.empty)
if mem.empty or not _prev_active:
LOG.debug("initializing memory channel %d" % mem.number)
- _mem.set_raw(BLANK_MEMORY)
+ _mem.set_raw(self.BLANK_MEMORY)
if mem.empty:
return
+ if self.MODEL == "MA1":
+ _mem.set_raw(self.INIT_MEMORY)
+
_mem.rx_freq = mem.freq / 10
if mem.duplex == "split":
_mem.tx_freq = mem.offset / 10
+ _mem.offset = abs(mem.offset - mem.freq) / 10
elif mem.duplex == "-":
_mem.tx_freq = (mem.freq - mem.offset) / 10
+ _mem.offset = (mem.offset) / 10
elif mem.duplex == "+":
_mem.tx_freq = (mem.freq + mem.offset) / 10
+ _mem.offset = (mem.offset) / 10
elif mem.duplex == "off":
_mem.tx_freq = 0
_mem.offset = 0
else:
_mem.tx_freq = mem.freq / 10
- _mem.tmode = TMODES.index(mem.tmode)
- if mem.tmode == "TSQL" or mem.tmode == "DTCS":
- _mem.sqlmode = 1
+ if self.MODEL == "MA1":
+ ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
+ chirp_common.split_tone_encode(mem)
+ self.encode_tone(_mem.tx_tone, txmode, txtone, txpol,
+ _mem.tx_tmode)
+ self.encode_tone(_mem.rx_tone, rxmode, rxtone, rxpol,
+ _mem.rx_tmode)
else:
- _mem.sqlmode = 0
- _mem.ctcss = mem.rtone * 10
- _mem.dtcs = mem.dtcs
- _mem.dtcs_pol = DTCS_POLARITY.index(mem.dtcs_polarity)
-
- _mem.name = mem.name.ljust(6, "\xFF")
-
- # autoset display to name if filled, else show frequency
- if mem.extra:
- # mem.extra only seems to be populated when called from edit panel
- display = mem.extra["display"]
- else:
- display = None
- if mem.name:
- _mem.display = True
- else:
- _mem.display = False
-
- _mem.scan = SCAN_MODES.index(mem.skip)
+ _mem.tmode = self.TMODES.index(mem.tmode)
+ if mem.tmode == "TSQL" or mem.tmode == "DTCS":
+ _mem.sqlmode = 1
+ else:
+ _mem.sqlmode = 0
+ _mem.ctcss = mem.rtone * 10
+ _mem.dtcs = mem.dtcs
+ _mem.dtcs_pol = DTCS_POLARITY.index(mem.dtcs_polarity)
+
+ pad_char = "\x00" if self.MODEL == "MA1" else "\xFF"
+ _mem.name = mem.name.ljust(6, pad_char)
+
+ if not self.MODEL == "MA1":
+ # autoset display to name if filled, else show frequency
+ if mem.extra:
+ # mem.extra only seems to be populated when called from edit
+ # panel
+ display = mem.extra["display"]
+ else:
+ display = None
+ if mem.name:
+ _mem.display = True
+ else:
+ _mem.display = False
+
+ _mem.scan = self.SCAN_MODES.index(mem.skip)
if mem.skip == "P":
self.set_active("priority", mem.number, True)
self.set_active("scan_enable", mem.number, True)
@@ -411,17 +541,45 @@ class TYTTH9800Base(chirp_common.Radio):
self.set_active("priority", mem.number, False)
self.set_active("scan_enable", mem.number, True)
- if mem.mode == "AM":
- _mem.am = True
- _mem.fmdev = 0
+ if self.MODEL == "MA1":
+ # Set the channel width - remember we promote 20 kHz channels to FM
+ # on import
+ # , so don't handle them here
+ if mem.mode == "AM":
+ _mem.am = True
+ _mem.fmdev = 0
+ elif mem.mode in ["FM", "NFM"]:
+ _mem.am = False
+ if mem.mode == 'FM':
+ _mem.fmdev = self.CHANNEL_WIDTH_25kHz
+ elif mem.mode == 'NFM':
+ _mem.fmdev = self.CHANNEL_WIDTH_12d5kHz
+ else:
+ LOG.error('%s: set_mem: unhandled mode: %s' % (
+ mem.name, mem.mode))
else:
- _mem.am = False
- _mem.fmdev = MODES.index(mem.mode)
-
- if mem.power:
- _mem.power = POWER_LEVELS.index(mem.power)
+ if mem.mode == "AM":
+ _mem.am = True
+ _mem.fmdev = 0
+ else:
+ _mem.am = False
+ _mem.fmdev = self.MODES.index(mem.mode)
+
+ if self.MODEL == "MA1":
+ if mem.power == self.POWER_LEVELS[0]:
+ _mem.power = self.TXPOWER_LOW
+ elif mem.power == self.POWER_LEVELS[1]:
+ _mem.power = self.TXPOWER_MED
+ elif mem.power == self.POWER_LEVELS[2]:
+ _mem.power = self.TXPOWER_HIGH
+ else:
+ LOG.error('%s: set_mem: unhandled power level: %s' %
+ (mem.name, mem.power))
else:
- _mem.power = 0 # low
+ if mem.power:
+ _mem.power = self.POWER_LEVELS.index(mem.power)
+ else:
+ _mem.power = 0 # low
_mem.step = STEPS.index(mem.tuning_step)
for setting in mem.extra:
@@ -441,115 +599,263 @@ class TYTTH9800Base(chirp_common.Radio):
basic.append(RadioSetting(
"beep_vol", "Beep Volume",
RadioSettingValueInteger(0, 15, _settings.beep_vol)))
- basic.append(RadioSetting(
- "keylock", "Key Lock",
- RadioSettingValueBoolean(_settings.keylock)))
+ if not self.MODEL == "MA1":
+ basic.append(RadioSetting(
+ "keylock", "Key Lock",
+ RadioSettingValueBoolean(_settings.keylock)))
basic.append(RadioSetting(
"ani_display", "ANI Display",
RadioSettingValueBoolean(_settings.ani_display)))
basic.append(RadioSetting(
"auto_xfer", "Auto Transfer",
RadioSettingValueBoolean(_settings.auto_xfer)))
- basic.append(RadioSetting(
- "auto_contact", "Auto Contact Always Remind",
- RadioSettingValueBoolean(_settings.auto_contact)))
+ if not self.MODEL == "MA1":
+ basic.append(RadioSetting(
+ "auto_contact", "Auto Contact Always Remind",
+ RadioSettingValueBoolean(_settings.auto_contact)))
basic.append(RadioSetting(
"auto_am", "Auto AM",
RadioSettingValueBoolean(_settings.auto_am)))
- basic.append(RadioSetting(
- "left_sql", "Left Squelch",
- RadioSettingValueList(
- SQLPRESET, current_index=_settings.left_sql)))
- basic.append(RadioSetting(
- "right_sql", "Right Squelch",
- RadioSettingValueList(
- SQLPRESET, current_index=_settings.right_sql)))
+ if not self.MODEL == "MA1":
+ basic.append(RadioSetting(
+ "left_sql", "Left Squelch",
+ RadioSettingValueList(
+ SQLPRESET, current_index=_settings.left_sql)))
+ basic.append(RadioSetting(
+ "right_sql", "Right Squelch",
+ RadioSettingValueList(
+ SQLPRESET, current_index=_settings.right_sql)))
# basic.append(RadioSetting("apo", "Auto Power off (0.1h)",
# RadioSettingValueInteger(0, 20, _settings.apo)))
- opts = ["Off"] + ["%0.1f" % (t / 10.0) for t in range(1, 21, 1)]
+ if self.MODEL == "MA1":
+ opts = ["Off"] + ["%0.1f" % (t / 10.0) for t in range(5, 35, 5)]
+ else:
+ opts = ["Off"] + ["%0.1f" % (t / 10.0) for t in range(1, 21, 1)]
basic.append(RadioSetting(
"apo", "Auto Power off (Hours)",
RadioSettingValueList(opts, current_index=_settings.apo)))
- opts = ["Off", "1", "2", "3", "Full"]
+ if self.MODEL == "MA1":
+ opts = ["Off"] + list("12345678")
+ else:
+ opts = ["Off", "1", "2", "3", "Full"]
basic.append(
RadioSetting(
"backlight", "Display Backlight",
RadioSettingValueList(
opts, current_index=_settings.backlight)))
- opts = ["Off", "Right", "Left", "Both"]
- basic.append(RadioSetting(
- "pttlock", "PTT Lock",
- RadioSettingValueList(opts, current_index=_settings.pttlock)))
- opts = ["Manual", "Auto"]
- basic.append(
- RadioSetting(
- "hyper_chan", "Hyper Channel",
- RadioSettingValueList(
- opts, current_index=_settings.hyper_chan)))
- opts = ["Key 1", "Key 2"]
- basic.append(
- RadioSetting(
- "right_func_key", "Right Function Key",
- RadioSettingValueList(
- opts, current_index=_settings.right_func_key)))
- opts = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"]
- basic.append(
- RadioSetting(
- "tbst_freq", "Tone Burst Frequency",
- RadioSettingValueList(
- opts, current_index=_settings.tbst_freq)))
- opts = ["Off", "TX", "RX", "TX RX"]
- basic.append(
- RadioSetting(
- "mute_mode", "Mute Mode",
- RadioSettingValueList(
- opts, current_index=_settings.mute_mode)))
- opts = ["MEM", "MSM"]
- scanmode = RadioSetting(
- "scan_mode", "Scan Mode",
- RadioSettingValueList(opts, current_index=_settings.scan_mode))
- scanmode.set_doc("MEM = Normal scan, bypass channels marked skip. "
- " MSM = Scan only channels marked priority.")
- basic.append(scanmode)
- opts = ["TO", "CO"]
+ if not self.MODEL == "MA1":
+ opts = ["Off", "Right", "Left", "Both"]
+ basic.append(RadioSetting(
+ "pttlock", "PTT Lock",
+ RadioSettingValueList(
+ opts, current_index=_settings.pttlock)))
+ opts = ["Manual", "Auto"]
+ basic.append(
+ RadioSetting(
+ "hyper_chan", "Hyper Channel",
+ RadioSettingValueList(
+ opts, current_index=_settings.hyper_chan)))
+ opts = ["Key 1", "Key 2"]
+ basic.append(
+ RadioSetting(
+ "right_func_key", "Right Function Key",
+ RadioSettingValueList(
+ opts, current_index=_settings.right_func_key)))
+ opts = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"]
+ basic.append(
+ RadioSetting(
+ "tbst_freq", "Tone Burst Frequency",
+ RadioSettingValueList(
+ opts, current_index=_settings.tbst_freq)))
+ opts = ["Off", "TX", "RX", "TX RX"]
+ basic.append(
+ RadioSetting(
+ "mute_mode", "Mute Mode",
+ RadioSettingValueList(
+ opts, current_index=_settings.mute_mode)))
+ opts = ["MEM", "MSM"]
+ scanmode = RadioSetting(
+ "scan_mode", "Scan Mode",
+ RadioSettingValueList(
+ opts, current_index=_settings.scan_mode))
+ scanmode.set_doc("MEM = Normal scan, bypass channels marked skip. "
+ " MSM = Scan only channels marked priority.")
+ basic.append(scanmode)
+ if self.MODEL == "MA1":
+ opts = ["TO", "CO", "Seek"]
+ else:
+ opts = ["TO", "CO"]
basic.append(
RadioSetting(
"scan_resume", "Scan Resume",
RadioSettingValueList(
opts, current_index=_settings.scan_resume)))
- opts = ["%0.1f" % (t / 10.0) for t in range(0, 51, 1)]
- basic.append(
- RadioSetting(
- "exit_delay", "Span Transit Exit Delay",
- RadioSettingValueList(
- opts, current_index=_settings.exit_delay)))
+ if self.MODEL == "MA1":
+ opts_choices = ["%0.1f" % (t / 10.0) for t in range(0, 51, 10)]
+ opts_values = [0x00, 0x0A, 0x14, 0x1E, 0x28, 0x32]
+
+ def apply_exit_delay_listvalue(setting, obj):
+ LOG.debug("Setting value: " + str(setting.value) +
+ " from list")
+ val = str(setting.value)
+ index = opts_choices.index(val)
+ val = opts_values[index]
+ obj.set_value(val)
+
+ if _settings.exit_delay in opts_values:
+ idx = opts_values.index(_settings.exit_delay)
+ else:
+ idx = opts_values.index(0x00)
+ rs = RadioSettingValueList(opts_choices, current_index=idx)
+ rset = RadioSetting("exit_delay",
+ "Span Transit Exit Delay", rs)
+ rset.set_apply_callback(apply_exit_delay_listvalue,
+ _settings.exit_delay)
+ basic.append(rset)
+ else:
+ opts = ["%0.1f" % (t / 10.0) for t in range(0, 51, 1)]
+ basic.append(
+ RadioSetting(
+ "exit_delay", "Span Transit Exit Delay",
+ RadioSettingValueList(
+ opts, current_index=_settings.exit_delay)))
basic.append(RadioSetting(
"tot", "Time Out Timer (minutes)",
RadioSettingValueInteger(0, 30, _settings.tot)))
- basic.append(RadioSetting(
- "tot_alert", "Time Out Timer Pre Alert(seconds)",
- RadioSettingValueInteger(0, 15, _settings.tot_alert)))
+ if not self.MODEL == "MA1":
+ basic.append(RadioSetting(
+ "tot_alert", "Time Out Timer Pre Alert(seconds)",
+ RadioSettingValueInteger(0, 15, _settings.tot_alert)))
basic.append(RadioSetting(
"tot_rekey", "Time Out Rekey (seconds)",
- RadioSettingValueInteger(0, 15, _settings.tot_rekey)))
- basic.append(RadioSetting(
- "tot_reset", "Time Out Reset(seconds)",
- RadioSettingValueInteger(0, 15, _settings.tot_reset)))
+ RadioSettingValueInteger(0, 30, _settings.tot_rekey)))
+ if not self.MODEL == "MA1":
+ basic.append(RadioSetting(
+ "tot_reset", "Time Out Reset(seconds)",
+ RadioSettingValueInteger(0, 15, _settings.tot_reset)))
basic.append(RadioSetting(
"p1", "P1 Function",
- RadioSettingValueList(MICKEYFUNC, current_index=_settings.p1)))
+ RadioSettingValueList(self.MICKEYFUNC,
+ current_index=_settings.p1)))
basic.append(RadioSetting(
"p2", "P2 Function",
- RadioSettingValueList(MICKEYFUNC, current_index=_settings.p2)))
+ RadioSettingValueList(self.MICKEYFUNC,
+ current_index=_settings.p2)))
basic.append(RadioSetting(
"p3", "P3 Function",
- RadioSettingValueList(MICKEYFUNC, current_index=_settings.p3)))
+ RadioSettingValueList(self.MICKEYFUNC,
+ current_index=_settings.p3)))
basic.append(RadioSetting(
"p4", "P4 Function",
- RadioSettingValueList(MICKEYFUNC, current_index=_settings.p4)))
+ RadioSettingValueList(self.MICKEYFUNC,
+ current_index=_settings.p4)))
+ if self.MODEL == "MA1":
+ def apply_pnl_listvalue(setting, obj):
+ LOG.debug("Setting value: " + str(setting.value) +
+ " from list")
+ val = str(setting.value)
+ index = self.PNLKEY_CHOICES.index(val)
+ val = self.PNLKEY_VALUES[index]
+ obj.set_value(val)
+
+ if _settings.pnl_band in self.PNLKEY_VALUES:
+ idx = self.PNLKEY_VALUES.index(_settings.pnl_band)
+ else:
+ idx = self.PNLKEY_VALUES.index(0x00)
+ rs = RadioSettingValueList(self.PNLKEY_CHOICES, current_index=idx)
+ rset = RadioSetting("pnl_band", "Panel BAND Function", rs)
+ rset.set_apply_callback(apply_pnl_listvalue, _settings.pnl_band)
+ basic.append(rset)
+ if _settings.pnl_ctrl in self.PNLKEY_VALUES:
+ idx = self.PNLKEY_VALUES.index(_settings.pnl_ctrl)
+ else:
+ idx = self.PNLKEY_VALUES.index(0x01)
+ rs = RadioSettingValueList(self.PNLKEY_CHOICES, current_index=idx)
+ rset = RadioSetting("pnl_ctrl", "Panel CTRL Function", rs)
+ rset.set_apply_callback(apply_pnl_listvalue, _settings.pnl_ctrl)
+ basic.append(rset)
+ if _settings.pnl_m in self.PNLKEY_VALUES:
+ idx = self.PNLKEY_VALUES.index(_settings.pnl_m)
+ else:
+ idx = self.PNLKEY_VALUES.index(0x02)
+ rs = RadioSettingValueList(self.PNLKEY_CHOICES, current_index=idx)
+ rset = RadioSetting("pnl_m", "Panel M Function", rs)
+ rset.set_apply_callback(apply_pnl_listvalue, _settings.pnl_m)
+ basic.append(rset)
# opts = ["0", "1"]
# basic.append(RadioSetting("x", "Desc",
# RadioSettingValueList(opts, opts[_settings.x])))
+ if self.MODEL == "MA1":
+ opts = ["Cross Band", "A TX/B RX", "A RX/B TX"]
+ basic.append(RadioSetting(
+ "repeater_mode", "Repeater Mode",
+ RadioSettingValueList(
+ opts, current_index=_settings.repeater_mode)))
+ basic.append(RadioSetting(
+ "dtmf_keylock", "DTMF Key Lock",
+ RadioSettingValueBoolean(
+ _settings.dtmf_keylock)))
+ autobright = RadioSetting(
+ "auto_brightness", "Auto Brightness",
+ RadioSettingValueBoolean(
+ _settings.auto_brightness))
+ autobright.set_doc("Auto Brightness. Requires 'Display Backlight' "
+ "set to 1, 2 or 3 to enable.")
+ basic.append(autobright)
+ basic.append(RadioSetting(
+ "non_subvoice_tail", "Non Subvoice Tail",
+ RadioSettingValueBoolean(
+ _settings.non_subvoice_tail)))
+ opts = ["Auto"] + list("1234567")
+ if _settings.mic_gain >= len(opts):
+ val = 0x00
+ else:
+ val = _settings.mic_gain
+ basic.append(RadioSetting(
+ "mic_gain", "Mic Gain",
+ RadioSettingValueList(
+ opts, current_index=val)))
+ txanc = RadioSetting(
+ "txanc", "TX ANC",
+ RadioSettingValueBoolean(
+ _settings.txanc))
+ txanc.set_doc("Transmit/uplink Noise Cancellation.")
+ basic.append(txanc)
+ opts = ["Off"] + list("1234")
+ if _settings.vox >= len(opts):
+ val = 0x00
+ else:
+ val = _settings.vox
+ basic.append(RadioSetting(
+ "vox", "VOX",
+ RadioSettingValueList(
+ opts, current_index=val)))
+
+ MA1_CHARSET = chirp_common.CHARSET_ALPHANUMERIC + \
+ "!\"#$%&'()*+,-./:;<=>?@"
+
+ # Clean/validate for the UI: uppercase,
+ # replace invalid chars with space,
+ # truncate
+ def _cleanScreenText(value):
+ return "".join(c if c in MA1_CHARSET else " "
+ for c in str(value).upper())[:6]
+
+ # Apply: pad to device width when actually storing
+ def apply_screentext(setting):
+ _settings.screen_text = _cleanScreenText(setting.value
+ ).ljust(6, '\x00')
+
+ # Initialize safely
+ _text = str(_settings.screen_text).rstrip('\x00\x20\xFF')
+ initial = _cleanScreenText(_text)
+
+ rsvs = RadioSettingValueString(0, 6, initial, False, MA1_CHARSET)
+ rsvs.set_validate_callback(_cleanScreenText)
+
+ rs = RadioSetting("screen_text", "Screen Text", rsvs)
+ rs.set_apply_callback(apply_screentext)
+ basic.append(rs)
def _filter(name):
filtered = ""
@@ -640,8 +946,14 @@ class TYTTH9800Base(chirp_common.Radio):
oldval = getattr(_settings, setting)
newval = element.value
- LOG.debug("Setting %s(%s) <= %s" % (setting, oldval, newval))
- setattr(_settings, setting, newval)
+ if element.has_apply_callback():
+ LOG.debug("Using apply callback")
+ element.run_apply_callback()
+ else:
+ LOG.debug(
+ "Setting %s(%s) <= %s" % (setting, oldval, newval)
+ )
+ setattr(_settings, setting, newval)
except Exception:
LOG.debug(element.get_name())
raise
@@ -657,7 +969,7 @@ class TYTTH9800File(TYTTH9800Base, chirp_common.FileBackedRadio):
_memsize = 69632
_mmap_offset = 0x1100
_scanlimits_offset = 0xC800 + _mmap_offset
- _settings_offset = 0xCB20 + _mmap_offset
+ _settings_offset = 0xCB07 + _mmap_offset
_chan_active_offset = 0xCB80 + _mmap_offset
_info_offset = 0xfe00 + _mmap_offset
@@ -681,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":
@@ -739,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()
@@ -802,7 +1123,7 @@ class TYTTH9800Radio(TYTTH9800Base, chirp_common.CloneModeRadio,
_memsize = 65296
_mmap_offset = 0x0010
_scanlimits_offset = 0xC800 + _mmap_offset
- _settings_offset = 0xCB20 + _mmap_offset
+ _settings_offset = 0xCB07 + _mmap_offset
_chan_active_offset = 0xCB80 + _mmap_offset
_info_offset = 0xfe00 + _mmap_offset
@@ -835,6 +1156,123 @@ 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)
+ self.process_mmap()
+
+ 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)
+
+
+@directory.register
+class RetevisMA1Radio(TYTTH9800Base, chirp_common.CloneModeRadio,
+ chirp_common.ExperimentalRadio):
+ VENDOR = "Retevis"
+ MODEL = "MA1"
+ BAUD_RATE = 38400
+
+ _memsize = 65296
+ _mmap_offset = 0x0010
+ _scanlimits_offset = 0xC800 + _mmap_offset
+ _settings_offset = 0xCB07 + _mmap_offset
+ _chan_active_offset = 0xCB80 + _mmap_offset
+ _info_offset = 0xfe00 + _mmap_offset
+
+ _upper = 999
+
+ MA1_MEM_FORMAT = """
+ struct mem {
+ lbcd rx_freq[4];
+ lbcd tx_freq[4];
+ lbcd rx_tone[2];
+ lbcd tx_tone[2];
+ u8 power:2,
+ BeatShift:1,
+ unknown0a:4,
+ scan:1;
+ u8 fmdev:2, // wide=00, mid=01, narrow=10
+ scramb:1,
+ compand:1,
+ emphasis:1,
+ unknown1a:2,
+ sqlmode:1; // carrier, tone
+ u8 rptmod:2, // off, -, +
+ reverse:1,
+ talkaround:1,
+ step:4;
+ u8 tx_tmode:2,
+ bclo:2,
+ rx_tmode:2,
+ unknown2a:2;
+ lbcd offset[4];
+ u8 hsdtype:2, // off, 2-tone, 5-tone, dtmf
+ unknown5a:1,
+ am:1,
+ unknown5b:4;
+ u8 unknown6a:5,
+ pttid_mode:3;
+ u8 unknown6[2];
+ char name[6];
+ u8 empty[2];
+ };
+ """
+
+ BLANK_MEMORY = "\xFF" * 32
+ INIT_MEMORY = "\xFF" * 12 + "\xC0\x08\x00\x00" + \
+ "\x00" * 6 + "\xFF\xFF" + "\x00" * 6 + "\xFF\xFF"
+ SCAN_MODES = ["", "S"]
+ MODES = ["FM", "NFM"]
+ TMODES = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
+
+ TXPOWER_LOW = 0x00
+ TXPOWER_MED = 0x01
+ TXPOWER_HIGH = 0x03
+
+ CHANNEL_WIDTH_25kHz = 0x00
+ CHANNEL_WIDTH_20kHz = 0x01
+ CHANNEL_WIDTH_12d5kHz = 0x02
+
+ POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5.00),
+ chirp_common.PowerLevel("Mid", watts=20.00),
+ chirp_common.PowerLevel("High", watts=50.00)]
+ BUSY_LOCK = ["Off", "Carrier", "CTCSS/DCS"]
+ MICKEYFUNC = ["FR.BAND", "CTRL", "MONI", "MENU", "MUTE", "SHIFT", "DUAL",
+ "M>V", "VFO", "MR", "CALL", "MHZ", "TONE", "REV", "LOW",
+ "LOCK", "A/B", "Enter", "1750"]
+ PNLKEY_CHOICES = MICKEYFUNC[:8] + MICKEYFUNC[18:]
+ 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 = (
+ 'This is experimental support for MA1 '
+ 'which is still under development.\n'
+ 'Please ensure you have a good backup with OEM software.\n'
+ 'Also please send in bug and enhancement requests!\n'
+ 'You have been warned. Proceed at your own risk!')
+ return rp
+
+ 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)
@@ -843,6 +1281,51 @@ 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)
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.memory_bounds = (1, self._upper)
+ rf.has_bank = False
+ rf.has_tuning_step = False
+ rf.valid_tuning_steps = STEPS
+ rf.can_odd_split = True
+ rf.valid_duplexes = ["", "-", "+", "split", "off"]
+ rf.valid_tmodes = self.TMODES
+ rf.valid_cross_modes = ['Tone->Tone',
+ 'Tone->DTCS',
+ 'DTCS->Tone',
+ 'DTCS->DTCS',
+ 'DTCS->',
+ '->DTCS',
+ '->Tone']
+ rf.has_ctone = True
+ rf.has_cross = True
+ rf.has_dtcs = True
+ rf.has_rx_dtcs = True
+ rf.has_dtcs_polarity = True
+ rf.valid_power_levels = self.POWER_LEVELS
+ rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + "#*-+"
+ rf.valid_bands = [(108000000, 134000000),
+ (134000000, 180000000),
+ (400000000, 512000000)]
+ rf.valid_skips = self.SCAN_MODES
+ rf.valid_modes = self.MODES + ["AM"]
+ rf.valid_name_length = 6
+ rf.has_settings = True
+ return rf
+
+ def process_mmap(self):
+ fmt = (self.MA1_MEM_FORMAT + MEM_FORMAT)
+ self._memobj = bitwise.parse(
+ fmt % (self._mmap_offset,
+ self._upper,
+ self._scanlimits_offset,
+ self._settings_offset,
+ self._chan_active_offset,
+ self._info_offset
+ ), self._mmap)
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..3fec893 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"
diff --git a/chirp/drivers/thd74.py b/chirp/drivers/thd74.py
index ef94047..fd39a55 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)
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..68f1bcd 100644
--- a/chirp/drivers/tk280.py
+++ b/chirp/drivers/tk280.py
@@ -21,6 +21,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, \
@@ -625,14 +626,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 +657,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 +714,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 +764,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:
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 5d61c89..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, \
@@ -267,7 +268,6 @@ MEM_BLOCKS = list(range(0, BLOCKS))
# define and empty block of data, as it will be used a lot in this code
EMPTY_BLOCK = b"\xFF" * 256
-RO_BLOCKS = list(range(0x10, 0x1F)) + list(range(0x59, 0x5f))
ACK_CMD = b"\x06"
POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1),
@@ -363,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)
@@ -418,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)
@@ -433,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)
@@ -463,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")
@@ -474,7 +469,11 @@ def _open_radio(radio, status):
_raw_send(radio, b"\x02")
rid = _raw_recv(radio, 8)
- if not (radio.TYPE in rid):
+ # See issue #12227 and associated ones. Some strange (potentially
+ # pre-release) models seem to identify with a lowercase form factor
+ # character. Allow these and let the variant check sort out the
+ # differences).
+ if not (radio.TYPE in rid.upper()):
# bad response, properly close the radio before exception
_close_radio(radio)
@@ -563,7 +562,7 @@ def do_upload(radio):
# The blocks from x59-x5F are NOT programmable
# The blocks from x11-x1F are written only if not empty
- if addr in RO_BLOCKS:
+ if addr in radio.RO_BLOCKS:
# checking if in the range of optional blocks
if addr >= 0x10 and addr <= 0x1F:
# block is empty ?
@@ -581,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)
@@ -661,8 +660,8 @@ class memBank(chirp_common.Bank):
index = 0
-class Kenwood_Serie_60G(chirp_common.CloneModeRadio,
- chirp_common.ExperimentalRadio):
+class Kenwood_Series_60G(chirp_common.CloneModeRadio,
+ chirp_common.ExperimentalRadio):
"""Kenwood Series 60G Radios base class"""
VENDOR = "Kenwood"
BAUD_RATE = 9600
@@ -676,6 +675,7 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio,
_kind = ""
VARIANT = ""
MODEL = ""
+ RO_BLOCKS = list(range(0x10, 0x1F)) + list(range(0x59, 0x5f))
@classmethod
def get_prompts(cls):
@@ -855,6 +855,8 @@ class Kenwood_Serie_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()
@@ -1069,12 +1071,7 @@ class Kenwood_Serie_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)
@@ -1483,7 +1480,7 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio,
@directory.register
-class TK868G_Radios(Kenwood_Serie_60G):
+class TK868G_Radios(Kenwood_Series_60G):
"""Kenwood TK-868G Radio M/C"""
MODEL = "TK-868G"
TYPE = b"M8680"
@@ -1496,7 +1493,7 @@ class TK868G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK862G_Radios(Kenwood_Serie_60G):
+class TK862G_Radios(Kenwood_Series_60G):
"""Kenwood TK-862G Radio K/E/(N)E"""
MODEL = "TK-862G"
TYPE = b"M8620"
@@ -1509,7 +1506,7 @@ class TK862G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK860G_Radios(Kenwood_Serie_60G):
+class TK860G_Radios(Kenwood_Series_60G):
"""Kenwood TK-860G Radio K"""
MODEL = "TK-860G"
TYPE = b"M8600"
@@ -1524,7 +1521,7 @@ class TK860G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK768G_Radios(Kenwood_Serie_60G):
+class TK768G_Radios(Kenwood_Series_60G):
"""Kenwood TK-768G Radios [M/C]"""
MODEL = "TK-768G"
TYPE = b"M7680"
@@ -1538,7 +1535,7 @@ class TK768G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK762G_Radios(Kenwood_Serie_60G):
+class TK762G_Radios(Kenwood_Series_60G):
"""Kenwood TK-762G Radios [K/E/NE]"""
MODEL = "TK-762G"
TYPE = b"M7620"
@@ -1552,7 +1549,7 @@ class TK762G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK760G_Radios(Kenwood_Serie_60G):
+class TK760G_Radios(Kenwood_Series_60G):
"""Kenwood TK-760G Radios [K/M/(N)E]"""
MODEL = "TK-760G"
TYPE = b"M7600"
@@ -1565,7 +1562,7 @@ class TK760G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK388G_Radios(Kenwood_Serie_60G):
+class TK388G_Radios(Kenwood_Series_60G):
"""Kenwood TK-388 Radio [K/E/M/NE]"""
MODEL = "TK-388G"
TYPE = b"P3880"
@@ -1575,7 +1572,7 @@ class TK388G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK378G_Radios(Kenwood_Serie_60G):
+class TK378G_Radios(Kenwood_Series_60G):
"""Kenwood TK-378 Radio [K/E/M/NE]"""
MODEL = "TK-378G"
TYPE = b"P3780"
@@ -1588,21 +1585,21 @@ class TK378G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK372G_Radios(Kenwood_Serie_60G):
- """Kenwood TK-372 Radio [K/E/M/NE]"""
+class TK372G_Radios(Kenwood_Series_60G):
+ """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_Serie_60G):
- """Kenwood TK-370 Radio [K/E/M/NE]"""
+class TK370G_Radios(Kenwood_Series_60G):
+ """Kenwood TK-370G Radio [K/E/M/NE]"""
MODEL = "TK-370G"
TYPE = b"P3700"
VARIANTS = {
@@ -1620,7 +1617,7 @@ class TK370G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK360G_Radios(Kenwood_Serie_60G):
+class TK360G_Radios(Kenwood_Series_60G):
"""Kenwood TK-360 Radio [K/E/M/NE]"""
MODEL = "TK-360G"
TYPE = b"P3600"
@@ -1640,7 +1637,7 @@ class TK360G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK278G_Radios(Kenwood_Serie_60G):
+class TK278G_Radios(Kenwood_Series_60G):
"""Kenwood TK-278G Radio C/C1/M/M1"""
MODEL = "TK-278G"
TYPE = b"P2780"
@@ -1654,7 +1651,7 @@ class TK278G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK272G_Radios(Kenwood_Serie_60G):
+class TK272G_Radios(Kenwood_Series_60G):
"""Kenwood TK-272G Radio K/K1"""
MODEL = "TK-272G"
TYPE = b"P2720"
@@ -1667,7 +1664,7 @@ class TK272G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK270G_Radios(Kenwood_Serie_60G):
+class TK270G_Radios(Kenwood_Series_60G):
"""Kenwood TK-270G Radio K/K1/M/E/NE/NT"""
MODEL = "TK-270G"
TYPE = b"P2700"
@@ -1681,16 +1678,19 @@ class TK270G_Radios(Kenwood_Serie_60G):
@directory.register
-class TK260G_Radios(Kenwood_Serie_60G):
+class TK260G_Radios(Kenwood_Series_60G):
"""Kenwood TK-260G Radio K/K1/M/E/NE/NT"""
MODEL = "TK-260G"
_hasbanks = False
TYPE = b"P2600"
+ RO_BLOCKS = list(range(0x10, 0x1F)) + list(range(0x52, 0x5f))
VARIANTS = {
b"P2600U\xff": (8, 136, 150, "N1"),
b"P2600T\xff": (8, 146, 174, "N"),
b"P2600$\xff": (8, 150, 174, "E"),
b"P2600\x14\xff": (8, 150, 174, "M"),
b"P2600\x05\xff": (8, 136, 150, "K1"),
- b"P2600\x04\xff": (8, 150, 174, "K")
+ b"P2600\x04\xff": (8, 150, 174, "K"),
+ # See issue #12227 for discussion of this odd variant
+ b"p2600\x24\xfb": (8, 150, 174, "E?"),
}
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..fb314aa 100644
--- a/chirp/drivers/tk8160.py
+++ b/chirp/drivers/tk8160.py
@@ -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
@@ -152,7 +152,7 @@ _KEYS = [
'Status',
'Selcall+Status',
'?', # 1E
- '?', # 1F
+ 'Channel Entry', # 1F
'?', # 20
'?', # 21
'?', # 22
@@ -164,21 +164,53 @@ _KEYS = [
'Volume Up',
'Volume Down',
'None',
- ]
+]
-KEYS = {i: key for i, key in enumerate(_KEYS)
- if not key.startswith('?')}
+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 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),
@@ -273,6 +305,10 @@ 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
+ _mem_format = mem_format
def sync_in(self):
try:
@@ -286,7 +322,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 +330,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 +342,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 +362,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,7 +550,7 @@ 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'
@@ -667,3 +706,131 @@ 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
+ _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..ff71a7f 100644
--- a/chirp/drivers/tk8180.py
+++ b/chirp/drivers/tk8180.py
@@ -13,12 +13,13 @@
# 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 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 +139,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 +159,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 +172,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 +209,8 @@ struct memory {
u8 unknown4;
};
-#seekto 0xC570; // Fixme
-u8 skipflags[64];
+#seekto 0xC570;
+lbit skipflags[512];
"""
@@ -229,7 +233,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 +263,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 +322,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 +363,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 +380,63 @@ POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5),
chirp_common.PowerLevel("High", watts=50)]
+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 +486,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 +501,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 +514,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)
@@ -471,7 +551,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 +601,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':
@@ -586,6 +666,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 +696,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')
@@ -712,6 +809,7 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
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
@@ -731,11 +829,11 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
# Copy the zone record from the source, but then update
# the count
- dest_zoneinfo.set_raw(source_zoneinfo.get_raw(asbytes=False))
+ dest_zoneinfo.set_raw(source_zoneinfo.get_raw())
dest_zoneinfo.count = count
for dest_i in range(0, min(count, old_count)):
- dest[dest_i].set_raw(source[dest_i].get_raw(asbytes=False))
+ dest[dest_i].set_raw(source[dest_i].get_raw())
else:
LOG.debug('New zone %i' % zone_number)
dest_zone.zoneinfo.number = zone_number + 1
@@ -750,6 +848,8 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
dest_zone.zoneinfo.tot_alert = z0info.tot_alert
dest_zone.zoneinfo.tot_rekey = z0info.tot_rekey
dest_zone.zoneinfo.tot_reset = z0info.tot_reset
+ dest_zone.zoneinfo.flagoffset = scan_index
+ scan_index += count
def shuffle_zone(self):
"""Sort the memories in the zone according to logical channel number"""
@@ -762,7 +862,7 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
if current == memories:
LOG.debug('Shuffle not required')
return
- raw_data = [raw_memories[i].get_raw(asbytes=False)
+ raw_data = [raw_memories[i].get_raw()
for i, n in memories]
for i, raw_mem in enumerate(raw_data):
raw_memories[i].set_raw(raw_mem)
@@ -825,11 +925,20 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
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 +1012,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 +1106,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 +1313,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(),
@@ -1398,24 +1506,24 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio):
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 +1540,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 +1699,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..204c497 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
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/uv5r.py b/chirp/drivers/uv5r.py
index 6e67dcc..d4a5b24 100644
--- a/chirp/drivers/uv5r.py
+++ b/chirp/drivers/uv5r.py
@@ -1027,16 +1027,27 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
rs = RadioSetting("bcl", "BCL",
RadioSettingValueBoolean(_mem.bcl))
+ rs.set_doc(
+ "Busy Channel Lockout. Prevents transmitting on this channel "
+ "while the radio is receiving a signal, even when a different "
+ "CTCSS tone or DCS code keeps that signal muted.")
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,30 @@ 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; higher values reject more "
+ "weak signals and noise. The manual recommends 5 as a starting "
+ "point.")
basic.append(rs)
rs = RadioSetting("save", "Battery Saver",
RadioSettingValueList(
SAVE_LIST, current_index=_settings.save))
+ rs.set_doc(
+ "Reduces standby battery use by periodically putting the "
+ "receiver to sleep. Higher ratios save more power, but may "
+ "delay reception of the beginning of a transmission.")
basic.append(rs)
rs = RadioSetting("vox", "VOX Sensitivity",
RadioSettingValueList(
VOX_LIST, current_index=_settings.vox))
+ rs.set_doc(
+ "Allows voice-operated transmission without pressing PTT. "
+ "Lower numbered levels are more sensitive; choose a level that "
+ "responds to speech without being triggered by background "
+ "noise, or select OFF to disable VOX.")
advanced.append(rs)
if self.MODEL == "UV-6":
@@ -1218,35 +1243,59 @@ class BaofengUV5R(chirp_common.CloneModeRadio):
# by the wrong name for the UV-6.
rs = RadioSetting("autolk", "Vox",
RadioSettingValueBoolean(_settings.autolk))
+ rs.set_doc(
+ "Enables voice-operated transmission. When "
+ "enabled, speaking into the microphone can start "
+ "transmission without pressing PTT.")
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 A or B as the transmit side while Dual Watch is "
+ "enabled. Off leaves transmit selection under the radio's "
+ "normal Dual Watch behavior.")
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 +1305,199 @@ 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(
+ "Enables the audible confirmation beep for keypad presses.")
basic.append(rs)
rs = RadioSetting("timeout", "Timeout Timer",
RadioSettingValueList(
TIMEOUT_LIST, current_index=_settings.timeout))
+ rs.set_doc(
+ "Limits the length of one continuous transmission. When the "
+ "selected time expires, the radio stops transmitting to help "
+ "prevent overheating and an accidentally stuck transmitter.")
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(
+ "Enables or disables spoken prompts for radio operations.")
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 while the radio is receiving a signal. "
+ "This helps avoid interrupting other users whose signal is "
+ "muted by your selected CTCSS tone or DCS code.")
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 +1505,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 +1532,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 +1546,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 +1569,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 +1582,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 +1634,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 +1697,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 +1708,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 +1724,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 +1737,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 +1857,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 +1880,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 +1899,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 +1909,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 +1928,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 +1942,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 +1954,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 +1990,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 +2006,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 +2043,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 +2071,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 +2108,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/uvb5.py b/chirp/drivers/uvb5.py
index b212d8b..8733f62 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)
diff --git a/chirp/drivers/uvk5.py b/chirp/drivers/uvk5.py
index 6706b90..f0d9fbb 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, \
@@ -364,30 +366,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 +387,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))
@@ -613,7 +598,7 @@ class UVK5RadioBase(chirp_common.CloneModeRadio):
_expanded_limits = False
_upload_calibration = False
_pttid_list = ["off", "BOT", "EOT", "BOTH"]
- _steps = [1.0, 2.5, 5.0, 6.25, 10.0, 12.5, 25.0, 8.33]
+ _steps = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0]
_langs = ["Chinese", "English"]
_backlight = ["Off"] + ['%is' % (i + 1) for i in range(5)]
@@ -2022,8 +2007,17 @@ class UVK5Radio(UVK5RadioBase):
@classmethod
def k5_approve_firmware(cls, firmware):
approved_prefixes = (
+ # These are the original OEM firmware versions
'k5_2.01.', 'app_2.01.', '2.01.', '3.00.',
- '1o11', '4.00.', 'k5_4.00.', '5.00.')
+ '4.00.', 'k5_4.00.', '5.00.', '7.00.',
+ # This "oneofeeleven" prefix really covers a wide range of
+ # firmwares that are user-built, but people report them working
+ # fine with the base driver.
+ '1o11',
+ # These are reportendly OEM and newer than the original firmwares,
+ # as of late 2025
+ '1.02.',
+ )
return any(firmware.startswith(x) for x in approved_prefixes)
@classmethod
@@ -2089,11 +2083,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'))
@@ -2101,3 +2090,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_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 22e04a5..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."
@@ -555,21 +558,6 @@ def model_match(cls, data):
return False
-def _split(rf, f1, f2):
- """Returns False if the two freqs are in the same band (no split)
- or True otherwise"""
-
- # determine if the two freqs are in the same band
- for low, high in rf.valid_bands:
- if f1 >= low and f1 <= high and \
- f2 >= low and f2 <= high:
- # if the two freqs are on the same Band this is not a split
- return False
-
- # if you get here is because the freq pairs are split
- return True
-
-
class VGCStyleRadio(chirp_common.CloneModeRadio,
chirp_common.ExperimentalRadio):
"""BTECH's UV-50X3"""
@@ -764,8 +752,8 @@ class VGCStyleRadio(chirp_common.CloneModeRadio,
# TX feq set
offset = (int(_mem.txfreq) * 10) - mem.freq
if offset != 0:
- if _split(self.get_features(), mem.freq, int(
- _mem.txfreq) * 10):
+ 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:
diff --git a/chirp/drivers/vx1.py b/chirp/drivers/vx1.py
new file mode 100644
index 0000000..71bb74e
--- /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
+ _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
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ return (len(filedata) == cls._memsize and
+ filedata[0xE6:0xEB] == b"YAESU")
+
+ def sync_out(self):
+
+ # 9600 8N1 baud for 4818 bytes = 5.02 seconds
+ 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..9717ca4 100644
--- a/chirp/drivers/vx8.py
+++ b/chirp/drivers/vx8.py
@@ -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;
@@ -697,6 +697,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/vxa700.py b/chirp/drivers/vxa700.py
deleted file mode 100644
index 50777ee..0000000
--- a/chirp/drivers/vxa700.py
+++ /dev/null
@@ -1,319 +0,0 @@
-# Copyright 2012 Dan Smith <dsmith@danplanet.com>
-#
-# This program is free software: you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation, either version 3 of the License, or
-# (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-from chirp import chirp_common, util, directory, memmap, errors
-from chirp import bitwise
-
-import time
-import struct
-import logging
-
-LOG = logging.getLogger(__name__)
-
-
-def _send(radio, data):
- LOG.debug("Sending %s" % repr(data))
- radio.pipe.write(data)
- radio.pipe.flush()
- echo = radio.pipe.read(len(data))
- if len(echo) != len(data):
- raise errors.RadioError("Invalid echo")
-
-
-def _spoonfeed(radio, data):
- # count = 0
- LOG.debug("Writing %i:\n%s" % (len(data), util.hexprint(data)))
- for byte in data:
- radio.pipe.write(byte)
- radio.pipe.flush()
- time.sleep(0.01)
- continue
- # This is really unreliable for some reason,
- # so just blindly send the data
- echo = radio.pipe.read(1)
- if echo != byte:
- LOG.debug("%02x != %02x" % (ord(echo), ord(byte)))
- raise errors.RadioError("No echo?")
- # count += 1
-
-
-def _download(radio):
- count = 0
- data = ""
- while len(data) < radio.get_memsize():
- count += 1
- chunk = radio.pipe.read(133)
- if len(chunk) == 0 and len(data) == 0 and count < 30:
- continue
- if len(chunk) != 132:
- raise errors.RadioError("Got short block (length %i)" % len(chunk))
-
- checksum = ord(chunk[-1])
- _flag, _length, _block, _data, checksum = \
- struct.unpack("BBB128sB", chunk)
-
- cs = 0
- for byte in chunk[:-1]:
- cs += ord(byte)
- if (cs % 256) != checksum:
- raise errors.RadioError("Invalid checksum at 0x%02x" % len(data))
-
- data += _data
- _send(radio, "\x06")
-
- if radio.status_fn:
- status = chirp_common.Status()
- status.msg = "Cloning from radio"
- status.cur = len(data)
- status.max = radio.get_memsize()
- radio.status_fn(status)
-
- return memmap.MemoryMap(data)
-
-
-def _upload(radio):
- for i in range(0, radio.get_memsize(), 128):
- chunk = radio.get_mmap()[i:i+128]
- cs = 0x20 + 130 + (i // 128)
- for byte in chunk:
- cs += ord(byte)
- _spoonfeed(radio,
- struct.pack("BBB128sB",
- 0x20,
- 130,
- i // 128,
- chunk,
- cs % 256))
- radio.pipe.write("")
- # This is really unreliable for some reason, so just
- # blindly proceed
- # ack = radio.pipe.read(1)
- ack = "\x06"
- time.sleep(0.5)
- if ack != "\x06":
- LOG.debug(repr(ack))
- raise errors.RadioError("Radio did not ack block %i" % (i // 132))
- # radio.pipe.read(1)
- if radio.status_fn:
- status = chirp_common.Status()
- status.msg = "Cloning to radio"
- status.cur = i
- status.max = radio.get_memsize()
- radio.status_fn(status)
-
-
-MEM_FORMAT = """
-struct memory_struct {
- u8 unknown1;
- u8 unknown2:2,
- isfm:1,
- power:2,
- step:3;
- u8 unknown5:2,
- showname:1,
- skip:1,
- duplex:2,
- unknown6:2;
- u8 tmode:2,
- unknown7:6;
- u8 unknown8;
- u8 unknown9:2,
- tone:6;
- u8 dtcs;
- u8 name[8];
- u16 freq;
- u8 offset;
-};
-
-u8 headerbytes[6];
-
-#seekto 0x0006;
-u8 invisible_bits[13];
-u8 bitfield_pad[3];
-u8 invalid_bits[13];
-
-#seekto 0x017F;
-struct memory_struct memory[100];
-"""
-
-CHARSET = "".join(["%i" % i for i in range(0, 10)]) + \
- "".join([chr(ord("A") + i) for i in range(0, 26)]) + \
- "".join([chr(ord("a") + i) for i in range(0, 26)]) + \
- "., :;!\"#$%&'()*+-/=<>?@[?]^_`{|}????~??????????????????????????"
-
-TMODES = ["", "Tone", "TSQL", "DTCS"]
-DUPLEX = ["", "-", "+", ""]
-POWER = [chirp_common.PowerLevel("Low1", watts=0.050),
- chirp_common.PowerLevel("Low2", watts=1.000),
- chirp_common.PowerLevel("Low3", watts=2.500),
- chirp_common.PowerLevel("High", watts=5.000)]
-
-
-def _wipe_memory(_mem):
- _mem.set_raw("\x00" * (_mem.size() // 8))
-
-
-@directory.register
-class VXA700Radio(chirp_common.CloneModeRadio):
- """Vertex Standard VXA-700"""
- VENDOR = "Vertex Standard"
- MODEL = "VXA-700"
- NEEDS_COMPAT_SERIAL = True
- _memsize = 4096
-
- def sync_in(self):
- try:
- self.pipe.timeout = 2
- self._mmap = _download(self)
- except errors.RadioError:
- raise
- except Exception as e:
- raise errors.RadioError("Failed to communicate " +
- "with the radio: %s" % e)
- self.process_mmap()
-
- def sync_out(self):
- # header[4] = 0x00 <- default
- # 0xFF <- air band only
- # 0x01 <- air band only
- # 0x02 <- air band only
- try:
- self.pipe.timeout = 2
- _upload(self)
- except errors.RadioError:
- raise
- except Exception as e:
- raise errors.RadioError("Failed to communicate " +
- "with the radio: %s" % e)
-
- def process_mmap(self):
- self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
-
- def get_features(self):
- rf = chirp_common.RadioFeatures()
- rf.has_bank = False
- rf.has_ctone = False
- rf.has_dtcs_polarity = False
- rf.has_tuning_step = False
- rf.valid_tmodes = TMODES
- rf.valid_name_length = 8
- rf.valid_characters = CHARSET
- rf.valid_skips = ["", "S"]
- rf.valid_bands = [(88000000, 165000000)]
- rf.valid_tuning_steps = \
- [5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0, 100.0]
- rf.valid_modes = ["AM", "FM"]
- rf.valid_power_levels = POWER
- rf.memory_bounds = (1, 100)
- return rf
-
- def _get_mem(self, number):
- return self._memobj.memory[number - 1]
-
- def get_raw_memory(self, number):
- _mem = self._get_mem(number)
- return repr(_mem) + util.hexprint(_mem.get_raw(asbytes=False))
-
- def get_memory(self, number):
- _mem = self._get_mem(number)
- byte = (number - 1) // 8
- bit = 1 << ((number - 1) % 8)
-
- mem = chirp_common.Memory()
- mem.number = number
-
- if self._memobj.invisible_bits[byte] & bit:
- mem.empty = True
- if self._memobj.invalid_bits[byte] & bit:
- mem.empty = True
- return mem
-
- if _mem.step & 0x05: # Not sure this is right, but it seems to be
- mult = 6250
- else:
- mult = 5000
-
- mem.freq = int(_mem.freq) * mult
- mem.rtone = chirp_common.TONES[_mem.tone]
- mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs]
- mem.tmode = TMODES[_mem.tmode]
- mem.duplex = DUPLEX[_mem.duplex]
- mem.offset = int(_mem.offset) * 5000 * 10
- mem.mode = _mem.isfm and "FM" or "AM"
- mem.skip = _mem.skip and "S" or ""
- mem.power = POWER[_mem.power]
-
- for char in _mem.name:
- try:
- mem.name += CHARSET[char]
- except IndexError:
- break
- mem.name = mem.name.rstrip()
-
- return mem
-
- def set_memory(self, mem):
- _mem = self._get_mem(mem.number)
- byte = (mem.number - 1) // 8
- bit = 1 << ((mem.number - 1) % 8)
-
- if mem.empty and self._memobj.invisible_bits[byte] & bit:
- self._memobj.invalid_bits[byte] |= bit
- return
- if mem.empty:
- self._memobj.invisible_bits[byte] |= bit
- return
-
- if self._memobj.invalid_bits[byte] & bit:
- _wipe_memory(_mem)
-
- self._memobj.invisible_bits[byte] &= ~bit
- self._memobj.invalid_bits[byte] &= ~bit
-
- _mem.unknown2 = 0x02 # Channels don't display without this
- _mem.unknown7 = 0x01 # some bit in this field is related to
- _mem.unknown8 = 0xFF # being able to transmit
-
- if chirp_common.required_step(mem.freq) == 12.5:
- mult = 6250
- _mem.step = 0x05
- else:
- mult = 5000
- _mem.step = 0x00
-
- _mem.freq = mem.freq / mult
- _mem.tone = chirp_common.TONES.index(mem.rtone)
- _mem.dtcs = chirp_common.DTCS_CODES.index(mem.dtcs)
- _mem.tmode = TMODES.index(mem.tmode)
- _mem.duplex = DUPLEX.index(mem.duplex)
- _mem.offset = mem.offset // 5000 // 10
- _mem.isfm = mem.mode == "FM"
- _mem.skip = mem.skip == "S"
- try:
- _mem.power = POWER.index(mem.power)
- except ValueError:
- _mem.power = 3 # High
-
- for i in range(0, 8):
- try:
- _mem.name[i] = CHARSET.index(mem.name[i])
- except IndexError:
- _mem.name[i] = 0x40
- _mem.showname = bool(mem.name.strip())
-
- @classmethod
- def match_model(cls, filedata, filename):
- return len(filedata) == cls._memsize and \
- filedata[5] == 0x0F
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..8f0d40a
--- /dev/null
+++ b/chirp/kenwood_tone.py
@@ -0,0 +1,251 @@
+#
+# 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]
+ 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':
+ 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 20f6fa2..7c5fc6f 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..69cda04 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/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 0b25dfb..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
@@ -304,6 +307,10 @@ class RadioSettingValueString(RadioSettingValue):
def maxlength(self):
return self._maxlength
+ @property
+ def minlength(self):
+ return self._minlength
+
def set_charset(self, charset):
"""Sets the set of allowed characters"""
self._charset = charset
@@ -385,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)
@@ -419,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
@@ -441,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:
@@ -608,6 +628,8 @@ class RadioSetting(RadioSettingGroup):
self._warning_text = None
self._safe_value = None
self._volatile = False
+ if self.__doc__ == self.get_name():
+ self.__doc__ = None
@property
def volatile(self):
@@ -745,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)
@@ -755,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/US Aviation Frequencies.csv b/chirp/stock_configs/US Aviation Frequencies.csv
index 1688eeb..9741be5 100644
--- a/chirp/stock_configs/US Aviation Frequencies.csv
+++ b/chirp/stock_configs/US Aviation Frequencies.csv
@@ -1,13 +1,13 @@
Location,Name,Frequency,Duplex,Offset,Tone,rToneFreq,cToneFreq,DtcsCode,DtcsPolarity,RxDtcsCode,CrossMode,Mode,TStep,Skip,Power,Comment,URCALL,RPT1CALL,RPT2CALL,DVCODE
-0,VHF Guard,121.500000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Aircraft Emergency and Distress,,,,
-1,ELT Training,121.775000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Emergency Locator Transmitter (ELT) Training Beacons,,,,
-2,AvSup 121.95,121.950000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Aviation Support,,,,
-3,FLightWatch WX,122.200000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Watch Weather ,,,,
+0,VHF Guard,121.500000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Aircraft Emergency and Distress,,,,
+1,ELT Training,121.775000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Emergency Locator Transmitter (ELT) Training Beacons,,,,
+2,AvSup 121.95,121.950000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Aviation Support,,,,
+3,FLightWatch WX,122.200000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Watch Weather ,,,,
4,UNICOM 122.7,122.700000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,Airports without an Air Traffic Control tower or FSS on the airport.,,,,
5,UNICOM 122.725,122.725000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,Airports without an Air Traffic Control tower or FSS on the airport.,,,,
6,Air-Air Fixed Wing,122.750000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,USA: Air-to-air communication (private fixed wing aircraft).,,,,
7,UNICOM 122.8,122.800000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,Airports without an Air Traffic Control tower or FSS on the airport.,,,,
-8,MULTICOM 122.85,122.850000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,"Multicom, Aviation Support",,,,
+8,MULTICOM 122.85,122.850000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,"Multicom, Aviation Support",,,,
9,MULTICOM 122.9,122.900000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,"Multicom, Search and Rescue Training ",,,,
10,MULTICOM 122.925,122.925000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,"Multicom, Special Use, Natural resource management ",,,,
11,UNICOM 122.95 (ATC),122.950000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,Airports with an Air Traffic Control tower or FSS (Alaska only) on the airport.,,,,
@@ -16,28 +16,28 @@ Location,Name,Frequency,Duplex,Offset,Tone,rToneFreq,cToneFreq,DtcsCode,DtcsPola
14,Air-Air Helo,123.025000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,USA: Helicopter air-to-air communications; air traffic control operations.,,,,
15,UNICOM 123.05,123.050000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,Airports without an Air Traffic Control tower or FSS on the airport.,,,,
16,UNICOM 123.075,123.075000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,Airports without an Air Traffic Control tower or FSS on the airport.,,,,
-17,SAR Primary,123.100000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,"Search and Rescue primary, ATC for special events secondary.",,,,
-18,FlightTest 123.125,123.125000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test itinerant,,,,
-19,FlightTest 123.15,123.150000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test itinerant ,,,,
-20,FlightTest 123.175,123.175000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test itinerant ,,,,
-21,FlightTest 123.2,123.200000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test,,,,
-22,FlightTest 123.225,123.225000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test,,,,
-23,FlightTest 123.25,123.250000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test,,,,
-24,FlightTest 123.275,123.275000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test,,,,
+17,SAR Primary,123.100000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,"Search and Rescue primary, ATC for special events secondary.",,,,
+18,FlightTest 123.125,123.125000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test itinerant,,,,
+19,FlightTest 123.15,123.150000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test itinerant ,,,,
+20,FlightTest 123.175,123.175000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test itinerant ,,,,
+21,FlightTest 123.2,123.200000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test,,,,
+22,FlightTest 123.225,123.225000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test,,,,
+23,FlightTest 123.25,123.250000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test,,,,
+24,FlightTest 123.275,123.275000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test,,,,
25,AvSup 123.3,123.300000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,"Aviation instruction, Glider, Hot Air Balloon (not to be used for advisory service).",,,,
-26,FlightTest 123.325,123.325000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test,,,,
-27,FlightTest 123.35,123.350000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,25.00,,50W,Flight Test,,,,
-28,FlightTest 123.375,123.375000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test,,,,
-29,FlightTest 123.4,123.400000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,25.00,,50W,Flight Test itinerant,,,,
-30,FlightTest 123.425,123.425000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test itinerant,,,,
-31,FlightTest 123.45,123.450000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,25.00,,50W,Flight Test,,,,
-32,FlightTest 123.475,123.475000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test,,,,
+26,FlightTest 123.325,123.325000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test,,,,
+27,FlightTest 123.35,123.350000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,Flight Test,,,,
+28,FlightTest 123.375,123.375000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test,,,,
+29,FlightTest 123.4,123.400000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,Flight Test itinerant,,,,
+30,FlightTest 123.425,123.425000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test itinerant,,,,
+31,FlightTest 123.45,123.450000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,Flight Test,,,,
+32,FlightTest 123.475,123.475000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test,,,,
33,AvSup 123.5,123.500000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,AM,25.00,,50W,"Aviation instruction, Glider, Hot Air Balloon (not to be used for advisory service).",,,,
-34,FlightTest 123.525,123.525000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test,,,,
-35,FlightTest 123.55,123.550000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test,,,,
-36,FlightTest 123.575,123.575000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Flight Test,,,,
-37,MILCOM 126.2,126.200000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Military Common (advisory) ,,,,
-38,Deicing Common,129.525000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Deicing Common,,,,
-39,MILCOM 134.1,134.100000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,Military Common (advisory) ,,,,
-40,FlightInsp 135.85,135.850000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,FAA Flight Inspection,,,,
-41,FlightInsp 135.9,135.900000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,FAA Flight Inspection,,,,
+34,FlightTest 123.525,123.525000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test,,,,
+35,FlightTest 123.55,123.550000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test,,,,
+36,FlightTest 123.575,123.575000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Flight Test,,,,
+37,MILCOM 126.2,126.200000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Military Common (advisory) ,,,,
+38,Deicing Common,129.525000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Deicing Common,,,,
+39,MILCOM 134.1,134.100000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,Military Common (advisory) ,,,,
+40,FlightInsp 135.85,135.850000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,FAA Flight Inspection,,,,
+41,FlightInsp 135.9,135.900000,,0.600000,,88.5,88.5,023,NN,023,Tone->Tone,AM,5.00,,50W,FAA Flight Inspection,,,,
diff --git a/chirp/wxui/__init__.py b/chirp/wxui/__init__.py
index 854bbfa..bdb5319 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):
@@ -112,8 +113,8 @@ 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')
+ parser.add_argument('--compat-linux-gdk-backend', action='store_true',
+ help='Force GDK_BACKEND=x11 for compatibility')
desktop.add_argument('--install-desktop-app', action='store_true',
default=False,
help=('Install a desktop icon even if it was '
@@ -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/bugreport.py b/chirp/wxui/bugreport.py
index 50b449e..5ed1508 100644
--- a/chirp/wxui/bugreport.py
+++ b/chirp/wxui/bugreport.py
@@ -34,10 +34,13 @@ 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')
LOG = logging.getLogger(__name__)
ReportThreadEvent, EVT_REPORT_THREAD = wx.lib.newevent.NewCommandEvent()
@@ -146,10 +149,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):
@@ -366,12 +370,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 +389,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 +406,29 @@ 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=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()
@@ -620,17 +649,23 @@ class ResultPage(BugReportPage):
def _upload_file(self, manifest, fn):
for i in range(3):
LOG.debug('Uploading %s attempt %i', fn, i + 1)
- r = self.context.session.post(
- BASE + '/uploads.json',
- params={'filename': fn},
- data=manifest['files'][fn],
- headers={
- 'Content-Type': 'application/octet-stream'},
- auth=self.context.auth)
- if r.status_code >= 500:
+ try:
+ r = self.context.session.post(
+ BASE + '/uploads.json',
+ params={'filename': fn},
+ data=manifest['files'][fn],
+ headers={
+ 'Content-Type': 'application/octet-stream'},
+ auth=self.context.auth)
+ except Exception as e:
+ LOG.error('Exception uploading %s: %s', fn, e)
+ time.sleep(2 + (2 * i))
+ continue
+ if r.status_code >= 400:
LOG.error('Failed to upload %s: %s %s',
fn, r.status_code, r.reason)
time.sleep(2 + (2 * i))
+ continue
elif r.status_code != 201:
LOG.error('Failed to upload %s: %s %s',
fn, r.status_code, r.reason)
diff --git a/chirp/wxui/clone.py b/chirp/wxui/clone.py
index 21bc7fc..d226d71 100644
--- a/chirp/wxui/clone.py
+++ b/chirp/wxui/clone.py
@@ -48,9 +48,10 @@ def is_prolific_warning(string):
def get_model_label(rclass):
- detected = ','.join(
+ 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 a66d0de..2d78322 100644
--- a/chirp/wxui/common.py
+++ b/chirp/wxui/common.py
@@ -33,6 +33,7 @@ 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
@@ -372,11 +373,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)
@@ -403,15 +421,131 @@ class ChirpSettingGrid(wx.Panel):
tip = None
if prop:
setting = self.get_setting_by_name(prop.GetName())
- tip = setting.__doc__ or None
- if tip and tip == setting.get_name():
- # This is the default, which makes no sense, but it's been
- # that way for ages, so just avoid exposing it here if it's
- # set to the default.
- tip = None
+ # 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
+ else:
+ extra = '%i-%i characters' % (setting.value.minlength,
+ setting.value.maxlength)
+ tip = (tip + ' (%s)' % extra).strip()
+ else:
+ tip = setting.__doc__ or None
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:
@@ -455,6 +589,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():
@@ -478,6 +617,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!'),
@@ -773,8 +929,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 3d616f3..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
@@ -608,9 +611,20 @@ class IssueModuleLoader:
issue_num, r.status_code))
r.raise_for_status()
issue = r.json()['issue']
- allowed_states = ['New', 'In Progress', 'Resolved']
+ 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..4baa07a 100644
--- a/chirp/wxui/main.py
+++ b/chirp/wxui/main.py
@@ -908,6 +908,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 +1369,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'),
@@ -2100,6 +2111,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 bb6aabd..9b59e95 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)
@@ -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"""
@@ -1714,6 +1780,8 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
return
if not only:
only = ['offset', 'duplex', 'tuning_step', 'mode', 'rtone']
+ else:
+ only = list(only)
for prop in mem.immutable:
if prop in only:
only.remove(prop)
@@ -1974,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),
@@ -2297,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
@@ -2392,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)
@@ -2537,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])
@@ -2728,20 +2800,26 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
def set_scroll_pos(self, pos):
self._grid.Scroll(*pos)
- def export_to_file(self, filename):
+ def _export_to_file(self, filename):
if not filename.lower().endswith('.csv'):
raise Exception(_('Export can only write CSV files'))
selected = self._grid.GetSelectedRows()
if len(selected) <= 1:
selected = range(0, self._grid.GetNumberRows())
- r = generic_csv.CSVRadio(None)
+ max_memory = 999
+ for row in reversed(selected):
+ m = self._memory_cache[row]
+ if isinstance(m.number, int) and m.number >= 0:
+ max_memory = m.number
+ break
+ r = generic_csv.CSVRadio(None, max_memory=max_memory)
# The CSV driver defaults to a single non-empty memory at location
# zero, so delete it before we go to export.
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:
@@ -2749,9 +2827,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
m = import_logic.import_mem(r, self._features, m,
mem_cls=chirp_common.Memory)
except import_logic.ImportError as e:
- LOG.error('Failed to export %r: %s', m, e)
- raise common.ExportFailed(
- 'Failed to export memory %i: %s' % (m.number, e))
+ LOG.error('Failed to export memory %i: %s', m.number, e)
r.set_memory(m)
r.save(filename)
LOG.info('Wrote exported CSV to %s' % filename)
@@ -2762,6 +2838,12 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor):
rows = list(range(self._grid.GetNumberRows()))
return [self._memory_cache[r] for r in rows]
+ def export_to_file(self, filename):
+ with common.expose_logs(logging.WARNING, 'chirp',
+ _('Failed to export some memories'),
+ parent=self):
+ self._export_to_file(filename)
+
class ChirpLiveMemEdit(ChirpMemEdit, common.ChirpAsyncEditor):
pass
@@ -2938,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),
@@ -2954,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..e2142c5 100644
--- a/chirp/wxui/radioinfo.py
+++ b/chirp/wxui/radioinfo.py
@@ -18,6 +18,7 @@ import wx.propgrid
from chirp.drivers import icf
from chirp import util
+from chirp.wxui import accessibility
from chirp.wxui import common
@@ -42,6 +43,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():
@@ -60,6 +62,7 @@ class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor):
pg = wx.propgrid.PropertyGrid(
self, style=wx.propgrid.PG_SPLITTER_AUTO_CENTER)
pg.EnableScrolling(True, True)
+ accessibility.enable_propgrid_a11y(pg, _('Radio Info: Driver'))
self._group_control.AddPage(pg, _('Driver'))
try:
@@ -86,6 +89,7 @@ class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor):
pg = wx.propgrid.PropertyGrid(
self, style=wx.propgrid.PG_SPLITTER_AUTO_CENTER)
pg.EnableScrolling(True, True)
+ accessibility.enable_propgrid_a11y(pg, _('Radio Info: Icom'))
self._group_control.AddPage(pg, 'Icom')
attrs = dict(self._radio._icf_data)
@@ -113,6 +117,7 @@ class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor):
pg = wx.propgrid.PropertyGrid(
self, style=wx.propgrid.PG_SPLITTER_AUTO_CENTER)
pg.EnableScrolling(True, True)
+ 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..cb4cf59 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,11 +59,63 @@ 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
+
def open(self):
super().open()
try:
@@ -80,6 +134,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 +145,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/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 aecc3bf..74e0546 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='20250912',
+ version='20260814',
url='https://chirp.danplanet.com',
python_requires=">=3.10,<4",
install_requires=[
diff --git a/tests/__pycache__/base.cpython-310.pyc b/tests/__pycache__/base.cpython-310.pyc
index 0d22964..f1054ea 100644
--- a/tests/__pycache__/base.cpython-310.pyc
+++ b/tests/__pycache__/base.cpython-310.pyc
Binary files differ
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 7cd6a5e..4f6f2ab 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/base.py b/tests/base.py
index af29310..c6ed191 100644
--- a/tests/base.py
+++ b/tests/base.py
@@ -79,6 +79,16 @@ class DriverTest(unittest.TestCase):
attempt = 0
for band_lo, band_hi in self.rf.valid_bands:
m.freq = band_lo
+ if chirp_common.is_airband(m.freq):
+ # Air band requires special step handling.
+ # First see if we can pick a 2m frequency to avoid airband
+ # details.
+ if chirp_common.in_range(146520000, self.rf.valid_bands):
+ m.freq = 146520000
+ else:
+ # Nope, so go 25kHz up from the bottom of the band to
+ # avoid 8.33kHz issues
+ m.freq += 25000
if self.rf.valid_tuning_steps:
# If we have valid tuning steps, go one step above the
# bottom of the band. Select a different tuning_step each
diff --git a/tests/driver_xfails.yaml b/tests/driver_xfails.yaml
index 6064656..a60b646 100644
--- a/tests/driver_xfails.yaml
+++ b/tests/driver_xfails.yaml
@@ -13,50 +13,14 @@ BTECH_GMRS-20V2:
- class: TestCaseBruteForce
test: test_validate_all
reason: Improper application of the duplex policy
-BTECH_GMRS-V2:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Improper application of the duplex policy
-BTECH_GMRS-50X1:
- - 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
-BTECH_MURS-V2:
- - 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?
-Radtel_RT-730:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Improper application of the duplex policy
-Retevis_RB17P:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Improper application of the duplex policy
-TIDRADIO_TD-H3:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Memory 3 stored with TX outside TX range
-TIDRADIO_TD-H8:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Memory 6 stored with TX outside TX range
-TIDRADIO_TD-H8-GMRS:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Memory 31 stored with TX outside gmrs bands
-TIDRADIO_TD-H8-HAM:
- - class: TestCaseBruteForce
- test: test_validate_all
- reason: Memory 31 stored with TX outside ham bands
Yaesu_FT-90:
- class: TestCaseBruteForce
test: test_validate_all
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_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-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/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/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/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-900.img b/tests/images/Radtel_RT-900.img
new file mode 100644
index 0000000..f397c04
--- /dev/null
+++ b/tests/images/Radtel_RT-900.img
Binary files differ
diff --git a/tests/images/Radtel_RT-900_BT.img b/tests/images/Radtel_RT-900_BT.img
new file mode 100644
index 0000000..6c890aa
--- /dev/null
+++ b/tests/images/Radtel_RT-900_BT.img
Binary files differ
diff --git a/tests/images/Radtel_RT-910.img b/tests/images/Radtel_RT-910.img
new file mode 100644
index 0000000..355c76c
--- /dev/null
+++ b/tests/images/Radtel_RT-910.img
Binary files differ
diff --git a/tests/images/Radtel_RT-910_BT.img b/tests/images/Radtel_RT-910_BT.img
new file mode 100644
index 0000000..235d21a
--- /dev/null
+++ b/tests/images/Radtel_RT-910_BT.img
Binary files differ
diff --git a/tests/images/Radtel_RT-920.img b/tests/images/Radtel_RT-920.img
new file mode 100644
index 0000000..9b7fd6c
--- /dev/null
+++ 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_HA1G.img b/tests/images/Retevis_HA1G.img
new file mode 100644
index 0000000..eaabb41
--- /dev/null
+++ b/tests/images/Retevis_HA1G.img
Binary files differ
diff --git a/tests/images/Retevis_HA1UV.img b/tests/images/Retevis_HA1UV.img
new file mode 100644
index 0000000..a989840
--- /dev/null
+++ b/tests/images/Retevis_HA1UV.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_MA1.img b/tests/images/Retevis_MA1.img
new file mode 100644
index 0000000..dbe9632
--- /dev/null
+++ b/tests/images/Retevis_MA1.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_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/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/Vertex_Standard_FTL-2011.img b/tests/images/Vertex_Standard_FTL-2011.img
deleted file mode 100644
index 5eff340..0000000
--- a/tests/images/Vertex_Standard_FTL-2011.img
+++ /dev/null
Binary files differ
diff --git a/tests/images/Vertex_Standard_VXA-700.img b/tests/images/Vertex_Standard_VXA-700.img
deleted file mode 100644
index e0dbbc0..0000000
--- a/tests/images/Vertex_Standard_VXA-700.img
+++ /dev/null
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_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/test_brute_force.py b/tests/test_brute_force.py
index f3bd68f..0114868 100644
--- a/tests/test_brute_force.py
+++ b/tests/test_brute_force.py
@@ -197,11 +197,13 @@ class TestCaseBruteForce(base.DriverTest):
lo, hi = self.rf.memory_bounds
for i in range(lo, hi + 1):
m1 = self.radio.get_memory(i)
+ if m1.empty:
+ continue
errs, warns = chirp_common.split_validation_msgs(
self.radio.validate_memory(m1))
self.assertEqual([], errs,
('Radio has validation errors for memory %i '
- 'stored in sample image') % i)
+ 'stored in sample image: %s') % (i, m1))
@base.requires_feature('has_nostep_tuning', equal=False)
def test_validate_all_steps(self):
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/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_bitwise.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc
index bdb9f73..0e83cfc 100644
--- a/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc
+++ b/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc
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 95787cc..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_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..ba7d6fe
--- /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/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_bitwise.py b/tests/unit/test_bitwise.py
index c50c3fc..1e88194 100644
--- a/tests/unit/test_bitwise.py
+++ b/tests/unit/test_bitwise.py
@@ -395,6 +395,120 @@ class TestBitwiseStructTypes(BaseTest):
self.assertEqual(ord('1'), obj.foo[0].bar)
+class TestBitwiseUnionTypes(BaseTest):
+ def test_union_one_element(self):
+ defn = 'union { u8 bar; } foo;'
+ data = memmap.MemoryMapBytes(bytes(b'\x80'))
+ obj = bitwise.parse(defn, data)
+ self.assertEqual(128, obj.foo.bar)
+
+ def test_union_two_elements(self):
+ defn = 'union { u8 bar; u8 baz; } foo;'
+ data = memmap.MemoryMapBytes(bytes(b'\x80'))
+ obj = bitwise.parse(defn, data)
+ self.assertEqual(128, obj.foo.bar)
+ self.assertEqual(128, obj.foo.baz)
+ obj.foo.baz = 1
+ self.assertEqual(1, obj.foo.baz)
+ self.assertEqual(1, obj.foo.bar)
+ obj.foo.bar = 2
+ self.assertEqual(2, obj.foo.baz)
+ self.assertEqual(2, obj.foo.bar)
+
+ def test_empty_union(self):
+ defn = 'union { } foo;'
+ data = memmap.MemoryMapBytes(bytes(b'\x80'))
+ self.assertRaises(SyntaxError, bitwise.parse, defn, data)
+
+ def test_union_size_mismatch(self):
+ defn = 'union { u16 bar; u8 baz; } foo;'
+ data = memmap.MemoryMapBytes(bytes(b'\x80'))
+ self.assertRaises(bitwise.ParseError, bitwise.parse, defn, data)
+
+ def test_union_adjacent(self):
+ # Make sure that unions don't mess up adjacent fields
+ defn = 'u8 pre; union { u8 bar; u8 baz; } foo; u8 post;'
+ data = memmap.MemoryMapBytes(bytes(b'\x01\x02\x03'))
+ obj = bitwise.parse(defn, data)
+ self.assertEqual(1, obj.pre)
+ self.assertEqual(2, obj.foo.bar)
+ self.assertEqual(2, obj.foo.baz)
+ self.assertEqual(3, obj.post)
+ obj.pre = 4
+ obj.foo.baz = 5
+ obj.post = 6
+ self.assertEqual(4, obj.pre)
+ self.assertEqual(5, obj.foo.bar)
+ self.assertEqual(5, obj.foo.baz)
+ self.assertEqual(6, obj.post)
+
+ def test_complex_union(self):
+ defn = """u8 pre;
+ union {
+ u16 whole;
+ struct { u8 lo; u8 hi; } bytes;
+ union { u16 big; ul16 little; } endian;
+ bbcd digits[2];
+ } foo;
+ u8 post;
+ """
+ data = memmap.MemoryMapBytes(bytes(b'\x01\x02\x03\x04'))
+ obj = bitwise.parse(defn, data)
+
+ self.assertEqual(1, obj.pre)
+ self.assertEqual(4, obj.post)
+ self.assertEqual(0x0203, obj.foo.whole)
+ self.assertEqual(2, obj.foo.bytes.lo)
+ self.assertEqual(3, obj.foo.bytes.hi)
+ self.assertEqual(0x0203, obj.foo.endian.big)
+ self.assertEqual(0x0302, obj.foo.endian.little)
+ self.assertEqual(2, int(obj.foo.digits[0]))
+ self.assertEqual(3, int(obj.foo.digits[1]))
+
+ obj.foo.bytes.lo = 5
+ self.assertEqual(1, obj.pre)
+ self.assertEqual(4, obj.post)
+ self.assertEqual(0x0503, obj.foo.whole)
+ self.assertEqual(5, obj.foo.bytes.lo)
+ self.assertEqual(3, obj.foo.bytes.hi)
+ self.assertEqual(0x0503, obj.foo.endian.big)
+ self.assertEqual(0x0305, obj.foo.endian.little)
+ self.assertEqual(5, int(obj.foo.digits[0]))
+ self.assertEqual(3, int(obj.foo.digits[1]))
+
+ def test_union_array(self):
+ defn = 'union { u8 bar; u8 baz; } foo[2];'
+ data = memmap.MemoryMapBytes(bytes(b'\x01\x02'))
+ obj = bitwise.parse(defn, data)
+ self.assertEqual(1, obj.foo[0].bar)
+ self.assertEqual(1, obj.foo[0].baz)
+ self.assertEqual(2, obj.foo[1].bar)
+ self.assertEqual(2, obj.foo[1].baz)
+ obj.foo[0].bar = 3
+ obj.foo[1].baz = 4
+ self.assertEqual(3, obj.foo[0].bar)
+ self.assertEqual(3, obj.foo[0].baz)
+ self.assertEqual(4, obj.foo[1].bar)
+ self.assertEqual(4, obj.foo[1].baz)
+
+ def test_struct_size_with_union(self):
+ # Make sure to include a bitfield at the start of the union to
+ # confirm that we properly account for the union size separately.
+ defn = ('struct { u8 pre; union { u8 bar1:4, bar2:4; u8 baz; } foo; '
+ 'u8 post; } st;')
+ data = memmap.MemoryMapBytes(bytes(b'\x01\x02\x03'))
+ obj = bitwise.parse(defn, data)
+ # Make sure the union is counted as a single byte
+ self.assertEqual(8 * 3, obj.st.size())
+
+ # Make sure raw operations work across unions
+ obj.st.set_raw(b'\x00' * 3)
+ self.assertEqual(0, obj.st.foo.bar1)
+ obj.st.fill_raw(b'\xFF')
+ self.assertEqual(0x0F, obj.st.foo.bar1)
+ self.assertEqual(b'\xFF\xFF\xFF', obj.st.get_raw())
+
+
class TestBitwisePrintoffset(BaseTest):
@mock.patch.object(bitwise.LOG, 'debug')
def test_printoffset(self, mock_log):
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 0edce51..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()
@@ -310,6 +308,15 @@ class TestUtilityFunctions(base.BaseTest):
for s in invalid:
self.assertRaises(ValueError, chirp_common.parse_power, s)
+ def test_airband(self):
+ self.assertTrue(chirp_common.is_airband(108000000))
+ self.assertTrue(chirp_common.is_airband(108000000 + 25000))
+ self.assertTrue(chirp_common.is_airband(136000000 - 25000))
+ self.assertTrue(chirp_common.is_airband(136000000))
+
+ self.assertFalse(chirp_common.is_airband(108000000 - 1))
+ self.assertFalse(chirp_common.is_airband(137000000 + 1))
+
class TestSplitTone(base.BaseTest):
def _test_split_tone_decode(self, tx, rx, **vals):
@@ -552,6 +559,74 @@ class TestStepFunctions(base.BaseTest):
self.assertEqual(146520000,
chirp_common.fix_rounded_step(146520000))
+ def test_fix_rounded_step_833(self):
+ # 118.008 should be aligned to 8.33kHz step
+ self.assertEqual(
+ 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(
+ chirp_common.to_MHz(108)))
+ self.assertEqual(chirp_common.to_MHz(108),
+ chirp_common.fix_rounded_step(
+ chirp_common.to_MHz(108)))
+
+ # 108.025 MHz should be left unchanged
+ self.assertFalse(chirp_common.is_8_33(
+ chirp_common.to_MHz(108.025)))
+ self.assertEqual(chirp_common.to_MHz(108.025),
+ chirp_common.fix_rounded_step(
+ chirp_common.to_MHz(108.025)))
+
+ # Even though 146.008333 is a valid 8.33kHz step, we should
+ # not align it as such since it is not in airband
+ self.assertTrue(chirp_common.is_8_33(
+ chirp_common.to_MHz(146.008333)))
+ self.assertRaisesRegex(errors.InvalidDataError,
+ 'Unable to correct.*',
+ 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_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..a45657e
--- /dev/null
+++ b/tests/unit/test_kenwood_tone.py
@@ -0,0 +1,2187 @@
+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_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, "D032R")
+
+ 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/tools/check_commit.sh b/tools/check_commit.sh
index 9273912..ac95ef5 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,10 +74,18 @@ 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