diff options
| author | Dave Hibberd <hibby@debian.org> | 2025-02-27 20:47:59 +0000 |
|---|---|---|
| committer | Dave Hibberd <hibby@debian.org> | 2025-02-27 20:47:59 +0000 |
| commit | f6b2e6e7159906b8b3204dca3a9e58e42c36ccbb (patch) | |
| tree | f823b552593e7c151d07e99fdb6c0f64622ba5e8 | |
| parent | af38e5c951c5c0e8a80808eed77c9d8ea810a858 (diff) | |
New upstream version 20250221upstream/20250221
103 files changed, 6524 insertions, 455 deletions
@@ -1,6 +1,6 @@ -Metadata-Version: 2.1 +Metadata-Version: 2.2 Name: chirp -Version: 20241227 +Version: 20250221 Summary: A cross-platform cross-radio programming tool Home-page: https://chirp.danplanet.com Requires-Python: >=3.10,<4 @@ -12,3 +12,8 @@ Requires-Dist: suds Requires-Dist: lark Provides-Extra: wx Requires-Dist: wxPython; extra == "wx" +Dynamic: home-page +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary diff --git a/chirp.egg-info/PKG-INFO b/chirp.egg-info/PKG-INFO index 104a15f..85945e1 100644 --- a/chirp.egg-info/PKG-INFO +++ b/chirp.egg-info/PKG-INFO @@ -1,6 +1,6 @@ -Metadata-Version: 2.1 +Metadata-Version: 2.2 Name: chirp -Version: 20241227 +Version: 20250221 Summary: A cross-platform cross-radio programming tool Home-page: https://chirp.danplanet.com Requires-Python: >=3.10,<4 @@ -12,3 +12,8 @@ Requires-Dist: suds Requires-Dist: lark Provides-Extra: wx Requires-Dist: wxPython; extra == "wx" +Dynamic: home-page +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary diff --git a/chirp.egg-info/SOURCES.txt b/chirp.egg-info/SOURCES.txt index e8ad8b2..08042f8 100644 --- a/chirp.egg-info/SOURCES.txt +++ b/chirp.egg-info/SOURCES.txt @@ -99,6 +99,7 @@ chirp/drivers/ic9x_icf.py chirp/drivers/ic9x_icf_ll.py chirp/drivers/ic9x_ll.py chirp/drivers/icf.py +chirp/drivers/icf520.py chirp/drivers/icm710.py chirp/drivers/icomciv.py chirp/drivers/icp7.py @@ -174,7 +175,9 @@ chirp/drivers/thd72.py chirp/drivers/thd74.py chirp/drivers/thuv1f.py chirp/drivers/tk270.py +chirp/drivers/tk280.py chirp/drivers/tk3140.py +chirp/drivers/tk481.py chirp/drivers/tk690.py chirp/drivers/tk760.py chirp/drivers/tk760g.py @@ -187,6 +190,7 @@ chirp/drivers/tmv71_ll.py chirp/drivers/ts2000.py chirp/drivers/ts480.py chirp/drivers/ts590.py +chirp/drivers/ts790e.py chirp/drivers/ts850.py chirp/drivers/uv5r.py chirp/drivers/uv5x3.py @@ -240,6 +244,7 @@ chirp/share/welcome_screen_zh_CN.png chirp/sources/__init__.py chirp/sources/base.py chirp/sources/dmrmarc.py +chirp/sources/mapy73pl.py chirp/sources/przemienniki_eu.py chirp/sources/przemienniki_net.py chirp/sources/radioreference.py @@ -285,6 +290,7 @@ chirp/wxui/settingsedit.py tests/__init__.py tests/base.py tests/conftest.py +tests/driver_xfails.yaml tests/icom_clone_simulator.py tests/model_stats.tsv tests/py3-untested-drivers.txt @@ -389,6 +395,7 @@ tests/images/Icom_IC-2720H.img tests/images/Icom_IC-2730A.img tests/images/Icom_IC-2820H.img tests/images/Icom_IC-E90.img +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 @@ -421,13 +428,17 @@ 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-280.img tests/images/Kenwood_TK-3140K.img tests/images/Kenwood_TK-3180K2.img +tests/images/Kenwood_TK-481.img tests/images/Kenwood_TK-7160K.img tests/images/Kenwood_TK-760G.img tests/images/Kenwood_TK-8102.img tests/images/Kenwood_TK-8180.img +tests/images/Kenwood_TK-880.img tests/images/Kenwood_TK-890.img +tests/images/Kenwood_TK-981.img tests/images/Kenwood_TM-D710G_CloneMode.img tests/images/Kenwood_TM-D710_CloneMode.img tests/images/Kenwood_TS-480_CloneMode.img @@ -467,6 +478,7 @@ tests/images/Radtel_RT-620.img tests/images/Radtel_RT-630.img 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_P2.img tests/images/Retevis_P62.img @@ -495,6 +507,7 @@ tests/images/Retevis_RB615.img tests/images/Retevis_RB617.img tests/images/Retevis_RB618.img tests/images/Retevis_RB619.img +tests/images/Retevis_RB626.img tests/images/Retevis_RB627B.img tests/images/Retevis_RB628.img tests/images/Retevis_RB628B.img diff --git a/chirp/__init__.py b/chirp/__init__.py index 1b1ef71..560165c 100644 --- a/chirp/__init__.py +++ b/chirp/__init__.py @@ -1 +1 @@ -CHIRP_VERSION = "next-20241227" +CHIRP_VERSION = "next-20250221" diff --git a/chirp/bitwise.py b/chirp/bitwise.py index 4e1188c..53581bd 100644 --- a/chirp/bitwise.py +++ b/chirp/bitwise.py @@ -161,7 +161,29 @@ def int_to_bcd(bcd_array, value): """Convert an int like 1234 into bcdDataElements like "\x12\x34" """ for i in reversed(range(0, len(bcd_array))): bcd_array[i].set_value(value % 100) - value /= 100 + value //= 100 + + +def numeric_str_to_bcd(bcdel, string, pad='0'): + """Convert a string of digits into BCD-like bytes. + + This should only be used for the quasi-BCD encodings of DTMF characters + that some radios use (i.e. 0x12 == "12" and 0x1D == "1D") + """ + string = string.ljust(2 * bcdel.size() // 8, pad) + for i in range(0, bcdel.size() // 8): + bcdel[i] = int(string[i*2:i*2+2], 16) + + +def bcd_to_numeric_str(bcdel, pad='0'): + """Convert a list of BCD-like bytes into a string. + + See numeric_str_to_bcd above. + """ + string = '' + for i in range(0, bcdel.size() // 8): + string += '%02X' % bcdel[i] + return string.ljust(2 * bcdel.size() // 8, pad) def get_string(char_array): @@ -335,13 +357,13 @@ class arrayDataElement(DataElement): def __set_value_bbcd(self, value): for i in reversed(self.__items): twodigits = value % 100 - value /= 100 + value //= 100 i.set_value(twodigits) def __set_value_lbcd(self, value): for i in self.__items: twodigits = value % 100 - value /= 100 + value //= 100 i.set_value(twodigits) def __set_value_char(self, value): @@ -854,6 +876,13 @@ class structDataElement(DataElement): yield key, self._generators[key] +def parse_count(string): + if string.startswith('0x'): + return int(string, 16) + else: + return int(string) + + class Processor: _types = { "u8": u8DataElement, @@ -956,7 +985,7 @@ class Processor: else: if defn[1][0] == "array": sym = defn[1][1][0] - count = int(defn[1][1][1][1]) + count = parse_count(defn[1][1][1][1]) else: count = 1 sym = defn[1] @@ -983,7 +1012,7 @@ class Processor: self._offset += (gen.size() // 8) res.append(gen) - if count == 1: + if defn[1][0] != "array": self._generators[name] = res[0] else: self._generators[name] = res @@ -997,7 +1026,7 @@ class Processor: deftype = struct[-1] if deftype[0] == "array": name = deftype[1][0][1] - count = int(deftype[1][1][1]) + count = parse_count(deftype[1][1][1]) elif deftype[0] == "symbol": name = deftype[1] count = 1 @@ -1015,7 +1044,7 @@ class Processor: self._generators = tmp self._lines = tmp_lines - if count == 1: + if deftype[0] != "array": self._generators[name] = result[0] else: self._generators[name] = result diff --git a/chirp/chirp_common.py b/chirp/chirp_common.py index 53d77a6..b867952 100644 --- a/chirp/chirp_common.py +++ b/chirp/chirp_common.py @@ -523,7 +523,7 @@ class Memory: self.name = vals[1] try: - self.freq = float(vals[2]) + self.freq = to_MHz(float(vals[2])) except Exception: raise errors.InvalidDataError("Frequency is not a valid number") @@ -533,7 +533,7 @@ class Memory: raise errors.InvalidDataError("Duplex is not +,-, or empty") try: - self.offset = float(vals[4]) + self.offset = to_MHz(float(vals[4])) except Exception: raise errors.InvalidDataError("Offset is not a valid number") @@ -563,30 +563,32 @@ class Memory: if self.dtcs not in DTCS_CODES: raise errors.InvalidDataError("DTCS code is not valid") + if vals[9] in ["NN", "NR", "RN", "RR"]: + self.dtcs_polarity = vals[9] + else: + raise errors.InvalidDataError("DtcsPolarity is not valid") + try: - self.rx_dtcs = int(vals[8], 10) + self.rx_dtcs = int(vals[10], 10) except Exception: raise errors.InvalidDataError("DTCS Rx code is not a valid number") if self.rx_dtcs not in DTCS_CODES: raise errors.InvalidDataError("DTCS Rx code is not valid") - if vals[9] in ["NN", "NR", "RN", "RR"]: - self.dtcs_polarity = vals[9] - else: - raise errors.InvalidDataError("DtcsPolarity is not valid") + self.cross_mode = vals[11] - if vals[10] in MODES: - self.mode = vals[10] + if vals[12] in MODES: + self.mode = vals[12] else: - raise errors.InvalidDataError("Mode is not valid") + raise errors.InvalidDataError("Mode %r is not valid" % vals[10]) try: - self.tuning_step = float(vals[11]) + self.tuning_step = float(vals[13]) except Exception: raise errors.InvalidDataError("Tuning step is invalid") try: - self.skip = vals[12] + self.skip = vals[14] except Exception: raise errors.InvalidDataError("Skip value is not valid") @@ -906,6 +908,7 @@ class RadioFeatures: "has_comment": BOOLEAN, "has_settings": BOOLEAN, "has_variable_power": BOOLEAN, + "has_dynamic_subdevices": BOOLEAN, # Attributes "valid_modes": LIST, @@ -1005,6 +1008,8 @@ class RadioFeatures: self.init("has_variable_power", False, "Indicates the radio supports any power level between the " "min and max in valid_power_levels") + self.init("has_dynamic_subdevices", False, + "Indicates the radio has a non-static list of subdevices") self.init("valid_modes", list(MODES), "Supported emission (or receive) modes") @@ -2076,7 +2081,23 @@ def urlretrieve(url, fn): f.write(resp.read()) +def mem_from_tsv(tsv_text): + fields = tsv_text.split('\t') + if len(fields) < 13: + raise ValueError('Not enough fields to be a memory') + mem = Memory() + mem.really_from_csv(fields) + print('Parsed %s from tsv' % mem) + return mem + + def mem_from_text(text): + if text.count('\t') > 10: + # Seems like plausible TSV, return if it parses + try: + return mem_from_tsv(text) + except Exception: + pass m = Memory() freqs = re.findall(r'\b(\d{1,3}\.\d{2,6})\b', text) if not freqs: diff --git a/chirp/drivers/__init__.py b/chirp/drivers/__init__.py index 03e174b..ad2b12b 100644 --- a/chirp/drivers/__init__.py +++ b/chirp/drivers/__init__.py @@ -155,20 +155,24 @@ from chirp.drivers import vxa700 from chirp.drivers import wouxun from chirp.drivers import wouxun_common from chirp.drivers import kenwood_d7 -from chirp.drivers import yaesu_clone 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 tdh8 from chirp.drivers import uvk5 -from chirp.drivers import baofeng_uv17 -from chirp.drivers import icm710 -from chirp.drivers import mml_jc8810 from chirp.drivers import radtel_rt620 from chirp.drivers import radtel_rt490 -from chirp.drivers import baofeng_uv17Pro -from chirp.drivers import alinco_dr735t 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 -__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', 'yaesu_clone', 'iradio_uv_5118plus', 'ksun_m6', 'retevis_ra87', 'uvk5_egzumer', 'tdh8', 'uvk5', 'baofeng_uv17', 'icm710', 'mml_jc8810', 'radtel_rt620', 'radtel_rt490', 'baofeng_uv17Pro', 'alinco_dr735t', 'baofeng_digital', 'tk690'] +from chirp.drivers import yaesu_clone +from chirp.drivers import tk481 +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'] diff --git a/chirp/drivers/alinco_dr735t.py b/chirp/drivers/alinco_dr735t.py index 988a22c..19306b1 100644 --- a/chirp/drivers/alinco_dr735t.py +++ b/chirp/drivers/alinco_dr735t.py @@ -243,6 +243,7 @@ class AlincoDR735T(chirp_common.CloneModeRadio): mem.freq = int(_mem.frequency) mem.name = "".join([CHARSET[_mem.name[i]] for i in range(6)]).strip() + mem.name = mem.name.replace('\x00', '') mem.tmode = self.TONE_MODE_MAP[int(_mem.subtone_selection)] mem.duplex = self.SHIFT_DIR_MAP[_mem.shift_direction] diff --git a/chirp/drivers/anytone.py b/chirp/drivers/anytone.py index 4526382..8ae7a39 100644 --- a/chirp/drivers/anytone.py +++ b/chirp/drivers/anytone.py @@ -132,6 +132,13 @@ struct { char welcome[8]; } settings; +#seekto 0x0400; +struct { + u8 code[12]; + u8 len; + u8 unknown2[3]; +} dtmf_codes[16]; + #seekto 0x0540; struct memory memblk1[12]; @@ -416,7 +423,7 @@ class AnyTone5888UVRadio(chirp_common.CloneModeRadio, rf.valid_tones = TONES rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES rf.valid_bands = [(108000000, 500000000)] - rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + "-" + rf.valid_characters = chirp_common.CHARSET_ALPHANUMERIC + "-*#" rf.valid_name_length = 7 rf.valid_power_levels = POWER_LEVELS rf.memory_bounds = (1, NUMBER_OF_MEMORY_LOCATIONS) @@ -471,7 +478,7 @@ class AnyTone5888UVRadio(chirp_common.CloneModeRadio, mem.freq += 50 mem.offset = int(_mem.offset) * 100 - mem.name = str(_mem.name).rstrip() + mem.name = str(_mem.name).rstrip().replace('\x00', '') mem.duplex = DUPLEXES[_mem.duplex] mem.mode = _mem.is_am and "AM" or MODES[_mem.channel_width] mem.tuning_step = TUNING_STEPS[_mem.tune_step] @@ -707,11 +714,33 @@ class AnyTone5888UVRadio(chirp_common.CloneModeRadio, current_index=_settings.mute)) basic.append(rs) + dtmf = RadioSettingGroup('dtmf', 'DTMF') + for i in range(16): + length = int(self._memobj.dtmf_codes[i].len) + val = bitwise.bcd_to_numeric_str(self._memobj.dtmf_codes[i].code) + val = val[:length] + val = val.replace('E', '*').replace('F', '#') + rs = RadioSetting('dtmf%i' % i, 'DTMF M%i' % (i + 1), + RadioSettingValueString( + 0, 24, + val, autopad=False, + charset='01234567890*#abcdABCD')) + dtmf.append(rs) + + settings.append(dtmf) return settings def set_settings(self, settings): _settings = self._memobj.settings for element in settings: + if element.get_name() == 'dtmf': + for i in range(16): + val = str(element['dtmf%i' % i].value).strip() + val = val.replace('*', 'E').replace('#', 'F') + self._memobj.dtmf_codes[i].len = len(val) + bitwise.numeric_str_to_bcd( + self._memobj.dtmf_codes[i].code, val) + continue if not isinstance(element, RadioSetting): self.set_settings(element) continue diff --git a/chirp/drivers/baofeng_digital.py b/chirp/drivers/baofeng_digital.py index f7f4f14..39eba04 100644 --- a/chirp/drivers/baofeng_digital.py +++ b/chirp/drivers/baofeng_digital.py @@ -471,3 +471,16 @@ class BaofengW31D(BaofengDigital): ] _serial_id = 0x04 _proto = PROTO_D + + +@directory.register +class BaofengBFT20D(BaofengDigital): + """Baofeng BF-T20D""" + MODEL = 'BF-T20D' + VALID_BANDS = [(400000000, 480000000)] + POWER_LEVELS = [ + chirp_common.PowerLevel("Low", watts=0.5), + chirp_common.PowerLevel("High", watts=2.00), + ] + _serial_id = 0x05 + _proto = PROTO_D diff --git a/chirp/drivers/baofeng_uv17.py b/chirp/drivers/baofeng_uv17.py index 1e6838f..48fb57f 100644 --- a/chirp/drivers/baofeng_uv17.py +++ b/chirp/drivers/baofeng_uv17.py @@ -492,14 +492,6 @@ class UV17(baofeng_uv17Pro.UV17Pro): self.set_memory_common(mem, _mem) - def get_features(self): - rf = super().get_features() - rf.has_bank = False - return rf - - def get_mapping_models(self): - return [] - @directory.register class UV13Pro(UV17): diff --git a/chirp/drivers/baofeng_uv17Pro.py b/chirp/drivers/baofeng_uv17Pro.py index 3a0347e..550a5fc 100644 --- a/chirp/drivers/baofeng_uv17Pro.py +++ b/chirp/drivers/baofeng_uv17Pro.py @@ -500,7 +500,11 @@ class UV17Pro(bfc.BaofengCommonHT): if ord(str(char)) in [0, 255]: break fname += int(char).to_bytes(1, 'big') - return fname.decode('gb2312').strip() + try: + return fname.decode('gb2312').strip() + except UnicodeDecodeError: + LOG.warning('Unable to decode code name %r' % name) + return '' def apply_codename(self, setting, obj): codename = (str(setting.value).encode('gb2312')[:10].ljust(10, @@ -1139,15 +1143,12 @@ class UV17Pro(bfc.BaofengCommonHT): raise errors.RadioError('Unexpected error communicating ' 'with the radio') - def get_bank_model(self): - return chirp_common.StaticBankModel(self, banks=10) - def get_features(self): """Get the radio's features""" rf = chirp_common.RadioFeatures() rf.has_settings = True - rf.has_bank = True + rf.has_bank = False rf.has_tuning_step = False rf.can_odd_split = True rf.has_name = True @@ -1415,6 +1416,14 @@ class UV17ProGPS(UV17Pro): UV17Pro._uhf_range, UV17Pro._uhf2_range] MODES = UV17Pro.MODES + ['AM'] + def get_bank_model(self): + return chirp_common.StaticBankModel(self, banks=10) + + def get_features(self): + rf = super().get_features() + rf.has_bank = True + return rf + @directory.register class BF5RM(UV17Pro): @@ -1611,6 +1620,14 @@ class F8HPPro(UV17Pro): rs.set_apply_callback(apply_stationid, _nameobj) basic.append(rs) + def get_bank_model(self): + return chirp_common.StaticBankModel(self, banks=10) + + def get_features(self): + rf = super().get_features() + rf.has_bank = True + return rf + @directory.register class UV5RH(UV17Pro): diff --git a/chirp/drivers/bj9900.py b/chirp/drivers/bj9900.py index 3bf7898..97487b4 100644 --- a/chirp/drivers/bj9900.py +++ b/chirp/drivers/bj9900.py @@ -44,7 +44,7 @@ class BJ9900Radio(chirp_common.CloneModeRadio, VALID_BANDS = [(109000000, 136000000), (136000000, 174000000), (400000000, 470000000)] - CHARSET = list(chirp_common.CHARSET_ALPHANUMERIC) + CHARSET = list(chirp_common.CHARSET_ALPHANUMERIC + '-') CHARSET.remove(" ") POWER_LEVELS = [ diff --git a/chirp/drivers/fd268.py b/chirp/drivers/fd268.py index 39ea7c2..c1e6760 100644 --- a/chirp/drivers/fd268.py +++ b/chirp/drivers/fd268.py @@ -63,9 +63,9 @@ struct { bw1:1, // twin setting of bw (LCD "romb") bs1:1, // twin setting of bs (LCD "S") warning1:1; // twin setting of warning (LCD "Tune") - u8 sql[1]; + u8 sql; u8 monitorval; - u8 tot[1]; + u8 tot; u8 powerrank; u8 unknown23[3]; u8 unknown24[8]; diff --git a/chirp/drivers/ft2d.py b/chirp/drivers/ft2d.py index 6e0b8c9..aa08b26 100644 --- a/chirp/drivers/ft2d.py +++ b/chirp/drivers/ft2d.py @@ -90,16 +90,16 @@ class FT2D(ft1d.FT1Radio): "1. Turn radio off.\n" "2. Connect cable to DATA terminal.\n" "3. Press and hold [DISP] key while turning on radio\n" - " (\"CLONE\" will appear on the display).\n" - "4. <b>After clicking OK here in chirp</b>,\n" + " (\"CLONE\" will appear on radio LCD).\n" + "4. <b>After clicking OK here in Chirp</b>,\n" " press the [Send] screen button.\n") rp.pre_upload = _( - " 1. Turn radio off.\n" - " 2. Connect cable to DATA terminal.\n" - " 3. Press and hold in [DISP] key while turning on radio\n" - " (\"CLONE\" will appear on radio LCD).\n" - " 4. Press [RECEIVE] screen button\n" - " (\"-WAIT-\" will appear on radio LCD).\n" + "1. Turn radio off.\n" + "2. Connect cable to DATA terminal.\n" + "3. Press and hold in [DISP] key while turning on radio\n" + " (\"CLONE\" will appear on radio LCD).\n" + "4. Press [RECEIVE] screen button\n" + " (\"-WAIT-\" will appear on radio LCD).\n" "5. Finally, press OK button below.\n") return rp diff --git a/chirp/drivers/ft450d.py b/chirp/drivers/ft450d.py index 6d9661b..2f96ccf 100644 --- a/chirp/drivers/ft450d.py +++ b/chirp/drivers/ft450d.py @@ -611,6 +611,7 @@ class FT450DRadio(yaesu_clone.YaesuCloneModeRadio): rf.has_ctone = True rf.has_settings = True rf.has_cross = True + rf.has_nostep_tuning = True return rf def get_raw_memory(self, number): diff --git a/chirp/drivers/ic2100.py b/chirp/drivers/ic2100.py index 631df29..40297b4 100644 --- a/chirp/drivers/ic2100.py +++ b/chirp/drivers/ic2100.py @@ -188,6 +188,7 @@ class IC2100Radio(icf.IcomCloneModeRadio): rf.valid_bands = [(118000000, 174000000)] rf.valid_skips = ["", "S"] rf.valid_special_chans = sorted(_get_special().keys()) + rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + '-/' return rf def process_mmap(self): diff --git a/chirp/drivers/ic2720.py b/chirp/drivers/ic2720.py index 5d0e459..5e147d9 100644 --- a/chirp/drivers/ic2720.py +++ b/chirp/drivers/ic2720.py @@ -63,9 +63,6 @@ DUPLEX = ["", "", "-", "+"] POWER_LEVELS_VHF = [chirp_common.PowerLevel("High", watts=50), chirp_common.PowerLevel("Low", watts=5), chirp_common.PowerLevel("Mid", watts=15)] -POWER_LEVELS_UHF = [chirp_common.PowerLevel("High", watts=35), - chirp_common.PowerLevel("Low", watts=5), - chirp_common.PowerLevel("Mid", watts=15)] @directory.register @@ -148,10 +145,7 @@ class IC2720Radio(icf.IcomCloneModeRadio): mem.skip = (_skp & bitpos) and "S" or "" - if int(mem.freq / 100000000) == 1: - mem.power = POWER_LEVELS_VHF[_mem.power] - else: - mem.power = POWER_LEVELS_UHF[_mem.power] + mem.power = POWER_LEVELS_VHF[_mem.power] return mem diff --git a/chirp/drivers/icf.py b/chirp/drivers/icf.py index e94281d..cc4c9f8 100644 --- a/chirp/drivers/icf.py +++ b/chirp/drivers/icf.py @@ -131,7 +131,7 @@ class RadioStream: end = self.data.index(b'\xFD') frame = IcfFrame.parse(self.data[:end + 1]) self.data = self.data[end + 1:] - if frame.src == 0xEE and frame.dst == 0xEF: + if frame.src == ADDR_PC and frame.dst == ADDR_RADIO: # PC echo, ignore if self.iecho is None: LOG.info('Detected an echoing cable') @@ -181,28 +181,33 @@ class RadioStream: if len(f) != 0: LOG.warning('Expected to read one echo frame, found %i', len(f)) - if f and f[0].src == 0xEF: + if f and f[0].src == ADDR_RADIO: LOG.warning('Expected PC echo but found radio frame!') def decode_model(data): - if len(data) != 49: + if len(data) == 49: + rev = util.byte_to_int(data[5]) + LOG.info('Radio revision is %i' % rev) + comment = data[6:6 + 16] + LOG.info('Radio comment is %r' % comment) + serial = binascii.unhexlify(data[35:35 + 14]) + model, b1, b2, u1, s3 = struct.unpack('>HBBBH', serial) + serial_num = '%04i%02i%02i%04i' % (model, b1, b2, s3) + LOG.info('Radio serial is %r' % serial_num) + if len(data) == 56: + rev = None + comment = data[6:6 + 32] + LOG.info('Radio comment is %r' % comment) + else: + rev = None LOG.info('Unable to decode %i-byte model data' % len(data)) - return None - rev = util.byte_to_int(data[5]) - LOG.info('Radio revision is %i' % rev) - comment = data[6:6 + 16] - LOG.info('Radio comment is %r' % comment) - serial = binascii.unhexlify(data[35:35 + 14]) - model, b1, b2, u1, s3 = struct.unpack('>HBBBH', serial) - serial_num = '%04i%02i%02i%04i' % (model, b1, b2, s3) - LOG.info('Radio serial is %r' % serial_num) return rev def get_model_data(radio, mdata=b"\x00\x00\x00\x00", stream=None): """Query the @radio for its model data""" - send_clone_frame(radio, 0xe0, mdata, raw=True) + send_clone_frame(radio, CMD_CLONE_ID, mdata, raw=True) if stream is None: stream = RadioStream(radio.pipe) @@ -250,7 +255,7 @@ def send_clone_frame(radio, cmd, data, raw=False, checksum=False): if TRACE_ICF: LOG.debug('Sending:\n%s' % frame) - if cmd == 0xe4: + if cmd == CMD_CLONE_DAT: # Uncomment to avoid cloning to the radio # return frame pass diff --git a/chirp/drivers/icf520.py b/chirp/drivers/icf520.py new file mode 100644 index 0000000..0304217 --- /dev/null +++ b/chirp/drivers/icf520.py @@ -0,0 +1,1610 @@ +""" +Icom IC-F621 Land Mobile Radio +""" + +# Copyright 2023 Dan Smith <dsmith@danplanet.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import logging + +from chirp import chirp_common +from chirp import directory +from chirp import bitwise +from chirp.drivers import icf +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueInteger, RadioSettingValueList, \ + RadioSettingValueString, RadioSettingValueFloat + +LOG = logging.getLogger(__name__) + +MEM_FORMAT = """ +u8 model_code[4]; +u8 unknown100[269]; +u8 beep_on:1, + beep_level_linked:1, + beep_level:6; +u8 squelch_level; +u8 volume_min_level; +u8 unknown101:5, + mic_gain:3; +u8 unknown102[9]; +u8 unknown103:3, + ignition_switch_on:1, + audio_filter:2, + backlight:2; +u8 horn_off:1, + unknown104:7; +u8 unknown105[16]; +struct { + u16 user_1:4, + user_2:4, + user_3:4, + user_4:4; + u24 dealer_1:4, + dealer_2:4, + dealer_3:4, + dealer_4:4, + dealer_5:4, + dealer_6:4; +} passwd; +u8 scrambler_syn_capture:2, + scrambler_tone_start_timing:2, + scrambler_non_rolling:1, + unknown106:1, + scrambler_group_code:2; +u8 unknown107[4]; +u16 beep_frequency_low; +u16 beep_frequency_high; +u16 unknown107a; +u8 backlight_set_enable:1, + beep_set_enable:1, + beep_level_set_enable:1, + squelch_level_set_enable:1, + volume_min_level_set_enable:1, + audio_filter_set_enable:1, + mic_gain_set_enable:1, + horn_set_enable:1; +u8 unknown108[5]; +bit trunk_on[16]; +struct { + u8 emergency; + u8 priority_a; + u8 priority_b; +} channel; +struct { + u8 unk1; + u8 unk2; + u8 unk3; + u8 unk4; + u8 unk5; + u8 unk6; +} unknown109; +u8 tx_dtcs_inverse:1, + rx_dtcs_inverse:1, + unknown110:6; +u8 unknown111:2, + emergency_channel_on:1, + unknown112:1, + tone_burst_phase_on:1, + rx_af_filter_low_cut_on:1, + unknown113:2; +u8 poweron_scan_on:1, + unknown114:1, + dtmf_id_out_on:1, + time_out_timer_beep_on:1, + unknown115:1, + data_out_on:1, + poweron_priority_a:1, + unknown116:1; +u8 unknown117:2, + opening_text_on:1, + poweron_selection_off:1, + unknown118:4; +u8 unknown119:2, + password_on:1, + unknown120:2, + rf_power_selection:1, + unknown121:2; +u8 unknown122; +u8 hookoff_monitor_on:1, + hookoff_priority_a:1, + hookon_scan_on:1, + unknown123:1, + exo_on:1, + tone_mute_eptt_on:1, + unknown124:2; +struct { + u8 scan_fast; + u8 scan_slow; + u8 ctcss_reverse_burst; + u8 unk1; + u8 unk2; + u8 unk3; + u8 unk4; + u8 two_tone_1_period; + u8 unk5; + u8 dtmf; + u8 dtmf_first; + u8 dtmf_starpound; + u8 two_tone_group; + u8 scan_stop; + u8 scan_resume; + u8 unk6; + u8 unk7; + u8 emergency_switch_on; + u8 emergency_switch_off; + u8 emergency_start_repeat; + u8 time_out; + u8 penalty; + u8 lockout_penalty; + u8 two_tone_beep_repeat; + u8 auto_reset_a; + u8 auto_reset_b; + u8 unk8; + u8 two_tone_auto_tx; + u8 horn; + u8 exo_delay; + u8 eptt_delay; + u8 ignition_switch_delay:4, + unk9:4; +} timer; +struct { + u8 lup; + u8 ldown; + u8 rup; + u8 rdown; + u8 p0; + u8 p1; + u8 p2; + u8 p3; + u8 p4; + u8 opf0; + u8 opf1; + u8 opf2; +} conv_key; +struct { + u8 lup; + u8 ldown; + u8 rup; + u8 rdown; + u8 p0; + u8 p1; + u8 p2; + u8 p3; + u8 p4; + u8 opf0; + u8 opf1; + u8 opf2; +} trunk_key; +struct { + u16 capacity; +} bank[16]; +struct { + u16 unk; +} unknown125[16]; +char clone_comment[32]; +struct { + u16 map; +} custom_characters[16]; +u16 two_tone_1_tone; +u16 two_tone_2_tone; +struct { + u16 unk; +} unknown126[40]; +u8 two_tone_2_period; +struct { + u8 unk; +} unknown127[14]; +u8 two_tone_timer_notone; +struct { + u8 unk; +} unknown128[22]; +u16 user_ctcss_freq; +u32 unknown129; +struct { + u16 rx; + u16 tx; +} continuous_tone[9]; +struct { + char name[10]; + bit active[256]; + u8 text_on:1, + unk1:5, + scan_mode:2; + u8 unk2; +} scan_list[10]; +struct { + char name[10]; + u8 code[12]; + u8 count; +} dtmf_autodial[10]; +struct { + char name[10]; + u32 disp_inhibit:1, + freq_rx:31; + u32 tx_inhibit:1, + freq_tx:31; + u16 rx_tone_off:1, + rx_tone_digital:1, + unk01:5, + rx_tone:9; + u16 tx_tone_off:1, + tx_tone_digital:1, + unk02:5, + tx_tone:9; + u8 unk03:3, + tot_on:1, + lockout_repeater:1, + lockout_busy:1, + power_rf:2; + u8 log_in:2, + log_out:2, + unk04:1, + text_on:1, + unk05:1, + two_tone_unk1:1; + u8 unk06:4, + two_tone_unk2:2, + auto_reset:1, + unk07:1; + u8 narrow:1, + scrambler_on:1, + scrambler_inhibit:1, + compander_on:1, + unk08:4; + u8 unk09; + u8 scrambler_code; + u16 unk10; + u16 unk11; + u8 unk12:6, + two_tone_index:2; +} memory[256]; +struct { + char name[10]; + u16 unk1; + u16 unk2; + u16 unk3; +} unknown130[32]; +u32 unknown131; +struct { + char name[10]; + u8 unk1; + u8 ans_on; + u8 unk2:2, + scan_start:1, + scan_cancel:1, + unk3:1, + beep:3; + u8 exo_on:1, + unk4:1, + auto_tx_on:1, + stun_on:1, + kill_on:1, + unk5:1, + bell:2; + u8 unk6; + u16 unk7; + u16 unk8; +} two_tone[9]; +u8 unknown132[4]; +char opening_text[10]; + +""" + +APPEAR_CHOICE = ["Appear", "Inhibit"] +ENABLE_CHOICE = ["Disable", "Enable"] +INVERSE_CHOICE = ["Normal", "Inverse"] +NO_YES_CHOICE = ["No", "Yes"] +ON_CHOICE = ["", "On"] # ["OFF", "ON"] +ON_OFF_CHOICE = ["Off", "On"] +YES_CHOICE = ["", "Yes"] + +MODES = ["FM", "NFM"] # Supported emission (or receive) modes + +TMODES = ["", "Tone", "TSQL", "DTCS", "Cross", ] +CROSS_MODES = [ + "Tone->Tone", + "Tone->DTCS", + "DTCS->Tone", + "DTCS->", + "->Tone", + "->DTCS", + "DTCS->DTCS", + ] + +TONES = [ + 67.0, 69.3, 71.0, 71.9, 74.4, 77.0, 79.7, 82.5, + 85.4, 88.5, 91.5, 94.8, 97.4, 100.0, 103.5, + 107.2, 110.9, 114.8, 118.8, 123.0, 127.3, + 131.8, 136.5, 141.3, 146.2, 151.4, 156.7, + 159.8, 162.2, 165.5, 167.9, 171.3, 173.8, + 177.3, 179.9, 183.5, 186.2, 189.9, 192.8, + 196.6, 199.5, 203.5, 206.5, 210.7, 218.1, + 225.7, 229.1, 233.6, 241.8, 250.3, 254.1, + ] + +DUPLEX = ["", "+", "-", "split", "off"] + +# Valid values for programable keys. +# Hex numbers are used for unkown functions. +KEY_FUNC = [ + "Null", + "CH Up", + "CH Down", + "Bank", + "Scan A Start/Stop", + "Scan B Start/Stop", + "Scan Add/Del(Tag)", + "Prio A", + "Prio A(Rewrite)", + "Prio B", + "MR-CH 1", + "MR-CH 2", + "MR-CH 3", + "MR-CH 4", + "Moni", + "Lock", + "High/Low", + "Wide/Narrow", + "Compander", + "C.Tone CH Ent", + "Talk Around", + "Scrambler", + "Re-dial", + "DTMF Autodial", + "Call", + "0x19", + "0x1A", + "Emergency Single", + "Emergency Repeat", + "0x1D", + "0x1E", + "0x1F", + "0x20", + "User Set Mode", + "Public Address", + "RX Speaker", + "0x24", + "0x25", + "0x26", + "0x27", + "Turbo SpeeDial A", + "Turbo SpeeDial B", + "Turbo SpeeDial C", + "Turbo SpeeDial D", + "Trunking Group Switch", + "Sp. Func 1", + "Sp. Func 2", + "Hook Scan", + "OPT1 Out", + "OPT2 Out", + "OPT3 Out", + "OPT1 Momentary", + "OPT2 Momentary", + "OPT3 Momentary", + ] + +# List of valid conventional keys +# in the order they should be presented to the user. +KEY_CONV = [ + "Null", + "CH Up", + "CH Down", + "Bank", + "Scan A Start/Stop", + "Scan B Start/Stop", + "Scan Add/Del(Tag)", + "Prio A", + "Prio A(Rewrite)", + "Prio B", + "MR-CH 1", + "MR-CH 2", + "MR-CH 3", + "MR-CH 4", + "Moni", + "Public Address", + "RX Speaker", + "Lock", + "High/Low", + "C.Tone CH Ent", + "Talk Around", + "Wide/Narrow", + "DTMF Autodial", + "Re-dial", + "Call", + "Emergency Single", + "Emergency Repeat", + "Scrambler", + "Compander", + "Hook Scan", + "User Set Mode", + "OPT1 Out", + "OPT2 Out", + "OPT3 Out", + "OPT1 Momentary", + "OPT2 Momentary", + "OPT3 Momentary", + "Sp. Func 1", + "Sp. Func 2", + ] + +# List of valid trunk keys +# in the order they should be presented to the user. +KEY_TRUNK = [ + "Null", + "Bank", + "Lock", + "High/Low", + "Trunking Group Switch", + "Turbo SpeeDial A", + "Turbo SpeeDial B", + "Turbo SpeeDial C", + "Turbo SpeeDial D", + "CH Up", + "CH Down", + "Compander", + "Sp. Func 1", + "Sp. Func 2", + ] + +AUDIO_FILTER_RX_OPTIONS = [ + "Normal", + "Low Cut", + ] + +RF_POWER_SELECTION_OPTIONS = [ + "MR CH Individual", + "Override", + ] + +BACKLIGHT_VALUES = [ + "Off", + "Dim", + "Auto", + "On", + ] + +BEEP_LEVEL_VALUES = [ + "", + "1", + "2", + "3", + "4", + "5", + ] + +AUDIO_FILTER_VALUES = [ + "300-3000 Hz", + "0-3000 Hz", + "300-3400 Hz", + "0-3400 Hz", + ] + +# Valid values for Mic Gain. +# Hex numbers are used for unkown functions. +MIC_GAIN_FUNC = [ + "0x00", + "1 Min", + "2", + "3", + "4", + "5 Max", + ] + +# List of valid Mic Gain choices +# in the order they should be presented to the user. +MIC_GAIN_CHOICE = [ + "1 Min", + "2", + "3", + "4", + "5 Max", + ] + +LOCKOUT_VALUES = [ # CS-F500 equivalent + "", # OFF + "Repeater", # Repeater Lockout + "Busy", # Busy Lockout + ] + +LOG_IN_OUT_VALUES = [ # CS-F500 equivalent + "", # OFF + "L-IN", # Log IN + "L-OFF", # Log OFF + "Both", # Log IN/OFF + ] + +RESET_TIMERS_VALUES = [ + "Timer B", + "Timer A", + ] + +SCRAMBLER_TYPE_VALUES = [ + "Rolling", + "Non-rolling", + ] + +SCRAMBLER_GCODE_VALUES = [ + "1", + "2", + "3", + "4", + ] + +# Valid values for Scrambler Synchronous Capture. +# Hex numbers are used for unkown functions. +SYN_CAPTURE_FUNC = [ + "Standard", + "0x01", + "0x02", + "Continuous", + ] + +# List of valid Scrambler Synchronous Capture choices +# in the order they should be presented to the user. +SYN_CAPTURE_CHOICE = [ + "Standard", + "Continuous", + ] + +TONE_BURST_VALUES = [ + "Notone", + "Phase", + ] + +TONE_STIMING_VALUES = [ + "Off", + "300 ms", + "600 ms", + "1100 ms", + ] + + +def kf_kc(i): + """ + Given the index of the conventional key choice + return the index of the corresponding function + """ + return int(KEY_FUNC.index(KEY_CONV[int(i)])) + + +def kc_kf(i): + """ + Given the index of the key function + return the index of the corresponding conventional key choice + """ + return int(KEY_CONV.index(KEY_FUNC[int(i)])) + + +def kf_kt(i): + """ + Given the index of the trunk key choice + return the index of the corresponding function + """ + return int(KEY_FUNC.index(KEY_TRUNK[int(i)])) + + +def kt_kf(i): + """ + Given the index of the key function + return the index of the corresponding trunk key choice + """ + return int(KEY_TRUNK.index(KEY_FUNC[int(i)])) + + +def mf_mc(i): + """ + Given the index of the mic gain choice + return the index of the corresponding function + """ + return int(MIC_GAIN_FUNC.index(MIC_GAIN_CHOICE[int(i)])) + + +def mc_mf(i): + """ + Given the index of the mic gain function + return the index of the corresponding choice + """ + return int(MIC_GAIN_CHOICE.index(MIC_GAIN_FUNC[int(i)])) + + +def sf_sc(i): + """ + Given the index of the sync capture choice + return the index of the corresponding function + """ + return int(SYN_CAPTURE_FUNC.index(SYN_CAPTURE_CHOICE[int(i)])) + + +def sc_sf(i): + """ + Given the index of the sync capture function + return the index of the corresponding choice + """ + return int(SYN_CAPTURE_CHOICE.index(SYN_CAPTURE_FUNC[int(i)])) + + +@directory.register +class ICF621_2Radio(icf.IcomCloneModeRadio): + """ + Icom IC-F621-2 UHF Land Mobile Radio + """ + VENDOR = "Icom" + MODEL = "IC-F621-2" + + # _power_high watts is taken from the brochure. + # FIXME: The others are guesses + _power_low1 = chirp_common.PowerLevel("Low1", watts=5) + _power_low2 = chirp_common.PowerLevel("Low2", watts=20) + _power_high = chirp_common.PowerLevel("High", watts=45) + + _model = "\x25\x26\x02\x00" # 4 byte model (don't use Byte String) + _memsize = 0x3000 + _endframe = "Icom Inc." # \x49\x63\x6F\x6D\x20\x49\x6E\x63\x2E + + # Ranges of the mmap to send to the radio + _ranges = [(0x0100, 0x3000, 16)] + + _num_banks = 16 + _can_hispeed = False + + # Different models and versions support subsets of the valid bands. + # Frequency values out of range for a radio will not cause a + # transfer error. The radio display will flash when that channel + # is selected. + # IC-F521 _valid_bands = [(136000000, 174000000)] + _valid_bands = [(440000000, 490000000)] + + _memories = {} + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.has_settings = True + + # Channels + rf.has_bank = False + rf.has_bank_names = False + rf.memory_bounds = (1, 256) + + # Channel Name + rf.has_name = True + rf.valid_characters = chirp_common.CHARSET_ASCII + rf.valid_name_length = 10 + + # Frequency + rf.valid_modes = list(MODES) + rf.has_offset = True + rf.has_tuning_step = False + rf.valid_tuning_steps = chirp_common.TUNING_STEPS + rf.valid_duplexes = list(DUPLEX) + rf.valid_bands = list(self._valid_bands) + rf.can_odd_split = True + rf.has_mode = True + + # Tone + rf.has_ctone = True + rf.has_dtcs = True + rf.has_rx_dtcs = True + rf.has_dtcs_polarity = False + rf.has_cross = True + rf.valid_cross_modes = list(CROSS_MODES) + rf.valid_tmodes = list(TMODES) + rf.valid_tones = list(TONES) + + # RF Power + rf.has_variable_power = False + rf.valid_power_levels = [ + self._power_high, self._power_low2, self._power_low1] + + # Scanning + rf.valid_skips = [] + + return rf + + def process_mmap(self): + """Convert the raw byte array into a memory object structure""" + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + # FIXME: BEGIN Ugly Hack + # Force driver to use one bank that contains all memories. + # This allows us to work on other parts of the driver before + # the bank model is complete. + self._memobj.bank[0].capacity = 256 + for i in range(1, self._num_banks): + self._memobj.bank[i].capacity = 0 + # When deleting this ugly hack, remember to change: + # rf.has_bank = True + # below. + # FIXME: END Ugly Hack + + def get_memory(self, number): + """Create a high-level memory object to return to the UI""" + + _mem = self._memobj.memory[number - 1] + memory = chirp_common.Memory() + memory.number = number + memory.immutable = [] + + # Frequency: Low level format is frequency in Hz + memory.freq = int(_mem.freq_rx) + + if _mem.tx_inhibit: + memory.duplex = "off" + memory.offset = 0 + elif int(_mem.freq_rx) == int(_mem.freq_tx): + memory.duplex = "" + memory.offset = 0 + else: + chirp_common.split_to_offset( + memory, int(_mem.freq_rx), int(_mem.freq_tx)) + + # Modes + if _mem.narrow: + memory.mode = "NFM" + else: + memory.mode = "FM" + + # Name + memory.name = str(_mem.name).rstrip() + + # Tone + txpol = None + if _mem.tx_tone_off: + txmode = None + txval = None + elif _mem.tx_tone_digital: + txmode = "DTCS" + txval = chirp_common.ALL_DTCS_CODES[int(_mem.tx_tone)] + else: + txmode = "Tone" + txval = TONES[_mem.tx_tone] + + rxpol = None + if _mem.rx_tone_off: + rxmode = None + rxval = None + elif _mem.rx_tone_digital: + rxmode = "DTCS" + rxval = chirp_common.ALL_DTCS_CODES[int(_mem.rx_tone)] + else: + rxmode = "Tone" + rxval = TONES[_mem.rx_tone] + + txspec = (txmode, txval, txpol) + rxspec = (rxmode, rxval, rxpol) + chirp_common.split_tone_decode(memory, txspec, rxspec) + + # RF Power + if _mem.power_rf == 3: + memory.power = self._power_high + elif _mem.power_rf == 2: + memory.power = self._power_low2 + else: + memory.power = self._power_low1 + + memory.extra = RadioSettingGroup('extra', 'Extra') + + # Mask (Don't display) channel on radio. + # This is refered as Inhibit in the CS-F500 software. + _disp_inhibit = RadioSetting( + "disp_inhibit", "Mask", + RadioSettingValueList( + YES_CHOICE, current_index=int(_mem.disp_inhibit))) + _disp_inhibit.set_doc( + "Prevent the radio from displaying the channel. This " + "prevents use of the channel but CHIRP will still download " + "the channel information.") + memory.extra.append(_disp_inhibit) + + _compander_on = RadioSetting( + "compander_on", "Compander", + RadioSettingValueList( + ON_CHOICE, current_index=int( + _mem.compander_on))) + _compander_on.set_doc("Compander On") + memory.extra.append(_compander_on) + + _tot_on = RadioSetting( + "tot_on", "TOT", + RadioSettingValueList( + ON_CHOICE, current_index=int(_mem.tot_on))) + _tot_on.set_doc("Time Out Timer On") + memory.extra.append(_tot_on) + + _auto_reset_timer = RadioSetting( + "auto_reset_timer", "Auto Reset Timer", + RadioSettingValueList( + RESET_TIMERS_VALUES, current_index=int( + _mem.auto_reset))) + _auto_reset_timer.set_doc("Auto Reset Timer Selection") + memory.extra.append(_auto_reset_timer) + + _lockout_bits = (_mem.lockout_busy << 1) | _mem.lockout_repeater + _lockout = RadioSetting( + "lockout", "Lockout", + RadioSettingValueList( + LOCKOUT_VALUES, current_index=int(_lockout_bits))) + _lockout.set_doc("Transmit Lockout") + memory.extra.append(_lockout) + + _log_in_out_bits = (_mem.log_in << 2) + _mem.log_out + _log_in_out_index = 0 + if _log_in_out_bits == 0x03: + _log_in_out_index = 2 + elif _log_in_out_bits == 0x0C: + _log_in_out_index = 1 + elif _log_in_out_bits == 0x0F: + _log_in_out_index = 3 + _log_in_out = RadioSetting( + "log_in_out", "Log", + RadioSettingValueList( + LOG_IN_OUT_VALUES, current_index=int(_log_in_out_index))) + _log_in_out.set_doc("Log in and Log out") + memory.extra.append(_log_in_out) + + # Any memory with a frequency of 0 MHz is treated as empty. + # + # When CS-F500 inserts a blank memory, it sets Tx and Rx frequency + # to 0 MHz and leaves the disp_inhibit bit unset. When the + # disp_inhibit bit is set, the memory is displayed in CS-F500 + # with an "i" in the inhibit column. + # + # The radio does not display inhibited (masked) memory + # channels. + if memory.freq == 0: + memory.empty = True + + return memory + + def set_memory(self, memory): + """Set the memory object @memory""" + # Store details about a high-level memory to the memory map + # This is called when a user edits a memory in the UI + + # Get a low-level memory object mapped to the image + _mem = self._memobj.memory[memory.number - 1] + + rf = self.get_features() + + # Frequency: Low level format is frequency in Hz + _mem.freq_rx = memory.freq + _mem.tx_inhibit = 0 + if memory.duplex == "off": + _mem.freq_tx = memory.freq + _mem.tx_inhibit = 1 + elif memory.duplex == "split": + _mem.freq_tx = memory.offset + elif memory.duplex == "-": + _mem.freq_tx = _mem.freq_rx - memory.offset + elif memory.duplex == "+": + _mem.freq_tx = _mem.freq_rx + memory.offset + else: + _mem.freq_tx = memory.freq + + # Modes + if memory.mode == "NFM": + _mem.narrow = 1 + else: + _mem.narrow = 0 + + # Name (alpha tag) + _mem.name = str(memory.name).ljust(rf.valid_name_length)[ + :rf.valid_name_length] + _mem.text_on = 1 + + # Tone + txspec, rxspec = chirp_common.split_tone_encode(memory) + txmode, txval, txpol = txspec + rxmode, rxval, rxpol = rxspec + + _mem.tx_tone_off = 1 + _mem.tx_tone_digital = 0 + _mem.tx_tone = 0 + if txmode == "Tone": + _mem.tx_tone_off = 0 + _mem.tx_tone = TONES.index(txval) + elif txmode == "DTCS": + _mem.tx_tone_off = 0 + _mem.tx_tone_digital = 1 + _mem.tx_tone = chirp_common.ALL_DTCS_CODES.index(txval) + + _mem.rx_tone_off = 1 + _mem.rx_tone_digital = 0 + _mem.rx_tone = 0 + if rxmode == "Tone": + _mem.rx_tone_off = 0 + _mem.rx_tone = TONES.index(rxval) + elif rxmode == "DTCS": + _mem.rx_tone_off = 0 + _mem.rx_tone_digital = 1 + _mem.rx_tone = chirp_common.ALL_DTCS_CODES.index(rxval) + + # RF Power + if memory.power == self._power_high: + _mem.power_rf = 3 + elif memory.power == self._power_low2: + _mem.power_rf = 2 + else: + _mem.power_rf = 1 + + _mem.disp_inhibit = 0 + _mem.compander_on = 0 + _mem.tot_on = 0 + _mem.auto_reset = 0 + _mem.lockout_busy = 0 + _mem.lockout_repeater = 0 + _mem.log_in = 0 + _mem.log_out = 0 + + if memory.extra: + _mem.disp_inhibit = memory.extra['disp_inhibit'].value + _mem.compander_on = memory.extra['compander_on'].value + _mem.tot_on = memory.extra['tot_on'].value + _mem.auto_reset = memory.extra['auto_reset_timer'].value + + _lockout = int(memory.extra['lockout'].value) + _mem.lockout_repeater = _lockout & 1 + _mem.lockout_busy = (_lockout >> 1) & 1 + + # There are two bits each for log in and log out/off. + # 0 is off and 3 is on. 1 and 2 remain a mystery + _log_in_out = int(memory.extra['log_in_out'].value) + _mem.log_in = 0 + _mem.log_out = 0 + if _log_in_out == 1: + _mem.log_in = 3 + elif _log_in_out == 2: + _mem.log_out = 3 + elif _log_in_out == 3: + _mem.log_in = 3 + _mem.log_out = 3 + + if memory.empty: + _mem.freq_rx = 0 + _mem.freq_tx = 0 + _mem.narrow = 0 + _mem.name = " " + _mem.text_on = 0 + _mem.tx_tone_off = 1 + _mem.tx_tone_digital = 0 + _mem.tx_tone = 0 + _mem.rx_tone_off = 1 + _mem.rx_tone_digital = 0 + _mem.rx_tone = 0 + +# Radio Settings + + # Build the "DTMF" menu. + # TODO: This menu is not even started. + + # Build the "Continuous Tone" menu. + # TODO: This menu is not complete. + def _get_continuous_tone_group(self): + _group = RadioSettingGroup( + "group_continuous_tone", "Continuous Tone") + # 9 custom CTCSS pairs + _group.append(RadioSetting( + "tone_burst_phase_on", "Tone Burst", + RadioSettingValueList( + TONE_BURST_VALUES, current_index=int( + self._memobj.tone_burst_phase_on)))) + # "CTCSS Reverse Burst Timer" + # "User CTCSS Freq (Hz)" + _group.append(RadioSetting( + "tx_dtcs_inverse", "TX DTCS Inverse", + RadioSettingValueList( + INVERSE_CHOICE, current_index=int( + self._memobj.tx_dtcs_inverse)))) + _group.append(RadioSetting( + "rx_dtcs_inverse", "RX DTCS Inverse", + RadioSettingValueList( + INVERSE_CHOICE, current_index=int( + self._memobj.rx_dtcs_inverse)))) + _group.append(RadioSetting( + "rx_af_filter_low_cut_on", "RX AF Filter", + RadioSettingValueList( + AUDIO_FILTER_RX_OPTIONS, current_index=int( + self._memobj.rx_af_filter_low_cut_on)))) + return _group + + # Build the "Scan" menu. + # TODO: This menu is barely started + def _get_scan_group(self): + _group = RadioSettingGroup("group_scan", "Scan") + # 10 scan lists + # timer.scan_stop "Stop" + # timer.scan_resume "Resume" + # timer.scan_fast "Fast Scan + # timer.scan_slow "Slow Scan" + _group.append(RadioSetting( + "poweron_scan_on", "Power on Scan", + RadioSettingValueList( + ON_OFF_CHOICE, current_index=int( + self._memobj.poweron_scan_on)))) + return _group + + # Build the "2TONE" menu + # TODO: This menu is not even started. + + # Build the "Conventional Key" menu. + def _get_conv_key_group(self): + _group = RadioSettingGroup("conv_keys", "Conventional Keys") + _group.append(RadioSetting( + "conv_key_lup", "L-Up", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.lup)))) + _group.append(RadioSetting( + "conv_key_ldown", "L-Down", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.ldown)))) + _group.append(RadioSetting( + "conv_key_rup", "R-Up", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.rup)))) + _group.append(RadioSetting( + "conv_key_rdown", "R-Down", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.rdown)))) + _group.append(RadioSetting( + "conv_key_p0", "P0", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.p0)))) + _group.append(RadioSetting( + "conv_key_p1", "P1", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.p1)))) + _group.append(RadioSetting( + "conv_key_p2", "P2", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.p2)))) + _group.append(RadioSetting( + "conv_key_p3", "P3", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.p3)))) + _group.append(RadioSetting( + "conv_key_p4", "P4", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.p4)))) + _group.append(RadioSetting( + "conv_key_opf0", "OPF0", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.opf0)))) + _group.append(RadioSetting( + "conv_key_opf1", "OPF1", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.opf1)))) + _group.append(RadioSetting( + "conv_key_opf2", "OPF2", + RadioSettingValueList( + KEY_CONV, current_index=kc_kf( + self._memobj.conv_key.opf2)))) + return _group + + # Build the "SmarTrunk Key" menu. + def _get_trunk_key_group(self): + _group = RadioSettingGroup("trunk_keys", "SmarTrunk Keys") + _group.append(RadioSetting( + "trunk_key_lup", "L-Up", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.lup)))) + _group.append(RadioSetting( + "trunk_key_ldown", "L-Down", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.ldown)))) + _group.append(RadioSetting( + "trunk_key_rup", "R-Up", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.rup)))) + _group.append(RadioSetting( + "trunk_key_rdown", "R-Down", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.rdown)))) + _group.append(RadioSetting( + "trunk_key_p0", "P0", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.p0)))) + _group.append(RadioSetting( + "trunk_key_p1", "P1", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.p1)))) + _group.append(RadioSetting( + "trunk_key_p2", "P2", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.p2)))) + _group.append(RadioSetting( + "trunk_key_p3", "P3", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.p3)))) + _group.append(RadioSetting( + "trunk_key_p4", "P4", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.p4)))) + _group.append(RadioSetting( + "trunk_key_opf0", "OPF0", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.opf0)))) + _group.append(RadioSetting( + "trunk_key_opf1", "OPF1", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.opf1)))) + _group.append(RadioSetting( + "trunk_key_opf2", "OPF2", + RadioSettingValueList( + KEY_TRUNK, current_index=kt_kf( + self._memobj.trunk_key.opf2)))) + return _group + + # Build the "Display" menu. + def _get_display_group(self): + _freq_lo = self._memobj.beep_frequency_low / 10.0 + _freq_hi = self._memobj.beep_frequency_high / 10.0 + _psw = int(not self._memobj.poweron_selection_off) + _isw = int(self._memobj.ignition_switch_on) + _pria = int(self._memobj.poweron_priority_a) + + _group = RadioSettingGroup("group_display", "Display") + _group.append(RadioSetting( + "beep_frequency_low", "Beep Low Freq", + RadioSettingValueFloat( + 400.0, 3000.0, _freq_lo, precision=0))) + _group.append(RadioSetting( + "beep_frequency_high", "Beep High Freq", + RadioSettingValueFloat( + 400.0, 3000.0, _freq_hi, precision=0))) + _group.append(RadioSetting( + "opening_text", "Opening Text", + RadioSettingValueString( + 0, 10, str(self._memobj.opening_text).rstrip(), False))) + _group.append(RadioSetting( + "rf_power_selection", "RF Power", + RadioSettingValueList( + RF_POWER_SELECTION_OPTIONS, current_index=int( + self._memobj.rf_power_selection)))) + _group.append(RadioSetting( + "poweron_selection_off", "Power Switch Selection", + RadioSettingValueList(APPEAR_CHOICE, current_index=_psw))) + _group.append(RadioSetting( + "ignition_switch_on", "Ignition Switch", + RadioSettingValueList(APPEAR_CHOICE, current_index=_isw))) + _group.append(RadioSetting( + "ignition_switch_delay", "Ignition Switch Delay Timer", + RadioSettingValueInteger( + 0, 240, self._memobj.timer.ignition_switch_delay))) + _group.append(RadioSetting( + "poweron_priority_a", "Power On Priority A Channel", + RadioSettingValueList(ENABLE_CHOICE, current_index=_pria))) + _group.append(RadioSetting( + "hookoff_priority_a", "Hook Off Priority A Channel", + RadioSettingValueList( + ENABLE_CHOICE, current_index=int( + self._memobj.hookoff_priority_a)))) + _group.append(RadioSetting( + "hookoff_monitor_on", "Hook Off Monitor", + RadioSettingValueList( + ON_OFF_CHOICE, current_index=int( + self._memobj.hookoff_monitor_on)))) + _group.append(RadioSetting( + "hookon_scan_on", "Hook on Scan", + RadioSettingValueList( + ON_OFF_CHOICE, current_index=int( + self._memobj.hookon_scan_on)))) + return _group + + # Build the "Set Mode" menu. + def _get_set_mode_group(self): + _hrn = int(not self._memobj.horn_off) + + _group = RadioSettingGroup("set_mode_group", "Set Mode") + _group.append(RadioSetting( + "backlight", "Backlight", + RadioSettingValueList( + BACKLIGHT_VALUES, current_index=int( + self._memobj.backlight)))) + _group.append(RadioSetting( + "backlight_set_enable", "Enable Backlight", + RadioSettingValueList( + NO_YES_CHOICE, current_index=int( + self._memobj.backlight_set_enable)))) + _group.append(RadioSetting( + "beep_on", "Beep", + RadioSettingValueList( + ON_OFF_CHOICE, current_index=int( + self._memobj.beep_on)))) + _group.append(RadioSetting( + "beep_set_enable", "Enable Beep", + RadioSettingValueList( + NO_YES_CHOICE, current_index=int( + self._memobj.beep_set_enable)))) + _group.append(RadioSetting( + "beep_level", "Beep Level", + RadioSettingValueList( + BEEP_LEVEL_VALUES, current_index=int( + self._memobj.beep_level)))) + _group.append(RadioSetting( + "beep_level_set_enable", "Enable Beep Level", + RadioSettingValueList( + NO_YES_CHOICE, current_index=int( + self._memobj.beep_level_set_enable)))) + _group.append(RadioSetting( + "squelch_level", "Squelch Level", + RadioSettingValueInteger( + 0, 255, self._memobj.squelch_level))) + _group.append(RadioSetting( + "squelch_level_set_enable", "Enable Squelch Level", + RadioSettingValueList( + NO_YES_CHOICE, current_index=int( + self._memobj.squelch_level_set_enable)))) + _group.append(RadioSetting( + "volume_min_level", "Volume Minimum Level", + RadioSettingValueInteger( + 0, 255, self._memobj.volume_min_level))) + _group.append(RadioSetting( + "volume_min_level_set_enable", "Enable Volume Minimum Level", + RadioSettingValueList( + NO_YES_CHOICE, current_index=int( + self._memobj.volume_min_level_set_enable)))) + _group.append(RadioSetting( + "audio_filter", "Audio Filter", + RadioSettingValueList( + AUDIO_FILTER_VALUES, current_index=int( + self._memobj.audio_filter)))) + _group.append(RadioSetting( + "audio_filter_set_enable", "Enable Audio Filter", + RadioSettingValueList( + NO_YES_CHOICE, current_index=int( + self._memobj.audio_filter_set_enable)))) + _group.append(RadioSetting( + "mic_gain", "Mic Gain", + RadioSettingValueList( + MIC_GAIN_CHOICE, current_index=mc_mf( + self._memobj.mic_gain)))) + _group.append(RadioSetting( + "mic_gain_set_enable", "Enable Mic Gain", + RadioSettingValueList( + NO_YES_CHOICE, current_index=int( + self._memobj.mic_gain_set_enable)))) + _group.append(RadioSetting( + "horn_off", "Horn", + RadioSettingValueList( + ON_CHOICE, current_index=_hrn))) + _group.append(RadioSetting( + "horn_set_enable", "Enable Horn", + RadioSettingValueList( + NO_YES_CHOICE, current_index=int( + self._memobj.horn_set_enable)))) + return _group + + # Build the "Common" menu. + def _get_common_group(self): + _timer_eptt = self._memobj.timer.eptt_delay / 10.0 + _timer_exo = self._memobj.timer.exo_delay / 10.0 + _timer_es_on = self._memobj.timer.emergency_switch_on / 10.0 + _timer_es_off = self._memobj.timer.emergency_switch_off / 10.0 + + _group = RadioSettingGroup("common_group", "Common") + _group.append(RadioSetting( + "clone_comment", "Clone Comment", + RadioSettingValueString( + 0, 32, str(self._memobj.clone_comment).rstrip(), False))) + _group.append(RadioSetting( + "password_on", "Power-on Password", + RadioSettingValueList( + ON_OFF_CHOICE, current_index=int( + self._memobj.password_on)))) + _group.append(RadioSetting( + "data_out_on", "Transceiver Data Out", + RadioSettingValueList( + ON_OFF_CHOICE, current_index=int( + self._memobj.data_out_on)))) + _group.append(RadioSetting( + "timer_auto_reset_a", "Auto Reset Timer A", + RadioSettingValueInteger( + 0, 255, self._memobj.timer.auto_reset_a))) + _group.append(RadioSetting( + "timer_auto_reset_b", "Auto Reset Timer B", + RadioSettingValueInteger( + 0, 255, self._memobj.timer.auto_reset_b))) + _group.append(RadioSetting( + "timer_time_out", "Time Out Timer", + RadioSettingValueInteger( + 0, 255, self._memobj.timer.time_out))) + _group.append(RadioSetting( + "timer_penalty", "Penalty Timer", + RadioSettingValueInteger( + 0, 255, self._memobj.timer.penalty))) + _group.append(RadioSetting( + "dtmf_id_out_on", "DTMF ID Out", + RadioSettingValueList( + ON_OFF_CHOICE, current_index=int( + self._memobj.dtmf_id_out_on)))) + _group.append(RadioSetting( + "time_out_timer_beep_on", "Time Out Timer Beep", + RadioSettingValueList( + ON_OFF_CHOICE, current_index=int( + self._memobj.time_out_timer_beep_on)))) + _group.append(RadioSetting( + "timer_lockout_penalty", "Lockout Penalty Timer", + RadioSettingValueInteger( + 0, 255, self._memobj.timer.lockout_penalty))) + _group.append(RadioSetting( + "timer_eptt_delay", "EPTT Delay Timer", + RadioSettingValueFloat(0, 25.5, _timer_eptt, precision=1))) + _group.append(RadioSetting( + "tone_mute_eptt_on", "Tone Mute EPTT", + RadioSettingValueList( + ON_OFF_CHOICE, current_index=int( + self._memobj.tone_mute_eptt_on)))) + _group.append(RadioSetting( + "exo_on", "EXO", RadioSettingValueList( + ON_OFF_CHOICE, current_index=int(self._memobj.exo_on)))) + _group.append(RadioSetting( + "timer_exo_delay", "EXO Delay Timer", + RadioSettingValueFloat(0, 25.5, _timer_exo, precision=1))) + _group.append(RadioSetting( + "timer_horn", "EXO/Horn Timer", + RadioSettingValueInteger(0, 255, self._memobj.timer.horn))) + _group.append(RadioSetting( + "scrambler_non_rolling", "Scrambler Type", + RadioSettingValueList( + SCRAMBLER_TYPE_VALUES, current_index=int( + self._memobj.scrambler_non_rolling)))) + _group.append(RadioSetting( + "scrambler_group_code", "Scrambler Group Code", + RadioSettingValueList( + SCRAMBLER_GCODE_VALUES, current_index=int( + self._memobj.scrambler_group_code)))) + _group.append(RadioSetting( + "scrambler_syn_capture", "Scrambler Synchronous Capture", + RadioSettingValueList( + SYN_CAPTURE_CHOICE, current_index=sc_sf( + self._memobj.scrambler_syn_capture)))) + _group.append(RadioSetting( + "scrambler_tone_start_timing", "Scrambler Tone Start Timing", + RadioSettingValueList( + TONE_STIMING_VALUES, current_index=int( + self._memobj.scrambler_tone_start_timing)))) + _group.append(RadioSetting( + "timer_emergency_switch_on", "Emergency Switch On Timer", + RadioSettingValueFloat(0, 25.5, _timer_es_on, precision=1))) + _group.append(RadioSetting( + "timer_emergency_switch_off", "Emergency Switch Off Timer", + RadioSettingValueFloat(0, 25.5, _timer_es_off, precision=1))) + _group.append(RadioSetting( + "emergency_start_repeat", "Emergency Start/Repeat", + RadioSettingValueInteger( + 0, 255, self._memobj.timer.emergency_start_repeat))) + return _group + + # Build the top menu. + def get_settings(self): + """Returns a RadioSettingGroup containing one or more + RadioSettingGroup or RadioSetting objects. These represent general + setting knobs and dials that can be adjusted on the radio.""" + return list( + RadioSettingGroup( + "top", "LMR", + self._get_continuous_tone_group(), + self._get_scan_group(), + self._get_conv_key_group(), + self._get_trunk_key_group(), + self._get_display_group(), + self._get_set_mode_group(), + self._get_common_group())) + + def set_settings(self, settings): + """Accepts the top-level RadioSettingGroup returned from get_settings() + and adjusts the values in the radio accordingly. This function expects + the entire RadioSettingGroup hierarchy returned from get_settings().""" + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + + # "Continuous Tone" items + elif element.get_name() == "tone_burst_phase_on": + self._memobj.tone_burst_phase_on = element.value + elif element.get_name() == "tx_dtcs_inverse": + self._memobj.tx_dtcs_inverse = element.value + elif element.get_name() == "rx_dtcs_inverse": + self._memobj.rx_dtcs_inverse = element.value + elif element.get_name() == "rx_af_filter_low_cut_on": + self._memobj.rx_af_filter_low_cut_on = element.value + + # "Scan" items + elif element.get_name() == "poweron_scan_on": + self._memobj.poweron_scan_on = element.value + + # "Conventional Key" items + elif element.get_name() == "conv_key_lup": + self._memobj.conv_key.lup = kf_kc(element.value) + elif element.get_name() == "conv_key_ldown": + self._memobj.conv_key.ldown = kf_kc(element.value) + elif element.get_name() == "conv_key_rup": + self._memobj.conv_key.rup = kf_kc(element.value) + elif element.get_name() == "conv_key_rdown": + self._memobj.conv_key.rdown = kf_kc(element.value) + elif element.get_name() == "conv_key_p0": + self._memobj.conv_key.p0 = kf_kc(element.value) + elif element.get_name() == "conv_key_p1": + self._memobj.conv_key.p1 = kf_kc(element.value) + elif element.get_name() == "conv_key_p2": + self._memobj.conv_key.p2 = kf_kc(element.value) + elif element.get_name() == "conv_key_p3": + self._memobj.conv_key.p3 = kf_kc(element.value) + elif element.get_name() == "conv_key_p4": + self._memobj.conv_key.p4 = kf_kc(element.value) + elif element.get_name() == "conv_key_opf0": + self._memobj.conv_key.opf0 = kf_kc(element.value) + elif element.get_name() == "conv_key_opf1": + self._memobj.conv_key.opf1 = kf_kc(element.value) + elif element.get_name() == "conv_key_opf2": + self._memobj.conv_key.opf2 = kf_kc(element.value) + elif element.get_name() == "trunk_key_lup": + self._memobj.trunk_key.lup = kf_kt(element.value) + + # "SmarTrunk Key" items + elif element.get_name() == "trunk_key_ldown": + self._memobj.trunk_key.ldown = kf_kt(element.value) + elif element.get_name() == "trunk_key_rup": + self._memobj.trunk_key.rup = kf_kt(element.value) + elif element.get_name() == "trunk_key_rdown": + self._memobj.trunk_key.rdown = kf_kt(element.value) + elif element.get_name() == "trunk_key_p0": + self._memobj.trunk_key.p0 = kf_kt(element.value) + elif element.get_name() == "trunk_key_p1": + self._memobj.trunk_key.p1 = kf_kt(element.value) + elif element.get_name() == "trunk_key_p2": + self._memobj.trunk_key.p2 = kf_kt(element.value) + elif element.get_name() == "trunk_key_p3": + self._memobj.trunk_key.p3 = kf_kt(element.value) + elif element.get_name() == "trunk_key_p4": + self._memobj.trunk_key.p4 = kf_kt(element.value) + elif element.get_name() == "trunk_key_opf0": + self._memobj.trunk_key.opf0 = kf_kt(element.value) + elif element.get_name() == "trunk_key_opf1": + self._memobj.trunk_key.opf1 = kf_kt(element.value) + elif element.get_name() == "trunk_key_opf2": + self._memobj.trunk_key.opf2 = kf_kt(element.value) + + # "Display Mode" items + elif element.get_name() == "beep_frequency_low": + self._memobj.beep_frequency_low = element.value * 10.0 + elif element.get_name() == "beep_frequency_high": + self._memobj.beep_frequency_high = element.value * 10.0 + elif element.get_name() == "opening_text": + self._memobj.opening_text = str( + element.value).ljust(10)[:10] + elif element.get_name() == "rf_power_selection": + self._memobj.rf_power_selection = element.value + elif element.get_name() == "poweron_selection_off": + self._memobj.poweron_selection_off = not element.value + elif element.get_name() == "ignition_switch_on": + self._memobj.ignition_switch_on = element.value + elif element.get_name() == "ignition_switch_delay": + self._memobj.timer.ignition_switch_delay = element.value + elif element.get_name() == "poweron_priority_a": + self._memobj.poweron_priority_a = element.value + elif element.get_name() == "hookoff_priority_a": + self._memobj.hookoff_priority_a = element.value + elif element.get_name() == "hookoff_monitor_on": + self._memobj.hookoff_monitor_on = element.value + elif element.get_name() == "hookon_scan_on": + self._memobj.hookon_scan_on = element.value + + # "Set Mode" items + elif element.get_name() == "backlight": + self._memobj.backlight = element.value + elif element.get_name() == "backlight_set_enable": + self._memobj.backlight_set_enable = element.value + elif element.get_name() == "beep_on": + self._memobj.beep_on = element.value + elif element.get_name() == "beep_set_enable": + self._memobj.beep_set_enable = element.value + elif element.get_name() == "beep_level": + self._memobj.beep_level = element.value + elif element.get_name() == "beep_level_set_enable": + self._memobj.beep_level_set_enable = element.value + elif element.get_name() == "squelch_level": + self._memobj.squelch_level = element.value + elif element.get_name() == "squelch_level_set_enable": + self._memobj.squelch_level_set_enable = element.value + elif element.get_name() == "volume_min_level": + self._memobj.volume_min_level = element.value + elif element.get_name() == "volume_min_level_set_enable": + self._memobj.volume_min_level_set_enable = element.value + elif element.get_name() == "audio_filter": + self._memobj.audio_filter = element.value + elif element.get_name() == "audio_filter_set_enable": + self._memobj.audio_filter_set_enable = element.value + elif element.get_name() == "mic_gain": + self._memobj.mic_gain = mf_mc(element.value) + elif element.get_name() == "mic_gain_set_enable": + self._memobj.mic_gain_set_enable = element.value + elif element.get_name() == "horn_off": + self._memobj.horn_off = not element.value + elif element.get_name() == "horn_set_enable": + self._memobj.horn_set_enable = element.value + + # "Common" items + elif element.get_name() == "clone_comment": + self._memobj.clone_comment = str( + element.value).ljust(32)[:32] + elif element.get_name() == "password_on": + self._memobj.password_on = element.value + elif element.get_name() == "data_out_on": + self._memobj.data_out_on = element.value + elif element.get_name() == "timer_auto_reset_a": + self._memobj.timer.auto_reset_a = element.value + elif element.get_name() == "timer_auto_reset_b": + self._memobj.timer.auto_reset_b = element.value + elif element.get_name() == "timer_time_out": + self._memobj.timer.time_out = element.value + elif element.get_name() == "timer_penalty": + self._memobj.timer.penalty = element.value + elif element.get_name() == "dtmf_id_out_on": + self._memobj.dtmf_id_out_on = element.value + elif element.get_name() == "time_out_timer_beep_on": + self._memobj.time_out_timer_beep_on = element.value + elif element.get_name() == "timer_lockout_penalty": + self._memobj.timer.lockout_penalty = element.value + elif element.get_name() == "timer_eptt_delay": + self._memobj.timer.eptt_delay = element.value * 10.0 + elif element.get_name() == "tone_mute_eptt_on": + self._memobj.tone_mute_eptt_on = element.value + elif element.get_name() == "exo_on": + self._memobj.tone_mute_eptt_on = element.value + elif element.get_name() == "timer_exo_delay": + self._memobj.timer.exo_delay = element.value * 10.0 + elif element.get_name() == "timer_horn": + self._memobj.timer.horn = element.value + elif element.get_name() == "scrambler_non_rolling": + self._memobj.scrambler_non_rolling = element.value + elif element.get_name() == "scrambler_group_code": + self._memobj.scrambler_group_code = element.value + elif element.get_name() == "scrambler_syn_capture": + self._memobj.scrambler_syn_capture = sf_sc(element.value) + elif element.get_name() == "scrambler_tone_start_timing": + self._memobj.scrambler_tone_start_timing = element.value + elif element.get_name() == "timer_emergency_switch_on": + self._memobj.timer.emergency_switch_on = element.value * 10.0 + elif element.get_name() == "timer_emergency_switch_off": + self._memobj.timer.emergency_switch_off = element.value * 10.0 + elif element.get_name() == "emergency_start_repeat": + self._memobj.timer.emergency_start_repeat = element.value + else: + LOG.warning( + 'Attempt to set _memobj.%s to "%s"' + % (element.get_name(), element.value)) diff --git a/chirp/drivers/icm710.py b/chirp/drivers/icm710.py index fe999e4..17a5a13 100644 --- a/chirp/drivers/icm710.py +++ b/chirp/drivers/icm710.py @@ -90,6 +90,7 @@ class IcomM710Radio(icf.IcomCloneModeRadio): rf.can_odd_split = True rf.valid_modes = MODULATION_MODES rf.valid_power_levels = POWER_LEVELS + rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + '/-' rf.valid_tones = [] rf.valid_tmodes = [] rf.valid_skips = [] diff --git a/chirp/drivers/icomciv.py b/chirp/drivers/icomciv.py index dd10f6a..ea87a63 100644 --- a/chirp/drivers/icomciv.py +++ b/chirp/drivers/icomciv.py @@ -1,4 +1,4 @@ -# Latest update: April, 2021 Add hasattr test at line 564 +# Latest update: Jan, 2025 add IC7410 support import struct import logging from chirp.drivers import icf @@ -239,6 +239,34 @@ bbcd dtcs_tx[2]; char name[8]; """ +MEM_IC7410_FORMAT = """ +bbcd number[2]; +u8 duplex:4, // 3 split and select memory settings + select:4; +lbcd freq[5]; +u8 mode; +u8 filter; +u8 unknown2:7, + dig:1; +u8 unknown3:6, + tmode:2; +bbcd rtone[3]; +bbcd ctone[3]; +// As with IC-7300 it seems the following are duplicated parameters save for +// `dig` which seem to be zeroed in unknown5 +lbcd duplexOffset[5]; +u8 mode_tx; +u8 filter_tx; +u8 unknown5:7, + dig_tx:1; +u8 unknown6:6, + skip:2; +bbcd rtone_tx[3]; +bbcd ctone_tx[3]; +// End TX duplicate block +char name[9]; +""" + MEM_IC7610_FORMAT = """ bbcd number[2]; // 1,2 u8 spl:4, // 3 split and select memory settings @@ -410,6 +438,12 @@ class IC7400MemFrame(MemFrame): return bitwise.parse(MEM_IC7400_FORMAT, self._data) +class IC7410MemFrame(MemFrame): + def get_obj(self): + self._data = MemoryMapBytes(bytes(self._data)) + return bitwise.parse(MEM_IC7410_FORMAT, self._data) + + class IC7300MemFrame(MemFrame): FORMAT = MEM_IC7300_FORMAT @@ -1059,6 +1093,68 @@ class Icom7400Radio(IcomCIVRadio): @directory.register +class Icom7410Radio(IcomCIVRadio): + """Icom IC-7410""" + MODEL = "IC-7410" + BAUD_RATE = 9600 + _model = "\x80" + _template = 99 + + _num_banks = 1 # Banks not supported + + _SPECIAL_CHANNELS = { + "P1": 100, + "P2": 101, + } + _SPECIAL_CHANNELS_REV = dict(zip(_SPECIAL_CHANNELS.values(), + _SPECIAL_CHANNELS.keys())) + + def _is_special(self, number): + return isinstance(number, str) or number > 99 + + def _get_special_info(self, number): + info = SpecialChannel() + if isinstance(number, str): + info.name = number + info.channel = self._SPECIAL_CHANNELS[number] + info.location = info.channel + else: + info.location = number + info.name = self._SPECIAL_CHANNELS_REV[number] + info.channel = info.location + return info + + def _initialize(self): + self._classes["mem"] = IC7410MemFrame + self._rf.has_bank = False + self._rf.has_dtcs_polarity = False + self._rf.has_dtcs = False + self._rf.has_ctone = True + self._rf.has_offset = False + self._rf.has_name = True + self._rf.has_tuning_step = False + self._rf.valid_modes = [ + "LSB", "USB", "AM", "CW", "RTTY", "FM", "CWR", "RTTYR", + "Data+LSB", "Data+USB", "Data+AM", "N/A", "N/A", "Data+FM" + ] + self._rf.valid_tmodes = ["", "Tone", "TSQL"] + self._rf.valid_duplexes = ["", "split"] + self._rf.valid_bands = [(30000, 60000000)] + self._rf.valid_tuning_steps = [] + self._rf.valid_skips = [] + self._rf.valid_name_length = 9 + self._rf.valid_characters = " !#$%&'()*+,-./" \ + "0123456789" \ + ":;<=>?" \ + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ + "[\\]^_" \ + "abcdefghijklmnopqrstuvwxyz" \ + "{|}~" + self._rf.memory_bounds = (1, 99) + self._rf.valid_special_chans = sorted(self._SPECIAL_CHANNELS.keys()) + + +@directory.register class Icom910Radio(IcomCIVRadio): """Icom IC-910""" MODEL = "IC-910" diff --git a/chirp/drivers/ict8.py b/chirp/drivers/ict8.py index 7e3805d..37484e5 100644 --- a/chirp/drivers/ict8.py +++ b/chirp/drivers/ict8.py @@ -118,7 +118,7 @@ class ICT8ARadio(icf.IcomCloneModeRadio): mem.tmode = TMODES[_flg.tmode] mem.skip = _flg.skip and "S" or "" if _name.name.get_raw(asbytes=False) != "\xFF\xFF\xFF\xFF": - mem.name = str(_name.name).rstrip() + mem.name = str(_name.name).rstrip().rstrip('\x00') return mem diff --git a/chirp/drivers/icw32.py b/chirp/drivers/icw32.py index 82689e0..1db6d1e 100644 --- a/chirp/drivers/icw32.py +++ b/chirp/drivers/icw32.py @@ -50,7 +50,7 @@ struct { left_scan_direction:1; u8 left_scanning:1, unknown4:7; -} state[1]; +} state; #seekto 0x0F20; struct { @@ -100,6 +100,7 @@ class ICW32ARadio(icf.IcomCloneModeRadio): rf.valid_tmodes = ["", "Tone", "TSQL"] rf.valid_name_length = 8 rf.valid_special_chans = sorted(_get_special().keys()) + rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + '-./' rf.valid_tuning_steps = [5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 30.0, 50.0] rf.has_sub_devices = self.VARIANT == "" diff --git a/chirp/drivers/icx90.py b/chirp/drivers/icx90.py index 2abf5e3..3c4e5d5 100644 --- a/chirp/drivers/icx90.py +++ b/chirp/drivers/icx90.py @@ -769,7 +769,7 @@ class ICx90Radio_tv(ICx90Radio): rf.valid_modes = list(TV_MODE) rf.valid_tmodes = [] rf.valid_duplexes = [""] - rf.valid_tuning_steps = [] + rf.valid_tuning_steps = [5.0] rf.valid_bands = [(46750000, 957750000)] rf.valid_skips = ["", "S"] rf.valid_name_length = TV_NAME_LENGTH diff --git a/chirp/drivers/id800.py b/chirp/drivers/id800.py index 8e8e87c..c2c5700 100644 --- a/chirp/drivers/id800.py +++ b/chirp/drivers/id800.py @@ -230,6 +230,7 @@ class ID800v2Radio(icf.IcomCloneModeRadio, chirp_common.IcomDstarSupport): rf.valid_bands = [(118000000, 173995000), (230000000, 549995000), (810000000, 999990000)] rf.valid_skips = ["", "S", "P"] + rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + '*' rf.valid_name_length = 6 rf.valid_special_chans = sorted(ID800_SPECIAL.keys()) rf.valid_power_levels = list(POWER_LEVELS) diff --git a/chirp/drivers/kenwood_live.py b/chirp/drivers/kenwood_live.py index f780b1c..79cffe1 100644 --- a/chirp/drivers/kenwood_live.py +++ b/chirp/drivers/kenwood_live.py @@ -47,6 +47,7 @@ THF6_MODES = ["FM", "WFM", "AM", "LSB", "USB", "CW"] RADIO_IDS = { + "ID007": "TS-790E", "ID019": "TS-2000", "ID009": "TS-850", "ID020": "TS-480_LiveMode", @@ -54,102 +55,6 @@ RADIO_IDS = { "ID023": "TS-590S/SG_LiveMode" # as SG } -LOCK = threading.Lock() -COMMAND_RESP_BUFSIZE = 8 -LAST_BAUD = 4800 -LAST_DELIMITER = ("\r", " ") - -# The Kenwood TS-2000, TS-480, TS-590 & TS-850 use ";" -# as a CAT command message delimiter, and all others use "\n". -# Also, TS-2000 and TS-590 don't space delimite the command -# fields, but others do. - - -def _command(ser, cmd, *args): - """Send @cmd to radio via @ser""" - global LOCK, LAST_DELIMITER, COMMAND_RESP_BUFSIZE - - start = time.time() - - # TODO: This global use of LAST_DELIMITER breaks reentrancy - # and needs to be fixed. - if args: - cmd += LAST_DELIMITER[1] + LAST_DELIMITER[1].join(args) - cmd += LAST_DELIMITER[0] - - LOG.debug("PC->RADIO: %s" % cmd.strip()) - ser.write(cmd.encode('cp1252')) - - result = "" - while not result.endswith(LAST_DELIMITER[0]): - result += ser.read(COMMAND_RESP_BUFSIZE).decode('cp1252') - if (time.time() - start) > 1: # TXH sometimes takes longer on TH-D7G - LOG.error("Timeout waiting for data") - break - - if result.endswith(LAST_DELIMITER[0]): - LOG.debug("RADIO->PC: %r" % result.strip()) - result = result[:-1] - else: - LOG.error("Giving up") - - return result.strip() - - -def command(ser, cmd, *args): - with LOCK: - return _command(ser, cmd, *args) - - -def get_id(ser): - """Get the ID of the radio attached to @ser""" - global LAST_BAUD - bauds = [4800, 9600, 19200, 38400, 57600, 115200] - bauds.remove(LAST_BAUD) - # Make sure LAST_BAUD is last so that it is tried first below - bauds.append(LAST_BAUD) - - global LAST_DELIMITER - command_delimiters = [("\r", " "), (";", "")] - - for delimiter in command_delimiters: - # Process the baud options in reverse order so that we try the - # last one first, and then start with the high-speed ones next - for i in reversed(bauds): - LAST_DELIMITER = delimiter - LOG.info("Trying ID at baud %i with delimiter \"%s\"" % - (i, repr(delimiter))) - ser.baudrate = i - ser.write(LAST_DELIMITER[0].encode()) - ser.read(25) - try: - resp = command(ser, "ID") - except UnicodeDecodeError: - # If we got binary here, we are using the wrong rate - # or not talking to a Kenwood live radio. - continue - - # most Kenwood radios - if " " in resp: - LAST_BAUD = i - return resp.split(" ")[1] - - # Radio responded in the right baud rate, - # but threw an error because of all the crap - # we have been hurling at it. Retry the ID at this - # baud rate, which will almost definitely work. - if "?" in resp: - resp = command(ser, "ID") - LAST_BAUD = i - if " " in resp: - return resp.split(" ")[1] - - # Kenwood radios that return ID numbers - if resp in list(RADIO_IDS.keys()): - return RADIO_IDS[resp] - - raise errors.RadioError("No response from radio") - def get_tmode(tone, ctcss, dcs): """Get the tone mode based on the values of the tone, ctcss, dcs""" @@ -187,15 +92,101 @@ class KenwoodLiveRadio(chirp_common.LiveRadio): chirp_common.LiveRadio.__init__(self, *args, **kwargs) self._memcache = {} + self.LOCK = threading.Lock() + self.LAST_BAUD = 4800 + self.LAST_DELIMITER = ("\r", " ") if self.pipe: self.pipe.timeout = 0.1 - radio_id = get_id(self.pipe) + radio_id = self.get_id(self.pipe) if radio_id != self.MODEL.split(" ")[0]: raise Exception("Radio reports %s (not %s)" % (radio_id, self.MODEL)) - command(self.pipe, "AI", "0") + self.command(self.pipe, "AI", "0") + + # The Kenwood TS-2000, TS-480, TS-590 & TS-850 use ";" + # as a CAT command message delimiter, and all others use "\n". + # Also, TS-2000 and TS-590 don't space delimite the command + # fields, but others do. + def get_id(self, ser): + """Get the ID of the radio attached to @ser""" + bauds = [4800, 9600, 19200, 38400, 57600, 115200] + bauds.remove(self.LAST_BAUD) + # Make sure LAST_BAUD is last so that it is tried first below + bauds.append(self.LAST_BAUD) + + command_delimiters = [("\r", " "), (";", "")] + + for delimiter in command_delimiters: + # Process the baud options in reverse order so that we try the + # last one first, and then start with the high-speed ones next + for i in reversed(bauds): + self.LAST_DELIMITER = delimiter + LOG.info("Trying ID at baud %i with delimiter \"%s\"" % + (i, repr(delimiter))) + ser.baudrate = i + ser.write(self.LAST_DELIMITER[0].encode()) + ser.read(25) + try: + resp = self.command(ser, "ID") + except UnicodeDecodeError: + # If we got binary here, we are using the wrong rate + # or not talking to a Kenwood live radio. + continue + + # most Kenwood radios + if " " in resp: + self.LAST_BAUD = i + return resp.split(" ")[1] + + # Radio responded in the right baud rate, + # but threw an error because of all the crap + # we have been hurling at it. Retry the ID at this + # baud rate, which will almost definitely work. + if "?" in resp: + resp = self.command(ser, "ID") + self.LAST_BAUD = i + if " " in resp: + return resp.split(" ")[1] + + # Kenwood radios that return ID numbers + if resp in list(RADIO_IDS.keys()): + return RADIO_IDS[resp] + + raise errors.RadioError("No response from radio") + + def _command(self, ser, cmd, *args): + """Send @cmd to radio via @ser""" + + start = time.time() + + if args: + cmd += self.LAST_DELIMITER[1] + self.LAST_DELIMITER[1].join(args) + cmd += self.LAST_DELIMITER[0] + + LOG.debug("PC->RADIO: %s" % cmd.strip()) + ser.write(cmd.encode('cp1252')) + + result = "" + while not result.endswith(self.LAST_DELIMITER[0]): + result += ser.read(8).decode('cp1252') + if (time.time() - start) > 1: + # TXH sometimes takes longer on TH-D7G + LOG.error("Timeout waiting for data") + break + + if result.endswith(self.LAST_DELIMITER[0]): + LOG.debug("RADIO->PC: %r" % result.strip()) + result = result[:-1] + else: + LOG.error("Giving up") + + return result.strip() + + def command(self, ser, cmd, *args): + with self.LOCK: + return self._command(ser, cmd, *args) def _cmd_get_memory(self, number): return "MR", "%i,0,%03i" % (self._vfo, number) @@ -218,7 +209,7 @@ class KenwoodLiveRadio(chirp_common.LiveRadio): return "MW", "%i,1,%03i,%s" % (self._vfo, number, spec) def get_raw_memory(self, number): - return command(self.pipe, *self._cmd_get_memory(number)) + return self.command(self.pipe, *self._cmd_get_memory(number)) def get_memory(self, number): if number < 0 or number > self._upper: @@ -227,7 +218,7 @@ class KenwoodLiveRadio(chirp_common.LiveRadio): if number in self._memcache and not NOCACHE: return self._memcache[number] - result = command(self.pipe, *self._cmd_get_memory(number)) + result = self.command(self.pipe, *self._cmd_get_memory(number)) if result == "N" or result == "E": mem = chirp_common.Memory() mem.number = number @@ -245,7 +236,8 @@ class KenwoodLiveRadio(chirp_common.LiveRadio): self._memcache[mem.number] = mem if self._has_name: - result = command(self.pipe, *self._cmd_get_memory_name(number)) + result = self.command(self.pipe, + *self._cmd_get_memory_name(number)) if " " in result: value = result.split(" ", 1)[1] if value.count(",") == 2: @@ -254,7 +246,7 @@ class KenwoodLiveRadio(chirp_common.LiveRadio): _loc, mem.name = value.split(",") if mem.duplex == "" and self._kenwood_split: - result = command(self.pipe, *self._cmd_get_split(number)) + result = self.command(self.pipe, *self._cmd_get_split(number)) if " " in result: value = result.split(" ", 1)[1] self._parse_split_spec(mem, value.split(",")) @@ -281,14 +273,16 @@ class KenwoodLiveRadio(chirp_common.LiveRadio): spec = self._make_mem_spec(memory) spec = ",".join(spec) - r1 = command(self.pipe, *self._cmd_set_memory(memory.number, spec)) + del self._memcache[memory.number] + r1 = self.command(self.pipe, + *self._cmd_set_memory(memory.number, spec)) if not iserr(r1) and self._has_name: time.sleep(0.5) - r2 = command(self.pipe, *self._cmd_set_memory_name(memory.number, - memory.name)) + r2 = self.command( + self.pipe, + *self._cmd_set_memory_name(memory.number, memory.name)) if not iserr(r2): memory.name = memory.name.rstrip() - self._memcache[memory.number] = memory.dupe() else: raise errors.InvalidDataError("Radio refused name %i: %s" % (memory.number, @@ -298,8 +292,8 @@ class KenwoodLiveRadio(chirp_common.LiveRadio): if memory.duplex == "split" and self._kenwood_split: spec = ",".join(self._make_split_spec(memory)) - result = command(self.pipe, *self._cmd_set_split(memory.number, - spec)) + result = self.command(self.pipe, + *self._cmd_set_split(memory.number, spec)) if iserr(result): raise errors.InvalidDataError("Radio refused %i" % memory.number) @@ -308,13 +302,13 @@ class KenwoodLiveRadio(chirp_common.LiveRadio): if number not in self._memcache: return - resp = command(self.pipe, *self._cmd_set_memory(number, "")) + resp = self.command(self.pipe, *self._cmd_set_memory(number, "")) if iserr(resp): raise errors.RadioError("Radio refused delete of %i" % number) del self._memcache[number] def _kenwood_get(self, cmd): - resp = command(self.pipe, cmd) + resp = self.command(self.pipe, cmd) if " " in resp: return resp.split(" ", 1) else: @@ -324,7 +318,7 @@ class KenwoodLiveRadio(chirp_common.LiveRadio): raise errors.RadioError("Radio refused to return %s" % cmd) def _kenwood_set(self, cmd, value): - resp = command(self.pipe, cmd, value) + resp = self.command(self.pipe, cmd, value) if resp[:len(cmd)] == cmd: return raise errors.RadioError("Radio refused to set %s" % cmd) @@ -1280,8 +1274,8 @@ class TS590Radio(KenwoodLiveRadio): mem.extra = RadioSettingGroup("extra", "Extra") # Read the base and split MR strings mem.number = number - spec0 = command(self.pipe, "MR0 %02i" % mem.number) - spec1 = command(self.pipe, "MR1 %02i" % mem.number) + spec0 = self.command(self.pipe, "MR0 %02i" % mem.number) + spec1 = self.command(self.pipe, "MR1 %02i" % mem.number) mem.name = spec0[41:49] # Max 8-Char Name if assigned mem.name = mem.name.strip() mem.name = mem.name.upper() @@ -1343,7 +1337,7 @@ class TS590Radio(KenwoodLiveRadio): mem.freq = 0 mem.offset = 0 spx = "MW0%03i00000000000000000000000000000000000" % number - rx = command(self.pipe, spx) # Send MW0 + rx = self.command(self.pipe, spx) # Send MW0 return mem def set_memory(self, mem): @@ -1387,7 +1381,7 @@ class TS590Radio(KenwoodLiveRadio): spx = "%011i%1i%1i%1i%02i%02i000%1i0000000000%02i%1i%s" \ % (xfreq, xmode, xdata, xtmode, xrtone, xctone, xfltr, xfm, xskip, mem.name) - rx = command(self.pipe, pfx, spx) # Send MW0 + rx = self.command(self.pipe, pfx, spx) # Send MW0 if mem.offset != 0: pfx = "MW1%03i" % mem.number xfreq = mem.freq - mem.offset @@ -1396,7 +1390,7 @@ class TS590Radio(KenwoodLiveRadio): spx = "%011i%1i%1i%1i%02i%02i000%1i0000000000%02i%1i%s" \ % (xfreq, xmode, xdata, xtmode, xrtone, xctone, xfltr, xfm, xskip, mem.name) - rx = command(self.pipe, pfx, spx) # Send MW1 + rx = self.command(self.pipe, pfx, spx) # Send MW1 @directory.register @@ -1469,8 +1463,8 @@ class TS480Radio(KenwoodLiveRadio): mem = chirp_common.Memory() # Read the base and split MR strings mem.number = number - spec0 = command(self.pipe, "MR0%03i" % mem.number) - spec1 = command(self.pipe, "MR1%03i" % mem.number) + spec0 = self.command(self.pipe, "MR0%03i" % mem.number) + spec1 = self.command(self.pipe, "MR1%03i" % mem.number) # Add 1 to string idecis if referring to CAT manual mem.name = spec0[41:49] # Max 8-Char Name if assigned mem.name = mem.name.strip() @@ -1523,7 +1517,7 @@ class TS480Radio(KenwoodLiveRadio): mem.freq = 0 mem.offset = 0 spx = "MW0%03i00000000000000000000000000000000000" % number - rx = command(self.pipe, spx) # Send MW0 + rx = self.command(self.pipe, spx) # Send MW0 return mem def set_memory(self, mem): @@ -1558,7 +1552,7 @@ class TS480Radio(KenwoodLiveRadio): spx = "%011i%1i%1i%1i%02i%02i00000000000000%02i%s" \ % (xfreq, xmode, xskip, xtmode, xrtone, xctone, xstep, mem.name) - rx = command(self.pipe, pfx, spx) # Send MW0 + rx = self.command(self.pipe, pfx, spx) # Send MW0 if mem.offset != 0: # Don't send MW1 if empty pfx = "MW1%03i" % mem.number xfreq = mem.freq - mem.offset @@ -1567,4 +1561,4 @@ class TS480Radio(KenwoodLiveRadio): spx = "%011i%1i%1i%1i%02i%02i00000000000000%02i%s" \ % (xfreq, xmode, xskip, xtmode, xrtone, xctone, xstep, mem.name) - rx = command(self.pipe, pfx, spx) # Send MW1 + rx = self.command(self.pipe, pfx, spx) # Send MW1 diff --git a/chirp/drivers/kguv920pa.py b/chirp/drivers/kguv920pa.py index 04a1479..049fe52 100644 --- a/chirp/drivers/kguv920pa.py +++ b/chirp/drivers/kguv920pa.py @@ -788,6 +788,12 @@ class KGUV920PARadio(chirp_common.CloneModeRadio, _mem.rxfreq = 0xFFFFFFFF return + # Zero the entire structure and set these fields to default values + # instead of leaving unused fields as FF + _mem.fill_raw(b'\x00') + _mem.unknown2_32 = 0x02 + _mem.mute_mode = 0x01 + _mem.rxfreq = _freq_encode(mem.freq) if mem.duplex == "off": _mem.txfreq = 0xFFFFFFFF diff --git a/chirp/drivers/mml_jc8810.py b/chirp/drivers/mml_jc8810.py index 3ce988c..f21eeee 100644 --- a/chirp/drivers/mml_jc8810.py +++ b/chirp/drivers/mml_jc8810.py @@ -553,7 +553,7 @@ class JC8810base(chirp_common.CloneModeRadio): if str(char) == "\xFF": char = " " # may have 0xFF mid-name mem.name += str(char) - mem.name = mem.name.rstrip() + mem.name = mem.name.rstrip().replace('\x00', '') dtcs_pol = ["N", "N"] diff --git a/chirp/drivers/puxing.py b/chirp/drivers/puxing.py index c7ab2e8..b49801a 100644 --- a/chirp/drivers/puxing.py +++ b/chirp/drivers/puxing.py @@ -106,7 +106,7 @@ struct { struct { u8 limits; u8 model; -} model[1]; +} model; #seekto 0x0850; struct { diff --git a/chirp/drivers/radtel_t18.py b/chirp/drivers/radtel_t18.py index bca31d1..3337d18 100644 --- a/chirp/drivers/radtel_t18.py +++ b/chirp/drivers/radtel_t18.py @@ -56,9 +56,10 @@ struct { #seekto 0x03C0; struct { u8 codesw:1, // Retevis RB29 code switch + // Retevis H777H code switch scanmode:1, vox:1, // Retevis RB19 VOX - speccode:1, + speccode:1, // Retevis H777H VOX voiceprompt:2, batterysaver:1, beep:1; // Retevis RB87 vox @@ -68,6 +69,7 @@ struct { // Retevis RB19 sidekey 2 long // Retevis RT47 sidekey 1 long // Retevis RB87 sidekey 1 long + // Retevis H777H roger u8 timeouttimer; u8 voxlevel; u8 sidekey2S; @@ -176,10 +178,6 @@ VOICE_LIST = ["Off", "Chinese", "English"] VOICE_LIST2 = ["English", "Chinese"] VOICE_LIST3 = ["Off", "English", "Chinese"] VOICE_LIST4 = ["Chinese", "English"] -TIMEOUTTIMER_LIST = ["Off", "30 seconds", "60 seconds", "90 seconds", - "120 seconds", "150 seconds", "180 seconds", - "210 seconds", "240 seconds", "270 seconds", - "300 seconds"] SCANMODE_LIST = ["Carrier", "Time"] VOXLEVEL_LIST = ["Off", "1", "2", "3", "4", "5", "6", "7", "8", "9"] VOXDELAY_LIST = ["0.5 seconds", "1.0 seconds", "1.5 seconds", @@ -223,6 +221,10 @@ SIDEKEYV8A_LIST = ["Off", "High/Low Power", "Alarm"] SIDEKEY87_LIST = ["Scan", "Emergency Alarm"] +SIDEKEYH777H_LIST = ["Off", + "VOX", + "SCAN", + "Monitor"] FRS_FREQS1 = [462562500, 462587500, 462612500, 462637500, 462662500, 462687500, 462712500] @@ -427,6 +429,11 @@ class T18Radio(chirp_common.CloneModeRadio): VALID_BANDS = [(400000000, 470000000)] + TIMEOUTTIMER_LIST = ["Off", "30 seconds", "60 seconds", "90 seconds", + "120 seconds", "150 seconds", "180 seconds", + "210 seconds", "240 seconds", "270 seconds", + "300 seconds"] + _magic = b"1ROGRAM" _fingerprint = [b"SMP558" + b"\x00\x00"] _upper = 16 @@ -434,6 +441,7 @@ class T18Radio(chirp_common.CloneModeRadio): ) _frs = _frs16 = _murs = _pmr = _gmrs = False _echo = False + _reserved = False _ranges = [ (0x0000, 0x03F0), @@ -515,6 +523,10 @@ class T18Radio(chirp_common.CloneModeRadio): mem = chirp_common.Memory() mem.number = number + + if self._reserved: + _rsvd = _mem.unknown3.get_raw() + mem.freq = int(_mem.rxfreq) * 10 # We'll consider any blank (i.e. 0 MHz frequency) to be empty @@ -657,23 +669,31 @@ class T18Radio(chirp_common.CloneModeRadio): # Get a low-level memory object mapped to the image _mem = self._memobj.memory[mem.number - 1] + if self._reserved: + _rsvd = _mem.unknown3.get_raw() + if mem.empty: - _mem.set_raw("\xFF" * (_mem.size() // 8)) + if self._reserved: + _mem.set_raw(b"\xFF" * 13 + _rsvd) + else: + _mem.set_raw(b"\xFF" * (_mem.size() // 8)) return - if self.MODEL == "BF-V8A" or self.MODEL == "BF-T20FRS": - _mem.set_raw("\x00" * 12 + "\x09\xFF\xFF\xFF") + if self._reserved: + _mem.set_raw(b"\x00" * 13 + _rsvd) + elif self.MODEL == "BF-V8A" or self.MODEL == "BF-T20FRS": + _mem.set_raw(b"\x00" * 12 + b"\x09\xFF\xFF\xFF") elif self.MODEL == "RB29" or self.MODEL == "RB629": - _mem.set_raw("\x00" * 12 + "\xF7\xFF\xFF\xFF") + _mem.set_raw(b"\x00" * 12 + b"\xF7\xFF\xFF\xFF") else: - _mem.set_raw("\x00" * 12 + "\xF9\xFF\xFF\xFF") + _mem.set_raw(b"\x00" * 12 + b"\xF9\xFF\xFF\xFF") _mem.rxfreq = mem.freq / 10 if mem.duplex == "off": for i in range(0, 4): - _mem.txfreq[i].set_raw("\xFF") + _mem.txfreq[i].set_raw(b"\xFF") elif mem.duplex == "split": _mem.txfreq = mem.offset / 10 elif mem.duplex == "+": @@ -693,6 +713,8 @@ class T18Radio(chirp_common.CloneModeRadio): _mem.narrow = 'N' in mem.mode _mem.skip = mem.skip == "S" + _mem.unknown2 = 1 + for setting in mem.extra: # NOTE: Only three settings right now, all are inverted setattr(_mem, setting.get_name(), not int(setting.value)) @@ -712,7 +734,7 @@ class T18Radio(chirp_common.CloneModeRadio): rs = RadioSetting("timeouttimer", "Timeout timer", RadioSettingValueList( - TIMEOUTTIMER_LIST, + self.TIMEOUTTIMER_LIST, current_index=_settings.timeouttimer)) basic.append(rs) @@ -1020,6 +1042,25 @@ class T18Radio(chirp_common.CloneModeRadio): current_index=_settings.sidekey2L)) basic.append(rs) + if self.MODEL == "H777H_FRS" or self.MODEL == "H777H_PMR": + rs = RadioSetting("codesw", "Code Switch", + RadioSettingValueBoolean(_settings.codesw)) + basic.append(rs) + + rs = RadioSetting("speccode", "VOX", + RadioSettingValueBoolean(_settings.speccode)) + basic.append(rs) + + rs = RadioSetting("sidekey2L", "Side Key 2(Long)", + RadioSettingValueList( + SIDEKEYH777H_LIST, + current_index=_settings.sidekey2L)) + basic.append(rs) + + rs = RadioSetting("sidekey2", "Roger", + RadioSettingValueBoolean(_settings.sidekey2)) + basic.append(rs) + return top def set_settings(self, settings): @@ -1504,3 +1545,39 @@ class BFT20FRSRadio(T18Radio): def process_mmap(self): self._memobj = bitwise.parse(MEM_FORMAT_T20FRS % self._mem_params, self._mmap) + + +@directory.register +class H777HFRSRadio(T18Radio): + """Retevis H777H FRS""" + VENDOR = "Retevis" + MODEL = "H777H_FRS" # SKU: A9104J + ACK_BLOCK = False + + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.000), + chirp_common.PowerLevel("Low", watts=0.500)] + + TIMEOUTTIMER_LIST = ["Off", "30 seconds", "60 seconds", "90 seconds", + "120 seconds", "150 seconds", "180 seconds"] + + _magic = b"C701RAD" + _fingerprint = [b"SMP558" + b"\x02"] + _upper = 16 + _mem_params = (_upper # number of channels + ) + _reserved = True + _frs16 = True + _pmr = False + + +@directory.register +class H777HPMRRadio(H777HFRSRadio): + """Retevis H777H PMR""" + VENDOR = "Retevis" + MODEL = "H777H_PMR" # SKU: A9104K + + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=0.500), + chirp_common.PowerLevel("Low", watts=0.500)] + + _frs16 = False + _pmr = True diff --git a/chirp/drivers/retevis_rt21.py b/chirp/drivers/retevis_rt21.py index b060eea..01187ff 100644 --- a/chirp/drivers/retevis_rt21.py +++ b/chirp/drivers/retevis_rt21.py @@ -147,7 +147,7 @@ struct { bcl:1, // Busy Lock OFF=0 ON=1 unknown2:3; // u8 reserved[3]; // Reserved D-F -} memory[30]; +} memory[%(memcnt)d]; #seekto 0x002D; struct { @@ -179,7 +179,7 @@ struct { u8 tailmode; // QT/DQT Tail Mode 007F } settings; -#seekto 0x01F0; +#seekto %(settings_offset)s; u8 skipflags[4]; // Scan Add #seekto 0x029F; @@ -767,6 +767,8 @@ class RT21Radio(chirp_common.CloneModeRadio): _skipflags = True _reserved = False _mask = 0x2000 # bit mask to identify DTCS tone decoding is used + _dcs_octal = 0x0800 # bit mask to identify DTCS stored in octal + _dcs_inverse = 0x8000 # bit mask to identify inverted DTCS codes _gmrs = _frs = _pmr = False _echo = False @@ -839,9 +841,29 @@ class RT21Radio(chirp_common.CloneModeRadio): return repr(self._memobj.memory[number - 1]) def _get_tone(self, _mem, mem): + # 0xA662 = 662R = 1010 0... + # 0xA9DC = 734R = 1010 1... + # 0x29D3 = 723N - 0010 1... + def _get_dcs(val): - code = int("%03o" % (val & 0x07FF)) - pol = (val & 0x8000) and "R" or "N" + # 0x0800 means code is stored in hex instead of ocal (?!) + if val & self._dcs_octal: + code = int("%03o" % (val & 0x07FF)) + else: + try: + code = int("%03x" % (val & 0x07FF)) + if code not in chirp_common.DTCS_CODES: + raise ValueError('DCS code assumed to be wrong') + except ValueError: + # Memories may have been stored as octal but without the + # proper bit flag in the past, so if we see something + # recorded as "should be hex" but interpretation as hex + # yields an invalid code, assume it's actually octal and + # parse it as such. + LOG.warning('Trying DCS conversion of 0x%04x as octal ' + 'for compatibility', val) + code = int("%03o" % (val & 0x07FF)) + pol = (val & self._dcs_inverse) and "R" or "N" return code, pol tpol = False @@ -1129,9 +1151,10 @@ class RT21Radio(chirp_common.CloneModeRadio): def _set_tone(self, mem, _mem): def _set_dcs(code, pol): - val = int("%i" % code, 8) + self._mask + val = int("%i" % code, 8) if pol == "R": - val += 0x8000 + val |= self._dcs_inverse + val |= self._mask | self._dcs_octal return val rx_mode = tx_mode = None @@ -1919,7 +1942,6 @@ class RB26Radio(RT21Radio): _ack_1st_block = False _skipflags = True _reserved = True - _mask = 0x2800 # bit mask to identify DTCS tone decoding is used _gmrs = True _ranges = [ @@ -1928,14 +1950,40 @@ class RB26Radio(RT21Radio): _memsize = 0x0320 def process_mmap(self): - self._memobj = bitwise.parse(MEM_FORMAT_RB26, self._mmap) + mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0'} + self._memobj = bitwise.parse(MEM_FORMAT_RB26 % mem_params, self._mmap) @directory.register -class RB626(RB26Radio): - MODEL = 'RB626' +class RB626(RT21Radio): + """RETEVIS RB626""" + VENDOR = "Retevis" + MODEL = "RB626" + BAUD_RATE = 9600 + BLOCK_SIZE = 0x20 + BLOCK_SIZE_UP = 0x10 + + DTCS_CODES = DTCS_EXTRA + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=3.00), + chirp_common.PowerLevel("Low", watts=0.50)] + + _magic = b"PHOGR" + b"\x01" + b"0" + _fingerprint = [b"P32073" + b"\x02\xFF", ] + _upper = 32 + _ack_1st_block = False + _skipflags = True + _reserved = True _gmrs = False + _ranges = [ + (0x0000, 0x0320), + ] + _memsize = 0x0320 + + def process_mmap(self): + mem_params = {'memcnt': self._upper, 'settings_offset': '0x0200'} + self._memobj = bitwise.parse(MEM_FORMAT_RB26 % mem_params, self._mmap) + @directory.register class RT76Radio(RT21Radio): @@ -1956,7 +2004,6 @@ class RT76Radio(RT21Radio): _ack_1st_block = False _skipflags = False _reserved = True - _mask = 0x2800 # bit mask to identify DTCS tone decoding is used _gmrs = True _ranges = [ @@ -2038,7 +2085,6 @@ class RB23Radio(RT21Radio): _ack_1st_block = False _skipflags = True _reserved = True - _mask = 0x2800 # bit mask to identify DTCS tone decoding is used _gmrs = True _ranges = [ @@ -2047,7 +2093,8 @@ class RB23Radio(RT21Radio): _memsize = 0x0320 def process_mmap(self): - self._memobj = bitwise.parse(MEM_FORMAT_RB26, self._mmap) + mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0'} + self._memobj = bitwise.parse(MEM_FORMAT_RB26 % mem_params, self._mmap) @directory.register @@ -2071,7 +2118,6 @@ class RT19Radio(RT21Radio): _ack_1st_block = False _skipflags = False _reserved = True - _mask = 0x2800 # bit mask to identify DTCS tone decoding is used _frs = True _ranges = [ @@ -2100,7 +2146,6 @@ class RT619Radio(RT19Radio): 0x100, # memory start _upper # number of freqhops ) - _mask = 0x2800 # bit mask to identify DTCS tone decoding is used _frs = False _pmr = True @@ -2128,7 +2173,6 @@ class AR63Radio(RT21Radio): _ack_1st_block = False _skipflags = True _reserved = True - _mask = 0x2800 # bit mask to identify DTCS tone decoding is used _gmrs = False _ranges = [ @@ -2162,7 +2206,6 @@ class RT40BRadio(RT21Radio): _ack_1st_block = False _skipflags = True _reserved = True - _mask = 0x2800 # bit mask to identify DTCS tone decoding is used _gmrs = True _echo = True @@ -2194,7 +2237,6 @@ class RB28BRadio(RT21Radio): _ack_1st_block = False _skipflags = False _reserved = True - _mask = 0x2800 # bit mask to identify DTCS tone decoding is used _frs = True _ranges = [ @@ -2218,7 +2260,6 @@ class RB628BRadio(RB28BRadio): _magic = b"PHOGR\x09\xB2" _fingerprint = [b"P32073" + b"\x02\xFF", ] _upper = 16 - _mask = 0x2800 # bit mask to identify DTCS tone decoding is used _frs = False _pmr = True @@ -2243,7 +2284,6 @@ class RT86Radio(RT21Radio): _ack_1st_block = False _skipflags = True _reserved = True - _mask = 0x2800 # bit mask to identify DTCS tone decoding is used _ranges = [ (0x0000, 0x01A0), @@ -2279,4 +2319,5 @@ class RB89Radio(RT21Radio): _memsize = 0x0340 def process_mmap(self): - self._memobj = bitwise.parse(MEM_FORMAT_RB26, self._mmap) + mem_params = {'memcnt': self._upper, 'settings_offset': '0x01F0'} + self._memobj = bitwise.parse(MEM_FORMAT_RB26 % mem_params, self._mmap) diff --git a/chirp/drivers/rh5r_v2.py b/chirp/drivers/rh5r_v2.py index 7850c2d..2f9155c 100644 --- a/chirp/drivers/rh5r_v2.py +++ b/chirp/drivers/rh5r_v2.py @@ -26,9 +26,9 @@ LOG = logging.getLogger(__name__) def _identify(radio): try: - radio.pipe.write("PGM2015") + radio.pipe.write(b"PGM2015") ack = radio.pipe.read(2) - if ack != "\x06\x30": + if ack != b"\x06\x30": raise errors.RadioError("Radio did not ACK first command: %r" % ack) except: @@ -40,7 +40,7 @@ def _download(radio): _identify(radio) data = [] for i in range(0, 0x2000, 0x40): - msg = struct.pack('>cHb', 'R', i, 0x40) + msg = struct.pack('>cHb', b'R', i, 0x40) radio.pipe.write(msg) block = radio.pipe.read(0x40 + 4) if len(block) != (0x40 + 4): @@ -55,20 +55,20 @@ def _download(radio): status.msg = "Cloning from radio" radio.status_fn(status) - radio.pipe.write("E") - data += 'PGM2015' + data = bytes(data) + data += b'PGM2015' - return memmap.MemoryMap(data) + return memmap.MemoryMapBytes(data) def _upload(radio): _identify(radio) for i in range(0, 0x2000, 0x40): - msg = struct.pack('>cHb', 'W', i, 0x40) + msg = struct.pack('>cHb', b'W', i, 0x40) msg += radio._mmap[i:(i + 0x40)] radio.pipe.write(msg) ack = radio.pipe.read(1) - if ack != '\x06': + if ack != b'\x06': raise errors.RadioError('Radio did not ACK block %i (0x%04x)' % ( i, i)) @@ -79,8 +79,6 @@ def _upload(radio): status.msg = "Cloning from radio" radio.status_fn(status) - radio.pipe.write("E") - MEM_FORMAT = """ struct memory { @@ -126,7 +124,6 @@ class TYTTHUVF8_V2(chirp_common.CloneModeRadio): MODEL = "TH-UVF8F" BAUD_RATE = 9600 _FILEID = b'OEMOEM \\XFF' - NEEDS_COMPAT_SERIAL = True def get_features(self): rf = chirp_common.RadioFeatures() @@ -153,11 +150,24 @@ class TYTTHUVF8_V2(chirp_common.CloneModeRadio): return rf def sync_in(self): - self._mmap = _download(self) + try: + self._mmap = _download(self) + finally: + try: + self.pipe.write(b"E") + except Exception: + pass + self.process_mmap() def sync_out(self): - _upload(self) + try: + _upload(self) + finally: + try: + self.pipe.write(b"E") + except Exception: + pass @classmethod def match_model(cls, filedata, filename): @@ -221,7 +231,7 @@ class TYTTHUVF8_V2(chirp_common.CloneModeRadio): else: mem.number = number - if _mem.get_raw(asbytes=False).startswith("\xFF\xFF\xFF\xFF"): + if _mem.get_raw().startswith(b"\xFF\xFF\xFF\xFF"): mem.empty = True return mem @@ -254,10 +264,10 @@ class TYTTHUVF8_V2(chirp_common.CloneModeRadio): def set_memory(self, mem): _mem, _name = self._get_memobjs(mem.number) if mem.empty: - _mem.set_raw('\xFF' * 16) - _name.set_raw('\xFF' * 7) + _mem.set_raw(b'\xFF' * 16) + _name.set_raw(b'\xFF' * 7) return - _mem.set_raw('\x00' * 16) + _mem.set_raw(b'\x00' * 16) _mem.rx_freq = mem.freq / 10 if mem.duplex == '-': diff --git a/chirp/drivers/tdh8.py b/chirp/drivers/tdh8.py index 3b4c9bd..ccaa2ff 100644 --- a/chirp/drivers/tdh8.py +++ b/chirp/drivers/tdh8.py @@ -703,10 +703,6 @@ 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"] -ASTEP_LIST = ["2.50K", "5.00K", "6.25K", - "10.00K", "12.00K", "25.00K", "50.00K"] -BSTEP_LIST = ["2.50K", "5.00K", "6.25K", - "10.00K", "12.00K", "25.00K", "50.00K"] SCAN_MODE_LIST = ["TO", "CO", "SE"] PRIO_LIST = ["Edit", "Busy"] SHORT_KEY_LIST = ["None", "FM Radio", "Lamp", "Monitor", @@ -804,7 +800,6 @@ 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"] -PONMSG_LIST = ["Full", "Message", "Icon"] 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"] @@ -1053,6 +1048,7 @@ 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"] @classmethod def detect_from_serial(cls, pipe): @@ -1496,13 +1492,13 @@ class TDH8(chirp_common.CloneModeRadio): if self.MODEL != "RT-730": rs = RadioSetting("astep", "A Step", RadioSettingValueList( - ASTEP_LIST, + STEP_LIST, current_index=_settings.astep)) basic.append(rs) rs = RadioSetting("bstep", "B Step", RadioSettingValueList( - BSTEP_LIST, + STEP_LIST, current_index=_settings.bstep)) basic.append(rs) @@ -1649,7 +1645,7 @@ class TDH8(chirp_common.CloneModeRadio): rs = RadioSetting("ponmsg", "Power-On Message", RadioSettingValueList( - PONMSG_LIST, + self._ponmsg_list, current_index=_settings.ponmsg)) basic.append(rs) @@ -2671,6 +2667,7 @@ 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"] def process_mmap(self): self._memobj = bitwise.parse(MEM_FORMAT_H3, self._mmap) diff --git a/chirp/drivers/thuv1f.py b/chirp/drivers/thuv1f.py index c2fd4bd..ab277dc 100644 --- a/chirp/drivers/thuv1f.py +++ b/chirp/drivers/thuv1f.py @@ -197,7 +197,7 @@ class TYTTHUVF1Radio(chirp_common.CloneModeRadio): rf.can_odd_split = True rf.valid_duplexes = ["", "-", "+", "split", "off"] rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] - rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + "-" + rf.valid_characters = chirp_common.CHARSET_ALPHANUMERIC + "-/" rf.valid_bands = [(136000000, 174000000), (420000000, 470000000)] rf.valid_skips = ["", "S"] diff --git a/chirp/drivers/tk280.py b/chirp/drivers/tk280.py new file mode 100644 index 0000000..75ac12e --- /dev/null +++ b/chirp/drivers/tk280.py @@ -0,0 +1,1892 @@ +# Copyright 2016 Pavel Milanes, CO7WT, <pavelmc@gmail.com> +# Copyright 2024 Dan Smith <chirp@f.danplanet.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import collections +import itertools +import logging +import struct +import time + +from chirp import chirp_common, directory, memmap, errors, util, bitwise +from chirp.settings import RadioSettingGroup, RadioSetting, \ + RadioSettingValueBoolean, RadioSettingValueList, \ + RadioSettingValueString, RadioSettingValueInteger, \ + RadioSettings, MemSetting, RadioSettingValueInvertedBoolean, \ + RadioSettingValueMap, RadioSettingSubGroup + +LOG = logging.getLogger(__name__) + +# IMPORTANT DATA: +# This radios have a span of +# 0x00000 - 0x07FFF => Radio Memory / Settings data +# 0x08000 - => FIRMWARE... hum... + +# Notes: March 5 2024 +# This file was heavily modified from tk760g.py for use with TK-380 by +# Thomas P. It is far from perfect but the main objective was to map a +# Kenwood x80 series to help further development. If radio is programmed in +# trunked mode, this module won't work as the mem map changes drastically. +# Stick to Conventional. +# FYI: Tk-981, 980, 480 and 481 are ONLY trunked mode so have different mem +# map. +# +# I believe the memmap is complete-ish but most likely needs corrections +# (data types, etc) if planning on completing a functional UI section. +# +# Many features are missing from the UI. Such as... +# 2-Tone, FleetSync, Emergency Information, Operator Selectable Tone, +# Test Frequency +# +# Some features are shown in UI but incomplete. Such as... +# Scan Information, DTMF +# +# + +CONVENTIONAL_DEFS = """ +struct conv_settings { + // x00-x01, Edit>>Model Information>>Radio Format, + // '03 00':Conventional Format, '00 03':Trunked Format + u8 format[2]; + u8 unknown0[12]; // unknown, all xFF in UNPROGRAM mode + u8 groups; // How many banks are programmed + u8 channels; // How many total channels are programmed + ul16 tot; // TOT value: range(15, 600, 15); x04b0 = off + u8 tot_rekey; // TOT Re-key value range(0, 60); off= 0 + u8 unknown1; // unknown + u8 tot_reset; // TOT Re-key value range(0, 60); off= 0 + u8 unknown2; // unknowns + u8 tot_alert; // TOT pre alert: range(0,10); 0 = off + u8 unknown3[7]; // 1d, unknown + u8 sql_level; // SQ reference level + u8 battery_save; // Portable: FF=off,32=Long,30=Short,31=Middle + u8 sc_nfo_priority; // Scan '31'=Selected, '30'=Fixed, 'FF'=None + ul16 sc_nfo_lbt_a; // Scan Look Back Time A[sec],range(0.35, 5.0, .05) + ul16 sc_nfo_lbt_b; // Scan Look Back Time B[sec],range(0.5, 5.0, .05) + ul16 sc_nfo_ddtime; // Scan Dropout Delay Time[sec],range(0, 300, 1) + ul16 sc_nfo_dwell; // Scan Dwell Time[sec], range(0, 300, 1) + // Scan Revert Ch 30=Last Called, 31=Last Used, 34=Priority, + // 35=Priority+TalkBack) + u8 sc_nfo_revert; + u8 sc_nfo_grp_scan; // 8th bit, Scan Info, Group, 30=Single, 31=Multi + u8 sc_nfo_prio_grp; // Scan Priority Group, [None,1-32?] + u8 sc_nfo_prio_ch; // Scan Priority Channel, [None,1-128?] + u8 unknown5:2, // unknown + ptt_release_tone:1, // PTT Release Tone, '1'=off, '0'=on + sc_nfo_rev_disp:1, // Scan Revert Ch Display, '1'=disable, '0'=enable + c2t:1, // Clear to transpond: 1=off, + ost_direct:1, // Operator Sel Tone, Direct (1=disable, 0=enable) + ost_backup:1, // Operator Sel Tone, Back Up (1=disable, 0=enable) + unknown117:1; // unknown + u8 unknown113[2]; // 2 bytes, unknown + u8 2t_a_tone_x[6]; // 2-Tone, A Tone [Hz], (41 24 FB 24 87 23) + u8 2t_b_tone_x[6]; // 2-Tone, B Tone [Hz], (41 24 FB 24 87 23) + u8 unknown8[4]; + u8 unknown9[16]; + u8 unknown10[16]; + lbit add[256]; //corresponding chan add/skip values, UNCONFIRMED + u8 unknown12:1, + ptt_inhib_ta:1, // Inhibit PTT ID in TA(TalkAround), 1=off + sel_call_alert_led:1, // Sel Call Alert LED, '1'=enable, '0'=disable + battery_warn:1, // Battery Warning, '0'=enable, '1'=disable + off_hook_decode:1, // off hook decode enabled: 1-off + off_hook_horn_alert:1, // off hook horn alert: 1-off + busy_led:1, // Busy LED, '0'=enable, '1'=disable + disp_char:1; // Opt 1, Display Character (1=ChName, 0=Grp#/Ch#) + u8 unknown14; +}; +// Conventional ends here? +""" + +DEFS = """ +struct settings { + u8 unknown15:3, + self_prog:1, // Self programming enabled: 1-on + clone:1, // clone enabled: 1-on + firmware_prog:1, // firmware programming enabled: 1-on + panel_tuning:1, // Panel Tuning, 1-on, Requires panel_test=on + panel_test:1; // Panel test enabled, 1-on + u8 unknown17; + u8 unknown18:5, + warn_tone:1, // warning tone, enabled: 1-on + control_tone:1, // control tone (key tone), enabled: 1-on + poweron_tone:1; // power on tone, enabled: 1-on + u8 unknown19[5]; + u8 min_vol; // minimum volume possible: range(0,32); 0 = off + u8 tone_vol; // minimum tone volume FF=Continuous, range(0, 31) + u8 sub_lcd_disp; // Sub LCD Display (FF=none, 30=Group, 31=Channel) + u8 grp_name_len; // Group Name text length (0-10) + u8 unknown119[2]; // unknown + u8 unknown21:3, // unknown + access_log_sig:1, // Access Logic Signal, '1'=Continuous, '0'=Pulse + sq_logic_sig:1, // Squelch Logic Signal, '1'=COR, '0'=TOR + unknown111:1, + access_log_type:1, // Access Logic, '1'=Active Low, '0'=Active High + sq_logic_type:1; // Squelch Logic, '1'=Active Low, '0'=Active High + u8 unknown106:4, + em_type:2, // Emergency, '11'=None, '10'=DTMF, '00'=FleetSync + em_mode_type:1, // Emergency Mode Type, '1'=Silent, '0'=Audible + em_display:1; // Emergency Display, 'FE'=Revert, 'FF'=Text' + u8 unknown107[2]; + char poweronmesg[12]; // Power on mesg 12 bytes, off is "xFF" * 12 + u8 unknown23[6]; + u8 unknown133; // FleetSync Enhanced, 00:enable, FF:disable + char ident[8]; // radio identification string + struct { + char radio[6]; // 0xAF-0xB4, 6 digit Radio Password + char data[6]; // 0xB5-0xBA, 6 digit Data Password + } passwords; + char lastsoftversion[5]; // software version employed to program the radio + char dtmf_prim_code[7]; // DTMF Decode, Primary Code + char dtmf_sec_code[7]; // DTMF Decode, Secondary Code + char dtmf_DBD_code[7]; // DTMF Decode, Dead Beat Disable Code + char ptt_id_bot[16]; // PTT ID Begin of TX + char ptt_id_eot[16]; // PTT ID End of TX + ul16 d_auto_r_timer; // DTMF Auto Reset Timer [sec], 'Off', '0-300' + u8 d_enc_dig_time; // DTMF Encode Digit Time [dig/sec], 6,8,10,15 + u8 unknown100; + ul16 d_enc_first_d; // DTMF Encode First Digit [msec], 0,100,500,1000 + ul16 d_enc_sym_d; // DTMF Encode * and # Digit [msec], 0,100,500,1000 + u8 d_dir_access:1, // DTMF Encode * Direct, '1'=disable, '0'=enable + unknown101:1, + d_store_send:1, // DTMF Enc Store and Send, '1'=disable, '0'=enable + d_man_dial:1, // DTMF Manual Dial, '1'=enable, '0'=disable + d_side_tone:1, // DTMF Side Tone, '1'=enable, '0'=disable + d_db_dis_resp:1, // DTMF Dead Beat Disable, 1=TX Inh, 0=TX/RX Inh + d_sec_dec_resp:1, // DTMF Secondary Decode, 1=Alert, 0=Transpond + d_prim_dec_resp:1; // DTMF Primary Decode, 1=Alert, 0=Transpond + u8 unknown102:1, + d_call_alert:1, // DTMF Call Alert, '1'=Normal, '0'=Continuous + // Decode Response, changes to '1' when "Alert+Transpond" selected + unknown103:1, // Secondary + unknown132:1, // Primary + d_kp_auto_ptt:1, // DTMF Keypad Auto-PTT, '0'=enable, '1'=disable + ptt_id_when:2, // PTT ID, '10'=BOT, '01'=EOT, '00'=Both + signalling_type:1; //Signalling, '1'=OR, '0'=AND +}; +struct keys { + u8 kA; // A button + u8 kLEFT; // Triangle to Left on portable, B + u8 kRIGHT; // Triangle to Right on portable, C + u8 kSIDE1; // Side button 1 (lamp), D on mobile + u8 kSCN; // S switch + u8 kMON; // Side button 2 (mon) + u8 kORANGE; // Orange button on portable, Foot Switch on mobile + // PF1(ORANGE) on portable, Group Up (Right Side Up Arrow) on mobile + u8 kPF1; + // PF2(BLACK) on portable, Group Down (Right Side Down Arrow) on mobile + u8 kPF2; + u8 kVOL_UP; // Volume Up (Left Side Up Arrow), Mobile only + u8 kVOL_DOWN; // Volume Down (Left Side Down Arrow), Mobile only + u8 unknown30[9]; // unknown + u8 kP_KNOB; // Just portable: channel knob + u8 unknown131[4]; // unknown + u8 unknown31[7]; // unknown + u8 k0; // Numkey 0 + u8 k1; // Numkey 1 + u8 k2; // Numkey 2 + u8 k3; // Numkey 3 + u8 k4; // Numkey 4 + u8 k5; // Numkey 5 + u8 k6; // Numkey 6 + u8 k7; // Numkey 7 + u8 k8; // Numkey 8 + u8 k9; // Numkey 9 + u8 unknown130[4]; // Unknown + u8 kASTR; // Numkey * + u8 kPOUND; // Numkey # +}; +struct misc { + u8 d_enc_hold_time; // DTMF Encode Hold Time [sec], Off, 0.5-2.0, .1 incr + u8 unknown120; // unknown + u8 ptt_id_type; // PTT ID Type, '00'=DTMF, '01'=FleetSync, NOT emergency + u8 unknown112; // unknown + // Com 0(Accessory Connector), FF=none, 33=rem, 30=Data, + // 35=Data+GPS NOT related to emergency + u8 com_0; + // Com 1(Internal Port), FF=none, 33=rem, 36=man down in, 31=GPS, + // NOT related to emergency but convenient to put here + u8 com_1; + // Com 2(Internal Port), FF=none, 33=rem, 36=man down in, 31=GPS, + // 32=AUX Hook/PTT, 34=Data PTT, 35=Data+GPS + u8 com_2; + u8 em_group; // Emergency Group + u8 em_chan; // Emergency Channel + ul16 em_key_delay; // Emergency Key Delay Time [sec] Off, .1-5.0 in .1 incr + u8 em_active_time; // Emergency Active time [sec], 1-60 + u8 unknown_105; // unknown + u8 em_int_time; // Emergency Interval Time [sec], 30-180 + u8 unknown107; // unknown + char em_text[10]; // Emergency Text + char line1[32]; // Embedded Message Line 1 + char line2[32]; // Embedded Message Line 2 + u8 em_dtmf_id[16]; // x240-x24F, 16 bytes, Emergency DTMF ID +}; +""" + +MEM_FORMAT = DEFS + CONVENTIONAL_DEFS + """ + // #seekto 0x0000; + struct conv_settings conv; + // #seekto 0x0082; + struct settings settings; +//These are ALL the keys on TK-380 keypad version. These locations are assigned +// functions from values in KEYS below +#seekto 0x0110; +struct keys keys; + +//#seekto 0x0140; +struct { + lbcd tf01_rx[4]; + lbcd tf01_tx[4]; + u8 tf01_u_rx; + u8 tf01_u_tx; + lbcd tf02_rx[4]; + lbcd tf02_tx[4]; + u8 tf02_u_rx; + u8 tf02_u_tx; + lbcd tf03_rx[4]; + lbcd tf03_tx[4]; + u8 tf03_u_rx; + u8 tf03_u_tx; + lbcd tf04_rx[4]; + lbcd tf04_tx[4]; + u8 tf04_u_rx; + u8 tf04_u_tx; + lbcd tf05_rx[4]; + lbcd tf05_tx[4]; + u8 tf05_u_rx; + u8 tf05_u_tx; + lbcd tf06_rx[4]; + lbcd tf06_tx[4]; + u8 tf06_u_rx; + u8 tf06_u_tx; + lbcd tf07_rx[4]; + lbcd tf07_tx[4]; + u8 tf07_u_rx; + u8 tf07_u_tx; + lbcd tf08_rx[4]; + lbcd tf08_tx[4]; + u8 tf08_u_rx; + u8 tf08_u_tx; + lbcd tf09_rx[4]; + lbcd tf09_tx[4]; + u8 tf09_u_rx; + u8 tf09_u_tx; + lbcd tf10_rx[4]; + lbcd tf10_tx[4]; + u8 tf10_u_rx; + u8 tf10_u_tx; + lbcd tf11_rx[4]; + lbcd tf11_tx[4]; + u8 tf11_u_rx; + u8 tf11_u_tx; + lbcd tf12_rx[4]; + lbcd tf12_tx[4]; + u8 tf12_u_rx; + u8 tf12_u_tx; + lbcd tf13_rx[4]; + lbcd tf13_tx[4]; + u8 tf13_u_rx; + u8 tf13_u_tx; + lbcd tf14_rx[4]; + lbcd tf14_tx[4]; + u8 tf14_u_rx; + u8 tf14_u_tx; + lbcd tf15_rx[4]; + lbcd tf15_tx[4]; + u8 tf15_u_rx; + u8 tf15_u_tx; + lbcd tf16_rx[4]; + lbcd tf16_tx[4]; + u8 tf16_u_rx; + u8 tf16_u_tx; +} test_freq; + +#seekto 0x1E7; +struct misc misc; + +#seekto 0x0300; +struct { + u8 group; // Group number + u8 number; // Memory number in zone + u8 group_index;// The *index* of the group record + u8 index; // Index of memory in array +} group_mapping[250]; + +#seekto 0x700; +struct { + ul16 ost_dec_tone; // Operator Selectable Tones, QT/DQT Decode + ul16 ost_enc_tone; // Operator Selectable Tones, QT/DQT Encode + char ost_name[10]; // Operator Selectable Tones, OST Name + u8 unknown118[2]; // unknown +} ost[16]; + +//#seekto 0x800; +struct { + u8 2t_a_tone_y[4]; // 2t_a_tone_x and 2t_a_tone_z + u8 2t_b_tone_y[4]; // 2t_b_tone_x and 2t_b_tone_z + u8 2t_c_tone_y[4]; // 2t_c_tone_z + u8 2t_a_tone_z[2]; // 2t_a_tone_x and 2t_a_tone_y + u8 2t_b_tone_z[2]; // 2t_b_tone_x and 2t_b_tone_y + u8 2t_c_tone_z[2]; // 2t_c_tone_y + // Decoder1 Call Format, (30=A-B, 31=A-C, 32=C-B, 33=A, 34=B, 35=C) + u8 2t_dec1_ca_form; + // Decoder2 Call Format, (FF=None, 30=A-B, 31=A-C, 32=C-B, 33=A, 34=B, 35=C) + u8 2t_dec2_ca_form; + u8 2t_call_alert; // 2-Tone, Call Alert, (FF=no, x30=Normal, x31=Cont) + u8 2t_ar_timer[2]; // 2-Tone, Auto Reset[sec], range(Off, 1-300) incr of 1 + u8 unknown115:5, + 2t_transpond:1, // Transpond (1=disable, 0=enable) + 2t_dec2_c_type:1, // Decoder2 Call Type, (1=Individual, 0=Group) + 2t_dec1_c_type:1; // Decoder1 Call Type, (1=Individual, 0=Group) + u8 unknown116[8]; + +} 2tone[3]; // Attempt at capturing 2-Tone 1, 2 and 3 + +#seekto 0x1000; +struct { + u8 number; // Group Number + u8 channels; // Channels in Group + char name[10]; // Group Name + u8 data_grp; // Data Group + u8 data_chan; // Data Channel + u8 unknown108; + u8 unknown109; +} groups[250]; + +#seekto 0x2000; +struct { + u8 number; // Channel Number + u8 group; // to which bank/group it belongs + char name[10]; // Channel name, 10 chars + lbcd rxfreq[4]; // rx freq + lbcd txfreq[4]; // tx freq + u8 unknown_rx:4, + rx_step:4; // rx tuning step + u8 unknown_tx:4, + tx_step:4; + ul16 rx_tone; // rx tone + ul16 tx_tone; // tx tone + u8 unknown23[5]; // unknown yet + u8 signalling; // Option Sig, FF=off, 30=DTMF, 32=2-Tone 1,32=FleetSync, + u8 unknown24:1, // unknown + ptt_id:1, // PTT ID, '1'=off, '0'=on + beat_shift:1, // Beat Shift, 1 = off + busy_lock:1, // BCL, 1=none, 0=QT/DQT Tone, see also 2 bits in x2021 + data_en:1, // Data, 1=enable + power:1, // TX Power: 0 low / 1 high + compander:1, // Compander, 1 = off + wide:1; // Wide/Narrow, wide 1 / 0 narrow + u8 unknown27:4, // unknown + busy_lock_opt:2,// Busy Lock, 11=none, 00=Carrier, 01=OptSig, + unknown28:2; // unknown + u8 unknown29[14]; // unknown yet +} memory[250]; + +#seekto 0x5000; +struct { + u8 d_num; // DTMF Memory number + u8 unknown32; // unknown + char d_an[10]; // A/N + u8 unknown33[4]; // unknown + u8 d_code[8]; // Code + u8 unknown34[8]; // unknown +} dtmf_memory[32]; + +#seekto 0x6000; +struct { + // method unknown so far + u8 fs_fleet_id[3]; // FleetSync, Fleet(Own):100-349 and ID(Own): 1000-3999 + u8 unknown126[2]; + ul16 fs_max_ack_wt; // FleetSync, Maximum ACK Wait [sec]: 0.5-60, .10 incr + ul16 fs_dtx_mod_dt; // FleetSync, Data TX Mod Delay [msec]: 0-6000, 1 incr + u8 unknown125[3]; + u8 fs_uid_enc_blk[4]; // FleetSync, UnitID Enc Block: 1000-4999, method unk + u8 fs_gtc_count; // FleetSync, GTC Count: 0-5 + ul16 fs_tx_bw_time; // FleetSync, TX Busy Wait [sec]: 0.5-60.0, .10 incr + ul16 fs_ack_delay; // FleetSync, ACK Delay Time[sec]: 0.1-60.0, .10 incr + u8 fs_num_retries; // FleetSync, Number of Retries: 0-8 + ul16 fs_txdel_rxcap; // FleetSync, TX Delay (RX Capt): 0.0-25.0, .10 incr + u8 unknown124[3]; + u8 fs_baud; // FleetSync, Baud Rate [bps]: (x31=2400, 30=1200) + ul16 fs_mm_timer; // FleetSync, Message Mode Timer[sec]: (off, 1-300) + u8 fs_em_stat_resp; // FleetSync, Emerg Status Resp: (x00=none, x01=Alert) + u8 fs_ptt_st; // FleetSync, PTT ID Side Tone: (1=enable, 0=disable) + u8 unknown127[3]; + u8 fs_stat_m_data; // FleetSync, Status Msg on Data Ch 1=dis, 0=en + u8 fs_caller_id_st:1, // FleetSync, Caller ID Stack: 1=dis, 0=en + unknown121:1, + fs_stat_8090:1, // FleetSync, Status 80-99(Special): 1=dis, 0=en + unknown122:1, + data_tx_qt:1, // Opt Feat2, Data TX with QT/DQT, '1'=dis, '0'en + fs_man_dial:1, // FleetSync, Manual Dial: 0=disable, 1=enable + fs_if_call:1, // FleetSync, Inter-fleet Call: 1=disable, 0=enable + fs_rand_acc:1; // FleetSync, Random Access (Cont): 0=enable, 1=disable + u8 unknown123:5, + fs_ss_val:1, // FleetSync, Stun Status Valid: (1=enable, 0=disable) + fs_ca_cont:1, // FleetSync, Call Alert(Cont): (1=enable, 0=disable) + fs_call_id_disp:1; // FleetSync, Caller ID Display (1=disable, 0=enable) +} fleetsync; + +#seekto 0x6040; +struct { + u8 em_call_fleet; // x6040, 1 byte, Emergency FleetSync Call Fleet #, 100-350 + u8 em_call_id[2]; // x6041, 2 byte, Emergency FleetSync Call ID #, 1000-3999 +} emergency; + +#seekto 0x6C00; +struct { + u8 fs_idl_fleet; // FleetSync, ID List, Fleet: 100-349 + ul16 fs_idl_id; // FleetSync, ID: 1000-4999 x004E=ALL + char fs_id_name[10]; // FleetSync, ID List, ID Name + u8 fs_idl_tx_inhibit; // FleetSync, ID List, TX Inhibit: FF=No, FE=Yes + u8 unknown127[2]; +} fs_id_list[64]; + +//#seekto 0x7000; +struct { + u8 fs_sl_status; // FleetSync, Status List, Status: 10-99 + u8 unknown120; + char fs_stat_name[16]; // FleetSync, Status List, Status Name + u8 fs_sl_tx_inhibit; // FleetSync, Status List, TX Inhibit: FE=Yes, FF=No + u8 unknown128[13]; +} fs_stat_list[50]; +""" + +NOTE = """ MENTAL NOTE ABOUT RADIO MEM + +The OEM insist on not reading/writing some mem segments, see below + +read: (hex) + 00 - 03 + 07 - 08 + 10 + 20 - 21 + 58 - 7F + +write: (hex) + 00 - 03 + 07 - 08 + 10 + 20 - 21 + 60 - 7F + + +This can be an artifact to just read/write in the needed mem space and speed +up things, if so the first read blocks has all the data about channel groups +and freq/tones & names employed. + +This is a copied trick from the "60G series" ones and may use the same schema. + +I must investigate further on this. +""" + +MEM_SIZE = 0x8000 # 32,768 bytes (128 blocks of 256 bytes) +BLOCK_SIZE = 256 +MEM_BLOCKS = range(0, MEM_SIZE // BLOCK_SIZE) + +# define and empty block of data, as it will be used a lot in this code +EMPTY_BLOCK = b"\xFF" * 256 + +ACK_CMD = b"\x06" +NAK_CMD = b"\x15" + +# TK-280:1,5 TK-380:1,4 TK-780:25 TK-880:5,25 + +MODES = ["NFM", "FM"] # 12.5 / 25 Khz +VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + "_-*()/\\-+=)." +SKIP_VALUES = ["", "S"] + +TONES = chirp_common.TONES +# TONES.remove(254.1) +DTCS_CODES = chirp_common.DTCS_CODES + + +TOT = [("off", 0x04B0)] + [("%s" % x, x) for x in range(15, 615, 15)] +TOT_PRE = ["off"] + ["%s" % x for x in range(1, 11)] +TOT_REKEY = ["off"] + ["%s" % x for x in range(1, 61)] +TOT_RESET = ["off"] + ["%s" % x for x in range(1, 16)] +VOL = ["off"] + ["%s" % x for x in range(1, 32)] +TVOL = ["%s" % x for x in range(0, 33)] +TVOL[32] = "Continuous" +SQL = ["off"] + ["%s" % x for x in range(1, 10)] +SIG_TYPE = ["AND", "OR"] +CM0 = { + 0xFF: "None", + 0x30: "Data", + 0x31: "GPS", + 0x32: "AUX Hook/PTT", + 0x33: "REM", + 0x34: "Data PTT", + 0x35: "Data+GPS", + 0x36: "Man Down In", +} +BSAVE = {0xFF: "Off", 0x32: "Long", 0x30: "Short", 0x31: "Middle"} +PIDT = {0x00: "DTMF", 0x01: "FleetSync"} +PID = {0o10: "BOT", 0o01: "EOT", 0o00: "Both"} +SLT = {1: "Active Low", 0: "Active High"} +SLS = {1: "COR", 0: "TOR"} +ALT = {1: "Active Low", 0: "Active High"} +ALS = {1: "Continuous", 0: "Pulse"} +SIP = {0x31: "Selected", 0x30: "Fixed", 0xFF: "None"} +PG = ["None"] + ["%s" % x for x in range(1, 32)] +PCH = ["None"] + ["%s" % x for x in range(1, 250)] +LBTA = [x / 100.0 for x in range(35, 505, 5)] +LBTB = [x / 100.0 for x in range(50, 505, 5)] +REVCH = { + 0x30: "Last Called", + 0x31: "Last Used", + 0x34: "Priority", + 0x35: "Priority+TalkBack", +} +DDT = ["%s" % x for x in range(0, 300)] +DWT = ["%s" % x for x in range(0, 300)] +GRPSC = {0x30: "Single", 0x31: "Multi"} +BCL_OPTS = ['Off', 'QT/DQT', 'Option Signalling', 'Carrier Only'] + +KEYS = { + 0x30: "Memory(RCL/STO)", + 0x31: "DTMF ID(BOT)", + 0x32: "DTMF ID(EOT)", + 0x33: "Display character", + 0x34: "Emergency", + 0x35: "Home Channel", # Possible portable only, check it + 0x36: "Function", + 0x37: "Channel down", + 0x38: "Channel up", + 0x39: "Key lock", + 0x3b: "Public address", + 0x3c: "Reverse", # Not all firmware versions? + 0x3d: "Horn alert", + 0x3e: "Memory(RCL)", + 0x3f: "Memory(STO)", + 0x40: "Monitor A: Open Momentary", + 0x41: "Monitor B: Open Toggle", + 0x42: "Monitor C: Carrier Squelch Momentary", + 0x43: "Monitor D: Carrier Squelch Toggle", + 0x45: "Redial", + 0x47: "Scan", + 0x48: "Scan Del/Add", + 0x4a: "Group Down", + 0x4b: "Group Up", + 0x4e: "Operator Selectable Tone", + 0x4f: "None", + 0x50: "Volume down", + 0x51: "Volume up", + 0x52: "Talk around", +} +PORTABLE_KEYS = { + 0x3a: "Lamp", + 0x5d: "AUX", + 0x46: "RF Power Low", +} +MOBILE_KEYS = { + 0x5D: 'AUX A', # Same as AUX on portable + 0x44: 'AUX B', +} + + +def _close_radio(radio): + """Get the radio out of program mode""" + try: + radio.pipe.write(b"E") + except Exception as e: + LOG.error('Failed to close radio: %s' % e) + + +def _checksum(data): + """the radio block checksum algorithm""" + cs = 0 + for byte in data: + cs += byte + return cs % 256 + + +def _make_frame(cmd, addr): + """Pack the info in the format it likes""" + return struct.pack(">BH", cmd[0], addr) + + +def _open_radio(radio, status): + """Open the radio into program mode and check if it's the correct model""" + radio.pipe.baudrate = 9600 + radio.pipe.parity = "E" + radio.pipe.timeout = 1 + + LOG.debug("Entering program mode.") + tries = 10 + + status.msg = "Entering program mode..." + radio.status_fn(status) + + for i in range(0, tries): + radio.pipe.write(b"PROGRAM") + ack = radio.pipe.read(1) + LOG.debug('Ack: %r' % ack) + if not ack: + LOG.debug('No response from radio, will retry') + time.sleep(0.5) + elif ack != ACK_CMD: + LOG.debug('Received unexpected response from radio: %r' % ack) + radio.pipe.flush() + time.sleep(0.5) + else: + break + + if ack != ACK_CMD: + raise errors.RadioError('Failed to put radio into programming mode') + + radio.pipe.write(b"\x02") + rid = radio.pipe.read(8) + if radio.TYPE not in rid: + LOG.debug("Incorrect model ID:") + LOG.debug(util.hexprint(rid)) + raise errors.RadioError( + "Incorrect model ID, got %s, it doesn't contain %s" % + (rid.strip(b"\xff"), radio.TYPE)) + + LOG.debug("Full ident string is:") + LOG.debug(util.hexprint(rid)) + exchange_ack(radio.pipe) + + status.msg = "Radio ident success!" + radio.status_fn(status) + + radio.pipe.write(b"P") + ver = radio.pipe.read(10) + LOG.debug("Version returned by the radios is:") + LOG.debug(util.hexprint(ver)) + exchange_ack(radio.pipe) + # the radio that was processed returned this: + # v2.00k.. [76 32 2e 30 30 6b ef ff] + # version 1 TK-280: + # v1.04.. 76 31 2e 30 34 20 ff ff + + # now the OEM writes simply "O" and gets no answer... + # after that we are ready to receive the radio image or to write to it + radio.pipe.write(b'O') + + radio.metadata = {'tkx80_ver': ver.strip(b'\xFF').decode('ascii', + errors='ignore'), + 'tkx80_rid': list(rid.strip(b'\xFF'))} + + +def exchange_ack(pipe): + pipe.write(ACK_CMD) + ack = pipe.read(1) + if ack == NAK_CMD: + LOG.debug('Radio sent explicit NAK') + raise errors.RadioError('Radio sent NAK') + elif ack != ACK_CMD: + LOG.debug('Radio sent unexpected response: %r' % ack) + raise errors.RadioError('Radio did not ack') + + +def read_block(pipe): + cmd = pipe.read(1) + if cmd == b'Z': + block = b'\xFF' * BLOCK_SIZE + else: + block = pipe.read(BLOCK_SIZE) + checksum = pipe.read(1) + calc = _checksum(block) + if calc != checksum[0] and cmd != b'Z': + LOG.debug('Checksum %i does not match %i', calc, checksum[0]) + raise errors.RadioError('Checksum reading block from radio') + exchange_ack(pipe) + return block + + +def do_download(radio): + status = chirp_common.Status() + status.cur = 0 + status.max = MEM_SIZE // BLOCK_SIZE + radio.status_fn(status) + + data = b"" + count = 0 + _open_radio(radio, status) + + status.msg = "Cloning from radio..." + for addr in MEM_BLOCKS: + radio.pipe.write(_make_frame(b"R", addr)) + block = read_block(radio.pipe) + data += block + status.cur = count + radio.status_fn(status) + count += 1 + + return memmap.MemoryMapBytes(data) + + +def do_upload(radio): + status = chirp_common.Status() + status.cur = 0 + status.max = MEM_SIZE // BLOCK_SIZE + status.msg = "Cloning to radio..." + radio.status_fn(status) + + _open_radio(radio, status) + + status.msg = "Cloning to radio..." + for block in MEM_BLOCKS: + if 0x50 < block < 0x60: + # This causes a NAK if the radio does not have this feature + LOG.debug('Skipping DTMF memory block 0x%x', block) + continue + data = radio.get_mmap()[block * BLOCK_SIZE:(block + 1) * BLOCK_SIZE] + if data == EMPTY_BLOCK: + frame = _make_frame(b'Z', block) + b'\xFF' + else: + cs = _checksum(data) + frame = _make_frame(b'W', block) + data + bytes([cs]) + radio.pipe.write(frame) + try: + exchange_ack(radio.pipe) + except Exception: + LOG.error('Failed to send block 0x%x', block) + raise + status.cur = block + radio.status_fn(status) + + +class TKx80SubdevMeta(type): + """Metaclass for generating subdevice subclasses""" + def __new__(cls, name, parent, dct): + return super(TKx80SubdevMeta, cls).__new__(cls, name, (parent,), dct) + + @staticmethod + def make_subdev(parent_dev, child_cls, key, to_copy, **args): + """parent_dev: An instance of the parent class + child_cls: The class of the child device + key: Some class-name-suitable value to set this off from others + to_copy: Class variables tp copy from the parent + args: Class variables to set on the new class + """ + return TKx80SubdevMeta('%s_%s' % (child_cls.__name__, key), + child_cls, + dict({k: getattr(parent_dev, k) + for k in to_copy}, **args)) + + +class KenwoodTKx80(chirp_common.CloneModeRadio): + """Kenwood Series 80 Radios base class""" + VENDOR = "Kenwood" + BAUD_RATE = 9600 + _memsize = MEM_SIZE + NAME_LENGTH = 8 + _range = [] + _upper = 250 + _steps = chirp_common.COMMON_TUNING_STEPS + # Ver1 and Ver2 radios use a different multiplier for in-memory frequency + _freqmult = 10 + VARIANT = "" + MODEL = "" + FORMATS = [directory.register_format('Kenwood KPG-49D', '.dat')] + POWER_LEVELS = [] + + def load_mmap(self, filename): + if filename.lower().endswith('.dat'): + with open(filename, 'rb') as f: + f.seek(0x32) + self._mmap = memmap.MemoryMapBytes(f.read()) + LOG.info('Loaded DAT file at offset 0x32') + self.process_mmap() + else: + return super().load_mmap(filename) + + @property + def dat_header(self): + return (b'KPG49D\xFF\xFF\xFF\xFFV4.02P0' + + self.MODEL[3:].encode() + + b'\x04\xFF\xF1\xFF' + + b'\xFF' * 26) + + def save_mmap(self, filename): + if filename.lower().endswith('.dat'): + with open(filename, 'wb') as f: + f.write(self.dat_header) + f.write(self._mmap.get_packed()) + LOG.info('Write DAT file') + else: + super().save_mmap(filename) + + @classmethod + def get_prompts(cls): + rp = chirp_common.RadioPrompts() + rp.experimental = \ + ('This driver is experimental and supports only conventional ' + 'zones.') + return rp + + def get_features(self): + """Return information about this radio's features""" + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.has_tuning_step = False + rf.has_name = True + 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.has_dynamic_subdevices = True + rf.valid_modes = MODES + rf.valid_duplexes = ["", "-", "+", "off", "split"] + rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross'] + rf.valid_cross_modes = [ + "Tone->Tone", + "DTCS->", + "->DTCS", + "Tone->DTCS", + "DTCS->Tone", + "->Tone", + "DTCS->DTCS"] + rf.valid_power_levels = self.POWER_LEVELS + rf.valid_characters = VALID_CHARS + rf.valid_skips = SKIP_VALUES + rf.valid_dtcs_codes = DTCS_CODES + rf.valid_bands = self._range + rf.valid_tuning_steps = self._steps + rf.valid_name_length = 10 + rf.memory_bounds = (1, self._upper) + rf.has_sub_devices = True + rf.has_bank = False + rf.can_odd_split = True + return rf + + def get_sub_devices(self): + if not self._memobj: + return [TKx80Group(self, 1)] + to_copy = ('MODEL', 'TYPE', 'POWER_LEVELS', '_range', '_steps', + '_freqmult') + return sorted([ + TKx80SubdevMeta.make_subdev( + self, TKx80Group, i, + to_copy, VARIANT=str(self._memobj.groups[i].name).strip())( + self, self._memobj.groups[i].number) + for i in range(250) + if self._memobj.groups[i].number <= 250], + key=lambda z: z.group) + + def sync_in(self): + """Do a download of the radio eeprom""" + try: + self._mmap = do_download(self) + except errors.RadioError: + raise + except Exception as e: + LOG.exception('Unexpected radio error: %s' % e) + raise errors.RadioError(str(e)) + finally: + _close_radio(self) + self.process_mmap() + + def sync_out(self): + """Do an upload to the radio eeprom""" + + try: + do_upload(self) + except errors.RadioError: + raise + except Exception as e: + raise errors.RadioError("Failed to communicate with radio: %s" % e) + finally: + _close_radio(self) + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + self._compact_mappings() + + def _decode_tone(self, val): + """Parse the tone data to decode from mem, it returns: + Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)""" + val = int(val) + if val == 65535: + return '', None, None + elif val >= 0x2800: + code = int("%03o" % (val & 0x07FF)) + pol = (val & 0x8000) and "R" or "N" + return 'DTCS', code, pol + else: + a = val / 10.0 + return 'Tone', a, None + + def _encode_tone(self, memval, mode, value, pol): + """Parse the tone data to encode from UI to mem""" + if mode == '': + memval.set_raw(b"\xff\xff") + elif mode == 'Tone': + memval.set_value(int(value * 10)) + elif mode == 'DTCS': + val = int("%i" % value, 8) + 0x2800 + if pol == "R": + val += 0xA000 + memval.set_value(val) + else: + raise Exception("Internal error: invalid mode `%s'" % mode) + + def _get_scan(self, chan): + """Get the channel scan status from the 16 bytes array on the eeprom + then from the bits on the byte, return '' or 'S' as needed""" + return '' if bool(self._memobj.conv.add[chan]) else 'S' + + def _set_scan(self, chan, value): + """Set the channel scan status from UI to the mem_map""" + self._memobj.conv.add[chan] = value == '' + + def _get_memory_mapping(self, group, number, allocate=False): + """Find a virtual memory mapping in the group's index. + + Raise IndexError if not mapped. + """ + try: + return self._map_cache[(group, number)] + except KeyError: + if not allocate: + raise IndexError('Memory %i-%i not mapped' % (group, number)) + + LOG.debug('Cache miss for allocating %i,%i' % (group, number)) + empty = None + free_memories = set(range(250)) + this_group_index = None + # Count to 250 and... + for i in range(250): + mapping = self._memobj.group_mapping[i] + if mapping.group == group and mapping.number == number: + # Direct hit, return it. But, we should have found this in the + # cache + LOG.warning('Found mapping for %i-%i but was not in cache?', + group, number) + return mapping + elif empty is None and mapping.group == 0xFF: + # Record the earliest-available mapping + empty = i + elif mapping.index < 255: + # Any valid mapping consumes a slot in the memory array, + # so keep track of which ones are unused + free_memories.remove(int(mapping.index)) + + # Also record the index of this group in case we have to allocate + # below + if self._memobj.groups[i].number == group: + this_group_index = i + + if this_group_index is None: + raise errors.RadioError( + 'Allocate for group %i did not find a record' % group) + # Use the first available memory location + memory = list(sorted(free_memories))[0] + mapping = self._memobj.group_mapping[empty] + mapping.group = group + mapping.number = number + mapping.group_index = this_group_index + mapping.index = memory + self._memobj.groups[this_group_index].channels += 1 + LOG.info(('Allocating slot %i memory %i for %i-%i ' + 'grp index %i channels %i') % ( + empty, memory, group, number, this_group_index, + self._memobj.groups[this_group_index].channels)) + self._compact_mappings() + # The above may have rearranged things so re-search for our + # new slot + return self._get_memory_mapping(group, number) + + def _delete_memory_mapping(self, group, number): + mapping = self._parent._get_memory_mapping(group, number) + mem = self._memobj.memory[mapping.index] + group_rec = self._memobj.groups[mapping.group_index] + group_rec.channels -= 1 + LOG.info( + 'Deleting memory mapping for %i-%i memory %i (%i in group)' % ( + group, number, mapping.index, group_rec.channels)) + mem.fill_raw(b'\xFF') + mapping.fill_raw(b'\xFF') + self._compact_mappings() + + def _compact_mappings(self): + """Survey all the memories in mapping list and update.""" + group_counts = collections.defaultdict(lambda: 0) + valid = [] + # Count to 250 and ... + for i in range(250): + # Find all the valid mappings and count up number of valid + # memories in each group + mapping = self._memobj.group_mapping[i] + if mapping.group < 255 and mapping.number < 255: + valid.append((int(mapping.group), int(mapping.number), + int(mapping.group_index), int(mapping.index))) + group_counts[int(mapping.group)] += 1 + + # The mappings need to be in order, at least by group, perhaps by + # memory number as well + valid.sort(key=lambda x: (x[0], x[1])) + + memories = 0 + groups = set() + self._map_cache = {} + # Count to 250 again and... + for i in range(250): + # Update all the mappings with the new sorted survey results + try: + group, number, group_index, index = valid[i] + memories += 1 + groups.add(group) + except IndexError: + group = number = group_index = index = 0xFF + mapping = self._memobj.group_mapping[i] + mapping.group = group + mapping.number = number + mapping.group_index = group_index + mapping.index = index + + # Rebuild our cache + self._map_cache[int(mapping.group), int(mapping.number)] = mapping + + # Also update the groups with correct memory counts + group = int(self._memobj.groups[i].number) + if group in group_counts: + self._memobj.groups[i].channels = group_counts[group] + + # Radio-wide group and memory counts need to be updated + self._memobj.conv.groups = len(groups) + self._memobj.conv.channels = memories + LOG.info('%i groups, %i memories', + self._memobj.conv.groups, + self._memobj.conv.channels) + + @classmethod + def match_model(cls, filedata, filename): + model = cls.MODEL[3:].encode() + if (filename.lower().endswith('.dat') and + b'KPG49D' in filedata and model in filedata[:0x32]): + return True + return False + + def _get_settings_groups(self, groups): + group_index = {} + unused_slots = set() + + # Survey the currently-mapped groups + for i in range(250): + if self._memobj.groups[i].number < 0xFF: + group_index[int(self._memobj.groups[i].number)] = i + else: + unused_slots.add(i) + + for i in range(250): + group_number = i + 1 + try: + group = self._memobj.groups[group_index[group_number]] + group_name = str(group.name).strip('\xFF') + group_count = int(group.channels) + enabled = True + except KeyError: + group_name = '' + group_count = 0 + enabled = False + name = RadioSetting('group-%i-name' % group_number, 'Name', + RadioSettingValueString( + 0, 10, group_name)) + enable = RadioSetting('group-%i-enable' % group_number, 'Enabled', + RadioSettingValueBoolean(enabled)) + enable.set_volatile(True) + count = RadioSetting('group-%i-count' % group_number, + 'Active Memories', + RadioSettingValueInteger(0, 250, group_count)) + if group_count: + # Can't delete groups with active memories + enable.value.set_mutable(False) + enable.set_doc('Delete all memories from group to disable') + else: + name.value.set_mutable(False) + count.value.set_mutable(False) + groups.append(RadioSettingSubGroup( + 'group-%i' % group_number, + 'Group %i' % group_number, + name, enable, count)) + + def _parse_qtdqt(self, v): + v = v.upper().strip() + if v.startswith('D'): + try: + val = int(v[1:4]) + pol = v[4] + return 'DTCS', val, pol + except (ValueError, IndexError): + raise errors.InvalidValueError( + 'DCS value must be in the form "D023N"') + elif v: + try: + val = float(v) + return 'Tone', val, '' + except ValueError: + raise errors.InvalidValueError( + 'Tone value must be in the form 103.5') + else: + return '', None, None + + def _format_qtdtq(self, raw): + mode, val, pol = self._decode_tone(raw) + if mode == 'DTCS': + return 'D%03.3i%s' % (val, pol) + elif mode == 'Tone': + return '%3.1f' % val + else: + return '' + + def _get_settings_ost(self, ost): + rs = MemSetting('conv.ost_backup', 'OST Backup', + RadioSettingValueInvertedBoolean( + not self._memobj.conv.ost_backup)) + rs.set_doc('Store OST on channel even if dialed away') + ost.append(rs) + + rs = MemSetting('conv.ost_direct', 'OST Direct', + RadioSettingValueInvertedBoolean( + not self._memobj.conv.ost_direct)) + ost.append(rs) + + def apply_ost(setting, index, which): + try: + mode, val, pol = self._parse_qtdqt(str(setting.value)) + except Exception: + LOG.error('Failed to parse %r', str(setting.value)) + raise + self._encode_tone(getattr(self._memobj.ost[index], which), + mode, val, pol) + + for i in range(16): + name = MemSetting( + 'ost[%i].ost_name' % i, 'Name', + RadioSettingValueString( + 0, 10, str(self._memobj.ost[i].ost_name).rstrip('\xFF'))) + rxt = RadioSetting( + 'ost[%i].ost_dec_tone' % i, 'RX Tone', + RadioSettingValueString( + 0, 5, + self._format_qtdtq(self._memobj.ost[i].ost_dec_tone))) + rxt.set_apply_callback(apply_ost, i, 'ost_dec_tone') + rxt.set_doc('Receive squelch mode and value ' + '(either like 103.5 or D023N)') + txt = RadioSetting( + 'ost[%i].ost_enc_tone' % i, 'TX Tone', + RadioSettingValueString( + 0, 5, + self._format_qtdtq(self._memobj.ost[i].ost_enc_tone))) + txt.set_apply_callback(apply_ost, i, 'ost_enc_tone') + txt.set_doc('Transmit mode and value ' + '(either like 103.5 or D023N)') + sg = RadioSettingSubGroup('ost%i' % i, 'OST %i' % (i + 1)) + sg.append(name) + sg.append(rxt) + sg.append(txt) + ost.append(sg) + + def _get_settings_format(self, optfeat1, optfeat2, scaninf): + conv = self._memobj.conv + + if self.TYPE[0:1] == b"P": + bsav = MemSetting( + "conv.battery_save", "Battery Save", + RadioSettingValueMap([(v, k) for k, v in BSAVE.items()], + conv.battery_save)) + optfeat1.append(bsav) + + tot = MemSetting("conv.tot", "Time Out Timer (TOT)", + RadioSettingValueMap( + TOT, conv.tot)) + optfeat1.append(tot) + + totalert = MemSetting("conv.tot_alert", "TOT pre alert", + RadioSettingValueList( + TOT_PRE, + current_index=conv.tot_alert)) + optfeat1.append(totalert) + + totrekey = MemSetting("conv.tot_rekey", "TOT re-key time", + RadioSettingValueList( + TOT_REKEY, + current_index=conv.tot_rekey)) + optfeat1.append(totrekey) + + totreset = MemSetting("conv.tot_reset", "TOT reset time", + RadioSettingValueList( + TOT_RESET, + current_index=conv.tot_reset)) + optfeat1.append(totreset) + + c2t = MemSetting("conv.c2t", "Clear to Transpond", + RadioSettingValueInvertedBoolean(not conv.c2t)) + optfeat1.append(c2t) + + bled = MemSetting('conv.busy_led', 'Busy LED', + RadioSettingValueInvertedBoolean( + not bool(conv.busy_led))) + optfeat1.append(bled) + + scled = MemSetting("conv.sel_call_alert_led", + "Selective Call Alert LED", + RadioSettingValueBoolean(conv.sel_call_alert_led)) + optfeat1.append(scled) + + pttr = MemSetting("conv.ptt_release_tone", "PTT Release Tone", + RadioSettingValueInvertedBoolean( + not conv.ptt_release_tone)) + optfeat2.append(pttr) + + inhta = MemSetting("conv.ptt_inhib_ta", + "PTT Inhibit ID in TA(TalkAround)", + RadioSettingValueInvertedBoolean( + not conv.ptt_inhib_ta)) + optfeat2.append(inhta) + + drdt = MemSetting("conv.sc_nfo_ddtime", + "Dropout Delay Time[sec]", + RadioSettingValueList( + DDT, current_index=conv.sc_nfo_ddtime)) + scaninf.append(drdt) + + dwet = MemSetting("conv.sc_nfo_dwell", "Dwell Time[sec]", + RadioSettingValueList( + DWT, + current_index=conv.sc_nfo_dwell)) + scaninf.append(dwet) + + rchd = MemSetting("conv.sc_nfo_rev_disp", + "Revert Channel Display", + RadioSettingValueInvertedBoolean( + not bool(conv.sc_nfo_rev_disp))) + scaninf.append(rchd) + + def _get_settings_misc(self, optfeat2, dealer): + msc = self._memobj.misc + # PTT ID Section + pdt = MemSetting("misc.ptt_id_type", "PTT ID Type", + RadioSettingValueList( + PIDT.values(), + current_index=msc.ptt_id_type)) + optfeat2.append(pdt) + + l1 = str(msc.line1).strip("\xFF") + line1 = MemSetting("misc.line1", "Comment 1", + RadioSettingValueString(0, 32, l1, + mem_pad_char='\xFF')) + dealer.append(line1) + + l2 = str(msc.line2).strip("\xFF") + line2 = MemSetting("misc.line2", "Comment 2", + RadioSettingValueString(0, 32, l2, + mem_pad_char='\xFF')) + dealer.append(line2) + + def _get_settings_keys(self, fkeys): + keys = self._memobj.keys + + if self.TYPE[0] == ord("P"): + model_keys = PORTABLE_KEYS + else: + model_keys = MOBILE_KEYS + key_map = sorted([(v, k) for k, v in itertools.chain( + KEYS.items(), + model_keys.items())]) + + mobile_keys = { + 'VOL_UP': 'Volume Up (Left Arrow Up)', + 'VOL_DOWN': 'Volume Down (Left Arrow Down)', + 'PF1': 'Group Up (Right Side Up Arrow)', + 'PF2': 'Group Down (Right Side Down Arrow)', + 'ORANGE': 'Foot Switch', + 'MON': 'MON', + 'SCN': 'SCN', + 'A': 'A', + 'LEFT': 'B', + 'RIGHT': 'C', + 'SIDE1': 'D', + } + portable_keys = { + 'PF1': 'Orange', + 'SIDE1': 'Side 1', + 'MON': 'Side 2', + 'SCN': 'S', + 'A': 'A', + 'LEFT': 'B', + 'RIGHT': 'C', + } + + if self.TYPE[0] == ord("P"): + knob_map = {'Channel Up/Down': 0xa1, + 'Group Up/Down': 0xa2} + knob = MemSetting("keys.kP_KNOB", "Knob", + RadioSettingValueMap( + knob_map.items(), + keys.kP_KNOB)) + fkeys.append(knob) + + if self.TYPE[0] == ord('M'): + model_keys = mobile_keys + else: + model_keys = portable_keys + + for key, name in model_keys.items(): + rs = MemSetting("keys.k%s" % key, name, + RadioSettingValueMap( + key_map, getattr(keys, 'k%s' % key))) + fkeys.append(rs) + + # TODO Make the following (keypad 0-9,*,#) contingent on variant. + # Only concerned with TK-380 for now + for key in '0123456789*#': + xlate = {'*': 'ASTR', '#': 'POUND'} + name = xlate.get(key, key) + btn = MemSetting("keys.k%s" % name, "Keypad %s" % key, + RadioSettingValueMap( + key_map, getattr(keys, 'k%s' % name))) + fkeys.append(btn) + + def _get_settings_fsync(self, optfeat2): + fsync = self._memobj.fleetsync + + # Extended Function Section + dtxqt = MemSetting("fleetsync.data_tx_qt", "Data TX with QT/DQT", + RadioSettingValueInvertedBoolean( + not fsync.data_tx_qt)) + optfeat2.append(dtxqt) + + def get_settings(self): + """Translate the bit in the mem_struct into settings in the UI""" + sett = self._memobj.settings + passwd = self._memobj.settings.passwords + + optfeat1 = RadioSettingSubGroup("optfeat1", "Optional Features 1") + optfeat2 = RadioSettingSubGroup("optfeat2", "Optional Features 2") + optfeat = RadioSettingGroup("optfeat", "Optional Features", + optfeat1, optfeat2) + dealer = RadioSettingGroup("dealer", "Dealer Settings") + fkeys = RadioSettingGroup("keys", "Keys") + scaninf = RadioSettingGroup("scaninf", "Scan Information") + dtmfset = RadioSettingGroup("dtmfset", "DTMF") + ost = RadioSettingGroup("ost", "OST") + groups = RadioSettingGroup("groups", "Groups") + + top = RadioSettings(optfeat, dealer, fkeys, scaninf, + dtmfset, ost, groups) + + self._get_settings_groups(groups) + self._get_settings_format(optfeat1, optfeat2, scaninf) + self._get_settings_ost(ost) + self._get_settings_misc(optfeat2, dealer) + self._get_settings_keys(fkeys) + self._get_settings_fsync(optfeat2) + # If user changes passwords to blank, which is actually x20 not xFF, + # that sets impossible password. + # Read-only to view unknown passwords only + radiop = RadioSetting( + "passwords.radio", "Radio Password", + RadioSettingValueString(0, 6, + str(passwd.radio).strip('\xFF'))) + radiop.value.set_mutable(False) + optfeat1.append(radiop) + + datap = RadioSetting( + "passwords.data", "Data Password", + RadioSettingValueString(0, 6, str(passwd.data).strip('\xFF'))) + datap.value.set_mutable(False) + optfeat1.append(datap) + + pom = MemSetting( + "settings.poweronmesg", "Power on message", + RadioSettingValueString(0, 12, + str(sett.poweronmesg).strip('\xFF'))) + optfeat1.append(pom) + + sigtyp = MemSetting( + "settings.signalling_type", "Signalling Type", + RadioSettingValueList(SIG_TYPE, + current_index=int(sett.signalling_type))) + optfeat1.append(sigtyp) + + if self.TYPE[0] == "P": + bw = MemSetting("settings.battery_warn", "Battery Warning", + RadioSettingValueInvertedBoolean( + sett.battery_warn)) + optfeat1.append(bw) + + if self.TYPE[0] == "M": + ohd = MemSetting("settings.off_hook_decode", "Off Hook Decode", + RadioSettingValueInvertedBoolean( + sett.off_hook_decode)) + optfeat1.append(ohd) + + ohha = MemSetting("settings.off_hook_horn_alert", + "Off Hook Horn Alert", + RadioSettingValueInvertedBoolean( + sett.off_hook_horn_alert)) + optfeat1.append(ohha) + + minvol = MemSetting("settings.min_vol", "Minimum Volume", + RadioSettingValueList( + VOL, current_index=sett.min_vol)) + optfeat2.append(minvol) + + tv = int(sett.tone_vol) + if tv == 255: + tv = 32 + tvol = MemSetting("settings.tone_vol", "Tone Volume", + RadioSettingValueList(TVOL, current_index=tv)) + optfeat2.append(tvol) + + """sql = RadioSetting("settings.sql_level", "SQL Ref Level", + RadioSettingValueList( + SQL, SQL[int(sett.sql_level)])) + optfeat1.append(sql)""" + + # Tone Volume Section + ptone = MemSetting("settings.poweron_tone", "Power On Tone", + RadioSettingValueBoolean(sett.poweron_tone)) + optfeat2.append(ptone) + + wtone = MemSetting("settings.warn_tone", "Warning Tone", + RadioSettingValueBoolean(sett.warn_tone)) + optfeat2.append(wtone) + + ctone = MemSetting("settings.control_tone", "Control (Key) Tone", + RadioSettingValueBoolean(sett.control_tone)) + optfeat2.append(ctone) + + bot = str(sett.ptt_id_bot).strip("\xFF") + pttbot = MemSetting("settings.ptt_id_bot", "PTT Begin of TX", + RadioSettingValueString(0, 16, bot, + mem_pad_char='\xFF')) + optfeat2.append(pttbot) + + eot = str(sett.ptt_id_eot).strip("\xFF") + ptteot = MemSetting("settings.ptt_id_eot", "PTT End of TX", + RadioSettingValueString(0, 16, eot, + mem_pad_char='\xFF')) + optfeat2.append(ptteot) + + svp = str(sett.lastsoftversion).strip("\xFF") + sver = RadioSetting("not.softver", "Last Used Software Version", + RadioSettingValueString(0, 5, svp, + mem_pad_char='\xFF')) + sver.value.set_mutable(False) + dealer.append(sver) + + try: + vtmp = str(self.metadata.get('tkx80_ver', '(unknown)')) + except AttributeError: + vtmp = '' + frev = RadioSetting("not.ver", "Radio Version", + RadioSettingValueString(0, 10, vtmp)) + frev.set_doc('Radio version (as downloaded)') + frev.value.set_mutable(False) + dealer.append(frev) + + panel = MemSetting("settings.panel_test", "Panel Test", + RadioSettingValueBoolean(sett.panel_test)) + optfeat2.append(panel) + + ptun = MemSetting("settings.panel_tuning", "Panel Tuning", + RadioSettingValueBoolean(sett.panel_tuning)) + optfeat2.append(ptun) + + fmw = MemSetting("settings.firmware_prog", "Firmware Programming", + RadioSettingValueBoolean(sett.firmware_prog)) + optfeat2.append(fmw) + + clone = MemSetting("settings.clone", "Allow clone", + RadioSettingValueBoolean(sett.clone)) + optfeat2.append(clone) + + sprog = MemSetting("settings.self_prog", "Self Programming", + RadioSettingValueBoolean(sett.self_prog)) + optfeat2.append(sprog) + + # Logic Signal Section + sqlt = MemSetting("settings.sq_logic_type", "Squelch Logic Type", + RadioSettingValueList( + SLT.values(), + current_index=sett.sq_logic_type)) + optfeat2.append(sqlt) + + sqls = MemSetting("settings.sq_logic_sig", "Squelch Logic Signal", + RadioSettingValueList( + SLS.values(), + current_index=sett.sq_logic_sig)) + optfeat2.append(sqls) + + aclt = MemSetting("settings.access_log_type", "Access Logic Type", + RadioSettingValueList( + ALT.values(), + current_index=sett.access_log_type)) + optfeat2.append(aclt) + + acls = MemSetting("settings.access_log_sig", "Access Logic Signal", + RadioSettingValueList( + ALS.values(), + current_index=sett.access_log_sig)) + optfeat2.append(acls) + + # DTMF Settings + # Decode Section + deccode = str(sett.dtmf_prim_code).strip("\xFF") + decpc = MemSetting("settings.dtmf_prim_code", "Decode Primary Code", + RadioSettingValueString(0, 7, deccode)) + dtmfset.append(decpc) + + deccode = str(sett.dtmf_sec_code).strip("\xFF") + decpc = MemSetting("settings.dtmf_sec_code", "Decode Secondary Code", + RadioSettingValueString(0, 7, deccode)) + dtmfset.append(decpc) + + deccode = str(sett.dtmf_DBD_code).strip("\xFF") + decpc = MemSetting("settings.dtmf_DBD_code", + "Decode Dead Beat Disable Code", + RadioSettingValueString(0, 7, deccode, + mem_pad_char='\xFF')) + dtmfset.append(decpc) + + return top + + def _set_settings_groups(self, settings): + group_index = {} + unused_slots = [] + + # Survey the currently-mapped groups + for i in range(250): + if self._memobj.groups[i].number < 0xFF: + group_index[int(self._memobj.groups[i].number)] = i + else: + unused_slots.append(i) + + allocated = False + for i in range(250): + group_number = i + 1 + enable_setting = settings.get('group-%i-enable' % group_number) + name_setting = settings.get('group-%i-name' % group_number) + try: + group = self._memobj.groups[group_index[group_number]] + except KeyError: + if enable_setting and enable_setting.value: + slot = unused_slots.pop(0) + LOG.debug('Allocating group slot %i for group %i', + slot, group_number) + group = self._memobj.groups[slot] + group.number = group_number + group.channels = 0 + group.name = (name_setting and str(name_setting.value) or + str(group_number).ljust(10)) + allocated = True + group = None + if enable_setting and not enable_setting.value and group: + # Group is allocated, UI asked to disable it + group.fill_raw(b'\xFF') + elif group and name_setting: + # Group is allocated, set name + group.name = name_setting.value + if allocated: + LOG.debug('Compacting group mappings after new allocation') + self._compact_mappings() + + def set_settings(self, settings): + # All the actual settings we care about are MemSetting and can be + # direct applied. + all_other_settings = settings.apply_to(self._memobj) + # This should just be group geometry settings at this point + other_settings = {s.get_name(): s for s in all_other_settings} + self._set_settings_groups(other_settings) + for setting in all_other_settings: + if setting.has_apply_callback(): + setting.run_apply_callback() + + def _get_memory_base(self, mem, _mem): + mem.number = int(_mem.number) + mem.freq = int(_mem.rxfreq) * self._freqmult + if _mem.txfreq.get_raw()[0] == 0xFF: + mem.offset = 0 + mem.duplex = "off" + else: + chirp_common.split_to_offset( + mem, mem.freq, int(_mem.txfreq) * self._freqmult) + + mem.name = str(_mem.name).rstrip() + + txtone = self._decode_tone(_mem.tx_tone) + rxtone = self._decode_tone(_mem.rx_tone) + chirp_common.split_tone_decode(mem, txtone, rxtone) + if self.POWER_LEVELS: + mem.power = self.POWER_LEVELS[_mem.power] + + def _set_memory_base(self, mem, _mem): + _mem.number = mem.number + + _mem.rxfreq = mem.freq // self._freqmult + + _mem.unknown_rx = 0x3 + _mem.unknown_tx = 0x3 + + if mem.duplex == "+": + _mem.txfreq = (mem.freq + mem.offset) // self._freqmult + elif mem.duplex == "-": + _mem.txfreq = (mem.freq - mem.offset) // self._freqmult + elif mem.duplex == "off": + _mem.txfreq.fill_raw(b'\xFF') + elif mem.duplex == 'split': + _mem.txfreq = mem.offset // self._freqmult + else: + _mem.txfreq = mem.freq // self._freqmult + + step_lookup = { + 2.5: 0x0, + 6.25: 0x2, + 12.5: 0x5, + 5.0: 0x1, + } + 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 + + ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \ + chirp_common.split_tone_encode(mem) + self._encode_tone(_mem.tx_tone, txmode, txtone, txpol) + self._encode_tone(_mem.rx_tone, rxmode, rxtone, rxpol) + + _namelength = self.get_features().valid_name_length + _mem.name = mem.name.ljust(_namelength) + + if self.POWER_LEVELS: + try: + _mem.power = self.POWER_LEVELS.index(mem.power) + except ValueError: + _mem.power = self.POWER_LEVELS[0] + + +class TKx80Group(KenwoodTKx80): + def __init__(self, parent, group): + self._parent = parent + self._group = int(group) + + @property + def group(self): + return self._group + + @property + def _memobj(self): + return self._parent._memobj + + def load_mmap(self, filename): + self._parent.load_mmap(filename) + + def _compact_mappings(self): + self._parent._compact_mappings() + + def get_sub_devices(self): + return [] + + def get_features(self): + rf = self._parent.get_features() + rf.has_sub_devices = False + rf.memory_bounds = (1, 250) + return rf + + def get_raw_memory(self, number): + """Return a raw representation of the memory object, which + is very helpful for development""" + try: + mapping = self._parent._get_memory_mapping(self.group, number) + except IndexError: + return 'Memory not set' + return repr(self._memobj.memory[mapping.index]) + + def get_memory(self, number): + mem = chirp_common.Memory() + mem.number = number + try: + mapping = self._parent._get_memory_mapping(self.group, number) + except IndexError: + mem.empty = True + return mem + + _mem = self._memobj.memory[mapping.index] + + self._get_memory_base(mem, _mem) + mem.mode = MODES[_mem.wide] + mem.skip = self._get_scan(mapping.index) + + mem.extra = RadioSettingGroup("extra", "Extra") + + bs = MemSetting("beat_shift", "Beat shift", + RadioSettingValueInvertedBoolean( + not bool(_mem.beat_shift))) + mem.extra.append(bs) + + cp = MemSetting("compander", "Compander", + RadioSettingValueInvertedBoolean( + not bool(_mem.compander))) + mem.extra.append(cp) + + pttid = MemSetting("ptt_id", "PTTID", + RadioSettingValueInvertedBoolean(not _mem.ptt_id)) + mem.extra.append(pttid) + + if _mem.busy_lock == 1: + index = 0 + elif _mem.busy_lock_opt == 1: + index = 2 + elif _mem.busy_lock_opt == 0: + index = 3 + else: + index = 1 + bl = RadioSetting("busy_lock", "Busy Channel lock", + RadioSettingValueList(BCL_OPTS, current_index=index)) + + mem.extra.append(bl) + + return mem + + def set_memory(self, mem): + try: + mapping = self._parent._get_memory_mapping(self.group, mem.number, + allocate=True) + except IndexError as e: + # Out of memory + raise errors.RadioError(str(e)) + + _mem = self._memobj.memory[mapping.index] + + if mem.empty: + self._delete_memory_mapping(self.group, mem.number) + return + + self._set_memory_base(mem, _mem) + + _mem.wide = MODES.index(mem.mode) + self._set_scan(mapping.index, mem.skip) + + _mem.number = mem.number + _mem.group = self.group + + if mem.extra: + bcl = int(mem.extra['busy_lock'].value) + if bcl == 0: + _mem.busy_lock = 1 + _mem.busy_lock_opt = 3 + elif bcl == 2: + _mem.busy_lock = 0 + _mem.busy_lock_opt = 1 + elif bcl == 3: + _mem.busy_lock = 0 + _mem.busy_lock_opt = 0 + elif bcl == 1: + _mem.busy_lock = 0 + _mem.busy_lock_opt = 3 + + # extra settings + mem.extra['ptt_id'].apply_to_memobj(_mem) + mem.extra['compander'].apply_to_memobj(_mem) + mem.extra['beat_shift'].apply_to_memobj(_mem) + + return mem + + +@directory.register +class TK280_Radios(KenwoodTKx80): + """Kenwood TK-280 Radio""" + MODEL = "TK-280" + TYPE = b"P0280" + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1), + chirp_common.PowerLevel("High", watts=5)] + # VARIANTS = { + # # VERIFIED variant. Range expanded for ham bands. Orig: 146, 174 + # b"P0280\x04\xFF": (250, 144, 174, "K Non-Keypad Model"), + # b"P0280\x05\xFF": (250, 136, 162, "K2 Non-Keypad Model"), + # # Range expanded for ham bands. Orig: 146, 174 + # b"P0280\xFF\xFF": (250, 144, 174, "K3 Keypad Model"), + # b"P0280\xFF\xFF": (250, 136, 162, "K4 Keypad Model"), + # } + _range = [(136000000, 174000000)] + _steps = chirp_common.COMMON_TUNING_STEPS + (2.5, 6.25) + + +@directory.register +class TK380_Radios(KenwoodTKx80): + """Kenwood TK-380 Radio """ + MODEL = "TK-380" + TYPE = b"P0380" + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1), + chirp_common.PowerLevel("High", watts=4)] + # VARIANTS = { + # # Range expanded for ham bands. Orig: 450, 490 + # b"P0380\x06\xFF": (250, 420, 490, "K Non-Keypad Model"), + # # Range expanded for ham bands. Orig: 470, 512 + # b"P0380\x07\xFF": (250, 420, 512, "K2 Non-Keypad Model"), + # # Range expanded for ham bands. Orig: 400, 430 + # b"P0380\x08\xFF": (250, 400, 450, "K3 Non-Keypad Model"), + # # VERIFIED variant. Range expanded for ham bands. Orig: 450, 490 + # b"P0380\x0a\xFF": (250, 420, 490, "K4 Keypad Model"), + # # Range expanded for ham bands. Orig: 400, 430 + # b"P0380\xFF\xFF": (250, 400, 450, "K6 Keypad Model"), + # # Range expanded for ham bands. Orig: 470, 520 + # b"P0380\xFF\xFF": (250, 420, 520, "K5 Keypad Model"), + # } + _range = [(400000000, 520000000)] + _steps = chirp_common.COMMON_TUNING_STEPS + (6.25,) + + +@directory.register +class TK780_Radios(KenwoodTKx80): + """Kenwood TK-780 Radio """ + MODEL = "TK-780" + TYPE = b"M0780" + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5), + chirp_common.PowerLevel("High", watts=25)] + # VARIANTS = { + # # VERIFIED variant. #Range expanded for ham bands. Orig: 146, 174 + # b"M0780\x04\xFF": (250, 144, 174, "K"), + # b"M0780\x05\xFF": (250, 136, 174, "K2"), + # } + _range = [(136000000, 174000000)] + _steps = chirp_common.COMMON_TUNING_STEPS + (2.5, 6.25) + + +@directory.register +class TK880_Radios(KenwoodTKx80): + """Kenwood TK-880 Radio """ + MODEL = "TK-880" + TYPE = b"M0880" + # VARIANTS = { + # # VERIFIED variant. #Range expanded for ham bands. Orig: 450, 490 + # b"M0880\x06\xFF": (250, 420, 490, "K"), + # # Range expanded for ham bands. Orig: 485, 512 + # b"M0880\x07\xFF": (250, 420, 512, "K2"), + # # Range expanded for ham bands. Orig: 400, 430 + # b"M0880\x08\xFF": (250, 400, 450, "K3"), + # } + _range = [(400000000, 520000000)] + _steps = chirp_common.COMMON_TUNING_STEPS + (6.25, 12.5) + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5), + chirp_common.PowerLevel("High", watts=25)] diff --git a/chirp/drivers/tk481.py b/chirp/drivers/tk481.py new file mode 100644 index 0000000..f03cd74 --- /dev/null +++ b/chirp/drivers/tk481.py @@ -0,0 +1,395 @@ +# Copyright 2024 Dan Smith <chirp@f.danplanet.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from collections import namedtuple +import logging + +from chirp import bitwise +from chirp import chirp_common +from chirp import directory +from chirp.drivers import tk280 +from chirp.settings import RadioSetting, RadioSettingSubGroup, MemSetting +from chirp.settings import RadioSettingValueBoolean, RadioSettingValueString +from chirp.settings import RadioSettingValueInvertedBoolean +from chirp.settings import RadioSettingGroup + +TRUNK_DEFS = """ +struct trunk_settings { + ul16 sys_start[32]; + u8 systems; +}; +""" + +MEM_FORMAT = tk280.DEFS + TRUNK_DEFS + """ +struct trunk_settings trunk; + +#seekto 0x004A; +lbit system_lockout[32]; +lbit trunk_systems[32]; // 1 if system is trunking, 0 if conventional + +#seekto 0x005C; +struct { + u16 first_system; + u16 last_system; // nope +} state; + +#seekto 0x0082; +struct settings settings; + +#seekto 0x0110; +struct keys keys; + +#seekto 0x1E7; +struct misc misc; + +struct system { + u8 system; + u8 channels; + u8 unknown1; + char name[10]; + u8 unknown2; + u8 unknown3; + u8 unknown4; + u8 unknown5[16]; +}; + +struct channel { + u8 number; + lbcd rxfreq[4]; + lbcd txfreq[4]; + u8 unknown_rx:4, + rx_step:4; // 0x5 + u8 unknown_tx:4, + tx_step:4; // 0x5 + ul16 rx_tone; + ul16 tx_tone; + char name[10]; + u8 unknown4; // 0xFF + u8 unknown4_1:4, + power:1, // 0=low, 1=high + unknown4_2:3; + u8 unknown5_1:2, + talkaround:1, // 1=No, 0=Yes + call:1, // 1=No, 0=Yes + unknown5_2:1, + grouplockout:1, // 1=No, 0=Yes + unknown5_3:2; //0xFB + u8 unknown6[4]; // 0xFF +}; +""" + +LOG = logging.getLogger(__name__) +SystemDef = namedtuple('SystemDef', ('index', 'number')) + + +class TKx80_Trunked(tk280.KenwoodTKx80): + _system = 0 + + def process_mmap(self): + memobj = bitwise.parse(MEM_FORMAT, self._mmap) + first = memobj.state.first_system + + my_format = MEM_FORMAT + '#seekto 0x%04x;\n' % first + for i in range(32): + start = memobj.trunk.sys_start[i] + if start == 0xFFFF: + # Not used + continue + # We need to know how many channels each system has in some easy- + # to-calculate way without having to parse all the headers. To + # avoid another intermediate parse, just grab the start and add + # one for the number of channels count. + count = self._mmap[start + 1][0] + sys_format = ( + "struct { \n" + " struct system sys;\n" + " struct channel channels[0x%x];\n" + "} system%i;\n") % (count, i) + my_format += sys_format + self._memobj = bitwise.parse(my_format, self._mmap) + + def _get_system_info(self, index): + if self._memobj.trunk.sys_start[index] == 0xFFFF: + raise IndexError('No such system') + system = getattr(self._memobj, 'system%i' % index) + system_start = self._memobj.trunk.sys_start[index] + system_end = system_start + (32 * (system.sys.channels + 1)) + return system_start, system_end, system + + def _expand_system(self, system_number, amount=1): + """Expand a system to make more room for memories""" + + my_index = system_number - 1 + try: + system_start, system_end, system = self._get_system_info(my_index) + system.sys.channels += amount + except IndexError: + system = None + # If we're the first, we'll start at beginning of memory + system_start = 0x0300 + # Find first used system before me, grab its start+size + for i in range(my_index): + try: + _, system_start, _ = self._get_system_info(i) + except IndexError: + continue + LOG.debug('Allocating new system %i at 0x%04x', + my_index, system_start) + # An empty system has only the 32-byte header + system_end = system_start + 32 + + # Add space to all the system starts after this one + for index in reversed(range(32)): + if index > my_index: + if self._memobj.trunk.sys_start[index] == 0xFFFF: + continue + self._memobj.trunk.sys_start[index] += (amount * 32) + elif index == my_index: + self._memobj.trunk.sys_start[index] = system_start + + # Calculate the new end of the system we need to expand: + # number of channels (plus one for the system header), 32 bytes each + new_end = system_end + (amount * 32) + + # Copy everything to the new location + self._mmap[new_end] = self._mmap[system_end:-(amount * 32)] + + # Clear the new hole and add to the channels + self._mmap[system_end] = b'\xFF' * 32 * amount + + # If we allocated a new system, bootstrap the channel count, mark as + # non-trunked, increase the total system count + if system is None: + self._mmap[system_start + 1] = amount + self._memobj.trunk_systems[my_index] = 0 + self._memobj.trunk.systems += 1 + + # Rebuild the internal memory object + self.process_mmap() + LOG.debug('Expanded system %i index %i to %i channels ' + '(start 0x%04x new end %04x)', + system_number, my_index, + system and system.sys.channels or amount, + system_start, new_end) + + return getattr(self._memobj, 'system%i' % my_index) + + def _reduce_system(self, system_number, channel): + """Remove a memory slot from a system""" + + my_index = system_number - 1 + system_start, system_end, system = self._get_system_info(my_index) + + # Shift memories up in the system, or fail before accounting if we + # do not find the one specified + found_channel = False + for i in range(0, system.sys.channels): + if system.channels[i].number == channel: + found_channel = True + elif found_channel: + system.channels[i - 1].set_raw(system.channels[i].get_raw()) + if not found_channel: + raise IndexError('Memory %i not mapped' % channel) + + # Remove space from all the system starts after this one + for index in reversed(range(32)): + if index > my_index: + if self._memobj.trunk.sys_start[index] == 0xFFFF: + continue + self._memobj.trunk.sys_start[index] -= 32 + + # Calculate the new end of the system we need to expand: + # number of channels (plus one for the system header), 32 bytes each + new_end = system_end - 32 + + # Copy everything to the new location + self._mmap[new_end] = self._mmap[system_end:] + + # Clear the hole at the end (if necessary) and decrement the channels + self._mmap[-32] = b'\xFF' * 32 + system.sys.channels -= 1 + + # Rebuild the internal memory object + self.process_mmap() + LOG.debug('Reduced system %i index %i to %i channels ' + '(start 0x%04x new end %04x)', + system_number, my_index, + system.sys.channels, system_start, new_end) + + def get_features(self): + rf = super().get_features() + rf.memory_bounds = (1, 250) + # These are all NFM only? + rf.valid_modes = ['NFM'] + rf.valid_skips = ['', 'S'] + 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') + return [ + tk280.TKx80SubdevMeta.make_subdev( + self, TKx80System, i, + to_copy, + VARIANT=str(getattr(self._memobj, + 'system%i' % i).sys.name).strip(' \xFF'))( + self, i + 1) + for i in range(32) + if self._memobj.trunk.sys_start[i] != 0xFFFF] + + def _get_memory(self, number): + system = getattr(self._memobj, 'system%i' % (self._system - 1)) + for i in range(system.sys.channels): + if int(system.channels[i].number) == number: + return system.channels[i] + raise IndexError('Memory %i not mapped' % number) + + def get_raw_memory(self, number): + return repr(self._get_memory(number)) + + def get_memory(self, number): + mem = chirp_common.Memory() + try: + _mem = self._get_memory(number) + except IndexError: + mem.number = number + mem.empty = True + return mem + self._get_memory_base(mem, _mem) + mem.mode = 'NFM' + mem.skip = '' if bool(_mem.grouplockout) else 'S' + + mem.extra = RadioSettingGroup('extra', 'Extra') + rs = MemSetting('call', 'Call', + RadioSettingValueInvertedBoolean(not _mem.call)) + mem.extra.append(rs) + + return mem + + def set_memory(self, mem): + try: + _mem = self._get_memory(mem.number) + except IndexError: + system = self._parent._expand_system(self._system) + _mem = system.channels[system.sys.channels - 1] + # Immediately set the channel number on the new memory in case + # fail to do anything below (or delete it immediately) + _mem.number = mem.number + + if mem.empty: + self._parent._reduce_system(self._system, mem.number) + return + + self._set_memory_base(mem, _mem) + + _mem.talkaround = 0 if not mem.duplex else 1 + _mem.grouplockout = 1 if mem.skip == '' else 0 + + if mem.extra: + mem.extra['call'].apply_to_memobj(_mem) + + def _set_settings_groups(self, settings): + for i in range(32): + try: + enabled = settings['system-%i-enable' % i].value + except KeyError: + enabled = True + try: + name = str(settings['system-%i-name' % i].value) + except KeyError: + name = None + try: + _, _, system = self._get_system_info(i) + except IndexError: + if enabled: + new_system = self._expand_system(i + 1) + new_system.sys.name = ('System %i' % (i + 1)).ljust(10) + else: + if name is not None: + system.sys.name = name + + def _get_settings_groups(self, groups): + groups.set_shortname('Systems') + for i in range(32): + rsg = RadioSettingSubGroup('system-%i' % i, 'System %i' % (i + 1)) + rse = RadioSetting('system-%i-enable' % i, 'Enabled', + RadioSettingValueBoolean( + self._memobj.trunk.sys_start[i] != 0xFFFF)) + rse.set_volatile(True) + rse.set_doc('Requires reload of file after changing!') + if rse.value: + # FIXME: Don't allow deleting systems yet + rse.value.set_mutable(False) + rsg.append(rse) + if rse.value: + _, _, system = self._get_system_info(i) + name = str(system.sys.name).strip() + else: + name = '' + + rs = RadioSetting('system-%i-name' % i, 'Name', + RadioSettingValueString( + 0, 10, name.strip(' \xFF'))) + rs.value.set_mutable(bool(rse.value)) + rsg.append(rs) + + rs = RadioSetting('system-%i-lockout' % i, 'Scan', + RadioSettingValueBoolean( + self._memobj.system_lockout[i])) + rs.value.set_mutable(bool(rse.value)) + rsg.append(rs) + groups.append(rsg) + + # FIXME: Not yet decoded + def _get_settings_fsync(self, optfeat2): + return + + def _get_settings_ost(self, ost): + return + + def _get_settings_format(self, optfeat1, optfeat2, scaninf): + return + + +class TKx80System(TKx80_Trunked): + def __init__(self, parent, system): + self._system = system + self._parent = parent + + @property + def _memobj(self): + return self._parent._memobj + + +@directory.register +class TK481(TKx80_Trunked): + MODEL = 'TK-481' + TYPE = b'PG481' + POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1), + chirp_common.PowerLevel("High", watts=2.5)] + _range = [(896000000, 941000000)] + _steps = chirp_common.COMMON_TUNING_STEPS + (6.25, 12.5) + + +@directory.register +class TK981(TKx80_Trunked): + MODEL = 'TK-981' + TYPE = b'M0981' + POWER_LEVELS = [] + _range = [(896000000, 941000000)] + _steps = chirp_common.COMMON_TUNING_STEPS + (6.25, 12.5) diff --git a/chirp/drivers/tk690.py b/chirp/drivers/tk690.py index e3c25ad..a248f41 100644 --- a/chirp/drivers/tk690.py +++ b/chirp/drivers/tk690.py @@ -150,6 +150,11 @@ struct { char soft_ver[5]; } properties; +struct { + lbcd rxfreq[4]; // 00-03 + lbcd txfreq[4]; // 04-07 +} test_frequencies[16]; + #seekto 0x40A0; struct { char name[16]; @@ -544,9 +549,10 @@ class Kenwoodx90(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): BAUD_RATE = 9600 VARIANT = "" MODEL = "" - POWER_LEVELS = [chirp_common.PowerLevel("High", watts=45), - chirp_common.PowerLevel("Low", watts=5)] + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=110), + chirp_common.PowerLevel("Low", watts=45)] MODES = ["NFM", "FM"] # 12.5 / 25 Khz + STEPS = [5.0] _name_chars = 8 _group_name_chars = 8 @@ -610,6 +616,7 @@ class Kenwoodx90(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): rf.valid_dtcs_codes = DTCS_CODES rf.valid_bands = [self._range] rf.valid_name_length = self._name_chars + rf.valid_tuning_steps = self.STEPS rf.memory_bounds = (1, self._upper) return rf @@ -877,7 +884,7 @@ class Kenwoodx90(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): if mem.power is None: _mem.power = 0 else: - self.POWER_LEVELS.index(mem.power) + _mem.power = self.POWER_LEVELS.index(mem.power) _mem.wide = self.MODES.index(mem.mode) @@ -1044,7 +1051,10 @@ class Kenwoodx90(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): "Basic Settings") button_assignments = RadioSettingGroup("button_assignments", "Configurable Button Functions") - group = RadioSettings(basic_settings, button_assignments) + test_frequencies = RadioSettingGroup("test_frequencies", + "Test Frequencies") + group = RadioSettings(basic_settings, button_assignments, + test_frequencies) # Basic Settings: rs = RadioSetting("head_type", @@ -1096,6 +1106,28 @@ class Kenwoodx90(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): "Configured function for "+buttonName+" button"+_fullHeadWarning, button_func_setting) button_assignments.append(rs) + + for index in range(0, 16): + rxfreq = int(self._memobj.test_frequencies[index]["rxfreq"])*10 + txfreq = int(self._memobj.test_frequencies[index]["txfreq"])*10 + # don't populate invalid values + if not ((self._range[0] < rxfreq < self._range[1]) or + (self._range[0] < txfreq < self._range[1])): + rs = RadioSetting("add_testfreq_%i" % index, + "Add test frequency #%i" % index, + RadioSettingValueBoolean(False)) + rs.set_volatile(True) + test_frequencies.append(rs) + else: + for direction in ["rx", "tx"]: + key = "set_testfreq_%i_%s" % (index, direction) + name = "test frequency %i %s" % (index+1, direction) + rs = RadioSetting(key, name, + RadioSettingValueInteger( + self._range[0]/10, self._range[1]/10, + self._memobj.test_frequencies[index] + [direction+"freq"])) + test_frequencies.append(rs) return group def set_settings(self, settings): @@ -1117,6 +1149,18 @@ class Kenwoodx90(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): elif settingKey == "poweron_msg": self._memobj.poweron_msg = _filter_settings_string( button.value.get_value()) + elif groupKey == "test_frequencies": + keyItems = settingKey.split("_") + if keyItems[0] == "set": + self._memobj.test_frequencies[ + int(keyItems[2])][ + keyItems[3]+"freq"] = int(button.value) + elif keyItems[0] == "add" and button.value.get_value(): + centerFreq = (self._range[0]+self._range[1])/2/10 + self._memobj.test_frequencies[ + int(keyItems[2])]["rxfreq"] = centerFreq + self._memobj.test_frequencies[ + int(keyItems[2])]["txfreq"] = centerFreq @directory.register @@ -1128,7 +1172,7 @@ class TK690Radio(Kenwoodx90): VARIANTS = { b"M0690\x01": (160, 28, 37, "K"), # see note below b"M0690\x02": (160, 35, 43, "K2"), - b"M0690\x03": (160, 136, 156, "K3") + b"M0690\x03": (160, 40, 54, "K3") } @@ -1141,6 +1185,7 @@ class TK790Radio(Kenwoodx90): b"M0790\x04": (160, 144, 174, "K"), # see note below b"M0790\x05": (160, 136, 156, "K2") } + STEPS = [5.0, 6.25, 7.5, 12.5] @directory.register @@ -1154,6 +1199,7 @@ class TK890Radio(Kenwoodx90): b"M0890\x08": (160, 403, 430, "K3"), b"M0890\x09": (160, 450, 480, "K(H)") } + STEPS = [5.0, 6.25, 12.5] # Note: # These radios originally are constrained to certain band segments but the diff --git a/chirp/drivers/tk8160.py b/chirp/drivers/tk8160.py index 0aff91d..879df69 100644 --- a/chirp/drivers/tk8160.py +++ b/chirp/drivers/tk8160.py @@ -308,6 +308,7 @@ class TKx160Radio(chirp_common.CloneModeRadio): rf.has_cross = True rf.has_bank = False rf.has_sub_devices = not self.VARIANT + rf.has_dynamic_subdevices = rf.has_sub_devices rf.has_tuning_step = False rf.has_rx_dtcs = True rf.has_settings = True @@ -603,9 +604,9 @@ class TKx160Radio(chirp_common.CloneModeRadio): 'zonecount', 'Number of Zones', settings.RadioSettingValueInteger(1, 128, num_zones)) zone_count.set_doc('Number of zones in the radio. ' - 'Requires a save and re-load of the file to take ' - 'effect. Reducing this number will DELETE ' + 'Reducing this number will DELETE ' 'memories in the affected zones!') + zone_count.set_volatile(True) zones.append(zone_count) keys = self.make_key_group(self._memobj.keys, KEY_NAMES, diff --git a/chirp/drivers/tk8180.py b/chirp/drivers/tk8180.py index 3e04a55..b439f8c 100644 --- a/chirp/drivers/tk8180.py +++ b/chirp/drivers/tk8180.py @@ -20,10 +20,12 @@ from collections import OrderedDict from chirp import chirp_common, directory, memmap, errors, util from chirp import bitwise +from chirp.settings import MemSetting, RadioSettingValueInvertedBoolean from chirp.settings import RadioSettingGroup, RadioSetting from chirp.settings import RadioSettingValueBoolean, RadioSettingValueList from chirp.settings import RadioSettingValueString, RadioSettingValueInteger from chirp.settings import RadioSettings, RadioSettingSubGroup +from chirp.settings import RadioSettingValueMap LOG = logging.getLogger(__name__) @@ -62,7 +64,8 @@ struct { u8 alert_tone; u8 sidetone; u8 locator_tone; - u8 unknown3[2]; + u8 battsave; // FF=off, 30=short, 31=med, 32=long + u8 battwarn; // FF=off, 30=Transmit, 31=Always, 32=AlwaysBeep u8 ignition_mode; u8 ignition_time; // In tens of minutes (6 = 1h) u8 micsense; @@ -71,13 +74,17 @@ struct { u8 unknown4; // 0x0180 - u8 unknown5[16]; + u8 pttid_type; // 30=DTMF, 31=FleetSync + u8 pttid_dtmf_bot_count; // number of digits + u8 pttid_dtmf_bot_code[8]; // digits, 0xFF padded + u8 pttid_dtmf_eot_count; // number of digits + u8 pttid_dtmf_eot_code[8]; // digits, 0xFF padded - // 0x0190 - u8 unknown6[3]; + // 0x0193 u8 pon_msgtype; u8 unknown7[8]; - u8 unknown8_1:2, + u8 battstatus:1, + unknown8_1:1, ssi:1, busy_led:1, power_switch_memory:1, @@ -110,6 +117,50 @@ struct { ul16 txtone; } ost_tones[40]; +// Button config +// 0xFF = none 0x00=2t 0x26=lamp 04=autotel 01=autodial 12= 5=chentry +// 13=clock 02=autodial-prog 08=call1 09=call2 (up to call6) 21=function +// 20=fixedvol 28=lowpow 2A=monitor 2B=monmoment 42=TA 43=teldisc +// 1E=displaychar 3D=sqlvl 3E=sqoff 3F=sqoffmom 32=password +// 10=grpup (but more changes) +// 0E=grpdn (but more changes) +// 0x582 selector mode FF=none 30=group 31=channel +// 0x583 keypad type ff=none 30=dtmf +// 0x584 keypad op: +// 0x58E 0x04 list sel key (inverted) +// ff=none +#seekto 0x0582; +u8 selector_knob; // FF=none 30=group 31=channel +u8 keypad_type; // ff=none 30=12-key +// 30=channel 31=OST 32=DTMF(autodial) 33=DTMF(keypad auto ptt) +// 34=FS(SC) 35=FS(ST) 36=FS(SC+ST) +u8 keypad_op; +u8 lsk_unknown1:5, + list_selector_key:1, + lsk_unknown2:3; +#seekto 0x05C0; +// side1 primary 0x5C0 +// S 0x5C8 +// A 0x5D0 +// B 0x5D8 +// C 0x5E0 +// side2 primary 0x5E8 +// two? +// aux primary 0x600 +// 0 0x608 +// 1 0x610 +// .. * +// 0x668 ? +// mic pf1 0x688 +// mic pf2 0x690 + +struct button { + u8 primary; + u8 secondary; + u8 unknown[6]; // These all change for some of the more advanced ones +}; +struct button buttons[26]; + #seekto 0x0A00; ul16 zone_starts[128]; @@ -135,11 +186,16 @@ struct memory { u8 number; lbcd rx_freq[4]; lbcd tx_freq[4]; - u8 unknown1[2]; + u8 unknown11:4, + rx_step:4; + u8 unknown12:4, + tx_step:4; ul16 rx_tone; ul16 tx_tone; char name[12]; - u8 unknown2[19]; + u8 unknown1[2]; + u8 pttid; + u8 unknown2[16]; u8 unknown3_1:4, highpower:1, unknown3_2:1, @@ -178,12 +234,141 @@ DATEFMT = ['Day/Month', 'Month/Day'] MICSENSE = ['On'] ONLY_MOBILE_SETTINGS = ['power_switch_memory', 'off_hook_decode', 'ignition_sense', 'mvp', 'it', 'ignition_mode'] - +PTTID_SETTINGS = { + 'Off': 0xFF, + 'BOT': 0x30, + 'EOT': 0x31, + 'Both': 0x32, +} +PTTID_TYPES = { + 'DTMF': 0x30, + 'FleetSync': 0x31, +} +BATTSAVE_SETTINGS = { + 'Off': 0xFF, + 'Short': 0x30, + 'Medium': 0x31, + 'Long': 0x32, +} +BATTWARN_SETTINGS = { + 'Off': 0xFF, + 'Transmit': 0x30, + 'Always': 0x31, + 'Always with Beep': 0x32, +} +# The buttons in memory are not logically arranged for display and sorting +# would do weird things, so map them manually here +BUTTONS = { + 'Side 1': 0, + 'Side 2': 5, + 'S': 1, + 'A': 2, + 'B': 3, + 'C': 4, + # Skip 2 + 'Top Aux': 8, + 'DTMF 0': 9, + 'DTMF 1': 10, + 'DTMF 2': 11, + 'DTMF 3': 12, + 'DTMF 4': 13, + 'DTMF 5': 14, + 'DTMF 6': 15, + 'DTMF 7': 16, + 'DTMF 8': 17, + 'DTMF 9': 18, + 'DTMF *': 19, + 'DTMF #': 20, + 'Mic PF1': 24, + 'Mic PF2': 25, +} +# IDs of the buttons that can only be primary +PRIMARY_ONLY = [0x0E, 0x10, 0x21, 0x2B, 0x3F, 0x4B, 0x4C] +BUTTON_FUNCTIONS = { + 'None': 0xFF, + '2-tone': 0x00, + 'Autodial': 0x01, + 'Autodial Programming': 0x02, + # 0x03 + 'Auto Telephone': 0x04, + # 0x06 0x07 + 'Call 1': 0x08, + 'Call 2': 0x09, + 'Call 3': 0x0A, + 'Call 4': 0x0B, + 'Call 5': 0x0C, + 'Call 6': 0x0D, + # 0x0D + 'CH/GID Down': 0x0E, + # 0x0F + 'CH/GID Up': 0x10, + # 0x11 + 'Channel Entry': 0x12, + 'Clock': 0x13, + 'Display Character': 0x1E, + 'Fixed Volume': 0x20, + 'Function': 0x21, + 'Monitor': 0x2A, + 'Monitor Momentary': 0x2B, + 'Transceiver Password': 0x32, + 'Squelch Level': 0x3D, + 'Squelch Off': 0x3E, + 'Squelch Off (momentary)': 0x3F, + 'Talk Around': 0x42, + 'Telephone Disconnect': 0x43, + 'Zone Down': 0x4B, + 'Zone Up': 0x4C, + 'CH/GID Recall': 0x4E, +} +# These are only available on the portable transceiver +PORTABLE_BUTTON_FUNCTIONS = { + 'AUX': 0x05, + 'Lamp': 0x26, + 'Low TX Power': 0x28, +} +# These are only available on the mobile transceiver +MOBILE_BUTTON_FUNCTIONS = { +} +KNOB_MODE = { + 'None': 0xFF, + 'Group': 0x30, + 'Channel': 0x31, +} +KEYPAD_TYPE = { + 'None': 0xFF, + '12-key': 0x30, +} +KEYPAD_OP = { + 'None': 0xFF, + 'Channel': 0x30, + 'OST': 0x31, + 'DTMF (autodial)': 0x32, + 'DTMF (Keypad Auto PTT)': 0x33, + 'FleetSync (Selcall)': 0x34, + 'FleetSync (Status)': 0x35, + 'FleetSync (Selcall+Status)': 0x36, +} POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5), chirp_common.PowerLevel("High", watts=50)] +def decode_dtmf(array): + return ''.join('%x%x' % (int(i) & 0x0F, (int(i) & 0xF0) >> 4) + for i in array if i != 0xFF) + + +def encode_dtmf(string): + nibs = [int(c, 16) for c in string] + nibs += [0xF for i in range(16 - len(nibs))] + bytevals = [(nibs[i + 1] << 4) | nibs[i] for i in range(0, 16, 2)] + return bytevals + + +def reverse_dict(d): + return {v: k for k, v in d.items()} + + def set_choice(setting, obj, key, choices, default='Off'): settingstr = str(setting.value) if settingstr == default: @@ -389,6 +574,11 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): _system_start = 0x0B00 _memsize = 0xD100 + @property + def is_mobile(self): + """True if this is a mobile transceiver""" + return self.MODEL[3] in ('78') + def __init__(self, *a, **k): self._zones = [] chirp_common.CloneModeRadio.__init__(self, *a, **k) @@ -489,7 +679,7 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): mem_format += '\n\n' + ( SYSTEM_MEM_FORMAT % { 'addr': addr, - 'count': max(count, 2), # bitwise bug, one-element array + 'count': max(count, 1), # Never allow array of zero 'index': index}) self._memobj = bitwise.parse(mem_format, self._mmap) @@ -508,7 +698,7 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): for index, count in enumerate(zone_sizes): new_format += SYSTEM_MEM_FORMAT % { 'addr': addr, - 'count': max(count, 2), # bitwise bug + 'count': max(count, 1), # Never allow array of zero 'index': index} self._zones.append((addr, count)) addr += 0x20 + (count * 0x30) @@ -600,6 +790,7 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): rf.has_settings = True rf.has_bank = False rf.has_sub_devices = True + rf.has_dynamic_subdevices = True rf.has_rx_dtcs = True rf.can_odd_split = True rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross'] @@ -717,6 +908,12 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): skipbit = skipbyte & (1 << (mem.number - 1) % 8) mem.skip = skipbit and 'S' or '' + mem.extra = RadioSettingGroup('extra', 'Extra') + mem.extra.append(MemSetting( + 'pttid', 'PTTID', + RadioSettingValueMap(PTTID_SETTINGS.items(), + int(_mem.pttid)))) + return mem def set_memory(self, mem): @@ -744,14 +941,18 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): 'memory allocation') # Default values for unknown things - _mem.unknown1[0] = 0x36 - _mem.unknown1[1] = 0x36 - _mem.unknown2 = [0xFF for i in range(0, 19)] + _mem.unknown11 = 0x3 + _mem.unknown12 = 0x3 + _mem.unknown1 = [0xFF, 0xFF] + _mem.unknown2 = [0xFF for i in range(0, 16)] _mem.unknown3_1 = 0xF _mem.unknown3_2 = 0x1 _mem.unknown3_3 = 0x0 _mem.unknown4 = 0xFF + # Defaults for known things that might not always get set + _mem.pttid = 0xFF + if mem.empty: LOG.debug('Need to shrink zone %i' % self._zone) # Make the memory sort to the end, and sort the zone @@ -787,12 +988,34 @@ 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, + 6.25: 0x3, + 12.5: 0x3, + 5: 0x2, + } + # 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) + skipbyte = self._memobj.skipflags[(mem.number - 1) // 8] if mem.skip == 'S': skipbyte |= (1 << (mem.number - 1) % 8) else: skipbyte &= ~(1 << (mem.number - 1) % 8) + for setting in mem.extra: + setting.apply_to_memobj(_mem) + def _pure_choice_setting(self, settings_key, name, choices, default='Off'): if default is not None: ui_choices = [default] + choices @@ -824,7 +1047,7 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): def _get_common1(self): settings = self._memobj.settings - common1 = RadioSettingGroup('common1', 'Common 1') + common1 = RadioSettingSubGroup('common1', 'Common 1') common1.append(self._pure_choice_setting('sublcd', 'Sub LCD Display', @@ -903,7 +1126,7 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): def _get_common2(self): settings = self._memobj.settings - common2 = RadioSettingGroup('common2', 'Common 2') + common2 = RadioSettingSubGroup('common2', 'Common 2') def apply_ponmsgtext(setting): settings.pon_msgtext = ( @@ -989,6 +1212,47 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): return common2 + def _get_common3(self): + settings = self._memobj.settings + group = RadioSettingSubGroup('common3', 'Common 3') + + rs = MemSetting('settings.battsave', 'Battery Save', + RadioSettingValueMap(BATTSAVE_SETTINGS.items(), + settings.battsave)) + group.append(rs) + + rs = MemSetting('settings.battwarn', 'Battery Warning', + RadioSettingValueMap(BATTWARN_SETTINGS.items(), + settings.battwarn)) + group.append(rs) + + rs = MemSetting('settings.battstatus', 'Battery Status', + RadioSettingValueInvertedBoolean( + not settings.battstatus)) + group.append(rs) + + rs = MemSetting('settings.pttid_type', 'PTTID Type', + RadioSettingValueMap(PTTID_TYPES.items(), + settings.pttid_type)) + group.append(rs) + + def apply_dtmf(setting, which): + setattr(settings, which, encode_dtmf(str(setting.value).strip())) + + code = decode_dtmf(settings.pttid_dtmf_bot_code) + rs = RadioSetting('pttid_bot', 'Beginning of Transmit', + RadioSettingValueString(0, 16, code)) + rs.set_apply_callback(apply_dtmf, 'pttid_dtmf_bot_code') + group.append(rs) + + code = decode_dtmf(settings.pttid_dtmf_eot_code) + rs = RadioSetting('pttid_eot', 'End of Transmit', + RadioSettingValueString(0, 16, code)) + rs.set_apply_callback(apply_dtmf, 'pttid_dtmf_eot_code') + group.append(rs) + + return group + def _get_conventional(self): settings = self._memobj.settings @@ -1022,9 +1286,9 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): RadioSettingValueInteger( 1, 128, len(self._zones))) zone_count.set_doc('Number of zones in the radio. ' - 'Requires a save and re-load of the ' - 'file to take effect. Reducing this number ' + 'Reducing this number ' 'will DELETE memories in affected zones!') + zone_count.set_volatile(True) zones.append(zone_count) for i in range(len(self._zones)): @@ -1032,8 +1296,9 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): _zone = getattr(self._memobj, 'zone%i' % i).zoneinfo _name = str(_zone.name).rstrip('\x00') - name = RadioSetting('name%i' % i, 'Name', - RadioSettingValueString(0, 12, _name)) + name = MemSetting('zone%i.zoneinfo.name' % i, 'Name', + RadioSettingValueString(0, 12, _name, + mem_pad_char='\x00')) zone.append(name) def apply_timer(setting, key, zone_number): @@ -1050,32 +1315,34 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): return val timer = RadioSetting( - 'timeout', 'Time-out Timer', + 'z%itimeout' % i, 'Time-out Timer', RadioSettingValueInteger(15, 1200, collapse(_zone.timeout))) timer.set_apply_callback(apply_timer, 'timeout', i) zone.append(timer) timer = RadioSetting( - 'tot_alert', 'TOT Pre-Alert', + 'z%itot_alert' % i, 'TOT Pre-Alert', RadioSettingValueInteger(0, 10, collapse(_zone.tot_alert))) timer.set_apply_callback(apply_timer, 'tot_alert', i) zone.append(timer) timer = RadioSetting( - 'tot_rekey', 'TOT Re-Key Time', + 'z%itot_rekey' % i, 'TOT Re-Key Time', RadioSettingValueInteger(0, 60, collapse(_zone.tot_rekey))) timer.set_apply_callback(apply_timer, 'tot_rekey', i) zone.append(timer) timer = RadioSetting( - 'tot_reset', 'TOT Reset Time', + 'z%itot_reset' % i, 'TOT Reset Time', RadioSettingValueInteger(0, 15, collapse(_zone.tot_reset))) timer.set_apply_callback(apply_timer, 'tot_reset', i) zone.append(timer) - zone.append(self._inverted_flag_setting( - 'bcl_override', 'BCL Override', - _zone)) + rs = MemSetting('zone%i.zoneinfo.bcl_override' % i, + 'BCL Override', + RadioSettingValueInvertedBoolean( + not _zone.bcl_override)) + zone.append(rs) zones.append(zone) @@ -1104,8 +1371,9 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): 'OST %i' % (i + 1)) cur = str(_ost.name).rstrip('\x00') - name = RadioSetting('name%i' % i, 'Name', - RadioSettingValueString(0, 12, cur)) + name = MemSetting('ost_tones[%i].name' % i, 'Name', + RadioSettingValueString(0, 12, cur, + mem_pad_char='\x00')) ost.append(name) if _ost.rxtone == 0xFFFF: @@ -1138,22 +1406,74 @@ class KenwoodTKx180Radio(chirp_common.CloneModeRadio): ostgroup.append(ost) + def _get_keys(self): + if self.is_mobile: + model_functions = MOBILE_BUTTON_FUNCTIONS + else: + model_functions = PORTABLE_BUTTON_FUNCTIONS + + pri_functions = model_functions | BUTTON_FUNCTIONS + sec_functions = ( + {k: v for k, v in (model_functions | BUTTON_FUNCTIONS).items() + if v not in PRIMARY_ONLY}) + + group = RadioSettingGroup('keys', 'Keys') + pri = RadioSettingSubGroup('primary', 'Primary') + sec = RadioSettingSubGroup('secondary', 'Secondary') + buttons = self._memobj.buttons + + rs = MemSetting('selector_knob', 'Selector Knob', + RadioSettingValueMap(KNOB_MODE.items(), + self._memobj.selector_knob)) + group.append(rs) + + rs = MemSetting('keypad_type', 'Keypad Type', + RadioSettingValueMap(KEYPAD_TYPE.items(), + self._memobj.keypad_type)) + group.append(rs) + + rs = MemSetting('keypad_op', 'Keypad Operation', + RadioSettingValueMap(KEYPAD_OP.items(), + self._memobj.keypad_op)) + group.append(rs) + + rs = MemSetting('list_selector_key', 'List Selector Key', + RadioSettingValueInvertedBoolean( + not self._memobj.list_selector_key)) + group.append(rs) + + for key, index in BUTTONS.items(): + rs = MemSetting('buttons[%i].primary' % index, key, + RadioSettingValueMap(pri_functions.items(), + buttons[index].primary)) + pri.append(rs) + + rs = MemSetting('buttons[%i].secondary' % index, key, + RadioSettingValueMap(sec_functions.items(), + buttons[index].secondary)) + sec.append(rs) + group.append(pri) + group.append(sec) + + return group + def get_settings(self): settings = self._memobj.settings zones = self._get_zones() common1 = self._get_common1() common2 = self._get_common2() + common3 = self._get_common3() + common = RadioSettingGroup('common', 'Common', + common1, common2, common3) conv = self._get_conventional() - top = RadioSettings(zones, common1, common2, conv) + keys = self._get_keys() + top = RadioSettings(zones, common, conv, keys) return top def set_settings(self, settings): - for element in settings: - if not isinstance(element, RadioSetting): - self.set_settings(element) - continue - elif element.get_name() == '_zonecount': + for element in settings.apply_to(self._memobj): + if element.get_name() == '_zonecount': new_zone_count = int(element.value) zone_sizes = [x[1] for x in self._zones[:new_zone_count]] if len(self._zones) > new_zone_count: diff --git a/chirp/drivers/tmd710.py b/chirp/drivers/tmd710.py index f517245..8768039 100644 --- a/chirp/drivers/tmd710.py +++ b/chirp/drivers/tmd710.py @@ -85,7 +85,7 @@ def _connect_radio(radio): """Determine baud rate and verify radio on-line""" global BAUD xid = "D710" + radio.SHORT - resp = kenwood_live.get_id(radio.pipe) + resp = kenwood_live.KenwoodLiveRadio().get_id(radio.pipe) BAUD = radio.pipe.baudrate # As detected by kenwood_live LOG.debug("Got [%s] at %i Baud." % (resp, BAUD)) resp = resp[3:] # Strip "ID " prefix diff --git a/chirp/drivers/ts2000.py b/chirp/drivers/ts2000.py index d52d41f..d60ff25 100644 --- a/chirp/drivers/ts2000.py +++ b/chirp/drivers/ts2000.py @@ -16,8 +16,7 @@ import re from chirp import chirp_common, directory, util, errors from chirp.drivers import kenwood_live -from chirp.drivers.kenwood_live import KenwoodLiveRadio, \ - command, iserr, NOCACHE +from chirp.drivers.kenwood_live import KenwoodLiveRadio, iserr, NOCACHE TS2000_SSB_STEPS = [1.0, 2.5, 5.0, 10.0] TS2000_FM_STEPS = [5.0, 6.25, 10.0, 12.5, 15.0, 20.0, 25.0, 30.0, 50.0, 100.0] @@ -88,7 +87,7 @@ class TS2000Radio(KenwoodLiveRadio): if number not in self._memcache: return - resp = command(self.pipe, *self._cmd_erase_memory(number)) + resp = self.command(self.pipe, *self._cmd_erase_memory(number)) if iserr(resp): raise errors.RadioError("Radio refused delete of %i" % number) del self._memcache[number] @@ -100,7 +99,7 @@ class TS2000Radio(KenwoodLiveRadio): if number in self._memcache and not NOCACHE: return self._memcache[number] - result = command(self.pipe, *self._cmd_get_memory(number)) + result = self.command(self.pipe, *self._cmd_get_memory(number)) if result == "N": mem = chirp_common.Memory() mem.number = number @@ -113,7 +112,7 @@ class TS2000Radio(KenwoodLiveRadio): # check for split frequency operation if mem.duplex == "" and self._kenwood_split: - result = command(self.pipe, *self._cmd_get_split(number)) + result = self.command(self.pipe, *self._cmd_get_split(number)) self._parse_split_spec(mem, result) return mem @@ -190,13 +189,14 @@ class TS2000Radio(KenwoodLiveRadio): spec = self._make_mem_spec(memory) spec = "".join(spec) - r1 = command(self.pipe, *self._cmd_set_memory(memory.number, spec)) + r1 = self.command(self.pipe, + *self._cmd_set_memory(memory.number, spec)) if not iserr(r1): memory.name = memory.name.rstrip() self._memcache[memory.number] = memory # if we're tuned to the channel, reload it - r1 = command(self.pipe, *self._cmd_cur_memory(memory.number)) + r1 = self.command(self.pipe, *self._cmd_cur_memory(memory.number)) if not iserr(r1): pattern = re.compile("MC([0-9]{3})") match = pattern.search(r1) @@ -204,16 +204,17 @@ class TS2000Radio(KenwoodLiveRadio): cur_mem = int(match.group(1)) if cur_mem == memory.number: cur_mem = \ - command(self.pipe, - *self._cmd_recall_memory(memory.number)) + self.command( + self.pipe, + *self._cmd_recall_memory(memory.number)) else: raise errors.InvalidDataError("Radio refused %i" % memory.number) # FIXME if memory.duplex == "split" and self._kenwood_split: spec = "".join(self._make_split_spec(memory)) - result = command(self.pipe, *self._cmd_set_split(memory.number, - spec)) + result = self.command(self.pipe, + *self._cmd_set_split(memory.number, spec)) if iserr(result): raise errors.InvalidDataError("Radio refused %i" % memory.number) diff --git a/chirp/drivers/ts790e.py b/chirp/drivers/ts790e.py new file mode 100644 index 0000000..81bf588 --- /dev/null +++ b/chirp/drivers/ts790e.py @@ -0,0 +1,264 @@ +import logging +import threading + +from chirp import chirp_common, directory, errors + +from chirp.drivers.kenwood_live import KenwoodLiveRadio, NOCACHE, RADIO_IDS + +LOG = logging.getLogger(__name__) + +TS790E_DUPLEX = ["", "split", "+", "-"] +TS790E_TMODES = ["", "Tone"] +TS790E_SKIP = ["", "S"] + +TS790E_MODES = { + "LSB": "1", + "USB": "2", + "CW": "3", + "FM": "4", + "CWN": "7", +} +TS790E_MODES_REV = {val: mode for mode, val in TS790E_MODES.items()} + +TS790E_TONES = list(chirp_common.OLD_TONES) +TS790E_TONES.remove(69.3) +TS790E_TONES.remove(97.4) +TS790E_OFFSETS = ["", "+", "-"] + +TS790E_BANDS = [ + (135000000, 173999900), + (300000000, 949999900), + (1200000000, 1304957000), +] + +TS790E_SHIFTS = [600000, 1600000, 35000000] + +TS790E_SPECIALS = ["P1", "P2", "P3", "A1", "A2", "A3", "C1", "C2", "C3"] + + +def get_band(freq): + i = 0 + for band in TS790E_BANDS: + if freq >= band[0] and freq <= band[1]: + return i + i += 1 + return None + + +@directory.register +class TS790ERadio(KenwoodLiveRadio): + """Kenwood TS-790E""" + MODEL = "TS-790E" + BAUD_RATE = 4800 + HARDWARE_FLOW = False + COMMAND_DELIMITER = (";", "") + + _upper = 49 + _kenwood_valid_tones = list(TS790E_TONES) + + def command_no_output(self, ser, cmd, *args): + """Send @cmd to radio via @ser""" + with self.LOCK: + cmd += "".join(args) + ";" + + LOG.debug("PC->RADIO: %s" % cmd.strip()) + ser.write(cmd.encode('cp1252')) + + def __init__(self, *args, **kwargs): + chirp_common.LiveRadio.__init__(self, *args, **kwargs) + self._memcache = {} + self.LOCK = threading.Lock() + self.LAST_BAUD = self.BAUD_RATE + self.LAST_DELIMITER = self.COMMAND_DELIMITER + + if self.pipe: + self.pipe.timeout = 0.1 + self.pipe.baudrate = 4800 + try: + resp = self.command(self.pipe, "ID") + except UnicodeDecodeError: + raise Exception("Radio is likely not %s" % (self.MODEL)) + radio_id = resp.split(";")[0] + if RADIO_IDS[radio_id] != \ + self.MODEL.split(" ")[0]: + raise Exception("Radio reports %s (not %s)" % (radio_id, + self.MODEL)) + self.command_no_output(self.pipe, "AI", "0") + + def get_features(self): + rf = chirp_common.RadioFeatures() + + rf.can_odd_split = True + + rf.has_bank = False + rf.has_ctone = False + rf.has_dtcs = False + rf.has_dtcs_polarity = False + rf.has_name = False + rf.has_tuning_step = False + rf.has_nostep_tuning = True + rf.memory_bounds = (0, self._upper) + + rf.valid_bands = TS790E_BANDS + rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + rf.valid_duplexes = TS790E_DUPLEX + rf.valid_modes = list(TS790E_MODES.keys()) + rf.valid_skips = TS790E_SKIP + rf.valid_tmodes = TS790E_TMODES + rf.valid_special_chans = list(TS790E_SPECIALS) + + return rf + + def get_memory(self, number): + if isinstance(number, str): + number = 50 + TS790E_SPECIALS.index(number) + if number < 0 or number > (self._upper + len(TS790E_SPECIALS)): + raise errors.InvalidMemoryLocation( + "Number must be between 0 and %i" % ( + self._upper + len(TS790E_SPECIALS))) + if number in self._memcache and not NOCACHE: + return self._memcache[number] + + result = self.command( + self.pipe, *self._cmd_get_memory(number)) + if result.endswith("00000000000000000") or result.endswith("?"): + mem = chirp_common.Memory() + if number >= 30: + mem.duplex = TS790E_DUPLEX[1] + if number >= 50: + mem.extd_number = TS790E_SPECIALS[number - 50] + mem.number = number + mem.offset = None + mem.empty = True + mem.skip = TS790E_SKIP[0] + self._memcache[number] = mem + return mem + + mem = self._parse_mem_spec(result) + if number >= 30: # check for split frequency operation + result = self.command( + self.pipe, *self._cmd_get_split(number)) + self._parse_split_spec(mem, result) + self._memcache[number] = mem + + return mem + + def set_memory(self, memory): + LOG.debug("set_memory(%s)" % repr(memory)) + if memory.extd_number: + real_number = 50 + TS790E_SPECIALS.index(memory.extd_number) + else: + real_number = memory.number + if real_number < 0 or real_number > (self._upper + + len(TS790E_SPECIALS)): + raise errors.InvalidMemoryLocation( + "Number must be between 0 and %i" % ( + self._upper + len(TS790E_SPECIALS))) + + if memory.extd_number and (memory.extd_number[0] in ["A", "C", "P"]): + band = get_band(memory.freq) + supposed_band = int(memory.extd_number[1]) - 1 + if band != supposed_band: + raise errors.InvalidMemoryLocation( + "%s frequency must be between %f and %f " % + (memory.extd_number, *TS790E_BANDS[supposed_band])) + + del self._memcache[real_number] + + # If we have a split set the transmit frequency first. + if real_number >= 30 and memory.offset is not None: + spec = self._make_base_spec(memory, memory.offset) + self.command_no_output( + self.pipe, *self._cmd_set_split(real_number, spec)) + + spec = self._make_base_spec(memory, memory.freq) + self.command_no_output(self.pipe, + *self._cmd_set_memory(real_number, spec)) + + def erase_memory(self, number): + if number not in self._memcache and not NOCACHE: + return + self.command_no_output(self.pipe, *self._cmd_erase_memory(number)) + del self._memcache[number] + + def _cmd_get_memory(self, number): + return "MR0 %02i" % number + + def _cmd_get_split(self, number): + return "MR1 %02i" % number + + def _cmd_set_memory(self, number, spec): + return "MW0 %02i%s" % (number, spec) + + def _cmd_set_split(self, number, spec): + return "MW1 %02i%s" % (number, spec) + + def _cmd_erase_memory(self, number): + return "MW0 %02i%017i" % (number, 0) + + def _parse_mem_spec(self, spec): + mem = chirp_common.Memory() + + # pad string so indexes match Kenwood docs + spec = " " + spec # Param Format Function + + _p3 = spec[5:7] # P3 7 Memory Channel + _p4 = spec[7:18] # P4 4 Frequency + _p5 = spec[18] # P5 2 Mode + _p6 = spec[19] # P6 10 Memory Lockout + if len(spec) == 24: + _p7 = spec[20] # P7 1 Tone On/Off + _p8 = spec[21:23] # P8 14 Tone Frequency + _p9 = spec[23] # P9 13 Offset + + if not TS790E_MODES_REV[_p5]: + return mem + mem.number = int(_p3) + mem.duplex = TS790E_DUPLEX[0] + mem.freq = int(_p4) + mem.mode = TS790E_MODES_REV[_p5] + if mem.number < 30 and mem.mode == "FM": + mem.duplex = TS790E_OFFSETS[int(_p9)] + if mem.duplex != TS790E_OFFSETS[0]: + cur_band = get_band(mem.freq) + mem.offset = TS790E_SHIFTS[cur_band] + else: + mem.offset = None + + mem.skip = TS790E_SKIP[int(_p6)] + if mem.mode == "FM": + mem.tmode = TS790E_TMODES[int(_p7)] + if mem.tmode == TS790E_TMODES[1]: + mem.rtone = TS790E_TONES[int(_p8)-1] + if mem.number >= 50: + mem.extd_number = TS790E_SPECIALS[mem.number - 50] + return mem + + def _parse_split_spec(self, mem, spec): + split_freq_bytes = spec[7:17] # P4 + if len(split_freq_bytes) > 0: + split_freq = int(split_freq_bytes) + if mem.freq != 0: + mem.duplex = "split" + mem.offset = split_freq + return mem + + def _make_base_spec(self, mem, freq): + if mem.mode == "FM" \ + and mem.tmode == TS790E_TMODES[1]: + tmode = "1" + tone = "%02i" % (TS790E_TONES.index(mem.rtone)+1) + else: + tmode = "0" + tone = "01" + if not mem.offset or mem.offset not in TS790E_OFFSETS: + offset = "0" + else: + offset = str(TS790E_OFFSETS.index(mem.offset)) + return "%011i%s%i%s%s%s" % ( # P# Format Function + freq, # P4 4 Frequency + TS790E_MODES[mem.mode], # P5 2 Mode + mem.skip == TS790E_SKIP[1], # P6 10 Memory Lockout + tmode, # P7 1 Tone On/Off + tone, # P8 14 Tone Frequency + offset) # P9 13 Offset diff --git a/chirp/drivers/ts850.py b/chirp/drivers/ts850.py index d367a14..8f832cd 100644 --- a/chirp/drivers/ts850.py +++ b/chirp/drivers/ts850.py @@ -16,8 +16,7 @@ import logging from chirp import chirp_common, directory, errors -from chirp.drivers.kenwood_live import KenwoodLiveRadio, \ - command, iserr, NOCACHE +from chirp.drivers.kenwood_live import KenwoodLiveRadio, iserr, NOCACHE LOG = logging.getLogger(__name__) @@ -94,7 +93,7 @@ class TS850Radio(KenwoodLiveRadio): if number in self._memcache and not NOCACHE: return self._memcache[number] - result = command(self.pipe, *self._cmd_get_memory(number)) + result = self.command(self.pipe, *self._cmd_get_memory(number)) if result == "N": mem = chirp_common.Memory() @@ -107,7 +106,7 @@ class TS850Radio(KenwoodLiveRadio): self._memcache[mem.number] = mem # check for split frequency operation - result = command(self.pipe, *self._cmd_get_split(number)) + result = self.command(self.pipe, *self._cmd_get_split(number)) self._parse_split_spec(mem, result) return mem @@ -130,7 +129,8 @@ class TS850Radio(KenwoodLiveRadio): # Clear out memory contents to prevent errors spec = self._make_base_spec(memory, 0) spec = "".join(spec) - result = command(self.pipe, *self._cmd_set_memory(memory.number, spec)) + result = self.command(self.pipe, + *self._cmd_set_memory(memory.number, spec)) if iserr(result): raise errors.InvalidDataError("Radio refused %i" % @@ -139,15 +139,16 @@ class TS850Radio(KenwoodLiveRadio): # If we have a split set the transmit frequency first. if memory.duplex == TS850_DUPLEX[1]: spec = "".join(self._make_split_spec(memory)) - result = command(self.pipe, *self._cmd_set_split(memory.number, - spec)) + result = self.command(self.pipe, + *self._cmd_set_split(memory.number, spec)) if iserr(result): raise errors.InvalidDataError("Radio refused %i" % memory.number) spec = self._make_mem_spec(memory) spec = "".join(spec) - result = command(self.pipe, *self._cmd_set_memory(memory.number, spec)) + result = self.command(self.pipe, + *self._cmd_set_memory(memory.number, spec)) if iserr(result): raise errors.InvalidDataError("Radio refused %i" % memory.number) @@ -155,7 +156,7 @@ class TS850Radio(KenwoodLiveRadio): if number not in self._memcache: return - resp = command(self.pipe, *self._cmd_erase_memory(number)) + resp = self.command(self.pipe, *self._cmd_erase_memory(number)) if iserr(resp): raise errors.RadioError("Radio refused delete of %i" % number) diff --git a/chirp/drivers/uvb5.py b/chirp/drivers/uvb5.py index b8277a2..bd89e1a 100644 --- a/chirp/drivers/uvb5.py +++ b/chirp/drivers/uvb5.py @@ -13,8 +13,6 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. -from __future__ import division - import struct import logging from chirp import chirp_common, directory, bitwise, memmap, errors, util diff --git a/chirp/drivers/yaesu_clone.py b/chirp/drivers/yaesu_clone.py index c434ed0..b719a14 100644 --- a/chirp/drivers/yaesu_clone.py +++ b/chirp/drivers/yaesu_clone.py @@ -148,12 +148,14 @@ 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 buf and buf[0] != CMD_ACK: - buf = pipe.read(block) - if not buf or buf[-1] != CMD_ACK: + if not buf or buf[0] != CMD_ACK: + LOG.error('Expected ack but got %r', buf) raise Exception("Radio did not ack block %i" % blocks) else: _chunk_write(pipe, mmap[pos:], diff --git a/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo b/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo Binary files differindex 7b4964c..3369823 100644 --- a/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/bg_BG/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/de/LC_MESSAGES/CHIRP.mo b/chirp/locale/de/LC_MESSAGES/CHIRP.mo Binary files differindex 556ea75..d1c26f0 100644 --- a/chirp/locale/de/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/de/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/el/LC_MESSAGES/CHIRP.mo b/chirp/locale/el/LC_MESSAGES/CHIRP.mo Binary files differindex 9624ba4..c7852e6 100644 --- a/chirp/locale/el/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/el/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/en_US/LC_MESSAGES/CHIRP.mo b/chirp/locale/en_US/LC_MESSAGES/CHIRP.mo Binary files differindex da634de..cf4af6d 100644 --- a/chirp/locale/en_US/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/en_US/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/es/LC_MESSAGES/CHIRP.mo b/chirp/locale/es/LC_MESSAGES/CHIRP.mo Binary files differindex ab8592c..379edd6 100644 --- a/chirp/locale/es/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/es/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/fr/LC_MESSAGES/CHIRP.mo b/chirp/locale/fr/LC_MESSAGES/CHIRP.mo Binary files differindex 4acec20..2887273 100644 --- a/chirp/locale/fr/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/fr/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/hu/LC_MESSAGES/CHIRP.mo b/chirp/locale/hu/LC_MESSAGES/CHIRP.mo Binary files differindex 76fa313..4ea10bb 100644 --- a/chirp/locale/hu/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/hu/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/it/LC_MESSAGES/CHIRP.mo b/chirp/locale/it/LC_MESSAGES/CHIRP.mo Binary files differindex 12ff372..348cc55 100644 --- a/chirp/locale/it/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/it/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/ja_JP/LC_MESSAGES/CHIRP.mo b/chirp/locale/ja_JP/LC_MESSAGES/CHIRP.mo Binary files differindex d6ff34d..e28969a 100644 --- a/chirp/locale/ja_JP/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/ja_JP/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/nl/LC_MESSAGES/CHIRP.mo b/chirp/locale/nl/LC_MESSAGES/CHIRP.mo Binary files differindex bffb7ba..ffa3c2b 100644 --- a/chirp/locale/nl/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/nl/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/pl/LC_MESSAGES/CHIRP.mo b/chirp/locale/pl/LC_MESSAGES/CHIRP.mo Binary files differindex f3c234d..875d63f 100644 --- a/chirp/locale/pl/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/pl/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/pt_BR/LC_MESSAGES/CHIRP.mo b/chirp/locale/pt_BR/LC_MESSAGES/CHIRP.mo Binary files differindex 2c23df7..a4c4697 100644 --- a/chirp/locale/pt_BR/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/pt_BR/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/ru/LC_MESSAGES/CHIRP.mo b/chirp/locale/ru/LC_MESSAGES/CHIRP.mo Binary files differindex 39da9c6..68a56c0 100644 --- a/chirp/locale/ru/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/ru/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/tr_TR/LC_MESSAGES/CHIRP.mo b/chirp/locale/tr_TR/LC_MESSAGES/CHIRP.mo Binary files differindex eb15cd9..083176a 100644 --- a/chirp/locale/tr_TR/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/tr_TR/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mo b/chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mo Binary files differindex e681bb0..32029c7 100644 --- a/chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/uk_UA/LC_MESSAGES/CHIRP.mo diff --git a/chirp/locale/zh_CN/LC_MESSAGES/CHIRP.mo b/chirp/locale/zh_CN/LC_MESSAGES/CHIRP.mo Binary files differindex 78a34c4..a3aca06 100644 --- a/chirp/locale/zh_CN/LC_MESSAGES/CHIRP.mo +++ b/chirp/locale/zh_CN/LC_MESSAGES/CHIRP.mo diff --git a/chirp/settings.py b/chirp/settings.py index 2b4d76c..f400333 100644 --- a/chirp/settings.py +++ b/chirp/settings.py @@ -203,9 +203,14 @@ class RadioSettingValueFloat(RadioSettingValue): class RadioSettingValueBoolean(RadioSettingValue): - """A boolean setting""" + """A boolean setting - def __init__(self, current): + If using MemSetting, mem_vals can be set to the False, True values + that are to be actually stored in memory instead of 0, 1 + """ + + def __init__(self, current, mem_vals=(0, 1)): + self._mem_vals = mem_vals RadioSettingValue.__init__(self) self.queue_current(current) @@ -220,6 +225,15 @@ class RadioSettingValueBoolean(RadioSettingValue): return str(bool(self.get_value())) +class RadioSettingValueInvertedBoolean(RadioSettingValueBoolean): + """A boolean value that is actually stored inverted in memory. + + Only really useful for MemSetting, which will invert the value when + actually setting it in memory. + """ + pass + + class RadioSettingValueList(RadioSettingValue): """A list-of-strings setting""" @@ -268,14 +282,28 @@ class RadioSettingValueString(RadioSettingValue): """A string setting""" def __init__(self, minlength, maxlength, current, - autopad=True, charset=chirp_common.CHARSET_ASCII): + autopad=True, charset=chirp_common.CHARSET_ASCII, + mem_pad_char=' '): RadioSettingValue.__init__(self) self._minlength = minlength self._maxlength = maxlength self._charset = charset self._autopad = autopad + self._mem_pad_char = mem_pad_char self.queue_current(current) + @property + def mem_pad_char(self): + return self._mem_pad_char + + @property + def autopad(self): + return self._autopad + + @property + def maxlength(self): + return self._maxlength + def set_charset(self, charset): """Sets the set of allowed characters""" self._charset = charset @@ -390,6 +418,35 @@ class RadioSettings(list): items = [str(self[i]) for i in range(0, len(self))] return "\n".join(items) + def walk(self): + """Iterate over all the RadioSettings in this tree + + Returns a generator. + """ + for element in self: + if isinstance(element, RadioSetting): + yield element + elif isinstance(element, RadioSettingGroup): + for subel in element.walk(): + yield subel + else: + raise ValueError('Unable to iterate %r' % element) + + def apply_to(self, memobj): + """Walk all the settings in this tree, apply the direct-to-mem ones. + + Returns all the settings that are not MemSetting objects to be applied + manually. + """ + non_mem_settings = [] + for setting in self.walk(): + print("Walking %r" % setting) + if isinstance(setting, MemSetting): + setting.apply_to_memobj(memobj) + else: + non_mem_settings.append(setting) + return non_mem_settings + class RadioSettingGroup(object): @@ -425,6 +482,14 @@ class RadioSettingGroup(object): self.append(element) + def walk(self): + for el in self._elements.values(): + if isinstance(el, RadioSetting): + yield el + if isinstance(el, RadioSettingGroup): + for subel in el.walk(): + yield subel + def set_frozen(self): self._frozen = True for i in self: @@ -439,6 +504,9 @@ class RadioSettingGroup(object): """Returns the short group identifier""" return self._shortname + def set_shortname(self, new_name): + self._shortname = new_name + def set_doc(self, doc): """Sets the docstring for the group""" self.__doc__ = doc @@ -633,3 +701,57 @@ class RadioSetting(RadioSettingGroup): self._elements[name].set_value(value) else: self._elements[name] = value + + +class MemSetting(RadioSetting): + """A RadioSetting that maps directly to a memory object value. + + :param path: The dot-separated path to a setting value in the object ( + i.e. "settings.dtmf.pttid") + :param name: The human-readable name for this setting + :param values: The RadioSettingValue (only one allowed) + :param *kwargs: Other kwargs to be passed to RadioSetting + """ + def __init__(self, path, name, value, **kwargs): + self._path = path + setting_name = path.replace('.', '_') + super().__init__(setting_name, name, value, **kwargs) + + def apply_to_memobj(self, memobj): + """Apply this setting value to a memory object. + + Uses the path specified at init time, operates on memobj to find and + set the value in memory according to this setting. + """ + if not self.value.initialized: + LOG.warning('Unable to apply uninitialized value %s', + self._path) + return + if isinstance(self.value, RadioSettingValueInvertedBoolean): + value = not self.value + elif isinstance(self.value, RadioSettingValueList): + value = int(self.value) + elif isinstance(self.value, RadioSettingValueString): + value = str(self.value) + if self.value.autopad: + value = value.rstrip().ljust(self.value.maxlength, + self.value.mem_pad_char) + else: + value = self.value + + # After we determined if this is inverted or not, convert to the values + # that memory wants to see. + if isinstance(self.value, RadioSettingValueBoolean): + value = self.value._mem_vals[int(value)] + + obj = memobj + elements = self._path.split('.') + for element in elements[:-1]: + if '[' in element: + # foo[i] syntax + name, index = element.split('[', 1) + obj = getattr(obj, name) + obj = obj[int(index.replace(']', ''))] + else: + obj = getattr(obj, element) + setattr(obj, elements[-1], value) diff --git a/chirp/sources/mapy73pl.py b/chirp/sources/mapy73pl.py new file mode 100644 index 0000000..53999de --- /dev/null +++ b/chirp/sources/mapy73pl.py @@ -0,0 +1,72 @@ +# Copyright 2023 Dan Smith <chirp@f.danplanet.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import logging + +import requests +import wx + +from chirp.drivers import generic_csv +from chirp import errors +from chirp.sources import base + +_ = wx.GetTranslation +LOG = logging.getLogger(__name__) + + +class Mapy73Pl(base.NetworkResultRadio): + VENDOR = 'mapy73.pl' + + def get_label(self): + return 'mapy73.pl' + + def do_fetch(self, status, params): + status.send_status(_('Querying'), 10) + LOG.debug('query params: %s' % str(params)) + if 'api_option' in params: + export = params['api_option'] + else: + export = '' + + base_url = 'https://cache.mapy73.pl/snapshot/repeaters/export/chirp/' + request_url = base_url + export + try: + r = requests.get(request_url, headers=base.HEADERS) + r.raise_for_status() + except requests.exceptions.RequestException as e: + LOG.error('Failed to query mapy73.pl: %s' % e) + status.send_fail(_('Unable to query')) + return + status.send_status(_('Parsing'), 20) + try: + csv = generic_csv.CSVRadio(None) + csv._load(x.decode() for x in r.iter_lines()) + except errors.InvalidDataError: + status.send_fail(_('No results')) + return + except Exception as e: + LOG.error('Error parsing result: %s' % e) + status.send_fail(_('Failed to parse result')) + return + + status.send_status(_('Sorting'), 80) + + self._memories = [csv.get_memory(x) for x in range(0, 999) + if not csv.get_memory(x).empty] + self._memories.sort(key=lambda m: m.name) + for i, mem in enumerate(self._memories): + mem.number = i + 1 + + return status.send_end() diff --git a/chirp/sources/repeaterbook.py b/chirp/sources/repeaterbook.py index dcdca1b..879388a 100644 --- a/chirp/sources/repeaterbook.py +++ b/chirp/sources/repeaterbook.py @@ -1,4 +1,5 @@ import datetime +import glob import json import logging import math @@ -167,6 +168,22 @@ class RepeaterBook(base.NetworkResultRadio): status.send_status('Download complete', 50) return data_file + def _merge_cached(self, service, country, data, exclude_file): + db_dir = chirp_platform.get_platform().config_file('repeaterbook') + fn_pat = 'rb%s-%s-%s.json' % (service, + country.lower().replace(' ', '_'), + '*') + other_files = glob.glob(os.path.join(db_dir, fn_pat)) + for fn in other_files: + if fn == exclude_file: + continue + with open(fn, 'rb') as f: + d = json.loads(f.read()) + data['results'].extend(d['results']) + data['count'] += d['count'] + 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': m = chirp_common.DVMemory() @@ -222,6 +239,7 @@ class RepeaterBook(base.NetworkResultRadio): modes = params.pop('modes', []) fmconv = params.pop('fmconv', False) openonly = params.pop('openonly') + cached = params.pop('cached') data_file = self.get_data(status, params.get('country'), @@ -230,6 +248,12 @@ class RepeaterBook(base.NetworkResultRadio): if not data_file: return + data = json.loads(open(data_file, 'rb').read()) + if lat and lon and dist and cached: + self._merge_cached(params.get('service', ''), + params.get('country'), + data, data_file) + status.send_status('Parsing', 50) def sorter(item): @@ -263,8 +287,7 @@ class RepeaterBook(base.NetworkResultRadio): return False i = 0 - for item in sorted(json.loads(open(data_file, 'rb').read())['results'], - key=sorter): + for item in sorted(data['results'], key=sorter): if not item: continue if openonly and not open_repeater(item): diff --git a/chirp/wxui/bugreport.py b/chirp/wxui/bugreport.py index 98662b1..16e9fa3 100644 --- a/chirp/wxui/bugreport.py +++ b/chirp/wxui/bugreport.py @@ -437,6 +437,16 @@ class ExistingBugInfo(BugReportPage): _('An error has occurred'), style=wx.OK | wx.ICON_ERROR).ShowModal() event.Veto() + elif r.json()['issue']['status']['is_closed']: + LOG.error('Issue %s is closed', self.context.bugnum) + wx.MessageDialog( + self, + _('Please check the bug number and try again. If you do ' + 'actually want to report against this bug, please comment ' + 'on it via the website and ask for it to be re-opened.'), + _('Bug number %s is closed') % self.context.bugnum + ).ShowModal() + event.Veto() else: LOG.debug('Validated issue %s', self.context.bugnum) @@ -451,10 +461,21 @@ class BugUpdateInfo(BugReportPage): INST = _('Enter details about this update. Be descriptive about what ' 'you were doing, what you expected to happen, and what ' 'actually happened.') + DEFAULT = '\n'.join([ + _('(Describe what you were doing)'), + '', + _('(Describe what you expected to happen)'), + '', + _('(Describe what actually happened instead)'), + '', + _('(Has this ever worked before? New radio? ' + 'Does it work with OEM software?)'), + ]) def _build(self, vbox): self.context.bugdetails = None - self.details = wx.TextCtrl(self, style=wx.TE_MULTILINE) + self.details = wx.TextCtrl(self, style=wx.TE_MULTILINE, + value=self.DEFAULT) try: self.details.SetHint(_('Enter information to add to the bug here')) except Exception: @@ -465,19 +486,8 @@ class BugUpdateInfo(BugReportPage): flag=wx.EXPAND | wx.LEFT | wx.RIGHT) def _validate_next(self): - if self.details.GetValue() == '' and self.context.is_new: - self.details.SetValue('\n'.join([ - _('(Describe what you were doing)'), - '', - _('(Describe what you expected to happen)'), - '', - _('(Describe what actually happened instead)'), - '', - _('(Has this ever worked before? New radio? ' - 'Does it work with OEM software?)'), - ])) - - return len(self.details.GetValue()) > 10 + current = self.details.GetValue() + return len(current) > 10 and current != self.DEFAULT def validate_success(self, *a): self.context.bugdetails = self.details.GetValue() diff --git a/chirp/wxui/clone.py b/chirp/wxui/clone.py index 0ab2da6..21af53e 100644 --- a/chirp/wxui/clone.py +++ b/chirp/wxui/clone.py @@ -411,6 +411,8 @@ class ChirpCloneDialog(wx.Dialog): filter_ports = [ # MacOS unpaired bluetooth serial '/dev/cu.Bluetooth-Incoming-Port', + '/dev/cu.debug-console', + '/dev/cu.wlan-debug', ] LOG.debug('All system ports: %s', [x.__dict__ for x in system_ports]) @@ -459,6 +461,14 @@ class ChirpCloneDialog(wx.Dialog): LOG.warning('Did not find device for selected port %s' % selected) return selected + def set_selected_port(self, devname): + for device, name in self.ports: + if device == devname: + self._port.SetStringSelection(name) + return True + else: + LOG.debug('Port %s not in current list', devname) + def _port_assist(self, event): r = wx.MessageBox( _('Unplug your cable (if needed) and then click OK'), @@ -614,14 +624,35 @@ class ChirpCloneDialog(wx.Dialog): def _selected_vendor(self, event): self._select_vendor(event.GetString()) self._persist_choices() + self._select_port_for_model() def _selected_model(self, event): self._persist_choices() + self._select_port_for_model() def select_vendor_model(self, vendor, model): self._vendor.SetSelection(self._vendor.GetItems().index(vendor)) self._select_vendor(vendor) self._model.SetSelection(self._model_choices.index(model)) + self._select_port_for_model() + + 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') + 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) + else: + LOG.debug('No recent/available port for %s', modelstr) + + def _remember_port_for_selected(self): + modelstr = '%s:%s' % (self._vendor.GetStringSelection(), + self._model.GetStringSelection()) + port = self.get_selected_port() + CONF.set(modelstr, port, 'port_recall') + LOG.debug('Recorded last-used port %s for %s', port, modelstr) def _status(self, status): def _safe_status(): @@ -776,6 +807,8 @@ class ChirpDownloadDialog(ChirpCloneDialog): self.model_msg.SetLabel('%s %s %s' % ( rclass.VENDOR, rclass.MODEL, rclass.VARIANT)) + self._remember_port_for_selected() + try: self._radio = rclass(serial) except Exception as e: @@ -870,6 +903,8 @@ class ChirpUploadDialog(ChirpCloneDialog): LOG.debug('Opening serial %r after upload prompt' % port) s = open_serial(port, self._radio) + self._remember_port_for_selected() + try: self._radio.set_pipe(s) # Short-circuit straight to the previous baudrate for variable- diff --git a/chirp/wxui/common.py b/chirp/wxui/common.py index c906a2e..8c94221 100644 --- a/chirp/wxui/common.py +++ b/chirp/wxui/common.py @@ -41,6 +41,8 @@ CONF = config.get() CHIRP_DATA_MEMORY = wx.DataFormat('x-chirp/memory-channel') EditorChanged, EVT_EDITOR_CHANGED = wx.lib.newevent.NewCommandEvent() StatusMessage, EVT_STATUS_MESSAGE = wx.lib.newevent.NewCommandEvent() +EditorRefresh, EVT_EDITOR_REFRESH = wx.lib.newevent.NewCommandEvent() +CrossEditorAction, EVT_CROSS_EDITOR_ACTION = wx.lib.newevent.NewCommandEvent() INDEX_CHAR = settings.BANNED_NAME_CHARACTERS[0] # This is a lock that can be used to exclude edit-specific operations @@ -134,7 +136,9 @@ class EditorMenuItem(wx.MenuItem): ITEMS = {} def __init__(self, cls, callback_name, *a, **k): - self._wx_id = wx.NewId() + self._wx_id = k.pop('id', None) + if not self._wx_id: + self._wx_id = wx.NewId() super().__init__(None, self._wx_id, *a, **k) self._cls = cls self._callback_name = callback_name @@ -371,6 +375,14 @@ class ChirpSettingGrid(wx.Panel): self.pg.Bind(wx.propgrid.EVT_PG_CHANGED, self._pg_changed) self.pg.Bind(wx.EVT_MOTION, self._mouseover) + self.pg.DedicateKey(wx.WXK_TAB) + self.pg.DedicateKey(wx.WXK_RETURN) + self.pg.DedicateKey(wx.WXK_UP) + self.pg.DedicateKey(wx.WXK_DOWN) + self.pg.AddActionTrigger(wx.propgrid.PG_ACTION_EDIT, wx.WXK_RETURN) + self.pg.AddActionTrigger(wx.propgrid.PG_ACTION_NEXT_PROPERTY, + wx.WXK_RETURN) + sizer = wx.BoxSizer(wx.VERTICAL) self.SetSizer(sizer) sizer.Add(self.pg, 1, wx.EXPAND) diff --git a/chirp/wxui/config.py b/chirp/wxui/config.py index 4abe002..0da3a12 100644 --- a/chirp/wxui/config.py +++ b/chirp/wxui/config.py @@ -31,7 +31,7 @@ class ChirpConfig: self._default_section = "global" - self.__config = ConfigParser(interpolation=None) + self.__config = ConfigParser(interpolation=None, delimiters='=') cfg = os.path.join(basepath, name) if os.path.exists(cfg): diff --git a/chirp/wxui/developer.py b/chirp/wxui/developer.py index 88f3bb9..f9aa1b3 100644 --- a/chirp/wxui/developer.py +++ b/chirp/wxui/developer.py @@ -44,7 +44,15 @@ def simple_diff(a, b, diffsonly=False): diff = "" for i in range(0, len(lines_a)): - if lines_a[i] != lines_b[i]: + try: + line_a = lines_a[i] + except IndexError: + line_a = '' + try: + line_b = lines_b[i] + except IndexError: + line_b = '' + if line_a != line_b: diff += "-%s%s" % (lines_a[i], os.linesep) diff += "+%s%s" % (lines_b[i], os.linesep) blankprinted = False @@ -68,6 +76,7 @@ class MemoryDialog(wx.Dialog): self.text = wx.richtext.RichTextCtrl( self, style=wx.VSCROLL | wx.HSCROLL | wx.NO_BORDER) + self.text.SetEditable(False) sizer.Add(self.text, 1, wx.EXPAND) sizer.Add(wx.StaticLine(self), 0) @@ -114,9 +123,10 @@ class MemoryDialog(wx.Dialog): class ChirpEditor(wx.Panel): - def __init__(self, parent, obj): + def __init__(self, parent, obj, labelfmt='%s'): super(ChirpEditor, self).__init__(parent, ) self._obj = obj + self._labelfmt = labelfmt self._fixed_font = wx.Font(pointSize=10, family=wx.FONTFAMILY_TELETYPE, style=wx.FONTSTYLE_NORMAL, @@ -124,12 +134,19 @@ class ChirpEditor(wx.Panel): self._changed_color = wx.Colour(0, 255, 0) self._error_color = wx.Colour(255, 0, 0) + def label(self, label): + return self._labelfmt % label + + @property + def memobj(self): + return self._obj + def refresh(self): """Called to refresh the widget from memory""" pass def set_up(self): - pass + wx.StaticText(self, label=repr(self)) def _mark_changed(self, thing): thing.SetBackgroundColour(self._changed_color) @@ -180,22 +197,62 @@ class ChirpEditor(wx.Panel): class ChirpStringEditor(ChirpEditor): def set_up(self): sizer = wx.BoxSizer(wx.HORIZONTAL) - self._entry = wx.TextCtrl(self, value=str(self._obj), - style=wx.TE_PROCESS_ENTER) - self._entry.SetMaxLength(len(self._obj)) + self._len = len(self._obj) + + self._strentry = wx.TextCtrl(self, value=str(self._obj), + style=wx.TE_PROCESS_ENTER) + self._strentry.SetMaxLength(self._len) + + # Each char becomes two hex digits, plus one space between each + self._hexentry = wx.TextCtrl(self, style=wx.TE_PROCESS_ENTER) + self._hexentry.SetMaxLength(self._len * 2 + self._len - 1) + self._hexentry.Bind(wx.EVT_KEY_DOWN, self._hex_key) + self.hex_from_str() + self.SetSizer(sizer) - sizer.Add(self._entry, 1, wx.EXPAND) + sizer.Add(self._strentry, 1, border=5, flag=wx.EXPAND | wx.LEFT) + sizer.Add(self._hexentry, 1, border=5, flag=wx.EXPAND | wx.LEFT) + + self.Bind(wx.EVT_TEXT, self._edited) + self.Bind(wx.EVT_TEXT_ENTER, self._changed) + self._strentry.SetEditable(not FROZEN) + self._hexentry.SetEditable(not FROZEN) + + def _hex_key(self, event): + key = event.GetKeyCode() + pos = self._hexentry.GetInsertionPoint() + cur = self._hexentry.GetRange(pos, pos + 1) + if key in (wx.WXK_DELETE, wx.WXK_BACK): + # Don't allow delete or backspace to actually remove anything + return + elif chr(key) in 'ABCDEF0123456789' and cur != ' ': + # Hex characters do the edit in place/overwrite + self._hexentry.Replace(pos, pos + 1, chr(key)) + self.str_from_hex() + return + elif key in (wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_RETURN, + wx.WXK_NUMPAD_ENTER): + # Allow cursor movement + event.Skip() - self._entry.Bind(wx.EVT_TEXT, self._edited) - self._entry.Bind(wx.EVT_TEXT_ENTER, self._changed) - self._entry.SetEditable(not FROZEN) + def hex_from_str(self): + value = self._strentry.GetValue().ljust(self._len)[:self._len] + self._hexentry.ChangeValue(' '.join('%02X' % ord(x) for x in value)) + + def str_from_hex(self): + chars = ''.join(chr(int(x, 16)) + for x in self._hexentry.GetValue().split(' ')) + self._strentry.ChangeValue(chars) def refresh(self): - self._entry.SetValue(str(self._obj)) - self._mark_unchanged(self._entry, mem_changed=False) + self._strentry.SetValue(str(self._obj)) + self.hex_from_str() + self._mark_unchanged(self._strentry, mem_changed=False) def _edited(self, event): - entry = event.GetEventObject() + entry = self._strentry + if event.GetEventObject() == entry: + self.hex_from_str() value = entry.GetValue() if len(value) == len(self._obj): self._mark_changed(entry) @@ -204,7 +261,7 @@ class ChirpStringEditor(ChirpEditor): @common.error_proof() def _changed(self, event): - entry = event.GetEventObject() + entry = self._strentry value = entry.GetValue() self._obj.set_value(value) self._mark_unchanged(entry) @@ -315,8 +372,8 @@ class ChirpBCDEditor(ChirpEditor): class ChirpBrowserPanel(wx.lib.scrolledpanel.ScrolledPanel): def __init__(self, parent, memobj): super(ChirpBrowserPanel, self).__init__(parent) - self._sizer = wx.FlexGridSizer(2) - self._sizer.AddGrowableCol(1) + self._sizer = wx.FlexGridSizer(3) + self._sizer.AddGrowableCol(2) self.SetSizer(self._sizer) self.SetupScrolling() self._parent = parent @@ -331,18 +388,22 @@ class ChirpBrowserPanel(wx.lib.scrolledpanel.ScrolledPanel): def _panel_changed(self, event): wx.PostEvent(self, BrowserChanged(self.GetId())) - def _initialize(self): - for name, obj in self._memobj.items(): + def _initialize(self, memobj, labelfmt='%s'): + for name, obj in memobj.items(): editor = None if isinstance(obj, bitwise.arrayDataElement): if isinstance(obj[0], bitwise.charDataElement): 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) elif isinstance(obj, bitwise.intDataElement): - editor = ChirpIntegerEditor(self, obj) + editor = ChirpIntegerEditor(self, obj, labelfmt=labelfmt) elif isinstance(obj, bitwise.structDataElement): self._parent.add_sub_panel(name, obj, self) if editor: @@ -354,9 +415,17 @@ class ChirpBrowserPanel(wx.lib.scrolledpanel.ScrolledPanel): self._parent.add_sub_panel(name, obj, parent) def selected(self): + fixed_font = wx.Font(pointSize=12, + family=wx.FONTFAMILY_TELETYPE, + style=wx.FONTSTYLE_NORMAL, + weight=wx.FONTWEIGHT_NORMAL) + fixed_font = wx.Font(wx.FontInfo().Family(wx.FONTFAMILY_TELETYPE)) if not self._initialized: - self._initialize() - + self._initialize(self._memobj) + addr = wx.StaticText( + self, + label='0x%06x' % self._memobj.get_offset()) + addr.SetFont(fixed_font) label = wx.StaticText(self) pos = wx.StaticText( self, label='%i bits (%i bytes) at 0x%06x-0x%06x' % ( @@ -364,17 +433,27 @@ class ChirpBrowserPanel(wx.lib.scrolledpanel.ScrolledPanel): self._memobj.size() // 8, self._memobj.get_offset(), self._memobj.get_offset() + self._memobj.size() // 8)) - self._sizer.Add(label, 0, wx.ALIGN_CENTER) - self._sizer.Add(pos, 1, flag=wx.EXPAND) + self._sizer.Add(addr, 0, wx.ALIGN_LEFT) + self._sizer.Add(label, 1, wx.ALIGN_CENTER) + self._sizer.Add(pos, 2, flag=wx.EXPAND) for name, editor in self._editors.items(): + addr = wx.StaticText( + self, + label='0x%06x' % editor.memobj.get_offset()) + addr.SetFont(fixed_font) editor.set_up() - label = wx.StaticText(self, label='%s: ' % name) + label = wx.StaticText(self, label=editor.label(name)) tt = wx.ToolTip(repr(editor)) + label.SetFont(fixed_font) label.SetToolTip(tt) - self._sizer.Add(label, 0, wx.ALIGN_CENTER) - self._sizer.Add(editor, 1, flag=wx.EXPAND) + self._sizer.Add(addr, 0, border=5, + flag=wx.ALIGN_LEFT | wx.BOTTOM | wx.TOP) + self._sizer.Add(label, 0, border=5, + flag=wx.ALIGN_CENTER | wx.ALL) + self._sizer.Add(editor, 1, border=5, + flag=wx.EXPAND | wx.BOTTOM | wx.TOP) else: for editor in self._editors.values(): editor.refresh() diff --git a/chirp/wxui/main.py b/chirp/wxui/main.py index cb76a45..f0521a7 100644 --- a/chirp/wxui/main.py +++ b/chirp/wxui/main.py @@ -182,7 +182,7 @@ class ChirpEditorSet(wx.Panel): radios = [radio] format = '%(type)s' - if len(radios) > 2: + if len(radios) > 2 or features.has_dynamic_subdevices: LOG.info('Using TreeBook because radio has %i devices', len(radios)) self._editors = wx.Treebook(self, style=wx.NB_RIGHT) @@ -286,6 +286,11 @@ class ChirpEditorSet(wx.Panel): def current_editor_index(self): return self._editors.GetSelection() + def iter_editors(self, onlycls=None): + for title, editor in self._editor_index.items(): + if onlycls is None or isinstance(editor, onlycls): + yield title, editor + def select_editor(self, index=None, name=None): if index is None and name: try: @@ -299,6 +304,9 @@ class ChirpEditorSet(wx.Panel): return self._editors.SetSelection(index) + def selected(self): + self.current_editor.selected() + def cb_copy(self, cut=False): return self.current_editor.cb_copy(cut=cut) @@ -458,6 +466,7 @@ class ChirpMain(wx.Frame): self._editors.Bind(wx.aui.EVT_AUINOTEBOOK_TAB_RIGHT_DOWN, self._tab_rclick) self.Bind(wx.EVT_CLOSE, self._window_close) + self.Bind(common.EVT_CROSS_EDITOR_ACTION, self._editor_cross_action) self.statusbar = self.CreateStatusBar(2) self.statusbar.SetStatusWidths([-1, 200]) @@ -596,7 +605,10 @@ class ChirpMain(wx.Frame): select=select) self.Bind(EVT_EDITORSET_CHANGED, self._editor_changed, editorset) self.Bind(common.EVT_STATUS_MESSAGE, self._editor_status, editorset) + editorset.Bind(common.EVT_EDITOR_REFRESH, + lambda e: self._reload_editorset(e, editorset)) self._update_editorset_title(editorset) + editorset.selected() def add_stock_menu(self): stock = wx.Menu() @@ -616,6 +628,9 @@ class ChirpMain(wx.Frame): ) def add_stock(fn): + if fn.startswith('.') or fn.endswith('~'): + LOG.debug('Ignoring stock file %s', fn) + return submenu_item = stock.Append(wx.ID_ANY, fn) self.Bind(wx.EVT_MENU, self._menu_open_stock_config, submenu_item) @@ -796,7 +811,10 @@ class ChirpMain(wx.Frame): edit_menu.Append(wx.MenuItem(edit_menu, wx.ID_SEPARATOR)) for item in memedit_items[common.EditorMenuItem.MENU_EDIT]: - edit_menu.Append(item) + if item.GetId() in (wx.ID_UNDO, wx.ID_REDO): + edit_menu.Insert(0, item) + else: + edit_menu.Append(item) self.Bind(wx.EVT_MENU, self.do_editor_callback, item) item.add_menu_callback() @@ -867,6 +885,7 @@ class ChirpMain(wx.Frame): source_menu.Append(query_rr_item) query_rb_item = wx.MenuItem(source_menu, wx.NewId(), 'RepeaterBook') + query_rb_item.SetAccel(wx.AcceleratorEntry(updownmod, ord('B'))) self.Bind(wx.EVT_MENU, self._menu_query_rb, query_rb_item) source_menu.Append(query_rb_item) @@ -884,6 +903,10 @@ class ChirpMain(wx.Frame): self.Bind(wx.EVT_MENU, self._menu_query_przeu, query_przeu_item) source_menu.Append(query_przeu_item) + query_mapy73pl_item = wx.MenuItem(source_menu, wx.NewId(), 'mapy73.pl') + self.Bind(wx.EVT_MENU, self._menu_query_mapy73pl, query_mapy73pl_item) + source_menu.Append(query_mapy73pl_item) + radio_menu.Append(wx.MenuItem(radio_menu, wx.ID_SEPARATOR)) auto_edits = wx.MenuItem(radio_menu, wx.NewId(), @@ -1096,6 +1119,9 @@ class ChirpMain(wx.Frame): def _editor_page_changed(self, event): self._editors.GetPage(event.GetSelection()) self._update_window_for_editor() + editors = self._editors.GetPage(event.GetSelection()) + if editors: + editors.selected() def _editor_changed(self, event): self._update_editorset_title(event.editorset) @@ -1105,6 +1131,83 @@ class ChirpMain(wx.Frame): # FIXME: Should probably only do this for the current editorset self.statusbar.SetStatusText(event.message) + @common.error_proof() + def _reload_editorset(self, event, editorset): + # Rebuild a ChirpEditorSet for a radio who has undergone some + # fundamental change + LOG.info('Editor %s set %s needs refresh' % ( + event.GetEventObject(), editorset)) + + # Capture the index of the current editorset, the editor within, its + # class, and scroll position + index = self._editors.GetSelection() + selected_editor_idx = editorset.current_editor_index + selected_editor_cls = editorset.current_editor.__class__ + selected_editor_pos = editorset.current_editor.get_scroll_pos() + + # Build the new editorset from the previous radio and filename + new_eset = ChirpEditorSet(editorset.radio, editorset.filename, + self._editors) + new_eset._modified = editorset.modified + + # Remove the current one and replace with the new one + self._editors.DeletePage(index) + self.add_editorset(new_eset, atindex=index) + self._update_window_for_editor() + + # Try to find the equivalent editor we were on. Must be at least the + # same index, and same class. This is likely to be a SettingsEdit + # change that adds a MemEdit. However, if this ever removes one, it + # won't work. + for i, (name, editor) in enumerate(new_eset.iter_editors()): + if i >= selected_editor_idx and isinstance(editor, + selected_editor_cls): + LOG.debug('Selecting editor %i type %s name %r', + i, selected_editor_cls.__name__, name) + new_eset.select_editor(i) + new_eset.current_editor.set_scroll_pos(selected_editor_pos) + + def _editor_cross_action(self, event): + tabs = {} + for i in range(self._editors.GetPageCount()): + page = self._editors.GetPage(i) + for title, editor in page.iter_editors( + onlycls=memedit.ChirpMemEdit): + tabs['%s::%s' % (os.path.basename(page.filename), title)] = \ + editor + + d = wx.Dialog(self, title=_('Choose Diff Target')) + vbox = wx.BoxSizer(wx.VERTICAL) + d.SetSizer(vbox) + + label = wx.StaticText(d, label=_('Select a tab and memory to diff'), + style=wx.ALIGN_CENTER_HORIZONTAL) + tab = wx.Choice(d, choices=list(tabs.keys())) + try: + tab.SetStringSelection(self._last_diff_tab) + except AttributeError: + # No last default + pass + memory = wx.SpinCtrl(d) + memory.SetMin(0) + memory.SetMax(2000) + memory.SetValue(event.memory) + buttons = d.CreateButtonSizer(wx.OK | wx.CANCEL) + + vbox.Add(label, proportion=1, flag=wx.EXPAND | wx.ALL, border=10) + vbox.Add(tab, proportion=0, flag=wx.EXPAND | wx.ALL, border=10) + vbox.Add(memory, proportion=0, flag=wx.EXPAND | wx.ALL, border=10) + vbox.Add(buttons, proportion=0, flag=wx.EXPAND) + d.CenterOnParent() + c = d.ShowModal() + self._last_diff_tab = tab.GetStringSelection() + if c == wx.ID_OK: + mem_a = event.GetEventObject()._radio.get_raw_memory(event.memory) + editor = tabs[tab.GetStringSelection()] + mem_b = editor._radio.get_raw_memory(memory.GetValue()) + with developer.MemoryDialog((mem_a, mem_b), self) as d: + d.ShowModal() + def _editor_close(self, event): eset = self._editors.GetPage(event.GetSelection()) if self._prompt_to_close_editor(eset): @@ -1177,6 +1280,9 @@ class ChirpMain(wx.Frame): for menu, items in self.editor_menu_items.items(): for item in items: + if item.GetId() in (wx.ID_UNDO, wx.ID_REDO): + # These are managed by the editor always + continue editor_match = ( eset and isinstance(eset.current_editor, item.editor_class) or @@ -1671,15 +1777,21 @@ class ChirpMain(wx.Frame): # successfully last_editor = self.current_editorset.current_editor_index self.current_editorset.close() - self._editors.DeletePage(self._editors.GetSelection()) + current_index = self._editors.GetSelection() + self._editors.DeletePage(current_index) self._update_window_for_editor() # Mimic the File->Open process to get a new editorset based # on our franken-radio editorset = ChirpEditorSet(new_radio, filename, self._editors) - self.add_editorset(editorset, select=True) + self.add_editorset(editorset, select=True, atindex=current_index) editorset.select_editor(index=last_editor) - editorset.current_editor.set_scroll_pos(editor_pos) + try: + editorset.current_editor.set_scroll_pos(editor_pos) + except TypeError: + # Likely the editor at our old index is no longer the same type, + # so don't freak out + pass LOG.info('Reloaded radio driver%s in place; good luck!' % ( andfile and ' (and file)' or '')) @@ -1947,6 +2059,9 @@ GNU General Public License for more details.""" def _menu_query_przeu(self, event): self._do_network_query(query_sources.PrzemiennikiEuQueryDialog) + def _menu_query_mapy73pl(self, event): + self._do_network_query(query_sources.Mapy73PlQueryDialog) + def display_update_notice(version): LOG.info('Server reports %s is latest' % version) diff --git a/chirp/wxui/memedit.py b/chirp/wxui/memedit.py index 900ea81..4e166e7 100644 --- a/chirp/wxui/memedit.py +++ b/chirp/wxui/memedit.py @@ -13,9 +13,11 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. +import contextlib import functools import logging import pickle +import secrets import sys import wx @@ -674,6 +676,7 @@ class ChirpMemoryDropTarget(wx.DropTarget): payload = self.parse_data() x, y = self._memedit._grid.CalcUnscrolledPosition(x, y) y -= self._memedit._grid.GetColLabelSize() + y -= self._memedit._grid.GetPosition()[1] row, cell = self._memedit._grid.XYToCell(x, y) start_row = self._memedit.mem2row(payload['mems'][0].number) if row < 0 or row == start_row: @@ -684,13 +687,15 @@ class ChirpMemoryDropTarget(wx.DropTarget): LOG.debug('Memory dropped on row %s,%s' % (row, cell)) original_locs = [m.number for m in payload['mems']] source = self._memedit.FindWindowById(payload.pop('source')) - if not self._memedit._cb_paste_memories(payload, row=row): - return defResult + with self._memedit.undo_context( + 'Drag %i memories' % len(payload['mems'])): + if not self._memedit._cb_paste_memories(payload, row=row): + return defResult - if source == self._memedit and defResult == wx.DragMove: - LOG.debug('Same-memedit move requested') - for loc in original_locs: - self._memedit.erase_memory(loc) + if source == self._memedit and defResult == wx.DragMove: + LOG.debug('Same-memedit move requested') + for loc in original_locs: + self._memedit.erase_memory(loc) return defResult @@ -703,6 +708,7 @@ class ChirpMemoryDropTarget(wx.DropTarget): x, y = self._memedit._grid.CalcUnscrolledPosition(x, y) y -= self._memedit._grid.GetColLabelSize() + y -= self._memedit._grid.GetPosition()[1] row, cell = self._memedit._grid.XYToCell(x, y) max_row = self._memedit._grid.GetNumberRows() if row >= 0: @@ -715,6 +721,142 @@ class ChirpMemoryDropTarget(wx.DropTarget): return True +class MemeditActionContext: + def __init__(self, memedit, name): + self._memedit: ChirpMemEdit = memedit + self._name: str = name + self._mem_before = [] + self._mem_after = [] + self._id = 'A-' + secrets.token_urlsafe(4) + + @property + def name(self): + return self._name + + @property + def is_undoable(self): + return bool(self._mem_before) + + def record_memory(self, mem): + pass + + def record_current_memory(self, mem): + pass + + def record_changes(self): + pass + + def __repr__(self): + '[NOP Action]' + + +class MemeditUndoContext(MemeditActionContext): + """An object to record all the changes made in a single operation. + + This could be a single memory edit, bulk edit of multiple memories, + or a large operation like moving memories around, sorting, etc. The + name should be something suitable for showing to the user, and short + enough to fit in the menu next to the Undo item. + """ + + def __init__(self, memedit, name): + super().__init__(memedit, name) + LOG.info('[%s] Creating undo item %r', self._id, self.name) + self._pre_selection = self._memedit._grid.GetSelectedRows() + self._pre_pos = (self._memedit._grid.GetGridCursorRow(), + self._memedit._grid.GetGridCursorCol()) + self._post_selection = self._post_pos = None + + @property + def name(self): + return self._name + + def record_memory(self, mem): + """Records a single memory before a change""" + LOG.debug('[%s] Recording memory %s', self._id, mem) + self._mem_before.insert(0, mem.dupe()) + + def record_current_memory(self, number): + """Records the current state of a memory by number before a change""" + row = self._memedit.mem2row(number) + try: + current_mem = self._memedit._memory_cache[row] + except KeyError: + # This means we never loaded this memory from the radio in the + # first place, likely due to some error. + LOG.warning('[%s] Unable to record current memory %s', + self._id, number) + else: + self.record_memory(current_mem) + + def record_changes(self): + for mem in self._mem_before: + row = self._memedit.mem2row(mem.number) + new_mem = self._memedit._memory_cache[row] + self._mem_after.append(new_mem.dupe()) + LOG.debug('[%s] Recorded changes made to %i memories', + self._id, len(self._mem_before)) + self._post_selection = self._memedit._grid.GetSelectedRows() + self._post_pos = (self._memedit._grid.GetGridCursorRow(), + self._memedit._grid.GetGridCursorCol()) + + def _restore_selection(self, pos, selection): + self._memedit._grid.SetGridCursor(pos) + self._memedit._grid.ClearSelection() + for i, row in enumerate(selection): + self._memedit._grid.SelectRow(row, i != 0) + + def undo_changes(self): + """Replays all the pre-existing memory states from this context""" + LOG.debug('[%s] Un-applying changes', self._id) + try: + with self._memedit.undo_context('Undo', MemeditActionContext): + for mem in self._mem_before: + LOG.debug('[%s] Setting %s', self._id, mem) + if mem.empty: + self._memedit.erase_memory(mem.number) + else: + self._memedit.set_memory(mem, refresh=False) + self._restore_selection(self._pre_pos, self._pre_selection) + except Exception as e: + LOG.error('[%s] Failed to undo: %s', self._id, e) + LOG.info('[%s] Completed undo of %r', self._id, self) + + def redo_changes(self): + LOG.debug('[%s] Re-applying changes', self._id) + try: + with self._memedit.undo_context('Redo', MemeditActionContext): + for mem in self._mem_after: + if mem.empty: + self._memedit.erase_memory(mem.number) + else: + self._memedit.set_memory(mem, refresh=False) + self._restore_selection(self._post_pos, self._post_selection) + except Exception as e: + LOG.error('[%s] Failed to redo: %s', self._id, e) + LOG.info('[%s] Completed redo of %r', self._id, self) + + def __repr__(self): + return '[Undo %s %r mems %s]' % ( + self._id, self.name, + ','.join(str(m.number) for m in self._mem_after)) + + +def undoable(name): + """Mark a whole function as undoable. + + This is less desirable than using the context manager directly, but it + works better for some large complex operations. + """ + def _inner(f): + @functools.wraps(f) + def undo_wrapper(self, *a, **k): + with self.undo_context(name): + return f(self, *a, **k) + return undo_wrapper + return _inner + + class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): def __init__(self, radio, *a, **k): super(ChirpMemEdit, self).__init__(*a, **k) @@ -735,6 +877,11 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): # Memory errors by row self._memory_errors = {} + # Undo queue + self._undo_queue = [] + self._redo_queue = [] + self._undo_ctx = None + self._col_defs = self._setup_columns() self.bandplan = bandplan.BandPlans(CONF) @@ -751,10 +898,15 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self._default_cell_bg_color = self._grid.GetCellBackgroundColour(0, 0) sizer = wx.BoxSizer(wx.VERTICAL) - self._filter_query = memquery.SearchBox(self, - style=wx.TE_PROCESS_ENTER) - self._filter_query.Bind(wx.EVT_TEXT_ENTER, self._do_filter_query) - sizer.Add(self._filter_query, 0, wx.EXPAND | wx.ALL, border=5) + if sys.platform != 'linux': + # FIXME: This doesn't work properly on Linux/GTK because the help + # window takes over focus from everything and has to be force quit. + self._filter_query = memquery.SearchBox(self, + style=wx.TE_PROCESS_ENTER) + self._filter_query.Bind(wx.EVT_TEXT_ENTER, self._do_filter_query) + sizer.Add(self._filter_query, 0, wx.EXPAND | wx.ALL, border=5) + else: + self._filter_query = None sizer.Add(self._grid, 1, wx.EXPAND) self.SetSizer(sizer) @@ -776,8 +928,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self._grid.Bind(wx.grid.EVT_GRID_LABEL_RIGHT_CLICK, self._memory_rclick) self._grid.Bind(wx.grid.EVT_GRID_CELL_BEGIN_DRAG, self._memory_drag) - if WX_GTK: - self._grid.Bind(wx.EVT_KEY_DOWN, self._gtk_short_circuit_edit_copy) + self.Bind(wx.EVT_KEY_DOWN, self._keyboard_overrides) row_labels = self._grid.GetGridRowLabelWindow() row_labels.Bind(wx.EVT_LEFT_DOWN, self._row_click) row_labels.Bind(wx.EVT_LEFT_UP, self._row_click) @@ -791,12 +942,81 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self._dc = wx.ScreenDC() self.set_cell_attrs() + def _update_undo(self): + 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) + accel = item.GetAccel() + if queue: + item.SetItemLabel('%s %s' % (label, queue[0].name)) + item.Enable(True) + else: + item.SetItemLabel(label) + item.Enable(False) + item.SetAccel(accel) + + @contextlib.contextmanager + def undo_context(self, name, actiontype=MemeditUndoContext): + """Record changes made to memories as a single undo item""" + if self._undo_ctx: + LOG.error('Last undo context %s not closed!', + self._undo_ctx.name) + self._undo_cx = None + + self._undo_ctx = actiontype(self, name) + try: + yield self._undo_ctx + except Exception: + LOG.error('Not recording undo for failed action %s', name) + raise + else: + self._undo_ctx.record_changes() + if self._undo_ctx.is_undoable: + self._undo_queue.insert(0, self._undo_ctx) + self._undo_queue = self._undo_queue[:50] + finally: + self._undo_ctx = None + # After we do another thing, the items in the redo queue are no longer + # valid + self._redo_queue = [] + self._update_undo() + + def _undo(self, event): + """Undo the latest change.""" + if not self._undo_queue: + LOG.warning('Nothing in undo queue') + return + undo_item = self._undo_queue.pop(0) + undo_item.undo_changes() + self._redo_queue.insert(0, undo_item) + self._redo_queue = self._redo_queue[:50] + self.refresh() + self._update_undo() + wx.PostEvent(self, common.EditorChanged(self.GetId())) + + def _redo(self, event): + """Redo the latest un-done change.""" + if not self._redo_queue: + LOG.warning('Nothing in redo queue') + return + undo_item = self._redo_queue.pop(0) + undo_item.redo_changes() + self._undo_queue.insert(0, undo_item) + self.refresh() + self._update_undo() + wx.PostEvent(self, common.EditorChanged(self.GetId())) + @property def is_sorted(self): return self._grid.GetSortingColumn() != wx.NOT_FOUND @common.error_proof() def _do_filter_query(self, event=None): + if not self._filter_query: + return filter_str = self._filter_query.GetValue() if filter_str: @@ -838,15 +1058,22 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): LOG.debug('Showing %i/%i rows', visible, num_rows) self._filter_query.help.Hide() - def _gtk_short_circuit_edit_copy(self, event): - # wxGTK is broken and does not direct Ctrl-C to the menu items - # because wx.grid.Grid() tries to implement something for it, - # which we don't want. The wxWidgets people say the only way is to - # grab it ourselves and direct it appropriately before wx.grid.Grid() - # can do it. - # https://github.com/wxWidgets/wxWidgets/issues/22625 - if (event.GetKeyCode() == ord('C') and - event.GetModifiers() == wx.MOD_CONTROL): + def _keyboard_overrides(self, event): + if event.GetKeyCode() in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER): + if not self._grid.CanEnableCellControl(): + return + # Make the enter key start/stop editing instead of the default + # behavior + self._grid.EnableCellEditControl( + not self._grid.IsCellEditControlShown()) + elif (WX_GTK and event.GetKeyCode() == ord('C') and + event.GetModifiers() == wx.MOD_CONTROL): + # wxGTK is broken and does not direct Ctrl-C to the menu items + # because wx.grid.Grid() tries to implement something for it, + # which we don't want. The wxWidgets people say the only way is to + # grab it ourselves and direct it appropriately before + # wx.grid.Grid() can do it. + # https://github.com/wxWidgets/wxWidgets/issues/22625 self.cb_copy(cut=False) else: event.Skip() @@ -973,6 +1200,19 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): @classmethod def get_menu_items(cls): + undo = common.EditorMenuItem( + cls, '_undo', id=wx.ID_UNDO) + + redo = common.EditorMenuItem( + cls, '_redo', id=wx.ID_REDO) + try: + undo.Enable(False) + redo.Enable(False) + except Exception: + # Linux/GTK can not enable/disable items until they have been added + # to a menu. + pass + move_up = common.EditorMenuItem( cls, '_move_up', _('Move Up')) # Control-Up is used by default on macOS, so require shift as well @@ -1001,6 +1241,8 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): return { common.EditorMenuItem.MENU_EDIT: [ + redo, # First so Undo gets inserted at zero + undo, goto, move_up, move_dn, @@ -1247,6 +1489,9 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): """Update a memory in the radio and refresh our view on success""" row = self.mem2row(mem.number) orig_mem = mem.dupe() + if not self._undo_ctx: + raise RuntimeError('No undo context for action!') + self._undo_ctx.record_current_memory(mem.number) if refresh: self.set_row_pending(row) @@ -1273,6 +1518,9 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): def erase_memory(self, number, refresh=True): """Erase a memory in the radio and refresh our view on success""" + if not self._undo_ctx: + raise RuntimeError('No undo context for action!') + self._undo_ctx.record_current_memory(number) row = self.mem2row(number) if refresh: self.set_row_pending(row) @@ -1408,6 +1656,10 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): if defaults.mode and defaults.mode in features.valid_modes: if 'mode' in only: mem.mode = defaults.mode + elif mem.mode not in features.valid_modes: + LOG.debug('Chose mode %s because default %s is unsupported', + features.valid_modes[0], defaults.mode or mem.mode) + mem.mode = features.valid_modes[0] if defaults.tones and defaults.tones[0] in features.valid_tones: if 'rtone' in only: @@ -1621,7 +1873,9 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self.set_row_pending(row) LOG.debug('Memory row %i column %i(%s) edited: %s', row, col, col_def.name, orig_mem.debug_diff(mem, '->')) - self.set_memory(mem) + with self.undo_context( + _('Manual edit of memory %i') % orig_mem.number): + self.set_memory(mem) wx.CallAfter(self._resize_col_after_edit, row, col) @@ -1654,6 +1908,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self.erase_memory(number) @common.error_proof(errors.InvalidMemoryLocation) + @undoable(_('Delete memories')) def _delete_memories_at(self, rows, event, shift_up=None): if rows: wx.PostEvent(self, common.EditorChanged(self.GetId())) @@ -1696,7 +1951,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): # Shift them all up by however many we deleted for number in mems_to_move: LOG.debug('Moving memory %i -> %i', number, number - delta) - mem = self._memory_cache[self.mem2row(number)] + mem = self._memory_cache[self.mem2row(number)].dupe() mem.number -= delta if mem.empty: self.erase_memory(mem.number, refresh=False) @@ -1714,15 +1969,17 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self.refresh_memory(number) def _do_sort_memories(self, rows, reverse, sortattr): - memories = [self._memory_cache[r] for r in rows] + memories = [self._memory_cache[r].dupe() for r in rows] LOG.debug('Sorting %s by %s%s', memories, reverse and '>' or '<', sortattr) memories.sort(key=lambda m: getattr(m, sortattr), reverse=reverse) - for i, mem in enumerate(memories): - new_number = self.row2mem(rows[0] + i) - LOG.debug('Moving memory %i to %i', mem.number, new_number) - mem.number = new_number - self.set_memory(mem) + + with self.undo_context(_('Sort %i memories') % len(memories)): + for i, mem in enumerate(memories): + new_number = self.row2mem(rows[0] + i) + LOG.debug('Moving memory %i to %i', mem.number, new_number) + mem.number = new_number + self.set_memory(mem) LOG.debug('Sorted: %s', memories) wx.PostEvent(self, common.EditorChanged(self.GetId())) @@ -1889,6 +2146,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): functools.partial(self._mem_showraw, event.GetRow()), raw_item) menu.Append(raw_item) + menu.Enable(raw_item.GetId(), len(selected_rows) == 1) diff_item = wx.MenuItem(menu, wx.NewId(), _('Diff Raw Memories')) @@ -1898,6 +2156,14 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): menu.Append(diff_item) menu.Enable(diff_item.GetId(), len(selected_rows) == 2) + diff_across_item = wx.MenuItem(menu, wx.NewId(), + _('Diff against another editor')) + self.Bind(wx.EVT_MENU, + functools.partial(self._mem_diff_across, event.GetRow()), + diff_across_item) + menu.Append(diff_across_item) + menu.Enable(diff_across_item.GetId(), len(selected_rows) == 1) + self.PopupMenu(menu) menu.Destroy() @@ -1913,12 +2179,14 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): return # Schedule all the set jobs - for memory in memories: - self.set_memory(memory) + with self.undo_context(_('Edit %i memories') % len(memories)): + for memory in memories: + self.set_memory(memory) wx.PostEvent(self, common.EditorChanged(self.GetId())) @common.error_proof() + @undoable('Insert row') def _mem_insert(self, row, event): # Traverse memories downward until we find a hole for i in range(row, self.mem2row(self._features.memory_bounds[1]) + 1): @@ -1933,7 +2201,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): mems_to_refresh = [] # Move memories down in reverse order for target_row in range(empty_row, row, -1): - mem = self._memory_cache[target_row - 1] + mem = self._memory_cache[target_row - 1].dupe() LOG.debug('Moving memory %i -> %i', mem.number, self.row2mem(target_row)) mem.number = self.row2mem(target_row) @@ -1962,6 +2230,11 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): with developer.MemoryDialog((mem_a, mem_b), self) as d: d.ShowModal() + def _mem_diff_across(self, row, event): + evt = common.CrossEditorAction(self.GetId(), memory=self.row2mem(row)) + evt.SetEventObject(self) + wx.PostEvent(self, evt) + def update_font(self, refresh=True): fixed = CONF.get_bool('font_fixed', 'state', False) large = CONF.get_bool('font_large', 'state', False) @@ -1979,6 +2252,10 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): wx.CallAfter(self._grid.AutoSizeRows, setAsMin=False) wx.CallAfter(self._grid.SetRowLabelSize, wx.grid.GRID_AUTOSIZE) + def selected(self): + self._grid.SetFocus() + self._update_undo() + def cb_copy_getdata(self, cut=False): rows = self.get_selected_rows_safe() mems = [] @@ -2001,8 +2278,11 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): if any('empty' in mem.immutable for mem in mems): raise errors.InvalidMemoryLocation( _('Some memories are not deletable')) - for mem in mems: - self.erase_memory(mem.number) + with self.undo_context(_('Cut %i memories') % len(mems)): + for mem in mems: + # No need to delete empty memories + if not mem.empty: + self.erase_memory(mem.number) if cut: wx.PostEvent(self, common.EditorChanged(self.GetId())) @@ -2034,7 +2314,8 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): first, last, source_radio.VENDOR, source_radio.MODEL) payload = {'mems': [m for m in memories if first <= m.number <= last], 'features': source_rf} - self._cb_paste_memories(payload, row=row) + with self.undo_context(_('Import %i memories') % len(payload['mems'])): + self._cb_paste_memories(payload, row=row) def _cb_paste_memories(self, payload, row=None): mems = payload['mems'] @@ -2081,7 +2362,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): modified = False for mem in mems: try: - existing = self._memory_cache[row] + existing = self._memory_cache[row].dupe() except KeyError: if not mem.empty: LOG.debug('Not pasting to row %i beyond end of memory', @@ -2111,7 +2392,11 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): mem.immutable = immutable row += 1 try: - if mem.empty: + if mem.empty and existing.empty: + # No need to delete this + LOG.debug('Skipping re-deleting empty memory %i', + existing.number) + elif mem.empty: self.erase_memory(mem.number) self._radio.check_set_memory_immutable_policy(existing, mem) @@ -2162,6 +2447,7 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): return True + @undoable(_('Paste memories')) def cb_paste(self): data = super().cb_paste() if common.CHIRP_DATA_MEMORY in data.GetAllFormats(): @@ -2170,19 +2456,21 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): self._cb_paste_memories(payload) elif wx.DF_UNICODETEXT in data.GetAllFormats(): try: - mem = chirp_common.mem_from_text( - data.GetText()) + mems = [chirp_common.mem_from_text(line) + for line in data.GetText().split('\n') + if line.strip()] 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. - if mem.duplex in ('-', '+'): - self._set_memory_defaults(mem, 'offset') + for mem in mems: + if mem.duplex in ('-', '+'): + self._set_memory_defaults(mem, 'offset') LOG.debug('Generic text paste %r: %s' % ( - data.GetText(), mem)) - self._cb_paste_memories({'mems': [mem], + data.GetText(), mems)) + self._cb_paste_memories({'mems': mems, 'features': self._features}) else: LOG.warning('Unknown data format %s paste' % ( @@ -2236,25 +2524,29 @@ class ChirpMemEdit(common.ChirpEditor, common.ChirpSyncEditor): LOG.debug('Transplanting %s to %i for move indexes: %s -> %s', transplant, new_number, selected, new_indexes) + transplant = transplant.dupe() transplant.number = new_number - to_set = [transplant] - self._grid.ClearSelection() - for old_row, new_row in zip(selected, new_indexes): - mem = self._memory_cache[old_row] - new_number = self.row2mem(new_row) - LOG.debug('Moving %s to %i', mem, new_number) - mem.number = new_number - to_set.append(mem) - self._grid.SelectRow(new_row, True) - - for mem in to_set: - self.set_memory(mem) - cursor_r, cursor_c = self._grid.GetGridCursorCoords() - cursor_r += direction - if 0 <= cursor_r <= last_row: - # Avoid pushing the cursor past the edges - self._grid.SetGridCursor(cursor_r, cursor_c) + with self.undo_context(_('Move %i memories') % len(new_indexes)): + to_set = [transplant] + self._grid.ClearSelection() + for old_row, new_row in zip(selected, new_indexes): + mem = self._memory_cache[old_row].dupe() + new_number = self.row2mem(new_row) + LOG.debug('Moving %s to %i', mem, new_number) + mem.number = new_number + to_set.append(mem) + self._grid.SelectRow(new_row, True) + + for mem in to_set: + self.set_memory(mem) + + cursor_r, cursor_c = (self._grid.GetGridCursorRow(), + self._grid.GetGridCursorCol()) + cursor_r += direction + if 0 <= cursor_r <= last_row: + # Avoid pushing the cursor past the edges + self._grid.SetGridCursor(cursor_r, cursor_c) wx.PostEvent(self, common.EditorChanged(self.GetId())) @@ -2399,6 +2691,14 @@ class ChirpMemPropDialog(wx.Dialog): self._pg = wx.propgrid.PropertyGrid(self._tabs, style=wx.propgrid.PG_BOLD_MODIFIED) self._pg.Bind(wx.propgrid.EVT_PG_CHANGED, self._mem_prop_changed) + + self._pg.DedicateKey(wx.WXK_RETURN) + self._pg.DedicateKey(wx.WXK_UP) + self._pg.DedicateKey(wx.WXK_DOWN) + self._pg.AddActionTrigger(wx.propgrid.PG_ACTION_EDIT, wx.WXK_RETURN) + self._pg.AddActionTrigger(wx.propgrid.PG_ACTION_NEXT_PROPERTY, + wx.WXK_RETURN) + self._tabs.InsertPage(0, self._pg, _('Values')) page_index = 0 self._extra_page = None diff --git a/chirp/wxui/query_sources.py b/chirp/wxui/query_sources.py index 421cc7c..c4df553 100644 --- a/chirp/wxui/query_sources.py +++ b/chirp/wxui/query_sources.py @@ -30,6 +30,7 @@ from chirp.sources import radioreference from chirp.sources import repeaterbook from chirp.sources import przemienniki_net from chirp.sources import przemienniki_eu +from chirp.sources import mapy73pl from chirp.wxui import common from chirp.wxui import config @@ -156,6 +157,35 @@ class ZipValidator(wx.Validator): return True +class CachedValidator(wx.Validator): + def __init__(self, rbquery): + super().__init__() + self._rbquery = rbquery + + def Validate(self, window): + checkbox = self.GetWindow() + checked = checkbox.IsChecked() + is_proximity = all(getattr(self._rbquery, x).GetValue() + for x in ('_lat', '_lon', '_dist')) + if is_proximity: + valid = True + else: + valid = not checked + + if not valid: + wx.MessageBox( + _('Cached results can only be included for a ' + 'proximity query with Latitude, Longitude, and ' + 'Distance set. Please uncheck "%s"') % checkbox.GetLabel()) + return valid + + def Clone(self): + return self.__class__(self._rbquery) + + def TransferToWindow(self): + return True + + class QueryThread(threading.Thread, base.QueryStatus): END_SENTINEL = object() @@ -379,6 +409,21 @@ class RepeaterBookQueryDialog(QuerySourceDialog): 'analog will be shown as FM')) self._add_grid(grid, _('Digital Modes'), self._fmconv) + self._cached = wx.CheckBox( + panel, + label=_('Results from other areas'), + validator=CachedValidator(self)) + self._cached.SetValue(CONF.get_bool('cached', 'repeaterbook')) + self._cached.SetToolTip(_('With this option checked, a proximity ' + 'search will include cached results from ' + 'other localities if they are in range, ' + 'match other filter parameters, and have ' + 'been downloaded before.')) + self._add_grid( + grid, _('Include Cached'), self._cached, + url=('https://www.chirpmyradio.com/projects/chirp/' + 'wiki/ExternalDatabases#Including-multi-state-results')) + self._state_selected(None) self._service_selected(None) @@ -405,18 +450,24 @@ class RepeaterBookQueryDialog(QuerySourceDialog): except KeyError: self._state.SetItems([_('All')]) self._state.Enable(False) + self._cached.Enable(False) return self._state.SetItems(states) self._state.Enable(True) + self._cached.Enable(True) prev = CONF.get('state', 'repeaterbook') if prev and prev in states: self._state.SetStringSelection(prev) else: self._state.SetStringSelection(states[0]) - def _add_grid(self, grid, label, widget): - grid.Add(wx.StaticText(widget.GetParent(), label=label), - border=20, flag=wx.ALIGN_CENTER | wx.RIGHT | wx.LEFT) + def _add_grid(self, grid, label, widget, url=None): + if url is None: + label = wx.StaticText(widget.GetParent(), label=label) + else: + label = wx.adv.HyperlinkCtrl(widget.GetParent(), label=label, + url=url) + grid.Add(label, border=20, flag=wx.ALIGN_CENTER | wx.RIGHT | wx.LEFT) grid.Add(widget, 1, border=20, flag=wx.EXPAND | wx.RIGHT | wx.LEFT) def _select_bands(self, event): @@ -465,6 +516,7 @@ class RepeaterBookQueryDialog(QuerySourceDialog): CONF.set('service', self._service.GetStringSelection(), 'repeaterbook') CONF.set_bool('fmconv', self._fmconv.IsChecked(), 'repeaterbook') CONF.set_bool('openonly', self._openonly.IsChecked(), 'repeaterbook') + CONF.set_bool('cached', self._cached.IsChecked(), 'repeaterbook') self.result_radio = repeaterbook.RepeaterBook() super().do_query() @@ -483,6 +535,7 @@ class RepeaterBookQueryDialog(QuerySourceDialog): 'service_display': self._service.GetStringSelection(), 'fmconv': self._fmconv.IsChecked(), 'openonly': self._openonly.IsChecked(), + 'cached': self._cached.IsChecked(), } @@ -879,6 +932,89 @@ class PrzemiennikiEuQueryDialog(QuerySourceDialog): return params +class Mapy73PlQueryDialog(QuerySourceDialog): + NAME = 'mapy73.pl' + _section = 'mapy73pl' + _api_option = [ + 'pl-fmpoland', # 'FM-Poland network' + 'pl-fmlink', # 'Poland FM-LINK' + 'pl-dmr', # 'Poland DMR' + 'pl-c4fm', # 'Poland C4FM' + 'pl-dstar', # 'Poland DSTAR' + 'pl-fm', # 'Poland FM' + 'cz-fm', # 'Czechia FM' + 'sk-fm', # 'Slovakia FM' + 'fi-fm', # 'Finland FM' + 'se-fm', # 'Sweden FM' + 'no-fm', # 'Norway FM' + 'bg-fm', # 'Bulgaria FM' + 'dk-fm', # 'Denmark FM' + 'de-fm', # 'Germany FM' + 'si-fm', # 'Slovenia FM' + 'is-fm' # 'Iceland FM' + ] + _options_text = [ + 'FM-Poland network', + 'Poland FM-LINK', + 'Poland DMR', + 'Poland C4FM', + 'Poland DSTAR', + 'Poland FM', + 'Czechia FM', + 'Slovakia FM', + 'Finland FM', + 'Sweden FM', + 'Norway FM', + 'Bulgaria FM', + 'Denmark FM', + 'Germany FM', + 'Slovenia FM', + 'Iceland FM' + ] + + def _add_grid(self, grid, label, widget): + grid.Add(wx.StaticText(widget.GetParent(), label=label), + border=20, flag=wx.ALIGN_CENTER | wx.RIGHT | wx.LEFT) + grid.Add(widget, 1, border=20, flag=wx.EXPAND | wx.RIGHT | wx.LEFT) + + def build(self): + vbox = wx.BoxSizer(wx.VERTICAL) + self.SetSizer(vbox) + panel = wx.Panel(self) + vbox.Add(panel, 1, flag=wx.EXPAND | wx.ALL, border=20) + grid = wx.FlexGridSizer(2, 5, 0) + grid.AddGrowableCol(1) + panel.SetSizer(grid) + + # Option + self._option_text = wx.Choice(panel, choices=self._options_text) + self._option_text.SetStringSelection(self._options_text[0]) + self._add_grid(grid, _('Option'), self._option_text) + return vbox + + def get_info(self): + return _('FREE repeater database, which provides information\n' + 'about repeaters in Europe. No account is required.') + + def get_link(self): + return 'https://mapy73.pl' + + def do_query(self): + CONF.set('api_option', + self._api_option[self._option_text.GetSelection()], + self._section) + self.result_radio = mapy73pl.Mapy73Pl() + super().do_query() + + def get_params(self): + params = {} + params['api_option'] = '' + api_option = CONF.get('api_option', self._section) + if api_option: + params['api_option'] = api_option + return params + + class RRQueryDialog(QuerySourceDialog): NAME = 'RadioReference' diff --git a/chirp/wxui/settingsedit.py b/chirp/wxui/settingsedit.py index 1b4fbe6..225dd5f 100644 --- a/chirp/wxui/settingsedit.py +++ b/chirp/wxui/settingsedit.py @@ -38,10 +38,24 @@ class ChirpSettingsEdit(common.ChirpEditor): self._group_control = wx.Treebook(self, style=wx.LB_LEFT) self._group_control.GetTreeCtrl().SetMinSize((250, -1)) sizer.Add(self._group_control, 1, wx.EXPAND) + self._group_control.GetTreeCtrl().Bind(wx.EVT_KEY_DOWN, + self._key) + self._group_control.Bind(wx.EVT_TREEBOOK_PAGE_CHANGED, + self._click) self._initialized = False self._restore_selection = None + def _click(self, event): + # This has to eat this event in order to avoid unfocusing the + # treeview while clicking to start keyboard nav. + pass + + def _key(self, event): + if event.GetKeyCode() in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER): + self._group_control.GetCurrentPage().SetFocus() + event.Skip() + def _initialize(self, job): self.stop_wait_dialog() with common.error_proof(Exception): @@ -53,6 +67,10 @@ class ChirpSettingsEdit(common.ChirpEditor): self._group_control.SetSelection(self._restore_selection) self._restore_selection = None + # Focus the selector after it loads + tc = self._group_control.GetTreeCtrl() + wx.CallAfter(tc.SetFocus) + def selected(self): if not self._initialized: self._initialized = True @@ -183,7 +201,12 @@ class ChirpSettingsEdit(common.ChirpEditor): wx.PostEvent(self, common.EditorChanged(self.GetId())) if event.reload: LOG.warning('Settings grid needs a reload') - wx.CallAfter(self._reload) + if self.radio.get_features().has_dynamic_subdevices: + event = common.EditorRefresh(self.GetId()) + event.SetEventObject(self) + wx.PostEvent(self, event) + else: + wx.CallAfter(self._reload) def saved(self): for i in range(self._group_control.GetPageCount()): @@ -5,7 +5,7 @@ setup(name='chirp', description='A cross-platform cross-radio programming tool', packages=find_packages(include=["chirp*"]), include_package_data=True, - version='20241227', + version='20250221', url='https://chirp.danplanet.com', python_requires=">=3.10,<4", install_requires=[ diff --git a/tests/__init__.py b/tests/__init__.py index d076136..b2563b8 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,9 +1,12 @@ +import functools import glob import logging import os +from types import FunctionType import unittest import pytest +import yaml from chirp import directory @@ -20,7 +23,28 @@ LOG = logging.getLogger('testadapter') class TestAdapterMeta(type): + """Generate a subclass of a TestCase for our radio. + + This wraps each of the test functions so they can be marked by pytest + independently. + + Only works with a single parent! + """ def __new__(cls, name, parents, dct): + for attrname, attr in list(parents[0].__dict__.items()): + if (isinstance(attr, FunctionType) and + attrname.startswith('test') and + not hasattr(attr, 'pytestmark')): + # This is our wrapper, just so it can be independently marked + # by pytest without affecting the parent class + @functools.wraps(attr) + def wrapper(self, name, *a, **k): + # This is a hacky super() replacement + return getattr(parents[0], name)(self, *a, **k) + + # Make this an override in the child class + dct[attrname] = functools.partialmethod(wrapper, attrname) + return super(TestAdapterMeta, cls).__new__(cls, name, parents, dct) @@ -73,6 +97,10 @@ def _load_tests(loader, tests, pattern, suite=None): test_features.TestCaseFeatures, test_copy_all.TestCaseCopyAll) + # Load our list of dynamic XFAIL tests + with open('tests/driver_xfails.yaml') as xflist: + xfail_list = yaml.load(xflist, Loader=yaml.SafeLoader) + for image, test in tests.items(): rclass = directory.get_radio(test) if hasattr(rclass, '_orig_rclass'): @@ -83,16 +111,27 @@ def _load_tests(loader, tests, pattern, suite=None): for index, device in enumerate(subdevs): if not isinstance(device, type): device = device.__class__ + rclassid = directory.radio_class_id(device) + xfails = xfail_list.get(rclassid, []) for case in driver_test_cases: tc = TestAdapterMeta( - "%s_%s" % (case.__name__, - directory.radio_class_id(device)), + "%s_%s" % (case.__name__, rclassid), (case,), {'RADIO_CLASS': rclass, 'SUB_DEVICE': index if has_subdevs else None, 'TEST_IMAGE': image}) + # Mark the class with the driver module name tc = getattr(pytest.mark, module)(tc) + + # Look for any XFAILs and mark those test functions + for xfail in xfails: + if xfail['class'] == case.__name__: + # This is like decorating it. + setattr(tc, xfail['test'], + pytest.mark.xfail(reason=xfail['reason'])( + getattr(tc, xfail['test']))) + suite.addTests(loader.loadTestsFromTestCase(tc)) return suite diff --git a/tests/__pycache__/__init__.cpython-310.pyc b/tests/__pycache__/__init__.cpython-310.pyc Binary files differindex e42885a..e5edb17 100644 --- a/tests/__pycache__/__init__.cpython-310.pyc +++ b/tests/__pycache__/__init__.cpython-310.pyc diff --git a/tests/__pycache__/base.cpython-310.pyc b/tests/__pycache__/base.cpython-310.pyc Binary files differindex e20be95..0d22964 100644 --- a/tests/__pycache__/base.cpython-310.pyc +++ b/tests/__pycache__/base.cpython-310.pyc diff --git a/tests/__pycache__/test_brute_force.cpython-310-pytest-7.1.3.pyc b/tests/__pycache__/test_brute_force.cpython-310-pytest-7.1.3.pyc Binary files differindex 5691216..7cd6a5e 100644 --- a/tests/__pycache__/test_brute_force.cpython-310-pytest-7.1.3.pyc +++ b/tests/__pycache__/test_brute_force.cpython-310-pytest-7.1.3.pyc diff --git a/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc b/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc Binary files differindex f6922f0..47421f6 100644 --- a/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc +++ b/tests/__pycache__/test_edges.cpython-310-pytest-7.1.3.pyc diff --git a/tests/__pycache__/test_settings.cpython-310-pytest-7.1.3.pyc b/tests/__pycache__/test_settings.cpython-310-pytest-7.1.3.pyc Binary files differindex fc0c17c..5ce354a 100644 --- a/tests/__pycache__/test_settings.cpython-310-pytest-7.1.3.pyc +++ b/tests/__pycache__/test_settings.cpython-310-pytest-7.1.3.pyc diff --git a/tests/base.py b/tests/base.py index c2033aa..af29310 100644 --- a/tests/base.py +++ b/tests/base.py @@ -214,11 +214,12 @@ class DriverTest(unittest.TestCase): 'Memories have different mem.extra keys') -def requires_feature(flag): +def requires_feature(flag, equal=None): def inner(fn): @functools.wraps(fn) def wraps(self, *a, **k): - if getattr(self.rf, flag): + val = getattr(self.rf, flag) + if (val == equal if equal is not None else val): fn(self, *a, **k) else: self.skipTest('Feature %s not supported' % flag) diff --git a/tests/driver_xfails.yaml b/tests/driver_xfails.yaml new file mode 100644 index 0000000..6064656 --- /dev/null +++ b/tests/driver_xfails.yaml @@ -0,0 +1,107 @@ +Anysecu_UV-A37: + - class: TestCaseBruteForce + test: test_validate_all + reason: Broken name stored in memory 202? +Talkpod_A36plus: + - class: TestCaseBruteForce + test: test_validate_all + reason: Broken name stored in memory 202? + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +BTECH_GMRS-20V2: + - class: TestCaseBruteForce + test: test_validate_all + reason: Improper application of the duplex policy +BTECH_GMRS-V2: + - class: TestCaseBruteForce + test: test_validate_all + reason: Improper application of the duplex policy +BTECH_GMRS-50X1: + - class: TestCaseBruteForce + test: test_validate_all + reason: Improper application of the duplex policy +BTECH_GMRS-50V2: + - class: TestCaseBruteForce + test: test_validate_all + reason: Improper application of the duplex policy +BTECH_MURS-V2: + - class: TestCaseBruteForce + test: test_validate_all + reason: Improper application of the duplex policy +Abbree_AR-730: + - class: TestCaseBruteForce + test: test_validate_all + reason: Broken name stored in memory 256? +Radtel_RT-730: + - class: TestCaseBruteForce + test: test_validate_all + reason: Improper application of the duplex policy +Retevis_RB17P: + - class: TestCaseBruteForce + test: test_validate_all + reason: Improper application of the duplex policy +TIDRADIO_TD-H3: + - class: TestCaseBruteForce + test: test_validate_all + reason: Memory 3 stored with TX outside TX range +TIDRADIO_TD-H8: + - class: TestCaseBruteForce + test: test_validate_all + reason: Memory 6 stored with TX outside TX range +TIDRADIO_TD-H8-GMRS: + - class: TestCaseBruteForce + test: test_validate_all + reason: Memory 31 stored with TX outside gmrs bands +TIDRADIO_TD-H8-HAM: + - class: TestCaseBruteForce + test: test_validate_all + reason: Memory 31 stored with TX outside ham bands +Yaesu_FT-90: + - class: TestCaseBruteForce + test: test_validate_all + reason: Memory 7 stored with high power but unable to be set? +Wouxun_KG-UVD1P: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +Puxing_PX-2R: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +Radtel_RT-470X_BT: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +BTECH_UV-25X4_G2: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +Abbree_AR-63: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +Feidaxin_FD-288B: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +Wouxun_KG-UV8E: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +Boblov_X3Plus: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +QYT_KT7900D: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +BTECH_UV-25X4: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong +Baojie_BJ-9900_Left: + - class: TestCaseBruteForce + test: test_validate_all_steps + reason: Bad channel stored in image or code is wrong diff --git a/tests/images/Baofeng_UV-5R.img b/tests/images/Baofeng_UV-5R.img Binary files differindex dcdc3e8..773c32b 100644 --- a/tests/images/Baofeng_UV-5R.img +++ b/tests/images/Baofeng_UV-5R.img diff --git a/tests/images/Icom_IC-F621-2.img b/tests/images/Icom_IC-F621-2.img Binary files differnew file mode 100644 index 0000000..fe86e99 --- /dev/null +++ b/tests/images/Icom_IC-F621-2.img diff --git a/tests/images/Kenwood_TK-280.img b/tests/images/Kenwood_TK-280.img Binary files differnew file mode 100644 index 0000000..f6bc6c1 --- /dev/null +++ b/tests/images/Kenwood_TK-280.img diff --git a/tests/images/Kenwood_TK-481.img b/tests/images/Kenwood_TK-481.img Binary files differnew file mode 100644 index 0000000..26e8eb5 --- /dev/null +++ b/tests/images/Kenwood_TK-481.img diff --git a/tests/images/Kenwood_TK-880.img b/tests/images/Kenwood_TK-880.img Binary files differnew file mode 100644 index 0000000..3b38b43 --- /dev/null +++ b/tests/images/Kenwood_TK-880.img diff --git a/tests/images/Kenwood_TK-981.img b/tests/images/Kenwood_TK-981.img Binary files differnew file mode 100755 index 0000000..cb613fb --- /dev/null +++ b/tests/images/Kenwood_TK-981.img diff --git a/tests/images/Radioddity_GA-510_V2.img b/tests/images/Radioddity_GA-510_V2.img Binary files differindex 7695033..2c338a2 100644 --- a/tests/images/Radioddity_GA-510_V2.img +++ b/tests/images/Radioddity_GA-510_V2.img diff --git a/tests/images/Retevis_H777H_FRS.img b/tests/images/Retevis_H777H_FRS.img Binary files differnew file mode 100644 index 0000000..70a036a --- /dev/null +++ b/tests/images/Retevis_H777H_FRS.img diff --git a/tests/images/Retevis_RB626.img b/tests/images/Retevis_RB626.img Binary files differnew file mode 100644 index 0000000..c4cb38a --- /dev/null +++ b/tests/images/Retevis_RB626.img diff --git a/tests/images/Yaesu_VX-7.img b/tests/images/Yaesu_VX-7.img Binary files differindex 2542f8e..8a95099 100644 --- a/tests/images/Yaesu_VX-7.img +++ b/tests/images/Yaesu_VX-7.img diff --git a/tests/py3-untested-drivers.txt b/tests/py3-untested-drivers.txt index ac576c8..ae81485 100644 --- a/tests/py3-untested-drivers.txt +++ b/tests/py3-untested-drivers.txt @@ -35,7 +35,6 @@ Kenwood_TS-590S_SG_LiveMode Kenwood_TS-850 Puxing_PX-2R RT_Systems_CSV -Rugged_RH5R-V2 Sainsonic_AP510 TYT_TH-350 TYT_TH-7800_File diff --git a/tests/py3_driver_testers.txt b/tests/py3_driver_testers.txt index a0aaa55..2925741 100644 --- a/tests/py3_driver_testers.txt +++ b/tests/py3_driver_testers.txt @@ -253,6 +253,8 @@ Radtel_RT-495,@KC9HI,14-Jun-2024 Radtel_RT-630,@KC9HI,14-Jun-2024 Radtel_RT-730,@KC9HI,11-May-2024 Radtel_T18,@KC9HI,28-Nov-2022 +Retevis_H777H_FRS,@KC9HI,12-Jan-2025 +Retevis_H777H_PMR,@KC9HI,12-Jan-2025 Retevis_H777S,@KC9HI,22-Dec-2022 Retevis_H777_Plus,@KC9HI,4-Dec-2022 Retevis_P2,@KC9HI,15-Jun-2024 diff --git a/tests/test_brute_force.py b/tests/test_brute_force.py index eb5ea9b..f3bd68f 100644 --- a/tests/test_brute_force.py +++ b/tests/test_brute_force.py @@ -1,5 +1,7 @@ import logging +import pytest + from chirp import chirp_common from chirp import errors from tests import base @@ -190,3 +192,32 @@ class TestCaseBruteForce(base.DriverTest): # in some radios self.set_and_compare(tmp, ignore=['tuning_step']) successes += 1 + + def test_validate_all(self): + lo, hi = self.rf.memory_bounds + for i in range(lo, hi + 1): + m1 = self.radio.get_memory(i) + errs, warns = chirp_common.split_validation_msgs( + self.radio.validate_memory(m1)) + self.assertEqual([], errs, + ('Radio has validation errors for memory %i ' + 'stored in sample image') % i) + + @base.requires_feature('has_nostep_tuning', equal=False) + def test_validate_all_steps(self): + lo, hi = self.rf.memory_bounds + for i in range(lo, hi + 1): + m1 = self.radio.get_memory(i) + try: + chirp_common.required_step(m1.freq, self.rf.valid_tuning_steps) + except Exception as e: + self.fail('Memory %i: %s' % (i, e)) + + @pytest.mark.skip(reason='not ready yet') + def test_get_set_all(self): + lo, hi = self.rf.memory_bounds + for i in range(lo, hi + 1): + m1 = self.radio.get_memory(i) + self.radio.set_memory(m1) + m2 = self.radio.get_memory(i) + self.assertEqualMem(m1, m2) diff --git a/tests/test_edges.py b/tests/test_edges.py index b3391c4..c5c0775 100644 --- a/tests/test_edges.py +++ b/tests/test_edges.py @@ -107,6 +107,22 @@ class TestCaseEdges(base.DriverTest): 'to delete location %i' % loc) break + def test_redelete_memory(self): + m = self.get_mem() + if 'empty' in m.immutable: + self.skipTest('Test memory is not deletable') + + # Delete this memory + m.empty = True + self.radio.set_memory(m) + + # Try to delete it again + self.radio.set_memory(m) + + # Make sure it appears deleted + m2 = self.radio.get_memory(m.number) + self.assertTrue(m2.empty) + def test_get_set_specials(self): if not self.rf.valid_special_chans: self.skipTest('Radio has no specials') diff --git a/tests/test_settings.py b/tests/test_settings.py index 45267f0..2bcd302 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -35,6 +35,9 @@ class TestCaseSettings(base.DriverTest): self.assertEqual(a.get_value(), b.get_value(), 'Setting value changed from %r to %r' % ( a.get_value(), b.get_value())) + except Exception as e: + print('Failed %s on %s' % (e, a.get_name())) + raise def test_memory_extra_frozen(self): # Find the first non-empty memory and try to set it back as a diff --git a/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc Binary files differindex 9dcc2db..b65e7cd 100644 --- a/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc +++ b/tests/unit/__pycache__/test_bitwise.cpython-310-pytest-7.1.3.pyc diff --git a/tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc b/tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc Binary files differindex 9676932..9c51168 100644 --- a/tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc +++ b/tests/unit/__pycache__/test_repeaterbook.cpython-310-pytest-7.1.3.pyc diff --git a/tests/unit/test_bitwise.py b/tests/unit/test_bitwise.py index 4ba467f..dc38cb6 100644 --- a/tests/unit/test_bitwise.py +++ b/tests/unit/test_bitwise.py @@ -97,6 +97,21 @@ class TestBitwiseBaseIntTypes(BaseTest): obj.foo[i] = i * 2 self.assertEqual(b'\x00\x02\x04\x06', data.get_packed()) + def test_int_array_of_one(self): + data = memmap.MemoryMapBytes(bytes(b'\x00\x01\x02\x03')) + obj = bitwise.parse('u8 foo[1];', data) + self.assertEqual(0, obj.foo[0]) + obj.foo[0] = 1 + self.assertEqual(b'\x01\x01\x02\x03', data.get_packed()) + + def test_int_array_of_zero(self): + data = memmap.MemoryMapBytes(bytes(b'\x00\x01\x02\x03')) + obj = bitwise.parse('u8 foo[0x0]; u8 bar;', data) + # Make sure we can't access any elements of zero-length foo + self.assertRaises(IndexError, lambda: obj.foo[0]) + # Make sure bar is still at the front, unaffected by zero-length foo + self.assertEqual(0, obj.bar) + def test_int_array_set_raw(self): data = memmap.MemoryMapBytes(bytes(b'\x00\x01\x02\x03')) obj = bitwise.parse('u8 foo[4];', data) @@ -357,6 +372,12 @@ class TestBitwiseStructTypes(BaseTest): self.assertRaises(AssertionError, obj.fill_raw, b'AB') self.assertRaises(AssertionError, obj.fill_raw, False) + def test_struct_array_of_one(self): + data = memmap.MemoryMapBytes(bytes(b"123")) + defn = "struct { u8 bar; } foo[1];" + obj = bitwise.parse(defn, data) + self.assertEqual(ord('1'), obj.foo[0].bar) + class TestBitwisePrintoffset(BaseTest): @mock.patch.object(bitwise.LOG, 'debug') @@ -383,6 +404,17 @@ class TestBitwiseErrors(BaseTest): def test_missing_semicolon(self): self.assertRaises(SyntaxError, bitwise.parse, "u8 foo", "") + def test_missing_element(self): + obj = bitwise.parse('u8 foo; struct { u8 bar; } baz;', b'12') + self.assertRaisesRegex(AttributeError, + 'No attribute does_not_exist', + getattr, obj, 'does_not_exist') + self.assertRaisesRegex(AttributeError, + 'No attribute this_either', + getattr, obj.baz, 'this_either') + self.assertTrue('foo' in obj) + self.assertFalse('does_not_exist' in obj) + class TestBitwiseComments(BaseTest): def test_comment_inline_cppstyle(self): diff --git a/tests/unit/test_chirp_common.py b/tests/unit/test_chirp_common.py index ea3bcf8..facdbed 100644 --- a/tests/unit/test_chirp_common.py +++ b/tests/unit/test_chirp_common.py @@ -78,6 +78,11 @@ class TestUtilityFunctions(base.BaseTest): self.assertEqual(140, chirp_common.from_MHz(14000001)) self.assertEqual(140, chirp_common.from_kHz(14001)) + def test_mem_to_from_csv(self): + mem1 = chirp_common.Memory() + mem2 = chirp_common.Memory._from_csv(','.join(mem1.to_csv())) + self.assertEqual(str(mem1), str(mem2)) + def test_mem_from_text_rb1(self): text = '145.2500 -0.6 MHz 97.4 OPEN' mem = chirp_common.mem_from_text(text) @@ -227,6 +232,24 @@ class TestUtilityFunctions(base.BaseTest): self.assertEqual(150000000, mem.offset) self.assertEqual('split', mem.duplex) + def test_mem_from_text_tsv(self): + from_lo = """8 Mt Scott 147.28 + 0.6 TSQL 88.5 167.9 23 NN 23 Tone->Tone FM 5 50W TayDan Emergency Step #2 +9 Mt Tabor 145.39 - 0.6 TSQL 88.5 100 23 NN 23 Tone->Tone FM 5 50W TayDan Emergency Step #1 +10 Timberline V 147.12 + 0.6 TSQL 103.5 100 23 NN 23 Tone->Tone FM 5 50W TayDan Emergency Step #4 +11 Timberline U 444.225 + 5 TSQL 88.5 100 23 NN 23 Tone->Tone FM 5 50W K7RPT Timberline, Linked to VHF side, AC7QE-R echolink +12 GovtCamp 443.875 + 5 TSQL 88.5 103.5 23 NN 23 Tone->Tone FM 5 50W""" # noqa + + lines = from_lo.split('\n') + mem = chirp_common.mem_from_text(lines[0]) + self.assertEqual('Mt Scott', mem.name) + self.assertEqual('TSQL', mem.tmode) + self.assertEqual('+', mem.duplex) + self.assertEqual(600000, mem.offset) + self.assertEqual(147280000, mem.freq) + self.assertEqual(8, mem.number) + for line in from_lo.split('\n'): + chirp_common.mem_from_text(line) + def test_mem_to_text1(self): mem = chirp_common.Memory() mem.freq = 146900000 diff --git a/tests/unit/test_repeaterbook.py b/tests/unit/test_repeaterbook.py index 8a0b059..57532fa 100644 --- a/tests/unit/test_repeaterbook.py +++ b/tests/unit/test_repeaterbook.py @@ -43,6 +43,7 @@ class TestRepeaterbook(unittest.TestCase): 'lon': coords[1], 'dist': 100, 'openonly': False, + 'cached': False, }) m = rb.get_memory(0) self.assertIsInstance(m, chirp_common.Memory) @@ -81,6 +82,7 @@ class TestRepeaterbook(unittest.TestCase): 'dist': 100, 'service': 'gmrs', 'openonly': False, + 'cached': False, }) m = rb.get_memory(0) self.assertIsInstance(m, chirp_common.Memory) @@ -102,6 +104,7 @@ class TestRepeaterbook(unittest.TestCase): 'lon': 133, 'dist': 20000, 'openonly': False, + 'cached': False, }) m = rb.get_memory(0) self.assertIsInstance(m, chirp_common.Memory) @@ -122,6 +125,7 @@ class TestRepeaterbook(unittest.TestCase): 'lon': -122, 'dist': 0, 'openonly': False, + 'cached': False, 'filter': 'tower'} rb = self._test_with_mocked(params) self.assertGreater(sum(rb.get_features().memory_bounds), 5) @@ -133,6 +137,7 @@ class TestRepeaterbook(unittest.TestCase): 'lon': -122, 'dist': 0, 'openonly': False, + 'cached': False, 'filter': 'tower'} rb1 = self._test_with_mocked(dict(params)) self.assertGreater(sum(rb1.get_features().memory_bounds), 5) |
