From dff1a610625ebe7841fca01e20ca6d86b65ee4d0 Mon Sep 17 00:00:00 2001 From: Dave Hibberd Date: Thu, 25 Sep 2025 21:58:50 +0100 Subject: New upstream version 20250912 --- PKG-INFO | 5 +- chirp.egg-info/PKG-INFO | 5 +- chirp.egg-info/SOURCES.txt | 25 +- chirp/__init__.py | 2 +- chirp/bandplan.py | 2 +- chirp/bitwise.py | 21 +- chirp/chirp_common.py | 81 +- chirp/cli/experttune.py | 2 +- chirp/detect.py | 127 --- chirp/directory.py | 14 +- chirp/drivers/__init__.py | 21 +- chirp/drivers/alinco_dr735t.py | 8 +- chirp/drivers/baofeng_uv17.py | 9 +- chirp/drivers/baofeng_uv17Pro.py | 714 ++++++++++-- chirp/drivers/btech.py | 56 +- chirp/drivers/ft4.py | 10 +- chirp/drivers/ft7800.py | 134 ++- chirp/drivers/ga510.py | 4 +- chirp/drivers/generic_csv.py | 53 +- chirp/drivers/h777.py | 154 ++- chirp/drivers/icf.py | 9 +- chirp/drivers/icf520.py | 10 +- chirp/drivers/icomciv.py | 41 +- chirp/drivers/ict10.py | 577 ++++++++++ chirp/drivers/icv80.py | 4 +- chirp/drivers/id51.py | 3 + chirp/drivers/kenwood_live.py | 1 + chirp/drivers/kg935g.py | 337 +++++- chirp/drivers/mml_jc8810.py | 26 +- chirp/drivers/radioddity_gm30.py | 951 ++++++++++++++++ chirp/drivers/retevis_h777v4.py | 505 +++++++++ chirp/drivers/retevis_ra25.py | 1165 ++++++++++++++++++++ chirp/drivers/retevis_ra86.py | 609 ++++++++++ chirp/drivers/retevis_rt21.py | 278 ++++- chirp/drivers/tdh8.py | 209 ++-- chirp/drivers/th9000.py | 163 ++- chirp/drivers/thd74.py | 31 +- chirp/drivers/tk270.py | 77 +- chirp/drivers/tk280.py | 50 +- chirp/drivers/tk3140.py | 25 +- chirp/drivers/tk481.py | 17 +- chirp/drivers/tk760g.py | 80 +- chirp/drivers/tk8180.py | 58 +- chirp/drivers/uv5r.py | 40 + chirp/drivers/uvb5.py | 31 +- chirp/drivers/uvk5.py | 45 +- chirp/drivers/wouxun.py | 259 ++++- chirp/drivers/yaesu_clone.py | 15 +- chirp/errors.py | 6 + chirp/import_logic.py | 2 +- chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo | Bin 50372 -> 50740 bytes chirp/locale/es/LC_MESSAGES/CHIRP.mo | Bin 88456 -> 90737 bytes chirp/locale/fr/LC_MESSAGES/CHIRP.mo | Bin 77114 -> 92790 bytes chirp/locale/it/LC_MESSAGES/CHIRP.mo | Bin 90355 -> 90821 bytes chirp/locale/pl/LC_MESSAGES/CHIRP.mo | Bin 25934 -> 27170 bytes chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mo | Bin 0 -> 89721 bytes chirp/locale/ru/LC_MESSAGES/CHIRP.mo | Bin 83636 -> 121285 bytes chirp/settings.py | 9 +- chirp/share/welcome_screen_ro_RO.png | Bin 0 -> 25965 bytes chirp/sources/repeaterbook.py | 9 +- chirp/stock_configs/US MURS Channels.csv | 12 +- chirp/util.py | 3 +- chirp/wxui/bugreport.py | 47 +- chirp/wxui/clone.py | 86 +- chirp/wxui/common.py | 111 +- chirp/wxui/config.py | 34 +- chirp/wxui/developer.py | 31 +- chirp/wxui/main.py | 72 +- chirp/wxui/memedit.py | 219 +++- chirp/wxui/radioinfo.py | 3 + chirp/wxui/report.py | 2 - chirp/wxui/serialtrace.py | 129 +++ setup.py | 4 +- tests/__init__.py | 3 +- tests/__pycache__/__init__.cpython-310.pyc | Bin 4271 -> 4507 bytes .../test_clone.cpython-310-pytest-7.1.3.pyc | Bin 5388 -> 5451 bytes .../test_edges.cpython-310-pytest-7.1.3.pyc | Bin 7719 -> 8248 bytes tests/images/Baofeng_K6.img | Bin 0 -> 33965 bytes tests/images/Baofeng_UV-5G_Pro.img | Bin 0 -> 6665 bytes tests/images/Baofeng_UV-5R_Mini.img | Bin 0 -> 33537 bytes tests/images/Icom_IC-T10.img | Bin 0 -> 6065 bytes tests/images/Kenwood_TK-278.img | Bin 0 -> 1213 bytes tests/images/QYT_KT-5000.img | Bin 0 -> 16569 bytes tests/images/Radioddity_GM-30.img | Bin 0 -> 41149 bytes tests/images/Retevis_H777_V4.img | Bin 0 -> 423 bytes tests/images/Retevis_RA25.img | Bin 0 -> 20164 bytes tests/images/Retevis_RA86.img | Bin 0 -> 3785 bytes tests/images/Retevis_RT86S.img | Bin 0 -> 1049 bytes tests/images/TIDRADIO_TD-H3.img | Bin 8369 -> 8389 bytes tests/images/Wouxun_KG-805G.img | Bin 0 -> 8373 bytes tests/images/Wouxun_KG-935H.img | Bin 0 -> 32949 bytes tests/py3-untested-drivers.txt | 10 - tests/py3_driver_testers.txt | 1 + tests/test_clone.py | 3 +- tests/test_edges.py | 17 + .../test_bitwise.cpython-310-pytest-7.1.3.pyc | Bin 18507 -> 18843 bytes .../test_chirp_common.cpython-310-pytest-7.1.3.pyc | Bin 31643 -> 33055 bytes .../test_csv.cpython-310-pytest-7.1.3.pyc | Bin 10108 -> 11526 bytes .../test_serialtrace.cpython-310-pytest-7.1.3.pyc | Bin 0 -> 2863 bytes tests/unit/test_bitwise.py | 16 + tests/unit/test_chirp_common.py | 10 +- tests/unit/test_csv.py | 21 + tests/unit/test_serialtrace.py | 79 ++ tools/check_commit.sh | 35 +- tools/check_for_bug.sh | 7 - tools/cpep8.manifest | 2 - tools/fast-driver.py | 2 +- 107 files changed, 7046 insertions(+), 1002 deletions(-) delete mode 100644 chirp/detect.py create mode 100644 chirp/drivers/ict10.py create mode 100644 chirp/drivers/radioddity_gm30.py create mode 100644 chirp/drivers/retevis_h777v4.py create mode 100644 chirp/drivers/retevis_ra25.py create mode 100644 chirp/drivers/retevis_ra86.py create mode 100644 chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mo create mode 100644 chirp/share/welcome_screen_ro_RO.png create mode 100644 chirp/wxui/serialtrace.py create mode 100644 tests/images/Baofeng_K6.img create mode 100644 tests/images/Baofeng_UV-5G_Pro.img create mode 100644 tests/images/Baofeng_UV-5R_Mini.img create mode 100644 tests/images/Icom_IC-T10.img create mode 100644 tests/images/Kenwood_TK-278.img create mode 100644 tests/images/QYT_KT-5000.img create mode 100644 tests/images/Radioddity_GM-30.img create mode 100644 tests/images/Retevis_H777_V4.img create mode 100644 tests/images/Retevis_RA25.img create mode 100644 tests/images/Retevis_RA86.img create mode 100644 tests/images/Retevis_RT86S.img create mode 100644 tests/images/Wouxun_KG-805G.img create mode 100644 tests/images/Wouxun_KG-935H.img create mode 100644 tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc create mode 100644 tests/unit/test_serialtrace.py delete mode 100755 tools/check_for_bug.sh diff --git a/PKG-INFO b/PKG-INFO index 85945e1..bf281ef 100644 --- a/PKG-INFO +++ b/PKG-INFO @@ -1,6 +1,6 @@ -Metadata-Version: 2.2 +Metadata-Version: 2.4 Name: chirp -Version: 20250221 +Version: 20250912 Summary: A cross-platform cross-radio programming tool Home-page: https://chirp.danplanet.com Requires-Python: >=3.10,<4 @@ -13,6 +13,7 @@ Requires-Dist: lark Provides-Extra: wx Requires-Dist: wxPython; extra == "wx" Dynamic: home-page +Dynamic: license-file Dynamic: provides-extra Dynamic: requires-dist Dynamic: requires-python diff --git a/chirp.egg-info/PKG-INFO b/chirp.egg-info/PKG-INFO index 85945e1..bf281ef 100644 --- a/chirp.egg-info/PKG-INFO +++ b/chirp.egg-info/PKG-INFO @@ -1,6 +1,6 @@ -Metadata-Version: 2.2 +Metadata-Version: 2.4 Name: chirp -Version: 20250221 +Version: 20250912 Summary: A cross-platform cross-radio programming tool Home-page: https://chirp.danplanet.com Requires-Python: >=3.10,<4 @@ -13,6 +13,7 @@ Requires-Dist: lark Provides-Extra: wx Requires-Dist: wxPython; extra == "wx" Dynamic: home-page +Dynamic: license-file Dynamic: provides-extra Dynamic: requires-dist Dynamic: requires-python diff --git a/chirp.egg-info/SOURCES.txt b/chirp.egg-info/SOURCES.txt index 08042f8..8ec7a33 100644 --- a/chirp.egg-info/SOURCES.txt +++ b/chirp.egg-info/SOURCES.txt @@ -15,7 +15,6 @@ chirp/bandplan_na.py chirp/bitwise.py chirp/bitwise_grammar.py chirp/chirp_common.py -chirp/detect.py chirp/directory.py chirp/errors.py chirp/import_logic.py @@ -104,6 +103,7 @@ chirp/drivers/icm710.py chirp/drivers/icomciv.py chirp/drivers/icp7.py chirp/drivers/icq7.py +chirp/drivers/ict10.py chirp/drivers/ict70.py chirp/drivers/ict7h.py chirp/drivers/ict8.py @@ -141,10 +141,14 @@ chirp/drivers/mml_jc8810.py chirp/drivers/mursv1.py chirp/drivers/puxing.py chirp/drivers/puxing_px888k.py +chirp/drivers/radioddity_gm30.py chirp/drivers/radioddity_r2.py chirp/drivers/radtel_rt490.py chirp/drivers/radtel_rt620.py chirp/drivers/radtel_t18.py +chirp/drivers/retevis_h777v4.py +chirp/drivers/retevis_ra25.py +chirp/drivers/retevis_ra86.py chirp/drivers/retevis_ra87.py chirp/drivers/retevis_rb15.py chirp/drivers/retevis_rb17p.py @@ -223,6 +227,7 @@ chirp/locale/ja_JP/LC_MESSAGES/CHIRP.mo chirp/locale/nl/LC_MESSAGES/CHIRP.mo chirp/locale/pl/LC_MESSAGES/CHIRP.mo chirp/locale/pt_BR/LC_MESSAGES/CHIRP.mo +chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mo chirp/locale/ru/LC_MESSAGES/CHIRP.mo chirp/locale/tr_TR/LC_MESSAGES/CHIRP.mo chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mo @@ -240,6 +245,7 @@ chirp/share/welcome_screen_bg.png chirp/share/welcome_screen_es.png chirp/share/welcome_screen_fr.png chirp/share/welcome_screen_it.png +chirp/share/welcome_screen_ro_RO.png chirp/share/welcome_screen_zh_CN.png chirp/sources/__init__.py chirp/sources/base.py @@ -286,6 +292,7 @@ chirp/wxui/query_sources.py chirp/wxui/radioinfo.py chirp/wxui/radiothread.py chirp/wxui/report.py +chirp/wxui/serialtrace.py chirp/wxui/settingsedit.py tests/__init__.py tests/base.py @@ -366,12 +373,15 @@ tests/images/Baofeng_BF-T20FRS.img tests/images/Baofeng_BF-T8.img tests/images/Baofeng_F-11.img tests/images/Baofeng_GM-5RH.img +tests/images/Baofeng_K6.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-3R.img +tests/images/Baofeng_UV-5G_Pro.img tests/images/Baofeng_UV-5R.img +tests/images/Baofeng_UV-5R_Mini.img tests/images/Baofeng_UV-6R.img tests/images/Baofeng_UV-9G.img tests/images/Baofeng_UV-B5.img @@ -399,6 +409,7 @@ tests/images/Icom_IC-F621-2.img tests/images/Icom_IC-M710.img tests/images/Icom_IC-P7.img tests/images/Icom_IC-Q7A.img +tests/images/Icom_IC-T10.img tests/images/Icom_IC-T70.img tests/images/Icom_IC-T7H.img tests/images/Icom_IC-T8A.img @@ -428,6 +439,7 @@ tests/images/Kenwood_TH-D72_clone_mode.img tests/images/Kenwood_TH-D74_clone_mode.img tests/images/Kenwood_TH-D75.img tests/images/Kenwood_TK-272G.img +tests/images/Kenwood_TK-278.img tests/images/Kenwood_TK-280.img tests/images/Kenwood_TK-3140K.img tests/images/Kenwood_TK-3180K2.img @@ -456,6 +468,7 @@ tests/images/Puxing_PX-777.img tests/images/Puxing_PX-888K.img tests/images/Q-MAC_HF-90_v300_or_earlier.img tests/images/Q-MAC_HF-90_v301_or_later.img +tests/images/QYT_KT-5000.img tests/images/QYT_KT-8R.img tests/images/QYT_KT-WP12.img tests/images/QYT_KT7900D.img @@ -465,6 +478,7 @@ tests/images/Quansheng_UV-K5.img tests/images/Quansheng_UV-K5_egzumer.img tests/images/Radioddity_GA-510.img tests/images/Radioddity_GA-510_V2.img +tests/images/Radioddity_GM-30.img tests/images/Radioddity_GS-5B.img tests/images/Radioddity_R2.img tests/images/Radioddity_UV-5G.img @@ -480,11 +494,14 @@ tests/images/Radtel_RT-730.img tests/images/Radtel_T18.img tests/images/Retevis_H777H_FRS.img tests/images/Retevis_H777S.img +tests/images/Retevis_H777_V4.img tests/images/Retevis_P2.img tests/images/Retevis_P62.img +tests/images/Retevis_RA25.img tests/images/Retevis_RA685.img tests/images/Retevis_RA79.img tests/images/Retevis_RA85.img +tests/images/Retevis_RA86.img tests/images/Retevis_RA87.img tests/images/Retevis_RA89.img tests/images/Retevis_RB15.img @@ -541,6 +558,7 @@ tests/images/Retevis_RT668.img tests/images/Retevis_RT68.img tests/images/Retevis_RT76.img tests/images/Retevis_RT86.img +tests/images/Retevis_RT86S.img tests/images/Retevis_RT87.img tests/images/Retevis_RT9000D_136-174.img tests/images/Retevis_RT9000D_220-260.img @@ -573,10 +591,12 @@ 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 +tests/images/Wouxun_KG-805G.img tests/images/Wouxun_KG-816.img tests/images/Wouxun_KG-818.img tests/images/Wouxun_KG-935G.img tests/images/Wouxun_KG-935G_Plus.img +tests/images/Wouxun_KG-935H.img tests/images/Wouxun_KG-UV6.img tests/images/Wouxun_KG-UV8D.img tests/images/Wouxun_KG-UV8D_Plus.img @@ -655,6 +675,7 @@ tests/unit/test_logger.py tests/unit/test_mappingmodel.py tests/unit/test_network_sources.py tests/unit/test_repeaterbook.py +tests/unit/test_serialtrace.py tests/unit/test_settings.py tests/unit/test_th9800.py tests/unit/test_util.py @@ -680,6 +701,7 @@ tests/unit/__pycache__/test_logger.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_mappingmodel.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_network_sources.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc +tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_settings.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_th9800.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_util.cpython-310-pytest-7.1.3.pyc @@ -688,7 +710,6 @@ tests/unit/__pycache__/test_wxui_radiothread.cpython-310-pytest-7.1.3.pyc tests/unit/__pycache__/test_yaesu_clone.cpython-310-pytest-7.1.3.pyc tools/Makefile tools/check_commit.sh -tools/check_for_bug.sh tools/checkpatch.sh tools/cpep8.blacklist tools/cpep8.exceptions diff --git a/chirp/__init__.py b/chirp/__init__.py index 560165c..31b111c 100644 --- a/chirp/__init__.py +++ b/chirp/__init__.py @@ -1 +1 @@ -CHIRP_VERSION = "next-20250221" +CHIRP_VERSION = "next-20250912" diff --git a/chirp/bandplan.py b/chirp/bandplan.py index 30b940e..76d87f1 100644 --- a/chirp/bandplan.py +++ b/chirp/bandplan.py @@ -69,7 +69,7 @@ class Band(object): return self limits = (self.limits[0] + self.offset, self.limits[1] + self.offset) offset = -1 * self.offset - if self.duplex in '+-': + if self.duplex and self.duplex in '+-': duplex = '+' if self.duplex == '-' else '-' return Band(limits, self.name, self.mode, self.step_khz, input_offset=offset, tones=self.tones, duplex=duplex) diff --git a/chirp/bitwise.py b/chirp/bitwise.py index 53581bd..e595f1b 100644 --- a/chirp/bitwise.py +++ b/chirp/bitwise.py @@ -701,6 +701,10 @@ class charDataElement(DataElement): class bcdDataElement(DataElement): + def __init__(self, *a, **k): + super().__init__(*a, **k) + self._ignoremask = 0x00 + def __int__(self): tens, ones = self.get_value() return (tens * 10) + ones @@ -714,6 +718,9 @@ class bcdDataElement(DataElement): def get_bits(self, mask): return ord(self._data[self._offset]) & int(mask) + def ignore_bits(self, mask): + self._ignoremask = mask + def set_raw(self, data): if isinstance(data, int): self._data[self._offset] = data & 0xFF @@ -728,11 +735,14 @@ class bcdDataElement(DataElement): type(data)) def set_value(self, value): - self._data[self._offset] = int("%02i" % value, 16) + preserve = self._data[self._offset][0] & self._ignoremask + self._data[self._offset] = ( + int("%02i" % value, 16) & ~self._ignoremask) | preserve def _get_value(self, data): - a = (ord(data) & 0xF0) >> 4 - b = ord(data) & 0x0F + data = data[0] & ~self._ignoremask + a = (data & 0xF0) >> 4 + b = data & 0x0F return (a, b) @@ -826,12 +836,13 @@ class structDataElement(DataElement): self._generators[key] = value self._keys.append(key) + def __dir__(self): + return list(super().__dir__()) + list(self._generators.keys()) + def __getattr__(self, name): try: return self._generators[name] except KeyError: - LOG.error('Request for struct element %s not in %s' % ( - name, self._generators.keys())) raise AttributeError("No attribute %s in struct %s" % ( name, self._name)) diff --git a/chirp/chirp_common.py b/chirp/chirp_common.py index b867952..2a7d6f7 100644 --- a/chirp/chirp_common.py +++ b/chirp/chirp_common.py @@ -417,7 +417,7 @@ class Memory: if callable(valid): if not valid(val): raise ValueError("`%s' is not a valid value for `%s'" % ( - val, name)) + val, name)) elif val not in self._valid_map[name]: raise ValueError("`%s' is not in valid list: %s" % (val, self._valid_map[name])) @@ -769,6 +769,7 @@ class StaticBankModel(BankModel): channelAlwaysHasBank = True """A BankModel that shows a static mapping but does not allow changes.""" + def __init__(self, radio, name='Banks', banks=10): super().__init__(radio, name=name) self._num_banks = banks @@ -796,10 +797,10 @@ class StaticBankModel(BankModel): return [self._banks[(memory.number - lo) // count]] def remove_memory_from_mapping(self, memory, mapping): - raise NotImplementedError(self.MSG) + raise errors.RadioFixedBanks() def add_memory_to_mapping(self, memory, mapping): - raise NotImplementedError(self.MSG) + raise errors.RadioFixedBanks() class MappingModelIndexInterface: @@ -1772,88 +1773,65 @@ def make_is(stephz): def required_step(freq, allowed=None): """Returns the simplest tuning step that is required to reach @freq""" if allowed is None: - allowed = [5.0, 10.0, 12.5, 6.25, 2.5, 8.33] - - # These should be in order of most common to least common - steps = { - 5.0: make_is(5000), - 10.0: make_is(10000), - 12.5: make_is(12500), - 6.25: make_is(6250), - 2.5: make_is(2500), - 1.0: make_is(1000), - 0.5: make_is(500), - 0.25: make_is(250), - 8.33: is_8_33, - } - - # Try the above "standard" steps first in order - required_step = None - for step, validate in steps.items(): - if step in allowed and validate(freq): - return step - elif validate(freq) and required_step is None: - required_step = step + allowed = [5.0, 10.0, 12.5, 6.25, 2.5, 1.0, 0.5, 8.33, 0.25] - # Try any additional steps in the allowed list + special = {8.33: is_8_33} for step in allowed: - if step in steps: - # Already tried - continue - if make_is(int(step * 1000))(freq): - LOG.debug('Chose non-standard step %s for %s' % ( - step, format_freq(freq))) + if step in special: + validate = special[step] + else: + validate = make_is(int(step * 1000)) + if validate(freq): + LOG.debug('Chose step %s for %s' % (step, format_freq(freq))) return step - if required_step is not None: - raise errors.InvalidDataError(( - 'Frequency %s requires step %.2f, ' - 'which is not supported') % ( - format_freq(freq), required_step)) - else: - raise errors.InvalidDataError("Unable to find a supported " + - "tuning step for %s" % format_freq(freq)) + raise errors.InvalidDataError("Unable to find a supported " + + "tuning step for %s" % format_freq(freq)) 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""" - try: - required_step(freq) - return freq - except errors.InvalidDataError: - pass + allowed = [12.5, 6.25] try: - required_step(freq + 500) + required_step(freq + 500, allowed=allowed) return freq + 500 except errors.InvalidDataError: pass try: - required_step(freq + 250) + required_step(freq + 250, allowed=allowed) return freq + 250 except errors.InvalidDataError: pass try: - required_step(freq + 750) + required_step(freq + 750, allowed=allowed) return float(freq + 750) except errors.InvalidDataError: pass try: - required_step(freq + 330) + required_step(freq + 330, allowed=allowed) return float(freq + 330) except errors.InvalidDataError: pass try: - required_step(freq + 660) + required_step(freq + 660, allowed=allowed) return float(freq + 660) except errors.InvalidDataError: pass + # These radios can all resolve 5kHz, so make sure what we are left with + # is 5kHz-aligned, else we refuse below. + try: + required_step(freq, allowed=[5.0]) + return freq + except errors.InvalidDataError: + pass + raise errors.InvalidDataError("Unable to correct rounded frequency " + format_freq(freq)) @@ -1914,8 +1892,9 @@ def split_to_offset(mem, rxfreq, txfreq): """Set the freq, offset, and duplex fields of a memory based on a separate rx/tx frequency. """ + mem.freq = rxfreq + if abs(txfreq - rxfreq) > to_MHz(70): - mem.freq = rxfreq mem.offset = txfreq mem.duplex = 'split' else: diff --git a/chirp/cli/experttune.py b/chirp/cli/experttune.py index e256c4b..ac54338 100644 --- a/chirp/cli/experttune.py +++ b/chirp/cli/experttune.py @@ -1,4 +1,4 @@ -#!/bin/env python3 +#!/usr/bin/env python3 import argparse import contextlib diff --git a/chirp/detect.py b/chirp/detect.py deleted file mode 100644 index 9f97a31..0000000 --- a/chirp/detect.py +++ /dev/null @@ -1,127 +0,0 @@ -# Copyright 2010 Dan Smith -# -# 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 . - -import serial -import logging - -from chirp import chirp_common, errors, directory -from chirp.drivers import ic9x_ll, icf, kenwood_live, icomciv - -LOG = logging.getLogger(__name__) - - -class DetectorRadio(chirp_common.Radio): - """Minimal radio for model detection""" - - def get_payload(self, data, raw, checksum): - return data - - -def _icom_model_data_to_rclass(md): - for _rtype, rclass in list(directory.DRV_TO_RADIO.items()): - if rclass.VENDOR != "Icom": - continue - if not hasattr(rclass, 'get_model') or not rclass.get_model(): - continue - if rclass.get_model()[:4] == md[:4]: - return rclass - - raise errors.RadioError("Unknown radio type %02x%02x%02x%02x" % - (ord(md[0]), ord(md[1]), ord(md[2]), ord(md[3]))) - - -def _detect_icom_radio(ser): - # ICOM VHF/UHF Clone-type radios @ 9600 baud - - try: - ser.baudrate = 9600 - md = icf.get_model_data(DetectorRadio(ser)) - return _icom_model_data_to_rclass(md) - except errors.RadioError as e: - LOG.error("_detect_icom_radio: %s", e) - - # ICOM IC-91/92 Live-mode radios @ 4800/38400 baud - - ser.baudrate = 4800 - try: - ic9x_ll.send_magic(ser) - return _icom_model_data_to_rclass("ic9x") - except errors.RadioError: - pass - - # ICOM CI/V Radios @ various bauds - - for rate in [9600, 4800, 19200]: - try: - ser.baudrate = rate - return icomciv.probe_model(ser) - except errors.RadioError: - pass - - ser.close() - - raise errors.RadioError("Unable to get radio model") - - -def detect_icom_radio(port): - """Detect which Icom model is connected to @port""" - if '://' in port: - ser = serial.serial_for_url(port, do_not_open=True) - ser.timeout = 0.5 - ser.open() - else: - ser = serial.Serial(port=port, timeout=0.5) - - try: - result = _detect_icom_radio(ser) - except Exception: - ser.close() - raise - - ser.close() - - LOG.info("Auto-detected %s %s on %s" % - (result.VENDOR, result.MODEL, port)) - - return result - - -def detect_kenwoodlive_radio(port): - """Detect which Kenwood model is connected to @port""" - if '://' in port: - ser = serial.serial_for_url(port, do_not_open=True) - ser.timeout = 0.5 - ser.open() - else: - ser = serial.Serial(port=port, baudrate=9600, timeout=0.5) - - r_id = kenwood_live.get_id(ser) - ser.close() - - models = {} - for rclass in list(directory.DRV_TO_RADIO.values()): - if rclass.VENDOR == "Kenwood": - models[rclass.MODEL] = rclass - - if r_id in list(models.keys()): - return models[r_id] - else: - raise errors.RadioError("Unsupported model `%s'" % r_id) - - -DETECT_FUNCTIONS = { - "Icom": detect_icom_radio, - "Kenwood": detect_kenwoodlive_radio, -} diff --git a/chirp/directory.py b/chirp/directory.py index 0c029ee..42871aa 100644 --- a/chirp/directory.py +++ b/chirp/directory.py @@ -16,6 +16,7 @@ import glob import os +import inspect import logging import sys @@ -36,6 +37,18 @@ def radio_class_id(cls): return ident +def registered_class(cls): + """Find the first parent of @cls that is registered""" + bases = inspect.getmro(cls) + for base in bases: + try: + return get_driver(base) + except Exception: + pass + else: + raise KeyError('No parent radio class of %s is registered' % cls) + + ALLOW_DUPS = False @@ -51,7 +64,6 @@ def enable_reregistrations(): def register(cls): """Register radio @cls with the directory""" - global DRV_TO_RADIO ident = radio_class_id(cls) if ident in list(DRV_TO_RADIO.keys()): if ALLOW_DUPS: diff --git a/chirp/drivers/__init__.py b/chirp/drivers/__init__.py index ad2b12b..e6073f5 100644 --- a/chirp/drivers/__init__.py +++ b/chirp/drivers/__init__.py @@ -159,20 +159,25 @@ from chirp.drivers import iradio_uv_5118plus 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 icf520 +from chirp.drivers import tdh8 +from chirp.drivers import tk280 +from chirp.drivers import baofeng_uv17 from chirp.drivers import uvk5 +from chirp.drivers import retevis_ra25 from chirp.drivers import radtel_rt620 from chirp.drivers import radtel_rt490 from chirp.drivers import baofeng_digital -from chirp.drivers import tdh8 from chirp.drivers import ts790e -from chirp.drivers import baofeng_uv17 -from chirp.drivers import alinco_dr735t -from chirp.drivers import icf520 from chirp.drivers import icm710 -from chirp.drivers import mml_jc8810 -from chirp.drivers import tk280 from chirp.drivers import tk690 +from chirp.drivers import alinco_dr735t from chirp.drivers import yaesu_clone -from chirp.drivers import tk481 +from chirp.drivers import retevis_h777v4 from chirp.drivers import baofeng_uv17Pro -__all__ = ['anytone', 'btech', 'anytone778uv', 'anytone_ht', 'anytone_iii', 'baofeng_common', 'baofeng_uv3r', 'baofeng_wp970i', 'bf_t1', 'bf_t8', 'boblov_x3plus', 'fake', 'fd268', 'ft1500m', 'ft1802', 'ft1d', 'ft2800', 'ft2900', 'ft4', 'ft450d', 'ft50', 'ft2d', 'ft60', 'ft70', 'ft7100', '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', 'uvk5', 'radtel_rt620', 'radtel_rt490', 'baofeng_digital', 'tdh8', 'ts790e', 'baofeng_uv17', 'alinco_dr735t', 'icf520', 'icm710', 'mml_jc8810', 'tk280', 'tk690', 'yaesu_clone', 'tk481', 'baofeng_uv17Pro'] +from chirp.drivers import retevis_ra86 +__all__ = ['anytone', 'btech', 'anytone778uv', 'anytone_ht', 'anytone_iii', 'baofeng_common', 'baofeng_uv3r', 'baofeng_wp970i', 'bf_t1', 'bf_t8', 'boblov_x3plus', 'fake', 'fd268', 'ft1500m', 'ft1802', 'ft1d', 'ft2800', 'ft2900', 'ft4', 'ft450d', 'ft50', 'ft2d', 'ft60', 'ft70', 'ft7100', 'ft7800', 'ft8100', 'ft817', 'ft818', 'ft857', 'ft90', 'ftlx011', 'ftm3200d', 'ftm350', 'ftm7250d', 'ga510', 'generic_csv', 'generic_tpe', 'gmrsuv1', 'gmrsv2', 'h777', 'hf90', 'hg_uv98', 'alinco', 'bj9900', 'ic2100', 'hobbypcb', 'ic208', 'ic2300', 'ic2720', 'ic2200', 'ic2730', 'ic2820', 'ic9x_ll', 'ic9x', 'ic9x_icf', 'icf', 'ic9x_icf_ll', 'icomciv', 'icp7', 'icq7', 'ict8', 'icv80', 'ict70', 'ict7h', 'icv86', 'id51', 'icx90', 'icw32', 'icx8x', 'id31', 'id5100', 'id51plus', 'id800', 'id880', 'idrp', 'kg935g', 'kguv8d', 'iradio_uv_5118', 'kenwood_hmk', 'kenwood_itm', 'kenwood_live', 'kguv8e', 'kyd', 'kguv8dplus', 'kguv920pa', 'kguv980p', 'kguv9dplus', 'lt725uv', 'kyd_IP620', 'leixen', 'mursv1', 'puxing', 'ap510', 'puxing_px888k', 'radioddity_r2', 'radtel_t18', 'retevis_rb15', 'retevis_rb17p', 'retevis_rb28', 'retevis_rt1', 'retevis_rt21', 'retevis_rt22', 'retevis_rt23', 'retevis_rt26', 'retevis_rt76p', 'retevis_rt87', 'retevis_rt98', '__init__', 'bjuv55', 'rh5r_v2', 'tdxone_tdq8a', 'template', 'tg_uv2p', 'th350', 'th7800', 'th9000', 'th9800', 'th_uv3r', 'th_uv3r25', 'th_uv8000', 'th_uv88', 'th_uvf8d', 'thd72', 'thd74', 'thuv1f', 'tk270', 'tk3140', 'tk760', 'tk760g', 'tk8102', 'tk8160', 'tk8180', 'tmd710', 'tmv71', 'tmv71_ll', 'ts2000', 'ts480', 'ts590', 'ts850', 'uv5r', 'uv5x3', 'uv6r', 'uvb5', 'vgc', 'vx170', 'vx2', 'vx3', 'vx5', 'vx510', 'vx6', 'vx7', 'vx8', 'vxa700', 'wouxun', 'wouxun_common', 'kenwood_d7', 'iradio_uv_5118plus', 'ksun_m6', 'retevis_ra87', 'uvk5_egzumer', 'tk481', 'ict10', 'radioddity_gm30', 'mml_jc8810', 'icf520', 'tdh8', 'tk280', 'baofeng_uv17', 'uvk5', 'retevis_ra25', 'radtel_rt620', 'radtel_rt490', 'baofeng_digital', 'ts790e', 'icm710', 'tk690', 'alinco_dr735t', 'yaesu_clone', 'retevis_h777v4', 'baofeng_uv17Pro', 'retevis_ra86'] diff --git a/chirp/drivers/alinco_dr735t.py b/chirp/drivers/alinco_dr735t.py index 19306b1..17351ad 100644 --- a/chirp/drivers/alinco_dr735t.py +++ b/chirp/drivers/alinco_dr735t.py @@ -371,7 +371,7 @@ class AlincoDR735T(chirp_common.CloneModeRadio): "heterodyne_mode", "Heterodyne Mode", RadioSettingValueList( self.HET_MODE_MAP, - current=self.HET_MODE_MAP[int(_mem.heterodyne_mode)])) + current_index=int(_mem.heterodyne_mode))) het_mode.set_doc("Heterodyne Mode") bcl = RadioSetting("bcl", "BCL", @@ -391,21 +391,21 @@ class AlincoDR735T(chirp_common.CloneModeRadio): "stby_screen", "Standby Screen Color", RadioSettingValueList( self.SCREEN_COLOR_MAP, - current=self.SCREEN_COLOR_MAP[int(_mem.standby_screen_color)])) + current_index=int(_mem.standby_screen_color))) stby_screen.set_doc("Standby Screen Color") rx_screen = RadioSetting( "rx_screen", "RX Screen Color", RadioSettingValueList( self.SCREEN_COLOR_MAP, - current=self.SCREEN_COLOR_MAP[int(_mem.rx_screen_color)])) + current_index=int(_mem.rx_screen_color))) rx_screen.set_doc("RX Screen Color") tx_screen = RadioSetting( "tx_screen", "TX Screen Color", RadioSettingValueList( self.SCREEN_COLOR_MAP, - current=self.SCREEN_COLOR_MAP[int(_mem.tx_screen_color)])) + current_index=int(_mem.tx_screen_color))) tx_screen.set_doc("TX Screen Color") mem.extra.append(het_mode) diff --git a/chirp/drivers/baofeng_uv17.py b/chirp/drivers/baofeng_uv17.py index 48fb57f..1a04c41 100644 --- a/chirp/drivers/baofeng_uv17.py +++ b/chirp/drivers/baofeng_uv17.py @@ -22,7 +22,7 @@ from chirp.settings import RadioSettingGroup, RadioSetting, \ RadioSettings, RadioSettingValueString import struct from chirp.drivers import baofeng_common, baofeng_uv17Pro -from chirp import errors, util +from chirp import errors LOG = logging.getLogger(__name__) LIST_DTMFST = ["Off", "DT-ST", "ANI-ST", "DT+ANI"] @@ -88,15 +88,11 @@ def _download(radio): for addr in range(start_addr, start_addr + 0x1000, radio.BLOCK_SIZE): frame = radio._make_read_frame(addr, radio.BLOCK_SIZE) - # DEBUG - LOG.debug("Frame=" + util.hexprint(frame)) - + radio.pipe.log('Reading addr %04x' % addr) baofeng_common._rawsend(radio, frame) d = baofeng_common._rawrecv(radio, radio.BLOCK_SIZE + 5) - LOG.debug("Response Data= " + util.hexprint(d)) - data += d[5:] status.cur = len(data) // radio.BLOCK_SIZE @@ -133,6 +129,7 @@ def _upload(radio): data_addr = data_start_addr + addr - start_addr data = radio.get_mmap()[data_addr:data_addr + radio.BLOCK_SIZE] frame = radio._make_frame(b"W", addr, radio.BLOCK_SIZE, data) + radio.pipe.log('Sending addr %04x' % addr) baofeng_common._rawsend(radio, frame) # receiving the response diff --git a/chirp/drivers/baofeng_uv17Pro.py b/chirp/drivers/baofeng_uv17Pro.py index 550a5fc..65b9955 100644 --- a/chirp/drivers/baofeng_uv17Pro.py +++ b/chirp/drivers/baofeng_uv17Pro.py @@ -24,7 +24,7 @@ from chirp.settings import RadioSetting, \ RadioSettingValueString, \ RadioSettings, RadioSettingGroup import struct -from chirp import errors, util +from chirp import errors LOG = logging.getLogger(__name__) @@ -35,14 +35,16 @@ MSTRING_UV17PROGPS = b"PROGRAMCOLORPROU" MSTRING_GM5RH = b"PROGRAMBFGMRS05U" # BTECH BF-F8HP Pro magic string MSTRING_BFF8HPPRO = b"PROGRAMBF5RTECHU" +# Baofeng BF-K6 magic string +MSTRING_BFK6 = b"PROGRAMBF-K6PROU" -DTMF_CHARS = "0123456789 *#ABCD" +DTMF_CHARS = list("0123456789ABCD*#") +NUMERIC_CHARS = list("0123456789") LIST_AB = ["A", "B"] LIST_BANDWIDTH = ["Wide", "Narrow"] -LIST_DTMFSPEED = ["%s ms" % x for x in [50, 100, 200, 300, 500]] LIST_HANGUPTIME = ["%s s" % x for x in [3, 4, 5, 6, 7, 8, 9, 10]] -LIST_SIDE_TONE = ["Off", "Side Key", "ID", "Side + ID"] +LIST_SIDE_TONE = ["Off", "KB Side Tone", "ANI Side Tone", "KB + ANI Side Tone"] LIST_PTTID = ["Off", "BOT", "EOT", "Both"] LIST_TIMEOUT_ALARM = ["Off"] + ["%s sec" % x for x in range(1, 11)] LIST_PILOT_TONE = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"] @@ -58,6 +60,12 @@ LIST_VOX_LEVEL_ALT = ["%s" % x for x in range(1, 10, 1)] LIST_GPS_MODE = ["GPS", "Beidou", "GPS + Beidou"] LIST_GPS_TIMEZONE = ["%s" % x for x in range(-12, 13, 1)] LIST_SHIFTS = ["Off", "+", "-"] +LIST_OFF_AB = ["Off"] + LIST_AB +LIST_POWERON_TONE = ["Off", "Tone", "Voice"] +LIST_LCD_CONTRAST = ["%s" % x for x in range(1, 6, 1)] +LIST_MODES = ["Factory mode", "FCC amateur", "IC amateur", "CE amateur", + "Indonesian amateur", "Chinese amateur"] + CHARSET_GB2312 = chirp_common.CHARSET_ASCII for x in range(0xB0, 0xD7): for y in range(0xA1, 0xFF): @@ -137,17 +145,16 @@ def _download(radio): for addr in range(MEM_START, MEM_START + MEM_SIZE, radio.BLOCK_SIZE): frame = radio._make_read_frame(addr, radio.BLOCK_SIZE) - # DEBUG - LOG.debug("Frame=" + util.hexprint(frame)) - # Sending the read request + radio.pipe.log('Sending request for %04x' % addr) bfc._rawsend(radio, frame) - # Now we read data d = bfc._rawrecv(radio, radio.BLOCK_SIZE + 4) - LOG.debug("Response Data= " + util.hexprint(d)) - d = _crypt(radio._encrsym, d[4:]) + if radio._uses_encr: + d = _crypt(radio._encrsym, d[4:]) + else: + d = d[4:] # Aggregate the data data += d @@ -168,7 +175,7 @@ def _upload(radio): status = chirp_common.Status() status.cur = 0 status.max = radio.MEM_TOTAL // radio.BLOCK_SIZE - status.msg = "Cloning from radio..." + status.msg = "Cloning to radio..." radio.status_fn(status) data_addr = 0x00 @@ -179,17 +186,14 @@ def _upload(radio): for addr in range(MEM_START, MEM_START + MEM_SIZE, radio.BLOCK_SIZE): data = radio_mem[data_addr:data_addr + radio.BLOCK_SIZE] - data = _crypt(radio._encrsym, data) + if radio._uses_encr: + data = _crypt(radio._encrsym, data) data_addr += radio.BLOCK_SIZE frame = radio._make_frame(b"W", addr, radio.BLOCK_SIZE, data) - # DEBUG - LOG.debug("Frame=" + util.hexprint(frame)) - - # Sending the read request + radio.pipe.log('Sending address %04x' % addr) bfc._rawsend(radio, frame) - # receiving the response ack = bfc._rawrecv(radio, 1) if ack != b"\x06": msg = "Bad ack writing block 0x%04x" % addr @@ -244,10 +248,18 @@ class UV17Pro(bfc.BaofengCommonHT): _has_send_id_delay = False _has_skey1_short = False _has_skey2_short = False + _has_skey_disable = False + _has_zone_linking = False _scode_offset = 0 _encrsym = 1 _has_voice = True - _mem_positions = (0x8080, 0x80A0, 0x8280) + _uses_encr = True + _mem_params = { + 'mems': 1000, + 'ani': 0x8080, + 'pttid': 0x80A0, + 'names': 0x8280, + } MODES = ["NFM", "FM"] VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \ @@ -277,8 +289,10 @@ class UV17Pro(bfc.BaofengCommonHT): VALID_BANDS = [_vhf_range, _vhf2_range, _uhf_range] PTTID_LIST = LIST_PTTID + RXDTMF_LIST = ["CTCSS/DTS", "CTCSS/DCS + DTMF"] SCODE_LIST = ["%s" % x for x in range(1, 21)] SQUELCH_LIST = ["Off"] + list("12345") + SCRAMBLE_LIST = ["Off"] + ["SCR%s" % x for x in list("123")] LIST_POWERON_DISPLAY_TYPE = ["LOGO", "BATT voltage"] LIST_TIMEOUT = ["Off"] + ["%s sec" % x for x in range(15, 195, 15)] LIST_VOICE = ["English", "Chinese"] @@ -291,18 +305,23 @@ class UV17Pro(bfc.BaofengCommonHT): LIST_SEPARATE_CODE = ["A", "B", "C", "D", "*", "#"] LIST_GROUP_CALL_CODE = ["Off"] + LIST_SEPARATE_CODE LIST_SKEY2_SHORT = ["FM", "Scan", "Search", "Vox"] + LIST_DTMFSPEED = ["%s ms" % x for x in [50, 100, 200, 300, 500]] + LIST_DUAL_WATCH = ["Off", "On"] CHANNELS = 1000 - MEM_FORMAT = """ - struct { + _mem_format = """ + struct memory_obj { lbcd rxfreq[4]; lbcd txfreq[4]; ul16 rxtone; ul16 txtone; u8 scode; u8 pttid; - u8 lowpower; + u8 unknown7:2, + scramble:2, + unknown8:2, + lowpower:2; u8 unknown1:1, wide:1, sqmode:2, @@ -315,8 +334,9 @@ class UV17Pro(bfc.BaofengCommonHT): u8 unknown5; u8 unknown6; char name[12]; - } memory[1000]; - + }; + """ + _common_defns = """ struct vfo_entry { u8 freq[8]; ul16 rxtone; @@ -338,14 +358,19 @@ class UV17Pro(bfc.BaofengCommonHT): u8 sqmode; u8 unknown6[3]; }; - - #seekto 0x8000; - struct { - struct vfo_entry a; - struct vfo_entry b; - } vfo; - - struct { + struct ani_obj { + u8 code[5]; + u8 unknown[1]; + u8 unused1:6, + aniid:2; + u8 dtmfon; + u8 dtmfoff; + u8 separatecode; + u8 groupcallcode; + }; + """ + _settings_format = """ + struct settings_obj { u8 squelch; u8 savemode; u8 vox; @@ -403,22 +428,23 @@ class UV17Pro(bfc.BaofengCommonHT): u8 inputdtmf; u8 gpsunits; u8 pontime; - char stationid[8]; - } settings; + }; + """ - #seekto 0x%04X; + MEM_FORMAT = """ + struct memory_obj memory[%(mems)i]; + + #seekto 0x8000; struct { - u8 code[5]; - u8 unknown[1]; - u8 unused1:6, - aniid:2; - u8 dtmfon; - u8 dtmfoff; - u8 separatecode; - u8 groupcallcode; - } ani; + struct vfo_entry a; + struct vfo_entry b; + } vfo; - #seekto 0x%04X; + struct settings_obj settings; + #seekto 0x%(ani)X; + struct ani_obj ani; + + #seekto 0x%(pttid)04X; struct { u8 code[5]; char name[10]; @@ -433,8 +459,10 @@ class UV17Pro(bfc.BaofengCommonHT): struct { u8 code[16]; } downcode; + """ - #seekto 0x%04X; + _end_fmt = """ + #seekto 0x%(names)04X; struct { char name[16]; } bank_name[10]; @@ -481,7 +509,9 @@ class UV17Pro(bfc.BaofengCommonHT): def process_mmap(self): """Process the mem map into the mem object""" # make lines shorter for style check. - fmt = self.MEM_FORMAT % self._mem_positions + fmt = (self._mem_format + self._common_defns + + self._settings_format + self.MEM_FORMAT + + self._end_fmt) % self._mem_params self._memobj = bitwise.parse(fmt, self._mmap) # DTMF settings @@ -556,7 +586,7 @@ class UV17Pro(bfc.BaofengCommonHT): else: val = _mem.ani.dtmfon rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)", - RadioSettingValueList(LIST_DTMFSPEED, + RadioSettingValueList(self.LIST_DTMFSPEED, current_index=val)) dtmfe.append(rs) @@ -565,7 +595,7 @@ class UV17Pro(bfc.BaofengCommonHT): else: val = _mem.ani.dtmfoff rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)", - RadioSettingValueList(LIST_DTMFSPEED, + RadioSettingValueList(self.LIST_DTMFSPEED, current_index=val)) dtmfe.append(rs) @@ -604,8 +634,13 @@ class UV17Pro(bfc.BaofengCommonHT): self.LIST_TIMEOUT, current_index=val)) basic.append(rs) + if _mem.settings.dualstandby >= len(self.LIST_DUAL_WATCH): + val = 0x01 + else: + val = _mem.settings.dualstandby rs = RadioSetting("settings.dualstandby", "Dual Watch", - RadioSettingValueBoolean(_mem.settings.dualstandby)) + RadioSettingValueList( + self.LIST_DUAL_WATCH, current_index=val)) basic.append(rs) if _mem.settings.powerondistype >= len(self.LIST_POWERON_DISPLAY_TYPE): @@ -646,6 +681,10 @@ class UV17Pro(bfc.BaofengCommonHT): RadioSettingValueBoolean(_mem.settings.autolock)) basic.append(rs) + if _mem.settings.beep >= len(self.LIST_BEEP): + val = 0x01 + else: + val = _mem.settings.beep rs = RadioSetting("settings.beep", "Beep", RadioSettingValueList( self.LIST_BEEP, @@ -747,7 +786,10 @@ class UV17Pro(bfc.BaofengCommonHT): 0x1D: 2, 0x2D: 3, 0x0A: 4, - 0x0C: 5} + 0x0C: 5, + 0x34: 6, + 0x08: 4, + 0x03: 5} return key_to_index.get(int(value), 0) def apply_Key1short(setting, obj): @@ -757,7 +799,10 @@ class UV17Pro(bfc.BaofengCommonHT): 'Search': 0x1D, 'Vox': 0x2D, 'TX Power': 0x0A, - 'NOAA': 0x0C} + 'NOAA': 0x0C, + 'Zone Select': 0x34, + 'Flashlight': 0x08, + 'SOS': 0x03} obj.key1short = key_to_index.get(val, 0x07) def getKey2shortIndex(value): @@ -766,7 +811,8 @@ class UV17Pro(bfc.BaofengCommonHT): 0x1D: 2, 0x2D: 3, 0x0A: 4, - 0x0C: 5} + 0x0C: 5, + 0x34: 6} return key_to_index.get(int(value), 0) def apply_Key2short(setting, obj): @@ -776,7 +822,8 @@ class UV17Pro(bfc.BaofengCommonHT): 'Search': 0x1D, 'Vox': 0x2D, 'TX Power': 0x0A, - 'NOAA': 0x0C} + 'NOAA': 0x0C, + 'Zone Select': 0x34} obj.key2short = key_to_index.get(val, 0x07) if self._has_skey1_short: @@ -797,6 +844,13 @@ class UV17Pro(bfc.BaofengCommonHT): rs.set_apply_callback(apply_Key2short, _mem.settings) basic.append(rs) + if self._has_skey_disable: + rs = RadioSetting("settings.skdisable", "Side Key Disable", + RadioSettingValueList( + self.LIST_SKEY_DISABLE, + current_index=_mem.settings.skdisable)) + basic.append(rs) + rs = RadioSetting("settings.chaworkmode", "Channel A work mode", RadioSettingValueList( LIST_WORKMODE, @@ -869,6 +923,18 @@ class UV17Pro(bfc.BaofengCommonHT): RadioSettingValueBoolean(_mem.settings.fmenable)) basic.append(rs) + if self._has_zone_linking: + for i in range(1, 11): + rs = RadioSetting(f"settings.zn{i}linkd", + f"Scan Link Zone {i}", + RadioSettingValueBoolean(getattr( + _mem.settings, f"zn{i}linkd"))) + basic.append(rs) + + rs = RadioSetting("settings.lnkzones", "Scan Zone Linking", + RadioSettingValueBoolean(_mem.settings.lnkzones)) + basic.append(rs) + def get_settings_common_workmode(self, workmode, _mem): vfoA = RadioSettingGroup("vfoA", "VFO A") @@ -1106,6 +1172,9 @@ class UV17Pro(bfc.BaofengCommonHT): if element.has_apply_callback(): LOG.debug("Using apply callback") element.run_apply_callback() + elif setting == "pwronpwd": + numstr = self._num2bbcd(element.value) + setattr(self._memobj.settings, setting, numstr) elif element.value.get_mutable(): LOG.debug("Setting %s = %s" % (setting, element.value)) setattr(obj, setting, element.value) @@ -1278,7 +1347,6 @@ class UV17Pro(bfc.BaofengCommonHT): mem.mode = _mem.wide and self.MODES[0] or self.MODES[1] if chirp_common.in_range(mem.freq, [self._airband]): - print('freq %i means am' % mem.freq) mem.mode = "AM" mem.extra = RadioSettingGroup("Extra", "extra") @@ -1298,7 +1366,18 @@ class UV17Pro(bfc.BaofengCommonHT): current_index=scode)) mem.extra.append(rs) - if self.MODEL == "BF-F8HP-PRO": + if self.MODEL in ["BF-F8HP-PRO"]: + rs = RadioSetting("sqmode", "RX DTMF", + RadioSettingValueList( + self.RXDTMF_LIST, + current_index=_mem.sqmode)) + mem.extra.append(rs) + + rs = RadioSetting("fhss", "Encryption", + RadioSettingValueBoolean(_mem.fhss)) + mem.extra.append(rs) + + if self.MODEL in ["K6", "UV-5R Mini"]: rs = RadioSetting("sqmode", "RX DTMF", RadioSettingValueBoolean(_mem.sqmode)) mem.extra.append(rs) @@ -1307,6 +1386,13 @@ 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): @@ -1386,6 +1472,27 @@ class UV17Pro(bfc.BaofengCommonHT): self.set_memory_common(mem, _mem) +@directory.register +class UV21ProV2(UV17Pro): + VENDOR = "Baofeng" + MODEL = "UV-21ProV2" + + _airband_rx = (108000000, 135999999) + _vhf_range = (136000000, 174000000) + _vhf2_range = (220000000, 260000000) + _uhf_rx1_range = (350000000, 390000000) + _uhf_range = (400000000, 479999999) + _uhf_rx2_range = (480000000, 520000000) + + VALID_BANDS = [_airband_rx, + _vhf_range, + _vhf2_range, + _uhf_rx1_range, + _uhf_range, + _uhf_rx2_range] + MODES = UV17Pro.MODES + ['AM'] + + @directory.register class UV25(UV17Pro): VENDOR = "Baofeng" @@ -1425,6 +1532,15 @@ class UV17ProGPS(UV17Pro): return rf +@directory.register +class UV21ProGPS(UV17ProGPS): + VENDOR = "Baofeng" + MODEL = "UV-21ProGPS" + + VALID_BANDS = UV21ProV2.VALID_BANDS + MODES = UV21ProV2.MODES + + @directory.register class BF5RM(UV17Pro): VENDOR = "Baofeng" @@ -1448,6 +1564,11 @@ class MaxTalkerP15(BF5RM): MODEL = 'P15' +@directory.register +class MaxTalkerMT5RM(MaxTalkerP15): + MODEL = 'MT-5RM' + + @directory.register class BFK5Plus(BF5RM): VENDOR = "Baofeng" @@ -1492,7 +1613,7 @@ class F8HPPro(UV17Pro): # ========== # Notice to developers: - # The BF-F8HP-PRO support in this driver is currently based upon v0.33 + # The BF-F8HP-PRO support in this driver is currently based upon v0.44 # firmware. # ========== @@ -1503,13 +1624,16 @@ class F8HPPro(UV17Pro): b"\x12\x0A\x11\x06\x04\x0E\x02\x09\x0D\x00\x00", 1)] _encrsym = 3 - STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0, 100.0] + STEPS = [2.5, 5.0, 6.25, 8.33, 10.0, 12.5, 20.0, 25.0, 50.0, 100.0] LIST_STEPS = ["2.5", "5.0", "6.25", "10.0", "12.5", "20.0", "25.0", "50.0", "100.0"] - VALID_BANDS = [UV17Pro._airband, UV17Pro._vhf_range, UV17Pro._vhf2_range, + _airband = (108000000, 136999999) + _vhf_range = (137000000, 174000000) + + VALID_BANDS = [_airband, _vhf_range, UV17Pro._vhf2_range, UV17Pro._uhf_range, UV17Pro._uhf2_range] - POWER_LEVELS = [chirp_common.PowerLevel("High", watts=8.00), + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=10.00), chirp_common.PowerLevel("Low", watts=1.00), chirp_common.PowerLevel('Mid', watts=3.00)] LIST_POWER_ON_TIME = ['3 Seconds', '5 Seconds', '10 Seconds'] @@ -1520,8 +1644,11 @@ class F8HPPro(UV17Pro): LIST_BACKLIGHT_TIMER = ["Always On", "5 sec", "10 sec", "15 sec", "20 sec", "30 sec", "60 sec"] LIST_ID_DELAY = ["%s ms" % x for x in range(100, 3100, 100)] - LIST_SKEY2_SHORT = ["FM", "Scan", "Search", "Vox", "TX Power", "NOAA"] + LIST_SKEY2_SHORT = ["FM", "Scan", "Search", "Vox", "TX Power", "NOAA", + "Zone Select"] MODES = UV17Pro.MODES + ['AM'] + SQUELCH_LIST = ["Off"] + list("12345678") + LIST_SKEY_DISABLE = ["Off", "SK Only", "PTT Only", "SK + PTT"] _has_support_for_banknames = True _vfoscan = True @@ -1531,14 +1658,95 @@ class F8HPPro(UV17Pro): _has_send_id_delay = True _has_skey1_short = True _has_skey2_short = True + _has_skey_disable = True _has_voice = False _has_when_to_send_aniid = False + _has_zone_linking = True MEM_STARTS = [0x0000, 0x9000, 0xA000, 0xD000] MEM_SIZES = [0x8040, 0x0080, 0x02C0, 0x00C0] MEM_TOTAL = 0x8440 - _mem_positions = (0x80C0, 0x80E0, 0x8380) + _mem_params = { + 'mems': 1000, + 'ani': 0x80C0, + 'pttid': 0x80E0, + 'names': 0x8380, + } + + _settings_format = """ + struct settings_obj { + u8 squelch; + u8 savemode; + u8 vox; + u8 backlight; + u8 dualstandby; + u8 tot; + u8 beep; + u8 voicesw; + u8 voice; + u8 sidetone; + u8 scanmode; + u8 pttid; + u8 pttdly; + u8 chadistype; + u8 chbdistype; + u8 bcl; + u8 autolock; + u8 alarmmode; + u8 alarmtone; + u8 unknown1; + u8 tailclear; + u8 rpttailclear; + u8 rpttaildet; + u8 roger; + u8 a_or_b_selected; // a=0, b=1 + u8 fmenable; + u8 chbworkmode:4, + chaworkmode:4; + u8 keylock; + u8 powerondistype; + u8 tone; + u8 unknown4[2]; + u8 voxdlytime; + u8 menuquittime; + u8 unknown5[2]; + u8 dispani; + u8 unknown11[2]; + u8 skdisable; + u8 totalarm; + u8 zn8linkd:1, + zn7linkd:1, + zn6linkd:1, + zn5linkd:1, + zn4linkd:1, + zn3linkd:1, + zn2linkd:1, + zn1linkd:1; + u8 unknown6:6, + zn10linkd:1, + zn9linkd:1; + u8 ctsdcsscantype; + ul16 vfoscanmin; + ul16 vfoscanmax; + u8 gpsw; + u8 gpsmode; + u8 key1short; + u8 unknown7; + u8 key2short; + u8 unknown8[2]; + u8 rstmenu; + u8 singlewatch; + u8 hangup; + u8 voxsw; + u8 gpstimezone; + u8 lnkzones; + u8 inputdtmf; + u8 gpsunits; + u8 pontime; + char stationid[8]; + }; + """ def get_settings_pro_dtmf(self, dtmfe, _mem): super().get_settings_pro_dtmf(dtmfe, _mem) @@ -1546,13 +1754,13 @@ class F8HPPro(UV17Pro): rs = RadioSetting("ani.separatecode", "Separate Code", RadioSettingValueList( self.LIST_SEPARATE_CODE, - self.LIST_SEPARATE_CODE[_mem.ani.separatecode])) + current_index=_mem.ani.separatecode)) dtmfe.append(rs) rs = RadioSetting("ani.groupcallcode", "Group Call Code", RadioSettingValueList( self.LIST_GROUP_CALL_CODE, - self.LIST_GROUP_CALL_CODE[_mem.ani.groupcallcode])) + current_index=_mem.ani.groupcallcode)) dtmfe.append(rs) _codeobj = self._memobj.upcode.code @@ -1581,13 +1789,13 @@ class F8HPPro(UV17Pro): rs = RadioSetting("settings.pontime", "Power on Time", RadioSettingValueList( self.LIST_POWER_ON_TIME, - self.LIST_POWER_ON_TIME[_mem.settings.pontime])) + current_index=_mem.settings.pontime)) basic.append(rs) rs = RadioSetting("settings.gpsunits", "GPS Speed Units", RadioSettingValueList( self.LIST_GPS_UNITS, - self.LIST_GPS_UNITS[_mem.settings.gpsunits])) + current_index=_mem.settings.gpsunits)) basic.append(rs) rs = RadioSetting("settings.inputdtmf", "Input DTMF", @@ -1644,3 +1852,379 @@ class UV5RH(UV17Pro): LIST_PW_SAVEMODE = ["Off", "1:1", "1:2", "1:4"] MODES = UV17Pro.MODES + ['AM'] _has_workmode_support = True + + +@directory.register +class BFK6(UV17Pro): + VENDOR = "Baofeng" + MODEL = "K6" + + _magic = MSTRING_BFK6 + _magics = [(b"\x46", 16), + ] + _uses_encr = False + + LIST_DTMFSPEED = ["%s ms" % x for x in [50, 100, 200, 300, 400, 500]] + + _uhf_range = (400000000, 600000000) + + VALID_BANDS = [UV17Pro._airband, UV17Pro._vhf_range, (UV17Pro._vhf2_range), + _uhf_range, UV17Pro._uhf2_range] + MODES = UV17Pro.MODES + ['AM'] + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=5.00), + chirp_common.PowerLevel("Low", watts=1.00)] + LIST_PW_SAVEMODE = ["Off", "1:1", "1:2", "1:4"] + LIST_POWERON_DISPLAY_TYPE = ["LOGO", "Message", "BATT voltage"] + LIST_BEEP = ["Off", "On"] + LIST_ID_DELAY = ["Off", "100 ms", "200 ms"] + ["%s ms" % x for x in range( + 400, 1200, 200)] + LIST_SKEYS = ["Off", "Flashlight", "TX Power", "Scan", "VOX", "SOS", + "FM Radio"] + LIST_DUAL_WATCH = ["Single Display", "Dual Display, Dual Watch", + "Dual Display, Single Watch"] + + _has_voxsw = True + _has_pilot_tone = True + _has_send_id_delay = True + _has_when_to_send_aniid = False + + MEM_STARTS = [0x0000, 0x9000, 0xA000, 0xC000, 0xD000] + MEM_SIZES = [0x8040, 0x0080, 0x02C0, 0x0040, 0x0040] + + MEM_TOTAL = 0x8400 + _mem_params = { + 'mems': 999, + 'ani': 0x80C0, + 'pttid': 0x80E0, + } + CHANNELS = 999 + + _settings_format = """ + struct settings_obj { + u8 squelch; + u8 savemode; + u8 vox; + u8 backlight; + u8 dualstandby; + u8 tot; + u8 beep; + u8 voicesw; + u8 voice; + u8 sidetone; + u8 scanmode; + u8 pttid; + u8 pttdly; + u8 chadistype; + u8 chbdistype; + u8 bcl; + u8 autolock; + u8 alarmmode; + u8 alarmtone; + u8 tdr_tx; + u8 tailclear; + u8 rpttailclear; + u8 rpttaildet; + u8 roger; + u8 a_or_b_selected; // a=0, b=1 + u8 fmenable; + u8 chbworkmode:4, + chaworkmode:4; + u8 keylock; + u8 unknown2:4, + powerontone:2, + powerondistype:2; + u8 tone; + u8 unknown4[2]; + u8 voxdlytime; + u8 menuquittime; + u8 unknown5[2]; + u8 dispani; + u8 unknown11[3]; + u8 totalarm; + u8 lcdcontrast; + u8 invertlcd; + u8 ctsdcsscantype; + ul16 vfoscanmin; + ul16 vfoscanmax; + u8 fminterrupt; + u8 txdisable; + u8 key1short; + u8 key1long; + u8 key2short; + u8 unknown8[2]; + u8 rstmenu; + u8 singlewatch; + u8 hangup; + u8 voxsw; + u8 gpstimezone; + u8 pwronpwdsw; + u8 pwronpwd[3]; + char stationid[16]; + }; + """ + + _end_fmt = """ + #seekto 0x83C0; + struct { + u8 unknown1:4, + modetype:4; + u8 tx_220mhz; + u8 unknown2; + u8 tx_520mhz; + u8 rx_am; + } modes; + """ + + def _bbcd2num(self, bcdarr, strlen=6): + # doing bbcd + LOG.debug(bcdarr.get_value()) + string = ''.join("%02X" % b for b in bcdarr) + LOG.debug("@_bbcd2num, received: %s" % string) + if strlen <= 6: + string = string[:strlen] + return string + + def _num2bbcd(self, value): + numstr = value.get_value() + numstr = str.ljust(numstr.strip(), 6, "F") + bcdarr = list(bytearray.fromhex(numstr)) + LOG.debug("@_num2bbcd, sending: %s" % bcdarr) + return bcdarr + + def get_settings_pro_basic(self, basic, _mem): + super().get_settings_pro_basic(basic, _mem) + + if _mem.settings.tdr_tx >= len(LIST_OFF_AB): + val = 0x00 + else: + val = _mem.settings.tdr_tx + rs = RadioSetting("settings.tdr_tx", "TDR TX", + RadioSettingValueList( + LIST_OFF_AB, current_index=val)) + basic.append(rs) + + if _mem.settings.powerontone >= len(LIST_POWERON_TONE): + val = 0x00 + else: + val = _mem.settings.powerontone + rs = RadioSetting("settings.powerontone", "Power On Tone", + RadioSettingValueList( + LIST_POWERON_TONE, current_index=val)) + basic.append(rs) + + if _mem.settings.lcdcontrast >= len(LIST_LCD_CONTRAST): + val = 0x03 + else: + val = _mem.settings.lcdcontrast + rs = RadioSetting("settings.lcdcontrast", "LCD Contrast", + RadioSettingValueList( + LIST_LCD_CONTRAST, current_index=val)) + basic.append(rs) + + rs = RadioSetting("settings.invertlcd", "Invert LCD", + RadioSettingValueBoolean(_mem.settings.invertlcd)) + basic.append(rs) + + rs = RadioSetting("settings.key1short", "PF1", + RadioSettingValueList( + self.LIST_SKEYS, + current_index=_mem.settings.key1short)) + basic.append(rs) + + rs = RadioSetting("settings.key1long", "PF1 Long", + RadioSettingValueList( + self.LIST_SKEYS, + current_index=_mem.settings.key1long)) + basic.append(rs) + + rs = RadioSetting("settings.key2short", "PF2", + RadioSettingValueList( + self.LIST_SKEYS, + current_index=_mem.settings.key2short)) + basic.append(rs) + + rs = RadioSetting("settings.fminterrupt", "FM Interrupt", + RadioSettingValueBoolean(_mem.settings.fminterrupt)) + basic.append(rs) + + rs = RadioSetting("settings.txdisable", "Disable TX", + RadioSettingValueBoolean(_mem.settings.txdisable)) + basic.append(rs) + + rs = RadioSetting("settings.pwronpwdsw", "Power On Password Switch", + RadioSettingValueBoolean(_mem.settings.pwronpwdsw)) + basic.append(rs) + + def _filter(name): + filtered = "" + for char in str(name): + if char in NUMERIC_CHARS: + filtered += char + else: + filtered += " " + return filtered + + # setup power on password entry + codesetting = getattr(_mem.settings, "pwronpwd") + codestr = self._bbcd2num(codesetting, 6) + code = RadioSettingValueString(0, 6, _filter(codestr)) + code.set_charset(NUMERIC_CHARS + list(" ")) + rs = RadioSetting("settings.pwronpwd", "Power On Password", code) + basic.append(rs) + + def _filterStationID(name): + fname = b"" + for char in name: + if ord(str(char)) in [0, 255]: + break + fname += int(char).to_bytes(1, 'big') + return fname.decode('gb2312').strip() + + def apply_stationid(setting, obj): + stationid = (str(setting.value).encode('gb2312')[:16].ljust(16, + b"\xFF")) + obj.stationid = stationid + + _nameobj = self._memobj.settings + rs = RadioSetting("settings.stationid", + "StationID", + RadioSettingValueString( + 0, 16, _filterStationID(_nameobj.stationid), + False, CHARSET_GB2312)) + rs.set_apply_callback(apply_stationid, _nameobj) + basic.append(rs) + + rs = RadioSetting("modes.modetype", "Factory Modes", + RadioSettingValueList( + LIST_MODES, + current_index=_mem.modes.modetype)) + basic.append(rs) + + rs = RadioSetting("modes.tx_220mhz", "220M TX", + RadioSettingValueBoolean(_mem.modes.tx_220mhz)) + basic.append(rs) + + rs = RadioSetting("modes.tx_520mhz", "520M TX", + RadioSettingValueBoolean(_mem.modes.tx_520mhz)) + basic.append(rs) + + rs = RadioSetting("modes.rx_am", "AM RX", + RadioSettingValueBoolean(_mem.modes.rx_am)) + basic.append(rs) + + def get_settings_pro_dtmf(self, dtmfe, _mem): + super().get_settings_pro_dtmf(dtmfe, _mem) + + rs = RadioSetting("ani.separatecode", "Separate Code", + RadioSettingValueList( + self.LIST_SEPARATE_CODE, + current_index=_mem.ani.separatecode)) + dtmfe.append(rs) + + rs = RadioSetting("ani.groupcallcode", "Group Call Code", + RadioSettingValueList( + self.LIST_GROUP_CALL_CODE, + current_index=_mem.ani.groupcallcode)) + dtmfe.append(rs) + + _codeobj = self._memobj.upcode.code + _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) + < 0x1F]) + val = RadioSettingValueString(0, 16, _code, False) + val.set_charset(DTMF_CHARS) + rs = RadioSetting("upcode.code", "Up Code", val) + rs.set_apply_callback(self.apply_code, self._memobj.upcode, 16) + dtmfe.append(rs) + + _codeobj = self._memobj.downcode.code + _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) + < 0x1F]) + val = RadioSettingValueString(0, 16, _code, False) + val.set_charset(DTMF_CHARS) + rs = RadioSetting("downcode.code", "Down Code", val) + rs.set_apply_callback(self.apply_code, self._memobj.downcode, 16) + dtmfe.append(rs) + + +@directory.register +class UV5RMini(UV17Pro): + """Baofeng UV-5R Mini""" + VENDOR = "Baofeng" + MODEL = "UV-5R Mini" + + LIST_BEEP = ["Off", "On"] + LIST_DTMFSPEED = ["%s ms" % x for x in [50, 100, 200, 300, 400, 500]] + LIST_SKEY2_SHORT = ["FM Radio", "Scan", "Search", "VOX", "Flashlight", + "SOS"] + + MEM_STARTS = [0x0000, 0x9000, 0xA000] + MEM_SIZES = [0x8040, 0x0040, 0x01C0] + + MEM_TOTAL = 0x8240 + + _has_support_for_banknames = False + + _magic = MSTRING_UV17PROGPS + _mem_size = MEM_TOTAL + _has_voxsw = True + _has_pilot_tone = True + _has_send_id_delay = True + _has_skey1_short = True + _mem_params = { + 'mems': 999, + 'ani': 0x8080, + 'pttid': 0x80A0, + } + CHANNELS = 999 + + STEPS = [2.5, 5.0, 6.25, 8.33, 10.0, 12.5, 20.0, 25.0, 50.0] + + _uhf_rx1_range = (350000000, 390000000) + _uhf_range = (400000000, 480000000) + _uhf_rx2_range = (480000000, 520000000) + VALID_BANDS = [UV17Pro._airband, + UV17Pro._vhf_range, + _uhf_rx1_range, + _uhf_range, + _uhf_rx2_range] + MODES = UV17Pro.MODES + ['AM'] + + _end_fmt = """ + // #seekto 0x8220; + struct { + u8 unknown1[32]; + } modes; + """ + + def get_settings_pro_dtmf(self, dtmfe, _mem): + super().get_settings_pro_dtmf(dtmfe, _mem) + + rs = RadioSetting("ani.separatecode", "Separate Code", + RadioSettingValueList( + self.LIST_SEPARATE_CODE, + current_index=_mem.ani.separatecode)) + dtmfe.append(rs) + + rs = RadioSetting("ani.groupcallcode", "Group Call Code", + RadioSettingValueList( + self.LIST_GROUP_CALL_CODE, + current_index=_mem.ani.groupcallcode)) + dtmfe.append(rs) + + _codeobj = self._memobj.upcode.code + _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) + < 0x1F]) + val = RadioSettingValueString(0, 16, _code, False) + val.set_charset(DTMF_CHARS) + rs = RadioSetting("upcode.code", "Up Code", val) + rs.set_apply_callback(self.apply_code, self._memobj.upcode, 16) + dtmfe.append(rs) + + _codeobj = self._memobj.downcode.code + _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) + < 0x1F]) + val = RadioSettingValueString(0, 16, _code, False) + val.set_charset(DTMF_CHARS) + rs = RadioSetting("downcode.code", "Down Code", val) + rs.set_apply_callback(self.apply_code, self._memobj.downcode, 16) + dtmfe.append(rs) diff --git a/chirp/drivers/btech.py b/chirp/drivers/btech.py index 468bb05..bc9b75c 100644 --- a/chirp/drivers/btech.py +++ b/chirp/drivers/btech.py @@ -302,6 +302,9 @@ KTWP12_fp = b"WP3094" # Anysecu WP-9900 WP9900_fp = b"WP3094" +# QYT KT-5000 +KT5000_fp = b"WP9114" + # ### MAGICS # for the Waccom Mini-8900 @@ -327,6 +330,8 @@ MSTRING_GMRS20V2 = b"\x55\x20\x21\x03\x27\xFF\xDC\x02" MSTRING_KT8R = b"\x55\x20\x17\x07\x03\xFF\xDC\x02" # for the QYT KT-WP12, KT-9900 and Anysecu WP-9900 MSTRING_KTWP12 = b"\x55\x20\x18\x11\x02\xFF\xDC\x02" +# for the QYT KT-5000 +MSTRING_KT5000 = b"\x55\x20\x21\x01\x23\xFF\xDC\x02" def _clean_buffer(radio): @@ -414,11 +419,11 @@ def _recv(radio, addr): # Get the full 69 bytes at a time to reduce load # 1 byte ACK + 4 bytes header + 64 bytes of data (BLOCK_SIZE) - # get the whole block - block = _rawrecv(radio, BLOCK_SIZE + 5) + # get the whole block Bug #11851 BLOCKSIZE fix for KT-8900D + block = _rawrecv(radio, radio._block_size + 5) - # basic check - if len(block) < (BLOCK_SIZE + 5): + # basic check Bug #11851 BLOCKSIZE fix for KT-8900D + if len(block) < (radio._block_size + 5): raise errors.RadioError("Short read of the block 0x%04x" % addr) # checking for the ack @@ -427,7 +432,7 @@ def _recv(radio, addr): # header validation c, a, l = struct.unpack(">BHB", block[1:5]) - if a != addr or l != BLOCK_SIZE or c != ord("X"): + if a != addr or l != radio._block_size or c != ord("X"): LOG.debug("Invalid header for block 0x%04x" % addr) LOG.debug("CMD: %s ADDR: %04x SIZE: %02x" % (c, a, l)) raise errors.RadioError("Invalid header for block 0x%04x:" % addr) @@ -537,16 +542,16 @@ def _download(radio): # put radio in program mode and identify it _do_ident(radio, status) - # reset the progress bar in the UI - status.max = MEM_SIZE // BLOCK_SIZE + # reset the progress bar in the UI Bug #11851 BLOCKSIZE fix for KT-8900D + status.max = MEM_SIZE // radio._block_size status.msg = "Cloning from radio..." status.cur = 0 radio.status_fn(status) data = b"" - for addr in range(0, MEM_SIZE, BLOCK_SIZE): + for addr in range(0, MEM_SIZE, radio._block_size): # sending the read request - _send(radio, _make_frame("S", addr, BLOCK_SIZE)) + _send(radio, _make_frame("S", addr, radio._block_size)) # read d = _recv(radio, addr) @@ -657,6 +662,7 @@ class BTechMobileCommon(chirp_common.CloneModeRadio, """BTECH's UV-5001 and alike radios""" VENDOR = "BTECH" MODEL = "" + _block_size = BLOCK_SIZE # Bug 11851 should default to BLOCK_SIZE IDENT = "" BANDS = 2 COLOR_LCD = False @@ -4086,6 +4092,7 @@ class KT8900D(BTechColor): """QYT KT8900D""" VENDOR = "QYT" MODEL = "KT8900D" + _block_size = 0x10 # Bug 11851 BLOCKSIZE fix for KT-8900D BANDS = 2 LIST_TMR = LIST_TMR15 _vhf_range = (136000000, 175000000) @@ -5753,6 +5760,37 @@ class WP9900(BTechColorWP): self.set_options() +@directory.register +class KT5000(BTechColorWP): + """QYT KT-5000""" + # TODO: memory map is not EXACTLY the same as in WP12. E.g. setting + # "C display mode" overwrites VOX setting + VENDOR = "QYT" + MODEL = "KT-5000" + BANDS = 2 + UPLOAD_MEM_SIZE = 0X3100 + _power_levels = [chirp_common.PowerLevel("High", watts=25), + chirp_common.PowerLevel("Low", watts=5)] + _upper = 199 + _magic = MSTRING_KT5000 + _fileid = [KT5000_fp] + _gmrs = False + + def process_mmap(self): + """Process the mem map into the mem object""" + + # Get it + self._memobj = bitwise.parse(COLOR9900_MEM_FORMAT, self._mmap) + + # load specific parameters from the radio image + self.set_options() + + def get_features(self): + rf = super().get_features() + rf.has_settings = False + return rf + + @directory.register class GMRS20V2(BTechColorWP): """Baofeng Tech GMRS-20V2""" diff --git a/chirp/drivers/ft4.py b/chirp/drivers/ft4.py index 7fd92b6..6b463ff 100644 --- a/chirp/drivers/ft4.py +++ b/chirp/drivers/ft4.py @@ -345,13 +345,15 @@ def startcomms(radio, direction): if id_response != radio.id_str: substr0 = radio.id_str[:radio.id_str.find(b'\x00')] if id_response[:id_response.find(b'\x00')] != substr0: - msg = "ID mismatch. Expected" + util.hexprint(radio.id_str) - msg += ", Received:" + util.hexprint(id_response_mod) + msg = "ID mismatch.\nExpected:\n{}Received:\n{}".format( + util.hexprint(radio.id_str), util.hexprint(id_response_mod) + ) LOG.warning(msg) raise errors.RadioError("Incorrect ID read from radio.") else: - msg = "ID suspect. Expected" + util.hexprint(radio.id_str) - msg += ", Received:" + util.hexprint(id_response_mod) + msg = "ID suspect.\nExpected:\n{}Received:\n{}".format( + util.hexprint(radio.id_str), util.hexprint(id_response_mod) + ) LOG.warning(msg) return progressbar diff --git a/chirp/drivers/ft7800.py b/chirp/drivers/ft7800.py index 237e222..750e2c5 100644 --- a/chirp/drivers/ft7800.py +++ b/chirp/drivers/ft7800.py @@ -144,7 +144,8 @@ u8 checksum; MODES = ["FM", "AM", "NFM"] DUPLEX = ["", "", "-", "+", "split"] -STEPS = [5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0, 100.0] +STEPS = (5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0, 100.0) +STEPS_8800 = (5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0) SKIPS = ["", "S", "P", ""] CHARSET = ["%i" % int(x) for x in range(0, 10)] + \ @@ -251,7 +252,9 @@ class FTx800Radio(yaesu_clone.YaesuCloneModeRadio): """Base class for FT-7800,7900,8800,8900 radios""" BAUD_RATE = 9600 VENDOR = "Yaesu" - MODES = list(MODES) + MODES = MODES + STEPS = STEPS + _block_size = 64 POWER_LEVELS_VHF = [chirp_common.PowerLevel("Hi", watts=50), @@ -297,10 +300,10 @@ class FTx800Radio(yaesu_clone.YaesuCloneModeRadio): rf.has_bank = False rf.has_ctone = False rf.has_dtcs_polarity = False - rf.valid_modes = MODES + rf.valid_modes = self.MODES rf.valid_tmodes = self.TMODES rf.valid_duplexes = ["", "-", "+", "split"] - rf.valid_tuning_steps = STEPS + rf.valid_tuning_steps = self.STEPS rf.valid_bands = [(108000000, 520000000), (700000000, 990000000)] rf.valid_skips = ["", "S", "P"] rf.valid_power_levels = self.POWER_LEVELS_VHF @@ -385,6 +388,12 @@ class FTx800Radio(yaesu_clone.YaesuCloneModeRadio): flgidx = (mem.number - 1) % 4 _flg["skip%i" % flgidx] = SKIPS.index(mem.skip) + def _get_mem_mode(self, mem, _mem): + mem.mode = self.MODES[_mem.mode] + + def _set_mem_mode(self, mem, _mem): + _mem.mode = self.MODES.index(mem.mode) + def get_memory(self, number): _mem = self._memobj.memory[number - 1] @@ -397,10 +406,12 @@ class FTx800Radio(yaesu_clone.YaesuCloneModeRadio): mem.freq = get_freq(int(_mem.freq) * 10000) mem.rtone = chirp_common.TONES[_mem.tone] mem.tmode = self.TMODES[_mem.tmode] - mem.mode = self.MODES[_mem.mode] + + self._get_mem_mode(mem, _mem) + mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs] if self.get_features().has_tuning_step: - mem.tuning_step = STEPS[_mem.tune_step] + mem.tuning_step = self.STEPS[_mem.tune_step] mem.duplex = DUPLEX[_mem.duplex] mem.offset = self._get_mem_offset(mem, _mem) mem.name = self._get_mem_name(mem, _mem) @@ -424,10 +435,12 @@ class FTx800Radio(yaesu_clone.YaesuCloneModeRadio): set_freq(mem.freq, _mem, "freq") _mem.tone = chirp_common.TONES.index(mem.rtone) _mem.tmode = self.TMODES.index(mem.tmode) - _mem.mode = self.MODES.index(mem.mode) + + self._set_mem_mode(mem, _mem) + _mem.dtcs = chirp_common.DTCS_CODES.index(mem.dtcs) if self.get_features().has_tuning_step: - _mem.tune_step = STEPS.index(mem.tuning_step) + _mem.tune_step = self.STEPS.index(mem.tuning_step) _mem.duplex = DUPLEX.index(mem.duplex) _mem.split = mem.duplex == "split" and int(mem.offset / 10000) or 0 if mem.power: @@ -796,7 +809,8 @@ MEM_FORMAT_8800 = """ struct { u8 used:1, unknown1:1, - mode:2, + wid_nar:1, + am:1, unknown2:1, duplex:3; bbcd freq[3]; @@ -811,7 +825,7 @@ struct { u8 namevalid:1, dtcs:7; u8 name[6]; -} memory[500]; +} memory[512]; #seekto 0x%X; struct { @@ -824,7 +838,7 @@ struct { skip1:2, skip2:2, skip3:2; -} flags[250]; +} flags[256]; #seekto 0x7B48; u8 checksum; @@ -849,6 +863,7 @@ class FT8800Radio(FTx800Radio): _memstart = 0x0000 TMODES = ["", "Tone", "TSQL", "DTCS"] + STEPS = STEPS_8800 @classmethod def get_prompts(cls): @@ -880,7 +895,7 @@ class FT8800Radio(FTx800Radio): rf = FTx800Radio.get_features(self) rf.has_sub_devices = self.VARIANT == "" rf.has_bank = True - rf.memory_bounds = (1, 500) + rf.memory_bounds = (1, 512) return rf def get_sub_devices(self): @@ -940,6 +955,21 @@ class FT8800Radio(FTx800Radio): _mem.namevalid = 1 _mem.nameused = bool(mem.name.rstrip()) + def _get_mem_mode(self, mem, _mem): + if _mem.am: + mem.mode = "AM" + else: + mem.mode = "NFM" if _mem.wid_nar else "FM" + + def _set_mem_mode(self, mem, _mem): + if mem.mode == "AM": + _mem.am = True + _mem.wid_nar = False + + else: + _mem.am = False + _mem.wid_nar = mem.mode == "NFM" + class FT8800RadioLeft(FT8800Radio): """Yaesu FT-8800 Left VFO subdevice""" @@ -991,7 +1021,7 @@ u8 checksum; @directory.register -class FT8900Radio(FT8800Radio): +class FT8900Radio(FTx800Radio): """Yaesu FT-8900""" MODEL = "FT-8900" @@ -1000,17 +1030,40 @@ class FT8900Radio(FT8800Radio): _block_lengths = [8, 14784, 1] MODES = ["FM", "NFM", "AM"] + TMODES = ["", "Tone", "TSQL", "DTCS"] + STEPS = STEPS - def get_bank_model(self): - return + @classmethod + def get_prompts(cls): + rp = chirp_common.RadioPrompts() + rp.pre_download = _( + "1. Turn radio off.\n" + "2. Connect cable to DATA jack.\n" + "3. Press and hold in the \"left\" [V/M] key while turning the\n" + " radio on.\n" + "4. Rotate the \"right\" DIAL knob to select \"CLONE START\".\n" + "5. Press the [SET] key. The display will disappear\n" + " for a moment, then the \"CLONE\" notation will appear.\n" + "6. After clicking OK, press the \"left\" [V/M] key to\n" + " send image.\n") + rp.pre_upload = _( + "1. Turn radio off.\n" + "2. Connect cable to DATA jack.\n" + "3. Press and hold in the \"left\" [V/M] key while turning the\n" + " radio on.\n" + "4. Rotate the \"right\" DIAL knob to select \"CLONE START\".\n" + "5. Press the [SET] key. The display will disappear\n" + " for a moment, then the \"CLONE\" notation will appear.\n" + "6. Press the \"left\" [LOW] key (\"CLONE -RX-\" will appear" + " on\n" + " the display).\n") + return rp def process_mmap(self): self._memobj = bitwise.parse(MEM_FORMAT_8900, self._mmap) def get_features(self): - rf = FT8800Radio.get_features(self) - rf.has_sub_devices = False - rf.has_bank = False + rf = FTx800Radio.get_features(self) rf.valid_modes = self.MODES rf.valid_bands = [(28000000, 29700000), (50000000, 54000000), @@ -1025,19 +1078,50 @@ class FT8900Radio(FT8800Radio): def _checksums(self): return [yaesu_clone.YaesuChecksum(0x0000, 0x39C7)] + def _get_mem_offset(self, mem, _mem): + if mem.duplex == "split": + return get_freq(int(_mem.split) * 10000) + + # The offset is packed into the upper two bits of the last four + # bytes of the name (?!) + val = 0 + for i in _mem.name[2:6]: + val <<= 2 + val |= ((i & 0xC0) >> 6) + + return (val * 5) * 10000 + + def _set_mem_offset(self, mem, _mem): + if mem.duplex == "split": + set_freq(mem.offset, _mem, "split") + return + + val = int(mem.offset / 10000) // 5 + for i in reversed(list(range(2, 6))): + _mem.name[i] = (_mem.name[i] & 0x3F) | ((val & 0x03) << 6) + val >>= 2 + + def _get_mem_name(self, mem, _mem): + name = "" + if _mem.namevalid: + for i in _mem.name: + index = int(i) & 0x3F + if index < len(CHARSET): + name += CHARSET[index] + + return name.rstrip() + + def _set_mem_name(self, mem, _mem): + _mem.name = [CHARSET.index(x) for x in mem.name.ljust(6)[:6]] + _mem.namevalid = 1 + _mem.nameused = bool(mem.name.rstrip()) + def _get_mem_skip(self, mem, _mem): return SKIPS[_mem.skip] def _set_mem_skip(self, mem, _mem): _mem.skip = SKIPS.index(mem.skip) - def get_memory(self, number): - mem = super().get_memory(number) - - _mem = self._memobj.memory[number - 1] - - return mem - def set_memory(self, mem): FT8800Radio.set_memory(self, mem) diff --git a/chirp/drivers/ga510.py b/chirp/drivers/ga510.py index e6741be..7a9d24c 100644 --- a/chirp/drivers/ga510.py +++ b/chirp/drivers/ga510.py @@ -72,7 +72,7 @@ def do_download(radio): data = bytes() for addr in range(0, 0x1C40, 0x40): cmd = struct.pack('>cHB', b'R', addr, 0x40) - LOG.debug('Reading block at %04x: %r' % (addr, cmd)) + radio.pipe.log('Reading block at %04x' % addr) radio.pipe.write(cmd) block = radio.pipe.read(0x44) @@ -106,7 +106,7 @@ def do_upload(radio): # here. for addr in range(0, 0x1C20, 0x20): cmd = struct.pack('>cHB', b'W', addr, 0x20) - LOG.debug('Writing block at %04x: %r' % (addr, cmd)) + radio.pipe.log('Writing block at %04x' % addr) block = radio._mmap[addr:addr + 0x20] radio.pipe.write(cmd) radio.pipe.write(block) diff --git a/chirp/drivers/generic_csv.py b/chirp/drivers/generic_csv.py index e19e4f8..ed1de4d 100644 --- a/chirp/drivers/generic_csv.py +++ b/chirp/drivers/generic_csv.py @@ -13,6 +13,7 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . +import io import os import csv import logging @@ -61,6 +62,7 @@ class CSVRadio(chirp_common.FileBackedRadio): NEEDS_COMPAT_SERIAL = True FILE_EXTENSION = "csv" FORMATS = [directory.register_format('CSV', '*.csv')] + SEPCHAR = ',' ATTR_MAP = { "Location": (int, "number"), @@ -91,6 +93,9 @@ class CSVRadio(chirp_common.FileBackedRadio): # Default to 50W self.memories[0].power = DEFAULT_POWER_LEVEL + def clear(self): + self.memories = [] + def __init__(self, pipe): chirp_common.FileBackedRadio.__init__(self, None) self.memories = [] @@ -191,6 +196,9 @@ class CSVRadio(chirp_common.FileBackedRadio): return self._clean(headers, line, mem) + def load_from(self, string): + self._load(io.StringIO(string, newline='')) + def load(self, filename=None): if filename is None and self._filename is None: raise errors.RadioError("Need a location to load from") @@ -204,7 +212,7 @@ class CSVRadio(chirp_common.FileBackedRadio): return self._load(f) def _load(self, f): - reader = csv.reader(f, delimiter=chirp_common.SEPCHAR, quotechar='"') + reader = csv.reader(f, delimiter=self.SEPCHAR, quotechar='"') self._comments = [] good = 0 @@ -226,7 +234,8 @@ class CSVRadio(chirp_common.FileBackedRadio): self.file_has_cTone = "cToneFreq" in header continue - if len(header) > len(line): + # Spreadsheets like to omit trailing empty columns in TSV + if len(header) > len(line) and not self.SEPCHAR.isspace(): LOG.error("Line %i has %i columns, expected %i", lineno, len(line), len(header)) self.errors.append("Column number mismatch on line %i" % @@ -235,7 +244,7 @@ class CSVRadio(chirp_common.FileBackedRadio): try: mem = self._parse_csv_data_line(header, line) - if mem is None: + if mem is None or mem.freq == 0: LOG.debug('Line %i did not contain a valid memory', lineno) continue @@ -262,24 +271,32 @@ class CSVRadio(chirp_common.FileBackedRadio): self._filename = filename with open(self._filename, "w", newline='', encoding='utf-8') as f: - comments = list(self._comments) - writer = csv.writer(f, delimiter=chirp_common.SEPCHAR) + self._write_to(f) + + def _write_to(self, f): + comments = list(self._comments) + writer = csv.writer(f, delimiter=self.SEPCHAR) + + for index, comment in comments[:]: + if index >= 0: + break + writer.writerow([comment]) + comments.pop(0) + writer.writerow(chirp_common.Memory.CSV_FORMAT) + + for mem in self.memories: for index, comment in comments[:]: - if index >= 0: + if index >= mem.number: break writer.writerow([comment]) comments.pop(0) + write_memory(writer, mem) - writer.writerow(chirp_common.Memory.CSV_FORMAT) - - for mem in self.memories: - for index, comment in comments[:]: - if index >= mem.number: - break - writer.writerow([comment]) - comments.pop(0) - write_memory(writer, mem) + def as_string(self): + string = io.StringIO(newline='') + self._write_to(string) + return string.getvalue() # MMAP compatibility def save_mmap(self, filename): @@ -332,7 +349,7 @@ class CSVRadio(chirp_common.FileBackedRadio): def get_raw_memory(self, number): return ",".join(chirp_common.Memory.CSV_FORMAT) + \ os.linesep + \ - ",".join(self.memories[number].to_csv()) + self.SEPCHAR.join(self.memories[number].to_csv()) @classmethod def match_model(cls, filedata, filename): @@ -566,3 +583,7 @@ class RTCSVRadio(CSVRadio): return filename.lower().endswith("." + cls.FILE_EXTENSION) and \ 'Receive Frequency' in firstline_fields + + +class TSVRadio(CSVRadio): + SEPCHAR = '\t' diff --git a/chirp/drivers/h777.py b/chirp/drivers/h777.py index c5ef877..0586fd0 100644 --- a/chirp/drivers/h777.py +++ b/chirp/drivers/h777.py @@ -98,24 +98,28 @@ TIMEOUTTIMER_LIST = ["Off", "30 seconds", "60 seconds", "90 seconds", "120 seconds", "150 seconds", "180 seconds", "210 seconds", "240 seconds", "270 seconds", "300 seconds"] +DTCS_FLAG = 0x80 +DTCS_REV_FLAG = 0x40 -def _h777_enter_programming_mode(radio): - serial = radio.pipe +def _h777_enter_programming_mode(serial, radio_cls): # increase default timeout from .25 to .5 for all serial communications serial.timeout = 0.5 try: serial.write(b"\x02") time.sleep(0.1) - serial.write(radio.PROGRAM_CMD) + serial.write(radio_cls.PROGRAM_CMD) ack = serial.read(1) - except: + except Exception as e: + LOG.warning('Failed to send program command: %s', e) raise errors.RadioError("Error communicating with radio") if not ack: - raise errors.RadioError("No response from radio") + raise errors.RadioError("No response from radio to program command") elif ack != CMD_ACK: + LOG.warning('Ack from program command was %r, expected %r', + ack, CMD_ACK) raise errors.RadioError("Radio refused to enter programming mode") try: @@ -125,37 +129,29 @@ def _h777_enter_programming_mode(radio): # version data and the last three bytes. We need to raise the # timeout so that the read doesn't finish early. ident = serial.read(8) - except: + except Exception as e: + LOG.warning('Failed to read ident: %s', e) raise errors.RadioError("Error communicating with radio") - # check if ident is OK - itis = False - for fp in radio.IDENT: - if fp in ident: - # got it! - itis = True - - break - - if itis is False: - LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident)) - raise errors.RadioError("Radio identification failed.") - - try: - serial.write(CMD_ACK) - ack = serial.read(1) - except: - raise errors.RadioError("Error communicating with radio") + if ident: + LOG.info('Radio identified with:\n%s', util.hexprint(ident)) + try: + serial.write(CMD_ACK) + ack = serial.read(1) + if ack != CMD_ACK: + raise errors.RadioError("Bad ACK after reading ident") + except: + raise errors.RadioError('No ACK after reading ident') + return ident - if ack != CMD_ACK: - raise errors.RadioError("Radio refused to enter programming mode") + raise errors.RadioError('No identification received from radio') -def _h777_exit_programming_mode(radio): - serial = radio.pipe +def _h777_exit_programming_mode(serial): try: serial.write(b"E") - except: + except Exception as e: + LOG.warning('Failed to send exit command: %s', e) raise errors.RadioError("Radio refused to exit programming mode") @@ -170,6 +166,8 @@ def _h777_read_block(radio, block_addr, block_size): serial.write(cmd) response = serial.read(4 + BLOCK_SIZE) if response[:4] != expectedresponse: + LOG.warning('Got %r expected %r' % (response[:4], + expectedresponse)) raise Exception("Error reading block %04x." % (block_addr)) block_data = response[4:] @@ -191,8 +189,7 @@ def _h777_write_block(radio, block_addr, block_size): cmd = struct.pack(">cHb", b'W', block_addr, BLOCK_SIZE) data = radio.get_mmap().get_byte_compatible()[block_addr:block_addr + 8] - LOG.debug("Writing Data:") - LOG.debug(util.hexprint(cmd + data)) + radio.pipe.log('Writing %i block at %04x' % (BLOCK_SIZE, block_addr)) try: serial.write(cmd + data) @@ -206,9 +203,26 @@ def _h777_write_block(radio, block_addr, block_size): "to radio at %04x" % block_addr) +def _h777_enter_single_programming_mode(radio): + ident = _h777_enter_programming_mode(radio.pipe, radio.__class__) + if not ident: + raise errors.RadioError('Radio did not identify') + if not any(rc_ident in ident for rc_ident in radio.IDENT): + LOG.warning('Expected %s for %s but got:\n%s', + radio.IDENT, radio.__class__.__name__, + util.hexprint(ident)) + raise errors.RadioError('Incorrect model') + + def do_download(radio): LOG.debug("download") - _h777_enter_programming_mode(radio) + + if len(radio.detected_models()) <= 1: + LOG.debug('Entering programming mode for %s', radio.__class__.__name__) + _h777_enter_single_programming_mode(radio) + else: + LOG.debug('Already in programming mode for %s', + radio.__class__.__name__) data = b"" @@ -222,13 +236,11 @@ def do_download(radio): status.cur = addr + BLOCK_SIZE radio.status_fn(status) + radio.pipe.log('Reading %i block at %04x' % (BLOCK_SIZE, addr)) block = _h777_read_block(radio, addr, BLOCK_SIZE) data += block - LOG.debug("Address: %04x" % addr) - LOG.debug(util.hexprint(block)) - - _h777_exit_programming_mode(radio) + _h777_exit_programming_mode(radio.pipe) return memmap.MemoryMapBytes(data) @@ -237,7 +249,7 @@ def do_upload(radio): status = chirp_common.Status() status.msg = "Uploading to radio" - _h777_enter_programming_mode(radio) + _h777_enter_single_programming_mode(radio) status.cur = 0 status.max = radio._memsize @@ -248,7 +260,7 @@ def do_upload(radio): radio.status_fn(status) _h777_write_block(radio, addr, BLOCK_SIZE) - _h777_exit_programming_mode(radio) + _h777_exit_programming_mode(radio.pipe) class ArcshellAR5(chirp_common.Alias): @@ -281,11 +293,6 @@ class TenwayTW325Alias(chirp_common.Alias): MODEL = 'TW-325' -class RetevisH777Alias(chirp_common.Alias): - VENDOR = 'Retevis' - MODEL = 'H777' - - @directory.register class H777Radio(chirp_common.CloneModeRadio): """HST H-777""" @@ -303,7 +310,7 @@ class H777Radio(chirp_common.CloneModeRadio): VALID_BANDS = (400000000, 490000000) MAX_VOXLEVEL = 5 ALIASES = [ArcshellAR5, ArcshellAR6, GV8SAlias, GV9SAlias, A8SAlias, - TenwayTW325Alias, RetevisH777Alias] + TenwayTW325Alias] SIDEKEYFUNCTION_LIST = ["Off", "Monitor", "Transmit Power", "Alarm"] SCANMODE_LIST = ["Carrier", "Time"] @@ -371,27 +378,31 @@ class H777Radio(chirp_common.CloneModeRadio): def get_raw_memory(self, number): return repr(self._memobj.memory[number - 1]) - def _decode_tone(self, val): - val = int(val) - if val == 16665: + def _decode_tone(self, memval): + memval[1].ignore_bits(DTCS_FLAG | DTCS_REV_FLAG) + is_dtcs = memval[1].get_bits(DTCS_FLAG) + is_rev = memval[1].get_bits(DTCS_REV_FLAG) + if memval.get_raw() == b"\xFF\xFF": return '', None, None - elif val >= 12000: - return 'DTCS', val - 12000, 'R' - elif val >= 8000: - return 'DTCS', val - 8000, 'N' + elif is_dtcs: + return 'DTCS', int(memval), 'R' if is_rev else 'N' else: - return 'Tone', val / 10.0, None + return 'Tone', int(memval) / 10.0, None def _encode_tone(self, memval, mode, value, pol): + memval[1].ignore_bits(DTCS_FLAG | DTCS_REV_FLAG) if mode == '': - memval[0].set_raw(0xFF) - memval[1].set_raw(0xFF) + memval.fill_raw(b'\xFF') elif mode == 'Tone': + memval[1].clr_bits(DTCS_FLAG | DTCS_REV_FLAG) memval.set_value(int(value * 10)) elif mode == 'DTCS': - flag = 0x80 if pol == 'N' else 0xC0 + memval[1].set_bits(DTCS_FLAG) + if pol == 'R': + memval[1].set_bits(DTCS_REV_FLAG) + else: + memval[1].clr_bits(DTCS_REV_FLAG) memval.set_value(value) - memval[1].set_bits(flag) else: raise Exception("Internal error: invalid mode `%s'" % mode) @@ -614,6 +625,37 @@ class H777Radio(chirp_common.CloneModeRadio): raise +@directory.register +class RetevisH777(H777Radio): + VENDOR = 'Retevis' + MODEL = 'H777' + ALIASES = [] + + @classmethod + def detect_from_serial(cls, pipe): + cls_to_ident = {rc: rc.IDENT for rc in cls.detected_models()} + for ident_rclass in reversed(cls.detected_models()): + ident = _h777_enter_programming_mode(pipe, ident_rclass) + for rclass, idents in cls_to_ident.items(): + if any(rc_ident in ident for rc_ident in idents): + LOG.debug('Detected %s', rclass.__name__) + return rclass + LOG.debug('Ident was %r, idents were %r', ident, idents) + + LOG.info('Did not identify radio as %s', rclass.__name__) + time.sleep(0.5) + _h777_exit_programming_mode(pipe) + time.sleep(1) + + raise errors.RadioError('Failed to identify with radio.') + + @classmethod + def match_model(cls, filedata, filename): + # This radio has always been post-metadata, so never do + # old-school detection + return False + + class H777TestCase(unittest.TestCase): def setUp(self): diff --git a/chirp/drivers/icf.py b/chirp/drivers/icf.py index cc4c9f8..bc62bd5 100644 --- a/chirp/drivers/icf.py +++ b/chirp/drivers/icf.py @@ -766,7 +766,12 @@ class IcomBankModel(chirp_common.BankModel): if index is None: return [] else: - return [self.get_mappings()[index]] + try: + return [self.get_mappings()[index]] + except IndexError: + LOG.error('Invalid bank index %i for memory %i' % ( + index, memory.number)) + return [] class IcomIndexedBankModel(IcomBankModel, @@ -944,7 +949,9 @@ class IcomCloneModeRadio(chirp_common.CloneModeRadio): nice_name = listname.split('_', 1)[0].upper() group = RadioSettingGroup('%s_list' % listname, '%s List' % nice_name) + charset = chirp_common.CHARSET_UPPER_NUMERIC + '-' for i, cs in enumerate(current): + cs = ''.join(filter(lambda c: c in charset, cs)) group.append(RadioSetting('%03i' % i, '%i' % i, RadioSettingValueString(0, 8, cs))) return group diff --git a/chirp/drivers/icf520.py b/chirp/drivers/icf520.py index 0304217..2caa5dc 100644 --- a/chirp/drivers/icf520.py +++ b/chirp/drivers/icf520.py @@ -337,8 +337,8 @@ TONES = [ DUPLEX = ["", "+", "-", "split", "off"] -# Valid values for programable keys. -# Hex numbers are used for unkown functions. +# Valid values for programmable keys. +# Hex numbers are used for unknown functions. KEY_FUNC = [ "Null", "CH Up", @@ -493,7 +493,7 @@ AUDIO_FILTER_VALUES = [ ] # Valid values for Mic Gain. -# Hex numbers are used for unkown functions. +# Hex numbers are used for unknown functions. MIC_GAIN_FUNC = [ "0x00", "1 Min", @@ -544,7 +544,7 @@ SCRAMBLER_GCODE_VALUES = [ ] # Valid values for Scrambler Synchronous Capture. -# Hex numbers are used for unkown functions. +# Hex numbers are used for unknown functions. SYN_CAPTURE_FUNC = [ "Standard", "0x01", @@ -797,7 +797,7 @@ class ICF621_2Radio(icf.IcomCloneModeRadio): memory.extra = RadioSettingGroup('extra', 'Extra') # Mask (Don't display) channel on radio. - # This is refered as Inhibit in the CS-F500 software. + # This is referred as Inhibit in the CS-F500 software. _disp_inhibit = RadioSetting( "disp_inhibit", "Mask", RadioSettingValueList( diff --git a/chirp/drivers/icomciv.py b/chirp/drivers/icomciv.py index ea87a63..af46fa9 100644 --- a/chirp/drivers/icomciv.py +++ b/chirp/drivers/icomciv.py @@ -655,6 +655,10 @@ class IcomCIVRadio(icf.IcomLiveRadio): loc = "number %i" % ch self._send_frame(f) f.read(self.pipe) + try: + self.get_memory(number) + except Exception as e: + LOG.exception('Failed to get/parse test memory: %s', e) if f.get_data() and f.get_data()[-1] == "\xFF": return "Memory " + loc + " empty." else: @@ -757,7 +761,7 @@ class IcomCIVRadio(icf.IcomLiveRadio): mem.name = str(memobj.name).rstrip() if self._rf.valid_tmodes: - mem.tmode = self._rf.valid_tmodes[memobj.tmode] + self._decode_tmode(mem, memobj) if self._rf.has_dtcs_polarity: if memobj.dtcs_polarity == 0x11: @@ -883,7 +887,7 @@ class IcomCIVRadio(icf.IcomLiveRadio): memobj.name = mem.name.ljust(name_length)[:name_length] if self._rf.valid_tmodes: - memobj.tmode = self._rf.valid_tmodes.index(mem.tmode) + self._encode_tmode(mem, memobj) if self._rf.has_ctone: memobj.ctone = int(mem.ctone * 10) @@ -930,6 +934,12 @@ class IcomCIVRadio(icf.IcomLiveRadio): f = self._recv_frame() LOG.debug("Result:\n%s" % util.hexprint(bytes(f.get_data()))) + def _encode_tmode(self, mem, memobj): + memobj.tmode = self._rf.valid_tmodes.index(mem.tmode) + + def _decode_tmode(self, mem, memobj): + mem.tmode = self._rf.valid_tmodes[memobj.tmode] + @directory.register class Icom7200Radio(IcomCIVRadio): @@ -1008,7 +1018,7 @@ class Icom7100Radio(IcomCIVRadio): self._rf.has_dtcs_polarity = False self._rf.has_dtcs = False self._rf.has_ctone = True - self._rf.has_offset = False + self._rf.has_offset = True self._rf.has_name = True self._rf.has_tuning_step = False self._rf.valid_modes = [ @@ -1338,6 +1348,12 @@ class Icom9700Radio(IcomCIVRadio): "RTTY-R", None, None, None, None, None, None, None, None, None, "DV", None, None, None, None, "DD", None, None, None, None, None, ] + _CROSS_MODES = { + 4: 'DTCS->', + 5: 'Tone->DTCS', + 6: 'DTCS->Tone', + 7: 'Tone->Tone', + } def get_sub_devices(self): return [Icom9700RadioBand(self, 1), @@ -1351,6 +1367,21 @@ class Icom9700Radio(IcomCIVRadio): self._rf.memory_bounds = (1, 99) self._classes['mem'] = IC9700MemFrame + def _decode_tmode(self, mem, memobj): + if int(memobj.tmode) in self._CROSS_MODES: + mem.tmode = 'Cross' + mem.cross_mode = self._CROSS_MODES[int(memobj.tmode)] + else: + return super()._decode_tmode(mem, memobj) + + def _encode_tmode(self, mem, memobj): + cmr = {v: k for k, v in self._CROSS_MODES.items()} + if mem.tmode == 'Cross': + memobj.tmode = cmr[mem.cross_mode] + print('Setting tmode to %s for %s' % (memobj.tmode, mem.tmode)) + else: + return super()._encode_tmode(mem, memobj) + class Icom9700RadioBand(Icom9700Radio): _SPECIAL_CHANNELS = { @@ -1397,7 +1428,8 @@ class Icom9700RadioBand(Icom9700Radio): def _initialize(self): super()._initialize() self._rf.has_name = True - self._rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS'] + self._rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross'] + self._rf.valid_cross_modes = list(self._CROSS_MODES.values()) self._rf.has_dtcs = True self._rf.has_dtcs_polarity = True self._rf.has_bank = True @@ -1433,6 +1465,7 @@ class Icom9700SatelliteBand(Icom9700Radio): super()._initialize() self._rf.has_name = True self._rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS'] + self._rf.has_ctone = True self._rf.has_dtcs = True self._rf.has_dtcs_polarity = True self._rf.has_bank = False diff --git a/chirp/drivers/ict10.py b/chirp/drivers/ict10.py new file mode 100644 index 0000000..a9b073f --- /dev/null +++ b/chirp/drivers/ict10.py @@ -0,0 +1,577 @@ +# Copyright 2008 Dan Smith +# +# 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 . + +import logging + +from chirp.drivers import icf +from chirp import chirp_common, bitwise, errors, directory +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueInteger, RadioSettingValueList, \ + RadioSettingValueBoolean, RadioSettingValueString, \ + RadioSettings + +LOG = logging.getLogger(__name__) + + +ICV86_MEM_FORMAT = """ +#seekto 0x020; +lbit pskips[208]; + +#seekto 0x040; +lbit skips[208]; + +#seekto 0x060; +lbit used[208]; + +struct { + #seekto 0x010; + char comment[16]; + + #seekto 0x0FD; + u8 wx_channel; + + #seekto 0x100; + u8 reserved1:6, + beep:2; + u8 reserved2:3, + tot:5; + u8 reserved3; + u8 reserved4:6, + auto_pwr:2; + u8 reserved5:6, + lockout:2; + u8 reserved6:7, + sql_delay:1; + u8 reserved7; + u8 reserved8:6, + disp_type:2; + u8 reserved9; + u8 reserved10:5, + pwr_save:3; + u8 reserved11:7, + dial_speedup:1; + u8 reserved12:6, + simple_mode:2; + u8 reserved13:7, + ant:1; + u8 reserved14:7, + monitor:1; + u8 reserved15; + u8 reserved16; + u8 reserved17:6, + pause_timer:2; + u8 reserved18; + u8 reserved19:7, + skip_scan:1; + u8 reserved20:6, + lcd:2; + u8 reserved21:7, + wx:1; + u8 reserved22:6, + mic:2; + u8 reserved23:4, + vox_gain:4; + u8 reserved24:5, + vox_delay:3; + u8 reserved25:5, + vox_tot:3; + u8 reserved26; + u8 reserved27; + u8 reserved28:5, + edge:3; + u8 reserved29; + u8 reserved30:7, + auto_low:1; + u8 reserved31:7, + volt:1; + u8 reserved32:7, + ctcss_burst:1; + u8 reserved33; + u8 reserved34; + u8 reserved35; + u8 reserved36:7, + vox:1; + u8 reserved37; + u8 reserved38; + u8 reserved39:6, + p_short:2; + u8 reserved40:6, + p_long:2; +} settings; + +#seekto 0x0240; +struct { + ul32 freq; + ul32 offset; + char name[6]; + u8 reserved1:2, + rtone:6; + u8 reserved2:2, + ctone:6; + u8 reserved3:1, + dtcs:7; + u8 reserved4:4, + tuning_step:4; + u8 reserved5:2, + mode:1, + rev:1, + duplex:2, + reserved6:2; + u8 reserved7:2, + dtcs_polarity:2, + tmode:4; + u8 reserved8:5, + tx_inhibit:1, + power:2; + u8 reserved9; + u8 reserved10; + u8 reserved11; +} memory[208]; + +""" + +SPECIAL = { + "1A": 200, "1B": 201, + "2A": 202, "2B": 203, + "3A": 204, "3B": 205, + "C0": 206, "C1": 207, +} + +TMODES = ["", "Tone", "TSQL", "DTCS"] +MODES = ["FM", "NFM"] +SKIPS = ["", "S", "P"] +DUPLEXES = ["", "-", "+"] +DTCS_POLARITY = ["NN", "NR", "RN", "RR"] +TUNING_STEPS = [5., 10., 12.5, 15., 20., 25., 30., 50., 100., 125., 200.] +POWER_LEVELS = [ + chirp_common.PowerLevel("High", watts=5.0), + chirp_common.PowerLevel("Low", watts=0.5), + chirp_common.PowerLevel("Mid", watts=2.5), +] + + +@directory.register +class ICVT10Radio(icf.IcomCloneModeRadio): + """Icom IC-T10""" + VENDOR = "Icom" + MODEL = "IC-T10" + + _model = "\x43\x28\x00\x01" + _memsize = 5888 + _endframe = "Icom Inc\x2eB8" + + _ranges = [(0x0000, 5888, 32)] + + def get_features(self): + rf = chirp_common.RadioFeatures() + + rf.memory_bounds = (0, 199) + rf.valid_modes = MODES + rf.valid_tmodes = TMODES + rf.valid_duplexes = DUPLEXES + rf.valid_tuning_steps = TUNING_STEPS + rf.valid_power_levels = POWER_LEVELS + rf.valid_skips = SKIPS + rf.valid_name_length = 6 + rf.valid_special_chans = list(SPECIAL.keys()) + rf.valid_bands = [(136000000, 174000000), (400000000, 479000000)] + rf.has_ctone = True + rf.has_offset = True + rf.has_bank = False + rf.has_settings = True + + return rf + + def __init__(self, pipe): + icf.IcomCloneModeRadio.__init__(self, pipe) + + def sync_in(self): + icf.IcomCloneModeRadio.sync_in(self) + + def sync_out(self): + icf.IcomCloneModeRadio.sync_out(self) + + def process_mmap(self): + self._memobj = bitwise.parse(ICV86_MEM_FORMAT, self._mmap) + + def get_settings(self): + _settings = self._memobj.settings + + setmode = RadioSettingGroup("setmode", "Set Mode") + assign = RadioSettingGroup("assign", "Key Assign") + display = RadioSettingGroup("display", "Display") + sounds = RadioSettingGroup("sounds", "Sounds") + scan = RadioSettingGroup("Scan", "Scan") + fm = RadioSettingGroup("fm", "FM Radio") + wx = RadioSettingGroup("wx", "WX") + + settings = RadioSettings( + setmode, assign, display, sounds, scan, fm, wx) + + # Timeout Timer + opts = ["Off"] + ["%s min" % x for x in range(1, 31)] + setmode.append( + RadioSetting( + "tot", "Timeout Timer", + RadioSettingValueList(opts, current_index=_settings.tot))) + + # Auto Power Off + opts = ["Off", "30 min", "1 hr", "2 hrs"] + setmode.append( + RadioSetting( + "auto_pwr", "Auto Power Off", + RadioSettingValueList(opts, current_index=_settings.auto_pwr))) + + # Lockout + opts = ["Off", "Rpt", "Busy"] + setmode.append( + RadioSetting( + "lockout", "Lockout", + RadioSettingValueList(opts, current_index=_settings.lockout))) + + # Squelch Delay + opts = ["Short", "Long"] + setmode.append( + RadioSetting( + "sql_delay", "Squelch Delay", + RadioSettingValueList( + opts, current_index=_settings.sql_delay))) + + # Power Save + opts = ["Off", "1:2", "1:8", "1:16", "Auto"] + setmode.append( + RadioSetting( + "pwr_save", "Power Save", + RadioSettingValueList(opts, current_index=_settings.pwr_save))) + + # Dial Speed-up + setmode.append( + RadioSetting( + "dial_speedup", "Dial Speed-Up", + RadioSettingValueBoolean(bool(_settings.dial_speedup)))) + + # Mic Simple Mode + opts = ["Simple", "Normal-1", "Normal-2"] + setmode.append( + RadioSetting( + "simple_mode", "Mic Simple Mode", + RadioSettingValueList( + opts, current_index=_settings.simple_mode))) + + # Mic Gain + rs = RadioSetting( + "mic", "Mic Gain", + RadioSettingValueInteger(1, 4, _settings.mic + 1)) + rs.set_apply_callback( + lambda s, obj: setattr(obj, s.get_name(), int(s.value) - 1), + self._memobj.settings) + setmode.append(rs) + + # Auto Low Power + setmode.append( + RadioSetting( + "auto_low", "Auto Low Power", + RadioSettingValueBoolean(bool(_settings.auto_low)))) + + # Vox Function + setmode.append( + RadioSetting( + "vox", "Vox Function", + RadioSettingValueBoolean(bool(_settings.vox)))) + + # Vox Gain + opts = ["Off"] + ["%s" % x for x in range(1, 11)] + setmode.append( + RadioSetting( + "vox_gain", "Vox Gain", + RadioSettingValueList( + opts, current_index=_settings.vox_gain))) + + # Vox Delay + opts = ["0.5 seconds", "1.0 seconds", "1.5 seconds", "2.0 seconds", + "2.5 seconds", "3.0 seconds"] + setmode.append( + RadioSetting( + "vox_delay", "Vox Delay", + RadioSettingValueList( + opts, current_index=_settings.vox_delay))) + + # VOX Time out Timer + opts = ["Off", "1 min", "2 min", "3 min", "4 min", "5 min", + "10 min", "15 min"] + setmode.append( + RadioSetting( + "vox_tot", "VOX Time-Out Timer", + RadioSettingValueList(opts, current_index=_settings.vox_tot))) + + # CTCSS Burst + setmode.append( + RadioSetting( + "ctcss_burst", "CTCSS Burst", + RadioSettingValueBoolean(bool(_settings.ctcss_burst)))) + + # Monitor + opts = ["Push", "Hold"] + setmode.append( + RadioSetting( + "monitor", "Monitor", + RadioSettingValueList(opts, current_index=_settings.monitor))) + + # Comment + setmode.append( + RadioSetting( + "comment", "Comment", + RadioSettingValueString( + 0, 16, str(_settings.comment).rstrip(), autopad=False))) + + # P (Short) + opts = ["Null", "TS", "MHz", "T-CALL"] + assign.append( + RadioSetting( + "p_short", "P (Short)", + RadioSettingValueList(opts, current_index=_settings.p_short))) + + # P (Long) + opts = ["Null", "TS", "MHz", "T-CALL"] + assign.append( + RadioSetting( + "p_long", "P (Short)", + RadioSettingValueList(opts, current_index=_settings.p_long))) + + # Backlight + opts = ["Off", "On", "Auto"] + display.append( + RadioSetting( + "lcd", "Backlight", + RadioSettingValueList(opts, current_index=_settings.lcd))) + + # Display Type + opts = ["Frequency", "Channel", "Name"] + display.append( + RadioSetting( + "disp_type", "Display Type", + RadioSettingValueList( + opts, current_index=_settings.disp_type))) + + # Voltage Indicator + opts = ["Off", "On"] + display.append( + RadioSetting( + "volt", "Voltage Indicator", + RadioSettingValueList(opts, current_index=_settings.volt))) + + # Timeout Timer + opts = ["Off"] + ["%d" % x for x in range(1, 4)] + sounds.append( + RadioSetting( + "beep", "Beep Level", + RadioSettingValueList(opts, current_index=_settings.beep))) + + # Program Skip Scan + scan.append( + RadioSetting( + "skip_scan", "Program Skip Scan", + RadioSettingValueBoolean(bool(_settings.skip_scan)))) + + # Edge + opts = ["All", "Band", "P1", "P2", "P3"] + scan.append( + RadioSetting( + "edge", "Edge", + RadioSettingValueList(opts, current_index=_settings.edge))) + + # Pause Timer + opts = ["T-5", "T-10", "T-15", "P-2"] + scan.append( + RadioSetting( + "pause_timer", "Pause Timer", + RadioSettingValueList( + opts, current_index=_settings.pause_timer))) + + # Earphone Antenna + opts = ["Not Used", "Use"] + fm.append( + RadioSetting( + "ant", "Earphone Antenna", + RadioSettingValueList(opts, current_index=_settings.ant))) + + # WX Alert + wx.append( + RadioSetting( + "wx", "WX Alert", + RadioSettingValueBoolean(bool(_settings.wx)))) + + # Mic Gain + rs = RadioSetting( + "wx_channel", "WX Channel", + RadioSettingValueInteger(1, 10, _settings.wx_channel + 1)) + rs.set_apply_callback( + lambda s, obj: setattr(obj, s.get_name(), int(s.value) - 1), + self._memobj.settings) + wx.append(rs) + + return settings + + def set_settings(self, settings): + _settings = self._memobj.settings + for element in settings: + 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: + setting = element.get_name() + LOG.debug("Setting %s = %s" % (setting, element.value)) + setattr(_settings, setting, element.value) + except Exception: + LOG.debug(element.get_name()) + raise + + def _get_extra(self, mem): + ext = RadioSettingGroup("extra", "Extra") + + rev = RadioSetting("rev", "Reverse duplex", + RadioSettingValueBoolean(bool(mem.rev))) + rev.set_doc("Reverse duplex") + ext.append(rev) + + tx_inhibit = RadioSetting("tx_inhibit", "Tx inhibit", + RadioSettingValueBoolean( + bool(mem.tx_inhibit))) + tx_inhibit.set_doc("Tx inhibit") + ext.append(tx_inhibit) + + return ext + + def _get_memory(self, number, extd_number): + mem = chirp_common.Memory() + mem.number = number + + _mem = self._memobj.memory[number] + + if extd_number is None: + _usd = self._memobj.used[number] + _skp = self._memobj.skips[number] + _psk = self._memobj.pskips[number] + else: + mem.extd_number = extd_number + mem.immutable = ["number", "extd_number"] + if (number >= 206): + mem.immutable.append("skip") + _usd = self._memobj.used[number] if (number < 206) else None + _skp = self._memobj.skips[number] if (number < 206) else None + _psk = self._memobj.pskips[number] if (number < 206) else None + + if _usd is not None and _usd: + mem.empty = True + return mem + + mem.freq = _mem.freq + mem.offset = int(_mem.offset) + mem.name = str(_mem.name).rstrip() + mem.rtone = chirp_common.TONES[_mem.rtone] + mem.ctone = chirp_common.TONES[_mem.ctone] + mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs] + mem.tuning_step = TUNING_STEPS[_mem.tuning_step] + mem.mode = MODES[_mem.mode] + mem.duplex = DUPLEXES[_mem.duplex] + mem.dtcs_polarity = DTCS_POLARITY[_mem.dtcs_polarity] + mem.tmode = TMODES[_mem.tmode] + mem.power = POWER_LEVELS[_mem.power] + + mem.extra = self._get_extra(_mem) + + if _skp is not None: + mem.skip = (_psk and "P") or (_skp and "S") or "" + + return mem + + def get_memory(self, number): + extd_number = None + if isinstance(number, str): + try: + extd_number = number + number = dict(SPECIAL)[number] + except KeyError: + raise errors.InvalidMemoryLocation( + "Unknown channel %s" % number) + + return self._get_memory(number, extd_number) + + def _fill_memory(self, number): + _mem = self._memobj.memory[number] + + # Default values + _mem.fill_raw(b'\x00') + _mem.freq = 146010000 + _mem.offset = 146010000 + _mem.name = str("").ljust(6) + _mem.rtone = 0x8 + _mem.ctone = 0x8 + + def _set_memory(self, mem): + _mem = self._memobj.memory[mem.number] + _usd = self._memobj.used[mem.number] if mem.number < 206 else None + _skp = self._memobj.skips[mem.number] if mem.number < 206 else None + _psk = self._memobj.pskips[mem.number] if mem.number < 206 else None + + if mem.empty: + self._fill_memory(mem.number) + if _usd is not None: + _usd |= 1 + return + + if _usd is None or _usd: + self._fill_memory(mem.number) + + _mem.freq = mem.freq + _mem.offset = int(mem.offset) + _mem.name = str(mem.name).ljust(6) + _mem.rtone = chirp_common.TONES.index(mem.rtone) + _mem.ctone = chirp_common.TONES.index(mem.ctone) + _mem.dtcs = chirp_common.DTCS_CODES.index(mem.dtcs) + _mem.tuning_step = TUNING_STEPS.index(mem.tuning_step) + _mem.mode = MODES.index(mem.mode) + _mem.duplex = DUPLEXES.index(mem.duplex) + _mem.dtcs_polarity = DTCS_POLARITY.index(mem.dtcs_polarity) + _mem.tmode = TMODES.index(mem.tmode) + _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power) + + for setting in mem.extra: + setattr(_mem, setting.get_name(), setting.value) + + if _usd is not None: + _usd &= 0 + + if _skp is not None: + _skp &= 0 + _psk &= 0 + if mem.skip == "S": + _skp |= 1 + elif mem.skip == "P": + _psk |= 1 + + def set_memory(self, mem): + return self._set_memory(mem) + + def get_raw_memory(self, number): + return repr(self._memobj.memory[number]) + \ + repr(self._memobj.used[(number)]) diff --git a/chirp/drivers/icv80.py b/chirp/drivers/icv80.py index 1564a9e..b6bcf3d 100644 --- a/chirp/drivers/icv80.py +++ b/chirp/drivers/icv80.py @@ -410,7 +410,7 @@ class ICV80Radio(icf.IcomCloneModeRadio, chirp_common.ExperimentalRadio): if mem.extd_number == "": mem.name = str(_mem.name).rstrip() mem.skip = (_skip & bit) and "S" or "" - if _mem.tx_inhibit: + if not _mem.tx_inhibit: mem.duplex = 'off' else: mem.duplex = DUPLEXES[_mem.duplex] @@ -497,6 +497,7 @@ class ICV80Radio(icf.IcomCloneModeRadio, chirp_common.ExperimentalRadio): _mem.duplex = DUPLEXES.index(mem.duplex) except ValueError: _mem.duplex = 0 + _mem.tx_inhibit = mem.duplex != 'off' power = mem.power or POWER_LEVELS[0] _mem.power = POWER_LEVELS.index(power) _mem.tuning_step = TUNING_STEPS.index(mem.tuning_step) @@ -506,7 +507,6 @@ class ICV80Radio(icf.IcomCloneModeRadio, chirp_common.ExperimentalRadio): _mem.ctone = chirp_common.TONES.index(mem.ctone) _mem.dtcs = chirp_common.DTCS_CODES.index(mem.dtcs) _mem.dtcs_polarity = DTCS_POLARITY.index(mem.dtcs_polarity) - _mem.tx_inhibit = mem.duplex == 'off' # Set used _unused &= ~bit diff --git a/chirp/drivers/id51.py b/chirp/drivers/id51.py index 0146036..0e6b09f 100644 --- a/chirp/drivers/id51.py +++ b/chirp/drivers/id51.py @@ -127,6 +127,9 @@ class ID51Radio(id31.ID31Radio): def get_features(self): rf = super(ID51Radio, self).get_features() rf.valid_bands = [(108000000, 174000000), (400000000, 479000000)] + # The ID-51 D-STAR support seems broken, so disable getting settings + # that will contain the base-class call list support. + rf.has_settings = False return rf def process_mmap(self): diff --git a/chirp/drivers/kenwood_live.py b/chirp/drivers/kenwood_live.py index 79cffe1..52475bc 100644 --- a/chirp/drivers/kenwood_live.py +++ b/chirp/drivers/kenwood_live.py @@ -1046,6 +1046,7 @@ THK2_CHARS = chirp_common.CHARSET_UPPER_NUMERIC + "-/" class THK2Radio(KenwoodLiveRadio): """Kenwood TH-K2""" MODEL = "TH-K2" + HARDWARE_FLOW = False _kenwood_valid_tones = list(KENWOOD_TONES) diff --git a/chirp/drivers/kg935g.py b/chirp/drivers/kg935g.py index a2c8deb..51157de 100644 --- a/chirp/drivers/kg935g.py +++ b/chirp/drivers/kg935g.py @@ -74,6 +74,22 @@ config_map_935G = ( # map address, write size, write count (0x4780, 32, 375), # Memory Names 0-999 (0x7670, 8, 125), # Ch Valid bytes 0-999 ) +config_map_935H = ( # map address, write size, write count + # (0x00, 64, 512), #- Use for full upload testing + (0x14, 1, 1), # Tx Range Lock + (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] @@ -969,6 +985,283 @@ _MEM_FORMAT_UV8H = """ u8 valid[1000]; """ +_MEM_FORMAT_935H = """ + #seekto 0x0014; + struct { + u8 txlocked; + } lock; + + #seekto 0x0044; + struct { + u32 rx_start; + u32 rx_stop; + u32 tx_start; + u32 tx_stop; + } uhf_limits; + + #seekto 0x0054; + struct { + u32 rx_start; + u32 rx_stop; + u32 tx_start; + u32 tx_stop; + } vhf_limits; + + #seekto 0x0400; + struct { + char oem1[8]; + char unknown[2]; + u8 unknown2[10]; + u8 unknown3[10]; + u8 unknown4[8]; + char oem2[10]; + u8 version[6]; + char date[8]; + u8 unknown5[2]; + char model[8]; + } oem_info; + + #seekto 0x0480; + struct { + u16 Group_lower1; + u16 Group_upper1; + u16 Group_lower2; + u16 Group_upper2; + u16 Group_lower3; + u16 Group_upper3; + u16 Group_lower4; + u16 Group_upper4; + u16 Group_lower5; + u16 Group_upper5; + u16 Group_lower6; + u16 Group_upper6; + u16 Group_lower7; + u16 Group_upper7; + u16 Group_lower8; + u16 Group_upper8; + u16 Group_lower9; + u16 Group_upper9; + u16 Group_lower10; + u16 Group_upper10; + } scan_groups; + + #seekto 0x0500; + struct { + u8 cid[6]; + } call_ids[20]; + + #seekto 0x0580; + struct { + char call_name1[6]; + char call_name2[6]; + char call_name3[6]; + char call_name4[6]; + char call_name5[6]; + char call_name6[6]; + char call_name7[6]; + char call_name8[6]; + char call_name9[6]; + char call_name10[6]; + char call_name11[6]; + char call_name12[6]; + char call_name13[6]; + char call_name14[6]; + char call_name15[6]; + char call_name16[6]; + char call_name17[6]; + char call_name18[6]; + char call_name19[6]; + char call_name20[6]; + } call_names; + + + #seekto 0x0600; + struct { + u16 FM_radio1; + u16 FM_radio2; + u16 FM_radio3; + u16 FM_radio4; + u16 FM_radio5; + u16 FM_radio6; + u16 FM_radio7; + u16 FM_radio8; + u16 FM_radio9; + u16 FM_radio10; + u16 FM_radio11; + u16 FM_radio12; + u16 FM_radio13; + u16 FM_radio14; + u16 FM_radio15; + u16 FM_radio16; + u16 FM_radio17; + u16 FM_radio18; + u16 FM_radio19; + u16 FM_radio20; + u16 unknown_pad_x0640[235]; + u8 unknown07fe; + u8 unknown07ff; + u8 ponmsg; + char dispstr[15]; + u8 unknown0810; + u8 unknown0811; + u8 unknown0812; + u8 unknown0813; + u8 unknown0814; + u8 voice; + u8 timeout; + u8 toalarm; + u8 channel_menu; + u8 power_save; + u8 autolock; + u8 keylock; + u8 beep; + u8 stopwatch; + u8 vox; + u8 scan_rev; + u8 backlight; + u8 roger_beep; + char mode_sw_pwd[6]; + char reset_pwd[6]; + u16 pri_ch; + u8 ani_sw; + u8 ptt_delay; + u8 ani_code[6]; + u8 dtmf_st; + u8 BCL_A; + u8 BCL_B; + u8 ptt_id; + u8 prich_sw; + u8 rpttype; + u8 rptspk; + u8 rptptt; + u8 alert; + u8 pf1_shrt; + u8 pf1_long; + u8 pf2_shrt; + u8 pf2_long; + u8 unknown0845; + u8 work_mode_a; + u8 work_mode_b; + u8 dtmf_tx_time; + u8 dtmf_interval; + u8 main_band; + u16 work_ch_a; + u16 work_ch_b; + u8 unknown084f; + u8 unknown0850; + u8 unknown0851; + u8 unknown0852; + u8 unknown0853; + u8 unknown0854; + u8 unknown0855; + u8 unknown0856; + u8 unknown0857; + u8 unknown0858; + u8 unknown0859; + u8 unknown085a; + u8 unknown085b; + u8 unknown085c; + u8 unknown085d; + u8 unknown085e; + u8 unknown085f; + u8 unknown0860; + u8 TDR_single_mode; + u8 ring_time; + u8 ScnGrpA_Act; + u8 ScnGrpB_Act; + u8 unknown0865; + u8 rpt_tone; + u8 unknown0867; + u8 scan_det; + u8 ToneScnSave; + u8 unknown086a; + u8 smuteset; + u8 cur_call_grp; + u8 DspBrtAct; + u8 DspBrtSby; + u8 unknown086f; + u8 theme; + u8 batt_ind; + u8 wxalert; + u8 wxalert_type; + u8 VFO_repeater_a; + u8 VFO_repeater_b; + u8 sim_rec; + u8 unknown0877; + u8 unknown0878; + u8 unknown0879; + u8 unknown087a; + u8 unknown087b; + u8 unknown087c; + u8 unknown087d; + u8 unknown087e; + u8 unknown087f; + } settings; + + #seekto 0x0880; + struct { + u32 rxfreq; + u32 unknown0; + u16 rxtone; + u16 txtone; + u8 scrambler:4, + power:4; + u8 unknown3:1, + unknown5:2, + unknown4:1, + cmpndr:1, + mute_mode:2, + iswide:1; + u8 step; + u8 squelch; + } vfoa; + + #seekto 0x08c0; + struct { + u32 rxfreq; + u32 unknown0; + u16 rxtone; + u16 txtone; + u8 scrambler:4, + power:4; + u8 unknown3:1, + unknown5:2, + unknown4:1, + cmpndr:1, + mute_mode:2, + iswide:1; + u8 step; + u8 squelch; + } vfob; + + #seekto 0x0900; + struct { + u32 rxfreq; + u32 txfreq; + u16 rxtone; + u16 txtone; + u8 scrambler:4, + power:4; + u8 unknown3:2, + scan_add:1, + unknown4:1, + compander:1, + mute_mode:2, + iswide:1; + u8 unknown5; + u8 unknown6; + } memory[1000]; + + #seekto 0x4780; + struct { + u8 name[8]; + u8 unknown[4]; + } names[1000]; + + #seekto 0x7670; + u8 valid[1000]; + """ + # Support for the Wouxun KG-935G radio # Serial coms are at 19200 baud @@ -1035,6 +1328,7 @@ class KG935GRadio(chirp_common.CloneModeRadio, chirp_common.PowerLevel("M", watts=4.5), chirp_common.PowerLevel("H", watts=5.5)] _record_start = 0x7C + config_map = config_map_935G def _checksum(self, data): cs = 0 @@ -1178,7 +1472,7 @@ class KG935GRadio(chirp_common.CloneModeRadio, return def _do_upload(self): - cfgmap = config_map_935G + cfgmap = self.config_map for start, blocksize, count in cfgmap: end = start + (blocksize * count) @@ -1466,6 +1760,7 @@ class KG935GRadio(chirp_common.CloneModeRadio, def _get_settings(self): _settings = self._memobj.settings + # _txlock = self._memobj.lock _vfoa = self._memobj.vfoa _vfob = self._memobj.vfob _scan = self._memobj.scan_groups @@ -1497,7 +1792,8 @@ class KG935GRadio(chirp_common.CloneModeRadio, ani_msg = "ANI-ID Switch (ANI-SW)" pttdly_msg = "PTT-DLY" idtx_msg = "PTT-ID" - elif self.MODEL == "KG-935G Plus": + elif (self.MODEL == "KG-935G Plus" or + self.MODEL == "KG-935H"): themelist = THEME_LIST_935GPLUS vfoa_grp_label = "Freq Mode A Settings" vfob_grp_label = "Freq Mode B Settings" @@ -1578,7 +1874,7 @@ class KG935GRadio(chirp_common.CloneModeRadio, RadioSettingValueBoolean(_settings.wxalert)) cfg_grp.append(rs) - if self.MODEL == "KG-935G Plus": + if (self.MODEL == "KG-935G Plus" or self.MODEL == "KG-935H"): rs = RadioSetting("wxalert_type", "Weather Alert Notification", RadioSettingValueList(WX_TYPE, current_index=_settings. @@ -1705,6 +2001,18 @@ class KG935GRadio(chirp_common.CloneModeRadio, HOLD_TIMES, current_index=_settings.rpt_hold)) cfg_grp.append(rs) + if self.MODEL == "KG-935H": + rs = RadioSetting("rpttype", "Repeater Type", + RadioSettingValueMap(RPTTYPE_MAP, + _settings.rpttype)) + cfg_grp.append(rs) + rs = RadioSetting("rptspk", "Repeater Speaker", + RadioSettingValueBoolean(_settings.rptspk)) + cfg_grp.append(rs) + rs = RadioSetting("rptptt", "Repeater PTT", + RadioSettingValueBoolean(_settings.rptptt)) + cfg_grp.append(rs) + rs = RadioSetting("rpt_tone", "Repeater Tone", RadioSettingValueBoolean(_settings.rpt_tone)) cfg_grp.append(rs) @@ -1730,7 +2038,7 @@ class KG935GRadio(chirp_common.CloneModeRadio, _settings.dtmf_interval)) cfg_grp.append(rs) - if self.MODEL == "KG-935G Plus": + if (self.MODEL == "KG-935G Plus" or self.MODEL == "KG-935H"): rs = RadioSetting("batt_ind", "Battery Indicator", RadioSettingValueList( BATT_DISP_LIST, @@ -2062,6 +2370,12 @@ class KG935GRadio(chirp_common.CloneModeRadio, (self._memobj.uhf_limits.tx_stop / 100000.0), 0.000001, 6)) lmt_grp.append(rs) + if self.MODEL == "KG-935H": + val = self._memobj.lock.txlocked + rs = RadioSetting("lock.txlocked", + "Locked - Limits Tx to Factory Range", + RadioSettingValueBoolean(val)) + lmt_grp.append(rs) # OEM info def _decode(lst): @@ -2209,3 +2523,18 @@ class KGUV8HRadio(KG935GRadio): def process_mmap(self): self._memobj = bitwise.parse(_MEM_FORMAT_UV8H, self._mmap) + + +@directory.register +class KG935HRadio(KG935GRadio): + + """Wouxun KG-935H""" + VENDOR = "Wouxun" + MODEL = "KG-935H" + POWER_LEVELS = [chirp_common.PowerLevel("L", watts=2.0), + chirp_common.PowerLevel("M", watts=5.0), + chirp_common.PowerLevel("H", watts=8.0)] + config_map = config_map_935H + + def process_mmap(self): + self._memobj = bitwise.parse(_MEM_FORMAT_935H, self._mmap) diff --git a/chirp/drivers/mml_jc8810.py b/chirp/drivers/mml_jc8810.py index f21eeee..1ba0a5d 100644 --- a/chirp/drivers/mml_jc8810.py +++ b/chirp/drivers/mml_jc8810.py @@ -32,6 +32,7 @@ from chirp.settings import ( RadioSettingValueInteger, RadioSettingValueList, RadioSettingValueString, + RadioSettingValueMap, ) LOG = logging.getLogger(__name__) @@ -46,7 +47,7 @@ struct { scode:4; // Signaling u8 unknown2:6, // D pttid:2; // PTT-ID - u8 unknown3:6, // E + 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 @@ -269,6 +270,8 @@ ALL_SKEY_VALUES = [0xFF, 0x2D, 0x23] +SCRAMBLE_VALUEMAP = [("Off", 0x00), ("SCRAM1", 0x04), ("SCRAM2", 0x08)] + def _enter_programming_mode(radio): serial = radio.pipe @@ -628,6 +631,16 @@ class JC8810base(chirp_common.CloneModeRadio): mem.extra = RadioSettingGroup("Extra", "extra") + # Encryption + rs = RadioSettingValueList(ENCRYPT_LIST, current_index=_mem.encrypt) + rset = RadioSetting("encrypt", "Encryption", rs) + mem.extra.append(rset) + + # Scramble + rs = RadioSettingValueMap(SCRAMBLE_VALUEMAP, _mem.scramble) + rset = RadioSetting("scramble", "Scramble", rs) + mem.extra.append(rset) + # BCL (Busy Channel Lockout) rs = RadioSettingValueBoolean(_mem.bcl) rset = RadioSetting("bcl", "BCL", rs) @@ -1284,6 +1297,7 @@ class RT470Radio(JC8810base): b"\x00\x00\x00\x42\x00\x20\xF0\x04", b"\x00\x00\x00\x4A\x00\x20\xF8\x04", b"\x00\x00\x00\x3A\x00\x20\xE8\x04", # fw 1.25A + b"\x00\x00\x00\x42\x00\x20\xec\x04", # fw 1.27A ] # pcb 2 @@ -1364,24 +1378,27 @@ class RT470XRadio(RT470LRadio): def get_features(self): rf = super().get_features() rf.valid_modes.append('AM') + rf.valid_modes.append('NAM') rf.valid_bands = [(18000000, 1000000000)] return rf def validate_memory(self, mem): msgs = [] in_range = chirp_common.in_range - if in_range(mem.freq, [self._AIRBAND]) and not mem.mode == 'AM': + AM_mode = mem.mode == 'AM' or mem.mode == "NAM" + if in_range(mem.freq, [self._AIRBAND]) and not AM_mode: msgs.append(chirp_common.ValidationWarning( _('Frequency in this range requires AM mode'))) - if not in_range(mem.freq, [self._AIRBAND]) and mem.mode == 'AM': + if not in_range(mem.freq, [self._AIRBAND]) and AM_mode: msgs.append(chirp_common.ValidationWarning( _('Frequency in this range must not be AM mode'))) return msgs + super().validate_memory(mem) def get_memory(self, number): mem = super().get_memory(number) + _mem = self._memobj.memory[mem.number - 1] if chirp_common.in_range(mem.freq, [self._AIRBAND]): - mem.mode = 'AM' + mem.mode = _mem.narrow and "NAM" or "AM" return mem @@ -1563,6 +1580,7 @@ class RT630Radio(JC8810base): # ========== _fingerprint = [b"\x00\x00\x00\x32\x00\x20\xD8\x04", # fw 0.07 + b"\x00\x00\x00\x36\x00\x20\xDC\x04", # fw V0.09 20250703 ] POWER_LEVELS = [chirp_common.PowerLevel("H", watts=5.00), diff --git a/chirp/drivers/radioddity_gm30.py b/chirp/drivers/radioddity_gm30.py new file mode 100644 index 0000000..b08a241 --- /dev/null +++ b/chirp/drivers/radioddity_gm30.py @@ -0,0 +1,951 @@ +# Copyright 2025 Mike Iacovacci +# +# 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 . + +import struct +import logging + +from chirp import chirp_common, directory, memmap +from chirp import bitwise, errors +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueInteger, RadioSettingValueList, \ + RadioSettingValueBoolean, RadioSettingValueString, RadioSettings + +LOG = logging.getLogger(__name__) + +MEM_FORMAT = """ +struct{ + u8 unknown02[256]; +} unknown02[16]; +struct{ + u8 bootscrmode; + u8 bsmodepad[15]; + u8 bootscreen1[10]; + u8 bs1pad[6]; + u8 bootscreen2[10]; + u8 bs2pad[6]; + u8 unused[16]; + u8 timeout; + u8 squelch; + u8 vox_level; + u8 batt_save:4, + unk_bits:2, + work_mode:1, + voice_alert:1; + u8 backlight; + u8 beep_tone:1, + auto_key_lock:1, + unk_bit_2:1, + ctcss_revert:1, + scan_type:2, + side_tone:2; + u8 unk_bit_3:1, + standby:1, + roger:1, + alarm_mode:2, + alarm_sound:1, + fm_radio:1, + unk_bit_4:1; + u8 tail_revert; + u8 tail_delay; + u8 tbst; + u8 unk_bits_5:6, + a_ch_disp:1, + b_ch_disp:1; + u8 unk_sett[30]; + u8 passw_w_ena; + u8 passw_r_ena; + u8 passw_w_val[8]; + u8 passw_r_val[8]; + u8 unk_sett_2[5]; +} settings; +struct{ + u8 unusedsettings[32]; +} unusedsettings[124]; +struct{ + u8 entry[5]; +} dtmf_list[15]; +struct{ + u8 dtmf_l_pad[5]; + u8 radio_id[5]; + u8 unk_dtmf[11]; + u8 unk_dtmf_bits:6, + press_send:1, + release_send:1; + u8 delay_time; + u8 digit_dur; + u8 inter_dur; + u8 unk_dtmf_2[28]; +} dtmf; +struct{ + u8 unkdtmf[128]; +} unuseddtmf[31]; +struct{ + u8 unk_mem[16]; +} tuning; +struct { + lbcd rx_freq[4]; + lbcd tx_freq[4]; + u8 mem_changed; + lbcd rx_tone[2]; + lbcd tx_tone[2]; + u8 unk_mem2:1, + busy_lock:1, + ptt_id:2, + unk_mem3:1, + mode:1, + power:1, + unk_mem4:1; + u8 signal:4, + unk_mem5:2, + freq_hop:1, + scan:1; + u8 step; +} vfomemory[2]; +struct { + lbcd rx_freq[4]; + lbcd tx_freq[4]; + u8 mem_changed; + lbcd rx_tone[2]; + lbcd tx_tone[2]; + u8 unk_mem2:1, + busy_lock:1, + ptt_id:2, + unk_mem3:1, + mode:1, + power:1, + unk_mem4:1; + u8 signal:4, + unk_mem5:2, + freq_hop:1, + scan:1; + u8 step; +} memory[250]; +struct{ + u8 unused_memch[16]; +} unused_mem[3]; +struct{ + u8 unknown17[256]; +} unknown17[16]; +struct{ + u8 unknown18[256]; +} unknown18[16]; +struct{ + u8 unknown19[256]; +} unknown19[16]; +struct{ + char name[6]; + u8 pad[5]; +} memnames[250]; +struct{ + u8 unknames[64]; +} unknownnames [21]; +struct{ + u8 unknown25[256]; +} unknown25[16]; +struct{ + u8 unknown26[256]; +} unknown26[16]; +""" +# radio defines these types +# query each type to retrieve +# the mem location it is stored +TYPE_MAP = [ + (0x02, "unknown02"), + (0x04, "settings"), + (0x06, "dtmf"), + (0x16, "memories"), + (0x17, "unknown17"), + (0x18, "unknown18"), + (0x19, "unknown19"), + (0x24, "chan_names"), + (0x25, "unknown25"), + (0x26, "unknown26") +] + +# we only write these data types +# back to the radio. The 3rd tuple +# being the offset in _memobj +WRITE_MAP = [ + (0x04, "settings", 0x1000), + (0x06, "dtmf", 0x2000), + (0x16, "memories", 0x3000), + (0x24, "chan_names", 0x7000) +] + + +def do_ack_ack(serial): + serial.write(b'\x06') + ack = serial.read(1) + if ack != b'\x06': + err = f"Error expected 06 ack got {ack}" + LOG.debug(err) + raise errors.RadioError(err) + + +def raw_send(serial, data, exlen): + serial.write(data) + return serial.read(exlen) + + +def do_read_cmd(serial, cmd, exlen): + echo_ack = len(cmd) + 1 # ack 0x57 + echo of cmd + resp = raw_send(serial, b'\x52' + cmd, exlen + echo_ack) + if resp[0] != 0x57: + raise errors.RadioError(f"Read CMD resp failed got {resp}") + if len(resp[echo_ack:]) != exlen: + raise errors.RadioError(f"Read CMD resp expect len={exlen} got {resp}") + do_ack_ack(serial) + return resp[echo_ack:] + + +def enter_prog(serial): + resp = raw_send(serial, b'PSEARCH', 8) + if len(resp) != 8: + err = ("Enter programming failed" + + f" Resp : {resp}") + raise errors.RadioError(err) + if resp[0] != 0x06: + raise errors.RadioError("Enter programming: " + + f"Radio Bad Ack: {resp}") + return resp[1:] + + +def exit_prog(serial): + try: + serial.write(b'\x06') + serial.write(b'\x06') + serial.write(b'\x00') + serial.close() + LOG.debug("Exited programming") + except Exception as e: + raise errors.RadioError(f"Error exiting programming {e}") + + +def check_ident(data): + if data == b'P13GMRS': + LOG.info(f"Radio is: {data}") + else: + err = (f"Ident returned unknown Radio: {data}") + LOG.debug(err) + raise errors.RadioError(err) + + +def do_sysinfo(serial): + resp = raw_send(serial, b'PASSSTA', 3) + if resp != b'\x50\x00\x00': + raise errors.RadioError(f"Expected 0x500000 got {resp}") + resp = raw_send(serial, b'SYSINFO', 1) + if resp != b'\x06': + raise errors.RadioError(f"ACK expected got {resp}") + LOG.debug(f"SYSINFO: {resp}") + + +def do_readconfig(serial): + # cmds start with 56, and expect 06 ack after recv ack + for addr, _len in [(0x00000a0d, 13), (0x00100a0d, 13), + (0x00200a0d, 13), (0x0000000a, 11)]: + cmd = struct.pack('>BL', 0x56, addr) + resp = raw_send(serial, cmd, _len) + if len(resp) != _len: + raise errors.RadioError(f"Expected (_len) Bytes got {resp}") + do_ack_ack(serial) + return True + + +def do_prog2(serial): + cmd = struct.pack('>LB', 0xffffffff, 0x0c) + serial.write(cmd) # no resp expected + resp = raw_send(serial, b'P13GMRS', 1) + if resp != b'\x06': + raise errors.RadioError(f"Error expected 06 ack got {resp}") + resp = raw_send(serial, b'\x02', 8) + if len(resp) != 8: + raise errors.RadioError(f"Error expected len 8 got {resp}") + do_ack_ack(serial) + + +def do_read_tlmap(serial): + """ The radio has defined types of config data. + Before reading or writing, we ask the radio where + The data type is stored in memory. The radio + moves memory locations possibly for durability + Build ephemeral map of type to location """ + tl_map = {m[0]: 0 for m in TYPE_MAP} + for i in range(1, 16): + addr = (i << 4 | 0x0f) + # ask the radio where each data type is in mem + cmd = struct.pack('>4B', 0xff, addr, 0x00, 0x01) + resp = do_read_cmd(serial, cmd, 1) + # mem location is for this prog session only + r_int = struct.unpack('>B', resp)[0] + if r_int in tl_map: + tl_map[r_int] = (i << 4) + return tl_map + + +def do_read_ranges(serial, loc, radio, status): + # read each data/config type from the (loc)ation + # obtained by tlmap query. each loc has 4 (pre)fix + # block numbers. Each block is 64 bytes + data = b'' + for i in range(16): + for pre in range(0x0, 0xc1, 0x40): + addr = struct.pack('>BBBB', pre, loc + i, 0x00, 0x40) + data += do_read_cmd(serial, addr, 0x40) + status.cur += 0x40 + radio.status_fn(status) + return data + + +def do_upload_block(serial, loc, offset, radio, status): + # write each config type to loc retrieved from tlmap + # 4 defined (pre)fixes/blocks per (loc)ation + # pre = 0x00 , 0x40 , 0x80, 0xc0 + # full command example [57][80][4d]0040 + # 57 = write , 80 prefix/block , 4d location to write + _mem = radio._memobj.get_raw() + for i in range(16): + for pre in range(0x0, 0xc1, 0x40): + x = offset + (i * 0x100) + pre + block = _mem[x:x + 0x40] + addr = struct.pack('>BBBBB', 0x57, pre, loc + i, 0x00, 0x40) + data = addr + block + ack = raw_send(serial, data, 1) + if ack != b'\x06': + err = f"Bad ack on write expect 0x06 got {ack}" + LOG.debug(err) + raise errors.RadioError(err) + status.cur += len(block) + radio.status_fn(status) + + +def do_download(radio): + data = b'' + try: + status = chirp_common.Status() + serial = radio.pipe + serial.flush() + ident = enter_prog(serial) + check_ident(ident) + do_sysinfo(serial) + do_readconfig(serial) + do_prog2(serial) + tl_map = do_read_tlmap(serial) + status.max = len(tl_map) * 0x1000 + status.msg = "Downloading..." + for t, loc in tl_map.items(): + if loc == 0: + raise errors.RadioError(f"TL Map failed {t} {loc}") + data += do_read_ranges(serial, loc, radio, status) + except Exception as e: + raise errors.RadioError(f"Error during download {e}") + finally: + exit_prog(serial) + return memmap.MemoryMapBytes(data) + + +def do_upload(radio): + try: + status = chirp_common.Status() + status.max = len(WRITE_MAP) * 0x1000 + serial = radio.pipe + serial.flush() + ident = enter_prog(serial) + check_ident(ident) + do_sysinfo(serial) + do_readconfig(serial) + do_prog2(serial) + tl_map = do_read_tlmap(serial) + for wt, label, offset in WRITE_MAP: + status.msg = f"Uploading: {label}..." + loc = tl_map[wt] + do_upload_block(serial, loc, offset, radio, status) + except errors.RadioError: + raise + except Exception as e: + raise errors.RadioError(f"Error during upload {e}") + finally: + exit_prog(serial) + + +@directory.register +class RadioddityGM30(chirp_common.CloneModeRadio): + """Radioddity GM-30""" + VENDOR = "Radioddity" + MODEL = "GM-30" + BAUD_RATE = 57600 + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50), + chirp_common.PowerLevel("High", watts=3.00)] + VALID_MODES = ["NFM", "FM"] + _range = [(136000000, 174000000), (400000000, 470000000)] + GMRS_RPTR = [462550000, 462575000, 462600000, 462625000, 462650000, + 462675000, 462700000, 462725000] + + VALID_TONES = chirp_common.TONES + VALID_DCS = [i for i in range( + 0, 778) if '9' not in str(i) and '8' not in str(i)] + DCS_N = 0x80 + DCS_R = 0x40 + VALID_CHARSET = chirp_common.CHARSET_ASCII + VALID_DTMF = [str(i) for i in range(0, 10)] + \ + ["A", "B", "C", "D", "*", "#"] + ASCII_NUM = [str(i) for i in range(10)] + [' '] + + VALID_STEPS = [2.5, 5.0, 6.25, 10, 12.5, 20, 25, 50] + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.has_bank = False + rf.has_tuning_step = False + rf.valid_tuning_steps = self.VALID_STEPS + rf.has_name = True + rf.valid_characters = self.VALID_CHARSET + rf.valid_name_length = 6 + rf.has_offset = True + rf.has_mode = True + rf.has_dtcs = True + rf.has_rx_dtcs = True + rf.has_dtcs_polarity = True + rf.has_ctone = True + rf.has_cross = True + rf.can_odd_split = False + rf.can_delete = True + rf.valid_modes = self.VALID_MODES + rf.valid_duplexes = ["", "-", "+", "off"] + rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] + rf.valid_cross_modes = [ + "Tone->DTCS", + "DTCS->Tone", + "->Tone", + "Tone->Tone", + "->DTCS", + "DTCS->", + "DTCS->DTCS"] + rf.valid_power_levels = self.POWER_LEVELS + rf.valid_skips = ["", "S"] + rf.valid_bands = self._range + rf.memory_bounds = (1, 250) + return rf + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def sync_in(self): + try: + data = do_download(self) + except errors.RadioError: + raise + except Exception as e: + err = f'Error during download {e}' + LOG.error(err) + raise errors.RadioError(err) + self._mmap = data + self.process_mmap() + + def sync_out(self): + try: + do_upload(self) + except Exception as e: + err = f'Error during upload {e}' + LOG.error(err) + raise errors.RadioError(err) + + def val_or_def(self, memidx, _list): + try: + return _list[memidx] + except IndexError: + return _list[0] + + def idx_or_def(self, memitem, _list): + try: + return _list.index(memitem) + except ValueError: + return 0 + + def get_str_name(self, _name): + return ''.join(filter + (lambda x: x in self.VALID_CHARSET, + str(_name))) + + def get_memory(self, number): + mem = chirp_common.Memory() + mem.number = number + _mem = self._memobj.memory[number-1] + _name = self._memobj.memnames[number-1]["name"] + str_name = self.get_str_name(_name) + mem.name = str_name.rstrip() + + if _mem.rx_freq.get_raw() == b'\xff\xff\xff\xff': + mem.empty = True + return mem + + mem.freq = int(_mem.rx_freq) * 10 + + if _mem.tx_freq.get_raw() == b'\xff\xff\xff\xff': + mem.duplex = 'off' + elif int(_mem.tx_freq) - int(_mem.rx_freq) > 0: + # '+' duplex + mem.duplex = '+' + mem.offset = (int(_mem.tx_freq) - int(_mem.rx_freq)) * 10 + elif int(_mem.tx_freq) - int(_mem.rx_freq) < 0: + # '-' duplex + mem.duplex = '-' + mem.offset = (int(_mem.rx_freq) - int(_mem.tx_freq)) * 10 + + mem.mode = self.val_or_def(_mem.mode, self.VALID_MODES) + mem.power = self.val_or_def(_mem.power, self.POWER_LEVELS) + mem.skip = "" if _mem.scan else "S" + + if 1 <= mem.number <= 7 or 15 <= mem.number <= 22: + mem.duplex = "" + mem.immutable = ['duplex', 'offset', 'empty'] + elif 8 <= mem.number <= 14: + mem.duplex = "off" + mem.immutable += ['duplex', 'offset', 'empty', 'mode', 'power'] + elif 23 <= mem.number <= 54: + mem.offset = 5 * 1000000 + mem.duplex = '+' + mem.immutable = ['duplex', 'offset', 'empty'] + else: + mem.offset = 0 + mem.duplex = "off" + mem.immutable += ['offset', 'duplex'] + if 0 < mem.number <= 30: + mem.immutable = mem.immutable + ['freq'] + + txtone = self.get_tone(_mem.tx_tone) + rxtone = self.get_tone(_mem.rx_tone) + chirp_common.split_tone_decode(mem, txtone, rxtone) + + mem.extra = RadioSettingGroup("Extra", "extra") + + rs = RadioSettingValueBoolean(_mem.busy_lock) + rset = RadioSetting("busy_lock", "Busy Lock", rs) + mem.extra.append(rset) + + rs = RadioSettingValueBoolean(_mem.freq_hop) + rset = RadioSetting("freq_hop", "Freq. Hop", rs) + mem.extra.append(rset) + + _current = _mem.signal if _mem.signal else 1 + rs = RadioSettingValueInteger(1, 15, current=_current) + rset = RadioSetting("signal", "DTMF ID", rs) + mem.extra.append(rset) + + options = ['Off', 'BOT', 'EOT', 'BOTH'] + rs = RadioSettingValueList(options, current_index=_mem.ptt_id) + rset = RadioSetting("ptt_id", "PTT ID", rs) + mem.extra.append(rset) + + return mem + + def validate_memory(self, mem): + if 31 <= mem.number <= 54: + if mem.freq not in self.GMRS_RPTR: + return [chirp_common.ValidationError( + 'Only GMRS repeater freq. permitted' + ' on channels 31 - 54')] + return super().validate_memory(mem) + + def set_memory(self, mem): + number = mem.number + _mem = self._memobj.memory[number-1] + _name = self._memobj.memnames[number-1] + newname = [str(c) for c in mem.name] + _name.name = "".join(newname).ljust(6, '\x00') + + if mem.empty: + _mem.set_raw(b'\xff' * 13 + b'\x06\x11\x00') + return + + _mem.rx_freq = mem.freq // 10 + + if mem.duplex == "+": + _mem.tx_freq = (mem.freq + mem.offset) // 10 + elif mem.duplex == "-": + _mem.tx_freq = (mem.freq - mem.offset) // 10 + elif mem.duplex == "": + _mem.tx_freq = _mem.rx_freq + elif mem.duplex == "off": + _mem.tx_freq.fill_raw(b'\xff') + + _mem.mode = self.idx_or_def(mem.mode, self.VALID_MODES) + _mem.power = self.idx_or_def(mem.power, self.POWER_LEVELS) + _mem.scan = False if mem.skip == "S" else True + + ((txmode, txval, txpol), + (rxmode, rxval, rxpol)) = chirp_common.split_tone_encode(mem) + self.set_tone(_mem.tx_tone, txmode, txval, txpol) + self.set_tone(_mem.rx_tone, rxmode, rxval, rxpol) + + # extra settings + for setting in mem.extra: + setattr(_mem, setting.get_name(), setting.value) + + def get_tone(self, _memval): + _memval[1].ignore_bits(self.DCS_N | self.DCS_R) + dcsn = _memval[1].get_bits(self.DCS_N) + dcsr = _memval[1].get_bits(self.DCS_R) + rb = _memval[1].get_raw() + if rb == b'\xff' or rb == b'\x00': + return "", 0, None + elif dcsn: + pol = "R" if dcsr else "N" + return "DTCS", int(_memval), pol + else: + return "Tone", int(_memval) / 10, None + + def set_tone(self, _memval, mode, val, pol): + # sets tones in _mem from ui edit + _memval[1].ignore_bits(self.DCS_N | self.DCS_R) + if mode == "": + _memval.set_raw(b'\xff\xff') + if mode == "Tone": + _memval[1].clr_bits(self.DCS_N | self.DCS_R) + _memval.set_value(val * 10) + if mode == "DTCS": + _memval[1].set_bits(self.DCS_N) + if pol == 'R': + _memval[1].set_bits(self.DCS_R) + else: + _memval[1].clr_bits(self.DCS_R) + _memval.set_value(val) + + def get_settings(self): + _settings = self._memobj.settings + _dtmf = self._memobj.dtmf + _dtmf_list = self._memobj.dtmf_list + + gsettings = RadioSettingGroup("gsettings", "General Settings") + group = RadioSettings(gsettings) + + _options = ["Logo", "Message", "Voltage"] + rs = RadioSettingValueList(_options, + current_index=_settings.bootscrmode) + rset = RadioSetting("settings.bootscrmode", "Boot Screen Mode", rs) + gsettings.append(rset) + + _current = "".join(chr(i) for i in _settings.bootscreen1 + if chr(i) in self.VALID_CHARSET) + rs = RadioSettingValueString(minlength=0, maxlength=10, + current=_current, + charset=self.VALID_CHARSET, + mem_pad_char=' ') + rset = RadioSetting("settings.bootscreen1", + "Boot Screen 1", rs) + gsettings.append(rset) + + _current = "".join(chr(i) for i in _settings.bootscreen2 + if chr(i) in self.VALID_CHARSET) + rs = RadioSettingValueString(minlength=0, maxlength=10, + current=_current, + charset=self.VALID_CHARSET, + mem_pad_char=' ') + rset = RadioSetting("settings.bootscreen2", + "Boot Screen 2", rs) + gsettings.append(rset) + + _options = [str(i) for i in range(0, 601, 15)] + rs = RadioSettingValueList(_options, + current_index=_settings.timeout) + rset = RadioSetting("settings.timeout", "Timeout (s)", rs) + gsettings.append(rset) + + rs = RadioSettingValueInteger(minval=0, maxval=9, + current=_settings.squelch, step=1) + rset = RadioSetting("settings.squelch", "Squelch Level", rs) + gsettings.append(rset) + + rs = RadioSettingValueInteger(minval=0, maxval=9, + current=_settings.vox_level, step=1) + rset = RadioSetting("settings.vox_level", "Vox Level", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.voice_alert, mem_vals=(0, 1)) + rset = RadioSetting("settings.voice_alert", "Voice Alert", rs) + gsettings.append(rset) + + _options = ["Freq. Mode", "Ch. Mode"] + rs = RadioSettingValueList(_options, + current_index=_settings.work_mode) + rset = RadioSetting("settings.work_mode", "Display Mode", rs) + gsettings.append(rset) + + _options = ["None", "1:1", "1:2", "1:3", "1:4"] + rs = RadioSettingValueList(_options, + current_index=_settings.batt_save) + rset = RadioSetting("settings.batt_save", "Battery Save Mode", rs) + gsettings.append(rset) + + _options = ["Bright", "1", "2", "3", "4", "5", + "6", "7", "8", "9", "10"] + rs = RadioSettingValueList(_options, + current_index=_settings.backlight) + rset = RadioSetting("settings.backlight", "Backlight", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.auto_key_lock, mem_vals=(0, 1)) + rset = RadioSetting("settings.auto_key_lock", "Auto Key Lock", rs) + gsettings.append(rset) + + _options = ["Off", "DT-ST", "ANI-ST", "DT+ANI"] + rs = RadioSettingValueList(_options, + current_index=_settings.side_tone) + rset = RadioSetting("settings.side_tone", "DTMF Side Tone", rs) + gsettings.append(rset) + + _options = ["Time", "Carrier", "Search"] + rs = RadioSettingValueList(_options, + current_index=_settings.scan_type) + rset = RadioSetting("settings.scan_type", "Scan Type", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.ctcss_revert, mem_vals=(0, 1)) + rset = RadioSetting("settings.ctcss_revert", "CTCSS Tail Revert", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.beep_tone, mem_vals=(0, 1)) + rset = RadioSetting("settings.beep_tone", "Beep Tone", rs) + gsettings.append(rset) + + _options = ["On Site", "Send Sound", "Send Code"] + rs = RadioSettingValueList(_options, + current_index=_settings.alarm_mode) + rset = RadioSetting("settings.alarm_mode", "Alarm Mode", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.fm_radio, mem_vals=(0, 1)) + rset = RadioSetting("settings.fm_radio", "FM Radio", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.roger, mem_vals=(0, 1)) + rset = RadioSetting("settings.roger", "Roger Beep", rs) + gsettings.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.standby, mem_vals=(0, 1)) + rset = RadioSetting("settings.standby", "Dual Standby", rs) + gsettings.append(rset) + + _options = [str(i) for i in range(0, 1001, 100)] + rs = RadioSettingValueList(_options, + current_index=_settings.tail_revert) + rset = RadioSetting("settings.tail_revert", + "Repeater Tail Revert (ms)", rs) + gsettings.append(rset) + + # same options as tail_rvt + rs = RadioSettingValueList(_options, + current_index=_settings.tail_delay) + rset = RadioSetting("settings.tail_delay", + "Repeater Tail Delay (ms)", rs) + gsettings.append(rset) + + _options = ["1000", "1450", "1750", "2100"] + rs = RadioSettingValueList(_options, + current_index=_settings.tbst) + rset = RadioSetting("settings.tbst", "Tone Burst", rs) + gsettings.append(rset) + + _options = ["Name + Number", "Freq. + Number"] + rs = RadioSettingValueList(_options, + current_index=_settings.a_ch_disp) + rset = RadioSetting("settings.a_ch_disp", "A Channel Display Type", rs) + gsettings.append(rset) + + # same options as a_chan_disp + rs = RadioSettingValueList(_options, + current_index=_settings.b_ch_disp) + rset = RadioSetting("settings.b_ch_disp", "B Channel Display Type", rs) + gsettings.append(rset) + + # DTMF Menu + dtmf = RadioSettingGroup("dtmf", "DTMF") + group.append(dtmf) + + def _dtmf_decode(setting, pad_len): + _map = list(range(10)) + ['A', 'B', 'C', 'D', '*', '#'] + s = "" + for i in setting: + _i = int(i) + if _i < len(_map): + s += str(_map[_i]) + return s.ljust(pad_len) + + _current = _dtmf_decode(_dtmf.radio_id, 5) + rs = RadioSettingValueString( + minlength=5, maxlength=5, current=_current) + rset = RadioSetting("dtmf.radio_id", "Radio ID", rs) + dtmf.append(rset) + + rs = RadioSettingValueBoolean( + current=_dtmf.press_send, mem_vals=(0, 1)) + rset = RadioSetting("dtmf.press_send", "PTT Press Send", rs) + dtmf.append(rset) + + rs = RadioSettingValueBoolean( + current=_dtmf.release_send, mem_vals=(0, 1)) + rset = RadioSetting("dtmf.release_send", "PTT Release Send", rs) + dtmf.append(rset) + + _options = [str(i) for i in range(100, 1010, 50)] + rs = RadioSettingValueList(_options, + current_index=_dtmf.delay_time) + rset = RadioSetting("dtmf.delay_time", "Delay Time (ms)", rs) + dtmf.append(rset) + + _options = [str(i) for i in range(80, 2010, 10)] + rs = RadioSettingValueList(_options, + current_index=_dtmf.digit_dur) + rset = RadioSetting("dtmf.digit_dur", "Digit Duration (ms)", rs) + dtmf.append(rset) + + # uses same options as digit_dur + rs = RadioSettingValueList(_options, + current_index=_dtmf.inter_dur) + rset = RadioSetting( + "dtmf.inter_dur", "Digit Interval Duration (ms)", rs) + dtmf.append(rset) + + # DTMF Entries List + dtmflist = RadioSettingGroup("dtmflist", "DTMF List") + group.append(dtmflist) + for i in range(0, 15): # Entries # 1-15 + rs = RadioSettingValueString( + minlength=0, maxlength=5, + current=_dtmf_decode(_dtmf_list[i].entry, 5), + autopad=False, + charset=self.VALID_DTMF + [' ']) + rset = RadioSetting(f"dtmf_list[{i}].entry", f"Entry {i+1}", rs) + dtmflist.append(rset) + + # Password Menu + pro = RadioSettingGroup("protect", "Protect") + group.append(pro) + + def _ascii_num_filter(setting): + s = "" + for i in setting: + if chr(i) in self.ASCII_NUM: + s += str(chr(i)) + return s + + rs = RadioSettingValueBoolean( + current=_settings.passw_w_ena, mem_vals=(0, 1)) + rs.set_mutable(False) + rset = RadioSetting("settings.passw_w_ena", "Write Protect", rs) + pro.append(rset) + + _current = _ascii_num_filter(_settings.passw_w_val) + rs = RadioSettingValueString( + minlength=0, maxlength=8, current=_current, + charset=self.ASCII_NUM) + rs.set_mutable(False) + rset = RadioSetting("settings.passw_w_val", "Write Password", rs) + pro.append(rset) + + rs = RadioSettingValueBoolean( + current=_settings.passw_r_ena, mem_vals=(0, 1)) + rs.set_mutable(False) + rset = RadioSetting("settings.passw_r_ena", "Read Protect", rs) + pro.append(rset) + + _current = _ascii_num_filter(_settings.passw_r_val) + rs = RadioSettingValueString( + minlength=0, maxlength=8, current=_current, + charset=self.ASCII_NUM) + rs.set_mutable(False) + rset = RadioSetting("settings.passw_r_val", "Read Password", rs) + pro.append(rset) + + return group + + def _ff_pad__mem(self, obj, setting, element, charset, allow_space=False): + """ set_settings helper for 0xff padded elements + optional remove space chars + """ + _charset = [c for c in list(charset)] + if not allow_space: + _charset = [c for c in list(charset) if c != ' '] + _val = [0xff] * len(obj[setting]) + _i = 0 # offset for invalid chars + for i in range(len(obj[setting])): + if element.value[i] in _charset: + _val[i - _i] = ord(element.value[i]) + else: + _i += 1 + setattr(obj, setting, _val) + + def _dtmf_set__mem(self, obj, setting, element): + _dtmf_map = [str(i) for i in range(10)] + _dtmf_map += ['A', 'B', 'C', 'D', '*', '#'] + _val = [0xff] * len(obj[setting]) + _os = 0 # offset _mem setting idx for pad chars + for i in range(len(element.value)): + if element.value[i] in _dtmf_map: + _val[i - _os] = _dtmf_map.index(element.value[i]) + else: + _os += 1 + setattr(obj, setting, _val) + + def set_settings(self, settings): + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + continue + else: + try: + if "." in element.get_name(): + toks = element.get_name().split(".") + obj = self._memobj + for tok in toks[:-1]: + if '[' in tok: + t, i = tok.split("[") + i = int(i[:-1]) + obj = getattr(obj, t)[i] + else: + obj = getattr(obj, tok) + setting = toks[-1] + else: + obj = self._memobj.settings + setting = element.get_name() + + if element.has_apply_callback(): + LOG.debug("applying callback") + element.run_apply_callback() + + if element.value.get_mutable(): + if setting in ['passw_w_val', 'passw_r_val']: + self._ff_pad__mem( + obj, setting, element, self.ASCII_NUM) + elif setting in ['bootscreen1', 'bootscreen2']: + self._ff_pad__mem( + obj, setting, element, self.VALID_CHARSET, + allow_space=True) + elif setting == 'entry': + self._dtmf_set__mem( + obj, setting, element) + else: + setattr(obj, setting, element.value) + except Exception: + LOG.debug(element.get_name()) + raise diff --git a/chirp/drivers/retevis_h777v4.py b/chirp/drivers/retevis_h777v4.py new file mode 100644 index 0000000..a61998b --- /dev/null +++ b/chirp/drivers/retevis_h777v4.py @@ -0,0 +1,505 @@ +# Copyright 2025 Jim Unroe +# +# 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 . + +import logging +import struct + +from chirp import ( + bitwise, + chirp_common, + directory, + errors, + memmap, + util, +) +from chirp.drivers import h777 +from chirp.settings import ( + MemSetting, + RadioSettingGroup, + RadioSettings, + RadioSettingValueBoolean, + RadioSettingValueInvertedBoolean, + RadioSettingValueInteger, + RadioSettingValueList, +) + +LOG = logging.getLogger(__name__) + +MEM_FORMAT = """ +struct { + ul32 rxfreq; // 0-3 + ul32 txfreq; // 4-7 + lbcd rx_tone[2]; // 8-9 + lbcd tx_tone[2]; // A-B + u8 unknown0:2, // C + scramb:1, // Scramble 0 = Off, 1 = On + scanadd:1, // Scan Add 0 = Scan, 1 = Skip + ishighpower:1, // Power Level 0 = Low, 1 = High + narrow:1, // Bandwidth 0 = Wide, 1 = Narrow + unknown1:1, // + bcl:1; // Busy Channel Locklut 0 = On, 1 = Off +} memory[16]; + +struct { + u8 codesw:1, // 00D0 Code Switch + scanm:1, // Scan Mode + voxs:1, // VOX Switch + roger:1, // Roger + voice:1, // Voice Annunciation + unknown_0:1, + save:1, // Battery Save + beep:1; // Beep Tone + u8 squelch; // 00D1 Squelch Level + u8 tot; // 00D2 Time-out Timer + u8 vox; // 00D3 VOX Level + u8 voxd; // 00D4 Vox Delay + u8 unknown_1; + u8 unknown_2; + u8 skey2; // 00D7 Side Key 2 (long) + u8 unknown_3[5]; // 00D8 - 00DC + u8 password[6]; // 00DD - 00E2 Password +} settings; +""" + + +CMD_ACK = b"\x06" + +DTCS = tuple(sorted(chirp_common.DTCS_CODES + (645,))) + +OFF1TO9_LIST = ["Off"] + ["%s" % x for x in range(1, 10)] +SCANM_LIST = ["Carrier", "Time"] +SKEY2_LIST = ["Off", "VOX", "Power", "Scan"] +TIMEOUTTIMER_LIST = ["Off"] + ["%s seconds" % x for x in range(30, 210, 30)] +VOICE_LIST = ["Off", "English"] +VOXD_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0"] + + +def _read_block(radio, block_addr, block_size): + serial = radio.pipe + + cmd = struct.pack(">cHb", b'R', block_addr, block_size) + expectedresponse = b"W" + cmd[1:] + LOG.debug("Reading block %04x..." % (block_addr)) + + try: + serial.write(cmd) + response = serial.read(4 + block_size) + if response[:4] != expectedresponse: + raise Exception("Error reading block %04x." % (block_addr)) + + block_data = response[4:] + except Exception: + raise errors.RadioError("Failed to read block at %04x" % block_addr) + + return block_data + + +def _write_block(radio, block_addr, block_size): + serial = radio.pipe + + cmd = struct.pack(">cHb", b'W', block_addr, block_size) + data = radio.get_mmap()[block_addr:block_addr + block_size] + + LOG.debug("Writing Data:") + LOG.debug(util.hexprint(cmd + data)) + + try: + serial.write(cmd + data) + if serial.read(1) != CMD_ACK: + raise Exception("No ACK") + except Exception: + raise errors.RadioError("Failed to send block " + "to radio at %04x" % block_addr) + + +def do_download(radio): + LOG.debug("download") + + data = b"" + + status = chirp_common.Status() + status.msg = "Cloning from radio" + + status.cur = 0 + status.max = radio._memsize + + for addr in range(0, radio._memsize, radio.BLOCK_SIZE): + status.cur = addr + radio.BLOCK_SIZE + radio.status_fn(status) + + block = _read_block(radio, addr, radio.BLOCK_SIZE) + data += block + + LOG.debug("Address: %04x" % addr) + LOG.debug(util.hexprint(block)) + + return memmap.MemoryMapBytes(data) + + +def do_upload(radio): + status = chirp_common.Status() + status.msg = "Uploading to radio" + + h777._h777_enter_single_programming_mode(radio) + + status.cur = 0 + status.max = radio._memsize + + for start_addr, end_addr in radio._ranges: + for addr in range(start_addr, end_addr, radio.BLOCK_SIZE_UP): + status.cur = addr + radio.BLOCK_SIZE_UP + radio.status_fn(status) + _write_block(radio, addr, radio.BLOCK_SIZE_UP) + + +class H777V4BaseRadio(chirp_common.CloneModeRadio): + """RETEVIS H777 V4 Base""" + VENDOR = "Retevis" + MODEL = "H777 V4 Base" + BAUD_RATE = 9600 + BLOCK_SIZE = 0x0D + BLOCK_SIZE_UP = 0x0D + + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50), + chirp_common.PowerLevel("High", watts=2.00) + ] + + PROGRAM_CMD = b"C777HAM" + _ranges = [ + (0x0000, 0x00EA), + ] + _memsize = 0x00EA + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.has_bank = False + rf.has_ctone = True + rf.has_cross = True + rf.has_rx_dtcs = True + rf.has_tuning_step = False + rf.can_odd_split = True + rf.has_name = False + rf.valid_skips = ["", "S"] + rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] + rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone", + "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"] + rf.valid_power_levels = self.POWER_LEVELS + rf.valid_duplexes = ["", "-", "+", "split", "off"] + rf.valid_modes = ["FM", "NFM"] # 25 kHz, 12.5 kHz. + rf.valid_dtcs_codes = DTCS + rf.memory_bounds = (1, 16) + rf.valid_tuning_steps = [2.5, 5., 6.25, 10., 12.5, 20., 25., 50.] + rf.valid_bands = [(400000000, 520000000)] + return rf + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def sync_in(self): + """Download from radio""" + try: + data = do_download(self) + except errors.RadioError: + # Pass through any real errors we raise + raise + except Exception: + # If anything unexpected happens, make sure we raise + # a RadioError and log the problem + LOG.exception('Unexpected error during download') + raise errors.RadioError('Unexpected error communicating ' + 'with the radio') + self._mmap = data + self.process_mmap() + + def sync_out(self): + """Upload to radio""" + try: + do_upload(self) + except errors.RadioError: + raise + except Exception: + # If anything unexpected happens, make sure we raise + # a RadioError and log the problem + LOG.exception('Unexpected error during upload') + raise errors.RadioError('Unexpected error communicating ' + 'with the radio') + + def _decode_tone(self, toneval, txrx, chnum): + pol = "N" + rawval = (toneval[1].get_bits(0xFF) << 8) | toneval[0].get_bits(0xFF) + + if toneval[0].get_bits(0xFF) == 0xFF: + mode = "" + val = 0 + elif toneval[1].get_bits(0xC0) == 0xC0: + val = int(f'{rawval & 0x1FF:o}') + if val in DTCS: + mode = "DTCS" + pol = "R" + else: + LOG.error('unknown value: CH# %i DTCS %fR %s' % ( + chnum, val, txrx)) + mode = "" + val = 0 + elif toneval[1].get_bits(0x80): + val = int(f'{rawval & 0x1FF:o}') + if val in DTCS: + mode = "DTCS" + else: + LOG.error('unknown value: CH# %i DTCS %fN %s' % ( + chnum, val, txrx)) + mode = "" + val = 0 + else: + val = int(toneval) / 10.0 + if val in chirp_common.TONES: + mode = "Tone" + else: + LOG.error('unknown value: CH# %i CTCSS %fHZ %s' % ( + chnum, val, txrx)) + mode = "" + val = 0 + + return mode, val, pol + + def _encode_tone(self, _toneval, mode, val, pol): + toneval = 0 + if mode == "Tone": + toneval = int("%i" % (val * 10), 16) + elif mode == "DTCS": + toneval = int('%i' % val, 8) + toneval |= 0x8000 + if pol == "R": + toneval |= 0x4000 + else: + toneval = 0xFFFF + + _toneval[0].set_raw(toneval & 0xFF) + _toneval[1].set_raw((toneval >> 8) & 0xFF) + + def get_raw_memory(self, number): + return repr(self._memobj.memory[number - 1]) + + def get_memory(self, number): + _mem = self._memobj.memory[number - 1] + + mem = chirp_common.Memory() + mem.number = number + + if _mem.get_raw()[:1] == b"\xFF": + mem.empty = True + return mem + + mem.freq = int(_mem.rxfreq) * 10 + + if _mem.txfreq == 0xFFFFFFFF: + # TX freq not set + mem.duplex = "off" + mem.offset = 0 + elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 25000000: + mem.duplex = "split" + mem.offset = int(_mem.txfreq) * 10 + elif int(_mem.rxfreq) == int(_mem.txfreq): + mem.duplex = "" + mem.offset = 0 + else: + mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) \ + and "-" or "+" + mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10 + + txmode, txval, txpol = self._decode_tone(_mem.tx_tone, 'TX', number) + rxmode, rxval, rxpol = self._decode_tone(_mem.rx_tone, 'RX', number) + + chirp_common.split_tone_decode(mem, + (txmode, txval, txpol), + (rxmode, rxval, rxpol)) + + if _mem.scanadd: + mem.skip = "S" + + mem.power = self.POWER_LEVELS[_mem.ishighpower] + + mem.mode = _mem.narrow and "NFM" or "FM" + + mem.extra = RadioSettingGroup("Extra", "extra") + + # BCL (Busy Channel Lockout) + rs = RadioSettingValueInvertedBoolean(not bool(_mem.bcl)) + rset = MemSetting("bcl", "BCL", rs) + rset.set_doc("Busy Channel Lockout") + mem.extra.append(rset) + + # Scramble + rs = RadioSettingValueInvertedBoolean(not bool(_mem.scramb)) + rset = MemSetting("scramb", "Scramble", rs) + rset.set_doc("Frequency inversion Scramble") + mem.extra.append(rset) + + return mem + + def set_memory(self, mem): + _mem = self._memobj.memory[mem.number - 1] + + _mem.set_raw(b"\xff" * 13) + if mem.empty: + return + + _mem.rxfreq = mem.freq / 10 + if mem.duplex == "off": + _mem.txfreq = 0xFFFFFFFF + elif mem.duplex == "split": + _mem.txfreq = mem.offset / 10 + elif mem.duplex == "+": + _mem.txfreq = (mem.freq + mem.offset) / 10 + elif mem.duplex == "-": + _mem.txfreq = (mem.freq - mem.offset) / 10 + else: + _mem.txfreq = _mem.rxfreq + + (txmode, txval, txpol), (rxmode, rxval, rxpol) = \ + chirp_common.split_tone_encode(mem) + + self._encode_tone(_mem.tx_tone, txmode, txval, txpol) + self._encode_tone(_mem.rx_tone, rxmode, rxval, rxpol) + + _mem.scanadd = mem.skip == "S" + _mem.narrow = mem.mode == "NFM" + + _mem.ishighpower = mem.power == self.POWER_LEVELS[1] + + # resetting unknowns, this have to be set by hand + _mem.unknown0 = 3 + _mem.unknown1 = 1 + + for setting in mem.extra: + setting.apply_to_memobj(_mem) + + def get_settings(self): + _settings = self._memobj.settings + basic = RadioSettingGroup("basic", "Basic Settings") + group = RadioSettings(basic) + + # Squelch + rs = RadioSettingValueInteger(0, 9, _settings.squelch) + rset = MemSetting("squelch", "Squelch", rs) + rset.set_doc("Squelch Level: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9") + basic.append(rset) + + # Time Out Timer + rs = RadioSettingValueList(TIMEOUTTIMER_LIST, + current_index=_settings.tot) + rset = MemSetting("tot", "Time-out Timer", rs) + rset.set_doc("TX Time-out Timer: Off, 30, 60, 90, 120, 150," + + " 180 seconds") + basic.append(rset) + + # Vox Level + rs = RadioSettingValueList(OFF1TO9_LIST, current_index=_settings.vox) + rset = MemSetting("vox", "VOX Level", rs) + rset.set_doc("VOX Level: Off, 1, 2, 3, 4, 5, 6, 7, 8, 9") + basic.append(rset) + + # Vox Delay + rs = RadioSettingValueList(VOXD_LIST, + current_index=_settings.voxd) + rset = MemSetting("voxd", "Vox Delay", rs) + rset.set_doc("VOX Delay: 0.5, 1.0, 1.5, 2.0, 2.5, 3.0 seconds") + basic.append(rset) + + # Scan Mode + rs = RadioSettingValueList(SCANM_LIST, current_index=_settings.scanm) + rset = MemSetting("scanm", "Scan Mode", rs) + rset.set_doc("Scan Mode: Carrier, Time") + basic.append(rset) + + # Voice Annunciation + rs = RadioSettingValueList(VOICE_LIST, + current_index=_settings.voice) + rset = MemSetting("voice", "Voice", rs) + rset.set_doc("Voice Prompts: Off, English") + basic.append(rset) + + # Side Key 2 (long) + rs = RadioSettingValueList(SKEY2_LIST, + current_index=_settings.skey2) + rset = MemSetting("skey2", "Side Key 2", rs) + rset.set_doc("Side Key 2 (long press): Off, VOX, Power, Scan") + basic.append(rset) + + # Code Switch + rs = RadioSettingValueBoolean(_settings.codesw) + rset = MemSetting("codesw", "Code Switch", rs) + rset.set_doc("Code Switch: Off, Enabled") + basic.append(rset) + + # Battery Save + rs = RadioSettingValueBoolean(_settings.save) + rset = MemSetting("save", "Battery Save", rs) + rset.set_doc("Battery Save: Off, Enabled") + basic.append(rset) + + # Beep Tone + rs = RadioSettingValueBoolean(_settings.beep) + rset = MemSetting("beep", "Beep", rs) + rset.set_doc("Beep Prompt: Off, Enabled") + basic.append(rset) + + # VOX Switch + rs = RadioSettingValueBoolean(_settings.voxs) + rset = MemSetting("voxs", "VOX Switch", rs) + rset.set_doc("VOX Switch: Off, Enabled") + basic.append(rset) + + # Roger + rs = RadioSettingValueBoolean(_settings.roger) + rset = MemSetting("roger", "Roger", rs) + rset.set_doc("Roger: Off, Enabled") + basic.append(rset) + + return group + + def set_settings(self, settings): + others = settings.apply_to(self._memobj.settings) + if others: + LOG.error('Did not apply %s' % others) + + @classmethod + def match_model(cls, filedata, filename): + # This radio has always been post-metadata, so never do + # old-school detection + return False + + +@directory.register +@directory.detected_by(h777.RetevisH777) +class H777V4(H777V4BaseRadio): + """RETEVIS H777V4""" + VENDOR = "Retevis" + MODEL = "H777" + VARIANT = 'V4' + IDENT = [b'\x00' * 6, b'\xFF' * 6] + + # SKU #: A9294A (sold as FRS radio but supports full band TX/RX) + # Serial #: 2412R777XXXXXXX + + # SKU #: A9294C (same as SKU #: A9294A (2 pack)) + # Serial #: 2406R777XXXXXXX + + # SKU #: A9294B (sold as PMR radio but supports full band TX/RX) + # Serial #: 2412R777XXXXXXX + + # SKU #: A9294D (same as SKU #: A9294B (2 pack)) + # Serial #: 24XXR777XXXXXXX diff --git a/chirp/drivers/retevis_ra25.py b/chirp/drivers/retevis_ra25.py new file mode 100644 index 0000000..34bbb12 --- /dev/null +++ b/chirp/drivers/retevis_ra25.py @@ -0,0 +1,1165 @@ +# Copyright 2025 Mike Iacovacci +# +# 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 . + +from chirp import chirp_common, bitwise, memmap, errors, directory +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueBoolean, RadioSettingValueList, \ + RadioSettingValueInteger, RadioSettingValueString, \ + RadioSettingValueMap, RadioSettings +import struct +import logging + +LOG = logging.getLogger(__name__) + +SERIAL_TIMEOUT = 1.0 + +MEM_FORMAT = """ +// #seekto 0x0000; +struct{ + char model[8]; + lbcd mode[1]; + char ver[4]; + u8 ri_unk[2]; + u8 ack; +} radio_info; + +struct{ + bbcd freq[4]; + bbcd tx_offset[4]; + u8 step; + u8 unk_mem:1, + nc:1, + unk_mem2:2, + compander:1, + channel_width:1, + reverse:1, + tx_off:1; + u8 unk_mem3:3, + talkaround:1, + txpower:2, + duplex:2; + u8 specdcs; + u16 scramhz; + u16 decode; + u16 encode; + u8 scrambler; + char name[8]; + u8 busychannellockout; + u8 tone_id; + u8 unk_mem4[3]; +} vfo[2]; + +struct{ + lbit bitfield[256]; +} chans_present[2]; + +struct{ + lbit bitfield[256]; +} chans_scanned[2]; + +struct { + bbcd freq[4]; + bbcd tx_offset[4]; + u8 step; + u8 unk_mem:1, + nc:1, + unk_mem2:2, + compander:1, + channel_width:1, + reverse:1, + tx_off:1; + u8 unk_mem3:3, + talkaround:1, + txpower:2, + duplex:2; + u8 specdcs; + u16 scramhz; + u16 decode; + u16 encode; + u8 scrambler; + char name[8]; + u8 busychannellockout; + u8 tone_id; + u8 unk_mem4[3]; +} memory[504]; + +struct{ + u8 dispmode; + u8 unk_fs[7]; + u8 squelch; + u8 scan_pause; + u8 unk_fs1; + u8 backlight; + u8 unk_fs2; + u8 vicedisp; + u8 unk_fs3[2]; + u8 beep:1, + alarm_off:1, + main:1, + unkfs4:4, + moni_key:1; + u8 unk_fs5; + u8 tot; + u8 unk_fs6[3]; + u8 dtmf_trans; + u8 language; + u8 tbst_freq; + u8 vox_level; + u8 vox_delay; + u8 tail_elim_type; + u8 unk_fs7:4, + setup_inhib:1, + unk_fs8:2, + init_inhib:1; + u8 unk_fs9; + u8 dcs_tail_elim; + u8 sql_tail_elim; +} func_settings; + +struct{ + u8 m[16]; +}dtmf_list[16]; + +struct{ + u8 interval_char; + u8 group_code; + u8 decoding; + u8 pretime; + u8 first_dig_tm; + u8 autoreset_tm; + u8 unk_dtmf; + u8 self_id[3]; + u8 unk_dtmf1[3]; + u8 side_tone; + u8 timelapse_enc; + u8 pttid_pause; +}dtmf_menu; + +struct{ + u8 unk_menu1[16]; +} unk_menu1; + +struct{ + u8 id[16]; +} dtmf_start; + +struct{ + u8 id[16]; +} dtmf_end; + +struct{ + u8 unk_menu2[16]; + u8 unk_menu3[16]; +} unk_menu23; + +struct{ + u8 id[16]; +} remote_stun; + +struct{ + u8 id[16]; +} remote_kill; + +struct{ + u8 unk_menu4[16]; + u8 emerg_menu[16]; +} unk_menu4; + +struct{ + u8 scanmode; + u8 prio_chan; + u8 revert_chan; + u8 lookback_a; + u8 lookback_b; + u8 dropout_delay; + u8 dwell; + u8 unk_sm; + u8 unused[8]; +} scan_menu; + +struct{ + char message[16]; +}startup_display; + +struct{ + u8 notimpl[3107]; +} notimpl; + +struct{ + u8 unk_imm[16]; + char serial_number[16]; +} immut_1; + +struct{ + char prod_date[10]; + u8 unk_imm2[22]; +} immut_2; +""" + + +# RADIO MODES +BAND_LABELS = [ + "UHF ( 400 - 490 MHz ) + VHF( 136 - 174 MHz )", + "UHF ( 400 - 490 MHz ) + VHF( 144 - 146 MHz )", + "UHF ( 430 - 440 MHz ) + VHF( 136 - 174 MHz )", + "UHF ( 430 - 440 MHz ) + VHF( 144 - 146 MHz )", + "UHF ( 430 - 440 MHz ) + VHF( 144 - 148 MHz )", + "UHF ( 400 - 438 MHz ) + VHF( 136 - 174 MHz )", + "UHF ( 420 - 450 MHz ) + VHF( 144 - 148 MHz )", + "UHF ( 400 - 470 MHz ) + VHF( 136 - 174 MHz )", + "European Version PMR", + "US GMRS", + "Australian UHF CB" +] +BAND_LIMITS = [ + [(136000000, 174000001), (400000000, 490000001)], + [(144000000, 146000001), (400000000, 490000001)], + [(136000000, 174000001), (430000000, 440000001)], + [(144000000, 146000001), (430000000, 440000001)], + [(144000000, 148000001), (430000000, 440000001)], + [(136000000, 174000001), (400000000, 438000001)], + [(144000000, 148000001), (420000000, 450000001)], + [(136000000, 174000001), (400000000, 470000001)], + [(446000000, 446200001)], + [(462550000, 467725001)], + [(476425000, 477412501)] +] + +VALID_MODES = [0, 1, 2, 3, 4, 5, 6, 7, 15, 10, 11] + +READ_MAP = [ + (0x2000, 0x2000, 0x01), + (0x12000, 0x12000, 0x01), + (0x22000, 0x22001, 0x01), + (0x32000, 0x32001, 0x01), + (0x42000, 0x420c7, 0x01), + (0x52000, 0x520c7, 0x01), + (0x62000, 0x62067, 0x01), + (0x1002000, 0x1002000, 0x01), + (0x2001000, 0x200100f, 0x01), + (0x2011000, 0x2091000, 0x10000), + (0x3001000, 0x3091000, 0x10000), + (0x4000500, 0x400057e, 0x01), + (0x4010800, 0x401087e, 0x01), + (0x5001000, 0x500101f, 0x01), + (0x5012000, 0x5012000, 0x01), + (0x5021000, 0x5021000, 0x01), + (0x6002000, 0x600200f, 0x01), + (0x6012000, 0x6012000, 0x01), + (0x6021000, 0x6021000, 0x01), + (0x6032000, 0x6032006, 0x01), + (0x8002000, 0x8002001, 0x01) +] + +WRITE_MAP = [ + (0x2000, 0x2000, 0x01, 0x0010), + (0x12000, 0x12000, 0x01, 0x30), + (0x22000, 0x22001, 0x01, 0x50), + (0x32000, 0x32001, 0x01, 0x90), + (0x42000, 0x420c7, 0x01, 0xd0), + (0x52000, 0x520c7, 0x01, 0x19d0), + (0x62000, 0x62067, 0x01, 0x32d0), + (0x1002000, 0x1002000, 0x01, 0x3fd0), + (0x2001000, 0x200100f, 0x01, 0x3ff0), + (0x2011000, 0x2021000, 0x10000, 0x40f0), + (0x2031000, 0x2041000, 0x10000, 0x4110), + (0x2071000, 0x2081000, 0x10000, 0x4150), + (0x3011000, 0x3021000, 0x10000, 0x4190), +] + + +def bcd(i): + return ((i >> 4) * 10) + (i & 0x0f) + + +def send_cmd(serial, cmd, length): + try: + resp = b'' + serial.write(cmd) + serial.flush() + resp = serial.read(length) + if len(resp) != length: + err = (f'Data send expected {length} got {len(resp)}') + LOG.error(err) + raise errors.RadioError(err) + except Exception as e: + raise errors.RadioError(f'Error sending to serial {e}') + return resp + + +def start_programming(serial): + try: + r = send_cmd(serial, b'PROGRAM', 1) + if r != b'\x06': + err = (f'Enter Programming failed ' + f'expected 0x06 got {hex(r[0])}') + LOG.error(err) + raise errors.RadioError(err) + except Exception as e: + raise errors.RadioError(f'Error Entering Program Mode {e}') + return True + + +def end_programming(serial): + try: + r = send_cmd(serial, b'END', 1) + if r != b'\x06': + LOG.error(f'Error {hex(r[0])}') + except Exception as e: + raise errors.RadioError(f"Error {e}") + + +def parse_response(r): + ck = sum(r[:-1]) % 256 + if ck != r[-1]: + err = f'Data check sum failed calc {ck} got {r[-1]}' + LOG.error(err) + return r[5:-1] + + +def get_ident(radio): + try: + bs = send_cmd(radio.pipe, b'\x02', 16) + model, mode, ver = struct.unpack('>x7ss4s3x', bs) + if ver in radio.ALLOWED_RADIO_TYPES[model]: + LOG.info(f'Model {model} Ver: {ver} is supported') + return bs + else: + err = f'ERROR: Model: {model} Ver: {ver} is not supported!' + LOG.error(err) + raise errors.RadioError(err) + except Exception as e: + raise errors.RadioError(e) + + +def get_bands(mode): + i_mode = int(mode) + bltups = list(zip(VALID_MODES, BAND_LIMITS)) + bt = next((bl[1] for bl in bltups if bl[0] == i_mode), None) + if bt is None: + err = (f"Unknown Freq. Mode {mode}") + LOG.debug(err) + raise errors.RadioError(err) + return bt + + +def sum_map(MAP): + _sum = 0 + for rt in MAP: + x, y, z = rt[0], rt[1], rt[2] + _sum += ((((y - x) // z) + 1) * ((y & 0xf000) + (y & 0x0f00) >> 8)) + return _sum + + +def do_download(radio): + try: + data = b'' + serial = radio.pipe + serial.timeout = SERIAL_TIMEOUT + status = chirp_common.Status() + status.msg = "Connecting to Radio..." + radio.status_fn(status) + r = start_programming(serial) + if not r: + raise errors.RadioError('Failed to enter programming mode') + ident_bytes = get_ident(radio) + data = ident_bytes + status.max = sum_map(READ_MAP) + status.msg = "Downloading..." + for (x, y, z) in READ_MAP: + for addr in range(x, y + 1, z): + btr = ((y & 0xf000) + (y & 0x0f00) >> 8) + cmd = struct.pack('>BL', 0x52, addr) + r = send_cmd(serial, cmd, btr + 6) + if r[0] != 0x57: + err = (f'Bad ACK expected 0x57 got {hex(r[0])}') + LOG.error(err) + raise errors.RadioError(err) + data += parse_response(r) + status.cur += btr + radio.status_fn(status) + except Exception as e: + raise errors.RadioError(f'Exception During Download: {e}') + finally: + end_programming(serial) + return memmap.MemoryMapBytes(data) + + +def write_data(serial, addr, data): + pfx = struct.pack('>BL', 0x57, addr) + data = pfx + data + chk_int = sum(data) % 256 + chk_byte = struct.pack('>B', chk_int) + cmd = data + chk_byte + r = send_cmd(serial, cmd, 1) + if r != b'\x06': + err = (f'Received bad ACK from Radio ' + f'expect 0x06 got {hex(r[0])}') + LOG.error(err) + raise errors.RadioError(err) + + +def do_upload(radio): + try: + serial = radio.pipe + serial.timeout = SERIAL_TIMEOUT + status = chirp_common.Status() + r = start_programming(serial) + if not r: + raise errors.RadioError('Failed to enter programming mode') + ident_bytes = get_ident(radio) + mode = bcd(ident_bytes[8]) + if mode != int(radio._memobj.radio_info.mode): + raise errors.RadioError('The Radio Mode does not match' + ' [Settings]->[Radio Info]->Radio Mode') + status.max = sum_map(WRITE_MAP) + status.msg = "Uploading..." + for (x, y, z, _mb) in WRITE_MAP: + i = 0 + for addr in range(x, y + 1, z): + btw = ((y & 0xf000) + (y & 0x0f00) >> 8) + si = _mb + (btw * i) + ei = _mb + (btw * (i+1)) + data = radio._mmap[si:ei] + write_data(serial, addr, data) + status.cur += btw + radio.status_fn(status) + i += 1 + except Exception as e: + raise errors.RadioError(f"Exception During Upload: {e}") + finally: + end_programming(serial) + return + + +@directory.register +class RA25UVRadio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): + """Retevis RA-25 , Anytone AT-779UV, Radioddity DB20G """ + VENDOR = "Retevis" + MODEL = "RA25" + BAUD_RATE = 115200 + ALLOWED_RADIO_TYPES = {b'RA_25UV': [b'V200']} + _file_ident = [b'RA_25UV'] + _image_size = 0x4EC3 + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5.00), + chirp_common.PowerLevel("Mid", watts=10.00), + chirp_common.PowerLevel("High", watts=25.00)] + VALID_TONES = (62.5,) + chirp_common.TONES + VALID_DCS = [i for i in range( + 0, 778) if '9' not in str(i) and '8' not in str(i)] + VALID_TUNING_STEPS = [2.5, 5.0, 6.25, 10, 12.5, 20, 25, 30, 50] + VALID_CHARSET = "".join(chr(i) + for i in range(32, 127) if chr(i) not in '\\`~') + VALID_DTMF = [str(i) for i in range(0, 10)] + ['A', 'B', + 'C', 'D', '*', '#'] + + RX_BANDS = [(136000000, 174000001), (400000000, 490000001)] + + @classmethod + def get_prompts(cls): + rp = chirp_common.RadioPrompts() + rp.experimental = \ + ('This driver is experimental, ' + 'please report issues') + return rp + + def is_tx_allowed(self, freq): + tx_bands = get_bands(self._memobj.radio_info.mode) + for bt in tx_bands: + if bt[0] <= freq <= bt[1]: + return True + return False + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.valid_tmodes = ("", "Tone", "TSQL", "DTCS", "Cross") + rf.valid_cross_modes = [ + "Tone->Tone", + "Tone->DTCS", + "DTCS->Tone", + "DTCS->", + "->Tone", + "->DTCS", + "DTCS->DTCS" + ] + rf.valid_modes = ["FM", "NFM"] + rf.valid_power_levels = self.POWER_LEVELS + rf.valid_bands = [(136000000, 174000001), (400000000, 490000001)] + rf.valid_characters = self.VALID_CHARSET + rf.valid_name_length = 8 + rf.valid_duplexes = ["", "+", "-"] + rf.valid_tuning_steps = self.VALID_TUNING_STEPS + rf.valid_tones = self.VALID_TONES + rf.has_dtcs = True + rf.has_dtcs_polarity = True + rf.valid_dtcs_codes = self.VALID_DCS + rf.has_ctone = True + rf.has_rx_dtcs = True + rf.has_cross = True + rf.has_tuning_step = True + rf.has_bank = False + rf.has_settings = True + rf.memory_bounds = (1, 502) + rf.can_odd_split = False + rf.has_offset = True + return rf + + def sync_in(self): + self._mmap = do_download(self) + self.process_mmap() + + def sync_out(self): + do_upload(self) + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def get_raw_memory(self, number): + return repr(self._memobj.memory[number - 1]) + + # Populate the UI mem from _mem + + def get_memory(self, number): + + mem = chirp_common.Memory() + mem.number = number + + if 0 < number <= 500: + _mem = self._memobj.memory[number - 1] + _mem_chans_scanned = self._memobj.chans_scanned + _mem_chans_present = self._memobj.chans_present + mem.empty = not self.get_chan_status( + _mem_chans_present, mem.number - 1) + mem.skip = '' if self.get_chan_status( + _mem_chans_scanned, mem.number - 1) else 'S' + _name = "".join(c for c in str(_mem.name) + if c in self.VALID_CHARSET) + mem.name = _name.rstrip() + + else: + _mem = self._memobj.vfo[number - 501] + mem.name = f"VFO-{number - 500}" + mem.skip = "" + mem.immutable = ["empty", "skip", "name"] + + mem.power = self.POWER_LEVELS[0] + + if mem.empty: + return mem + + mem.freq = int(_mem.freq) * 10 + + mem.power = self.POWER_LEVELS[_mem.txpower] + mem.mode = "FM" if _mem.channel_width == 0 else "NFM" + self.get_tones(_mem, mem) + self.get_duplex(_mem, mem) + mem.offset = int(_mem.tx_offset) * 10 + mem.tuning_step = self.VALID_TUNING_STEPS[_mem.step] + + if not self.is_tx_allowed(mem.freq): + _mem.tx_off = 1 + + mem.extra = RadioSettingGroup("Extra", "extra") + + rstype = RadioSettingValueBoolean(_mem.tx_off) + rs = RadioSetting("tx_off", "TX Disable", rstype) + mem.extra.append(rs) + + bcl_options = ['Off', 'Repeater', 'Busy'] + _current = _mem.busychannellockout.get_value() + rstype = RadioSettingValueList(bcl_options, current_index=_current) + rs = RadioSetting("busychannellockout", + "Busy Channel Lockout", rstype) + mem.extra.append(rs) + + rstype = RadioSettingValueBoolean(_mem.talkaround) + rs = RadioSetting("talkaround", "Talk Around", rstype) + mem.extra.append(rs) + + rstype = RadioSettingValueBoolean(_mem.reverse) + rs = RadioSetting("reverse", "Reverse", rstype) + mem.extra.append(rs) + + rstype = RadioSettingValueBoolean(_mem.compander) + rs = RadioSetting("compander", "Compander", rstype) + mem.extra.append(rs) + + rstype = RadioSettingValueBoolean(_mem.nc) + rs = RadioSetting("nc", "Noise Cancellation", rstype) + mem.extra.append(rs) + + tid_options = ['Off', 'Begin', 'End', "Both"] + _current = _mem.tone_id.get_value() + rstype = RadioSettingValueList(tid_options, current_index=_current) + rs = RadioSetting("tone_id", "DTMF PTT ID", rstype) + mem.extra.append(rs) + + return mem + + # Called when a user edits UI mem + def set_memory(self, mem): + if 0 < mem.number <= 500: + _mem = self._memobj.memory[mem.number - 1] + _mem_chans_scanned = self._memobj.chans_scanned + _mem_chans_present = self._memobj.chans_present + + if mem.empty: + self.set_chan_status(_mem_chans_present, mem.number - 1, 0) + self.set_chan_status(_mem_chans_scanned, mem.number - 1, 0) + _mem.fill_raw(b'\x00') + return + + # setup a new memory + if not self.get_chan_status(_mem_chans_present, mem.number - 1): + _mem.fill_raw(b'\x00') + self.set_chan_status(_mem_chans_present, mem.number - 1, 1) + _scan = 0 if mem.skip == 'S' else 1 + self.set_chan_status(_mem_chans_scanned, mem.number - 1, _scan) + _mem.txpower = 2 + _mem.freq = mem.freq // 10 + _mem.tx_off = 0 if self.is_tx_allowed(mem.freq) else 1 + + _mem.name = mem.name.ljust(8)[:8] + # scan when set(1) skip when off(0) + _value = 0 if mem.skip == 'S' else 1 + self.set_chan_status(_mem_chans_scanned, mem.number - 1, _value) + self.set_chan_status(_mem_chans_present, mem.number - 1, 1) + else: + _mem = self._memobj.vfo[mem.number - 501] + + _mem.freq = mem.freq // 10 + + _mem.txpower = self.POWER_LEVELS.index(mem.power) if mem.power else 0 + _mem.channel_width = 0 if mem.mode == "FM" else 1 + self.set_tones__mem(_mem, mem) + self.set_duplex__mem(_mem, mem) + _mem.tx_offset = mem.offset/10 + _mem.step = self.VALID_TUNING_STEPS.index(mem.tuning_step) + + for setting in mem.extra: + setattr(_mem, setting.get_name(), setting.value) + + if not self.is_tx_allowed(mem.freq): + _mem.tx_off = 1 + + def get_chan_status(self, _mem_field, chan_n): + if chan_n < 256: + value = _mem_field[0]['bitfield'][chan_n].get_value() + else: + value = _mem_field[1]['bitfield'][chan_n - 256].get_value() + return value + + def set_chan_status(self, _mem_field, chan_n, value): + if chan_n < 256: + _mem_field[0]['bitfield'][chan_n].set_value(value) + else: + _mem_field[1]['bitfield'][chan_n - 256].set_value(value) + + def get_duplex(self, _mem, mem): + # get duplex from _mem for ui + if _mem.duplex == 0x0: + mem.duplex = '' + elif _mem.duplex == 0x2: + mem.duplex = '-' + elif _mem.duplex == 0x3: + mem.duplex = '+' + + def set_duplex__mem(self, _mem, mem): + # sets duplex _mem from ui edit + if mem.duplex == '': + _mem.duplex = 0x0 + _mem.tx_offset = 0 + elif mem.duplex == '-': + _mem.duplex = 0x2 + elif mem.duplex == '+': + _mem.duplex = 0x3 + + def get_tones(self, _mem, mem): + # populate ui from _mem + # parse decode/rtone/rx_dtcs + if _mem.decode == 0xffff: + # off + rxtone = ("", 0, None) + elif _mem.decode >= 0x1000 and _mem.decode < 0x2000: + # ctcss tone + rxtone = ("Tone", self.VALID_TONES[_mem.decode - 0x1000], None) + elif _mem.decode >= 0x2000 and _mem.decode < 0x3000: + # DCS Normal + rxtone = ("DTCS", self.VALID_DCS[_mem.decode - 0x2000], "N") + elif _mem.decode >= 0x3000 and _mem.decode <= 0x31ff: + # DCS Inverted + rxtone = ("DTCS", self.VALID_DCS[_mem.decode - 0x3000], "R") + else: + rxtone = ("", 0, None) + # parse encode/dtcs/ctone + if _mem.encode == 0xffff: + # off + txtone = ("", 0, None) + elif _mem.encode >= 0x1000 and _mem.encode < 0x2000: + # ctcss tone + txtone = ("Tone", self.VALID_TONES[_mem.encode - 0x1000], None) + elif _mem.encode >= 0x2000 and _mem.encode < 0x3000: + # DCS Normal + txtone = ("DTCS", self.VALID_DCS[_mem.encode - 0x2000], "N") + elif _mem.encode >= 0x3000 and _mem.encode <= 0x31ff: + # DCS Inverted + txtone = ("DTCS", self.VALID_DCS[_mem.encode - 0x3000], "R") + else: + txtone = ("", 0, None) + chirp_common.split_tone_decode(mem, txtone, rxtone) + + def set_tones__mem(self, _mem, mem): + # sets tones in _mem from ui edit + ((txmode, txval, txpol), + (rxmode, rxval, rxpol)) = chirp_common.split_tone_encode(mem) + if txmode == "": + _mem.encode = 0xffff + if rxmode == "": + _mem.decode = 0xffff + if txmode == "Tone": + _mem.encode = self.VALID_TONES.index(txval) + 0x1000 + if rxmode == "Tone": + _mem.decode = self.VALID_TONES.index(rxval) + 0x1000 + if txmode == "DTCS" and txpol == "N": + _mem.encode = self.VALID_DCS.index(txval) + 0x2000 + if rxmode == "DTCS" and rxpol == "N": + _mem.decode = self.VALID_DCS.index(rxval) + 0x2000 + if txmode == "DTCS" and txpol == "R": + _mem.encode = self.VALID_DCS.index(txval) + 0x3000 + if rxmode == "DTCS" and rxpol == "R": + _mem.decode = self.VALID_DCS.index(rxval) + 0x3000 + + def get_settings(self): + + _func_settings = self._memobj.func_settings + _dtmf_menu = self._memobj.dtmf_menu + _dtmf_list = self._memobj.dtmf_list + _dtmf_start = self._memobj.dtmf_start + _dtmf_end = self._memobj.dtmf_end + _remote_kill = self._memobj.remote_kill + _remote_stun = self._memobj.remote_stun + _scan_menu = self._memobj.scan_menu + _startup_display = self._memobj.startup_display + _immut_1 = self._memobj.immut_1 + _immut_2 = self._memobj.immut_2 + _radio_info = self._memobj.radio_info + + function = RadioSettingGroup("function", "Function Setup") + group = RadioSettings(function) + + rs = RadioSettingValueInteger(minval=0, maxval=9, + current=_func_settings.squelch, step=1) + rset = RadioSetting("func_settings.squelch", "Squelch Level", rs) + function.append(rset) + + rs = RadioSettingValueInteger(minval=0, maxval=9, + current=_func_settings.vox_level, step=1) + rset = RadioSetting("func_settings.vox_level", "Vox Level", rs) + function.append(rset) + + voxdelay_options = [str(i/10) for i in range(5, 31, 1)] + rs = RadioSettingValueList( + voxdelay_options, current_index=_func_settings.vox_delay) + rset = RadioSetting("func_settings.vox_delay", "Vox Delay", rs) + function.append(rset) + + scan_pause_options = ["5", "10", "15", "SCP2"] + rs = RadioSettingValueList( + scan_pause_options, current_index=_func_settings.scan_pause) + rset = RadioSetting("func_settings.scan_pause", "Scan Pause (s)", rs) + function.append(rset) + + main_options = ["Up", "Down"] + rs = RadioSettingValueList( + main_options, current_index=_func_settings.main) + rset = RadioSetting("func_settings.main", "Main Direction", rs) + function.append(rset) + + monikey_options = ["Squelch Off Momentary", "Squelch Off"] + rs = RadioSettingValueList( + monikey_options, current_index=_func_settings.moni_key) + rset = RadioSetting("func_settings.moni_key", "[MON] Key", rs) + function.append(rset) + + rs = RadioSettingValueInteger(minval=0, maxval=30, + current=_func_settings.tot, step=1) + rset = RadioSetting("func_settings.tot", + "Time Out Timer (minutes)", rs) + function.append(rset) + + tbst_options = ["Off", "1750", "2100", "1000", "1450"] + rs = RadioSettingValueList( + tbst_options, current_index=_func_settings.tbst_freq) + rset = RadioSetting("func_settings.tbst_freq", + "TBST Frequency (Hz)", rs) + function.append(rset) + + tailelim_options = ["Off", "120 deg", "180 deg", "240 deg", "55hz"] + rs = RadioSettingValueList( + tailelim_options, current_index=_func_settings.tail_elim_type) + rset = RadioSetting("func_settings.tail_elim_type", + "Tail Eliminator Type", rs) + function.append(rset) + + dcstail_options = ["134.4", "55.0"] + rs = RadioSettingValueList( + dcstail_options, current_index=_func_settings.dcs_tail_elim) + rset = RadioSetting("func_settings.dcs_tail_elim", + "DCS Tail Elimination", rs) + function.append(rset) + + sqltail_options = ["Off", "55.2", "259.2"] + rs = RadioSettingValueList( + sqltail_options, current_index=_func_settings.sql_tail_elim) + rset = RadioSetting("func_settings.sql_tail_elim", + "Squelch Tail Elimination (Hz)", rs) + function.append(rset) + + disp_options = ["Frequency", "Channel", "Name"] + rs = RadioSettingValueList( + disp_options, current_index=_func_settings.dispmode) + rset = RadioSetting("func_settings.dispmode", "Display Mode", rs) + function.append(rset) + + vicedisp_options = ["Freq/Chan", "Battery Volt", "Off"] + rs = RadioSettingValueList( + vicedisp_options, current_index=_func_settings.vicedisp) + rset = RadioSetting("func_settings.vicedisp", "Sub-Display", rs) + function.append(rset) + + _current = "".join(c for c in str( + _startup_display.message) if c in self.VALID_CHARSET) + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=_current, + charset=self.VALID_CHARSET, + mem_pad_char=' ') + rset = RadioSetting("startup_display.message", + "Startup Display Message", rs) + function.append(rset) + + rs = RadioSettingValueInteger( + minval=1, maxval=5, current=_func_settings.backlight, step=1) + rset = RadioSetting("func_settings.backlight", "Backlight Level", rs) + function.append(rset) + + rs = RadioSettingValueBoolean( + current=_func_settings.beep, mem_vals=(0, 1)) + rset = RadioSetting("func_settings.beep", "Beep", rs) + function.append(rset) + + rs = RadioSettingValueBoolean( + current=_func_settings.alarm_off, mem_vals=(0, 1)) + rset = RadioSetting("func_settings.alarm_off", "Alarm Off", rs) + function.append(rset) + + rs = RadioSettingValueBoolean( + current=_func_settings.setup_inhib, mem_vals=(0, 1)) + rset = RadioSetting("func_settings.setup_inhib", "Setup Inhibit", rs) + function.append(rset) + + rs = RadioSettingValueBoolean( + current=_func_settings.init_inhib, mem_vals=(0, 1)) + rset = RadioSetting("func_settings.init_inhib", + "Initialization Inhibit", rs) + function.append(rset) + + lang_options = ["Simplified Chinese", "English", "Traditional Chinese"] + rs = RadioSettingValueList( + lang_options, current_index=_func_settings.language) + rset = RadioSetting("func_settings.language", "Language", rs) + function.append(rset) + + # Scan Menu + scan = RadioSettingGroup("scan", "Scan Menu") + group.append(scan) + + rs = RadioSettingValueBoolean(current=_scan_menu.scanmode) + rset = RadioSetting("scan_menu.scanmode", "Scan Mode", rs) + scan.append(rset) + + _options = ["Off", "Chan 1", "Chan 2", "Chan 1 + Chan 2"] + rs = RadioSettingValueList( + _options, current_index=_scan_menu.prio_chan) + rset = RadioSetting("scan_menu.prio_chan", "Priority Channel", rs) + scan.append(rset) + + _options = ["Selected", "Selected + Talkback", + "Prio Ch 1", "Prio Ch 2", "Last Called", + "Last Used", "Prio Ch1 + Talkback", "Prio Ch2 + Talkback"] + rs = RadioSettingValueList( + _options, current_index=_scan_menu.revert_chan) + rset = RadioSetting("scan_menu.revert_chan", "Revert Channel", rs) + scan.append(rset) + + _options = [str(i/10) for i in range(5, 51, 1)] + rs = RadioSettingValueList( + _options, current_index=_scan_menu.lookback_a) + rset = RadioSetting("scan_menu.lookback_a", "Look Back Time A (s)", rs) + scan.append(rset) + + # Uses previous options + rs = RadioSettingValueList( + _options, current_index=_scan_menu.lookback_b) + rset = RadioSetting("scan_menu.lookback_b", "Look Back Time B (s)", rs) + scan.append(rset) + + _options = [str(i/10) for i in range(1, 51, 1)] + rs = RadioSettingValueList( + _options, current_index=_scan_menu.dropout_delay) + rset = RadioSetting("scan_menu.dropout_delay", "Dropout Delay (s)", rs) + scan.append(rset) + + # Uses previous options + rs = RadioSettingValueList( + _options, current_index=_scan_menu.dwell) + rset = RadioSetting("scan_menu.dwell", "Dwell Time (s)", rs) + scan.append(rset) + + # DTMF Menu + dtmf = RadioSettingGroup("dtmf", "DTMF") + group.append(dtmf) + + def dtmf_xlate(setting): + """ Translates * and # to ascii code E / F respectively""" + s = "" + for i in setting: + if chr(i) == 'E': + s += '*' + elif chr(i) == 'F': + s += '#' + elif chr(i) in self.VALID_DTMF: + s += chr(i) + return s + + _current = ''.join(str(int(i)) for i in _dtmf_menu.self_id) + rs = RadioSettingValueString( + minlength=0, maxlength=3, current=_current) + rset = RadioSetting("dtmf_menu.self_id", "Self ID", rs) + dtmf.append(rset) + + # DTMF Transmit time is in function memory but belongs here + dtmftt_options = ["50", "100", "200", "300", "500"] + rs = RadioSettingValueList( + dtmftt_options, current_index=_func_settings.dtmf_trans) + rset = RadioSetting("func_settings.dtmf_trans", + "DTMF Transmit Time (ms)", rs) + dtmf.append(rset) + + _options_map = [('A', 10), ('B', 11), ('C', 12), + ('D', 13), ('*', 14), ('#', 15)] + rs = RadioSettingValueMap(_options_map, _dtmf_menu.interval_char) + rset = RadioSetting("dtmf_menu.interval_char", "Interval Char", rs) + dtmf.append(rset) + + _options_map = [('Off', 0), ('A', 10), ('B', 11), + ('C', 12), ('D', 13), ('*', 14), ('#', 15)] + rs = RadioSettingValueMap(_options_map, _dtmf_menu.group_code) + rset = RadioSetting("dtmf_menu.group_code", "Group Code", rs) + dtmf.append(rset) + + _options = ["None", "Beep Tone", "Beep Tone & Response"] + rs = RadioSettingValueList( + _options, current_index=_dtmf_menu.decoding) + rset = RadioSetting("dtmf_menu.decoding", "Decoding", rs) + dtmf.append(rset) + + _options = [str(i) for i in range(10, 2510, 10)] + _mem_vals = [i for i in range(1, 251)] + _options_map = list(zip(_options, _mem_vals)) + rs = RadioSettingValueMap(_options_map, _dtmf_menu.pretime) + rset = RadioSetting("dtmf_menu.pretime", "Pretime (ms)", rs) + dtmf.append(rset) + + # using same _options as pre-time + rs = RadioSettingValueMap(_options_map, _dtmf_menu.timelapse_enc) + rset = RadioSetting("dtmf_menu.timelapse_enc", + "Time Lapse After Encode (ms)", rs) + dtmf.append(rset) + + _options = [str(i) for i in range(0, 2510, 10)] + rs = RadioSettingValueList( + _options, current_index=_dtmf_menu.first_dig_tm) + rset = RadioSetting("dtmf_menu.first_dig_tm", + "First Digit Time (ms)", rs) + dtmf.append(rset) + + _options = [str(i/10) for i in range(0, 251, 1)] + rs = RadioSettingValueList( + _options, current_index=_dtmf_menu.autoreset_tm) + rset = RadioSetting("dtmf_menu.autoreset_tm", + "Auto Reset Time (ms)", rs) + dtmf.append(rset) + + rs = RadioSettingValueBoolean( + current=_dtmf_menu.side_tone, mem_vals=(0, 1)) + rset = RadioSetting("dtmf_menu.side_tone", "Side Tone", rs) + dtmf.append(rset) + + _options_map = [("Off", 0)] + [(str(i), i) for i in range(5, 76, 1)] + rs = RadioSettingValueMap(_options_map, _dtmf_menu.pttid_pause) + rset = RadioSetting("dtmf_menu.pttid_pause", + "PTT ID Pause Time (s)", rs) + dtmf.append(rset) + + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=dtmf_xlate(_dtmf_start.id), + charset=self.VALID_DTMF + [' ']) + rset = RadioSetting("dtmf_start.id", "PTT ID Starting", rs) + dtmf.append(rset) + + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=dtmf_xlate(_dtmf_end.id), + charset=self.VALID_DTMF + [' ']) + rset = RadioSetting("dtmf_end.id", "PTT ID Ending", rs) + dtmf.append(rset) + + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=dtmf_xlate(_remote_kill.id), + charset=self.VALID_DTMF + [' '],) + rset = RadioSetting("remote_kill.id", "Remote Kill", rs) + dtmf.append(rset) + + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=dtmf_xlate(_remote_stun.id), + charset=self.VALID_DTMF + [' ']) + rset = RadioSetting("remote_stun.id", "Remote Stun", rs) + dtmf.append(rset) + + # DTMF Encode List + dtmf_mem = RadioSettingGroup("dtmf_mem", "DTMF Encode List") + group.append(dtmf_mem) + + for i in range(0, 16): # M1-16 + rs = RadioSettingValueString(minlength=0, maxlength=16, + current=dtmf_xlate(_dtmf_list[i].m), + charset=self.VALID_DTMF + [' ']) + rset = RadioSetting(f"dtmf_list[{i}].m", f"M{i+1}", rs) + dtmf_mem.append(rset) + + # Immutables Info + info_menu = RadioSettingGroup("immut_info", "Radio Info") + group.append(info_menu) + + _warning = ('To Upload to the Radio this setting must match ' + 'the Radio Mode. The Radio Mode can be changed by ' + 'holding down [V/M] during powerup. Note: Changing ' + 'the Radio Mode will set Radio memory to defaults.') + + _options_map = list(zip(BAND_LABELS, VALID_MODES)) + rs = RadioSettingValueMap(_options_map, int(_radio_info.mode)) + rset = RadioSetting("radio_info.mode", "Radio Mode", rs) + rset.set_warning(_warning) + info_menu.append(rset) + + _current = "".join(str(_radio_info.model[i]) + for i in range(1, len(_radio_info.model))) + rs = RadioSettingValueString( + minlength=1, maxlength=8, current=_current) + rs.set_mutable(False) + rset = RadioSetting("radio_info.model", "Model", rs) + info_menu.append(rset) + + _current = "".join(str(_radio_info.ver[i]) + for i in range(len(_radio_info.ver))) + rs = RadioSettingValueString( + minlength=4, maxlength=4, current=_current) + rs.set_mutable(False) + rset = RadioSetting("radio_info.ver", "Version", rs) + info_menu.append(rset) + + _current = "".join(str(_immut_1.serial_number[i]) for i in range( + len(_immut_1.serial_number))) + rs = RadioSettingValueString( + minlength=0, maxlength=16, current=_current) + rs.set_mutable(False) + rset = RadioSetting("immut_1.serial_number", "Serial Number", rs) + info_menu.append(rset) + + _current = "".join(str(_immut_2.prod_date[i]) for i in range( + len(_immut_2.prod_date)) if int(_immut_2.prod_date[i]) >= 0x20) + rs = RadioSettingValueString( + minlength=0, maxlength=10, current=_current) + rs.set_mutable(False) + rset = RadioSetting("immut_2.prod_date", "Production Date", rs) + info_menu.append(rset) + return group + + def dtmf_set__mem(self, obj, setting, element): + _val = [0] * len(obj[setting]) + _i = 0 # offset _mem setting idx for pad chars + for i in range(len(element.value)): + if element.value[i] == '*': + _val[i - _i] = ord('E') + elif element.value[i] == '#': + _val[i - _i] = ord('F') + elif element.value[i] in self.VALID_DTMF: + _val[i - _i] = ord(element.value[i]) + else: + _i += 1 + setattr(obj, setting, _val) + + def set_settings(self, settings): + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + continue + else: + try: + if "." in element.get_name(): + toks = element.get_name().split(".") + obj = self._memobj + for tok in toks[:-1]: + if '[' in tok: + t, i = tok.split("[") + i = int(i[:-1]) + obj = getattr(obj, t)[i] + else: + obj = getattr(obj, tok) + setting = toks[-1] + else: + obj = self._memobj.settings + setting = element.get_name() + + if element.has_apply_callback(): + LOG.debug("applying callback") + element.run_apply_callback() + + if element.value.get_mutable(): + if obj._name in ['dtmf_list', 'dtmf_start', 'dtmf_end', + 'remote_stun', 'remote_kill']: + self.dtmf_set__mem(obj, setting, element) + else: + setattr(obj, setting, element.value) + except Exception: + LOG.debug(element.get_name()) + raise + + @classmethod + def match_model(cls, filedata, filename): + # new drivers identified by metadata + return False + + +@directory.register +class AnyTone779UV(RA25UVRadio): + VENDOR = "AnyTone" + MODEL = "779UV" + ALLOWED_RADIO_TYPES = {b'AT779UV': [b'V200']} + + +@directory.register +class RadioddityDB20G(AnyTone779UV): + VENDOR = "Radioddity" + MODEL = "DB20-G" diff --git a/chirp/drivers/retevis_ra86.py b/chirp/drivers/retevis_ra86.py new file mode 100644 index 0000000..c0e1087 --- /dev/null +++ b/chirp/drivers/retevis_ra86.py @@ -0,0 +1,609 @@ +# Copyright 2025 Jim Unroe +# +# 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 . + +import struct +import logging + +from chirp import chirp_common, directory, memmap +from chirp import bitwise, errors, util +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueInteger, RadioSettingValueList, \ + RadioSettingValueBoolean, RadioSettings + +LOG = logging.getLogger(__name__) + +MEM_FORMAT = """ +struct memory { + u32 rxfreq; // 0-3 + ul16 rxtone; // 4-5 + u32 txfreq; // 6-9 + ul16 txtone; // A-B + u8 unknown0:3, // C + scan:1, // + is_wide:1, // + unknown1:1, // + highpower:1, // + unknown2:1; // + u8 unknown3[3]; // D-F +} ; + +struct memory lochannels[14]; +struct memory chnl15; +struct memory rptr15; +struct memory chnl16; +struct memory rptr16; +struct memory chnl17; +struct memory rptr17; +struct memory chnl18; +struct memory rptr18; +struct memory chnl19; +struct memory rptr19; +struct memory chnl20; +struct memory rptr20; +struct memory chnl21; +struct memory rptr21; +struct memory chnl22; +struct memory rptr22; +struct memory hichannels[77]; + +#seekto 0x0E00; +struct { + u8 unknown00:4, vox:4; // 0E00 VOX + u8 unknown01:7, keytone:1; // 0E01 Key Tone + u8 unknown02:7, roger:1; // 0E02 Roger Beep + u8 unknown03:5, calltone:3; // 0E03 Call Tone + u8 unknown04:6, brightness:2; // 0E04 Screen Brightness + u8 unknown05:5, backlight:3; // 0E05 Backlight Duration + u8 unknown06:4, squelch:4; // 0E06 Squelch Level + u8 unknown07; // 0E07 (Reserved/Unknown) + u8 unknown08:7, repeat:1; // 0E08 Repeater + u8 unknown09:5, sleeptime:3; // 0E09 Sleep Timer + u8 unknown10:6, speakersw:2; // 0E0A Speaker Switch + u8 unknown11:6, micgain:2; // 0E0B Mic Gain + u8 unknown12:4, tot:4; // 0E0C Timeout Timer (TOT) + u8 unknown13; // 0E0D (Reserved) + u8 unknown14; // 0E0E (Reserved) + u8 unknown15; // 0E0F (Reserved) +} settings; +""" + +CMD_ACK = b"\x06" + +LIST_OFF1TO9 = ["Off"] + ["%s" % x for x in range(1, 10)] +LIST_SLEEPTIME = ["OFF", "5s", "10s", "20s", "30s", "60s"] +LIST_SPEAKERSW = ["Base", "Mic", "Dual"] +LIST_TOT = ["Off"] + ["%s" % x for x in range(15, 195, 15)] + +SPECIALS = { + "RPTR15": -8, + "RPTR16": -7, + "RPTR17": -6, + "RPTR18": -5, + "RPTR19": -4, + "RPTR20": -3, + "RPTR21": -2, + "RPTR22": -1 + } + + +def _enter_programming_mode(radio): + serial = radio.pipe + + _magic = b"\x02" + radio._magic + + try: + serial.write(_magic) + serial.read(len(_magic)) # Chew the echo + ack = serial.read(1) + except Exception: + raise errors.RadioError("Error communicating with radio") + + if not ack: + raise errors.RadioError("No response from radio") + elif ack != CMD_ACK: + raise errors.RadioError("Radio refused to enter programming mode") + + try: + serial.write(b"\x02") + serial.read(1) # Chew the echo + ident = serial.read(8) + except Exception: + raise errors.RadioError("Error communicating with radio") + + # check if ident is OK + for fp in radio._fingerprint: + if ident.startswith(fp): + break + else: + LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident)) + raise errors.RadioError("Radio identification failed.") + + try: + serial.write(CMD_ACK) + serial.read(1) # Chew the echo + ack = serial.read(1) + except Exception: + raise errors.RadioError("Error communicating with radio") + + if ack != CMD_ACK: + raise errors.RadioError("Radio refused to enter programming mode") + + +def _exit_programming_mode(radio): + serial = radio.pipe + try: + serial.write(radio.CMD_EXIT) + serial.read(1) # Chew the echo + except Exception: + raise errors.RadioError("Radio refused to exit programming mode") + + +def _read_block(radio, block_addr, block_size): + serial = radio.pipe + + cmd = struct.pack(">cHb", b'R', block_addr, block_size) + expectedresponse = b"R" + cmd[1:] + LOG.debug("Reading block %04x..." % (block_addr)) + + try: + serial.write(cmd) + serial.read(4) # Chew the echo + response = serial.read(4 + block_size) + if response[:4] != expectedresponse: + raise Exception("Error reading block %04x." % (block_addr)) + + block_data = response[4:] + + except Exception: + raise errors.RadioError("Failed to read block at %04x" % block_addr) + + return block_data + + +def _write_block(radio, block_addr, block_size): + serial = radio.pipe + + cmd = struct.pack(">cHb", b'W', block_addr, block_size) + data = radio.get_mmap()[block_addr:block_addr + block_size] + + LOG.debug("Writing Data:") + LOG.debug(util.hexprint(cmd + data)) + + try: + serial.write(cmd + data) + serial.read(4 + len(data)) # Chew the echo + serial.read(1) # Chew the echo + ack = serial.read(1) + if ack != CMD_ACK: + raise Exception("No ACK") + except Exception: + raise errors.RadioError("Failed to send block " + "to radio at %04x" % block_addr) + + +def do_download(radio): + LOG.debug("download") + _enter_programming_mode(radio) + + data = b"" + + status = chirp_common.Status() + status.msg = "Cloning from radio" + + status.cur = 0 + status.max = radio._memsize + + for addr in range(0, radio._memsize, radio.BLOCK_SIZE): + status.cur = addr + radio.BLOCK_SIZE + radio.status_fn(status) + + block = _read_block(radio, addr, radio.BLOCK_SIZE) + data += block + + LOG.debug("Address: %04x" % addr) + LOG.debug(util.hexprint(block)) + + _exit_programming_mode(radio) + + return memmap.MemoryMapBytes(data) + + +def do_upload(radio): + status = chirp_common.Status() + status.msg = "Uploading to radio" + + _enter_programming_mode(radio) + + status.cur = 0 + status.max = radio._memsize + + for start_addr, end_addr in radio._ranges: + for addr in range(start_addr, end_addr, radio.BLOCK_SIZE): + status.cur = addr + radio.BLOCK_SIZE + radio.status_fn(status) + _write_block(radio, addr, radio.BLOCK_SIZE) + + _exit_programming_mode(radio) + + +def _split(rf, f1, f2): + """Returns False if the two freqs are in the same band (no split) + or True otherwise""" + + # determine if the two freqs are in the same band + for low, high in rf.valid_bands: + if f1 >= low and f1 <= high and \ + f2 >= low and f2 <= high: + # if the two freqs are on the same Band this is not a split + return False + + # if you get here is because the freq pairs are split + return True + + +@directory.register +class RA86Radio(chirp_common.CloneModeRadio): + """RETEVIS RA86""" + VENDOR = "Retevis" + MODEL = "RA86" + BAUD_RATE = 115200 + BLOCK_SIZE = 0x10 + CMD_EXIT = b"b" + + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=20.00), + chirp_common.PowerLevel("Low", watts=0.50)] + + VALID_BANDS = [(400000000, 470000000)] + + DTCS_CODES = tuple(sorted(chirp_common.DTCS_CODES + (645,))) + + _magic = b"PROGRAM" + _fingerprint = [b"SMP558"] + _upper = 99 + + _gmrs = False + + _ranges = [ + (0x0000, 0x06B0), + (0x0E00, 0x0E10), + ] + _memsize = 0x0E10 + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.valid_special_chans = list(SPECIALS.keys()) + rf.has_settings = True + rf.valid_modes = ["FM", "NFM"] # 25 kHz, 12.5 kHz. + rf.valid_skips = ["", "S"] + rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] + rf.valid_duplexes = ["", "-", "+", "split", "off"] + rf.valid_power_levels = self.POWER_LEVELS + rf.can_odd_split = True + rf.has_rx_dtcs = True + rf.has_ctone = True + rf.has_cross = True + rf.valid_cross_modes = [ + "Tone->Tone", + "DTCS->", + "->DTCS", + "Tone->DTCS", + "DTCS->Tone", + "->Tone", + "DTCS->DTCS"] + rf.valid_dtcs_codes = self.DTCS_CODES + rf.has_tuning_step = False + rf.has_bank = False + rf.has_name = False + rf.memory_bounds = (1, self._upper) + rf.valid_bands = self.VALID_BANDS + rf.valid_tuning_steps = chirp_common.TUNING_STEPS + + return rf + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def sync_in(self): + self._mmap = do_download(self) + self.process_mmap() + + def sync_out(self): + do_upload(self) + + def decode_tone(self, val): + mode = "" + pol = "N" + if val in [0, 0xFFFF]: + xval = 0 + elif val <= 0x32: + mode = "Tone" + index = val - 1 + xval = chirp_common.TONES[index] + elif val >= 0x0033: + mode = "DTCS" + if val > 0x69 + 0x32: + index = val - 0x69 - 0x32 - 1 + pol = "R" + else: + index = val - 0x32 - 1 + xval = self.DTCS_CODES[index] + else: + LOG.warn("Bug: tone is %04x" % val) + return mode, xval, pol + + def encode_tone(self, memtone, mode, tone, pol): + if mode == "Tone": + memtone.set_value(chirp_common.TONES.index(tone) + 1) + elif mode == "TSQL": + memtone.set_value(chirp_common.TONES.index(tone) + 1) + elif mode == "DTCS": + if pol == 'R': + memtone.set_value(self.DTCS_CODES.index(tone) + 0x33 + 0x69) + else: + memtone.set_value(self.DTCS_CODES.index(tone) + 0x33) + else: + memtone.set_value(0) + + def _get_memobjs(self, number): + if isinstance(number, str): + return (getattr(self._memobj, number.lower())) + elif number < 0: + for k, v in SPECIALS.items(): + if number == v: + return (getattr(self._memobj, k.lower())) + else: + if number < 15: + return self._memobj.lochannels[number - 1] + elif 15 <= number <= 22: + return getattr(self._memobj, f"chnl{number}") + else: # number > 22 + return self._memobj.hichannels[number - 23] + + def get_memory(self, number): + _mem = self._get_memobjs(number) + + mem = chirp_common.Memory() + + if isinstance(number, str): + mem.number = SPECIALS[number] + mem.extd_number = number + else: + mem.number = number + + mem.freq = int(_mem.rxfreq) + + # We'll consider any blank (i.e. 0 MHz frequency) to be empty + if mem.freq == 0: + mem.empty = True + return mem + + if _mem.rxfreq.get_raw() == b"\xFF\xFF\xFF\xFF": + mem.freq = 0 + mem.empty = True + return mem + + if _mem.get_raw() == (b"\xFF" * 16): + LOG.debug("Initializing empty memory") + _mem.set_raw(b"\x00" * 16) + + # Freq and offset + mem.freq = int(_mem.rxfreq) + # tx freq can be blank + if _mem.txfreq.get_raw() == b"\xFF\xFF\xFF\xFF": + # TX freq not set + mem.offset = 0 + mem.duplex = "off" + else: + # TX freq set + offset = (int(_mem.txfreq)) - mem.freq + if offset != 0: + if _split(self.get_features(), mem.freq, int( + _mem.txfreq)): + mem.duplex = "split" + mem.offset = int(_mem.txfreq) + elif offset < 0: + mem.offset = abs(offset) + mem.duplex = "-" + elif offset > 0: + mem.offset = offset + mem.duplex = "+" + else: + mem.offset = 0 + + mem.mode = _mem.is_wide and "FM" or "NFM" + + if not _mem.scan: + mem.skip = "S" + + txtone = self.decode_tone(_mem.txtone) + rxtone = self.decode_tone(_mem.rxtone) + chirp_common.split_tone_decode(mem, txtone, rxtone) + + mem.power = self.POWER_LEVELS[1 - _mem.highpower] + + return mem + + def set_memory(self, mem): + # Get a low-level memory object mapped to the image + _mem = self._get_memobjs(mem.number) + + if mem.empty: + _mem.fill_raw(b"\xFF") + + return + + _mem.fill_raw(b"\x00") + + _mem.rxfreq = mem.freq + + if mem.duplex == "off": + _mem.txfreq.fill_raw(b"\xFF") + elif mem.duplex == "split": + _mem.txfreq = mem.offset + elif mem.duplex == "+": + _mem.txfreq = (mem.freq + mem.offset) + elif mem.duplex == "-": + _mem.txfreq = (mem.freq - mem.offset) + else: + _mem.txfreq = mem.freq + + ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \ + chirp_common.split_tone_encode(mem) + self.encode_tone(_mem.txtone, txmode, txtone, txpol) + self.encode_tone(_mem.rxtone, rxmode, rxtone, rxpol) + + _mem.highpower = mem.power == self.POWER_LEVELS[0] + + _mem.is_wide = mem.mode == "FM" + _mem.scan = mem.skip != "S" + + _mem.unknown0 = 0 + _mem.unknown1 = 0 + _mem.unknown2 = 0 + _mem.unknown3 = b"\x92\x1B\xC4" + + def get_settings(self): + _mem = self._memobj + basic = RadioSettingGroup("basic", "Basic Settings") + top = RadioSettings(basic) + + if _mem.settings.vox >= len(LIST_OFF1TO9): + val = 0x00 + else: + val = _mem.settings.vox + rs = RadioSetting("settings.vox", "VOX", + RadioSettingValueList( + LIST_OFF1TO9, + current_index=val)) + basic.append(rs) + + rs = RadioSetting("settings.keytone", "Key Tone", + RadioSettingValueBoolean(_mem.settings.keytone)) + basic.append(rs) + + rs = RadioSetting("settings.roger", "Roger Beep", + RadioSettingValueBoolean(_mem.settings.roger)) + basic.append(rs) + + if _mem.settings.calltone > 4: + val = 1 + else: + val = _mem.settings.calltone + 1 + rs = RadioSetting("settings.calltone", "Call Tone", + RadioSettingValueInteger(1, 5, val)) + basic.append(rs) + + if _mem.settings.brightness > 2: + val = 1 + else: + val = _mem.settings.brightness + 1 + rs = RadioSetting("settings.brightness", "Brightness", + RadioSettingValueInteger(1, 3, val)) + basic.append(rs) + + if _mem.settings.backlight > 4: + val = 2 + else: + val = _mem.settings.backlight + rs = RadioSetting("settings.backlight", "Back Light", + RadioSettingValueInteger(0, 4, val)) + basic.append(rs) + + if _mem.settings.squelch >= len(LIST_OFF1TO9): + val = 0x05 + else: + val = _mem.settings.squelch + rs = RadioSetting("settings.squelch", "Squelch", + RadioSettingValueList( + LIST_OFF1TO9, + current_index=val)) + basic.append(rs) + + if _mem.settings.tot >= len(LIST_TOT): + val = 0x0C + else: + val = _mem.settings.tot + rs = RadioSetting("settings.tot", "TOT", + RadioSettingValueList( + LIST_TOT, + current_index=val)) + basic.append(rs) + + rs = RadioSetting("settings.repeat", "Repeater", + RadioSettingValueBoolean(_mem.settings.repeat)) + basic.append(rs) + + if _mem.settings.sleeptime >= len(LIST_SLEEPTIME): + val = 0x02 + else: + val = _mem.settings.sleeptime + rs = RadioSetting("settings.sleeptime", "Sleep Time", + RadioSettingValueList( + LIST_SLEEPTIME, + current_index=val)) + basic.append(rs) + + if _mem.settings.speakersw >= len(LIST_SPEAKERSW): + val = 0x02 + else: + val = _mem.settings.speakersw + rs = RadioSetting("settings.speakersw", "Speaker Select", + RadioSettingValueList( + LIST_SPEAKERSW, + current_index=val)) + basic.append(rs) + + if _mem.settings.micgain > 2: + val = 1 + else: + val = _mem.settings.micgain + 1 + rs = RadioSetting("settings.micgain", "Mic Gain", + RadioSettingValueInteger(1, 5, val)) + basic.append(rs) + + return top + + def set_settings(self, settings): + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + continue + else: + try: + if "." in element.get_name(): + bits = element.get_name().split(".") + obj = self._memobj + for bit in bits[:-1]: + obj = getattr(obj, bit) + setting = bits[-1] + else: + obj = self._memobj.settings + setting = element.get_name() + + if element.has_apply_callback(): + LOG.debug("Using apply callback") + element.run_apply_callback() + elif setting == "brightness": + setattr(obj, setting, int(element.value) - 1) + elif setting == "calltone": + setattr(obj, setting, int(element.value) - 1) + elif setting == "micgain": + setattr(obj, setting, int(element.value) - 1) + else: + LOG.debug("Setting %s = %s" % (setting, element.value)) + setattr(obj, setting, element.value) + except Exception: + LOG.debug(element.get_name()) + raise diff --git a/chirp/drivers/retevis_rt21.py b/chirp/drivers/retevis_rt21.py index 01187ff..662a377 100644 --- a/chirp/drivers/retevis_rt21.py +++ b/chirp/drivers/retevis_rt21.py @@ -449,7 +449,7 @@ struct { """ MEM_FORMAT_RT86 = """ -#seekto 0x0000; +// #seekto 0x0000; struct { lbcd rxfreq[4]; // RX Frequency 0-3 lbcd txfreq[4]; // TX Frequency 4-7 @@ -461,7 +461,7 @@ struct { bcl:1, // Busy Lock OFF=0 ON=1 scramble_type:3; // Scramble u8 reserved[3]; // Reserved D-F -} memory[16]; +} memory[%(memcnt)d]; #seekto 0x002D; struct { @@ -484,32 +484,68 @@ struct { u8 unknown_4; // 004D u8 unknown_5[2]; // 004E-004F u8 channel_6[13]; // 0050-005C - u8 unknown_6; // 005D + u8 removectdcs; // Remove CT/DCS RT86S 005D u8 unknown_7[2]; // 005E-005F u8 channel_7[13]; // 0060-006C u8 warn; // Warn Mode 006D u8 pf1; // Key Set PF1 006E - u8 pf2; // Key Set PF2 006F + u8 pf2; // Key Set PF2 006F RT86S: Group Ch # u8 channel_8[13]; // 0070-007C u8 unknown_8; // 007D u8 tail; // QT/DQT Tail(inverted) 007E u8 tailmode; // QT/DQT Tail Mode 007F u8 channel_9[13]; // 0080-008C - u8 unknown_9[3]; // 008D-008F + u8 unknown_9; // 008D + u8 pttack; // 008E + u8 waittime; // 008F u8 channel_10[13]; // 0090-009C u8 unknown_10[3]; // 009D-009F u8 channel_11[13]; // 00A0-00AC - u8 unknown_11[2]; // 00AD-00AE - u8 chnumber; // Channel Number 00AF + u8 weather; // Weather 00AD + u8 seekfreq; // Seek Freq 00AE + u8 chnumber; // Channel Number 00AF RT86S: Talk + u8 channel_12[13]; // 00B0-00BC + u8 unknown_12; // 00BD + u8 keylock; // Key Lock 00BE + u8 wxchnumber; // WX Channel Number 00BF + u8 channel_13[13]; // 00C0-00CC + u8 backlight; // Back Light 00CD + u8 micgain; // Microphone Gain 00CE + u8 unknown_cf; // 00CF + u8 channel_14[13]; // 00D0-00DC + u8 pf_1; // Key Set PF1 00DD + u8 pf_2; // Key Set PF2 00DE + u8 menuexit; // Menu Exit Time 00DF } settings; -#seekto 0x004E; -u8 skipflags[2]; // SCAN_ADD +#seekto %(settings_offset)s; +u8 skipflags[%(bytecnt)d]; // Scan Add #seekto 0x0100; struct { u8 freqhop; // Frequency Hop } freqhops[16]; + +#seekto 0x029F; +struct { + u8 ch_number; // RT86S: Channel Number +} settings2; + +#seekto 0x031E; +struct { + u8 voxl; // Vox Level + u8 voxd; // VOX Delay +} settings3; + +#seekto 0x326; +struct { + u8 roger; // Roger +} settings4; + +#seekto 0x0330; +struct { + u8 txpower; // TX Power Level +} levels[30]; """ CMD_ACK = b"\x06" @@ -522,13 +558,18 @@ CDCSS2_LIST = ["Normal Code", "Special Code"] # RT29 UHF and RT29 VHF FREQHOP_LIST = ["Off", "Hopping 1", "Hopping 2", "Hopping 3"] FUNCTION_LIST = ["Off", "Scramble", "Compand"] GAIN_LIST = ["Standard", "Enhanced"] +GROUPCH_LIST = ["OFF"] + ["%s" % x for x in range(1, 31)] +BACKLIGHT_LIST = ["%sS" % x for x in range(1, 21)] + ["60S", "120S", "ON"] HOP_LIST = ["Mode A", "Mode B", "Mode C", "Mode D", "Mode E"] HOP86_LIST = ["Off", "Mode 1", "Mode 2", "Mode 3", "Mode 4"] +MENUEXIT_LIST = ["%sS" % x for x in range(5, 65, 5)] +MICGAIN_LIST = ["-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5"] PFKEY_LIST = ["None", "Monitor", "Lamp", "Warn", "VOX", "VOX Delay", "Key Lock", "Scan"] PFKEY28B_LIST = ["None", "Scan", "Warn", "TX Power", "Monitor"] PFKEY86_LIST = ["None", "Monitor", "Lamp", "Warn", "VOX", "VOX Delay", "Key Lock", "TX Power", "Scan"] +PFKEY86S_LIST = ["Monitor", "Warn", "Lamp"] PFKEY89_LIST = PFKEY_LIST + ["Bluetooth ON/OFF"] POT_LIST = ["Channel Type", "Volume Type"] SAVE_LIST = ["Standard", "Super"] @@ -544,7 +585,19 @@ VOICE_LIST3 = VOICE_LIST2 + ["Chinese"] VOX_LIST = ["OFF"] + ["%s" % x for x in range(1, 17)] VOXD_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0"] VOXL_LIST = ["OFF"] + ["%s" % x for x in range(1, 10)] +WAITTIME_LIST = ["OFF"] + ["%s" % x for x in range(1, 21)] WARN_LIST = ["OFF", "Native Warn", "Remote Warn"] +WX_LIST = ["WX1 162.550 MHz", + "WX2 162.400 MHz", + "WX3 162.475 MHz", + "WX4 162.425 MHz", + "WX5 162.450 MHz", + "WX6 162.500 MHz", + "WX7 162.525 MHz", + "WX8 161.650 MHz", + "WX9 161.775 MHz", + "WX10 161.750 MHz", + "WX11 162.000 MHz"] PF1_CHOICES = ["None", "Monitor", "Scan", "Scramble", "Alarm"] PF1_VALUES = [0x0F, 0x04, 0x06, 0x08, 0x0C] PF1_17A_CHOICES = ["None", "Monitor", "Scan", "Scramble"] @@ -904,6 +957,9 @@ class RT21Radio(chirp_common.CloneModeRadio): LOG.debug("Got TX %s (%i) RX %s (%i)" % (txmode, _mem.tx_tone, rxmode, _mem.rx_tone)) + def _get_pwr(self, number): + return self._memobj.levels[number - 1] + def get_memory(self, number): if self._skipflags: bitpos = (1 << ((number - 1) % 8)) @@ -925,7 +981,9 @@ class RT21Radio(chirp_common.CloneModeRadio): _mem = self._memobj.memory[number - 1] if self._reserved: - _rsvd = _mem.reserved.get_raw(asbytes=False) + _rsvd = _mem.reserved.get_raw() + if self.MODEL == "RT86S": + _rsvdpwr = _mem.highpower.get_raw() mem.freq = int(_mem.rxfreq) * 10 @@ -963,6 +1021,15 @@ class RT21Radio(chirp_common.CloneModeRadio): else: LOG.error('%s: get_mem: unhandled power level: 0x%02x' % (mem.name, _mem.txpower)) + elif self.MODEL == "RT86S": + _pwr = self._get_pwr(number) + # set the power level + if _pwr.txpower == self.TXPOWER_LOW: + mem.power = self.POWER_LEVELS[2] + elif _pwr.txpower == self.TXPOWER_MED: + mem.power = self.POWER_LEVELS[1] + elif _pwr.txpower == self.TXPOWER_HIGH: + mem.power = self.POWER_LEVELS[0] else: mem.power = self.POWER_LEVELS[1 - _mem.highpower] @@ -1188,6 +1255,9 @@ class RT21Radio(chirp_common.CloneModeRadio): LOG.debug("Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone)) + def _set_pwr(self, number): + return self._memobj.levels[number - 1] + def set_memory(self, mem): if self._skipflags: bitpos = (1 << ((mem.number - 1) % 8)) @@ -1208,7 +1278,9 @@ class RT21Radio(chirp_common.CloneModeRadio): _mem = self._memobj.memory[mem.number - 1] if self._reserved: - _rsvd = _mem.reserved.get_raw(asbytes=False) + _rsvd = _mem.reserved.get_raw() + if self.MODEL == "RT86S": + _rsvdpwr = _mem.highpower.get_raw() if self.MODEL == "RT86": _freqhops = self._memobj.freqhops[mem.number - 1] @@ -1220,15 +1292,15 @@ class RT21Radio(chirp_common.CloneModeRadio): "RT76", "RT86", ]: - _mem.set_raw("\xFF" * 13 + _rsvd) + _mem.set_raw(b"\xFF" * 13 + _rsvd) elif self.MODEL in ["RT19", "RT86", "RT619", ]: - _mem.set_raw("\xFF" * 13 + _rsvd) + _mem.set_raw(b"\xFF" * 13 + _rsvd) _freqhops.freqhop.set_raw("\x00") elif self.MODEL == "AR-63": - _mem.set_raw("\xFF" * 13 + _rsvd) + _mem.set_raw(b"\xFF" * 13 + _rsvd) else: _mem.set_raw("\xFF" * (_mem.size() // 8)) @@ -1237,9 +1309,12 @@ class RT21Radio(chirp_common.CloneModeRadio): if self.MODEL == "RB17A": _mem.set_raw("\x00" * 14 + "\xFF\xFF") elif self._reserved: - _mem.set_raw("\x00" * 13 + _rsvd) + if self.MODEL == "RT86S": + _mem.set_raw(b"\x00" * 12 + _rsvdpwr + _rsvd) + else: + _mem.set_raw(b"\x00" * 13 + _rsvd) elif self.MODEL == "AR-63": - _mem.set_raw("\x00" * 13 + _rsvd) + _mem.set_raw(b"\x00" * 13 + _rsvd) else: _mem.set_raw("\x00" * 13 + "\x30\x8F\xF8") @@ -1271,6 +1346,15 @@ class RT21Radio(chirp_common.CloneModeRadio): else: LOG.error('%s: set_mem: unhandled power level: %s' % (mem.name, mem.power)) + elif self.MODEL == "RT86S": + _pwr = self._set_pwr(mem.number) + # set the power level + if mem.power == self.POWER_LEVELS[0]: + _pwr.txpower = self.TXPOWER_HIGH + elif mem.power == self.POWER_LEVELS[1]: + _pwr.txpower = self.TXPOWER_MED + elif mem.power == self.POWER_LEVELS[2]: + _pwr.txpower = self.TXPOWER_LOW else: _mem.highpower = mem.power == self.POWER_LEVELS[0] @@ -1441,11 +1525,14 @@ class RT21Radio(chirp_common.CloneModeRadio): "RT86", "RT619", "RB89", + "RT86S", ]: if self.MODEL == "RB26" or self.MODEL == "RB23" \ - or self.MODEL == "RB89": + or self.MODEL == "RB89"or self.MODEL == "RT86S": _settings2 = self._memobj.settings2 _settings3 = self._memobj.settings3 + if self.MODEL == "RT86S": + _settings4 = self._memobj.settings4 rs = RadioSettingValueInteger(0, 9, _settings.squelch) rset = RadioSetting("squelch", "Squelch Level", rs) @@ -1500,7 +1587,7 @@ class RT21Radio(chirp_common.CloneModeRadio): basic.append(rset) if self.MODEL == "RB26" or self.MODEL == "RB23" \ - or self.MODEL == "RB89": + or self.MODEL == "RB89" or self.MODEL == "RT86S": rs = RadioSettingValueList(VOICE_LIST2, current_index=_settings.voice) rset = RadioSetting("voice", "Voice Annumciation", rs) @@ -1511,7 +1598,8 @@ class RT21Radio(chirp_common.CloneModeRadio): rset = RadioSetting("chnumberd", "Channel Number Enable", rs) basic.append(rset) - if self.MODEL == "RT86" or self.MODEL == "RB89": + if self.MODEL == "RT86" or self.MODEL == "RB89" \ + or self.MODEL == "RT86S": rs = RadioSettingValueList(SPECIAL_LIST, current_index=_settings.tailmode) rset = RadioSetting("tailmode", "QT/DQT Tail Mode", rs) @@ -1529,6 +1617,7 @@ class RT21Radio(chirp_common.CloneModeRadio): "RB26", "RT86", "RB89", + "RT86S", ]: rs = RadioSettingValueBoolean(not _settings.tail) rset = RadioSetting("tail", "QT/DQT Tail", rs) @@ -1543,10 +1632,17 @@ class RT21Radio(chirp_common.CloneModeRadio): if self.MODEL != "RT19" and self.MODEL != "RT619" and \ self.MODEL != "AR-63" and \ self.MODEL != "RT40B": - rs = RadioSettingValueList(GAIN_LIST, - current_index=_settings.gain) - rset = RadioSetting("gain", "MIC Gain", rs) - basic.append(rset) + + if self.MODEL == "RT86S": + rs = RadioSettingValueList(MICGAIN_LIST, + current_index=_settings.micgain) + rset = RadioSetting("micgain", "MIC Gain", rs) + basic.append(rset) + else: + rs = RadioSettingValueList(GAIN_LIST, + current_index=_settings.gain) + rset = RadioSetting("gain", "MIC Gain", rs) + basic.append(rset) rs = RadioSettingValueList(WARN_LIST, current_index=_settings.warn) @@ -1554,8 +1650,10 @@ class RT21Radio(chirp_common.CloneModeRadio): basic.append(rset) if self.MODEL == "RT86": - rs = RadioSettingValueInteger(1, 16, _settings.chnumber + 1) - rset = RadioSetting("settings.chnumber", "Channel Number", rs) + rs = RadioSettingValueInteger(1, self._upper, + _settings.chnumber + 1) + rset = RadioSetting("settings.chnumber", + "Channel Number", rs) basic.append(rset) rs = RadioSettingValueBoolean(_settings.vox) @@ -1572,6 +1670,23 @@ class RT21Radio(chirp_common.CloneModeRadio): rset = RadioSetting("voxd", "Vox Delay", rs) basic.append(rset) + if self.MODEL == "RT86S": + rs = RadioSettingValueInteger(1, self._upper, + _settings2.ch_number + 1) + rset = RadioSetting("settings2.ch_number", + "Channel Number", rs) + basic.append(rset) + + rs = RadioSettingValueList(VOXL_LIST, + current_index=_settings3.voxl) + rset = RadioSetting("voxl", "Vox Level", rs) + basic.append(rset) + + rs = RadioSettingValueList(VOXD_LIST, + current_index=_settings3.voxd) + rset = RadioSetting("voxd", "Vox Delay", rs) + basic.append(rset) + if self.MODEL == "RB26" or self.MODEL == "RB23" \ or self.MODEL == "RB89": rs = RadioSettingValueBoolean(_settings3.vox) @@ -1740,6 +1855,17 @@ class RT21Radio(chirp_common.CloneModeRadio): rset = RadioSetting("pf2", "PF2 Key Set", rs) basic.append(rset) + if self.MODEL == "RT86S": + rs = RadioSettingValueList(PFKEY86S_LIST, + current_index=_settings.pf_1) + rset = RadioSetting("pf_1", "PF1 Key Set", rs) + basic.append(rset) + + rs = RadioSettingValueList(PFKEY86S_LIST, + current_index=_settings.pf_2) + rset = RadioSetting("pf_2", "PF2 Key Set", rs) + basic.append(rset) + if self.MODEL == "RB28B" or self.MODEL == "RB628B": rs = RadioSettingValueInteger(0, 9, _settings.squelch) rset = RadioSetting("squelch", "Squelch Level", rs) @@ -1814,6 +1940,60 @@ class RT21Radio(chirp_common.CloneModeRadio): rset = RadioSetting("pfkey_gt", "Key Set >", rs) basic.append(rset) + if self.MODEL == "RT86S": + rs = RadioSettingValueList(BACKLIGHT_LIST, + current_index=_settings.backlight) + rset = RadioSetting("backlight", "Back Light", rs) + basic.append(rset) + + rs = RadioSettingValueList(MENUEXIT_LIST, + current_index=_settings.menuexit) + rset = RadioSetting("menuexit", "Menu Exit Time", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.weather) + rset = RadioSetting("weather", "Weather", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.seekfreq) + rset = RadioSetting("seekfreq", "Seek Freq", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.chnumber) + rset = RadioSetting("chnumber", "Talk", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings4.roger) + rset = RadioSetting("settings4.roger", "Roger", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.keylock) + rset = RadioSetting("keylock", "Key Lock", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.removectdcs) + rset = RadioSetting("removectdcs", "Remove CT/DCS", rs) + basic.append(rset) + + rs = RadioSettingValueList(WX_LIST, + current_index=_settings.wxchnumber) + rset = RadioSetting("wxchnumber", "Weather Channel", rs) + basic.append(rset) + + rs = RadioSettingValueList(GROUPCH_LIST, + current_index=_settings.pf2) + rset = RadioSetting("pf2", "Group Channel #", rs) + basic.append(rset) + + rs = RadioSettingValueList(WAITTIME_LIST, + current_index=_settings.waittime) + rset = RadioSetting("waittime", "Group Wait Time", rs) + basic.append(rset) + + rs = RadioSettingValueBoolean(_settings.pttack) + rset = RadioSetting("pttack", "Group PTT ACK", rs) + basic.append(rset) + return top def set_settings(self, settings): @@ -1838,7 +2018,7 @@ class RT21Radio(chirp_common.CloneModeRadio): element.run_apply_callback() elif setting == "channel": setattr(obj, setting, int(element.value) - 1) - elif setting == "chnumber": + elif setting == "chnumber" and self.MODEL != "RT86S": setattr(obj, setting, int(element.value) - 1) elif setting == "chnumberd": setattr(obj, setting, not int(element.value)) @@ -1848,6 +2028,8 @@ class RT21Radio(chirp_common.CloneModeRadio): setattr(obj, setting, int(element.value) - 1) elif setting == "volume": setattr(obj, setting, int(element.value) - 1) + elif setting == "ch_number": + setattr(obj, setting, int(element.value) - 1) elif element.value.get_mutable(): LOG.debug("Setting %s = %s" % (setting, element.value)) setattr(obj, setting, element.value) @@ -2034,7 +2216,8 @@ class RT29UHFRadio(RT21Radio): chirp_common.PowerLevel("Low", watts=1.00)] _magic = b"PROHRAM" - _fingerprint = [b"P3207" + b"\x13\xF8\xFF", ] # UHF model + _fingerprint = [b"P3207" + b"\x13\xF8\xFF", + b"P3207s\xF8\xFF"] # UHF model _upper = 16 _skipflags = True _reserved = False @@ -2291,7 +2474,9 @@ class RT86Radio(RT21Radio): _memsize = 0x01A0 def process_mmap(self): - self._memobj = bitwise.parse(MEM_FORMAT_RT86, self._mmap) + mem_params = {'memcnt': self._upper, 'settings_offset': '0x004E', + 'bytecnt': 2} + self._memobj = bitwise.parse(MEM_FORMAT_RT86 % mem_params, self._mmap) @directory.register @@ -2321,3 +2506,40 @@ class RB89Radio(RT21Radio): def process_mmap(self): mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0'} self._memobj = bitwise.parse(MEM_FORMAT_RB26 % mem_params, self._mmap) + + +@directory.register +class RT86SRadio(RT21Radio): + """RETEVIS RT86S""" + VENDOR = "Retevis" + MODEL = "RT86S" + BLOCK_SIZE = 0x20 + BLOCK_SIZE_UP = 0x10 + + TXPOWER_LOW = 0x00 + TXPOWER_MED = 0x01 + TXPOWER_HIGH = 0x02 + + DTCS_CODES = DTCS_EXTRA + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.00), + chirp_common.PowerLevel("Mid", watts=1.00), + chirp_common.PowerLevel("Low", watts=0.50)] + + VALID_BANDS = [(400000000, 520000000)] + + _magic = b"PHOGR" + b"\xA7\xB8" + _fingerprint = [b"P32073" + b"\x00\xFF", ] + _upper = 30 + _ack_1st_block = False + _skipflags = True + _reserved = True + + _ranges = [ + (0x0000, 0x0350), + ] + _memsize = 0x0360 + + def process_mmap(self): + mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0', + 'bytecnt': 4} + self._memobj = bitwise.parse(MEM_FORMAT_RT86 % mem_params, self._mmap) diff --git a/chirp/drivers/tdh8.py b/chirp/drivers/tdh8.py index ccaa2ff..5c2916a 100644 --- a/chirp/drivers/tdh8.py +++ b/chirp/drivers/tdh8.py @@ -61,7 +61,7 @@ struct { ham:1, gmrs:1, unused14:1, - unused15:1, + dtmfst:1, pritx:1; u8 scanmode:2, unused16:1, @@ -100,7 +100,8 @@ struct { u8 ligcon; u8 voxdelay; u8 onlychmode:1, - unused:6, + breathled:3, + unused:3, alarm:1; } settings; @@ -309,7 +310,7 @@ struct { dtmfspeed:3; u8 unknown25:4, scanband:4; - u8 unknown26:8; + u8 brightness:8; u8 unknown27:8; u8 unknown28:8; u8 txled:1, @@ -696,13 +697,10 @@ struct{ SQUELCH = ['%s' % x for x in range(0, 10)] LIGHT_LIST = ["CONT", "5s", "10s", "15s", "30s"] LIGHT730_LIST = ["CONT", "10s", "20s", "30s"] -TIME_OUT_LIST = ["OFF", "60s", "120s", "180s"] MDFA_LIST = ["Frequency", "Name"] MDFB_LIST = ["Frequency", "Name"] HOP_LIST = ["A", "B", "C", "D"] -SYNC_LIST = ["ON", "OFF"] LANG_LIST = ["Chinese", "English"] -BTV_SAVER_LIST = ["OFF", "1:1", "1:2", "1:3", "1:4"] SCAN_MODE_LIST = ["TO", "CO", "SE"] PRIO_LIST = ["Edit", "Busy"] SHORT_KEY_LIST = ["None", "FM Radio", "Lamp", "Monitor", @@ -712,7 +710,6 @@ LONG_KEY_LIST = ["None", "FM Radio", "Lamp", SHORT_KEY730_LIST = ["None", "Scan", "FM", "Warn", "TONE", "Weather", "Copy CH"] LONG_KEY730_LIST = SHORT_KEY730_LIST + ["Monitor"] -BUSYLOCK_LIST = ["Off", "On"] PRESS_NAME = ["stopkey1", "ssidekey1", "ssidekey2", "ltopkey2", "lsidekey3", "lsidekey4"] @@ -738,10 +735,10 @@ VFOB_NAME = ["rxfreqb", "wideb", "offsetb"] -TOT_LIST = ["OFF", "30S", "60S", "90S", "120S", "150S", "180S", "210S"] +TOT_LIST = ["Off", "30S", "60S", "90S", "120S", "150S", "180S", "210S"] ALARM_LIST = ["On site", "Alarm"] -DTMF_AUTO_RESET_LIST = ["OFF", "5S", "10S", "15S"] +DTMF_AUTO_RESET_LIST = ["Off", "5S", "10S", "15S"] DTMF_DECODING_RESPONSE_LIST = ["NULL", "RING", "REPLY", "BOTH"] DTMF_SPEED_LIST = ["80ms", "90ms", @@ -764,71 +761,45 @@ SCAN_BAND_LIST = ["All", "5.0M"] # KEY -VOX_GAIN = ["OFF", "1", "2", "3", "4", "5"] +VOX_GAIN = ["Off", "1", "2", "3", "4", "5"] VOX_DELAY = ["1.05s", "2.0s", "3.0s"] -VOX_GAIN730 = ["OFF", "1", "2", "3"] +VOX_GAIN730 = ["Off", "1", "2", "3"] VOX_DELAY730 = ["0.5s", "1.0s", "2.0s", "3.0s"] PTTID_VALUES = ["Off", "BOT", "EOT", "BOTH"] BCLOCK_VALUES = ["Off", "On"] FREQHOP_VALUES = ["Off", "On"] -SCAN_VALUES = ["Del", "Add"] # AB CHANNEL A_OFFSET = ["Off", "-", "+"] A_BAND = ["Wide", "Narrow"] -A_BUSYLOCK = ["Off", "On"] -A_SPEC_QTDQT = ["Off", "On"] A_WORKMODE = ["VFO", "VFO+CH", "CH Mode"] B_OFFSET = ["Off", "-", "+"] B_BAND = ["Wide", "Narrow"] -B_BUSYLOCK = ["Off", "On"] -B_SPEC_QTDQT = ["Off", "On"] B_WORKMODE = ["VFO", "VFO+CH", "CH Mode"] # FM -FM_WORKMODE = ["CH", "VFO"] +FM_WORKMODE = ["VFO", "CH"] FM_CHANNEL = ['%s' % x for x in range(0, 26)] # DTMF GROUPCODE = ["", "Off", "*", "#", "A", "B", "C", "D"] AB_LIST = ["A", "B"] -ALMOD_LIST = ["Site", "Tone", "Code"] BANDWIDTH_LIST = ["Wide", "Narrow"] -COLOR_LIST = ["Off", "Blue", "Orange", "Purple"] -DTMFSPEED_LIST = ["%s ms" % x for x in range(50, 2010, 10)] -DTMFST_LIST = ["OFF", "DT-ST", "ANI-ST", "DT+ANI"] -MODE_LIST = ["Channel", "Name", "Frequency"] PTTID_LIST = ["Off", "BOT", "EOT", "Both"] -PTTIDCODE_LIST = ["%s" % x for x in range(1, 16)] RTONE_LIST = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"] -RESUME_LIST = ["TO", "CO", "SE"] -ROGERRX_LIST = ["Off"] + AB_LIST -RPSTE_LIST = ["OFF"] + ["%s" % x for x in range(1, 11)] -SAVE_LIST = ["Off", "1:1", "1:2", "1:3", "1:4"] SCODE_LIST = ["%s" % x for x in range(1, 16)] -SHIFTD_LIST = ["Off", "+", "-"] -STEDELAY_LIST = ["OFF"] + ["%s ms" % x for x in range(100, 1100, 100)] STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0] STEP_LIST = [str(x) for x in STEPS] STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0] -STEP291_LIST = [str(x) for x in STEPS] -TDRAB_LIST = ["Off"] + AB_LIST -TDRCH_LIST = ["CH%s" % x for x in range(1, 129)] -TIMEOUT_LIST = ["%s sec" % x for x in range(15, 615, 15)] + \ - ["Off (if supported by radio)"] TIMEOUT730_LIST = ["Off"] + ["%s sec" % x for x in range(30, 240, 30)] -VOICE_LIST = ["Off", "English", "Chinese"] -VOX_LIST = ["OFF"] + ["%s" % x for x in range(1, 11)] -WORKMODE_LIST = ["Frequency", "Channel"] # mic MIC_GAIN_LIST = ['%s' % x for x in range(0, 10)] -MIC_GAIN_LIST_H8 = ['%s' % x for x in range(0, 33)] H8_LIST = ["TD-H8", "TD-H8-HAM", "TD-H8-GMRS"] H3_LIST = ["TD-H3", "TD-H3-HAM", "TD-H3-GMRS"] -GMRS_FREQS = bandplan_na.GMRS_HIRPT +GMRS_FREQS = bandplan_na.ALL_GMRS_FREQS NOAA_FREQS = [162550000, 162400000, 162475000, 162425000, 162450000, 162500000, 162525000, 161650000, 161775000, 161750000, @@ -837,8 +808,7 @@ NOAA_FREQS = [162550000, 162400000, 162475000, 162425000, 162450000, HAM_GMRS_NAME = ["NOAA 1", "NOAA 2", "NOAA 3", "NOAA 4", "NOAA 5", "NOAA 6", "NOAA 7", "NOAA 8", "NOAA 9", "NOAA 10", "NOAA 11"] -ALL_MODEL = ["TD-H8", "TD-H8-HAM", "TD-H8-GMRS", "TD-H3", - "TD-H3-HAM", "TD-H3-GMRS", "RT-730"] +ALL_MODEL = H8_LIST + H3_LIST + ["RT-730"] TD_H8 = b"\x50\x56\x4F\x4A\x48\x1C\x14" TD_H3 = b"\x50\x56\x4F\x4A\x48\x5C\x14" @@ -1048,7 +1018,10 @@ class TDH8(chirp_common.CloneModeRadio): _tx_power = [chirp_common.PowerLevel("Low", watts=1.00), chirp_common.PowerLevel("Mid", watts=4.00), chirp_common.PowerLevel("High", watts=8.00)] - _ponmsg_list = ["Full", "Message", "Icon"] + _ponmsg_list = ["Off", "Msg", "Icon"] + _breath_led_list = ["Off", "5S", "10S", "15S", "30S"] + _save_list = ["Off", "1:1", "1:2", "1:3", "1:4", "1:8"] + _save_shortname = "Power Save" @classmethod def detect_from_serial(cls, pipe): @@ -1247,8 +1220,6 @@ class TDH8(chirp_common.CloneModeRadio): mem.immutable = ['freq', 'mode', 'power', 'duplex', 'offset'] elif mem.number >= 31 and mem.number <= 54: - # mem.immutable = ['duplex', 'offset'] - mem.duplex = '+' mem.offset = 5000000 elif mem.number >= 189 and mem.number <= 199: ham_freqs = NOAA_FREQS[mem.number - 189] @@ -1474,14 +1445,13 @@ class TDH8(chirp_common.CloneModeRadio): basic.append(rs) rs = RadioSetting("sync", "SYNC", - RadioSettingValueList( - SYNC_LIST, - current_index=_settings.sync)) + RadioSettingValueBoolean( + not _settings.sync)) basic.append(rs) - rs = RadioSetting("save", "Battery Save", + rs = RadioSetting("save", self._save_shortname, RadioSettingValueList( - BTV_SAVER_LIST, + self._save_list, current_index=_settings.save)) basic.append(rs) @@ -1519,12 +1489,34 @@ class TDH8(chirp_common.CloneModeRadio): basic.append(rs) if self.MODEL != "RT-730": - rs = RadioSetting("rogerprompt", "Roger", - RadioSettingValueBoolean(_settings.rogerprompt)) - basic.append(rs) + if self.MODEL in H8_LIST: + # H8 uses roger-beep bool + rs = RadioSetting("rogerprompt", "Roger", + RadioSettingValueBoolean( + _settings.rogerprompt)) + basic.append(rs) - rs = RadioSetting("txled", "Disp Lcd(TX)", + if self.MODEL in H3_LIST: + # H3 uses roger-beep list + rs = RadioSetting("rogerprompt", "Roger", + RadioSettingValueList( + self._roger_list, + current_index=_settings.rogerprompt)) + basic.append(rs) + + if _settings.brightness not in range(0, 5): + LOG.warning( + "brightness out of range 1 to 5. Actual value: %X. " + "Screen may not be visible", + _settings.brightness) + + rs = RadioSetting("brightness", "Brightness", + RadioSettingValueList( + self._brightness_list, + current_index=4 - _settings.brightness)) + basic.append(rs) + rs = RadioSetting("txled", "Disp Lcd(TX)", RadioSettingValueBoolean(_settings.txled)) basic.append(rs) @@ -1549,8 +1541,9 @@ class TDH8(chirp_common.CloneModeRadio): if self.MODEL in H8_LIST: rs = RadioSetting("stopkey1", "SHORT_KEY_TOP", - RadioSettingValueList(SHORT_KEY_LIST, - current_index=0)) + RadioSettingValueList( + SHORT_KEY_LIST, + current_index=_press.stopkey1)) basic.append(rs) rs = RadioSetting("ltopkey2", "LONG_KEY_TOP", @@ -1643,6 +1636,12 @@ class TDH8(chirp_common.CloneModeRadio): current_index=_settings.voxdelay)) basic.append(rs) + rs = RadioSetting("breathled", "Breath Led", + RadioSettingValueList( + self._breath_led_list, + current_index=_settings.breathled)) + basic.append(rs) + rs = RadioSetting("ponmsg", "Power-On Message", RadioSettingValueList( self._ponmsg_list, @@ -1811,8 +1810,8 @@ class TDH8(chirp_common.CloneModeRadio): cur_a_power = 0 rs = RadioSetting("lowpower", "A TX Power", RadioSettingValueList( - [str(x) for x in self._tx_power], - str(self._tx_power[cur_a_power]))) + [str(x) for x in self._tx_power], + current_index=cur_a_power)) abblock.append(rs) rs = RadioSetting("wide", "A Band", @@ -1821,14 +1820,11 @@ class TDH8(chirp_common.CloneModeRadio): abblock.append(rs) rs = RadioSetting("bcl", "A Busy Lock", - RadioSettingValueList( - A_BUSYLOCK, current_index=_vfoa.bcl)) + RadioSettingValueBoolean(_settings.ablock)) abblock.append(rs) rs = RadioSetting("specialqta", "A Special QT/DQT", - RadioSettingValueList( - A_SPEC_QTDQT, - current_index=_vfoa.specialqta)) + RadioSettingValueBoolean(_vfoa.specialqta)) abblock.append(rs) rs = RadioSetting( @@ -1880,8 +1876,8 @@ class TDH8(chirp_common.CloneModeRadio): cur_b_power = 0 rs = RadioSetting("lowpowerb", "B TX Power", RadioSettingValueList( - [str(x) for x in self._tx_power], - str(self._tx_power[cur_b_power]))) + [str(x) for x in self._tx_power], + current_index=cur_b_power)) abblock.append(rs) rs = RadioSetting("wideb", "B Band", @@ -1890,14 +1886,11 @@ class TDH8(chirp_common.CloneModeRadio): abblock.append(rs) rs = RadioSetting("bclb", "B Busy Lock", - RadioSettingValueList( - B_BUSYLOCK, current_index=_vfob.bclb)) + RadioSettingValueBoolean(_settings.bblock)) abblock.append(rs) rs = RadioSetting("specialqtb", "B Special QT/DQT", - RadioSettingValueList( - B_SPEC_QTDQT, - current_index=_vfob.specialqtb)) + RadioSettingValueBoolean(_vfob.specialqtb)) abblock.append(rs) rs = RadioSetting( @@ -1920,7 +1913,7 @@ class TDH8(chirp_common.CloneModeRadio): current_index=_settings.fmroad)) fmmode.append(rs) - rs = RadioSetting("fmrec", "Forbid Receive", + rs = RadioSetting("fmrec", "Allow Receive", RadioSettingValueBoolean(_settings.fmrec)) fmmode.append(rs) @@ -1970,9 +1963,11 @@ class TDH8(chirp_common.CloneModeRadio): gcode_val = "" else: gcode_val = gcode_val[1] - rs = RadioSetting("gcode", "Group Code", - RadioSettingValueList(GROUPCODE, - gcode_val)) + rs = RadioSetting( + "gcode", "Group Code", + RadioSettingValueList( + GROUPCODE, + current_index=GROUPCODE.index(gcode_val))) dtmf.append(rs) icode_list = self._memobj.icode.idcode @@ -2095,6 +2090,11 @@ class TDH8(chirp_common.CloneModeRadio): ecode_val = RadioSettingValueString(0, 7, used_ecode) rs = RadioSetting("ecode", "PTT ID Ending(BOT)", ecode_val) dtmf.append(rs) + if self.MODEL in H8_LIST: + rs = RadioSetting("dtmfst", "DTMF Side Tones", + RadioSettingValueBoolean(_settings.dtmfst)) + dtmf.append(rs) + # H3 if self.MODEL not in H8_LIST: # stuncode @@ -2196,7 +2196,6 @@ class TDH8(chirp_common.CloneModeRadio): elif name in PRESS_NAME: obj = _press setting = element.get_name() - elif name in VFOA_NAME: obj = _vfoa setting = element.get_name() @@ -2224,7 +2223,7 @@ class TDH8(chirp_common.CloneModeRadio): elif "scode" in name: obj = self._memobj.startcode.scode setting = element.get_name() - elif "ecode" in name: + elif "ecode" == name: obj = self._memobj.endcode.ecode setting = element.get_name() elif "group1" in name: @@ -2266,9 +2265,12 @@ class TDH8(chirp_common.CloneModeRadio): if element.has_apply_callback(): LOG.debug("Using apply callback") element.run_apply_callback() - + elif "brightness" == name: + _settings.brightness = 4 - int(element.value) + elif "sync" == name: + _settings.sync = not int(element.value) # Channel A - elif setting == "rxfreqa" and element.value.get_mutable(): + elif "rxfreqa" == setting and element.value.get_mutable(): val = int(str(element.value).replace( '.', '').ljust(8, '0')) if (val >= 13600000 and val <= 17400000) or \ @@ -2283,7 +2285,7 @@ class TDH8(chirp_common.CloneModeRadio): "or enabled in settings") raise InvalidValueError(msg) - elif setting == "ofseta" and element.value.get_mutable(): + elif "ofseta" == setting and element.value.get_mutable(): if '.' in str(element.value): val = str(element.value).replace(' ', '') if len( @@ -2317,7 +2319,7 @@ class TDH8(chirp_common.CloneModeRadio): raise InvalidValueError(msg) # B channel - elif setting == "rxfreqb" and element.value.get_mutable(): + elif "rxfreqb" == setting and element.value.get_mutable(): val = 0 val = int(str(element.value).replace( '.', '').ljust(8, '0')) @@ -2334,7 +2336,7 @@ class TDH8(chirp_common.CloneModeRadio): raise InvalidValueError(msg) # setattr(obj, setting, val) - elif setting == "ofsetb" and element.value.get_mutable(): + elif "ofsetb" == setting and element.value.get_mutable(): if '.' in str(element.value): val = str(element.value).replace(' ', '') if len(val[val.index(".") + 1:] @@ -2383,10 +2385,10 @@ class TDH8(chirp_common.CloneModeRadio): self._memobj.fmmode[num].fmblock = val self._memobj.fmusedflags[num] = bool(val) - elif setting == 'fmvfo' and element.value.get_mutable(): + elif 'fmvfo' == setting and element.value.get_mutable(): self._memobj.fmvfo = int(element.value * 10) - elif setting == 'gcode' and element.value.get_mutable(): + elif 'gcode' == setting and element.value.get_mutable(): val = str(element.value) if val == 'Off': gcode_used = 0xFF @@ -2406,7 +2408,7 @@ class TDH8(chirp_common.CloneModeRadio): gcode_used = 0x00 self._memobj.groupcode.gcode = gcode_used - elif setting == 'icode' and element.value.get_mutable(): + elif 'icode' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2419,7 +2421,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.icode.idcode = list_val - elif setting == 'scode' and element.value.get_mutable(): + elif 'scode' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2432,7 +2434,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.startcode.scode = list_val - elif setting == 'ecode' and element.value.get_mutable(): + elif 'ecode' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2445,7 +2447,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.endcode.ecode = list_val - elif setting == 'group1' and element.value.get_mutable(): + elif 'group1' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2458,7 +2460,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group1.group1 = list_val - elif setting == 'group2' and element.value.get_mutable(): + elif 'group2' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2471,7 +2473,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group2.group2 = list_val - elif setting == 'group3' and element.value.get_mutable(): + elif 'group3' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2484,7 +2486,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group3.group3 = list_val - elif setting == 'group4' and element.value.get_mutable(): + elif 'group4' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2497,7 +2499,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group4.group4 = list_val - elif setting == 'group5' and element.value.get_mutable(): + elif 'group5' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2510,7 +2512,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group5.group5 = list_val - elif setting == 'group6' and element.value.get_mutable(): + elif 'group6' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2523,7 +2525,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group6.group6 = list_val - elif setting == 'group7' and element.value.get_mutable(): + elif 'group7' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2536,7 +2538,7 @@ class TDH8(chirp_common.CloneModeRadio): lenth_val += 1 self._memobj.group7.group7 = list_val - elif setting == 'group8' and element.value.get_mutable(): + elif 'group8' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2551,7 +2553,7 @@ class TDH8(chirp_common.CloneModeRadio): elif setting == 'micgain': self._memobj.mic.micgain = ( str(element.value)) - elif setting == 'stuncode' and element.value.get_mutable(): + elif 'stuncode' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2563,7 +2565,7 @@ class TDH8(chirp_common.CloneModeRadio): list_val.append(0xFF) lenth_val += 1 self._memobj.skcode.stuncode = list_val - elif setting == 'killcode' and element.value.get_mutable(): + elif 'killcode' == setting and element.value.get_mutable(): val = str(element.value) list_val = [] lenth_val = 0 @@ -2638,10 +2640,16 @@ class TDH8_GMRS(TDH8): 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 31 <= mem.number <= 54: + if mem.freq not in GMRS_FREQS: + msgs.append(chirp_common.ValidationError( + "The frequency in channels 31-54 must be between " + "462.55000-467.71250 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 @@ -2667,7 +2675,8 @@ class TDH3(TDH8): _mem_params = (0x1F2F) _tx_power = [chirp_common.PowerLevel("Low", watts=2.00), chirp_common.PowerLevel("High", watts=5.00)] - _ponmsg_list = ["Off", "Message", "Icon"] + _roger_list = ["Off", "TONE1", "TONE2"] + _brightness_list = ["1", "2", "3", "4", "5"] def process_mmap(self): self._memobj = bitwise.parse(MEM_FORMAT_H3, self._mmap) diff --git a/chirp/drivers/th9000.py b/chirp/drivers/th9000.py index e56de60..859e599 100644 --- a/chirp/drivers/th9000.py +++ b/chirp/drivers/th9000.py @@ -58,6 +58,12 @@ TIMEOUT_LIST = ["Off"] + ["%s min" % x for x in range(1, 30)] TXPWR_LIST = ["60W", "25W"] # maximum power for Hi setting TBSTFREQ_LIST = ["1750 Hz", "2100 Hz", "1000 Hz", "1450 Hz"] BEEP_LIST = ["Off", "On"] +VFO_LIST = ["VFO", "MEM"] +BUTTONS_LIST = ["Off", "Call", "VFO/MEM", "CTCSS/DCS", "MHz Step", "Squelch", + "Transmit Power", "Repeater Shift", "Scan", "Lock", "Monitor", + "Copy Channel", "Delete Channel", "Reverse", + "Display Brightness", "Compander", "Priority", + "DTMF Autodialer", "Show Voltage", "Clone"] MEM_FORMAT = """ #seekto 0x0000; @@ -77,7 +83,7 @@ struct { # 1 Channel Set Flag 0100 011F 20 # 2 Channel Skip Flag 0120 013F 20 # 3 Blank/Unknown 0140 01EF B0 -# 4 Unknown 01F0 01FF 10 +# 4 Button Functions 01F0 01FF 10 # 5 TX/RX Range 0200 020F 10 # 6 Bootup Passwd 0210 021F 10 # 7 Options, Radio 0220 023F 20 @@ -130,6 +136,57 @@ struct { } ropt0120; """ # TH9000 memory map +# section: 4 Programmable Buttons +# used to configure the functions of the programmable buttons +# +# bytes:bit type description +# --------------------------------------------------------------------------- +# 1 u8 btn_p3; Function for P3 press, range 0-19 +# 1 u8 btn_p4; Function for P4 press, range 0-19 +# 1 u8 btn_p5; Function for P5 press, range 0-19 +# 1 u8 btn_p1; Function for P1 press, range 0-19 +# 1 u8 btn_p2; Function for P2 press, range 0-19 +# 1 u8 btn_p3_long; Function for P3 long press, range 0-19 +# 1 u8 btn_p4_long; Function for P4 long press, range 0-19 +# 1 u8 btn_p5_long; Function for P5 long press, range 0-19 +# 1 u8 btn_p1_long; Function for P1 long press, range 0-19 +# 1 u8 btn_p2_long; Function for P2 long press, range 0-19 +# 1 u8 btn_p3_func; Function for F + P3 press, range 0-19 +# 1 u8 btn_p4_func; Function for F + P4 press, range 0-19 +# 1 u8 btn_p5_func; Function for F + P5 press, range 0-19 +# 1 u8 btn_p1_func; Function for F + P1 press, range 0-19 +# 1 u8 btn_p2_func; Function for F + P2 press, range 0-19 +# 1 u8 unknown01FF; +# +# Button Functions: +# 0=Off, 1=Call, 2=VFO/MEM, 3=CTCSS/DCS +# 4=MHz Step, 5=Squelch, 6=TX Power, 7=Repeater Shift +# 8=Scan, 9=Lock, 10=Monitor, 11=Copy CH +# 12=Delete CH, 13=Reverse, 14=Brightness, 15=Compander +# 16=Priority, 17=DTMF Dialer, 18=Show Voltage, 19=Clone +# +MEM_FORMAT = MEM_FORMAT + """ +#seekto 0x01F0; +struct { + u8 btn_p3; + u8 btn_p4; + u8 btn_p5; + u8 btn_p1; + u8 btn_p2; + u8 btn_p3_long; + u8 btn_p4_long; + u8 btn_p5_long; + u8 btn_p1_long; + u8 btn_p2_long; + u8 btn_p3_func; + u8 btn_p4_func; + u8 btn_p5_func; + u8 btn_p1_func; + u8 btn_p2_func; + u8 unknown01FF; +} buttons; +""" +# TH9000 memory map # section: 5 TX/RX Range # used to set the TX/RX range of the radio (e.g. 222-228 MHz for 220 meter) # possible to set range for tx/rx @@ -711,10 +768,13 @@ class Th9000Radio(chirp_common.CloneModeRadio, _settings = self._memobj.settings _freqrange = self._memobj.freqrange _slabel = self._memobj.slabel + _buttons = self._memobj.buttons basic = RadioSettingGroup("basic", "Global Settings") freqrange = RadioSettingGroup("freqrange", "Frequency Ranges") - top = RadioSettingGroup("top", "All Settings", basic, freqrange) + buttons = RadioSettingGroup("buttons", "Programmable Buttons") + top = RadioSettingGroup("top", "All Settings", basic, freqrange, + buttons) settings = RadioSettings(top) def _filter(name): @@ -807,6 +867,96 @@ class Th9000Radio(chirp_common.CloneModeRadio, int(_freqrange.rxrangehi) / 10)) freqrange.append(rs) + rs = RadioSetting( + "btn_p1", "P1 Short Press", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p1)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p2", "P2 Short Press", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p2)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p3", "P3 Short Press", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p3)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p4", "P4 Short Press", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p4)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p5", "P5 Short Press", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p5)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p1_long", "P1 Long Press", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p1_long)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p2_long", "P2 Long Press", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p2_long)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p3_long", "P3 Long Press", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p3_long)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p4_long", "P4 Long Press", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p4_long)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p5_long", "P5 Long Press", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p5_long)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p1_func", "Function + P1", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p1_func)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p2_func", "Function + P2", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p2_func)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p3_func", "Function + P3", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p3_func)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p4_func", "Function + P4", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p4_func)) + buttons.append(rs) + + rs = RadioSetting( + "btn_p5_func", "Function + P5", + RadioSettingValueList( + BUTTONS_LIST, current_index=_buttons.btn_p5_func)) + buttons.append(rs) + return settings def get_settings(self): @@ -841,6 +991,15 @@ class Th9000Radio(chirp_common.CloneModeRadio, setattr(self._memobj.slabel, name, element.value) continue + if name in ["btn_p3", "btn_p4", "btn_p5", "btn_p1", + "btn_p2", "btn_p3_long", "btn_p4_long", + "btn_p5_long", "btn_p1_long", "btn_p2_long", + "btn_p3_func", "btn_p4_func", "btn_p5_func", + "btn_p1_func", "btn_p2_func"]: + LOG.debug("setting %s = %s" % (name, element.value)) + setattr(self._memobj.buttons, name, element.value) + continue + obj = _settings setting = element.get_name() diff --git a/chirp/drivers/thd74.py b/chirp/drivers/thd74.py index f05df6d..ef94047 100644 --- a/chirp/drivers/thd74.py +++ b/chirp/drivers/thd74.py @@ -9,6 +9,7 @@ from chirp import chirp_common from chirp import directory from chirp import errors from chirp import memmap +from chirp import settings LOG = logging.getLogger(__name__) @@ -189,6 +190,7 @@ class THD74Radio(chirp_common.CloneModeRadio, _memsize = 0x7A300 def read_block(self, block, count=256): + self.pipe.log('Reading block %i' % block) hdr = struct.pack(">cHH", b"R", block, 0) self.pipe.write(hdr) r = self.pipe.read(5) @@ -210,6 +212,7 @@ class THD74Radio(chirp_common.CloneModeRadio, return data def write_block(self, block, map, size=256): + self.pipe.log('Writing block %i' % block) hdr = struct.pack(">cHH", b"W", block, size < 256 and size or 0) base = block * size data = map[base:base + size] @@ -423,9 +426,10 @@ class THD74Radio(chirp_common.CloneModeRadio, mem.duplex = DUPLEX[_mem.duplex] mem.tuning_step = TUNE_STEPS[_mem.tuning_step] mem.mode = MODES[_mem.mode] - mem.rtone = chirp_common.TONES[_mem.rtone] - mem.ctone = chirp_common.TONES[_mem.ctone] - mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs_code] + if mem.mode != 'DV': + mem.rtone = chirp_common.TONES[_mem.rtone] + mem.ctone = chirp_common.TONES[_mem.ctone] + mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs_code] if _mem.tone_mode: mem.tmode = 'Tone' @@ -459,6 +463,13 @@ class THD74Radio(chirp_common.CloneModeRadio, if 'Call' in mem.extd_number and mem.mode == 'DV': mem.immutable.append('mode') + mem.extra = settings.RadioSettingGroup('extra', 'Extra') + rs = settings.RadioSetting( + 'rptmode', 'DV Repeater Mode', + settings.RadioSettingValueBoolean(_mem.mode == 7)) + if mem.mode != 'DV': + rs.value.set_mutable(False) + mem.extra.append(rs) return mem def set_memory(self, mem): @@ -472,6 +483,7 @@ class THD74Radio(chirp_common.CloneModeRadio, _flg = self._memobj.flags[mem.number] _nam = self._memobj.names[mem.number + name_index_adj] + was_empty = int(_flg.used) == 0xFF _flg.used = get_used_flag(mem) if mem.empty: @@ -483,7 +495,9 @@ class THD74Radio(chirp_common.CloneModeRadio, _mem.set_raw(b'\x00' * 40) - _flg.group = 0 # FIXME + if was_empty: + # New memories go to group 0 in case it wasn't cleared on delete + _flg.group = 0 _mem.freq = mem.freq _nam.name = mem.name.ljust(16) @@ -517,6 +531,15 @@ class THD74Radio(chirp_common.CloneModeRadio, _mem.dv_rpt1call = encode_call(mem.dv_rpt1call) _mem.dv_rpt2call = encode_call(mem.dv_rpt2call) _mem.dv_code = mem.dv_code + if mem.extra and 'rptmode' in mem.extra: + rptmode = bool(mem.extra['rptmode'].value) + else: + # Pasting a DV memory from another radio means we will + # not have the extra.rptmode flag. So, assume repeater mode + # if the rpt1call has a module in the last character + rptmode = mem.dv_rpt1call.ljust(8)[7] != ' ' + if mem.mode == 'DV' and rptmode: + _mem.mode = 7 def get_raw_memory(self, number): return (repr(self._get_raw_memory(number)) + diff --git a/chirp/drivers/tk270.py b/chirp/drivers/tk270.py index 98cbb1e..c4b664f 100644 --- a/chirp/drivers/tk270.py +++ b/chirp/drivers/tk270.py @@ -48,11 +48,11 @@ struct { #seekto 0x0338; u8 scan[4]; // 4 bytes / bit LSBF for the channel -#seekto 0x033C; +// #seekto 0x033C; u8 active[4]; // 4 bytes / bit LSBF for the active cha // active = 0 -#seekto 0x0340; +// #seekto 0x0340; struct { u8 kMoni; // monitor key function u8 kScan; // scan key function @@ -95,8 +95,8 @@ struct { MEM_SIZE = 0x400 BLOCK_SIZE = 8 MEM_BLOCKS = list(range(0, (MEM_SIZE // BLOCK_SIZE))) -ACK_CMD = "\x06" -TIMEOUT = 0.05 # from 0.03 up it' s safe, we set in 0.05 for a margin +ACK_CMD = b"\x06" +TIMEOUT = 1 POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1), chirp_common.PowerLevel("High", watts=5)] @@ -146,10 +146,10 @@ def send(radio, frame): rawsend(radio, frame) -def make_frame(cmd, addr, data=""): +def make_frame(cmd, addr, data=b""): """Pack the info in the format it likes""" ts = struct.pack(">BHB", ord(cmd), addr, 8) - if data == "": + if not data: return ts else: if len(data) == 8: @@ -200,33 +200,15 @@ def open_radio(radio): raise errors.RadioError(msg) # we will try to open the radio 5 times, this is an improved mechanism - magic = "PROGRAM" - exito = False - for i in range(0, 5): - for i in range(0, len(magic)): - ack = rawrecv(radio, 1) - time.sleep(0.05) - send(radio, magic[i]) + magic = b"PROGRAM" + radio.pipe.write(magic) + handshake(radio, 'Radio did not respond to program command') - try: - handshake(radio, "Radio not entering Program mode") - exito = True - break - except: - LOG.debug("Attempt #%s, failed, trying again" % i) - pass - - # check if we had EXITO - if exito is False: - msg = "The radio did not accept program mode after five tries.\n" - msg += "Check you interface cable and power cycle your radio." - raise errors.RadioError(msg) - - rawsend(radio, "\x02") + rawsend(radio, b"\x02") ident = rawrecv(radio, 8) handshake(radio, "Comm error after ident", True) - if not (radio.TYPE in ident): + if not (radio.TYPE.encode() in ident): LOG.debug("Incorrect model ID, got %s" % util.hexprint(ident)) msg = "Incorrect model ID, got %s, it not contains %s" % \ (ident[0:5], radio.TYPE) @@ -240,11 +222,11 @@ def do_download(radio): # UI progress status = chirp_common.Status() status.cur = 0 - status.max = MEM_SIZE / BLOCK_SIZE + status.max = MEM_SIZE // BLOCK_SIZE status.msg = "Cloning from radio..." radio.status_fn(status) - data = "" + data = b"" for addr in MEM_BLOCKS: send(radio, make_frame("R", addr * BLOCK_SIZE)) data += recv(radio) @@ -257,7 +239,7 @@ def do_download(radio): status.msg = "Cloning from radio..." radio.status_fn(status) - return memmap.MemoryMap(data) + return memmap.MemoryMapBytes(data) def do_upload(radio): @@ -267,7 +249,7 @@ def do_upload(radio): # UI progress status = chirp_common.Status() status.cur = 0 - status.max = MEM_SIZE / BLOCK_SIZE + status.max = MEM_SIZE // BLOCK_SIZE status.msg = "Cloning to radio..." radio.status_fn(status) count = 0 @@ -319,7 +301,6 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa VARIANT = "" MODEL = "" _kind = "" - NEEDS_COMPAT_SERIAL = True @classmethod def get_prompts(cls): @@ -384,7 +365,13 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa def sync_in(self): """Download from radio""" - self._mmap = do_download(self) + try: + self._mmap = do_download(self) + except errors.RadioError: + raise + except Exception as e: + LOG.exception('Error downloading: %s', e) + raise errors.RadioError("Error downloading data from radio") self.process_mmap() def sync_out(self): @@ -392,13 +379,17 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa # Get the data ready for upload try: self._prep_data() - except: + except Exception as e: + LOG.exception('Failed to prepare data for upload: %s', e) raise errors.RadioError("Error processing the radio data") # do the upload try: do_upload(self) - except: + except errors.RadioError: + raise + except Exception as e: + LOG.exception('Error uploading: %s', e) raise errors.RadioError("Error uploading data to radio") def set_variant(self): @@ -446,13 +437,13 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa # fldata = "\x00\xf0\xff\xff\xff" * achs + \ # "\xff" * (5 * (self._upper - achs)) - fldata = "\xFF" * 5 * self._upper + fldata = b"\xFF" * 5 * self._upper self._fill(0x0280, fldata) def _fill(self, offset, data): """Fill an specified area of the memmap with the passed data""" for addr in range(0, len(data)): - self._mmap[offset + addr] = data[addr] + self._mmap[offset + addr] = bytes([data[addr]]) def process_mmap(self): """Process the mem map into the mem object""" @@ -494,7 +485,7 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa def decode_tone(self, val): """Parse the tone data to decode from mem, it returns: Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)""" - if val.get_raw(asbytes=False) == "\xFF\xFF": + if val.get_raw() == b"\xFF\xFF": return '', None, None val = int(val) @@ -557,11 +548,11 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa # Memory number mem.number = number - if _mem.get_raw(asbytes=False)[0] == "\xFF": + if _mem.get_raw()[0] == 0xFF: mem.empty = True # but is not enough, you have to clear the memory in the mmap # to get it ready for the sync_out process, just in case - _mem.set_raw("\xFF" * 16) + _mem.set_raw(b"\xFF" * 16) # set the channel to inactive state self.set_active(number - 1, False) return mem @@ -569,7 +560,7 @@ class Kenwood_P60_Radio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRa # Freq and offset mem.freq = int(_mem.rxfreq) * 10 # tx freq can be blank - if _mem.get_raw(asbytes=False)[4] == "\xFF" or int(_mem.txen) == 255: + if _mem.get_raw()[4] == 0xFF or int(_mem.txen) == 255: # TX freq not set mem.offset = 0 mem.duplex = "off" diff --git a/chirp/drivers/tk280.py b/chirp/drivers/tk280.py index 75ac12e..1221cb6 100644 --- a/chirp/drivers/tk280.py +++ b/chirp/drivers/tk280.py @@ -55,6 +55,25 @@ LOG = logging.getLogger(__name__) # # + +def choose_step(step_map, freq, default=5.0): + """Choose the proper step index for a given frequency. + + @step_map should be a dict of step (in kHz) to index, in order of + preference. + @freq should be a frequency in Hz. + Returns the step index from step_map to use. + """ + try: + step = chirp_common.required_step(freq, step_map.keys()) + except errors.InvalidDataError: + step = default + LOG.warning('Frequency %s requires step not in available map, ' + 'using %s kHz by default', + chirp_common.format_freq(freq), step) + return step_map[step] + + CONVENTIONAL_DEFS = """ struct conv_settings { // x00-x01, Edit>>Model Information>>Radio Format, @@ -764,8 +783,8 @@ def do_upload(radio): class TKx80SubdevMeta(type): """Metaclass for generating subdevice subclasses""" - def __new__(cls, name, parent, dct): - return super(TKx80SubdevMeta, cls).__new__(cls, name, (parent,), dct) + def __new__(cls, name, bases, dct): + return super(TKx80SubdevMeta, cls).__new__(cls, name, bases, dct) @staticmethod def make_subdev(parent_dev, child_cls, key, to_copy, **args): @@ -776,7 +795,7 @@ class TKx80SubdevMeta(type): args: Class variables to set on the new class """ return TKx80SubdevMeta('%s_%s' % (child_cls.__name__, key), - child_cls, + (child_cls, parent_dev.__class__), dict({k: getattr(parent_dev, k) for k in to_copy}, **args)) @@ -870,10 +889,11 @@ class KenwoodTKx80(chirp_common.CloneModeRadio): return rf def get_sub_devices(self): - if not self._memobj: - return [TKx80Group(self, 1)] to_copy = ('MODEL', 'TYPE', 'POWER_LEVELS', '_range', '_steps', '_freqmult') + if not self._memobj: + return [TKx80SubdevMeta.make_subdev( + self, TKx80Group, 1, to_copy)(self, 1)] return sorted([ TKx80SubdevMeta.make_subdev( self, TKx80Group, i, @@ -1652,23 +1672,13 @@ class KenwoodTKx80(chirp_common.CloneModeRadio): _mem.txfreq = mem.freq // self._freqmult step_lookup = { - 2.5: 0x0, - 6.25: 0x2, 12.5: 0x5, + 6.25: 0x2, 5.0: 0x1, + 2.5: 0x0, } - try: - _mem.rx_step = step_lookup[chirp_common.required_step( - int(_mem.rxfreq) * 10)] - except errors.InvalidDataError: - LOG.warning('Unknown step for rx freq, defaulting to 5kHz') - _mem.rx_step = 0x1 - try: - _mem.tx_step = step_lookup[chirp_common.required_step( - int(_mem.txfreq) * 10)] - except errors.InvalidDataError: - LOG.warning('Unknown step for tx freq, defaulting to 5kHz') - _mem.tx_step = 0x1 + _mem.rx_step = choose_step(step_lookup, int(_mem.rxfreq) * 10) + _mem.tx_step = choose_step(step_lookup, int(_mem.txfreq) * 10) ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \ chirp_common.split_tone_encode(mem) @@ -1685,7 +1695,7 @@ class KenwoodTKx80(chirp_common.CloneModeRadio): _mem.power = self.POWER_LEVELS[0] -class TKx80Group(KenwoodTKx80): +class TKx80Group: def __init__(self, parent, group): self._parent = parent self._group = int(group) diff --git a/chirp/drivers/tk3140.py b/chirp/drivers/tk3140.py index af9e6ca..6148fa8 100644 --- a/chirp/drivers/tk3140.py +++ b/chirp/drivers/tk3140.py @@ -20,6 +20,7 @@ import struct from chirp import chirp_common from chirp import bitwise from chirp import directory +from chirp.drivers import tk280 from chirp.drivers import tk8160 from chirp.drivers import tk8180 from chirp import errors @@ -35,13 +36,11 @@ EMPTY_INDEX_ENTRY = IndexEntry(0xFF, 0xFF, 0xFF, 0xFF) def send(radio, frame): - LOG.debug("%04i P>R:\n%s" % (len(frame), util.hexprint(frame))) radio.pipe.write(frame) def recv(radio, count): buf = radio.pipe.read(count) - LOG.debug('%04i: R>P:\n%s' % (len(buf), util.hexprint(buf))) return buf @@ -143,7 +142,6 @@ def do_upload(radio): data = radio._mmap.get_packed() for block in range(0x80): if 0x54 <= block < 0x60: - LOG.debug('Skipping block 0x%02x' % block) continue addr = block * 256 chunk = data[addr:addr + 256] @@ -290,8 +288,10 @@ struct { char name[10]; lbcd rx_freq[4]; lbcd tx_freq[4]; - u8 rxsomething; - u8 txsomething; + u8 rxsomething:4, + rxstep:4; + u8 txsomething:4, + txstep:4; ul16 rxtone; ul16 txtone; u8 unknown2[5]; @@ -547,8 +547,8 @@ class KenwoodTKx140Radio(chirp_common.CloneModeRadio): _mem.memory = mem.number _mem.zone = self._zone self.sort_index() - _mem.rxsomething = 0x35 - _mem.txsomething = 0x35 + _mem.rxsomething = 0x3 + _mem.txsomething = 0x3 _mem.rx_freq = mem.freq // 10 if mem.duplex == '': @@ -564,6 +564,17 @@ class KenwoodTKx140Radio(chirp_common.CloneModeRadio): else: raise errors.RadioError('Unsupported duplex mode %r' % mem.duplex) + step_lookup = { + 6.25: 0x02, + 12.5: 0x05, + 5.0: 0x01, + 2.5: 0x00, + 10.0: 0x04, + 7.5: 0x06, # maybe? + } + _mem.rxstep = tk280.choose_step(step_lookup, int(_mem.rx_freq) * 10) + _mem.txstep = tk280.choose_step(step_lookup, int(_mem.tx_freq) * 10) + txtone, rxtone = chirp_common.split_tone_encode(mem) _mem.rxtone = tk8180.KenwoodTKx180Radio._encode_tone(*rxtone) _mem.txtone = tk8180.KenwoodTKx180Radio._encode_tone(*txtone) diff --git a/chirp/drivers/tk481.py b/chirp/drivers/tk481.py index f03cd74..b421f45 100644 --- a/chirp/drivers/tk481.py +++ b/chirp/drivers/tk481.py @@ -237,11 +237,12 @@ class TKx80_Trunked(tk280.KenwoodTKx80): return rf def get_sub_devices(self): - # For the uninitialized case of just surveying the features - if not self._memobj: - return [TKx80System(self, 1)] to_copy = ('MODEL', 'TYPE', 'POWER_LEVELS', '_range', '_steps', '_freqmult') + if not self._memobj: + # For the uninitialized case of just surveying the features + return [tk280.TKx80SubdevMeta.make_subdev( + self, TKx80System, 1, to_copy)(self, 1)] return [ tk280.TKx80SubdevMeta.make_subdev( self, TKx80System, i, @@ -366,7 +367,7 @@ class TKx80_Trunked(tk280.KenwoodTKx80): return -class TKx80System(TKx80_Trunked): +class TKx80System: def __init__(self, parent, system): self._system = system self._parent = parent @@ -375,6 +376,14 @@ class TKx80System(TKx80_Trunked): def _memobj(self): return self._parent._memobj + def get_sub_devices(self): + return [] + + def get_features(self): + rf = self._parent.get_features() + rf.has_sub_devices = False + return rf + @directory.register class TK481(TKx80_Trunked): diff --git a/chirp/drivers/tk760g.py b/chirp/drivers/tk760g.py index 934979d..5d61c89 100644 --- a/chirp/drivers/tk760g.py +++ b/chirp/drivers/tk760g.py @@ -21,7 +21,7 @@ from chirp import chirp_common, directory, memmap, errors, util, bitwise from chirp.settings import RadioSettingGroup, RadioSetting, \ RadioSettingValueBoolean, RadioSettingValueList, \ RadioSettingValueString, RadioSettingValueInteger, \ - RadioSettings + RadioSettings, RadioSettingValueMap LOG = logging.getLogger(__name__) @@ -327,13 +327,15 @@ KEYS = { 0x5d: "AUX", 0xa1: "Channel Up/Down" # Knob for portables only } +KEY_MAP = [(v, k) for k, v in KEYS.items()] def _raw_recv(radio, amount): """Raw read from the radio device""" try: data = radio.pipe.read(amount) - except: + except Exception as e: + LOG.exception('Failed read: %s', e) raise errors.RadioError("Error reading data from radio") # DEBUG @@ -347,7 +349,8 @@ def _raw_send(radio, data): """Raw send to the radio device""" try: radio.pipe.write(data) - except: + except Exception as e: + LOG.exception('Failed write: %s', e) raise errors.RadioError("Error sending data to radio") # DEBUG @@ -418,7 +421,7 @@ def _recv(radio): raise errors.RadioError('No response from radio') elif cmd == b'Z': # Empty "zero" block - ff = _raw_recv(radio, 1) + _raw_recv(radio, 1) _handshake(radio, "after zero block") return b'\xff' * 256 elif cmd != b'W': @@ -748,7 +751,7 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, if bnumb != 255 and (bank != 255 and bank != 0): try: data[bank].append(ch) - except: + except Exception: data[bank] = list() data[bank].append(ch) data[bank].sort() @@ -1117,7 +1120,6 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, mess = self._memobj.message keys = self._memobj.keys idm = self._memobj.id - passwd = self._memobj.passwords # basic features of the radio basic = RadioSettingGroup("basic", "Basic Settings") @@ -1134,7 +1136,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, # Basic tot = RadioSetting("settings.tot", "Time Out Timer (TOT)", - RadioSettingValueList(TOT, '%i' % sett.tot)) + RadioSettingValueList( + TOT, current_index=TOT.index('%i' % sett.tot))) basic.append(tot) totalert = RadioSetting("settings.tot_alert", "TOT pre alert", @@ -1199,6 +1202,12 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, RadioSettingValueString(0, 8, ponm, False)) basic.append(pom) + offhook = RadioSetting('settings.off_hook_decode', 'Off-hook decode', + RadioSettingValueBoolean( + not sett.off_hook_decode)) + offhook.set_doc('Squelch mode active when mic is off-hook') + basic.append(offhook) + # dealer valid_chars = ",-/:[]" + chirp_common.CHARSET_ALPHANUMERIC mstr = "".join([c for c in self._VARIANT if c in valid_chars]) @@ -1250,28 +1259,28 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, # The Mobile only parameters are wrapped here if self.TYPE[0] == "M": vu = RadioSetting("keys.kVOL_UP", "VOL UP", - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kVOL_UP)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kVOL_UP))) fkeys.append(vu) vd = RadioSetting("keys.kVOL_DOWN", "VOL DOWN", - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kVOL_DOWN)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kVOL_DOWN))) fkeys.append(vd) chu = RadioSetting("keys.kCH_UP", "CH UP", - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kCH_UP)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kCH_UP))) fkeys.append(chu) chd = RadioSetting("keys.kCH_DOWN", "CH DOWN", - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kCH_DOWN)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kCH_DOWN))) fkeys.append(chd) foot = RadioSetting("keys.kFOOT", "Foot switch", - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kFOOT)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kFOOT))) fkeys.append(foot) # this is the common buttons for all @@ -1283,8 +1292,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, scn_name = "Open Circle" scn = RadioSetting("keys.kSCN", scn_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kSCN)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kSCN))) fkeys.append(scn) a_name = "A" @@ -1292,8 +1301,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, a_name = "Closed circle" a = RadioSetting("keys.kA", a_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kA)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kA))) fkeys.append(a) da_name = "D/A" @@ -1301,8 +1310,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, da_name = "< key" da = RadioSetting("keys.kDA", da_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kDA)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kDA))) fkeys.append(da) gu_name = "Triangle up" @@ -1310,8 +1319,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, gu_name = "Side 1" gu = RadioSetting("keys.kGROUP_UP", gu_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kGROUP_UP)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kGROUP_UP))) fkeys.append(gu) # Side keys on portables @@ -1320,8 +1329,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, gd_name = "> key" gd = RadioSetting("keys.kGROUP_DOWN", gd_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kGROUP_DOWN)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kGROUP_DOWN))) fkeys.append(gd) mon_name = "MON" @@ -1329,8 +1338,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, mon_name = "Side 2" mon = RadioSetting("keys.kMON", mon_name, - RadioSettingValueList(KEYS.values(), - KEYS[int(keys.kMON)])) + RadioSettingValueMap(KEY_MAP, + int(keys.kMON))) fkeys.append(mon) return top @@ -1364,7 +1373,7 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, # catching the "off" values as zero try: value = int(value) - except: + except ValueError: value = 0 # tot case step 15 @@ -1383,11 +1392,11 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, # Bool types + inverted if setting in ["c2t", "poweron_tone", "control_tone", "warn_tone", "battery_save", "self_prog", - "clone", "panel_test"]: + "clone", "panel_test", "off_hook_decode"]: value = bool(value) # this cases are inverted - if setting == "c2t": + if setting in ["c2t", "off_hook_decode"]: value = not value # case battery save is special @@ -1447,7 +1456,8 @@ class Kenwood_Serie_60G(chirp_common.CloneModeRadio, b = 0 mem = self._memobj.memory[loc - 1] mem.bank = b + 1 - except: + except Exception as e: + LOG.warning('Failed to set bank: %s', e) msg = "You can't have a channel without a bank, click another bank" raise errors.InvalidDataError(msg) @@ -1649,7 +1659,9 @@ class TK272G_Radios(Kenwood_Serie_60G): MODEL = "TK-272G" TYPE = b"P2720" VARIANTS = { - b"P2720\x05\xfb": (32, 136, 150, "K1"), + # NOTE: This is technically 136-150 MHz, but the radio supports + # the full range for RX at least + b"P2720\x05\xfb": (32, 136, 174, "K1"), b"P2720\x04\xfb": (32, 150, 174, "K") } diff --git a/chirp/drivers/tk8180.py b/chirp/drivers/tk8180.py index b439f8c..d644933 100644 --- a/chirp/drivers/tk8180.py +++ b/chirp/drivers/tk8180.py @@ -20,6 +20,7 @@ from collections import OrderedDict from chirp import chirp_common, directory, memmap, errors, util from chirp import bitwise +from chirp.drivers import tk280 from chirp.settings import MemSetting, RadioSettingValueInvertedBoolean from chirp.settings import RadioSettingGroup, RadioSetting from chirp.settings import RadioSettingValueBoolean, RadioSettingValueList @@ -259,7 +260,7 @@ BATTWARN_SETTINGS = { # The buttons in memory are not logically arranged for display and sorting # would do weird things, so map them manually here BUTTONS = { - 'Side 1': 0, + 'Side 1 / Triangle': 0, 'Side 2': 5, 'S': 1, 'A': 2, @@ -308,6 +309,7 @@ BUTTON_FUNCTIONS = { 'Display Character': 0x1E, 'Fixed Volume': 0x20, 'Function': 0x21, + 'LCD Brightness': 0x27, 'Monitor': 0x2A, 'Monitor Momentary': 0x2B, 'Transceiver Password': 0x32, @@ -328,6 +330,7 @@ PORTABLE_BUTTON_FUNCTIONS = { } # These are only available on the mobile transceiver MOBILE_BUTTON_FUNCTIONS = { + 'Zone Down': 0x4A, # Different on mobile? } KNOB_MODE = { 'None': 0xFF, @@ -442,16 +445,15 @@ def do_download(radio): status.max = radio._memsize status.msg = "Cloning from radio" radio.status_fn(status) - LOG.debug('Radio address 0x%04x' % len(data)) # Addresses 0x0000-0xBF00 pulled by block number (divide by 0x100) for block in range(0, 0xBF + 1): + radio.pipe.log('Read block index %02x' % block) send(radio, make_frame('R', block)) cmd = radio.pipe.read(1) chunk = b'' if cmd == b'Z': data += bytes(b'\xff' * 256) - LOG.debug('Radio reports empty block %02x' % block) elif cmd == b'W': chunk = bytes(radio.pipe.read(256)) if len(chunk) != 256: @@ -463,7 +465,6 @@ def do_download(radio): chr(cmd))) raise errors.RadioError('Radio sent unexpected response') - LOG.debug('Read block index %02x' % block) status() chksum = radio.pipe.read(1) @@ -485,6 +486,7 @@ def do_download(radio): # Addresses 0xC000 - 0xD1F0 pulled by address for block in range(0x0100, 0x1200, 0x40): + radio.pipe.log('Read memory address %04x' % block) send(radio, make_frame('S', block, b'\x40')) x = radio.pipe.read(1) if x != b'X': @@ -492,7 +494,6 @@ def do_download(radio): chunk = radio.pipe.read(0x40) data += chunk - LOG.debug('Read memory address %04x' % block) status() radio.pipe.write(b'\x06') @@ -521,9 +522,9 @@ def do_upload(radio): addr = block * 0x100 chunk = bytes(radio._mmap[addr:addr + 0x100]) if all(byte == b'\xff' for byte in chunk): - LOG.debug('Sending zero block %i, range 0x%04x' % (block, addr)) send(radio, make_frame('Z', block, b'\xFF')) else: + radio.pipe.log('Sending block %i' % block) checksum = checksum_data(chunk) send(radio, make_frame('W', block, chunk + bytes([checksum]))) @@ -582,8 +583,8 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): def __init__(self, *a, **k): self._zones = [] chirp_common.CloneModeRadio.__init__(self, *a, **k) - _dat_header = (b'KPG89D\xFF\xFF\xFF\xFFV1.61' + self._model + - (b'\xFF' * 11) + (b'\xFF' * 32)) + self._dat_header = (b'KPG89D\xFF\xFF\xFF\xFFV1.61' + self._model + + (b'\xFF' * 11) + (b'\xFF' * 32)) def sync_in(self): try: @@ -636,7 +637,6 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): return self._model.startswith(b'P') def probe_layout(self): - start_addrs = [] tmp_format = '#seekto 0x0A00; ul16 zone_starts[128];' mem = bitwise.parse(tmp_format, self._mmap) zone_format = """struct zoneinfo { @@ -734,7 +734,6 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): dest_zoneinfo.set_raw(source_zoneinfo.get_raw(asbytes=False)) dest_zoneinfo.count = count - source_i = 0 for dest_i in range(0, min(count, old_count)): dest[dest_i].set_raw(source[dest_i].get_raw(asbytes=False)) else: @@ -988,24 +987,15 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): else: raise errors.RadioError('Unsupported duplex mode %r' % mem.duplex) - try: - tx_step = chirp_common.required_step(int(_mem.tx_freq) * 10) - except errors.InvalidDataError: - tx_step = 5 - try: - rx_step = chirp_common.required_step(int(_mem.rx_freq) * 10) - except errors.InvalidDataError: - rx_step = 5 - step_lookup = { - 2.5: 0x1, + 12.5: 0x6, + 10.0: 0x5, 6.25: 0x3, - 12.5: 0x3, 5: 0x2, + 2.5: 0x1, } - # Default to 5kHz if we don't know any better - _mem.rx_step = step_lookup.get(rx_step, 0x2) - _mem.tx_step = step_lookup.get(tx_step, 0x2) + _mem.rx_step = tk280.choose_step(step_lookup, int(_mem.rx_freq) * 10) + _mem.tx_step = tk280.choose_step(step_lookup, int(_mem.tx_freq) * 10) skipbyte = self._memobj.skipflags[(mem.number - 1) // 8] if mem.skip == 'S': @@ -1412,7 +1402,7 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): else: model_functions = PORTABLE_BUTTON_FUNCTIONS - pri_functions = model_functions | 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}) @@ -1458,8 +1448,6 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): return group def get_settings(self): - settings = self._memobj.settings - zones = self._get_zones() common1 = self._get_common1() common2 = self._get_common2() @@ -1486,22 +1474,20 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): def get_sub_devices(self): zones = [] + to_copy = ('VENDOR', 'MODEL', 'VALID_BANDS', '_model') for i, _ in enumerate(self._zones): zone = getattr(self._memobj, 'zone%i' % i) - class _Zone(KenwoodTKx180RadioZone): - VENDOR = self.VENDOR - MODEL = self.MODEL - VALID_BANDS = self.VALID_BANDS - VARIANT = 'Zone %s' % ( - str(zone.zoneinfo.name).rstrip('\x00').rstrip()) - _model = self._model + zone_cls = tk280.TKx80SubdevMeta.make_subdev( + self, KenwoodTKx180RadioZone, zone, to_copy, + VARIANT='Zone %s' % ( + str(zone.zoneinfo.name).rstrip('\x00').rstrip())) - zones.append(_Zone(self, i)) + zones.append(zone_cls(self, i)) return zones -class KenwoodTKx180RadioZone(KenwoodTKx180Radio): +class KenwoodTKx180RadioZone: _zone = None def __init__(self, parent, zone=0): diff --git a/chirp/drivers/uv5r.py b/chirp/drivers/uv5r.py index 32e3949..6e67dcc 100644 --- a/chirp/drivers/uv5r.py +++ b/chirp/drivers/uv5r.py @@ -1901,6 +1901,46 @@ class BaofengUV5RGeneric(BaofengUV5R): ROUV5REXAlias, A5RAlias] +@directory.register +class BaofengUV5GPro(BaofengUV5R): + MODEL = "UV-5G Pro" + _airband = (108000000, 136000000) + + def get_features(self): + rf = super().get_features() + rf.valid_bands = [(108000000, 174000000), + (220000000, 260000000), + (350000000, 390000000), + (400000000, 520000000)] + rf.valid_modes.append('AM') + return rf + + @classmethod + def match_model(cls, filename, filedata): + return False + + def get_memory(self, number): + mem = super().get_memory(number) + if chirp_common.in_range(mem.freq, [self._airband]): + # UV-5G Pro is AM in 108-136 MHz range + mem.mode = 'AM' + elif mem.mode == 'AM': + mem.mode = 'FM' + return mem + + def validate_memory(self, mem): + msgs = super().validate_memory(mem) + if (chirp_common.in_range(mem.freq, [self._airband]) and + not mem.mode == 'AM'): + msgs.append(chirp_common.ValidationWarning( + _('Frequency in this range requires AM mode'))) + if (not chirp_common.in_range(mem.freq, [self._airband]) and + mem.mode == 'AM'): + msgs.append(chirp_common.ValidationWarning( + _('Frequency in this range must not be AM mode'))) + return msgs + + @directory.register class BaofengF11Radio(BaofengUV5R): VENDOR = "Baofeng" diff --git a/chirp/drivers/uvb5.py b/chirp/drivers/uvb5.py index bd89e1a..b212d8b 100644 --- a/chirp/drivers/uvb5.py +++ b/chirp/drivers/uvb5.py @@ -678,20 +678,23 @@ class BaofengUVB5(chirp_common.CloneModeRadio, rs.set_apply_callback(apply_limit, self._memobj.limits) basic.append(rs) - fm_preset = RadioSettingGroup("fm_preset", "FM Radio Presets") - group.append(fm_preset) - - for i in range(0, 16): - if self._memobj.fm_presets[i] < 0x01AF: - used = True - preset = self._memobj.fm_presets[i] / 10.0 + 65 - else: - used = False - preset = 65 - rs = RadioSetting("fm_presets_%1i" % i, "FM Preset %i" % (i + 1), - RadioSettingValueBoolean(used), - RadioSettingValueFloat(65, 108, preset, 0.1, 1)) - fm_preset.append(rs) + if 'fm_presets' in self._memobj: + fm_preset = RadioSettingGroup("fm_preset", "FM Radio Presets") + group.append(fm_preset) + + for i in range(0, 16): + if self._memobj.fm_presets[i] < 0x01AF: + used = True + preset = self._memobj.fm_presets[i] / 10.0 + 65 + else: + used = False + preset = 65 + rs = RadioSetting("fm_presets_%1i" % i, + "FM Preset %i" % (i + 1), + RadioSettingValueBoolean(used), + RadioSettingValueFloat(65, 108, preset, + 0.1, 1)) + fm_preset.append(rs) testmode = RadioSettingGroup("testmode", "Test Mode Settings") group.append(testmode) diff --git a/chirp/drivers/uvk5.py b/chirp/drivers/uvk5.py index a22f8dd..6706b90 100644 --- a/chirp/drivers/uvk5.py +++ b/chirp/drivers/uvk5.py @@ -295,9 +295,9 @@ FMMAX = 108.0 # bands supported by the UV-K5 BANDS = { 0: [50.0, 76.0], - 1: [108.0, 135.9999], - 2: [136.0, 199.9990], - 3: [200.0, 299.9999], + 1: [108.0, 136.9999], + 2: [137.0, 173.9999], + 3: [174.0, 349.9999], 4: [350.0, 399.9999], 5: [400.0, 469.9999], 6: [470.0, 600.0] @@ -306,9 +306,9 @@ BANDS = { # for radios with modified firmware: BANDS_NOLIMITS = { 0: [18.0, 76.0], - 1: [108.0, 135.9999], - 2: [136.0, 199.9990], - 3: [200.0, 299.9999], + 1: [108.0, 136.9999], + 2: [137.0, 173.9999], + 3: [174.0, 349.9999], 4: [350.0, 399.9999], 5: [400.0, 469.9999], 6: [470.0, 1300.0] @@ -383,8 +383,8 @@ def calculate_crc16_xmodem(data: bytes): def _send_command(serport, data: bytes): """Send a command to UV-K5 radio""" - LOG.debug("Sending command (unobfuscated) len=0x%4.4x:\n%s", - len(data), util.hexprint(data)) + serport.log("Sending command (unobfuscated) len=0x%4.4x:\n%s" % ( + len(data), util.hexprint(data))) crc = calculate_crc16_xmodem(data) data2 = data + struct.pack("HBB", 0xabcd, len(data), 0) + \ xorarr(data2) + \ struct.pack(">H", 0xdcba) - if DEBUG_SHOW_OBFUSCATED_COMMANDS: - LOG.debug("Sending command (obfuscated):\n%s", util.hexprint(command)) try: result = serport.write(command) except Exception as e: @@ -434,15 +432,8 @@ def _receive_reply(serport): util.hexprint(footer), len(footer)) raise errors.RadioError("Bad response footer") - if DEBUG_SHOW_OBFUSCATED_COMMANDS: - LOG.debug("Received reply (obfuscated) len=0x%4.4x:\n%s", - len(cmd), util.hexprint(cmd)) - cmd2 = xorarr(cmd) - LOG.debug("Received reply (unobfuscated) len=0x%4.4x:\n%s", - len(cmd2), util.hexprint(cmd2)) - return cmd2 @@ -480,38 +471,27 @@ def _sayhello(serport): def _readmem(serport, offset, length): - LOG.debug("Sending readmem offset=0x%4.4x len=0x%4.4x", offset, length) + serport.log("Sending readmem offset=0x%4.4x len=0x%4.4x" % ( + offset, length)) readmem = b"\x1b\x05\x08\x00" + \ struct.pack("> 8) & 0xff): @@ -737,7 +717,8 @@ class UVK5RadioBase(chirp_common.CloneModeRadio): # Return a raw representation of the memory object, which # is very helpful for development def get_raw_memory(self, number): - return repr(self._memobj.channel[number-1]) + return '\n'.join([repr(self._memobj.channel[number-1]), + repr(self._memobj.channel_attributes[number-1])]) def _find_band(self, hz): return _find_band(self._expanded_limits, hz) diff --git a/chirp/drivers/wouxun.py b/chirp/drivers/wouxun.py index 1e87d83..3d0b170 100644 --- a/chirp/drivers/wouxun.py +++ b/chirp/drivers/wouxun.py @@ -60,7 +60,7 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio, MODEL = "KG-UVD1P" _model = b"KG669V" - _querymodel = (b"HiWOUXUN\x02", b"PROGUV6X\x02") + _querymodels = (b"HiWOUXUN\x02", b"PROGUV6X\x02") CHARSET = list("0123456789") + \ [chr(x + ord("A")) for x in range(0, 26)] + list("?+-") @@ -227,22 +227,11 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio, "6. Click OK to upload image to device.\n") return rp - @classmethod - def _get_querymodel(cls): - if isinstance(cls._querymodel, str): - while True: - yield cls._querymodel - else: - i = 0 - while True: - yield cls._querymodel[i % len(cls._querymodel)] - i += 1 - def _identify(self): """Do the original Wouxun identification dance""" - query = self._get_querymodel() for _i in range(0, 10): - self.pipe.write(next(query)) + model = self._querymodels[_i % len(self._querymodels)] + self.pipe.write(model) resp = self.pipe.read(9) if len(resp) != 9: LOG.debug("Got:\n%s" % util.hexprint(resp)) @@ -341,6 +330,64 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio, rf.can_odd_split = True return rf + @property + def transmit_time_out_setting(self): + options = ["%s" % x for x in range(15, 615, 15)] + rs = RadioSetting( + "transmit_time_out", + "TX Time-out Timer", + RadioSettingValueList( + options, + current_index=self._memobj.settings.transmit_time_out)) + return rs + + @property + def transmit_time_out_alert_setting(self): + options = ["OFF"] + ["%s" % x for x in range(1, 11)] + rs = RadioSetting( + "tx_time_out_alert", + "TX Time-out Alert", + RadioSettingValueList( + options, + current_index=self._memobj.settings.tx_time_out_alert)) + return rs + + @property + def roger_beep_setting(self): + options = ["Off", "Begin", "End", "Both"] + rs = RadioSetting( + "roger_beep", + "Roger beep select", + RadioSettingValueList( + options, + current_index=self._memobj.settings.roger_beep)) + return rs + + @property + def power_save_setting(self): + rs = RadioSetting("power_save", "Power save", + RadioSettingValueBoolean( + self._memobj.settings.power_save)) + return rs + + @property + def vox_setting(self): + options = ["OFF"] + ["%s" % x for x in range(1, 11)] + rs = RadioSetting( + "vox", + "Vox", + RadioSettingValueList( + options, + current_index=self._memobj.settings.vox)) + return rs + + @property + def beep_setting(self): + rs = RadioSetting("beep", "Beep", + RadioSettingValueBoolean( + self._memobj.settings.beep)) + return rs + def get_settings(self): freq_ranges = RadioSettingGroup("freq_ranges", "Freq Ranges") fm_preset = RadioSettingGroup("fm_preset", "FM Presets") @@ -469,10 +516,7 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio, RadioSettingValueInteger( 0, 199, self._memobj.settings.priority_chan)) cfg_s.append(rs) - rs = RadioSetting("power_save", "Power save", - RadioSettingValueBoolean( - self._memobj.settings.power_save)) - cfg_s.append(rs) + cfg_s.append(self.power_save_setting) options = ["Off", "Scan", "Lamp", "SOS", "Radio"] rs = RadioSetting( "pf1_function", "PF1 Function select", @@ -480,34 +524,15 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio, options, current_index=self._memobj.settings.pf1_function)) cfg_s.append(rs) - options = ["Off", "Begin", "End", "Both"] - rs = RadioSetting("roger_beep", "Roger beep select", - RadioSettingValueList( - options, - current_index=self._memobj.settings.roger_beep)) - cfg_s.append(rs) - options = ["%s" % x for x in range(15, 615, 15)] - transmit_time_out = options[self._memobj.settings.transmit_time_out] - rs = RadioSetting("transmit_time_out", "TX Time-out Timer", - RadioSettingValueList( - options, transmit_time_out)) - cfg_s.append(rs) - rs = RadioSetting("tx_time_out_alert", "TX Time-out Alert", - RadioSettingValueInteger( - 0, 10, self._memobj.settings.tx_time_out_alert)) - cfg_s.append(rs) - rs = RadioSetting("vox", "Vox", - RadioSettingValueInteger( - 0, 10, self._memobj.settings.vox)) - cfg_s.append(rs) + cfg_s.append(self.roger_beep_setting) + cfg_s.append(self.transmit_time_out_setting) + cfg_s.append(self.transmit_time_out_alert_setting) + cfg_s.append(self.vox_setting) options = ["Off", "Chinese", "English"] rs = RadioSetting("voice", "Voice", RadioSettingValueList( options, current_index=self._memobj.settings.voice)) cfg_s.append(rs) - rs = RadioSetting("beep", "Beep", - RadioSettingValueBoolean( - self._memobj.settings.beep)) - cfg_s.append(rs) + cfg_s.append(self.beep_setting) rs = RadioSetting("ani_id_enable", "ANI id enable", RadioSettingValueBoolean( self._memobj.settings.ani_id_enable)) @@ -747,17 +772,7 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio, def _is_txinh(self, _mem): return _mem.tx_freq.get_raw() == b"\xFF\xFF\xFF\xFF" - def get_memory(self, number): - _mem = self._memobj.memory[number - 1] - _nam = self._memobj.names[number - 1] - - mem = chirp_common.Memory() - mem.number = number - - if _mem.get_raw() == (b"\xff" * 16): - mem.empty = True - return mem - + def _set_duplex_offset_freq(self, _mem, mem): mem.freq = int(_mem.rx_freq) * 10 if _mem.splitdup: mem.duplex = "split" @@ -775,6 +790,19 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio, else: mem.offset = abs(int(_mem.tx_freq) - int(_mem.rx_freq)) * 10 + def get_memory(self, number): + _mem = self._memobj.memory[number - 1] + _nam = self._memobj.names[number - 1] + + mem = chirp_common.Memory() + mem.number = number + + if _mem.get_raw() == (b"\xff" * 16): + mem.empty = True + return mem + + self._set_duplex_offset_freq(_mem, mem) + if not _mem.skip: mem.skip = "S" if not _mem.iswide: @@ -842,6 +870,9 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio, 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" + def set_memory(self, mem): _mem = self._memobj.memory[mem.number - 1] _nam = self._memobj.names[mem.number - 1] @@ -864,7 +895,8 @@ class KGUVD1PRadio(chirp_common.CloneModeRadio, _mem.tx_freq = int(mem.freq / 10) - int(mem.offset / 10) else: _mem.tx_freq = int(mem.freq / 10) - _mem.splitdup = mem.duplex == "split" + + self._set_split_duplex(_mem, mem) _mem.skip = mem.skip != "S" _mem.iswide = mem.mode != "NFM" @@ -909,7 +941,7 @@ class KGUV6DRadio(KGUVD1PRadio): """Wouxun KG-UV6 (D and X variants)""" MODEL = "KG-UV6" - _querymodel = (b"HiWXUVD1\x02", b"HiKGUVD1\x02") + _querymodels = (b"HiWXUVD1\x02", b"HiKGUVD1\x02") _MEM_FORMAT = """ #seekto 0x0010; @@ -1436,7 +1468,7 @@ class KG816Radio(KGUVD1PRadio, chirp_common.ExperimentalRadio): """Wouxun KG-816""" MODEL = "KG-816" - _querymodel = b"HiWOUXUN\x02" + _querymodels = (b"HiWOUXUN\x02", ) _MEM_FORMAT = """ #seekto 0x0010; @@ -1566,3 +1598,118 @@ class KG818Radio(KG816Radio): @classmethod def match_model(cls, filedata, filename): return False + + +@directory.register +class KG805GRadio(KGUVD1PRadio): + """Wouxun KG-805G""" + MODEL = "KG-805G" + + _querymodels = (b"HiWOUXUN\x02", ) + valid_freq = [(400000000, 470987500)] + + _MEM_FORMAT = """ + #seekto 0x0010; + struct { + lbcd rx_freq[4]; + lbcd tx_freq[4]; + ul16 rx_tone; + ul16 tx_tone; + u8 _3_unknown_1:4, + bcl:1, + _3_unknown_2:3; + u8 _2_unknown_1:1, + skip:1, + power_high:1, + iswide:1, + _2_unknown_2:4; + u8 unknown; + u8 _0_unknown_1:3, + iswidex:1, + _0_unknown_2:4; + } memory[128]; + + #seekto 0x0E20; + struct { + u8 unknown_setting_01[2]; + u8 unknown_setting_02:4, + squelch:4; + u8 unknown_setting_03:7, + power_save:1; + u8 unknown_setting_04; + u8 unknown_setting_05:6, + roger_beep:2; + u8 unknown_setting_06:2, + transmit_time_out:6; + u8 unknown_setting_07:4, + vox:4; + u8 unknown_setting_08[5]; + u8 unknown_setting_09:7, + beep:1; + u8 unknown_setting_10[8]; + u8 unknown_setting_11:4, + tx_time_out_alert:4; + u8 unknown_setting_12[9]; + u8 unknown_setting_13; + u8 unknown_setting_14:7, + auto_lock:1; + } settings; + + + #seekto 0x1010; + struct { + u8 name[6]; + u8 pad[10]; + } names[128]; + """ + + def process_mmap(self): + self._memobj = bitwise.parse(self._MEM_FORMAT, self._mmap) + # This sets our frequency ranges, so run it once after we process the + # mmap to make sure they're set for later + self.get_settings() + + def get_settings(self): + cfg_s = RadioSettingGroup("cfg_settings", "Configuration Settings") + group = RadioSettings(cfg_s) + + cfg_s.append(self.power_save_setting) + + options = ["%s" % x for x in range(0, 10)] + rs = RadioSetting( + "squelch", + "Squelch", + RadioSettingValueList( + options, + current_index=self._memobj.settings.squelch)) + cfg_s.append(rs) + + cfg_s.append(self.roger_beep_setting) + cfg_s.append(self.transmit_time_out_setting) + cfg_s.append(self.transmit_time_out_alert_setting) + cfg_s.append(self.vox_setting) + cfg_s.append(self.beep_setting) + + rs = RadioSetting("auto_lock", "Auto lock", + RadioSettingValueBoolean( + self._memobj.settings.auto_lock)) + cfg_s.append(rs) + + return group + + def _set_duplex_offset_freq(self, _mem, mem): + if self._is_txinh(_mem): + # TX freq not set + mem.duplex = "off" + mem.offset = 0 + mem.freq = int(_mem.rx_freq) * 10 + else: + chirp_common.split_to_offset( + mem, int(_mem.rx_freq) * 10, int(_mem.tx_freq) * 10) + + def _set_split_duplex(self, _mem, mem): + pass + + @classmethod + def match_model(cls, filedata, filename): + return False diff --git a/chirp/drivers/yaesu_clone.py b/chirp/drivers/yaesu_clone.py index b719a14..83d8c8b 100644 --- a/chirp/drivers/yaesu_clone.py +++ b/chirp/drivers/yaesu_clone.py @@ -29,15 +29,12 @@ def _safe_read(pipe, count): first = True for _i in range(0, 60): buf += pipe.read(count - len(buf)) - # LOG.debug("safe_read: %i/%i\n" % (len(buf), count)) if buf: if first and buf[0] == CMD_ACK: - # LOG.debug("Chewed an ack") buf = buf[1:] # Chew an echo'd ack if using a 2-pin cable first = False if len(buf) == count: break - LOG.debug(util.hexprint(buf)) return buf @@ -55,7 +52,6 @@ def _chunk_read(pipe, count, status_fn): data += chunk if data[0] == CMD_ACK: data = data[1:] # Chew an echo'd ack if using a 2-pin cable - # LOG.debug("Chewed an ack") if time.time() - timer > 2: # It's been two seconds since we last saw data from the radio, # so it's time to give up. @@ -118,7 +114,6 @@ def _chunk_write(pipe, data, status_fn, block): chunk = data[i:i+block] pipe.write(chunk) count += len(chunk) - LOG.debug("@_chunk_write, count: %i, blocksize: %i" % (count, block)) time.sleep(delay) status = chirp_common.Status() @@ -148,14 +143,12 @@ def __clone_out(radio): for block in radio._block_lengths: blocks += 1 if blocks != len(radio._block_lengths): + LOG.debug("Sending %i-%i" % (pos, pos+block)) pipe.write(mmap[pos:pos+block]) - echo = pipe.read(block) - if len(echo) != block: - LOG.error('Expected %i bytes of echo, got %i', block, - len(echo)) buf = pipe.read(1) - if not buf or buf[0] != CMD_ACK: - LOG.error('Expected ack but got %r', buf) + if buf and buf[0] != CMD_ACK: + buf = pipe.read(block) + if not buf or buf[-1] != CMD_ACK: raise Exception("Radio did not ack block %i" % blocks) else: _chunk_write(pipe, mmap[pos:], diff --git a/chirp/errors.py b/chirp/errors.py index 0d9d85b..a2dc82f 100644 --- a/chirp/errors.py +++ b/chirp/errors.py @@ -18,6 +18,7 @@ import enum class Reasons(enum.Enum): NO_CONNECTION_K1 = "No response from radio. Check connector and cabling!" + FIXED_BANKS = "This radio has fixed banks and does not allow reassignment" class InvalidDataError(Exception): @@ -73,3 +74,8 @@ class SpecificRadioError(RadioError): class RadioNoContactLikelyK1(SpecificRadioError): """A radio that uses a K1 connector likely to have fitment issues.""" CODE = Reasons.NO_CONNECTION_K1 + + +class RadioFixedBanks(SpecificRadioError): + """A radio that has fixed banks and cannot be changed.""" + CODE = Reasons.FIXED_BANKS diff --git a/chirp/import_logic.py b/chirp/import_logic.py index 51704c5..6455690 100644 --- a/chirp/import_logic.py +++ b/chirp/import_logic.py @@ -71,7 +71,7 @@ def ensure_has_calls(radio, memory): def _import_freq(dst_radio, _srcrf, mem): dst_bands = dst_radio.get_features().valid_bands - if not any(lo < mem.freq <= hi for (lo, hi) in dst_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))) diff --git a/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo b/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo index 3369823..36570a8 100644 Binary files a/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo and b/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo differ diff --git a/chirp/locale/es/LC_MESSAGES/CHIRP.mo b/chirp/locale/es/LC_MESSAGES/CHIRP.mo index 379edd6..85c8a4e 100644 Binary files a/chirp/locale/es/LC_MESSAGES/CHIRP.mo and b/chirp/locale/es/LC_MESSAGES/CHIRP.mo differ diff --git a/chirp/locale/fr/LC_MESSAGES/CHIRP.mo b/chirp/locale/fr/LC_MESSAGES/CHIRP.mo index 2887273..61f4a0a 100644 Binary files a/chirp/locale/fr/LC_MESSAGES/CHIRP.mo and b/chirp/locale/fr/LC_MESSAGES/CHIRP.mo differ diff --git a/chirp/locale/it/LC_MESSAGES/CHIRP.mo b/chirp/locale/it/LC_MESSAGES/CHIRP.mo index 348cc55..20f6fa2 100644 Binary files a/chirp/locale/it/LC_MESSAGES/CHIRP.mo and b/chirp/locale/it/LC_MESSAGES/CHIRP.mo differ diff --git a/chirp/locale/pl/LC_MESSAGES/CHIRP.mo b/chirp/locale/pl/LC_MESSAGES/CHIRP.mo index 875d63f..1f23eca 100644 Binary files a/chirp/locale/pl/LC_MESSAGES/CHIRP.mo and b/chirp/locale/pl/LC_MESSAGES/CHIRP.mo differ diff --git a/chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mo b/chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mo new file mode 100644 index 0000000..57288bf Binary files /dev/null and b/chirp/locale/ro_RO/LC_MESSAGES/CHIRP.mo differ diff --git a/chirp/locale/ru/LC_MESSAGES/CHIRP.mo b/chirp/locale/ru/LC_MESSAGES/CHIRP.mo index 68a56c0..d978c35 100644 Binary files a/chirp/locale/ru/LC_MESSAGES/CHIRP.mo and b/chirp/locale/ru/LC_MESSAGES/CHIRP.mo differ diff --git a/chirp/settings.py b/chirp/settings.py index f400333..0b25dfb 100644 --- a/chirp/settings.py +++ b/chirp/settings.py @@ -310,12 +310,13 @@ class RadioSettingValueString(RadioSettingValue): def set_value(self, value): if len(value) < self._minlength or len(value) > self._maxlength: - raise InvalidValueError("Value must be between %i and %i chars" % - (self._minlength, self._maxlength)) + raise InvalidValueError( + "Value %r must be between %i and %i chars" % ( + value, self._minlength, self._maxlength)) for char in value: if char not in self._charset: - raise InvalidValueError("Value contains invalid " + - "character `%s'" % char) + raise InvalidValueError(("Value %r contains invalid " + "character `%s'") % (value, char)) if self._autopad: value = value.ljust(self._maxlength) RadioSettingValue.set_value(self, value) diff --git a/chirp/share/welcome_screen_ro_RO.png b/chirp/share/welcome_screen_ro_RO.png new file mode 100644 index 0000000..c953a9c Binary files /dev/null and b/chirp/share/welcome_screen_ro_RO.png differ diff --git a/chirp/sources/repeaterbook.py b/chirp/sources/repeaterbook.py index 879388a..0260cb2 100644 --- a/chirp/sources/repeaterbook.py +++ b/chirp/sources/repeaterbook.py @@ -184,8 +184,11 @@ class RepeaterBook(base.NetworkResultRadio): LOG.debug('Loading %i cached entries from %s for proximity search', d['count'], os.path.basename(fn)) - def item_to_memory(self, item): - if item.get('D-Star') == 'Yes': + def item_to_memory(self, item, fmconv): + should_dstar = ( + item.get('D-Star') == 'Yes' and not ( + item.get('FM Analog') == 'Yes' and fmconv)) + if should_dstar: m = chirp_common.DVMemory() m.dv_urcall = 'CQCQCQ'.ljust(8) m.dv_rpt1call = item.get('Callsign')[:8].ljust(8) @@ -304,7 +307,7 @@ class RepeaterBook(base.NetworkResultRadio): if not included_band(item): continue try: - m = self.item_to_memory(item) + m = self.item_to_memory(item, fmconv) except Exception as e: LOG.warning('Unable to convert repeater %s: %s', item['Rptr ID'], e) diff --git a/chirp/stock_configs/US MURS Channels.csv b/chirp/stock_configs/US MURS Channels.csv index e6fed17..9830fb8 100644 --- a/chirp/stock_configs/US MURS Channels.csv +++ b/chirp/stock_configs/US MURS Channels.csv @@ -1,6 +1,6 @@ -Location,Name,Frequency,Duplex,Offset,Tone,rToneFreq,cToneFreq,DtcsCode,DtcsPolarity,Mode,TStep,Skip,Comment,URCALL,RPT1CALL,RPT2CALL -1,MURS 1,151.820000,,0.000000,,88.5,88.5,023,NN,NFM,5.00,,,,, -2,MURS 2,151.880000,,0.000000,,88.5,88.5,023,NN,NFM,5.00,,,,, -3,MURS 3,151.940000,,0.000000,,88.5,88.5,023,NN,NFM,5.00,,,,, -4,Blue Dot,154.570000,,0.000000,,88.5,88.5,023,NN,FM,5.00,,,,, -5,Green Dot,154.600000,,0.000000,,88.5,88.5,023,NN,FM,5.00,,,,, +Location,Name,Frequency,Duplex,Offset,Tone,rToneFreq,cToneFreq,DtcsCode,DtcsPolarity,RxDtcsCode,CrossMode,Mode,TStep,Skip,Power,Comment,URCALL,RPT1CALL,RPT2CALL,DVCODE +1,MURS 1,151.820000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,NFM,5.00,,2.0W,,,,, +2,MURS 2,151.880000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,NFM,5.00,,2.0W,,,,, +3,MURS 3,151.940000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,NFM,5.00,,2.0W,,,,, +4,Blue Dot,154.570000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,2.0W,,,,, +5,Green Dot,154.600000,,0.000000,,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,2.0W,,,,, diff --git a/chirp/util.py b/chirp/util.py index 3ea5505..f07fa13 100644 --- a/chirp/util.py +++ b/chirp/util.py @@ -37,12 +37,11 @@ def int_to_byte(i): return i -def hexprint(data, addrfmt=None): +def hexprint(data, addrfmt=None, block_size=8): """Return a hexdump-like encoding of @data""" if addrfmt is None: addrfmt = '%(addr)03i' - block_size = 8 out = "" blocks = len(data) // block_size diff --git a/chirp/wxui/bugreport.py b/chirp/wxui/bugreport.py index 16e9fa3..50b449e 100644 --- a/chirp/wxui/bugreport.py +++ b/chirp/wxui/bugreport.py @@ -14,6 +14,7 @@ # along with this program. If not, see . import datetime +import gzip import logging import os import platform @@ -32,6 +33,7 @@ from chirp import logger from chirp import platform as chirp_platform from chirp.wxui import common from chirp.wxui import config +from chirp.wxui import serialtrace _ = wx.GetTranslation CONF = config.get() @@ -126,6 +128,15 @@ def prepare_report(chirpmain): manifest['files']['debug_log.txt'] = f.read() tmpf = tempfile.mktemp('.config', 'chirp') + # Grab any trace files + for tracefile in serialtrace.TRACEFILES: + if os.path.exists(tracefile): + LOG.debug('Capturing serial trace file %s', tracefile) + with open(tracefile, 'rb') as f: + manifest['files'][os.path.basename(tracefile)] = f.read() + else: + LOG.debug('Serial trace file %s does not exist', tracefile) + return manifest @@ -137,6 +148,7 @@ class BugReportContext: self.session = requests.Session() self.session.headers = { 'User-Agent': 'CHIRP/%s' % CHIRP_VERSION, + 'Referer': 'https://chirpmyradio.com/projects/chirp/issues/new', } def get_page(self, name, cls): @@ -622,7 +634,7 @@ class ResultPage(BugReportPage): elif r.status_code != 201: LOG.error('Failed to upload %s: %s %s', fn, r.status_code, r.reason) - raise Exception('Failed to upload file') + raise Exception('Failed to upload file: %s' % r.reason) return r.json()['upload']['token'] raise Exception('Failed to upload %s after multiple attempts', fn) @@ -630,19 +642,36 @@ class ResultPage(BugReportPage): if 'issue' not in manifest: self._create_bug(manifest) + for fn in list(manifest['files'].keys()): + fdata = manifest['files'][fn] + if len(fdata) > 1024 * 1024: + LOG.warning('File %s is larger than 1MB, compressing', fn) + fdata = gzip.compress(fdata) + manifest['files'].pop(fn) + fn += '.gz' + manifest['files'][fn] = fdata + + notes = '[Uploaded from CHIRP %s]\n\n' % CHIRP_VERSION tokens = [] for fn in manifest['files']: - token = self._upload_file(manifest, fn) - if fn.lower().endswith('.img'): - ct = 'application/octet-stream' - else: + try: + token = self._upload_file(manifest, fn) + except Exception as e: + LOG.error('Failed to upload file %s: %s', fn, e) + notes += '[Failed to upload file %s: %s]\n\n' % (fn, e) + continue + ext = os.path.splitext(fn)[1].lower() + if ext in ('.log', '.txt'): ct = 'text/plain' - tokens.append({'token': token, - 'filename': fn, - 'content_type': ct}) + else: + ct = 'application/octet-stream' + token_info = {'token': token, + 'filename': fn, + 'content_type': ct} + tokens.append(token_info) + LOG.debug('File tokens: %s', tokens) - notes = '[Uploaded from CHIRP %s]\n\n' % CHIRP_VERSION if not self.context.is_new: notes += manifest['desc'] r = self.context.session.put( diff --git a/chirp/wxui/clone.py b/chirp/wxui/clone.py index 21af53e..21bc7fc 100644 --- a/chirp/wxui/clone.py +++ b/chirp/wxui/clone.py @@ -33,6 +33,7 @@ from chirp import errors from chirp.wxui import config from chirp.wxui import common from chirp.wxui import developer +from chirp.wxui import serialtrace _ = wx.GetTranslation LOG = logging.getLogger(__name__) @@ -163,8 +164,9 @@ def open_serial(port, rclass): pipe.open() pipe.baudrate = rclass.BAUD_RATE else: - pipe = serial.Serial(baudrate=rclass.BAUD_RATE, - rtscts=rclass.HARDWARE_FLOW, timeout=0.25) + pipe = serialtrace.SerialTrace( + baudrate=rclass.BAUD_RATE, + rtscts=rclass.HARDWARE_FLOW, timeout=0.25) pipe.rts = rclass.WANTS_RTS pipe.dtr = rclass.WANTS_DTR pipe.port = port @@ -178,6 +180,7 @@ def open_serial(port, rclass): class ChirpRadioPromptDialog(wx.Dialog): def __init__(self, *a, **k): self.radio = k.pop('radio') + self.rconfig = config.get_for_radio(self.radio) self.prompt = k.pop('prompt') buttons = k.pop('buttons', wx.OK | wx.CANCEL) super().__init__(*a, **k) @@ -208,12 +211,19 @@ class ChirpRadioPromptDialog(wx.Dialog): self.Centre() def persist_flag(self, radio, flag): - key = '%s_%s' % (flag, directory.radio_class_id(radio)) - CONF.set_bool(key.lower(), not self.cb.IsChecked(), 'clone_prompts') + key = 'prompt_%s' % flag.lower() + self.rconfig.set_bool(key, not self.cb.IsChecked()) + oldkey = '%s_%s' % (flag, directory.radio_class_id(radio)) + if CONF.is_defined(oldkey, 'clone_prompts'): + CONF.remove_option(oldkey, 'clone_prompts') def check_flag(self, radio, flag): - key = '%s_%s' % (flag, directory.radio_class_id(radio)) - return CONF.get_bool(key.lower(), 'clone_prompts', True) + key = 'prompt_%s' % flag.lower() + if not self.rconfig.is_defined(key): + # FIXME: Remove this compatibility at some point + oldkey = '%s_%s' % (flag, directory.radio_class_id(radio)) + return CONF.get_bool(oldkey.lower(), 'clone_prompts', True) + return self.rconfig.get_bool(key, default=True) def ShowModal(self): if not self.message: @@ -224,7 +234,7 @@ class ChirpRadioPromptDialog(wx.Dialog): return wx.ID_OK LOG.debug('Showing %s prompt' % self.prompt) status = super().ShowModal() - if status == wx.ID_OK: + if status in (wx.ID_OK, wx.ID_YES): LOG.debug('Setting flag for prompt %s' % self.prompt) self.persist_flag(self.radio, self.prompt) else: @@ -534,10 +544,19 @@ class ChirpCloneDialog(wx.Dialog): self._model.Disable() self._recent.Disable() + def enable_model_select(self): + self._vendor.Enable() + self._model.Enable() + self._recent.Enable() + def disable_running(self): self._port.Disable() self.FindWindowById(wx.ID_OK).Disable() + def enable_running(self): + self._port.Enable() + self.FindWindowById(wx.ID_OK).Enable() + def _persist_choices(self): raise NotImplementedError() @@ -639,20 +658,23 @@ class ChirpCloneDialog(wx.Dialog): def _select_port_for_model(self): vendor = self._vendor.GetStringSelection() model = self._model.GetStringSelection() - modelstr = '%s:%s' % (vendor, model) - last_port = CONF.get(modelstr, 'port_recall') + + rclass = self.get_selected_rclass() + rconfig = config.get_for_radio(rclass) + last_port = rconfig.get('last_port') if last_port and self.set_selected_port(last_port): - LOG.debug('Automatically chose port %s as it is last-used for %s', - last_port, modelstr) + LOG.debug('Automatically chose last-used port %s for %s %s', + last_port, vendor, model) else: - LOG.debug('No recent/available port for %s', modelstr) + LOG.debug('No recent/available port for %s %s', vendor, model) def _remember_port_for_selected(self): - modelstr = '%s:%s' % (self._vendor.GetStringSelection(), - self._model.GetStringSelection()) + rclass = self.get_selected_rclass() + rconfig = config.get_for_radio(rclass) port = self.get_selected_port() - CONF.set(modelstr, port, 'port_recall') - LOG.debug('Recorded last-used port %s for %s', port, modelstr) + rconfig.set('last_port', port) + LOG.debug('Recorded last-used port %s for %s %s', + port, rclass.VENDOR, rclass.MODEL) def _status(self, status): def _safe_status(): @@ -667,34 +689,18 @@ class ChirpCloneDialog(wx.Dialog): wx.CallAfter(self.EndModal, wx.ID_OK) def fail(self, error): - if isinstance(error, errors.SpecificRadioError): - link = error.get_link() - message = str(error) - else: - link = None - message = str(error) - def safe_fail(): - if link: - buttons = wx.YES_NO | wx.NO_DEFAULT - else: - buttons = wx.OK - d = wx.MessageDialog(self, message, - _('Error communicating with radio'), - wx.ICON_ERROR | buttons) - if link: - d.SetYesNoLabels(_('More Info'), wx.ID_OK) - r = d.ShowModal() - if r == wx.ID_YES: - webbrowser.open(link) - - self.cancel_action() + common.error_proof.show_error( + error, parent=self, + title=_('Error communicating with radio')) + if isinstance(self, ChirpDownloadDialog): + self.enable_model_select() + self.enable_running() wx.CallAfter(safe_fail) def cancel_action(self): if isinstance(self, ChirpDownloadDialog): - self._vendor.Enable() - self._model.Enable() + self.enable_model_select() self._port.Enable() s = chirp_common.Status() s.cur = 0 @@ -729,6 +735,8 @@ class ChirpDownloadDialog(ChirpCloneDialog): if (CONF.get_bool('always_start_recent', 'state') and CONF.get('recent_models', 'state')): self._do_recent() + # Clean up old-style port recall + CONF.remove_section('port_recall') def _selected_model(self, event): super(ChirpDownloadDialog, self)._selected_model(event) diff --git a/chirp/wxui/common.py b/chirp/wxui/common.py index 8c94221..a66d0de 100644 --- a/chirp/wxui/common.py +++ b/chirp/wxui/common.py @@ -23,6 +23,7 @@ import platform import shutil import tempfile import threading +import webbrowser import wx @@ -163,10 +164,15 @@ class EditorMenuItem(wx.MenuItem): self.SetAccel(accel) -class EditorMenuItemToggle(EditorMenuItem): +class EditorMenuItemToggleStateless(EditorMenuItem): + def __init__(self, cls, callback_name, *a, **k): + k['kind'] = wx.ITEM_CHECK + super().__init__(cls, callback_name, *a, **k) + + +class EditorMenuItemToggle(EditorMenuItemToggleStateless): """An EditorMenuItem that manages boolean/check state in CONF""" def __init__(self, cls, callback_name, conf_tuple, *a, **k): - k['kind'] = wx.ITEM_CHECK super().__init__(cls, callback_name, *a, **k) self._conf_key, self._conf_section = conf_tuple @@ -608,54 +614,44 @@ class ChirpSettingGrid(wx.Panel): prop.SetModifiedStatus(False) -def _error_proof(*expected_errors): - """Decorate a method and display an error if it raises. - - If the method raises something in expected_errors, then - log an error, otherwise log exception. - """ - - def show_error(msg): - d = wx.MessageDialog(None, str(msg), _('An error has occurred'), - style=wx.OK | wx.ICON_ERROR) - d.ShowModal() - - def wrap(fn): - @functools.wraps(fn) - def inner(*args, **kwargs): - try: - return fn(*args, **kwargs) - except expected_errors as e: - LOG.error('%s: %s' % (fn, e)) - show_error(e) - except Exception as e: - LOG.exception('%s raised unexpected exception' % fn) - show_error(e) - - return inner - return wrap - - class error_proof(object): - def __init__(self, *expected_exceptions): + def __init__(self, *expected_exceptions, title=None): self._expected = expected_exceptions self.fn = None + self.title = title @staticmethod - def show_error(msg): - d = wx.MessageDialog(None, str(msg), _('An error has occurred'), - style=wx.OK | wx.ICON_ERROR) - d.ShowModal() + def show_error(error, parent=None, title=None): + title = title or _('An error has occurred') + + if isinstance(error, errors.SpecificRadioError): + link = error.get_link() + message = str(error) + else: + link = None + message = str(error) + + if link: + buttons = wx.YES_NO | wx.NO_DEFAULT + else: + buttons = wx.OK + d = wx.MessageDialog(parent, message, title, + wx.ICON_ERROR | buttons) + if link: + d.SetYesNoLabels(_('More Info'), wx.ID_OK) + r = d.ShowModal() + if r == wx.ID_YES: + webbrowser.open(link) def run_safe(self, fn, args, kwargs): try: return fn(*args, **kwargs) except self._expected as e: LOG.error('%s: %s' % (fn, e)) - self.show_error(e) + self.show_error(e, title=self.title) except Exception as e: LOG.exception('%s raised unexpected exception' % fn) - self.show_error(e) + self.show_error(e, title=self.title) def __call__(self, fn): self.fn = fn @@ -764,20 +760,57 @@ class MultiErrorDialog(wx.Dialog): @contextlib.contextmanager -def expose_logs(level, root, label, maxlen=128, parent=None): +def expose_logs(level, root, label, maxlen=128, parent=None, + show_on_raise=True): if not isinstance(root, tuple): root = (root,) + error = None + mgrs = (logger.log_history(level, x) for x in root) with contextlib.ExitStack() as stack: histories = [stack.enter_context(m) for m in mgrs] try: yield + except Exception as e: + LOG.warning('Failure while capturing logs (showing=%s): %s', + show_on_raise, e) + error = e finally: lines = list(itertools.chain.from_iterable(x.get_history() for x in histories)) - if lines: + if lines and (show_on_raise or not error): + LOG.warning('Showing %i lines of logs', len(lines)) d = MultiErrorDialog(parent) d.SetTitle(label) d.set_errors(lines) d.ShowModal() + else: + LOG.warning('Not showing %i lines of logs (error=%s,show=%s)', + len(lines), bool(error), show_on_raise) + if error: + raise error + + +def mems_from_clipboard(string, maxlen=128, parent=None): + label = _('Paste external memories') + radio = generic_csv.TSVRadio(None) + radio.clear() + # Try to load the whole thing as a full TSV with header row + try: + with expose_logs(logging.WARNING, 'chirp.drivers', label, + parent=parent, show_on_raise=False): + radio.load_from(string) + return [x for x in radio.get_memories() if not x.empty] + except errors.InvalidDataError: + LOG.debug('No header information found in TSV paste') + except RuntimeError: + pass + + # If we got no memories, try prefixing the default header row and repeat + header = generic_csv.TSVRadio.SEPCHAR.join(chirp_common.Memory.CSV_FORMAT) + string = os.linesep.join([header, string]) + with expose_logs(logging.WARNING, 'chirp.drivers', label, parent=parent): + radio.load_from(string) + + return [x for x in radio.get_memories() if not x.empty] diff --git a/chirp/wxui/config.py b/chirp/wxui/config.py index 0da3a12..73948ab 100644 --- a/chirp/wxui/config.py +++ b/chirp/wxui/config.py @@ -17,6 +17,7 @@ import base64 import binascii import logging +from chirp import directory from chirp import platform from configparser import ConfigParser import os @@ -71,12 +72,19 @@ class ChirpConfig: if not self.__config.items(section): self.__config.remove_section(section) + def remove_section(self, section): + return self.__config.remove_section(section) + class ChirpConfigProxy: def __init__(self, config, section="global"): self._config = config self._section = section + @property + def section(self): + return self._section + def get(self, key, section=None, raw=False): return self._config.get(key, section or self._section, raw=raw) @@ -161,8 +169,11 @@ class ChirpConfigProxy: def is_defined(self, key, section=None): return self._config.is_defined(key, section or self._section) - def remove_option(self, key, section): - self._config.remove_option(section, key) + def remove_option(self, key, section=None): + self._config.remove_option(section or self._section, key) + + def remove_section(self, section=None): + return self._config.remove_section(section or self._section) _CONFIG = None @@ -177,3 +188,22 @@ def get(section="global"): _CONFIG = ChirpConfig(p.config_dir()) return ChirpConfigProxy(_CONFIG, section) + + +def get_for_radio(radio): + if isinstance(radio, type): + rclass = radio + else: + rclass = radio.__class__ + try: + registered_id = directory.registered_class(rclass) + except KeyError: + # Network sources and any other special cases where a radio is not + # registered. Try to get a driver id if possible, otherwise combine + # into a single config blob + try: + registered_id = directory.radio_class_id(rclass) + except Exception: + LOG.warning('Unable to get radio-specific config for %s', rclass) + registered_id = 'other' + return get(section='radio_%s' % registered_id) diff --git a/chirp/wxui/developer.py b/chirp/wxui/developer.py index f9aa1b3..3d616f3 100644 --- a/chirp/wxui/developer.py +++ b/chirp/wxui/developer.py @@ -396,9 +396,6 @@ class ChirpBrowserPanel(wx.lib.scrolledpanel.ScrolledPanel): editor = ChirpStringEditor(self, obj) elif isinstance(obj[0], bitwise.bcdDataElement): editor = ChirpBCDEditor(self, obj) - elif (isinstance(obj[0], bitwise.intDataElement) and - not isinstance(obj[0], bitwise.bitDataElement)): - self._initialize(obj, labelfmt='%s[%%s]' % name) else: self._parent.add_sub_panel(name, obj, self) editor = ChirpEditor(self, obj) @@ -593,21 +590,35 @@ class FakeErrorOpenSerial(FakeSerial): raise Exception('Failed open') +class IsssueModuleLoadError(Exception): + pass + + class IssueModuleLoader: def __init__(self, parent): self._parent = parent report.ensure_session() self.session = report.SESSION - def get_attachments_from_issue(self, issue): + def get_attachments_from_issue(self, issue_num): r = self.session.get( - 'https://chirpmyradio.com/issues/%i.json' % issue, + 'https://chirpmyradio.com/issues/%i.json' % issue_num, params={'include': 'attachments'}) LOG.debug('Fetched attachments for issue %i (status %s)' % ( - issue, r.status_code)) + issue_num, r.status_code)) r.raise_for_status() - data = r.json()['issue']['attachments'] - return [a for a in data if + issue = r.json()['issue'] + allowed_states = ['New', 'In Progress', 'Resolved'] + valid = (issue['status']['name'] in allowed_states + and not issue['status']['is_closed']) + if not valid: + LOG.warning('Issue %i is in state %s', issue_num, issue['status']) + raise IsssueModuleLoadError( + _('Issue %i is not in a valid state to load ' + 'modules. It is highly recommended that you not ' + 'attempt to manually load modules from this ' + 'issue as it is likely to cause problems.') % issue_num) + return [a for a in issue['attachments'] if a['filename'].endswith('.py') and a.get('content_type', '').startswith('text/') and a['filesize'] < (256 * 1024)] @@ -666,6 +677,10 @@ class IssueModuleLoader: try: attachments = self.get_attachments_from_issue(issue) + except IsssueModuleLoadError as e: + LOG.exception('Failed to load module from issue %i: %s' % ( + issue, e)) + raise except Exception as e: LOG.exception('Failed to load attachments from %i: %s' % ( issue, e)) diff --git a/chirp/wxui/main.py b/chirp/wxui/main.py index f0521a7..b7380d7 100644 --- a/chirp/wxui/main.py +++ b/chirp/wxui/main.py @@ -51,6 +51,7 @@ from chirp.wxui import query_sources from chirp.wxui import radioinfo from chirp.wxui import radiothread from chirp.wxui import report +from chirp.wxui import serialtrace from chirp.wxui import settingsedit from chirp import CHIRP_VERSION @@ -1016,6 +1017,12 @@ class ChirpMain(wx.Frame): help_menu.Append(self.bug_report_item) self.bug_report_item.Enable(False) + if developer.developer_mode(): + trace_item = wx.MenuItem(help_menu, wx.NewId(), + _('Open last serial trace')) + self.Bind(wx.EVT_MENU, self._menu_last_trace, trace_item) + help_menu.Append(trace_item) + menu_bar = wx.MenuBar() menu_bar.Append(file_menu, wx.GetStockLabel(wx.ID_FILE)) menu_bar.Append(edit_menu, wx.GetStockLabel(wx.ID_EDIT)) @@ -1322,6 +1329,9 @@ class ChirpMain(wx.Frame): 'state') config._CONFIG.save() + # Clean up any trace files we left + serialtrace.purge_trace_files(0) + ALL_MAIN_WINDOWS.remove(self) self.Destroy() @@ -1718,14 +1728,15 @@ class ChirpMain(wx.Frame): else: d = clone.ChirpUploadDialog(radio, self) - d.Centre() - r = d.ShowModal() - if r != wx.ID_OK: - LOG.info('Removing un-uploaded backup %s', fn) - try: - os.remove(fn) - except Exception: - pass + with d: + d.Centre() + r = d.ShowModal() + if r != wx.ID_OK: + LOG.info('Removing un-uploaded backup %s', fn) + try: + os.remove(fn) + except Exception: + pass @common.error_proof() def _menu_reload_driver(self, event, andfile=False): @@ -1798,14 +1809,27 @@ class ChirpMain(wx.Frame): def _menu_interact_driver(self, event): LOG.warning('Going to interact with radio at the console') + radio = self.current_editorset.current_editor.radio - import code locals = {'main': self, 'radio': radio} + if self.current_editorset.radio != radio: locals['parent_radio'] = self.current_editorset.radio - code.interact(banner='Locals are: %s' % (', '.join(locals.keys())), - local=locals) + + banner = 'Locals are: %s' % (', '.join(locals.keys())) + + # Use ipython if it's installed which gives tab complete and some other + # nice features over the built in REPL. + try: + from IPython.terminal.embed import InteractiveShellEmbed + + shell = InteractiveShellEmbed() + shell(header=banner, local_ns=locals) + + except ModuleNotFoundError: + import code + code.interact(banner=banner, local=locals) @common.error_proof() def load_module(self, filename): @@ -1853,7 +1877,7 @@ class ChirpMain(wx.Frame): 'another source is akin to giving them direct ' 'access to your computer and everything on ' 'it! Proceed despite this risk?'), - 'Warning', + _('Warning'), wx.ICON_WARNING | wx.YES_NO) if r.ShowModal() != wx.ID_YES: return @@ -1889,11 +1913,10 @@ class ChirpMain(wx.Frame): border=10, flag=wx.ALIGN_CENTER) - license_link = wx.adv.HyperlinkCtrl( - d, label=_('Click here for full license text'), - url=('https://www.chirpmyradio.com/projects/chirp/repository/' - 'github/revisions/master/entry/COPYING')) - vbox.Add(license_link, border=10, flag=wx.ALL | wx.ALIGN_CENTER) + documentation_link = wx.adv.HyperlinkCtrl( + d, label=_('Click here for online documentation'), + url=('https://chirpmyradio.com/projects/chirp/wiki/Documentation')) + vbox.Add(documentation_link, border=10, flag=wx.ALL | wx.ALIGN_CENTER) licheader = """ This program is free software: you can redistribute it and/or modify @@ -1911,6 +1934,12 @@ GNU General Public License for more details.""" style=wx.TE_WORDWRAP | wx.TE_MULTILINE | wx.TE_READONLY) vbox.Add(lic, border=10, flag=wx.ALL | wx.EXPAND, proportion=1) + license_link = wx.adv.HyperlinkCtrl( + d, label=_('Click here for full license text'), + url=('https://www.chirpmyradio.com/projects/chirp/repository/' + 'github/revisions/master/entry/COPYING')) + vbox.Add(license_link, border=10, flag=wx.ALL | wx.ALIGN_CENTER) + license_approved = CONF.get_bool('agreed_to_license', 'state') if not license_approved: @@ -2011,6 +2040,14 @@ GNU General Public License for more details.""" _('Success'), wx.ICON_INFORMATION) + def _menu_last_trace(self, event): + try: + fn = serialtrace.TRACEFILES[-1] + wx.LaunchDefaultApplication(fn) + except IndexError: + common.error_proof.show_error( + _('No traces stored'), parent=self) + def _menu_auto_edits(self, event): CONF.set_bool('auto_edits', event.IsChecked(), 'state') LOG.debug('Set auto_edits=%s' % event.IsChecked()) @@ -2034,6 +2071,7 @@ GNU General Public License for more details.""" for shortname, name in plans: CONF.set_bool(shortname, shortname == selected, 'bandplan') + @common.error_proof() def _do_network_query(self, query_cls): self.enable_bugreport() d = query_cls(self, title=_('Query %s') % query_cls.NAME) diff --git a/chirp/wxui/memedit.py b/chirp/wxui/memedit.py index 4e166e7..bb6aabd 100644 --- a/chirp/wxui/memedit.py +++ b/chirp/wxui/memedit.py @@ -42,15 +42,17 @@ _ = wx.GetTranslation LOG = logging.getLogger(__name__) CONF = config.get() WX_GTK = 'gtk' in wx.version().lower() +TX_WORKFLOW_ID = wx.NewId() class ChirpGridTable(wx.grid.GridStringTable): - def __init__(self, features, num_cols): + def __init__(self, features, col_defs): self._features = features + self._col_defs = col_defs num_rows = (self._features.memory_bounds[1] - self._features.memory_bounds[0] + len(self._features.valid_special_chans) + 1) - super().__init__(num_rows, num_cols) + super().__init__(num_rows, len(col_defs)) self._rowmap = {x: x for x in range(0, self.GetRowsCount())} self._rowmap_rev = {v: k for k, v in self._rowmap.items()} @@ -73,6 +75,10 @@ class ChirpGridTable(wx.grid.GridStringTable): # order. That convoluted scheme makes us always sort empty values at # the bottom instead of the top of the list, which is what a human # will want. + + def sortable_value(val): + return self._col_defs[col].get_sortable_value(val) + if col < 0: self._rowmap = {x: x for x in range(0, self.GetRowsCount())} else: @@ -80,7 +86,8 @@ class ChirpGridTable(wx.grid.GridStringTable): (asc != bool( super(ChirpGridTable, self).GetValue( realrow, col).strip()), - super(ChirpGridTable, self).GetValue(realrow, col), + sortable_value( + super(ChirpGridTable, self).GetValue(realrow, col)), realrow) for realrow in range(0, self.GetRowsCount())), reverse=not asc) @@ -162,6 +169,12 @@ class ChirpMemoryColumn(object): self._features = radio.get_features() self._doc = None + @staticmethod + def get_sortable_value(value): + """Convert a rendered value into the type/format we should use for + sorting""" + return value + @property def name(self): return self._name @@ -189,7 +202,7 @@ class ChirpMemoryColumn(object): @property def valid(self): - if self._name in ['freq', 'rtone']: + if self._name in ['freq', 'rtone', 'txfreq']: return True to_try = ['has_%s', 'valid_%ss', 'valid_%ses', 'valid_%s_levels'] for thing in to_try: @@ -246,8 +259,11 @@ class ChirpMemoryColumn(object): raise ValueError( _('Unable to set %s on this memory') % self._name) else: - setattr(memory, self._name, self._digest_value(memory, - input_value)) + self._set_mem_value(memory, + self._digest_value(memory, input_value)) + + def _set_mem_value(self, memory, value): + setattr(memory, self._name, value) def get_editor(self): return wx.grid.GridCellTextEditor() @@ -289,19 +305,55 @@ class ChirpFrequencyColumn(ChirpMemoryColumn): super().__init__(*a, **k) self._wants_split = set() + @staticmethod + def get_sortable_value(value): + try: + return float(value) + except ValueError: + return 0 + + def value(self, memory): + if self._name == 'txfreq': + if memory.duplex == 'split': + return memory.offset + elif memory.duplex == '-': + mult = -1 + else: + mult = 1 + + return memory.freq + (memory.offset * mult) + return super().value(memory) + @property def label(self): if self._name == 'offset': return (_('Offset/\nTX Freq') if 'split' in self._features.valid_duplexes else _('Offset')) + elif self._name == 'txfreq': + return _('TX Frequency') else: return _('Frequency') def hidden_for(self, memory): - return (self._name == 'offset' and - memory.duplex in ('', 'off') and - memory.number not in self._wants_split) + if self._name == 'offset': + return (memory.duplex in ('', 'off') and + memory.number not in self._wants_split) + else: + return False + + def _set_mem_value(self, memory, value): + if self._name == 'txfreq': + if 'split' in self._features.valid_duplexes: + # Always in split mode + memory.duplex = 'split' + memory.offset = value + else: + # This radio does not support proper split, so try to fake it + chirp_common.split_to_offset(memory, + memory.freq, value) + else: + return super()._set_mem_value(memory, value) def _render_value(self, memory, value): if not value: @@ -361,6 +413,13 @@ class ChirpVariablePowerColumn(ChirpMemoryColumn): def _digest_value(self, memory, value): return chirp_common.parse_power(value) + @staticmethod + def get_sortable_value(value): + try: + return int(chirp_common.parse_power(value)) + except ValueError: + return 0 + class ChirpChoiceEditor(wx.grid.GridCellChoiceEditor): """A locking GridCellChoiceEditor. @@ -439,6 +498,13 @@ class ChirpToneColumn(ChirpChoiceColumn): super(ChirpToneColumn, self).__init__(name, radio, tones) + @staticmethod + def get_sortable_value(value): + try: + return float(value) + except ValueError: + return 0 + @property def label(self): if self._name == 'rtone': @@ -864,6 +930,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self.SetDropTarget(ChirpMemoryDropTarget(self)) self._radio = radio + self._rconfig = config.get_for_radio(radio) self._features = self._radio.get_features() # Cache of memories by *row* @@ -887,7 +954,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self.bandplan = bandplan.BandPlans(CONF) self._grid = ChirpMemoryGrid(self) - self._table = ChirpGridTable(self._features, len(self._col_defs)) + self._table = ChirpGridTable(self._features, self._col_defs) # AssignTable added in wxPython 4.1, so use the older interface for # earlier version support (i.e. Ubuntu Jammy) self._grid.SetTable(self._table, takeOwnership=True, @@ -942,13 +1009,14 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self._dc = wx.ScreenDC() self.set_cell_attrs() - def _update_undo(self): + def _update_menu(self): + menubar = self.GetTopLevelParent().GetMenuBar() items = { wx.ID_UNDO: (_('Undo'), self._undo_queue), wx.ID_REDO: (_('Redo'), self._redo_queue), } for ident, (label, queue) in items.items(): - item = self.GetTopLevelParent().GetMenuBar().FindItemById(ident) + item = menubar.FindItemById(ident) accel = item.GetAccel() if queue: item.SetItemLabel('%s %s' % (label, queue[0].name)) @@ -958,6 +1026,9 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): item.Enable(False) item.SetAccel(accel) + workflow = menubar.FindItemById(TX_WORKFLOW_ID) + workflow.Check(self._has_coldef('txfreq')) + @contextlib.contextmanager def undo_context(self, name, actiontype=MemeditUndoContext): """Record changes made to memories as a single undo item""" @@ -982,7 +1053,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): # After we do another thing, the items in the redo queue are no longer # valid self._redo_queue = [] - self._update_undo() + self._update_menu() def _undo(self, event): """Undo the latest change.""" @@ -994,7 +1065,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self._redo_queue.insert(0, undo_item) self._redo_queue = self._redo_queue[:50] self.refresh() - self._update_undo() + self._update_menu() wx.PostEvent(self, common.EditorChanged(self.GetId())) def _redo(self, event): @@ -1006,7 +1077,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): undo_item.redo_changes() self._undo_queue.insert(0, undo_item) self.refresh() - self._update_undo() + self._update_menu() wx.PostEvent(self, common.EditorChanged(self.GetId())) @property @@ -1239,6 +1310,10 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): cls, '_set_hide_empty', ('hide_empty', 'memedit'), _('Hide empty memories')) + use_txfreq = common.EditorMenuItemToggleStateless( + cls, '_set_use_txfreq', + _('Use TX Frequency Workflow'), id=TX_WORKFLOW_ID) + return { common.EditorMenuItem.MENU_EDIT: [ redo, # First so Undo gets inserted at zero @@ -1250,6 +1325,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): common.EditorMenuItem.MENU_VIEW: [ expand_extra, hide_empty, + use_txfreq, ] } @@ -1259,6 +1335,21 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): def _set_hide_empty(self, event): self.refresh() + def _set_use_txfreq(self, event): + wx.MessageBox(_('The memory editor requires a reload in order to ' + 'change the workflow. That will happen now. Any ' + 'other open tabs will be updated the next time they ' + 'are loaded.'), + _('Reload required'), + parent=self) + + self._rconfig.set_bool( + 'use_txfreq_workflow', + not self._rconfig.get_bool('use_txfreq_workflow')) + event = common.EditorRefresh(self.GetId()) + event.SetEventObject(self) + wx.PostEvent(self, event) + def _goto(self, event): l, u = self._features.memory_bounds a = wx.GetNumberFromUser(_('Goto Memory:'), _('Number'), @@ -1291,6 +1382,16 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): valid_power_levels = self._features.valid_power_levels power_column = ChirpChoiceColumn('power', self._radio, valid_power_levels) + + if self._rconfig.get_bool('use_txfreq_workflow'): + tx_cols = [ChirpFrequencyColumn('txfreq', self._radio),] + else: + tx_cols = [ + ChirpDuplexColumn('duplex', self._radio, + valid_duplexes), + ChirpFrequencyColumn('offset', self._radio), + ] + defs = [ ChirpFrequencyColumn('freq', self._radio), ChirpMemoryColumn('name', self._radio), @@ -1302,10 +1403,8 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): ChirpDTCSColumn('dtcs', self._radio), ChirpDTCSColumn('rx_dtcs', self._radio), ChirpDTCSPolColumn('dtcs_polarity', self._radio), + *tx_cols, ChirpCrossModeColumn('cross_mode', self._radio), - ChirpDuplexColumn('duplex', self._radio, - valid_duplexes), - ChirpFrequencyColumn('offset', self._radio), ChirpChoiceColumn('mode', self._radio, valid_modes), ChirpChoiceColumn('tuning_step', self._radio, @@ -1324,6 +1423,12 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): return coldef LOG.error('No column definition for %s' % name) + def _has_coldef(self, name): + for coldef in self._col_defs: + if coldef._name == name: + return True + return False + def mem2row(self, number): if isinstance(number, str): row = self._special_rows[number] @@ -1386,16 +1491,22 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self._grid.GetRowLabelValue(row))) return + if not isinstance(memory.number, int): + LOG.error('Memory for row %i (lookup number %r) ' + 'has non-integer number field: %r', + row, number, memory.number) + if row in self._memory_errors: del self._memory_errors[row] hide_empty = CONF.get_bool('hide_empty', 'memedit', False) if memory.empty: # Reset our "wants split" flags if the memory is empty - offset_col = self._col_def_by_name('offset') - duplex_col = self._col_def_by_name('duplex') - offset_col.wants_split(memory, False) - duplex_col.wants_split(memory, False) + if self._has_coldef('duplex'): + offset_col = self._col_def_by_name('offset') + duplex_col = self._col_def_by_name('duplex') + offset_col.wants_split(memory, False) + duplex_col.wants_split(memory, False) if hide_empty: self._grid.HideRow(row) else: @@ -1413,13 +1524,18 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self._memory_cache[row] = memory + # Build a list of coldef names that are immutable extras for this + # memory + immutable_extras = ['extra.%s' % setting.get_name() + for setting in memory.extra + if not setting.value.get_mutable()] with wx.grid.GridUpdateLocker(self._grid): self.set_row_finished(row) for col, col_def in enumerate(self._col_defs): self._grid.SetCellValue(row, col, col_def.render_value(memory)) - immutable = col_def.name in memory.immutable or ( - 'extra' in col_def.name and 'extra' in memory.immutable) + immutable = (col_def.name in memory.immutable or + col_def.name in immutable_extras) self._grid.SetReadOnly(row, col, immutable or not self.editable) if immutable: @@ -2028,14 +2144,21 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): cut_item = wx.MenuItem(menu, wx.NewId(), _('Cut')) self.Bind(wx.EVT_MENU, lambda e: self.cb_copy(cut=True), cut_item) menu.Append(cut_item) + cut_item.Enable(self.editable) copy_item = wx.MenuItem(menu, wx.NewId(), _('Copy')) self.Bind(wx.EVT_MENU, lambda e: self.cb_copy(cut=False), copy_item) menu.Append(copy_item) + copy_item = wx.MenuItem(menu, wx.NewId(), _('Copy portable')) + self.Bind(wx.EVT_MENU, lambda e: self.cb_copy( + cut=False, portable=True), copy_item) + menu.Append(copy_item) + paste_item = wx.MenuItem(menu, wx.NewId(), _('Paste')) self.Bind(wx.EVT_MENU, lambda e: self.cb_paste(), paste_item) menu.Append(paste_item) + paste_item.Enable(self.editable) delete_menu = wx.Menu() delete_menu_item = menu.AppendSubMenu(delete_menu, _('Delete')) @@ -2254,9 +2377,9 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): def selected(self): self._grid.SetFocus() - self._update_undo() + self._update_menu() - def cb_copy_getdata(self, cut=False): + def cb_copy_getdata(self, cut=False, portable=False): rows = self.get_selected_rows_safe() mems = [] for row in rows: @@ -2271,9 +2394,20 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): memdata = wx.CustomDataObject(common.CHIRP_DATA_MEMORY) data.Add(memdata) memdata.SetData(pickle.dumps(payload)) - strfmt = chirp_common.mem_to_text(mems[0]) - textdata = wx.TextDataObject(strfmt) - data.Add(textdata) + if portable: + strfmt = chirp_common.mem_to_text(mems[0]) + textdata = wx.TextDataObject(strfmt) + data.Add(textdata) + else: + try: + r = generic_csv.TSVRadio(None) + r.clear() + for m in mems: + r.set_memory(m.dupe()) + textdata = wx.TextDataObject(r.as_string()) + data.Add(textdata) + except Exception as e: + LOG.exception('Failed to get TSV format for paste: %s', e) if cut: if any('empty' in mem.immutable for mem in mems): raise errors.InvalidMemoryLocation( @@ -2289,8 +2423,8 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): return data - def cb_copy(self, cut=False): - self.cb_copy_data(self.cb_copy_getdata(cut=cut)) + def cb_copy(self, cut=False, portable=False): + self.cb_copy_data(self.cb_copy_getdata(cut=cut, portable=portable)) def memedit_import_all(self, source_radio): if self.is_sorted: @@ -2456,18 +2590,25 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self._cb_paste_memories(payload) elif wx.DF_UNICODETEXT in data.GetAllFormats(): try: - mems = [chirp_common.mem_from_text(line) - for line in data.GetText().split('\n') - if line.strip()] + if data.GetText().count('\t') > 10: + # This looks plausibly like a TSV paste from a spreadsheet + mems = common.mems_from_clipboard(data.GetText(), + parent=self) + if not mems: + raise ValueError('No channels extracted from paste') + else: + mems = [chirp_common.mem_from_text(line) + for line in data.GetText().split('\n') + if line.strip()] + # Since matching the offset is kinda iffy, set our band + # plan set the offset, if a rule exists. + for mem in mems: + if mem.duplex in ('-', '+') and not mem.offset: + self._set_memory_defaults(mem, 'offset') except Exception as e: LOG.warning('Failed to parse pasted data %r: %s' % ( data.GetText(), e)) return - # Since matching the offset is kinda iffy, set our band plan - # set the offset, if a rule exists. - for mem in mems: - if mem.duplex in ('-', '+'): - self._set_memory_defaults(mem, 'offset') LOG.debug('Generic text paste %r: %s' % ( data.GetText(), mems)) self._cb_paste_memories({'mems': mems, diff --git a/chirp/wxui/radioinfo.py b/chirp/wxui/radioinfo.py index abf99f0..db4f24c 100644 --- a/chirp/wxui/radioinfo.py +++ b/chirp/wxui/radioinfo.py @@ -59,6 +59,7 @@ class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor): def _add_driver(self): pg = wx.propgrid.PropertyGrid( self, style=wx.propgrid.PG_SPLITTER_AUTO_CENTER) + pg.EnableScrolling(True, True) self._group_control.AddPage(pg, _('Driver')) try: @@ -84,6 +85,7 @@ class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor): pg = wx.propgrid.PropertyGrid( self, style=wx.propgrid.PG_SPLITTER_AUTO_CENTER) + pg.EnableScrolling(True, True) self._group_control.AddPage(pg, 'Icom') attrs = dict(self._radio._icf_data) @@ -110,6 +112,7 @@ class ChirpRadioInfo(common.ChirpEditor, common.ChirpSyncEditor): pg = wx.propgrid.PropertyGrid( self, style=wx.propgrid.PG_SPLITTER_AUTO_CENTER) + pg.EnableScrolling(True, True) 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 9d6534b..c42dfd4 100644 --- a/chirp/wxui/report.py +++ b/chirp/wxui/report.py @@ -81,8 +81,6 @@ def with_session(fn): @functools.wraps(fn) def wrapper(*args, **kwargs): - global DISABLED - if DISABLED: return diff --git a/chirp/wxui/serialtrace.py b/chirp/wxui/serialtrace.py new file mode 100644 index 0000000..9939195 --- /dev/null +++ b/chirp/wxui/serialtrace.py @@ -0,0 +1,129 @@ +# Copyright 2025 Dan Smith +# +# 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 . + +import datetime +import logging +import os +import serial +import tempfile +import time + +from chirp import util +from chirp.wxui import config + +CONF = config.get() +LOG = logging.getLogger(__name__) +TRACEFILES = [] + + +def get_trace_entry(direction, start_ts, data): + loglines = util.hexprint(data, block_size=16).split('\n') + ts = time.monotonic() - start_ts + loglines = ['%7.3f %s %s%s' % (ts, direction, line, os.linesep) + for line in loglines if line.strip()] + if not loglines and direction == 'R' and not data: + # No data read means timeout, so denote that for clarity + loglines = ['%7.3f %s # timeout%s' % (ts, direction, os.linesep)] + return loglines + + +def purge_trace_files(keep=10): + global TRACEFILES + if keep == 0: + purge = TRACEFILES + TRACEFILES = [] + else: + purge = TRACEFILES[:-keep] + TRACEFILES = TRACEFILES[-10:] + for fn in purge: + try: + os.remove(fn) + LOG.debug('Removed old trace file %s', fn) + except FileNotFoundError: + pass + except Exception as e: + LOG.error('Failed to remove old trace file %s: %s', fn, e) + + +class SerialTrace(serial.Serial): + def __init__(self, *a, **k): + self.__tracef = None + super().__init__(*a, **k) + + def open(self): + super().open() + try: + self.__trace_start = time.monotonic() + self.__tracef = tempfile.NamedTemporaryFile(mode='w', + delete=False, + prefix='chirp-trace-', + suffix='.txt') + TRACEFILES.append(self.__tracef.name) + purge_trace_files(10) + now = datetime.datetime.now() + self.log('Serial trace %s started at %s' % (self, now.isoformat())) + LOG.info('Serial trace file created: %s' % self.__tracef.name) + except Exception as e: + LOG.error('Failed to create serial trace file: %s' % e) + self.__tracef = None + + def write(self, data): + super().write(data) + if self.__tracef: + try: + self.__tracef.writelines(get_trace_entry('W', + self.__trace_start, + data)) + except Exception as e: + LOG.error('Failed to write to serial trace file: %s' % e) + self.__tracef = None + + def read(self, size=1): + data = super().read(size) + if self.__tracef: + try: + self.__tracef.writelines(get_trace_entry('R', + self.__trace_start, + data)) + except Exception as e: + LOG.error('Failed to write to serial trace file: %s' % e) + self.__tracef = None + return data + + def close(self): + super().close() + if self.__tracef: + try: + now = datetime.datetime.now() + self.log('Trace ended at %s' % now.isoformat()) + self.__tracef.close() + LOG.info('Serial trace file closed: %s' % self.__tracef.name) + except Exception as e: + LOG.error('Failed to close serial trace file: %s' % e) + finally: + self.__tracef = None + + def log(self, message): + """Log a message to the trace file. + + Use this to annotate important events in the trace file, such as + reading a new block, etc. + """ + if self.__tracef: + try: + self.__tracef.write('# %s\n' % message) + except Exception as e: + LOG.error('Failed to write log message to trace file: %s' % e) + self.__tracef = None diff --git a/setup.py b/setup.py index 0898804..aecc3bf 100644 --- a/setup.py +++ b/setup.py @@ -1,11 +1,11 @@ -from distutils.core import setup +from setuptools import setup from setuptools import find_packages setup(name='chirp', description='A cross-platform cross-radio programming tool', packages=find_packages(include=["chirp*"]), include_package_data=True, - version='20250221', + version='20250912', url='https://chirp.danplanet.com', python_requires=">=3.10,<4", install_requires=[ diff --git a/tests/__init__.py b/tests/__init__.py index b2563b8..55640b0 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -76,11 +76,12 @@ def _load_tests(loader, tests, pattern, suite=None): images = os.environ['CHIRP_TESTIMG'].split() else: images = glob.glob("tests/images/*.img") + images = [os.path.basename(img) for img in images] tests = [os.path.splitext(os.path.basename(img))[0] for img in images] base = os.path.dirname(os.path.abspath(__file__)) base = os.path.join(base, 'images') - images = glob.glob(os.path.join(base, "*")) + images = [os.path.join(base, img) for img in images] tests = {img: os.path.splitext(os.path.basename(img))[0] for img in images} if pattern == 'test*.py': diff --git a/tests/__pycache__/__init__.cpython-310.pyc b/tests/__pycache__/__init__.cpython-310.pyc index e5edb17..f98eee7 100644 Binary files a/tests/__pycache__/__init__.cpython-310.pyc and b/tests/__pycache__/__init__.cpython-310.pyc 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 e682551..4f44f20 100644 Binary files a/tests/__pycache__/test_clone.cpython-310-pytest-7.1.3.pyc and b/tests/__pycache__/test_clone.cpython-310-pytest-7.1.3.pyc 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 47421f6..ff627da 100644 Binary files a/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc and b/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc differ diff --git a/tests/images/Baofeng_K6.img b/tests/images/Baofeng_K6.img new file mode 100644 index 0000000..3309aec Binary files /dev/null and b/tests/images/Baofeng_K6.img differ diff --git a/tests/images/Baofeng_UV-5G_Pro.img b/tests/images/Baofeng_UV-5G_Pro.img new file mode 100644 index 0000000..324157f Binary files /dev/null and b/tests/images/Baofeng_UV-5G_Pro.img differ diff --git a/tests/images/Baofeng_UV-5R_Mini.img b/tests/images/Baofeng_UV-5R_Mini.img new file mode 100644 index 0000000..4f9f268 Binary files /dev/null and b/tests/images/Baofeng_UV-5R_Mini.img differ diff --git a/tests/images/Icom_IC-T10.img b/tests/images/Icom_IC-T10.img new file mode 100644 index 0000000..23abac2 Binary files /dev/null and b/tests/images/Icom_IC-T10.img differ diff --git a/tests/images/Kenwood_TK-278.img b/tests/images/Kenwood_TK-278.img new file mode 100644 index 0000000..c7abbaf Binary files /dev/null and b/tests/images/Kenwood_TK-278.img differ diff --git a/tests/images/QYT_KT-5000.img b/tests/images/QYT_KT-5000.img new file mode 100644 index 0000000..2fc7b1c Binary files /dev/null and b/tests/images/QYT_KT-5000.img differ diff --git a/tests/images/Radioddity_GM-30.img b/tests/images/Radioddity_GM-30.img new file mode 100644 index 0000000..98e810c Binary files /dev/null and b/tests/images/Radioddity_GM-30.img differ diff --git a/tests/images/Retevis_H777_V4.img b/tests/images/Retevis_H777_V4.img new file mode 100644 index 0000000..38f479a Binary files /dev/null and b/tests/images/Retevis_H777_V4.img differ diff --git a/tests/images/Retevis_RA25.img b/tests/images/Retevis_RA25.img new file mode 100644 index 0000000..723ca6e Binary files /dev/null and b/tests/images/Retevis_RA25.img differ diff --git a/tests/images/Retevis_RA86.img b/tests/images/Retevis_RA86.img new file mode 100644 index 0000000..579046a Binary files /dev/null and b/tests/images/Retevis_RA86.img differ diff --git a/tests/images/Retevis_RT86S.img b/tests/images/Retevis_RT86S.img new file mode 100644 index 0000000..b6a26dc Binary files /dev/null and b/tests/images/Retevis_RT86S.img differ diff --git a/tests/images/TIDRADIO_TD-H3.img b/tests/images/TIDRADIO_TD-H3.img index e891793..bfb305d 100644 Binary files a/tests/images/TIDRADIO_TD-H3.img and b/tests/images/TIDRADIO_TD-H3.img differ diff --git a/tests/images/Wouxun_KG-805G.img b/tests/images/Wouxun_KG-805G.img new file mode 100644 index 0000000..967bde5 Binary files /dev/null and b/tests/images/Wouxun_KG-805G.img differ diff --git a/tests/images/Wouxun_KG-935H.img b/tests/images/Wouxun_KG-935H.img new file mode 100644 index 0000000..01cfbbd Binary files /dev/null and b/tests/images/Wouxun_KG-935H.img differ diff --git a/tests/py3-untested-drivers.txt b/tests/py3-untested-drivers.txt index ae81485..7a8ae4b 100644 --- a/tests/py3-untested-drivers.txt +++ b/tests/py3-untested-drivers.txt @@ -1,6 +1,5 @@ # These drivers have not been converted (or confirmed working) for python3 ARRL_Travel_Plus -Baofeng_K5-Plus Baojie_BJ-9900 Baojie_BJ-UV55 Boblov_X3Plus @@ -18,14 +17,6 @@ KSUN_M6 KYD_IP-620 KYD_NC-630A Kenwood_ITM -Kenwood_TK-260 -Kenwood_TK-270 -Kenwood_TK-272 -Kenwood_TK-278 -Kenwood_TK-360 -Kenwood_TK-370 -Kenwood_TK-372 -Kenwood_TK-378 Kenwood_TM-D710_CloneMode Kenwood_TS-480_CloneMode Kenwood_TS-480_LiveMode @@ -36,7 +27,6 @@ Kenwood_TS-850 Puxing_PX-2R RT_Systems_CSV Sainsonic_AP510 -TYT_TH-350 TYT_TH-7800_File TYT_TH-9800_File TYT_TH-UV3R diff --git a/tests/py3_driver_testers.txt b/tests/py3_driver_testers.txt index 2925741..53bee81 100644 --- a/tests/py3_driver_testers.txt +++ b/tests/py3_driver_testers.txt @@ -375,6 +375,7 @@ Wouxun_KG-UV9G_Pro,@mrtjr1,25-Apr-2023 Wouxun_KG-UV9K,@mrtjr1,14-Apr-2023 Wouxun_KG-935G,@mrtjr1,4-Jan-2022 Wouxun_KG-935G_Plus,@mrtjr1,7-Feb-2023 +Wouxun_KG-935H,@mrtjr1,14-Mar-2025 Yaesu_FT-1500M,@f3sty,05-Dec-2022 Yaesu_FT-2800M,#10616,05-Jun-2023 Yaesu_FT-2900R_1900R,#10274,14-Jan-2023 diff --git a/tests/test_clone.py b/tests/test_clone.py index 1723942..cb41bfb 100644 --- a/tests/test_clone.py +++ b/tests/test_clone.py @@ -5,6 +5,7 @@ from unittest import mock from chirp import chirp_common from chirp import errors +from chirp.wxui import serialtrace from tests import base LOG = logging.getLogger(__name__) @@ -14,7 +15,7 @@ class SerialException(Exception): pass -class SerialNone: +class SerialNone(serialtrace.SerialTrace): def flush(self): pass diff --git a/tests/test_edges.py b/tests/test_edges.py index c5c0775..d41970a 100644 --- a/tests/test_edges.py +++ b/tests/test_edges.py @@ -3,11 +3,20 @@ from unittest import mock from chirp import bitwise from chirp import chirp_common +from chirp import directory from chirp import errors from tests import base class TestCaseEdges(base.DriverTest): + def test_inherits_from_registered(self): + if self.rf.has_sub_devices: + devs = self.radio.get_sub_devices() + else: + devs = [self.radio] + for dev in devs: + directory.registered_class(dev.__class__) + def test_longname(self): m = self.get_mem() m.name = ("X" * 256) # Should be longer than any radio can handle @@ -133,6 +142,11 @@ class TestCaseEdges(base.DriverTest): # radios have empty in the immutable set. if m1.empty: m1.empty = False + + self.assertIsInstance(m1.number, int, + ('Special memory %s number %r is not an ' + 'integer') % (name, m1.number)) + try: del m1.extra except AttributeError: @@ -165,6 +179,9 @@ class TestCaseEdges(base.DriverTest): self.assertEqual('', m.extd_number, 'Non-special memory %i should not have ' 'extd_number set to %r' % (i, m.extd_number)) + self.assertIsInstance(m.number, int, + 'Memory number %r is not an integer' % + m.number) def test_get_memory_name_trailing_whitespace(self): if self.radio.MODEL == 'KG-UV8E': diff --git a/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc index b65e7cd..bdb9f73 100644 Binary files a/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc and b/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc 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 43d12a0..95787cc 100644 Binary files a/tests/unit/__pycache__/test_chirp_common.cpython-310-pytest-7.1.3.pyc and b/tests/unit/__pycache__/test_chirp_common.cpython-310-pytest-7.1.3.pyc differ diff --git a/tests/unit/__pycache__/test_csv.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_csv.cpython-310-pytest-7.1.3.pyc index 3ba6d7a..64c8587 100644 Binary files a/tests/unit/__pycache__/test_csv.cpython-310-pytest-7.1.3.pyc and b/tests/unit/__pycache__/test_csv.cpython-310-pytest-7.1.3.pyc 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 new file mode 100644 index 0000000..16f0c98 Binary files /dev/null and b/tests/unit/__pycache__/test_serialtrace.cpython-310-pytest-7.1.3.pyc differ diff --git a/tests/unit/test_bitwise.py b/tests/unit/test_bitwise.py index dc38cb6..c50c3fc 100644 --- a/tests/unit/test_bitwise.py +++ b/tests/unit/test_bitwise.py @@ -248,6 +248,22 @@ class TestBitwiseBCDTypes(BaseTest): def test_lbcd_array(self): self._test_def("lbcd foo[2];", "foo", b"\x12\x34", 3412) + def test_bbcd_array_leading_bits(self): + data = memmap.MemoryMapBytes(bytes(b"\xc7\x54")) + obj = bitwise.parse("bbcd foo[2];", data) + # This is what we interpret a leading 0xC000 as + self.assertEqual(int(obj.foo), 754 + 12000) + + # Ignore the top nibble and we expect just the bottom three + obj.foo[0].ignore_bits(0xF0) + self.assertEqual(int(obj.foo), 754) + + # If wet try to set something in the ignored nibble it should be + # ignored but preserved + obj.foo = 1754 + self.assertEqual(int(obj.foo), 754) + self.assertEqual(data[0][0], 0xC7) + class TestBitwiseCharTypes(BaseTest): def test_char(self): diff --git a/tests/unit/test_chirp_common.py b/tests/unit/test_chirp_common.py index facdbed..0edce51 100644 --- a/tests/unit/test_chirp_common.py +++ b/tests/unit/test_chirp_common.py @@ -504,7 +504,7 @@ class TestStepFunctions(base.BaseTest): 6.25: self._625, 12.5: self._125, } - allowed = [6.25, 12.5] + allowed = [12.5, 6.25] for step, freqs in list(steps.items()): for freq in freqs: # We don't support 5.0, so any of the frequencies in that @@ -520,7 +520,7 @@ class TestStepFunctions(base.BaseTest): def test_required_step_finds_suitable(self): # If we support 5.0, we should get it as the step for those self.assertEqual(5.0, chirp_common.required_step(self._005[0], - allowed=[2.5, 5.0])) + allowed=[5.0, 2.5])) # If we support 2.5 and not 5.0, then we should find 2.5 as a suitable # alternative self.assertEqual(2.5, chirp_common.required_step(self._005[0], @@ -534,7 +534,7 @@ class TestStepFunctions(base.BaseTest): def test_required_step_fail(self): self.assertRaises(errors.InvalidDataError, chirp_common.required_step, - 146520500) + 146520500, allowed=[5.0, 10.0, 12.5]) def test_fix_rounded_step_250(self): self.assertEqual(146106250, @@ -548,6 +548,10 @@ class TestStepFunctions(base.BaseTest): self.assertEqual(146118750, chirp_common.fix_rounded_step(146118000)) + def test_fix_rounded_step_no_change(self): + self.assertEqual(146520000, + chirp_common.fix_rounded_step(146520000)) + class TestImageMetadata(base.BaseTest): def test_make_metadata(self): diff --git a/tests/unit/test_csv.py b/tests/unit/test_csv.py index 60ee8cc..7974cec 100644 --- a/tests/unit/test_csv.py +++ b/tests/unit/test_csv.py @@ -28,6 +28,16 @@ CHIRP_CSV_MODERN_QUOTED_HEADER = ( 0,Nat Simplex,146.520000,,0.600000,TSQL,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,50W,This is the national calling frequency on 2m,,,, 1,"National Simp",446.000000,-,5.000000,DTCS,88.5,88.5,023,NN,023,Tone->Tone,FM,5.00,,5.0W,This is NOT the UHF calling frequency,,,, """) # noqa +CHIRP_TSV = ( + """Location Name Frequency Duplex Offset Tone rToneFreq cToneFreq DtcsCode DtcsPolarity RxDtcsCode CrossMode Mode TStep Skip Power Comment URCALL RPT1CALL RPT2CALL DVCODE +8 Mt Scott 147.280000 + 0.600000 TSQL 88.5 167.9 023 NN 023 Tone->Tone FM 5.00 50W TayDan Emergency Step #2\t\t\t\t +9 Mt Tabor 145.390000 - 0.600000 TSQL 88.5 100.0 023 NN 023 Tone->Tone FM 5.00 50W TayDan Emergency Step #1\t\t\t\t +10 Timberline V 147.120000 + 0.600000 TSQL 103.5 100.0 023 NN 023 Tone->Tone FM 5.00 50W TayDan Emergency Step #4\t\t\t\t +11 Timberline U 444.225000 + 5.000000 TSQL 88.5 100.0 023 NN 023 Tone->Tone FM 5.00 50W K7RPT Timberline, Linked to VHF side, AC7QE-R echolink\t\t\t\t +12 GovtCamp 443.875000 + 5.000000 TSQL 88.5 103.5 023 NN 023 Tone->Tone FM 5.00 50W\t\t\t\t +13 GoatMtn 443.700000 + 5.000000 TSQL 88.5 103.5 023 NN 023 Tone->Tone FM 5.00 50W SW Corner of Clackamas, Co.\t\t\t\t +14 TyghRdge 147.260000 + 0.600000 TSQL 103.5 82.5 023 NN 023 Tone->Tone FM 5.00 50W\t\t\t\t +""") # noqa class TestCSV(unittest.TestCase): @@ -182,6 +192,7 @@ class TestCSV(unittest.TestCase): def test_escaped_string_chars(self): m = chirp_common.Memory() + m.freq = 146520000 m.number = 1 m.name = 'This is "The one"' m.comment = 'Wow, a \nMulti-line comment!' @@ -191,6 +202,7 @@ class TestCSV(unittest.TestCase): def test_unicode_comment_chars(self): m = chirp_common.Memory() + m.freq = 146520000 m.number = 1 m.name = 'This is "The one"' m.comment = b'This is b\xc9\x90d news'.decode() @@ -200,6 +212,7 @@ class TestCSV(unittest.TestCase): def test_cross_dtcs(self): m = chirp_common.Memory() + m.freq = 146520000 m.number = 1 m.tmode = 'Cross' m.cross_mode = 'DTCS->DTCS' @@ -231,3 +244,11 @@ class RTCSV(unittest.TestCase): @ddt.data('ft3d', 'ftm400', 'ftm500') def test_sample_file(self, arg): self._test_open('rtcsv_%s.csv' % arg) + + +class TestTSV(unittest.TestCase): + def test_parse_tsv(self): + radio = generic_csv.TSVRadio(None) + radio.load_from(CHIRP_TSV) + m = radio.get_memory(8) + self.assertEqual('Mt Scott', m.name) diff --git a/tests/unit/test_serialtrace.py b/tests/unit/test_serialtrace.py new file mode 100644 index 0000000..22e8403 --- /dev/null +++ b/tests/unit/test_serialtrace.py @@ -0,0 +1,79 @@ +import unittest +from unittest import mock + +from chirp.wxui import serialtrace + + +class TestSerialTrace(unittest.TestCase): + @mock.patch('serial.Serial.open') + def test_open(self, mock_open): + trace = serialtrace.SerialTrace() + self.assertIsNone(trace._SerialTrace__tracef) + trace.open() + self.assertIsNotNone(trace._SerialTrace__tracef) + self.assertTrue(trace._SerialTrace__tracef.name.endswith('.txt')) + mock_open.assert_called_once() + + @mock.patch('os.remove') + def test_purge_trace_files(self, mock_remove): + from chirp.wxui import serialtrace + + for i in range(15): + serialtrace.TRACEFILES.append('test_trace_%i.txt' % i) + files = serialtrace.TRACEFILES[:] + + # Purge to 10 files keeps the last 10 + serialtrace.purge_trace_files(10) + self.assertEqual(len(serialtrace.TRACEFILES), 10) + self.assertEqual(['test_trace_%i.txt' % (i + 5) for i in range(10)], + serialtrace.TRACEFILES) + + # Purge to 20 does not change anything since only 10 stored + serialtrace.purge_trace_files(20) + self.assertEqual(10, len(serialtrace.TRACEFILES)) + + # Purge to zero removes all files + serialtrace.purge_trace_files(0) + self.assertEqual(0, len(serialtrace.TRACEFILES)) + + # Make sure we ended up removing all the files + mock_remove.assert_has_calls([mock.call(fn) for fn in files], + any_order=True) + + @mock.patch('serial.Serial.open') + @mock.patch('serial.Serial.write') + @mock.patch('serial.Serial.read') + def test_log_write(self, mock_read, mock_write, mock_open): + mock_read.side_effect = [b'123', b''] + trace = serialtrace.SerialTrace() + trace.open() + fn = serialtrace.TRACEFILES[-1] + trace.write(b'foo') + trace.read(3) + trace.read(5) + trace.close() + with open(fn, 'r') as f: + content = f.read() + self.assertIn('# Serial trace', content) + self.assertIn('foo...', content) + self.assertIn('R # timeout', content) + + @mock.patch('tempfile.NamedTemporaryFile') + @mock.patch('serial.Serial.open') + @mock.patch('serial.Serial.write') + @mock.patch('serial.Serial.read') + def test_log_write_fail(self, mock_read, mock_write, mock_open, mock_tf): + mock_tf.return_value.writelines.side_effect = [ + None, Exception("Write error")] + trace = serialtrace.SerialTrace() + trace.open() + # This should generate a write failure + trace.read(3) + + # Make sure we don't interrupt further communication + trace.write(b'foo') + trace.read() + trace.write(b'bar') + + # Before we are closed, the trace file should have been abandoned + self.assertIsNone(trace._SerialTrace__tracef) diff --git a/tools/check_commit.sh b/tools/check_commit.sh index 4a6d68d..9273912 100755 --- a/tools/check_commit.sh +++ b/tools/check_commit.sh @@ -16,7 +16,7 @@ echo -e "${GREEN}Checking from $(git rev-parse --short ${BASE}):${NC}" git log --pretty=oneline --no-merges --abbrev-commit ${BASE}.. echo -git diff ${BASE}.. '*.py' | grep '^+' > added_lines +git diff ${BASE}.. -- '*.py' | grep '^+' > added_lines if grep -E '(from|import).*six' added_lines; then fail No new uses of future @@ -50,11 +50,11 @@ if grep -E "eval\(" added_lines; then fail 'Use of eval() is dangerous and not permitted!' fi -if git diff ${BASE}.. 'tools/cpep8.manifest' | tail -n +5 | grep -q '^+'; then +if git diff ${BASE}.. -- 'tools/cpep8.manifest' | tail -n +5 | grep -q '^+'; then fail 'Do not add new files to cpep8.manifest; no longer needed' fi -if git diff ${BASE}.. 'tools/cpep8.blacklist' | tail -n +5 | grep -q '^+'; then +if git diff ${BASE}.. -- 'tools/cpep8.blacklist' | tail -n +5 | grep -q '^+'; then fail 'Do not add new files to cpep8.blacklist; fix the code' fi @@ -73,12 +73,16 @@ done # fail 'New drivers should not have match_model() implemented as it is not needed' #fi +if grep -E '\Wprint\(' added_lines; then + fail 'Do not use print()' +fi + if git log ${BASE}.. --merges | grep .; then fail Please do not include merge commits in your PR fi make -C chirp/locale clean all >/dev/null 2>&1 -if git diff chirp/locale | grep '^+[^#+]' | grep -v POT-Creation; then +if git diff -- chirp/locale | grep '^+[^#+]' | grep -v POT-Creation; then fail Locale files need updating fi @@ -88,7 +92,14 @@ if echo $added_py | grep -q chirp.drivers && ! echo $added_files | grep -q tests fail All new drivers should include a test image fi -existing_drivers=$(git ls-tree --name-only $BASE chirp/drivers/) +modified_files=$(git diff --name-only --diff-filter=M ${BASE}..) +modified_img=$(echo "$modified_files" | grep 'tests.images') +modified_py=$(echo "$modified_files" | grep '\.py$') +if [ "$modified_img" -a "$modified_py" ]; then + fail "Change modifies an image and (potentially) a driver for a possible upgrade breakage" +fi + +existing_drivers=$(git ls-tree --name-only $BASE -- chirp/drivers/) limit=51 for nf in $added_py; do for of in $existing_drivers; do @@ -104,4 +115,18 @@ done rm -f added_lines license_lines +commits=$(git log --pretty=format:%h ${BASE}..) +for commit in $commits; do + git log -n1 $commit --pretty=format:%B > commit_msg + if [[ `sed -n '1p' commit_msg | wc -c` > 99 ]]; then + fail "First line of commit message of $commit must be <99 chars" + fi + if [[ `wc -l < commit_msg` > 1 ]]; then + if ! sed -n '2p' commit_msg | grep '^$'; then + fail "Second line of commit message of $commit must be blank for proper formatting in the notification emails" + fi + fi + rm -f commit_msg +done + exit $RETCODE diff --git a/tools/check_for_bug.sh b/tools/check_for_bug.sh deleted file mode 100755 index c8b042d..0000000 --- a/tools/check_for_bug.sh +++ /dev/null @@ -1,7 +0,0 @@ -#!/usr/bin/env sh - -# This checks a given revision to make sure that it has a bug number -# in it, of the form "#123". It should be used in your pretxncommit -# hook - -hg log -r $1 --template {desc} | egrep -q "\#[0-9]+" diff --git a/tools/cpep8.manifest b/tools/cpep8.manifest index 2850863..1b499c3 100644 --- a/tools/cpep8.manifest +++ b/tools/cpep8.manifest @@ -53,8 +53,6 @@ ./chirp/drivers/th_uv88.py ./chirp/drivers/thd72.py ./chirp/drivers/tk760.py -./chirp/drivers/tk760g.py -./chirp/drivers/tk8180.py ./chirp/drivers/tmd710.py ./chirp/drivers/ts480.py ./chirp/drivers/ts590.py diff --git a/tools/fast-driver.py b/tools/fast-driver.py index 669a5e1..3f078e2 100755 --- a/tools/fast-driver.py +++ b/tools/fast-driver.py @@ -1,4 +1,4 @@ -#!/usr/bin/env Python3 +#!/usr/bin/env python3 import glob import os -- cgit v1.2.3