diff options
| author | Ana C. Custura <ana@netstat.org.uk> | 2018-08-15 17:32:23 +0100 |
|---|---|---|
| committer | Ana C. Custura <ana@netstat.org.uk> | 2018-08-15 17:32:23 +0100 |
| commit | 419fb7a940ff1ae9db0cd0d4826c34320b01ed4f (patch) | |
| tree | c19ff167a68dbf5e9e05654845351d0c1036bb33 | |
| parent | 3adef9d89f20324fbbcf3287cd22fb8f3855ebb9 (diff) | |
New upstream version 20180815upstream/20180815
67 files changed, 8922 insertions, 1023 deletions
diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 224e7f0..0000000 --- a/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.pc/ @@ -1,6 +1,6 @@ Metadata-Version: 1.0 Name: chirp -Version: daily-20170714 +Version: daily-20180815 Summary: UNKNOWN Home-page: UNKNOWN Author: UNKNOWN diff --git a/chirp/__init__.py b/chirp/__init__.py index 1e08ef5..f9b8f31 100644 --- a/chirp/__init__.py +++ b/chirp/__init__.py @@ -17,7 +17,7 @@ import os import sys from glob import glob -CHIRP_VERSION="daily-20170714" +CHIRP_VERSION="daily-20180815" module_dir = os.path.dirname(sys.modules["chirp"].__file__) __all__ = [] diff --git a/chirp/chirp_common.py b/chirp/chirp_common.py index 8ec3917..89b1abb 100644 --- a/chirp/chirp_common.py +++ b/chirp/chirp_common.py @@ -13,8 +13,13 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. +import base64 +import json +import logging import math -from chirp import errors, memmap +from chirp import errors, memmap, CHIRP_VERSION + +LOG = logging.getLogger(__name__) SEPCHAR = "," @@ -321,7 +326,7 @@ class Memory: "rToneFreq", "cToneFreq", "DtcsCode", "DtcsPolarity", "Mode", "TStep", "Skip", "Comment", - "URCALL", "RPT1CALL", "RPT2CALL"] + "URCALL", "RPT1CALL", "RPT2CALL", "DVCODE"] def __setattr__(self, name, val): if not hasattr(self, name): @@ -675,6 +680,7 @@ def console_status(status): class RadioPrompts: """Radio prompt strings""" + info = None experimental = None pre_download = None pre_upload = None @@ -1103,10 +1109,12 @@ class Radio(Alias): class FileBackedRadio(Radio): """A file-backed radio stores its data in a file""" FILE_EXTENSION = "img" + MAGIC = '\x00\xffchirp\xeeimg\x00\x01' def __init__(self, *args, **kwargs): Radio.__init__(self, *args, **kwargs) self._memobj = None + self._metadata = {} def save(self, filename): """Save the radio's memory map to @filename""" @@ -1120,10 +1128,50 @@ class FileBackedRadio(Radio): """Process a newly-loaded or downloaded memory map""" pass + @classmethod + def _strip_metadata(cls, raw_data): + try: + idx = raw_data.index(cls.MAGIC) + except ValueError: + LOG.debug('Image data has no metadata blob') + return raw_data, {} + + # Find the beginning of the base64 blob + raw_metadata = raw_data[idx + len(cls.MAGIC):] + metadata = {} + try: + metadata = json.loads(base64.b64decode(raw_metadata)) + except ValueError as e: + LOG.error('Failed to parse decoded metadata blob: %s' % e) + except TypeError as e: + LOG.error('Failed to decode metadata blob: %s' % e) + + if metadata: + LOG.debug('Loaded metadata: %s' % metadata) + + return raw_data[:idx], metadata + + @classmethod + def _make_metadata(cls): + return base64.b64encode(json.dumps( + {'rclass': cls.__name__, + 'vendor': cls.VENDOR, + 'model': cls.MODEL, + 'variant': cls.VARIANT, + 'chirp_version': CHIRP_VERSION, + })) + def load_mmap(self, filename): """Load the radio's memory map from @filename""" mapfile = file(filename, "rb") - self._mmap = memmap.MemoryMap(mapfile.read()) + data = mapfile.read() + if self.MAGIC in data: + data, self._metadata = self._strip_metadata(data) + if ('chirp_version' in self._metadata and + is_version_newer(self._metadata.get('chirp_version'))): + LOG.warning('Image is from version %s but we are %s' % ( + self._metadata.get('chirp_version'), CHIRP_VERSION)) + self._mmap = memmap.MemoryMap(data) mapfile.close() self.process_mmap() @@ -1135,6 +1183,9 @@ class FileBackedRadio(Radio): try: mapfile = file(filename, "wb") mapfile.write(self._mmap.get_packed()) + if filename.lower().endswith(".img"): + mapfile.write(self.MAGIC) + mapfile.write(self._make_metadata()) mapfile.close() except IOError: raise Exception("File Access Error") @@ -1143,6 +1194,14 @@ class FileBackedRadio(Radio): """Return the radio's memory map object""" return self._mmap + @property + def metadata(self): + return dict(self._metadata) + + @metadata.setter + def metadata(self, value): + self._metadata.update(values) + class CloneModeRadio(FileBackedRadio): """A clone-mode radio does a full memory dump in and out and we store @@ -1285,6 +1344,11 @@ def is_2_5(freq): return (freq % 2500) == 0 +def is_8_33(freq): + """Returns True if @freq is reachable by a 8.33kHz step""" + return (freq % 25000) in [0, 8330, 16660] + + def required_step(freq): """Returns the simplest tuning step that is required to reach @freq""" if is_5_0(freq): @@ -1295,6 +1359,8 @@ def required_step(freq): return 6.25 elif is_2_5(freq): return 2.5 + elif is_8_33(freq): + return 8.33 else: raise errors.InvalidDataError("Unable to calculate the required " + "tuning step for %i.%5i" % @@ -1328,6 +1394,18 @@ def fix_rounded_step(freq): except errors.InvalidDataError: pass + try: + required_step(freq + 330) + return float(freq + 330) + except errors.InvalidDataError: + pass + + try: + required_step(freq + 660) + return float(freq + 660) + except errors.InvalidDataError: + pass + raise errors.InvalidDataError("Unable to correct rounded frequency " + format_freq(freq)) @@ -1483,3 +1561,33 @@ def sanitize_string(astring, validcharset=CHARSET_ASCII, replacechar='*'): for x in xrange(256) ]) return astring.translate(myfilter) + + +def is_version_newer(version): + """Return True if version is newer than ours""" + + def get_version(v): + if v.startswith('daily-'): + _, stamp = v.split('-', 1) + ver = (int(stamp),) + elif '.' in v: + ver = tuple(int(p) for p in v.split('.')) + else: + ver = (0,) + LOG.debug('Parsed version %r to %r' % (v, ver)) + return ver + + from chirp import CHIRP_VERSION + + try: + version = get_version(version) + except ValueError as e: + LOG.error('Failed to parse version %r: %s' % (version, e)) + version = (0,) + try: + my_version = get_version(CHIRP_VERSION) + except ValueError as e: + LOG.error('Failed to parse my version %r: %s' % (CHIRP_VERSION, e)) + my_version = (0,) + + return version > my_version diff --git a/chirp/detect.py b/chirp/detect.py index 5115217..4298667 100644 --- a/chirp/detect.py +++ b/chirp/detect.py @@ -43,7 +43,7 @@ def _detect_icom_radio(ser): md = icf.get_model_data(ser) return _icom_model_data_to_rclass(md) except errors.RadioError, e: - LOG.error(e) + LOG.error("_detect_icom_radio: %s", e) # ICOM IC-91/92 Live-mode radios @ 4800/38400 baud diff --git a/chirp/directory.py b/chirp/directory.py index b1e39c7..22f2d42 100644 --- a/chirp/directory.py +++ b/chirp/directory.py @@ -137,9 +137,32 @@ def get_radio_by_image(image_file): else: filedata = "" + data, metadata = chirp_common.FileBackedRadio._strip_metadata(filedata) + for rclass in DRV_TO_RADIO.values(): if not issubclass(rclass, chirp_common.FileBackedRadio): continue - if rclass.match_model(filedata, image_file): + + # If no metadata, we do the old thing + if not metadata and rclass.match_model(filedata, image_file): return rclass(image_file) - raise errors.ImageDetectFailed("Unknown file format") + + # If metadata, then it has to match one of the aliases or the parent + for alias in rclass.ALIASES + [rclass]: + if (alias.VENDOR == metadata.get('vendor') and + alias.MODEL == metadata.get('model')): + + class DynamicRadioAlias(rclass): + VENDOR = metadata.get('vendor') + MODEL = metadata.get('model') + VARIANT = metadata.get('variant') + + return DynamicRadioAlias(image_file) + + if metadata: + e = errors.ImageMetadataInvalidModel("Unsupported model %s %s" % ( + metadata.get("vendor"), metadata.get("model"))) + e.metadata = metadata + raise e + else: + raise errors.ImageDetectFailed("Unknown file format") diff --git a/chirp/drivers/alinco.py b/chirp/drivers/alinco.py index 9ff6425..7ca252e 100644 --- a/chirp/drivers/alinco.py +++ b/chirp/drivers/alinco.py @@ -577,7 +577,7 @@ ul16 bank[50]; ul16 special_bank[7]; #seekto 0x1200; struct { - u8 unknown; + u8 empty; ul32 freq; u8 mode; u8 step; @@ -587,9 +587,11 @@ struct { u8 tx_tone; u8 rx_tone; u8 dcs; -#seek 3; + ul24 unknown1; u8 skip; -#seek 12; + ul32 unknown2; + ul32 unknown3; + ul32 unknown4; char name[32]; } memory[1000]; """ @@ -740,14 +742,53 @@ class AlincoDJG7EG(AlincoStyleRadio): status.msg = "Uploading to radio" self.status_fn(status) + def _get_empty_flag(self, freq, mode): + # Returns flag used to hide a channel from the main band. This occurs + # when the mode is anything but NFM or FM (main band can only do those) + # or when the frequency is outside of the range supported by the main + # band. + if mode not in ("NFM", "FM"): + return 0x01 + if (freq >= 136000000 and freq < 174000000) or \ + (freq >= 400000000 and freq < 470000000) or \ + (freq >= 1240000000 and freq < 1300000000): + return 0x02 + else: + return 0x01 + + def _check_channel_consistency(self, number): + _mem = self._memobj.memory[number] + if _mem.empty != 0x00: + if _mem.unknown1 == 0xffffff: + # Previous versions of this code have skipped the unknown + # fields. They contain bytes of value if the channel is empty + # and thus those bytes remain 0xff when the channel is put to + # use. The radio is totally fine with this but the Alinco + # programming software is not (see #5275). Here, we check for + # this and report if it is encountered. + LOG.warning("Channel %d is inconsistent: Found 0xff in " + "non-empty channel. Touch channel to fix." + % number) + + if _mem.empty != self._get_empty_flag(_mem.freq, + self.MODES[_mem.mode]): + LOG.warning("Channel %d is inconsistent: Found out of band " + "frequency. Touch channel to fix." % number) + def process_mmap(self): self._memobj = bitwise.parse(DJG7EG_MEM_FORMAT, self._mmap) + # We check all channels for corruption (see bug #5275) but we don't fix + # it automatically because it would be unpolite to modify something on + # a read operation. A log message is emitted though for the user to + # take actions. + for number in range(len(self._memobj.memory)): + self._check_channel_consistency(number) def get_memory(self, number): _mem = self._memobj.memory[number] mem = chirp_common.Memory() mem.number = number - if _mem.unknown == 0: + if _mem.empty == 0: mem.empty = True else: mem.freq = int(_mem.freq) @@ -774,9 +815,10 @@ class AlincoDJG7EG(AlincoStyleRadio): # Get a low-level memory object mapped to the image _mem = self._memobj.memory[mem.number] if mem.empty: - _mem.unknown = 0x00 # Maybe 0 is empty, 2 is used? + _mem.set_raw("\xff" * (_mem.size()/8)) + _mem.empty = 0x00 else: - _mem.unknown = 0x02 + _mem.empty = self._get_empty_flag(mem.freq, mem.mode) _mem.freq = mem.freq _mem.mode = self.MODES.index(mem.mode) _mem.step = self.STEPS.index(mem.tuning_step) @@ -819,3 +861,7 @@ class AlincoDJG7EG(AlincoStyleRadio): _mem.dcs = DCS_CODES[self.VENDOR].index(mem.dtcs) _mem.skip = (mem.skip == "S") _mem.name = "\x00".join(mem.name).ljust(32, "\x00") + _mem.unknown1 = 0x3e001c + _mem.unknown2 = 0x0000000a + _mem.unknown3 = 0x00000000 + _mem.unknown4 = 0x00000000 diff --git a/chirp/drivers/baofeng_common.py b/chirp/drivers/baofeng_common.py index bb2d9b7..8877bf1 100644 --- a/chirp/drivers/baofeng_common.py +++ b/chirp/drivers/baofeng_common.py @@ -185,6 +185,13 @@ def _download(radio): if radio_ident == "\xFF" * 16: ident += radio.MODEL.ljust(8) + elif radio.MODEL in ("GMRS-V1", "MURS-V1"): + # check if radio_ident is OK + if not radio_ident[:7] in radio._fileid: + msg = "Incorrect model ID, got this:\n\n" + msg += util.hexprint(radio_ident) + LOG.debug(msg) + raise errors.RadioError("Incorrect 'Model' selected.") # UI progress status = chirp_common.Status() @@ -242,6 +249,14 @@ def _upload(radio): LOG.info("Image firmware version:") LOG.debug(util.hexprint(image_ident)) + if radio.MODEL in ("GMRS-V1", "MURS-V1"): + # check if radio_ident is OK + if radio_ident != image_ident: + msg = "Incorrect model ID, got this:\n\n" + msg += util.hexprint(radio_ident) + LOG.debug(msg) + raise errors.RadioError("Image not supported by radio") + if radio_ident != "0xFF" * 16 and image_ident == radio_ident: _ranges = radio._ranges else: @@ -319,7 +334,9 @@ class BaofengCommonHT(chirp_common.CloneModeRadio, """Upload to radio""" try: _upload(self) - except: + except errors.RadioError: + raise + except Exception, e: # If anything unexpected happens, make sure we raise # a RadioError and log the problem LOG.exception('Unexpected error during upload') diff --git a/chirp/drivers/bf-t1.py b/chirp/drivers/bf-t1.py new file mode 100644 index 0000000..9d29640 --- /dev/null +++ b/chirp/drivers/bf-t1.py @@ -0,0 +1,916 @@ +# Copyright 2017 Pavel Milanes, CO7WT, <pavelmc@gmail.com> +# +# This driver is a community effort as I don't have the radio on my hands, so +# I was only the director of the orchestra, without the players this may never +# came true, so special thanks to the following hams for their contribution: +# - Henk van der Laan, PA3CQN +# - Setting Discovery. +# - Special channels for RELAY and EMERGENCY. +# - Harold Hankins +# - Memory limits, testing & bug hunting. +# - Dmitry Milkov +# - Testing & bug hunting. +# - Many others participants in the issue page on Chirp's site. +# +# 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 time import sleep +from chirp import chirp_common, directory, memmap +from chirp import bitwise, errors, util +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueBoolean, RadioSettingValueList, \ + RadioSettingValueInteger, RadioSettingValueString, \ + RadioSettingValueFloat, RadioSettings +from textwrap import dedent + +import struct +import logging + +LOG = logging.getLogger(__name__) + +# A note about the memmory in these radios +# +# The '9100' OEM software only manipulates the lower 0x0180 bytes on read/write +# operations as we know, the file generated by the OEM software IS NOT an exact +# eeprom image, it's a crude text file with a pseudo csv format +# +# Later investigations by Harold Hankins found that the eeprom extend up to 2k +# consistent with a hardware chip K24C16 a 2k x 8 bit serial eeprom + +MEM_SIZE = 0x0800 # 2048 bytes +WRITE_SIZE = 0x0180 # 384 bytes +BLOCK_SIZE = 0x10 +ACK_CMD = "\x06" +MODES = ["NFM", "FM"] +SKIP_VALUES = ["S", ""] +TONES = chirp_common.TONES +DTCS = sorted(chirp_common.DTCS_CODES + [645]) + +# Special channels +SPECIALS = { + "EMG": -2, + "RLY": -1 + } + +# Settings vars +TOT_LIST = ["Off"] + ["%s" % x for x in range(30, 210, 30)] +SCAN_TYPE_LIST = ["Time", "Carrier", "Search"] +LANGUAGE_LIST = ["Off", "English", "Chinese"] +TIMER_LIST = ["Off"] + ["%s h" % (x * 0.5) for x in range(1, 17)] +FM_RANGE_LIST = ["76-108", "65-76"] +RELAY_MODE_LIST = ["Off", "RX sync", "TX sync"] +BACKLIGHT_LIST = ["Off", "Key", "On"] +POWER_LIST = ["0.5 Watt", "1.0 Watt"] + +# This is a general serial timeout for all serial read functions. +# Practice has show that about 0.07 sec will be enough to cover all radios. +STIMEOUT = 0.07 + +# this var controls the verbosity in the debug and by default it's low (False) +# make it True and you will to get a very verbose debug.log +debug = False + +# #### ID strings ##################################################### + +# BF-T1 handheld +BFT1_magic = "\x05PROGRAM" +BFT1_ident = " BF9100S" + + +def _clean_buffer(radio): + """Cleaning the read serial buffer, hard timeout to survive an infinite + data stream""" + + dump = "1" + datacount = 0 + + try: + while len(dump) > 0: + dump = radio.pipe.read(100) + datacount += len(dump) + # hard limit to survive a infinite serial data stream + # 5 times bigger than a normal rx block (20 bytes) + if datacount > 101: + seriale = "Please check your serial port selection." + raise errors.RadioError(seriale) + + except Exception: + raise errors.RadioError("Unknown error cleaning the serial buffer") + + +def _rawrecv(radio, amount=0): + """Raw read from the radio device""" + + # var to hold the data to return + data = "" + + try: + if amount == 0: + data = radio.pipe.read() + else: + data = radio.pipe.read(amount) + + # DEBUG + if debug is True: + LOG.debug("<== (%d) bytes:\n\n%s" % + (len(data), util.hexprint(data))) + + # fail if no data is received + if len(data) == 0: + raise errors.RadioError("No data received from radio") + + except: + raise errors.RadioError("Error reading data from radio") + + return data + + +def _send(radio, data): + """Send data to the radio device""" + + try: + radio.pipe.write(data) + + # DEBUG + if debug is True: + LOG.debug("==> (%d) bytes:\n\n%s" % + (len(data), util.hexprint(data))) + except: + raise errors.RadioError("Error sending data to radio") + + +def _make_frame(cmd, addr, data=""): + """Pack the info in the header format""" + frame = struct.pack(">BHB", ord(cmd), addr, BLOCK_SIZE) + + # add the data if set + if len(data) != 0: + frame += data + + return frame + + +def _recv(radio, addr): + """Get data from the radio""" + + # Get the full 20 bytes at a time + # 4 bytes header + 16 bytes of data (BLOCK_SIZE) + + # get the whole block + block = _rawrecv(radio, BLOCK_SIZE + 4) + + # short answer + if len(block) < (BLOCK_SIZE + 4): + raise errors.RadioError("Wrong block length (short) at 0x%04x" % addr) + + # long answer + if len(block) > (BLOCK_SIZE + 4): + raise errors.RadioError("Wrong block length (long) at 0x%04x" % addr) + + # header validation + c, a, l = struct.unpack(">cHB", block[0:4]) + if c != "W" or a != addr or l != BLOCK_SIZE: + LOG.debug("Invalid header for block 0x%04x:" % addr) + LOG.debug("CMD: %s ADDR: %04x SIZE: %02x" % (c, a, l)) + raise errors.RadioError("Invalid header for block 0x%04x:" % addr) + + # return the data, 16 bytes of payload + return block[4:] + + +def _start_clone_mode(radio, status): + """Put the radio in clone mode, 3 tries""" + + # cleaning the serial buffer + _clean_buffer(radio) + + # prep the data to show in the UI + status.cur = 0 + status.msg = "Identifying the radio..." + status.max = 3 + radio.status_fn(status) + + try: + for a in range(0, status.max): + # Update the UI + status.cur = a + 1 + radio.status_fn(status) + + # send the magic word + _send(radio, radio._magic) + + # Now you get a x06 of ACK if all goes well + ack = _rawrecv(radio, 1) + + if ack == ACK_CMD: + # DEBUG + LOG.info("Magic ACK received") + status.cur = status.max + radio.status_fn(status) + + return True + + return False + + except errors.RadioError: + raise + except Exception, e: + raise errors.RadioError("Error sending Magic to radio:\n%s" % e) + + +def _do_ident(radio, status): + """Put the radio in PROGRAM mode & identify it""" + # set the serial discipline (default) + radio.pipe.baudrate = 9600 + radio.pipe.parity = "N" + radio.pipe.bytesize = 8 + radio.pipe.stopbits = 1 + radio.pipe.timeout = STIMEOUT + + # open the radio into program mode + if _start_clone_mode(radio, status) is False: + raise errors.RadioError("Radio did not enter clone mode, wrong model?") + + # Ok, poke it to get the ident string + _send(radio, "\x02") + ident = _rawrecv(radio, len(radio._id)) + + # basic check for the ident + if len(ident) != len(radio._id): + raise errors.RadioError("Radio send a odd identification block.") + + # check if ident is OK + if ident != radio._id: + LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident)) + raise errors.RadioError("Radio identification failed.") + + # handshake + _send(radio, ACK_CMD) + ack = _rawrecv(radio, 1) + + # checking handshake + if len(ack) == 1 and ack == ACK_CMD: + # DEBUG + LOG.info("ID ACK received") + else: + LOG.debug("Radio handshake failed.") + raise errors.RadioError("Radio handshake failed.") + + # DEBUG + LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL)) + + return True + + +def _download(radio): + """Get the memory map""" + + # UI progress + status = chirp_common.Status() + + # put radio in program mode and identify it + _do_ident(radio, status) + + # reset the progress bar in the UI + status.max = MEM_SIZE / BLOCK_SIZE + status.msg = "Cloning from radio..." + status.cur = 0 + radio.status_fn(status) + + # cleaning the serial buffer + _clean_buffer(radio) + + data = "" + for addr in range(0, MEM_SIZE, BLOCK_SIZE): + # sending the read request + _send(radio, _make_frame("R", addr)) + + # read + d = _recv(radio, addr) + + # aggregate the data + data += d + + # UI Update + status.cur = addr / BLOCK_SIZE + status.msg = "Cloning from radio..." + radio.status_fn(status) + + # close comms with the radio + _send(radio, "\x62") + # DEBUG + LOG.info("Close comms cmd sent, radio must reboot now.") + + return data + + +def _upload(radio): + """Upload procedure, we only upload to the radio the Writable space""" + + # UI progress + status = chirp_common.Status() + + # put radio in program mode and identify it + _do_ident(radio, status) + + # get the data to upload to radio + data = radio.get_mmap() + + # Reset the UI progress + status.max = WRITE_SIZE / BLOCK_SIZE + status.cur = 0 + status.msg = "Cloning to radio..." + radio.status_fn(status) + + # cleaning the serial buffer + _clean_buffer(radio) + + # the fun start here, we use WRITE_SIZE instead of the full MEM_SIZE + for addr in range(0, WRITE_SIZE, BLOCK_SIZE): + # getting the block of data to send + d = data[addr:addr + BLOCK_SIZE] + + # build the frame to send + frame = _make_frame("W", addr, d) + + # send the frame + _send(radio, frame) + + # receiving the response + ack = _rawrecv(radio, 1) + + # basic check + if len(ack) != 1: + raise errors.RadioError("No ACK when writing block 0x%04x" % addr) + + if ack != ACK_CMD: + raise errors.RadioError("Bad ACK writing block 0x%04x:" % addr) + + # UI Update + status.cur = addr / BLOCK_SIZE + status.msg = "Cloning to radio..." + radio.status_fn(status) + + # close comms with the radio + _send(radio, "\x62") + # DEBUG + LOG.info("Close comms cmd sent, radio must reboot now.") + + +def _model_match(cls, data): + """Match the opened/downloaded image to the correct version""" + + # a reliable fingerprint: the model name at + rid = data[0x06f8:0x0700] + + if rid == BFT1_ident: + return True + + return False + + +def _decode_ranges(low, high): + """Unpack the data in the ranges zones in the memmap and return + a tuple with the integer corresponding to the Mhz it means""" + return (int(low) * 100000, int(high) * 100000) + + +MEM_FORMAT = """ + +struct channel { + lbcd rxfreq[4]; // rx freq. + u8 rxtone; // x00 = none + // x01 - x32 = index of the analog tones + // x33 - x9b = index of Digital tones + // Digital tone polarity is handled below by + // ttondinv & ttondinv settings + lbcd txoffset[4]; // the difference against RX, direction handled by + // offplus & offminus + u8 txtone; // Idem to rxtone + u8 noskip:1, // if true is included in the scan + wide:1, // 1 = Wide, 0 = Narrow + ttondinv:1, // if true TX tone is Digital & Inverted + unA:1, // + rtondinv:1, // if true RX tone is Digital & Inverted + unB:1, // + offplus:1, // TX = RX + offset + offminus:1; // TX = RX - offset + u8 empty[5]; +}; + +#seekto 0x0000; +struct channel emg; // channel 0 is Emergent CH +#seekto 0x0010; +struct channel channels[20]; // normal 1-20 mem channels + +#seekto 0x0150; // Settings +struct { + lbcd vhfl[2]; // VHF low limit + lbcd vhfh[2]; // VHF high limit + lbcd uhfl[2]; // UHF low limit + lbcd uhfh[2]; // UHF high limit + u8 unk0[8]; + u8 unk1[2]; // start of 0x0160 <======= + u8 squelch; // byte: 0-9 + u8 vox; // byte: 0-9 + u8 timeout; // tot, 0 off, then 30 sec increments up to 180 + u8 batsave:1, // battery save 0 = off, 1 = on + fm_funct:1, // fm-radio 0=off, 1=on ( off disables fm button on set ) + ste:1, // squelch tail 0 = off, 1 = on + blo:1, // busy lockout 0 = off, 1 = on + beep:1, // key beep 0 = off, 1 = on + lock:1, // keylock 0 = ff, = on + backlight:2; // backlight 00 = off, 01 = key, 10 = on + u8 scantype; // scan type 0 = timed, 1 = carrier, 2 = stop + u8 channel; // active channel 1-20, setting it works on upload + u8 fmrange; // fm range 1 = low[65-76](ASIA), 0 = high[76-108](AMERICA) + u8 alarm; // alarm (count down timer) + // d0 - d16 in half hour increments => off, 0.5 - 8.0 h + u8 voice; // voice prompt 0 = off, 1 = english, 2 = chinese + u8 volume; // volume 1-7 as per the radio steps + // set to #FF by original software on upload + // chirp uploads actual value and works. + u16 fm_vfo; // the frequency of the fm receiver. + // resulting frequency is 65 + value * 0.1 MHz + // 0x145 is then 65 + 325*0.1 = 97.5 MHz + u8 relaym; // relay mode, d0 = off, d2 = re-tx, d1 = re-rx + // still a mystery on how it works + u8 tx_pwr; // tx pwr 0 = low (0.5W), 1 = high(1.0W) +} settings; + +#seekto 0x0170; // Relay CH +struct channel rly; + +""" + + +@directory.register +class BFT1(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): + """Baofeng BT-F1 radio & possibly alike radios""" + VENDOR = "Baofeng" + MODEL = "BF-T1" + _vhf_range = (130000000, 174000000) + _uhf_range = (400000000, 520000000) + _upper = 20 + _magic = BFT1_magic + _id = BFT1_ident + + @classmethod + def get_prompts(cls): + rp = chirp_common.RadioPrompts() + rp.experimental = \ + ('This driver is experimental.\n' + '\n' + 'Please keep a copy of your memories with the original software ' + 'if you treasure them, this driver is new and may contain' + ' bugs.\n' + '\n' + '"Emergent CH" & "Relay CH" are implemented via special channels,' + 'be sure to click on the button on the interface to access them.' + ) + rp.pre_download = _(dedent("""\ + Follow these instructions to download your info: + + 1 - Turn off your radio + 2 - Connect your interface cable + 3 - Turn on your radio + 4 - Do the download of your radio data + + """)) + rp.pre_upload = _(dedent("""\ + Follow these instructions to upload your info: + + 1 - Turn off your radio + 2 - Connect your interface cable + 3 - Turn on your radio + 4 - Do the upload of your radio data + + """)) + return rp + + def get_features(self): + """Get the radio's features""" + + rf = chirp_common.RadioFeatures() + rf.valid_special_chans = SPECIALS.keys() + rf.has_settings = True + rf.has_bank = False + rf.has_tuning_step = False + rf.can_odd_split = True + rf.has_name = False + rf.has_offset = True + rf.has_mode = True + rf.valid_modes = MODES + rf.has_dtcs = True + rf.has_rx_dtcs = True + rf.has_dtcs_polarity = True + rf.has_ctone = True + rf.has_cross = True + rf.valid_duplexes = ["", "-", "+", "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_skips = SKIP_VALUES + rf.valid_dtcs_codes = DTCS + rf.memory_bounds = (1, self._upper) + + # normal dual bands + rf.valid_bands = [self._vhf_range, self._uhf_range] + + return rf + + def process_mmap(self): + """Process the mem map into the mem object""" + + # Get it + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + # set the band limits as the memmap + settings = self._memobj.settings + self._vhf_range = _decode_ranges(settings.vhfl, settings.vhfh) + self._uhf_range = _decode_ranges(settings.uhfl, settings.uhfh) + + def sync_in(self): + """Download from radio""" + data = _download(self) + self._mmap = memmap.MemoryMap(data) + self.process_mmap() + + def sync_out(self): + """Upload to radio""" + + try: + _upload(self) + except errors.RadioError: + raise + except Exception, e: + raise errors.RadioError("Error: %s" % e) + + def _decode_tone(self, val, inv): + """Parse the tone data to decode from mem, it returns: + Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)""" + + if val == 0: + return '', None, None + elif val < 51: # analog tone + return 'Tone', TONES[val - 1], None + elif val > 50: # digital tone + pol = "N" + # polarity? + if inv == 1: + pol = "R" + + return 'DTCS', DTCS[val - 51], pol + + def _encode_tone(self, memtone, meminv, mode, tone, pol): + """Parse the tone data to encode from UI to mem""" + + if mode == '' or mode is None: + memtone.set_value(0) + meminv.set_value(0) + elif mode == 'Tone': + # caching errors for analog tones. + try: + memtone.set_value(TONES.index(tone) + 1) + meminv.set_value(0) + except: + msg = "TCSS Tone '%d' is not supported" % tone + LOG.error(msg) + raise errors.RadioError(msg) + + elif mode == 'DTCS': + # caching errors for digital tones. + try: + memtone.set_value(DTCS.index(tone) + 51) + if pol == "R": + meminv.set_value(True) + else: + meminv.set_value(False) + except: + msg = "Digital Tone '%d' is not supported" % tone + LOG.error(msg) + raise errors.RadioError(msg) + else: + msg = "Internal error: invalid mode '%s'" % mode + LOG.error(msg) + raise errors.InvalidDataError(msg) + + def get_raw_memory(self, number): + return repr(self._memobj.memory[number]) + + def _get_special(self, number): + if isinstance(number, str): + return (getattr(self._memobj, number.lower())) + elif number < 0: + for k, v in SPECIALS.items(): + if number == v: + return (getattr(self._memobj, k.lower())) + else: + return self._memobj.channels[number-1] + + def get_memory(self, number): + """Get the mem representation from the radio image""" + _mem = self._get_special(number) + + # Create a high-level memory object to return to the UI + mem = chirp_common.Memory() + + # Check if special or normal + if isinstance(number, str): + mem.number = SPECIALS[number] + mem.extd_number = number + else: + mem.number = number + + if _mem.get_raw()[0] == "\xFF": + mem.empty = True + return mem + + # Freq and offset + mem.freq = int(_mem.rxfreq) * 10 + + # TX freq (Stored as a difference) + mem.offset = int(_mem.txoffset) * 10 + mem.duplex = "" + + # must work out the polarity + if mem.offset != 0: + if _mem.offminus == 1: + mem.duplex = "-" + # tx below RX + + if _mem.offplus == 1: + # tx above RX + mem.duplex = "+" + + # split RX/TX in different bands + if mem.offset > 71000000: + mem.duplex = "split" + + # show the actual value in the offset, depending on the shift + if _mem.offminus == 1: + mem.offset = mem.freq - mem.offset + if _mem.offplus == 1: + mem.offset = mem.freq + mem.offset + + # wide/narrow + mem.mode = MODES[int(_mem.wide)] + + # skip + mem.skip = SKIP_VALUES[_mem.noskip] + + # tone data + rxtone = txtone = None + txtone = self._decode_tone(_mem.txtone, _mem.ttondinv) + rxtone = self._decode_tone(_mem.rxtone, _mem.rtondinv) + chirp_common.split_tone_decode(mem, txtone, rxtone) + + return mem + + def set_memory(self, mem): + """Set the memory data in the eeprom img from the UI""" + # get the eprom representation of this channel + _mem = self._get_special(mem.number) + + # if empty memmory + if mem.empty: + # the channel itself + _mem.set_raw("\xFF" * 16) + # return it + return mem + + # frequency + _mem.rxfreq = mem.freq / 10 + + # duplex/ offset Offset is an absolute value + _mem.txoffset = mem.offset / 10 + + # must work out the polarity + if mem.duplex == "": + _mem.offplus = 0 + _mem.offminus = 0 + elif mem.duplex == "+": + _mem.offplus = 1 + _mem.offminus = 0 + elif mem.duplex == "-": + _mem.offplus = 0 + _mem.offminus = 1 + elif mem.duplex == "split": + if mem.freq > mem.offset: + _mem.offplus = 0 + _mem.offminus = 1 + _mem.txoffset = (mem.freq - mem.offset) / 10 + else: + _mem.offplus = 1 + _mem.offminus = 0 + _mem.txoffset = (mem.offset - mem.freq) / 10 + + # wide/narrow + _mem.wide = MODES.index(mem.mode) + + # skip + _mem.noskip = SKIP_VALUES.index(mem.skip) + + # tone data + ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \ + chirp_common.split_tone_encode(mem) + self._encode_tone(_mem.txtone, _mem.ttondinv, txmode, txtone, txpol) + self._encode_tone(_mem.rxtone, _mem.rtondinv, rxmode, rxtone, rxpol) + + return mem + + def get_settings(self): + _settings = self._memobj.settings + basic = RadioSettingGroup("basic", "Basic Settings") + fm = RadioSettingGroup("fm", "FM Radio") + adv = RadioSettingGroup("adv", "Advanced Settings") + group = RadioSettings(basic, fm, adv) + + # ## Basic Settings + rs = RadioSetting("tx_pwr", "TX Power", + RadioSettingValueList( + POWER_LIST, POWER_LIST[_settings.tx_pwr])) + basic.append(rs) + + rs = RadioSetting("channel", "Active Channel", + RadioSettingValueInteger(1, 20, _settings.channel)) + basic.append(rs) + + rs = RadioSetting("squelch", "Squelch Level", + RadioSettingValueInteger(0, 9, _settings.squelch)) + basic.append(rs) + + rs = RadioSetting("vox", "VOX Level", + RadioSettingValueInteger(0, 9, _settings.vox)) + basic.append(rs) + + # volume validation, as the OEM software set 0xFF on write + _volume = _settings.volume + if _volume > 7: + _volume = 7 + rs = RadioSetting("volume", "Volume Level", + RadioSettingValueInteger(0, 7, _volume)) + basic.append(rs) + + rs = RadioSetting("scantype", "Scan Type", + RadioSettingValueList(SCAN_TYPE_LIST, SCAN_TYPE_LIST[ + _settings.scantype])) + basic.append(rs) + + rs = RadioSetting("timeout", "Time Out Timer (seconds)", + RadioSettingValueList( + TOT_LIST, TOT_LIST[_settings.timeout])) + basic.append(rs) + + rs = RadioSetting("voice", "Voice Prompt", + RadioSettingValueList( + LANGUAGE_LIST, LANGUAGE_LIST[_settings.voice])) + basic.append(rs) + + rs = RadioSetting("alarm", "Alarm Time", + RadioSettingValueList( + TIMER_LIST, TIMER_LIST[_settings.alarm])) + basic.append(rs) + + rs = RadioSetting("backlight", "Backlight", + RadioSettingValueList( + BACKLIGHT_LIST, + BACKLIGHT_LIST[_settings.backlight])) + basic.append(rs) + + rs = RadioSetting("blo", "Busy Lockout", + RadioSettingValueBoolean(_settings.blo)) + basic.append(rs) + + rs = RadioSetting("ste", "Squelch Tail Eliminate", + RadioSettingValueBoolean(_settings.ste)) + basic.append(rs) + + rs = RadioSetting("batsave", "Battery Save", + RadioSettingValueBoolean(_settings.batsave)) + basic.append(rs) + + rs = RadioSetting("lock", "Key Lock", + RadioSettingValueBoolean(_settings.lock)) + basic.append(rs) + + rs = RadioSetting("beep", "Key Beep", + RadioSettingValueBoolean(_settings.beep)) + basic.append(rs) + + # ## FM Settings + rs = RadioSetting("fm_funct", "FM Function", + RadioSettingValueBoolean(_settings.fm_funct)) + fm.append(rs) + + rs = RadioSetting("fmrange", "FM Range", + RadioSettingValueList( + FM_RANGE_LIST, FM_RANGE_LIST[_settings.fmrange])) + fm.append(rs) + + # callbacks for the FM VFO + def apply_fm_freq(setting, obj): + setattr(obj, setting.get_name(), int(setting.value. + get_value() * 10) - 650) + + _fm_vfo = int(_settings.fm_vfo) * 0.1 + 65 + rs = RadioSetting("fm_vfo", "FM Station", + RadioSettingValueFloat(65, 108, _fm_vfo)) + rs.set_apply_callback(apply_fm_freq, _settings) + fm.append(rs) + + # ## Advanced + def apply_limit(setting, obj): + setattr(obj, setting.get_name(), int(setting.value) * 10) + + rs = RadioSetting("vhfl", "VHF Low Limit", + RadioSettingValueInteger(136, 174, int( + _settings.vhfl) / 10)) + rs.set_apply_callback(apply_limit, _settings) + adv.append(rs) + + rs = RadioSetting("vhfh", "VHF High Limit", + RadioSettingValueInteger(136, 174, int( + _settings.vhfh) / 10)) + rs.set_apply_callback(apply_limit, _settings) + adv.append(rs) + + rs = RadioSetting("uhfl", "UHF Low Limit", + RadioSettingValueInteger(400, 470, int( + _settings.uhfl) / 10)) + rs.set_apply_callback(apply_limit, _settings) + adv.append(rs) + + rs = RadioSetting("uhfh", "UHF High Limit", + RadioSettingValueInteger(400, 470, int( + _settings.uhfh) / 10)) + rs.set_apply_callback(apply_limit, _settings) + adv.append(rs) + + rs = RadioSetting("relaym", "Relay Mode", + RadioSettingValueList(RELAY_MODE_LIST, + RELAY_MODE_LIST[_settings.relaym])) + adv.append(rs) + + return group + + def set_settings(self, uisettings): + _settings = self._memobj.settings + + for element in uisettings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + continue + if not element.changed(): + continue + + try: + name = element.get_name() + value = element.value + + if element.has_apply_callback(): + LOG.debug("Using apply callback") + element.run_apply_callback() + else: + obj = getattr(_settings, name) + setattr(_settings, name, value) + + LOG.debug("Setting %s: %s" % (name, value)) + except Exception, e: + LOG.debug(element.get_name()) + raise + + @classmethod + def match_model(cls, filedata, filename): + match_size = False + match_model = False + + # testing the file data size + if len(filedata) == MEM_SIZE: + match_size = True + + # DEBUG + if debug is True: + LOG.debug("BF-T1 matched!") + + # testing the firmware model fingerprint + match_model = _model_match(cls, filedata) + + return match_size and match_model diff --git a/chirp/drivers/btech.py b/chirp/drivers/btech.py index b5e1155..f49a484 100644 --- a/chirp/drivers/btech.py +++ b/chirp/drivers/btech.py @@ -213,6 +213,10 @@ KT8900R_id = "280528" # KT7900D (quad band) KT7900D_fp = "VC4004" +KT7900D_fp1 = "VC4284" + +# QB25 (quad band) - a clone of KT7900D +QB25_fp = "QB-25" # KT8900D (dual band) KT8900D_fp = "VC2002" @@ -924,6 +928,12 @@ class BTechMobileCommon(chirp_common.CloneModeRadio, _names.set_raw("\xFF" * 16) return + if mem_was_empty: + # Zero the whole memory if we're making it unempty for + # the first time + LOG.debug('Zeroing new memory') + _mem.set_raw('\x00' * 16) + # frequency _mem.rxfreq = mem.freq / 10 @@ -970,10 +980,25 @@ class BTechMobileCommon(chirp_common.CloneModeRadio, _mem.unknown5 = 0 _mem.unknown6 = 0 + def _zero_settings(): + _mem.spmute = 0 + _mem.optsig = 0 + _mem.scramble = 0 + _mem.bcl = 0 + _mem.pttid = 0 + _mem.scode = 0 + + if self.COLOR_LCD and _mem.scramble: + LOG.info('Resetting scramble bit for BTECH COLOR_LCD variant') + _mem.scramble = 0 + # extra settings if len(mem.extra) > 0: # there are setting, parse LOG.debug("Extra-Setting supplied. Setting them.") + # Zero them all first so any not provided by model don't + # stay set + _zero_settings() for setting in mem.extra: setattr(_mem, setting.get_name(), setting.value) else: @@ -983,14 +1008,9 @@ class BTechMobileCommon(chirp_common.CloneModeRadio, LOG.debug("New mem is NOT empty") # set extra-settings to default ONLY when apreviously empty or # deleted memory was edited to prevent errors such as #4121 - if mem_was_empty : + if mem_was_empty: LOG.debug("old mem was empty. Setting default for extras.") - _mem.spmute = 0 - _mem.optsig = 0 - _mem.scramble = 0 - _mem.bcl = 0 - _mem.pttid = 0 - _mem.scode = 0 + _zero_settings() return mem @@ -3608,6 +3628,11 @@ class SKT8900D(chirp_common.Alias): MODEL = "S-KT8900D" +class QB25(chirp_common.Alias): + VENDOR = "Radioddity" + MODEL = "QB25" + + # real radios @directory.register class UV25X2(BTechColor): @@ -3657,9 +3682,9 @@ class KT7900D(BTechColor): _uhf_range = (400000000, 481000000) _350_range = (350000000, 371000000) _magic = MSTRING_KT8900D - _fileid = [KT7900D_fp, ] + _fileid = [KT7900D_fp, KT7900D_fp1, QB25_fp, ] # Clones - ALIASES = [SKT8900D, ] + ALIASES = [SKT8900D, QB25, ] @directory.register diff --git a/chirp/drivers/fd268.py b/chirp/drivers/fd268.py index 44e5c66..8d9128b 100644 --- a/chirp/drivers/fd268.py +++ b/chirp/drivers/fd268.py @@ -214,7 +214,7 @@ def do_program(radio): send(radio, "\x02") ident = raw_recv(radio, 8) - ################# WARNING ########################################## + # ################ WARNING ########################################## # Feidaxin radios has a "send id" procedure in the initial handshake # but it's worthless, once you do a hardware reset the ident area # get all 0xFF. @@ -223,7 +223,7 @@ def do_program(radio): # mean, so I detected on a few images that the 3 first bytes are # unique to each radio model, so for now we use that method untill # proven otherwise - #################################################################### + # ################################################################### LOG.debug("Radio's ID string:") LOG.debug(util.hexprint(ident)) @@ -354,7 +354,7 @@ class FeidaxinFD2x8yRadio(chirp_common.CloneModeRadio): "->Tone", "DTCS->DTCS"] # Power levels are golbal and no per channel, so disabled - #rf.valid_power_levels = POWER_LEVELS + # rf.valid_power_levels = POWER_LEVELS # this radio has no skips rf.valid_skips = [] # this radio modes are global and not per channel, so just FM @@ -529,14 +529,9 @@ class FeidaxinFD2x8yRadio(chirp_common.CloneModeRadio): _mem.settings.tot])) basic.append(tot) - power = RadioSetting("settings.power", "Actual Power", - RadioSettingValueList(POWER_LEVELS, - POWER_LEVELS[_mem.settings.power])) - basic.append(power) - key_lock = RadioSetting("settings.key", "Keyboard Lock", - RadioSettingValueList(KEY_LOCK, - KEY_LOCK[_mem.settings.key])) + RadioSettingValueList(KEY_LOCK, KEY_LOCK[ + _mem.settings.key])) basic.append(key_lock) bw = RadioSetting("settings.bw", "Bandwidth", @@ -544,8 +539,8 @@ class FeidaxinFD2x8yRadio(chirp_common.CloneModeRadio): basic.append(bw) powerrank = RadioSetting("settings.powerrank", "Power output adjust", - RadioSettingValueList(POWER_RANK, - POWER_RANK[_mem.settings.powerrank])) + RadioSettingValueList(POWER_RANK, POWER_RANK[ + _mem.settings.powerrank])) basic.append(powerrank) lamp = RadioSetting("settings.lamp", "LCD Lamp", @@ -575,24 +570,36 @@ class FeidaxinFD2x8yRadio(chirp_common.CloneModeRadio): W_MODE, W_MODE[_mem.settings.wmem])) work.append(wmset) + power = RadioSetting("settings.power", "Actual Power", + RadioSettingValueList(POWER_LEVELS, POWER_LEVELS[ + _mem.settings.power])) + work.append(power) + active_ch = RadioSetting("settings.active_ch", "Work Channel", - RadioSettingValueList(ACTIVE_CH, - ACTIVE_CH[_mem.settings.active_ch])) + RadioSettingValueList(ACTIVE_CH, ACTIVE_CH[ + _mem.settings.active_ch])) work.append(active_ch) # vfo rx validation if _mem.vfo.vrx_freq.get_raw()[0] == "\xFF": # if the vfo is not set, the UI cares about the # length of the field, so set a default - LOG.debug("VFO freq not set, setting it to default %s" % - self._VFO_DEFAULT) + LOG.debug("Setting VFO to default %s" % self._VFO_DEFAULT) vfo = self._VFO_DEFAULT else: vfo = int(_mem.vfo.vrx_freq) * 10 - vf_freq = RadioSetting("vfo.vrx_freq", "VFO frequency", - RadioSettingValueString(0, 10, - chirp_common.format_freq(vfo))) + # frecuency apply_callback + def apply_freq(setting, obj): + """Setting is the UI returned value, obj is the memmap object""" + value = chirp_common.parse_freq(str(setting.value)) + obj.set_value(value / 10) + + # preparing for callback on vrxfreq (handled also in a special ) + vf_freq = RadioSetting("none.vrx_freq", "VFO frequency", + RadioSettingValueString(0, 10, chirp_common. + format_freq(vfo))) + vf_freq.set_apply_callback(apply_freq, _mem.vfo.vrx_freq) work.append(vf_freq) # shift works @@ -603,7 +610,7 @@ class FeidaxinFD2x8yRadio(chirp_common.CloneModeRadio): elif bool(_mem.vfo.shift_plus) is True: sset = 2 - shift = RadioSetting("shift", "VFO Shift", + shift = RadioSetting("none.shift", "VFO Shift", RadioSettingValueList(VSHIFT, VSHIFT[sset])) work.append(shift) @@ -616,33 +623,21 @@ class FeidaxinFD2x8yRadio(chirp_common.CloneModeRadio): else: vfo_shift = int(_mem.settings.vfo_shift) * 10 - offset = RadioSetting("settings.vfo_shift", "VFO Offset", - RadioSettingValueString(0, 9, - chirp_common.format_freq(vfo_shift))) + offset = RadioSetting("none.vfo_shift", "VFO Offset", + RadioSettingValueString(0, 9, chirp_common. + format_freq(vfo_shift))) work.append(offset) - step = RadioSetting("settings.step", "VFO step", - RadioSettingValueList(STEPF, - STEPF[_mem.settings.step])) + step = RadioSetting("settings", "VFO step", + RadioSettingValueList(STEPF, STEPF[ + _mem.settings.step])) work.append(step) - # at least for FD-268A/B it doesn't work as stated, so disabled - # by now - #scamble = RadioSetting("vfo.scramble", "Scramble", - #RadioSettingValueList(ONOFF, - #ONOFF[int(_mem.vfo.scramble)])) - #work.append(scamble) - - #busy_lock = RadioSetting("vfo.busy_lock", "Busy Lock out", - #RadioSettingValueList(ONOFF, - #ONOFF[int(_mem.vfo.busy_lock)])) - #work.append(busy_lock) - # FD-288 Family ANI settings if "FD-288" in self.MODEL: - ani_mode = RadioSetting("settings.ani_mode", "ANI ID", - RadioSettingValueList(ANI, - ANI[_mem.settings.ani_mode])) + ani_mode = RadioSetting("ani_mode", "ANI ID", + RadioSettingValueList(ANI, ANI[ + _mem.settings.ani_mode])) work.append(ani_mode) # it can't be \xFF @@ -650,189 +645,158 @@ class FeidaxinFD2x8yRadio(chirp_common.CloneModeRadio): if ani_value == "\xFF\xFF\xFF": ani_value = "200" - ani_value = "".join(x for x in ani_value - if (int(x) >= 2 and int(x) <= 9)) + ani_value = "".join(x for x in ani_value if (int(x) >= 2 and + int(x) <= 9)) - ani = RadioSetting("settings.ani", "ANI (200-999)", + ani = RadioSetting("ani", "ANI (200-999)", RadioSettingValueString(0, 3, ani_value)) work.append(ani) return top def set_settings(self, settings): - """Translate the settings in the UI into bit in the mem_struct - I don't understand well the method used in many drivers - so, I used mine, ugly but works ok""" - def _get_shift(obj): - """Get the amount of offset in the memmap""" - shift = 0 - sf = str(obj.settings.vfo_shift) - if sf[0] != "\xFF": - shift = int(mobj.settings.vfo_shift) * 10 - return shift - - def _get_vrx(obj): - """Get the vfo rx freq""" - return int(obj.vfo.vrx_freq) * 10 - - def _update_vtx(o, rx, offset): - """Update the Vfo TX mem from the value of rx & the offset""" - # check the shift sign - plus = bool(getattr(o, "shift_plus")) - minus = bool(getattr(o, "shift_minus")) - - if plus: - o.vtx_freq = (rx + offset) / 10 - elif minus: - o.vtx_freq = (rx - offset) / 10 + """Set settings in the Chirp way.""" + + # special case: shift handling + def handle_shift(_vfo, settings): + """_vfo is mmap obj for vfo, settings is for all UI settings""" + + # reset the shift in the memmap + _vfo.shift_minus = 0 + _vfo.shift_plus = 0 + + # parse and set if needed + rx = chirp_common.parse_freq( + str(settings["none.vrx_freq"]).split(":")[1]) + + offset = chirp_common.parse_freq( + str(settings["none.vfo_shift"]).split(":")[1]) + + shift = str(settings["none.shift"]).split(":")[1] + + if shift == "None" or shift == "": + # no shift + _vfo.vtx_freq = rx / 10 + if shift == "-": + # minus shift + _vfo.vtx_freq = (rx - offset) / 10 + if shift == "+": + # plus shift + _vfo.vtx_freq = (rx + offset) / 10 + + # special case: narrow/wide at radio level and display icon + def handle_width(_settings, settings): + """_settings is mmap obj for settings, + settings is all the UI settings""" + + value = str(settings["settings.bw"]).split(":")[1] + + # set bw in settings + if value == "Wide": + _settings.bw.set_value(1) + _settings.bw1.set_value(0) + else: + _settings.bw.set_value(0) + _settings.bw1.set_value(1) + + # special case: battery save and display icon + def handle_bsave(_settings, settings): + """_settings is mmap obj for settings, + settings is all the UI settings""" + + value = str(settings["settings.bs"]).split(":")[1] + + # set bs in settings + if value == "True": + _settings.bs.set_value(1) + _settings.bs1.set_value(0) + else: + _settings.bs.set_value(0) + _settings.bs1.set_value(1) + + # special case: warning tones and display icon + def handle_warning(_settings, settings): + """_settings is mmap obj for settings, + settings is all the UI settings""" + + value = str(settings["settings.warning"]).split(":")[1] + + # set warning in settings + if value == "True": + _settings.warning.set_value(1) + _settings.warning1.set_value(0) else: - o.vtx_freq = rx / 10 + _settings.warning.set_value(0) + _settings.warning1.set_value(1) - mobj = self._memobj - flag = False + _mem = self._memobj for element in settings: + name = element.get_name() + if not isinstance(element, RadioSetting): self.set_settings(element) continue - # Let's roll the ball - if "." in element.get_name(): - # real properties, more or less mapeable - inter, setting = element.get_name().split(".") - obj = getattr(mobj, inter) - value = element.value - - # test on this cases ....... - if setting in ["sql", "tot", "powerrank", "active_ch", - "ani_mode"]: - value = int(value) - - # test on this cases ....... - if setting in ["lamp", "lamp_auto", "bs", "warning", - "monitor"]: - value = bool(value) - # warning and bs have a sister setting in LCD - if setting == "warning" or setting == "bs": - # aditional setting - setattr(obj, setting + "1", value) - - # monitorval: monitor = 0 > monitorval = 0 - # monitorval: monitor = 1 > monitorval = x30 - if setting == "monitor": - # sister setting in LCD - if value: - setattr(obj, "monitorval", 0x30) - else: - setattr(obj, "monitorval", 0) - - # case power - if setting == "power": - value = str(value) == "High" and True or False - - # case key - # key => auto = 0, manu = 1 - if setting == "key": - value = str(value) == "Manual" and True or False - - # case bandwidth - # bw: 0 = nar, 1 = Wide & must equal bw1 - if setting == "bw": - value = str(value) == "Wide" and True or False - # sister attr - setattr(obj, "bw1", value) - - # work mem wmem/wvfo - if setting == "wmem": - if str(value) == "Memory": - value = True - # sister attr - setattr(obj, "wvfo", not value) - else: - value = False - # sister attr - setattr(obj, "wvfo", not value) - - # case step - # STEPF = ["5", "10", "6.25", "12.5", "25"] - if setting == "step": - value = STEPF.index(str(value)) - - # case vrx_freq - if setting == "vrx_freq": - value = chirp_common.parse_freq(str(value)) / 10 - # you must calculate the apropiate txfreq from - # shift and offset - shift = _get_shift(mobj) - # update the tx vfo freq - _update_vtx(obj, value * 10, shift) - - # vfo_shift = offset - if setting == "vfo_shift": - value = chirp_common.parse_freq(str(value)) / 10 - # you must calculate the apropiate txfreq from - # shift and offset - # get vfo rx - vrx = _get_vrx(mobj) - # update the tx vfo freq - _update_vtx(mobj.vfo, vrx, value * 10) - - # at least for FD-268A/B it doesn't work as stated, so disabled - # by now, does this work on the fd-288s? - - ## case scramble & busy_lock - #if setting == "scramble" or setting == "busy_lock": - #value = bool(ONOFF.index(str(value))) - - # ani value, only for FD-288 - if setting == "ani": - if "FD-268" in self.MODEL: - # 268 doesn't have ani setting + if not element.changed(): + continue + + sett, name = name.split(".") + + try: + # special cases + if name in ["vrx_freq", "vfo_shift", "shift"]: + # call local callback + print("Calling local callback for shift handling") + handle_shift(self._memobj.vfo, settings) + continue + + if name == "bw": + # call local callback + print("Calling local callback for bw handling") + handle_width(self._memobj.settings, settings) + continue + + if name == "bs": + # call local callback + print("Calling local callback for bs handling") + handle_bsave(self._memobj.settings, settings) + continue + + if name == "warning": + # call local callback + print("Calling local callback for warning handling") + handle_warning(self._memobj.settings, settings) + continue + + if element.has_apply_callback(): + try: + element.run_apply_callback() continue - else: - # 288 models, validate the input [200-999] | "" - # we will left adjust and zero pad to avoid errors - # between inputs in the UI - value = str(value).strip().ljust(3, "0") - value = int(value) - if value == 0: - value = 200 - else: - if value > 999 or value < 200: - raise errors.InvalidValueError( - "The ANI value must be between \ - 200 and 999, not %03i" % value) - - value = str(value) + except NotImplementedError as e: + raise - else: - # Others that are artifact for real values, not than mapeables - # selecting the values to work - setting = str(element.get_name()) - value = str(element.value) - - # vfo_shift - if setting == "shift": - # get shift - offset = _get_shift(mobj) - # get vfo rx - vrx = _get_vrx(mobj) - - # VSHIFT = ["None", "-", "+"] - if value == "+": - mobj.vfo.shift_plus = True - mobj.vfo.shift_minus = False - elif value == "-": - mobj.vfo.shift_plus = False - mobj.vfo.shift_minus = True - else: - mobj.vfo.shift_plus = False - mobj.vfo.shift_minus = False - - # update the tx vfo freq - _update_vtx(mobj.vfo, vrx, offset) - - if setting != "shift": - setattr(obj, setting, value) + elif sett == "none": + LOG.debug("Setting %sett.%s is ignored" % (sett, name)) + continue + + elif element.value.get_mutable(): + # value is mutable, find it on the mem space + + LOG.debug("Setting %s.%s = %s" % (sett, name, str( + element.value))) + + # process it + try: + obj = getattr(_mem, sett) + setattr(obj, name, element.value) + + except AttributeError, e: + m = "Setting %s is not in this setting block" % name + LOG.debug(m) + + except Exception, e: + LOG.debug(element.get_name()) + raise @classmethod def match_model(cls, filedata, filename): @@ -851,9 +815,10 @@ class FeidaxinFD2x8yRadio(chirp_common.CloneModeRadio): else: return False -## FD-268 family: this are the original tested models, FD-268B UHF -## was tested "remotely" with images thanks to AG5M -## I just have the 268A in hand to test +# ##########################################################################3 +# FD-268 family: this are the original tested models, FD-268B UHF +# was tested "remotely" with images thanks to AG5M +# I just have the 268A in hand to test @directory.register @@ -873,9 +838,11 @@ class FD268BRadio(FeidaxinFD2x8yRadio): _VFO_DEFAULT = 439000000 _IDENT = "\xFF\xEE\x47\xFF" -## FD-288 Family: the only difference from this family to the FD-268's -## are the ANI settings -## Tested hacking the FD-268A memmory + +# ##################################################################### +# FD-288 Family: the only difference from this family to the FD-268's +# are the ANI settings +# Tested hacking the FD-268A memmory @directory.register @@ -895,8 +862,11 @@ class FD288BRadio(FeidaxinFD2x8yRadio): _VFO_DEFAULT = 439000000 _IDENT = "\xFF\xEE\x4C\xFF" -## the following radios was tested hacking the FD-268A memmory with -## the software and found to be clones of FD-268 ones + +# ##################################################################### +# The following radios was tested hacking the FD-268A memmory with +# the software and found to be clones of FD-268 ones +# please report any problems to driver author (see head of this file) @directory.register diff --git a/chirp/drivers/ft1d.py b/chirp/drivers/ft1d.py index 1c3550a..0f79f8e 100644 --- a/chirp/drivers/ft1d.py +++ b/chirp/drivers/ft1d.py @@ -624,6 +624,7 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio): _BACKTRACK_STATUS = ("Valid", "Invalid") _NS_HEMI = ("N", "S") _WE_HEMI = ("W", "E") + _APRS_HIGH_SPEED_MAX = 70 @classmethod def get_prompts(cls): @@ -1350,7 +1351,8 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio): prof = aprs.smartbeaconing_profile[profile] low_val = RadioSettingValueInteger(2, 30, prof.low_speed_mph) - high_val = RadioSettingValueInteger(3, 70, prof.high_speed_mph) + high_val = RadioSettingValueInteger(3, self._APRS_HIGH_SPEED_MAX, + prof.high_speed_mph) low_val.get_max = lambda: min(30, int(high_val.get_value()) - 1) rs = RadioSetting("%s.low_speed_mph" % path, @@ -1470,6 +1472,12 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio): val) menu.append(rs) + rs = self._decode_opening_message(opening_message) + menu.append(rs) + + return menu + + def _decode_opening_message(self, opening_message): msg = "" for i in opening_message.message.padded_yaesu: if i == 0xFF: @@ -1480,9 +1488,7 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio): "Opening Message", val) rs.set_apply_callback(self.apply_ff_padded_yaesu, opening_message.message) - menu.append(rs) - - return menu + return rs def backtrack_ll_validate(self, number, min, max): if str(number).lstrip('0').strip().isdigit() and \ @@ -1844,7 +1850,7 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio): try: element.run_apply_callback() except NotImplementedError as e: - LOG.error(e) + LOG.error("ft1d.set_settings: %s", e) continue # Find the object containing setting. diff --git a/chirp/drivers/ft2d.py b/chirp/drivers/ft2d.py index 50ff482..50476cc 100644 --- a/chirp/drivers/ft2d.py +++ b/chirp/drivers/ft2d.py @@ -20,7 +20,8 @@ from textwrap import dedent from chirp.drivers import yaesu_clone, ft1d from chirp import chirp_common, directory, bitwise -from chirp.settings import RadioSettings +from chirp.settings import RadioSetting, RadioSettings +from chirp.settings import RadioSettingValueString # Differences from Yaesu FT1D # 999 memories, but 901-999 are only for skipping VFO frequencies @@ -75,6 +76,7 @@ class FT2D(ft1d.FT1Radio): 0x1064A, # APRS beacon content address. 134, # Length of beacon data stored. 60) # Number of beacons stored. + _APRS_HIGH_SPEED_MAX = 90 @classmethod def get_prompts(cls): @@ -125,4 +127,31 @@ class FT2D(ft1d.FT1Radio): if mem.number >= 901 and mem.number <= 999: # for FT2D; enforces skip flag.skip = True mem.skip = "S" - super(FT2D, self).set_memory(mem)
\ No newline at end of file + super(FT2D, self).set_memory(mem) + + def _decode_opening_message(self, opening_message): + msg = "" + for i in opening_message.message.padded_yaesu: + if i == 0xFF: + break + msg += chr(int(i)) + val = RadioSettingValueString(0, 16, msg) + rs = RadioSetting("opening_message.message.padded_yaesu", + "Opening Message", val) + rs.set_apply_callback(self._apply_opening_message, + opening_message.message.padded_yaesu) + return rs + + def _apply_opening_message(self, setting, obj): + data = self._add_ff_pad(setting.value.get_value().rstrip(), 16) + val = [] + for i in data: + val.append(ord(i)) + self._memobj.opening_message.message.padded_yaesu = val + +@directory.register +class FT2Dv2(FT2D): + """Yaesu FT-2D v2 firwmare""" + VARIANT = "Rv2" + + _model = "AH60G" diff --git a/chirp/drivers/ft450d.py b/chirp/drivers/ft450d.py new file mode 100644 index 0000000..6664f77 --- /dev/null +++ b/chirp/drivers/ft450d.py @@ -0,0 +1,1494 @@ +# Copyright 2018 by Rick DeWitt (aa0rd@yahoo.com>
+# Thanks to Filippi Marco <iz3gme.marco@gmail.com> for Yaesu processes
+#
+# 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/>.
+
+"""FT450D Yaesu Radio Driver"""
+
+from chirp.drivers import yaesu_clone
+from chirp import chirp_common, util, memmap, errors, directory, bitwise
+from chirp.settings import RadioSetting, RadioSettingGroup, \
+ RadioSettingValueInteger, RadioSettingValueList, \
+ RadioSettingValueBoolean, RadioSettingValueString, \
+ RadioSettingValueFloat, RadioSettings
+import time
+import logging
+from textwrap import dedent
+
+LOG = logging.getLogger(__name__)
+
+CMD_ACK = 0x06
+# TBD: Enable some form of generated UI field, for the memory tags
+# That field wiould not be stored in img file, but generated in get_memory
+MEM_GRP_LBL = False # To ignore Comment channel-tags for now
+EX_MODES = ["USER-L", "USER-U", "LSB+CW", "USB+CW", "RTTY-L", "RTTY-U", "N/A"]
+for i in EX_MODES:
+ chirp_common.MODES.append(i)
+T_STEPS = sorted(list(chirp_common.TUNING_STEPS))
+T_STEPS.remove(30.0)
+T_STEPS.remove(100.0)
+T_STEPS.remove(125.0)
+T_STEPS.remove(200.0)
+
+@directory.register
+class FT450DRadio(yaesu_clone.YaesuCloneModeRadio):
+ """Yaesu FT-450D"""
+ BAUD_RATE = 38400
+ COM_BITS = 8 # number of data bits
+ COM_PRTY = 'N' # parity checking
+ COM_STOP = 1 # stop bits
+ MODEL = "FT-450D"
+
+ DUPLEX = ["", "-", "+"]
+ MODES = ["LSB", "USB", "CW", "AM", "FM", "RTTY-L",
+ "USER-L", "USER-U", "NFM", "CWR"]
+ TMODES = ["", "Tone", "TSQL"]
+ STEPSFM = [5.0, 6.25, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0]
+ STEPSAM = [2.5, 5.0, 9.0, 10.0, 12.5, 25.0]
+ STEPSSSB = [1.0, 2.5, 5.0]
+ VALID_BANDS = [(100000, 33000000), (33000000, 56000000)]
+ FUNC_LIST = ['MONI', 'N/A', 'PBAK', 'PLAY1', 'PLAY2', 'PLAY3', 'QSPLIT',
+ 'SPOT', 'SQLOFF', 'SWR', 'TXW', 'VCC', 'VOICE2', 'VM1MONI',
+ 'VM1REC', 'VM1TX', 'VM2MONI', 'VM2REC', 'VM2TX', 'DOWN', 'FAST',
+ 'UP', 'DSP', 'IPO/ATT', 'NB', 'AGC' , 'MODEDN', 'MODEUP',
+ 'DSP/SEL', 'KEYER', 'CLAR' , 'BANDDN', 'BANDUP', 'A=B', 'A/B',
+ 'LOCK', 'TUNE', 'VOICE', 'MW', 'V/M', 'HOME', 'RCL', 'VOX', 'STO',
+ 'STEP', 'SPLIT', 'PMS', 'SCAN', 'MENU', 'DIMMER', 'MTR']
+ CHARSET = list(chirp_common.CHARSET_ASCII)
+ CHARSET.remove("\\")
+
+ MEM_SIZE = 15017
+ # block 9 (135 Bytes long) is to be repeated 101 times
+ _block_lengths = [4, 84, 135, 162, 135, 162, 151, 130, 135, 127, 189, 103]
+
+ MEM_FORMAT = """
+ struct mem_struct { // 27 bytes per channel
+ u8 tag_on_off:2, // @ Byte 0 1=Off, 2=On
+ unk0:2,
+ mode:4;
+ u8 duplex:2, // @ byte 1
+ att:1,
+ ipo:1,
+ unka1:1,
+ tunerbad:1, // ?? Possible tuner failed
+ unk1b:1, // @@@???
+ uprband:1;
+ u8 cnturpk:1, // @ Byte 2 Peak (clr), Null (set)
+ cnturmd:3, // Contour filter mode
+ cnturgn:1, // Contour filter gain Low/high
+ mode2:3; // When mode is data(5)
+ u8 ssb_step:2, // @ Byte 3
+ am_step:3,
+ fm_step:3;
+ u8 tunerok:1, // @ Byte 4 ?? Poss tuned ok
+ cnturon:1,
+ unk4b:1,
+ dnr_on:1
+ notch:1,
+ unk4c:1,
+ tmode:2; // Tone/Cross/etc as Off/Enc/Enc+Dec
+ u8 unk5a:4, // @ byte 5
+ dnr_val:4;
+ u8 cw_width:2, // # byte 6, Notch width indexes
+ fm_width:2,
+ am_width:2,
+ sb_width:2;
+ i8 notch_pos; // @ Byte 7 Signed: - 0 +
+ u8 tone; // @ Byte 8
+ u8 unk9; // @ Byte 9 Always set to 0
+ u8 unkA; // @ Byte A
+ u8 unkB; // @ Byte B
+ u32 freq; // @ C-F
+ u32 offset; // @ 10-13
+ u8 name[7]; // @ 14-1A
+ };
+
+ #seekto 0x04;
+ struct {
+ u8 set04; // ?Checksum / Clone counter?
+ u8 set05; // Current VFO?
+ u8 set06;
+ u8 fast:1,
+ lock:1, // Inverted: 1 = Off
+ nb:1,
+ agc:5;
+ u8 set08a:3,
+ keyer:1,
+ set08b:2,
+ mtr_mode:2;
+ u8 set09;
+ u8 set0A;
+ u8 set0B:2,
+ clk_sft:1,
+ cont:5; // 1:1
+ u8 beepvol_sgn:1, // @x0C: set : Link @0x41, clear: fix @ 0x40
+ set0Ca:3,
+ clar_btn:1, // 0 = Dial, 1= SEL
+ cwstone_sgn:1, // Set: Lnk @ x42, clear: Fixed at 0x43
+ beepton:2; // Index 0-3
+ u8 set0Da:1,
+ cw_key:1,
+ set0Db:3,
+ dialstp_mode:1,
+ dialstp:2;
+ u8 set0E:1,
+ keyhold:1,
+ lockmod:1,
+ set0ea:1,
+ amfmdial:1, // 0= Enabled. 1 = Disabled
+ cwpitch:3; // 0-based index
+ u8 sql_rfg:1
+ set0F:2,
+ cwweigt:5; // Index 1:2.5=0 -> 1:4.5=20
+ u8 cw_dly; // @x10 ms = val * 10
+ u8 set11;
+ u8 cwspeed; // val 4-60 is wpm, *5 is cpm
+ u8 vox_gain; // val 1:1
+ u8 set14:2,
+ emergen:1,
+ vox_dly:5; // ms = val * 100
+ u8 set15a:1,
+ stby_beep:1
+ set15b:1
+ mem_grp:1,
+ apo:4;
+ u8 tot; // Byte x16, 1:1
+ u8 micscan:1,
+ set17:5,
+ micgain:2;
+ u8 cwpaddl:1, // @x18 0=Key, 1=Mic
+ set18:7;
+ u8 set19;
+ u8 set1A;
+ u8 set1B;
+ u8 set1C;
+ u8 dig_vox; // 1:1
+ u8 set1E;
+ i16 d_disp; // @ x1F,x20 signed 16bit
+ u8 pnl_cs; // 0-based index
+ u8 pm_up;
+ u8 pm_fst;
+ u8 pm_dwn;
+ u8 set25;
+ u8 set26;
+ u8 set27;
+ u8 set28;
+ u8 beacon_time; // 1:1
+ u8 set2A;
+ u8 cat_rts:1, // @x2b: Enable=0, Disable=1
+ peakhold:1,
+ set2B:4,
+ cat_tot:2; // Index 0-3
+ u8 set2CA:2,
+ rtyrpol:1,
+ rtytpol:1
+ rty_sft:2,
+ rty_ton:1,
+ set2CC:1;
+ u8 dig_vox; // 1:1
+ u8 ext_mnu:1,
+ m_tune:1,
+ set2E:2,
+ scn_res:4;
+ u8 cw_auto:1, // Off=0, On=1
+ cwtrain:2, // Index
+ set2F:1,
+ cw_qsk:2, // Index
+ cw_bfo:2; // Index
+ u8 mic_eq; // @x30 1:1
+ u8 set31:5,
+ catrate:3; // Index 0-4
+ u8 set32;
+ u8 dimmer:4,
+ set33:4;
+ u8 set34;
+ u8 set35;
+ u8 set36;
+ u8 set37;
+ u8 set38a:1,
+ rfpower:7; // 1:1
+ u8 set39a:2,
+ tuner:3, // Index 0-4
+ seldial:3; // Index 0-5
+ u8 set3A;
+ u8 set3B;
+ u8 set3C;
+ i8 qspl_f; // Signed
+ u8 set3E;
+ u8 set3F;
+ u8 beepvol_fix; // 1:1
+ i8 beepvol_lnk; // SIGNED 2's compl byte
+ u8 cwstone_fix;
+ i8 cwstone_lnk; // signed byte
+ u8 set44:2,
+ mym_data:1, // My Mode: Data, set = OFF
+ mym_fm:1,
+ mym_am:1,
+ mym_cw:1,
+ mym_usb:1,
+ mym_lsb:1;
+ u8 myb_24:1, // My Band: 24Mhz set = OFF
+ myb_21:1,
+ myb_18:1,
+ myb_14:1,
+ myb_10:1,
+ myb_7:1,
+ myb_3_5:1,
+ myb_1_8:1;
+ u8 set46:6,
+ myb_28:1,
+ myb_50:1;
+ u8 set47;
+ u8 set48;
+ u8 set49;
+ u8 set4A;
+ u8 set4B;
+ u8 set4C;
+ u8 set4D;
+ u8 set4E;
+ u8 set4F;
+ u8 set50;
+ u8 set51;
+ u8 set52;
+ u8 set53;
+ u8 set54;
+ u8 set55;
+ u8 set56a:3,
+ split:1,
+ set56b:4;
+ u8 set57;
+ } settings;
+
+ #seekto 0x58;
+ struct mem_struct vfoa[11]; // The current cfgs for each vfo 'band'
+ struct mem_struct vfob[11];
+ struct mem_struct home[2]; // The 2 Home cfgs (HF and 6m)
+ struct mem_struct qmb; // The Quick Memory Bank STO/RCL
+ struct mem_struct mtqmb; // Last QMB-MemTune cfg (not displayed)
+ struct mem_struct mtune; // Last MemTune cfg (not displayed)
+
+ #seekto 0x343; // chan status
+ u8 visible[63]; // 1 bit per channel
+ u8 pmsvisible; // @ 0x382
+
+ #seekto 0x383;
+ u8 filled[63];
+ u8 pmsfilled; // @ 0x3c2
+
+ #seekto 0x3C3;
+ struct mem_struct memory[500];
+ struct mem_struct pms[4]; // Programed Scan limits @ x387F
+
+ #seekto 0x3906;
+ struct {
+ char t1[40]; // CW Beacon Text
+ char t2[40];
+ char t3[40];
+ } beacontext; // to 0x397E
+
+ #seekto 0x3985;
+ struct mem_struct m60[5]; // to 0x3A0B
+
+ #seekto 0x03a45;
+ struct mem_struct current;
+
+ """
+ _CALLSIGN_CHARSET = [chr(x) for x in range(ord("0"), ord("9") + 1) +
+ range(ord("A"), ord("Z") + 1) + [ord(" ")]]
+ _CALLSIGN_CHARSET_REV = dict(zip(_CALLSIGN_CHARSET,
+ range(0, len(_CALLSIGN_CHARSET))))
+
+ # WARNING Indecis are hard wired in get/set_memory code !!!
+ # Channels print in + increasing index order (PMS first)
+ SPECIAL_MEMORIES = {
+ "VFOa-1.8M": -27,
+ "VFOa-3.5M": -26,
+ "VFOa-7M": -25,
+ "VFOa-10M": -24,
+ "VFOa-14M": -23,
+ "VFOa-18M": -22,
+ "VFOa-21M": -21,
+ "VFOa-24M": -20,
+ "VFOa-28M": -19,
+ "VFOa-50M": -18,
+ "VFOa-HF": -17,
+ "VFOb-1.8M": -16,
+ "VFOb-3.5M": -15,
+ "VFOb-7M": -14,
+ "VFOb-10M": -13,
+ "VFOb-14M": -12,
+ "VFOb-18M": -11,
+ "VFOb-21M": - 10,
+ "VFOb-24M": -9,
+ "VFOb-28M": -8,
+ "VFOb-50M": -7,
+ "VFOb-HF": -6,
+ "HOME-HF": -5,
+ "HOME-50M": -4,
+ "QMB": -3,
+ "QMB-MTune": -2,
+ "Mem-Tune": -1,
+ }
+ FIRST_VFOB_INDEX = -6
+ LAST_VFOB_INDEX = -16
+ FIRST_VFOA_INDEX = -17
+ LAST_VFOA_INDEX = -27
+
+ SPECIAL_PMS = {
+ "PMS1-L": -36,
+ "PMS1-U": -35,
+ "PMS2-L": -34,
+ "PMS2-U": -33,
+ }
+ LAST_PMS_INDEX = -36
+ SPECIAL_MEMORIES.update(SPECIAL_PMS)
+
+ SPECIAL_60M = {
+ "60m-Ch1": -32,
+ "60m-Ch2": -31,
+ "60m-Ch3": -30,
+ "60m-Ch4": -29,
+ "60m-Ch5": -28,
+ }
+ LAST_60M_INDEX = -32
+ SPECIAL_MEMORIES.update(SPECIAL_60M)
+
+ SPECIAL_MEMORIES_REV = dict(zip(SPECIAL_MEMORIES.values(),
+ SPECIAL_MEMORIES.keys()))
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+ rp.info = _(dedent("""
+ The FT-450 radio driver loads the 'Special Channels' tab
+ with the PMS scanning range memories (group 11), 60meter
+ channels (group 12), the QMB (STO/RCL) memory, the HF and
+ 50m HOME memories and all the A and B VFO memories.
+ There are VFO memories for the last frequency dialed in
+ each band. The last mem-tune config is also stored.
+ These Special Channels allow limited field editting.
+ This driver also populates the 'Other' tab in the channel
+ memory Properties window. This tab contains values for
+ those channel memory settings that don't fall under the
+ standard Chirp display columns.
+ """))
+ rp.pre_download = _(dedent("""\
+ 1. Turn radio off.
+ 2. Connect cable to ACC jack.
+ 3. Press and hold in the [MODE <] and [MODE >] keys while
+ turning the radio on ("CLONE MODE" will appear on the
+ display).
+ 4. <b>After clicking OK</b> here, press the [C.S.] key to
+ send image."""))
+ rp.pre_upload = _(dedent("""\
+ 1. Turn radio off.
+ 2. Connect cable to ACC jack.
+ 3. Press and hold in the [MODE <] and [MODE >] keys while
+ turning the radio on ("CLONE MODE" will appear on the
+ display).
+ 4. Click OK here.
+ ("Receiving" will appear on the LCD)."""))
+ return rp
+
+ def _read(self, block, blocknum):
+ # be very patient at first block
+ if blocknum == 0:
+ attempts = 60
+ else:
+ attempts = 5
+ for _i in range(0, attempts):
+ data = self.pipe.read(block + 2) # Blocknum, data,checksum
+ if data:
+ break
+ time.sleep(0.5)
+ if len(data) == block + 2 and data[0] == chr(blocknum):
+ checksum = yaesu_clone.YaesuChecksum(1, block)
+ if checksum.get_existing(data) != \
+ checksum.get_calculated(data):
+ raise Exception("Checksum Failed [%02X<>%02X] block %02X" %
+ (checksum.get_existing(data),
+ checksum.get_calculated(data), blocknum))
+ # Remove the block number and checksum
+ data = data[1:block + 1]
+ else: # Use this info to decode a new Yaesu model
+ raise Exception("Unable to read block %i expected %i got %i"
+ % (blocknum, block + 2, len(data)))
+ return data
+
+ def _clone_in(self):
+ # Be very patient with the radio
+ self.pipe.timeout = 2
+ self.pipe.baudrate = self.BAUD_RATE
+ self.pipe.bytesize = self.COM_BITS
+ self.pipe.parity = self.COM_PRTY
+ self.pipe.stopbits = self.COM_STOP
+ self.pipe.rtscts = False
+
+ start = time.time()
+
+ data = ""
+ blocks = 0
+ status = chirp_common.Status()
+ status.msg = _("Cloning from radio")
+ nblocks = len(self._block_lengths) + 100 # Block 8 repeats
+ status.max = nblocks
+ for block in self._block_lengths:
+ if blocks == 8:
+ # repeated read of block 8 same size (chan memory area)
+ repeat = 101
+ else:
+ repeat = 1
+ for _i in range(0, repeat):
+ data += self._read(block, blocks)
+ self.pipe.write(chr(CMD_ACK))
+ blocks += 1
+ status.cur = blocks
+ self.status_fn(status)
+ data += self.MODEL # Append ID
+ return memmap.MemoryMap(data)
+
+ def _clone_out(self):
+ self.pipe.baudrate = self.BAUD_RATE
+ self.pipe.bytesize = self.COM_BITS
+ self.pipe.parity = self.COM_PRTY
+ self.pipe.stopbits = self.COM_STOP
+ self.pipe.rtscts = False
+ delay = 0.5
+ start = time.time()
+ blocks = 0
+ pos = 0
+ status = chirp_common.Status()
+ status.msg = _("Cloning to radio")
+ status.max = len(self._block_lengths) + 100
+ for block in self._block_lengths:
+ if blocks == 8:
+ repeat = 101
+ else:
+ repeat = 1
+ for _i in range(0, repeat):
+ time.sleep(0.01)
+ checksum = yaesu_clone.YaesuChecksum(pos, pos + block - 1)
+ self.pipe.write(chr(blocks))
+ self.pipe.write(self.get_mmap()[pos:pos + block])
+ self.pipe.write(chr(checksum.get_calculated(self.get_mmap())))
+ buf = self.pipe.read(1)
+ if not buf or buf[0] != chr(CMD_ACK):
+ time.sleep(delay)
+ buf = self.pipe.read(1)
+ if not buf or buf[0] != chr(CMD_ACK):
+ raise Exception(_("Radio did not ack block %i") % blocks)
+ pos += block
+ blocks += 1
+ status.cur = blocks
+ self.status_fn(status)
+
+
+ def sync_in(self):
+ try:
+ self._mmap = self._clone_in()
+ except errors.RadioError:
+ raise
+ except Exception, e:
+ raise errors.RadioError("Failed to communicate with radio: %s"
+ % e)
+ self.process_mmap()
+
+ def sync_out(self):
+ try:
+ self._clone_out()
+ except errors.RadioError:
+ raise
+ except Exception, e:
+ raise errors.RadioError("Failed to communicate with radio: %s"
+ % e)
+
+ def process_mmap(self):
+ self._memobj = bitwise.parse(self.MEM_FORMAT, self._mmap)
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_bank = False
+ rf.has_dtcs= False
+ if MEM_GRP_LBL:
+ rf.has_comment = True # Used for Mem-Grp number
+ rf.valid_modes = list(set(self.MODES))
+ rf.valid_tmodes = list(self.TMODES)
+ rf.valid_duplexes = list(self.DUPLEX)
+ rf.valid_tuning_steps = list(T_STEPS)
+ rf.valid_bands = self.VALID_BANDS
+ rf.valid_power_levels = []
+ rf.valid_characters = "".join(self.CHARSET)
+ rf.valid_name_length = 7
+ rf.valid_skips = []
+ rf.valid_special_chans = sorted(self.SPECIAL_MEMORIES.keys())
+ rf.memory_bounds = (1, 500)
+ rf.has_ctone = True
+ rf.has_settings = True
+ rf.has_cross = True
+ return rf
+
+ def get_raw_memory(self, number):
+ return repr(self._memobj.memory[number - 1])
+
+ def _get_tmode(self, mem, _mem):
+ mem.tmode = self.TMODES[_mem.tmode]
+ mem.rtone = chirp_common.TONES[_mem.tone]
+ mem.ctone = mem.rtone
+
+ def _set_duplex(self, mem, _mem):
+ _mem.duplex = self.DUPLEX.index(mem.duplex)
+
+ def get_memory(self, number):
+ if isinstance(number, str):
+ return self._get_special(number)
+ elif number < 0:
+ # I can't stop delete operation from loosing extd_number but
+ # I know how to get it back
+ return self._get_special(self.SPECIAL_MEMORIES_REV[number])
+ else:
+ return self._get_normal(number)
+
+ def set_memory(self, memory):
+ if memory.number < 0:
+ return self._set_special(memory)
+ else:
+ return self._set_normal(memory)
+
+ def _get_special(self, number):
+ mem = chirp_common.Memory()
+ mem.number = self.SPECIAL_MEMORIES[number]
+ mem.extd_number = number
+
+ if mem.number in range(self.FIRST_VFOA_INDEX,
+ self.LAST_VFOA_INDEX - 1, -1):
+ _mem = self._memobj.vfoa[-self.LAST_VFOA_INDEX + mem.number]
+ immutable = ["number", "extd_number", "name", "power"]
+ elif mem.number in range(self.FIRST_VFOB_INDEX,
+ self.LAST_VFOB_INDEX - 1, -1):
+ _mem = self._memobj.vfob[-self.LAST_VFOB_INDEX + mem.number]
+ immutable = ["number", "extd_number", "name", "power"]
+ elif mem.number in range(-4, -6, -1): # 2 Home Chans
+ _mem = self._memobj.home[5 + mem.number]
+ immutable = ["number", "extd_number", "name", "power"]
+ elif mem.number == -3:
+ _mem = self._memobj.qmb
+ immutable = ["number", "extd_number", "name", "power"]
+ elif mem.number == -2:
+ _mem = self._memobj.mtqmb
+ immutable = ["number", "extd_number", "name", "power"]
+ elif mem.number == -1:
+ _mem = self._memobj.mtune
+ immutable = ["number", "extd_number", "name", "power"]
+ elif mem.number in self.SPECIAL_PMS.values():
+ bitindex = (-self.LAST_PMS_INDEX) + mem.number
+ used = (self._memobj.pmsvisible >> bitindex) & 0x01
+ valid = (self._memobj.pmsfilled >> bitindex) & 0x01
+ if not used:
+ mem.empty = True
+ if not valid:
+ mem.empty = True
+ return mem
+ mx = (-self.LAST_PMS_INDEX) + mem.number
+ _mem = self._memobj.pms[mx]
+ mx = mx + 1
+ if MEM_GRP_LBL:
+ mem.comment = "M-11-%02i" % mx
+ immutable = ["number", "rtone", "ctone", "extd_number",
+ "tmode", "cross_mode",
+ "power", "duplex", "offset"]
+ elif mem.number in self.SPECIAL_60M.values():
+ mx = (-self.LAST_60M_INDEX) + mem.number
+ _mem = self._memobj.m60[mx]
+ mx = mx + 1
+ if MEM_GRP_LBL:
+ mem.comment = "M-12-%02i" % mx
+ immutable = ["number", "rtone", "ctone", "extd_number",
+ "tmode", "cross_mode",
+ "frequency", "power", "duplex", "offset"]
+ else:
+ raise Exception("Sorry, you can't edit that special"
+ " memory channel %i." % mem.number)
+
+ mem = self._get_memory(mem, _mem)
+ mem.immutable = immutable
+
+ return mem
+
+ def _set_special(self, mem):
+ if mem.empty and mem.number not in self.SPECIAL_PMS.values():
+ # can't delete special memories!
+ raise Exception("Sorry, special memory can't be deleted")
+
+ cur_mem = self._get_special(self.SPECIAL_MEMORIES_REV[mem.number])
+
+ if mem.number in range(self.FIRST_VFOA_INDEX,
+ self.LAST_VFOA_INDEX - 1, -1):
+ _mem = self._memobj.vfoa[-self.LAST_VFOA_INDEX + mem.number]
+ elif mem.number in range(self.FIRST_VFOB_INDEX,
+ self.LAST_VFOB_INDEX - 1, -1):
+ _mem = self._memobj.vfob[-self.LAST_VFOB_INDEX + mem.number]
+ elif mem.number in range(-4, -6, -1):
+ _mem = self._memobj.home[5 + mem.number]
+ elif mem.number == -3:
+ _mem = self._memobj.qmb
+ elif mem.number == -2:
+ _mem = self._memobj.mtqmb
+ elif mem.number == -1:
+ _mem = self._memobj.mtune
+ elif mem.number in self.SPECIAL_PMS.values():
+ bitindex = (-self.LAST_PMS_INDEX) + mem.number
+ wasused = (self._memobj.pmsvisible >> bitindex) & 0x01
+ wasvalid = (self._memobj.pmsfilled >> bitindex) & 0x01
+ if mem.empty:
+ if wasvalid and not wasused:
+ # pylint get confused by &= operator
+ self._memobj.pmsfilled = self._memobj.pmsfilled & \
+ ~ (1 << bitindex)
+ # pylint get confused by &= operator
+ self._memobj.pmsvisible = self._memobj.pmsvisible & \
+ ~ (1 << bitindex)
+ return
+ # pylint get confused by |= operator
+ self._memobj.pmsvisible = self._memobj.pmsvisible | 1 << bitindex
+ self._memobj.pmsfilled = self._memobj.pmsfilled | 1 << bitindex
+ _mem = self._memobj.pms[-self.LAST_PMS_INDEX + mem.number]
+ else:
+ raise Exception("Sorry, you can't edit"
+ " that special memory.")
+
+ for key in cur_mem.immutable:
+ if key != "extd_number":
+ if cur_mem.__dict__[key] != mem.__dict__[key]:
+ raise errors.RadioError("Editing field `%s' " % key +
+ "is not supported on this channel")
+
+ self._set_memory(mem, _mem)
+
+ def _get_normal(self, number):
+ _mem = self._memobj.memory[number - 1]
+ used = (self._memobj.visible[(number - 1) / 8] >> (number - 1) % 8) \
+ & 0x01
+ valid = (self._memobj.filled[(number - 1) / 8] >> (number - 1) % 8) \
+ & 0x01
+
+ mem = chirp_common.Memory()
+ mem.number = number
+ if not used:
+ mem.empty = True
+ if not valid or _mem.freq == 0xffffffff:
+ return mem
+ if MEM_GRP_LBL:
+ mgrp = int((number - 1) / 50)
+ mem.comment = "M-%02i-%02i" % (mgrp + 1, number - (mgrp * 50))
+ return self._get_memory(mem, _mem)
+
+ def _set_normal(self, mem):
+ _mem = self._memobj.memory[mem.number - 1]
+ wasused = (self._memobj.visible[(mem.number - 1) / 8] >>
+ (mem.number - 1) % 8) & 0x01
+ wasvalid = (self._memobj.filled[(mem.number - 1) / 8] >>
+ (mem.number - 1) % 8) & 0x01
+
+ if mem.empty:
+ if mem.number == 1:
+ raise Exception("Sorry, can't delete first memory")
+ if wasvalid and not wasused:
+ self._memobj.filled[(mem.number - 1) / 8] &= \
+ ~(1 << (mem.number - 1) % 8)
+ _mem.set_raw("\xFF" * (_mem.size() / 8)) # clean up
+ self._memobj.visible[(mem.number - 1) / 8] &= \
+ ~(1 << (mem.number - 1) % 8)
+ return
+ if not wasvalid:
+ _mem.set_raw("\x00" * (_mem.size() / 8)) # clean up
+
+ self._memobj.visible[(mem.number - 1) / 8] |= 1 << (mem.number - 1) \
+ % 8
+ self._memobj.filled[(mem.number - 1) / 8] |= 1 << (mem.number - 1) \
+ % 8
+ self._set_memory(mem, _mem)
+
+ def _get_memory(self, mem, _mem):
+ mem.freq = int(_mem.freq)
+ mem.offset = int(_mem.offset)
+ mem.duplex = self.DUPLEX[_mem.duplex]
+ # Mode gets tricky with dual (USB+DATA) options
+ vx = _mem.mode
+ if vx == 4: # FM or NFM
+ if _mem.mode2 == 2:
+ vx = 4 # FM
+ else:
+ vx = 8 # NFM
+ if vx == 10: # CWR
+ vx = 9
+ if vx == 5: # Data/Dual mode
+ if _mem.mode2 == 0: # RTTY-L
+ vx = 5
+ if _mem.mode2 == 1: # USER-L
+ vx = 6
+ if _mem.mode2 == 2: # USER-U
+ vx = 7
+ mem.mode = self.MODES[vx]
+ if mem.mode == "FM" or mem.mode == "NFM":
+ mem.tuning_step = self.STEPSFM[_mem.fm_step]
+ elif mem.mode == "AM":
+ mem.tuning_step = self.STEPSAM[_mem.am_step]
+ elif mem.mode[:2] == "CW":
+ mem.tuning_step = self.STEPSSSB[_mem.ssb_step]
+ else:
+ try:
+ mem.tuning_step = self.STEPSSSB[_mem.ssb_step]
+ except IndexError:
+ pass
+ self._get_tmode(mem, _mem)
+
+ if _mem.tag_on_off == 2:
+ for i in _mem.name:
+ if i == 0xFF:
+ break
+ if chr(i) in self.CHARSET:
+ mem.name += chr(i)
+ else:
+ # radio has some graphical chars that are not supported
+ # we replace those with a *
+ LOG.info("Replacing char %x with *" % i)
+ mem.name += "*"
+ mem.name = mem.name.rstrip()
+ else:
+ mem.name = ""
+
+ mem.extra = RadioSettingGroup("extra", "Extra")
+
+ rs = RadioSetting("ipo", "IPO",
+ RadioSettingValueBoolean(bool(_mem.ipo)))
+ rs.set_doc("Bypass preamp")
+ mem.extra.append(rs)
+
+ rs = RadioSetting("att", "ATT",
+ RadioSettingValueBoolean(bool(_mem.att)))
+ rs.set_doc("10dB front end attenuator")
+ mem.extra.append(rs)
+
+ rs = RadioSetting("cnturon", "Contour Filter",
+ RadioSettingValueBoolean(_mem.cnturon ))
+ rs.set_doc("Contour filter on/off")
+ mem.extra.append(rs)
+
+ options = ["Peak", "Null"]
+ rs = RadioSetting("cnturpk", "Contour Filter Mode",
+ RadioSettingValueList(options,
+ options[_mem.cnturpk]))
+ mem.extra.append(rs)
+
+ options = ["Low", "High"]
+ rs = RadioSetting("cnturgn", "Contour Filter Gain",
+ RadioSettingValueList(options,
+ options[_mem.cnturgn]))
+ rs.set_doc("Filter gain/attenuation")
+ mem.extra.append(rs)
+
+ options = ["-2", "-1", "Center", "+1", "+2"]
+ rs = RadioSetting("cnturmd", "Contour Filter Notch",
+ RadioSettingValueList(options,
+ options[_mem.cnturmd]))
+ rs.set_doc("Filter notch offset")
+ mem.extra.append(rs)
+
+ rs = RadioSetting("notch", "Notch Filter",
+ RadioSettingValueBoolean(_mem.notch ))
+ rs.set_doc("IF bandpass filter")
+ mem.extra.append(rs)
+
+ vx = 1
+ options = ["<-", "Center", "+>"]
+ if _mem.notch_pos < 0:
+ vx = 0
+ if _mem.notch_pos > 0:
+ vx = 2
+ rs = RadioSetting("notch_pos", "Notch Position",
+ RadioSettingValueList(options, options[vx]))
+ rs.set_doc("IF bandpass filter shift")
+ mem.extra.append(rs)
+
+ vx = 0
+ if mem.mode[1:] == "SB":
+ options = ["1.8kHz", "2.4kHz", "3.0kHz"]
+ vx = _mem.sb_width
+ stx = "sb_width"
+ elif mem.mode[:1] == "CW":
+ options = ["300Hz", "500 kHz", "2.4kHz"]
+ vx = _mem.cw_width
+ stx = "cw_width"
+ elif mem.mode[:4] == "USER" or mem.mode[:4] == "RTTY":
+ options = ["300Hz", "2.4kHz", "3.0kHz"]
+ vx = _mem.sb_width
+ stx = "sb_width"
+ elif mem.mode == "AM":
+ options = ["3.0kHz", "6.0kHz", "9.0 kHz"]
+ vx = _mem.am_width
+ stx = "am_width"
+ else:
+ options = ["2.5kHz", "5.0kHz"]
+ vx = _mem.fm_width
+ stx = "fm_width"
+ rs = RadioSetting(stx, "IF Bandpass Filter Width",
+ RadioSettingValueList(options, options[vx]))
+ rs.set_doc("DSP IF bandpass Notch width (Hz)")
+ mem.extra.append(rs)
+
+ rs = RadioSetting("dnr_on", "DSP Noise Reduction",
+ RadioSettingValueBoolean(bool(_mem.dnr_on)))
+ rs.set_doc("Digital noise processing")
+ mem.extra.append(rs)
+
+ options = ["Off", "1", "2", "3", "4", "5", "6", "7",
+ "8", "9", "10", "11"]
+ rs = RadioSetting("dnr_val", "DSP Noise Reduction Alg",
+ RadioSettingValueList(options,
+ options[ _mem.dnr_val]))
+ rs.set_doc("Digital noise reduction algorithm number (1-11)")
+ mem.extra.append(rs)
+
+ return mem # end get_memory
+
+ def _set_memory(self, mem, _mem):
+ if len(mem.name) > 0:
+ _mem.tag_on_off = 2
+ else:
+ _mem.tag_on_off = 1
+ self._set_duplex(mem, _mem)
+ _mem.mode2 = 0
+ if mem.mode == "USER-L":
+ _mem.mode = 5
+ _mem.mode2 = 1
+ elif mem.mode == "USER-U":
+ _mem.mode = 5
+ _mem.mode2 = 2
+ elif mem.mode == "RTTY-L":
+ _mem.mode = 5
+ _mem.mode2 = 0
+ elif mem.mode == "CWR":
+ _mem.mode = 10
+ _mem.mode2 = 0
+ elif mem.mode == "CW":
+ _mem.mode = 2
+ _mem.mode2 = 0
+ elif mem.mode == "NFM":
+ _mem.mode = 4
+ _mem.mode2 = 1
+ elif mem.mode == "FM":
+ _mem.mode = 4
+ _mem.mode2 = 2
+ else: # LSB, USB, AM
+ _mem.mode = self.MODES.index(mem.mode)
+ _mem.mode2 = 0
+ try:
+ _mem.ssb_step = self.STEPSSSB.index(mem.tuning_step)
+ except ValueError:
+ pass
+ try:
+ _mem.am_step = self.STEPSAM.index(mem.tuning_step)
+ except ValueError:
+ pass
+ try:
+ _mem.fm_step = self.STEPSFM.index(mem.tuning_step)
+ except ValueError:
+ pass
+ _mem.freq = mem.freq
+ _mem.uprband = 0
+ if mem.freq >= 33000000:
+ _mem.uprband = 1
+ _mem.offset = mem.offset
+ _mem.tmode = self.TMODES.index(mem.tmode)
+ _mem.tone = chirp_common.TONES.index(mem.rtone)
+ _mem.tunerok = 0 # Dont know what these two do...
+ _mem.tunerbad = 0
+
+ for i in range(0, 7):
+ _mem.name[i] = ord(mem.name.ljust(7)[i])
+
+ for setting in mem.extra:
+ if setting.get_name() == "notch_pos":
+ vx = 0 # Overide list string with signed value
+ stx = str(setting.value)
+ if stx == "<-":
+ vx = -13
+ if stx == "+>":
+ vx = 12
+ setattr(_mem, "notch_pos", vx)
+ elif setting.get_name() == "dnr_val":
+ stx = str(setting.value) # Convert string to int
+ vx = 0
+ if stx != "Off":
+ vx = int(stx)
+ else:
+ setattr(_mem, "dnr_on", 0)
+ setattr(_mem, setting.get_name(), vx)
+ else:
+ setattr(_mem, setting.get_name(), setting.value)
+
+
+ @classmethod
+ def match_model(cls, filedata, filename):
+ """Match the opened/downloaded image to the correct version"""
+ if len(filedata) == cls.MEM_SIZE + 7: # +7 bytes of model name
+ rid = filedata[cls.MEM_SIZE:cls.MEM_SIZE + 7]
+ if rid.startswith(cls.MODEL):
+ return True
+ else:
+ return False
+
+ def _invert_me(self, setting, obj, atrb):
+ """Callback: from inverted logic 1-bit booleans"""
+ invb = not setting.value
+ setattr(obj, atrb, invb)
+ return
+
+ def _chars2str(self, cary, knt):
+ """Convert raw memory char array to a string: NOT a callback."""
+ stx = ""
+ for char in cary[:knt]:
+ stx += chr(char)
+ return stx
+
+ def _my_str2ary(self, setting, obj, atrba, knt):
+ """Callback: convert string to fixed-length char array.."""
+ ary = ""
+ for j in range(0, knt, 1):
+ chx = ord(str(setting.value)[j])
+ if chx < 32 or chx > 125: # strip non-printing
+ ary += " "
+ else:
+ ary += str(setting.value)[j]
+ setattr(obj, atrba, ary)
+ return
+
+ def get_settings(self):
+ _settings = self._memobj.settings
+ _beacon = self._memobj.beacontext
+ gen = RadioSettingGroup("gen", "General")
+ cw = RadioSettingGroup("cw", "CW")
+ pnlcfg = RadioSettingGroup("pnlcfg", "Panel buttons")
+ pnlset = RadioSettingGroup("pnlset", "Panel settings")
+ voxdat = RadioSettingGroup("voxdat", "VOX and Data")
+ mic = RadioSettingGroup("mic", "Microphone")
+ mybands = RadioSettingGroup("mybands", "My Bands")
+ mymodes = RadioSettingGroup("mymodes", "My Modes")
+
+ top = RadioSettings(gen, cw, pnlcfg, pnlset, voxdat, mic,
+ mymodes, mybands)
+
+ self._do_general_settings(gen)
+ self._do_cw_settings(cw)
+ self._do_panel_buttons(pnlcfg)
+ self._do_panel_settings(pnlset)
+ self._do_vox_settings(voxdat)
+ self._do_mic_settings(mic)
+ self._do_mymodes_settings(mymodes)
+ self._do_mybands_settings(mybands)
+
+ return top
+
+ def _do_general_settings(self, tab):
+ _settings = self._memobj.settings
+
+ rs = RadioSetting("ext_mnu", "Extended menu",
+ RadioSettingValueBoolean(_settings.ext_mnu))
+ rs.set_doc("Enables access to extended settings in the radio")
+ tab.append(rs)
+
+ rs = RadioSetting("apo", "APO time (Hrs)",
+ RadioSettingValueInteger(1, 12, _settings.apo))
+ tab.append(rs)
+
+ options = ["%i" % i for i in range(0, 21)]
+ options[0] = "Off"
+ rs = RadioSetting("tot", "TX 'TOT' time-out (mins)",
+ RadioSettingValueList(options,
+ options[_settings.tot]))
+ tab.append(rs)
+
+ bx = not _settings.cat_rts # Convert from Enable=0
+ rs = RadioSetting("cat_rts", "CAT RTS flow control",
+ RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "cat_rts")
+ tab.append(rs)
+
+ options = ["0", "100ms", "1000ms", "3000ms"]
+ rs = RadioSetting("cat_tot", "CAT Timeout",
+ RadioSettingValueList(options,
+ options[_settings.cat_tot]))
+ tab.append(rs)
+
+ options = ["4800", "9600", "19200", "38400", "Data"]
+ rs = RadioSetting("catrate", "CAT rate",
+ RadioSettingValueList(options,
+ options[_settings.catrate]))
+ tab.append(rs)
+
+ rs = RadioSetting("mem_grp", "Mem groups",
+ RadioSettingValueBoolean(_settings.mem_grp))
+ tab.append(rs)
+
+ rs = RadioSetting("scn_res", "Resume scan (secs)",
+ RadioSettingValueInteger(0, 10, _settings.scn_res))
+ tab.append(rs)
+
+ rs = RadioSetting("clk_sft", "CPU clock shift",
+ RadioSettingValueBoolean(_settings.clk_sft))
+ tab.append(rs)
+
+ rs = RadioSetting("split", "TX/RX Frequency Split",
+ RadioSettingValueBoolean(_settings.split))
+ tab.append(rs)
+
+ rs = RadioSetting("qspl_f", "Quick-Split freq offset (KHz)",
+ RadioSettingValueInteger(-20, 20, _settings.qspl_f))
+ tab.append(rs)
+
+ rs = RadioSetting("emergen", "Alaska Emergency Mem 5167.5KHz",
+ RadioSettingValueBoolean(_settings.emergen))
+ tab.append(rs)
+
+ rs = RadioSetting("stby_beep", "PTT release 'Standby' beep",
+ RadioSettingValueBoolean(_settings.stby_beep))
+ tab.append(rs)
+
+ options = ["ATAS", "EXT ATU", "INT ATU", "INTRATU", "F-TRANS"]
+ rs = RadioSetting("tuner", "Antenna Tuner",
+ RadioSettingValueList(options,
+ options[_settings.tuner]))
+ tab.append(rs)
+
+ rs = RadioSetting("rfpower", "RF power (watts)",
+ RadioSettingValueInteger(5, 100, _settings.rfpower))
+ tab.append(rs) # End of _do_general_settings
+
+
+ def _do_cw_settings(self, cw): # - - - CW - - -
+ _settings = self._memobj.settings
+ _beacon = self._memobj.beacontext
+
+ rs = RadioSetting("cw_dly", "CW break-in delay (ms * 10)",
+ RadioSettingValueInteger(0, 300, _settings.cw_dly))
+ cw.append(rs)
+
+ options = ["%i Hz" % i for i in range(400, 801, 100)]
+ rs = RadioSetting("cwpitch", "CW pitch",
+ RadioSettingValueList(options,
+ options[_settings.cwpitch]))
+ cw.append(rs)
+
+ rs = RadioSetting("cwspeed", "CW speed (wpm)",
+ RadioSettingValueInteger(4, 60, _settings.cwspeed))
+ rs.set_doc("Cpm is Wpm * 5")
+ cw.append(rs)
+
+ options = ["1:%1.1f" % (i / 10) for i in range(25, 46, 1)]
+ rs = RadioSetting("cwweigt", "CW weight",
+ RadioSettingValueList(options,
+ options[_settings.cwweigt]))
+ cw.append(rs)
+
+ options = ["15ms", "20ms", "25ms", "30ms"]
+ rs = RadioSetting("cw_qsk", "CW delay before TX in QSK mode",
+ RadioSettingValueList(options,
+ options[_settings.cw_qsk]))
+ cw.append(rs)
+
+ rs = RadioSetting("cwstone_sgn", "CW sidetone volume Linked",
+ RadioSettingValueBoolean(_settings.cwstone_sgn))
+ rs.set_doc("If set; volume is relative to AF Gain knob.")
+ cw.append(rs)
+
+ rs = RadioSetting("cwstone_lnk", "CW sidetone linked volume",
+ RadioSettingValueInteger(-50, 50,
+ _settings.cwstone_lnk))
+ cw.append(rs)
+
+ rs = RadioSetting("cwstone_fix", "CW sidetone fixed volume",
+ RadioSettingValueInteger(0, 100,
+ _settings.cwstone_fix))
+ cw.append(rs)
+
+ options = [ "Numeric", "Alpha", "Mixed"]
+ rs = RadioSetting("cwtrain", "CW Training mode",
+ RadioSettingValueList(options,
+ options[_settings.cwtrain]))
+ cw.append(rs)
+
+ rs = RadioSetting("cw_auto", "CW key jack- auto CW mode",
+ RadioSettingValueBoolean(_settings.cw_auto))
+ rs.set_doc("Enable for CW mode auto-set when keyer pluuged in.")
+ cw.append(rs)
+
+ options = ["Normal", "Reverse"]
+ rs = RadioSetting("cw_key", "CW paddle wiring",
+ RadioSettingValueList(options,
+ options[_settings.cw_key]))
+ cw.append(rs)
+
+ rs = RadioSetting("beacon_time", "CW beacon Tx interval (secs)",
+ RadioSettingValueInteger(0, 255,
+ _settings.beacon_time))
+ cw.append(rs)
+
+ tmp = self._chars2str(_beacon.t1, 40)
+ rs=RadioSetting("t1", "CW Beacon Line 1",
+ RadioSettingValueString(0, 40, tmp))
+ rs.set_apply_callback(self._my_str2ary, _beacon, "t1", 40)
+ cw.append(rs)
+
+ tmp = self._chars2str(_beacon.t2, 40)
+ rs=RadioSetting("t2", "CW Beacon Line 2",
+ RadioSettingValueString(0, 40, tmp))
+ rs.set_apply_callback(self._my_str2ary, _beacon, "t2", 40)
+ cw.append(rs)
+
+ tmp = self._chars2str(_beacon.t3, 40)
+ rs=RadioSetting("t3", "CW Beacon Line 3",
+ RadioSettingValueString(0, 40, tmp))
+ rs.set_apply_callback(self._my_str2ary, _beacon, "t3", 40)
+ cw.append(rs) # END _do_cw_settings
+
+
+ def _do_panel_settings(self, pnlset): # - - - Panel settings
+ _settings = self._memobj.settings
+
+ bx = not _settings.amfmdial # Convert from Enable=0
+ rs = RadioSetting("amfmdial", "AM&FM Dial",
+ RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "amfmdial")
+ pnlset.append(rs)
+
+ options = ["440Hz", "880Hz", "1760Hz"]
+ rs = RadioSetting("beepton", "Beep frequency",
+ RadioSettingValueList(options,
+ options[_settings.beepton]))
+ pnlset.append(rs)
+
+ rs = RadioSetting("beepvol_sgn", "Beep volume Linked",
+ RadioSettingValueBoolean(_settings.beepvol_sgn))
+ rs.set_doc("If set; volume is relative to AF Gain knob.")
+ pnlset.append(rs)
+
+ rs = RadioSetting("beepvol_lnk", "Linked beep volume",
+ RadioSettingValueInteger(-50, 50,
+ _settings.beepvol_lnk))
+ rs.set_doc("Relative to AF-Gain setting.")
+ pnlset.append(rs)
+
+ rs = RadioSetting("beepvol_fix", "Fixed beep volume",
+ RadioSettingValueInteger(0, 100,
+ _settings.beepvol_fix))
+ rs.set_doc("When Linked setting is unchecked.")
+ pnlset.append(rs)
+
+ rs = RadioSetting("cont", "LCD Contrast",
+ RadioSettingValueInteger(1, 24, _settings.cont ))
+ rs.set_doc("This setting does not appear to do anything...")
+ pnlset.append(rs)
+
+ rs = RadioSetting("dimmer", "LCD Dimmer",
+ RadioSettingValueInteger(1, 8, _settings.dimmer ))
+ pnlset.append(rs)
+
+ options = ["RF-Gain", "Squelch"]
+ rs = RadioSetting("sql_rfg", "Squelch/RF-Gain",
+ RadioSettingValueList(options,
+ options[_settings.sql_rfg]))
+ pnlset.append(rs)
+
+ options = ["Frequencies", "Panel", "All"]
+ rs = RadioSetting("lockmod", "Lock Mode",
+ RadioSettingValueList(options,
+ options[_settings.lockmod]))
+ pnlset.append(rs)
+
+ options = ["Dial", "SEL"]
+ rs = RadioSetting("clar_btn", "CLAR button control",
+ RadioSettingValueList(options,
+ options[_settings.clar_btn]))
+ pnlset.append(rs)
+
+ if _settings.dialstp_mode == 0: # AM/FM
+ options = ["SSB/CW:1Hz", "SSB/CW:10Hz", "SSB/CW:20Hz"]
+ else:
+ options = ["AM/FM:100Hz", "AM/FM:200Hz"]
+ rs = RadioSetting("dialstp", "Dial tuning step",
+ RadioSettingValueList(options,
+ options[_settings.dialstp]))
+ pnlset.append(rs)
+
+ options = ["0.5secs", "1.0secs", "1.5secs", "2.0secs"]
+ rs = RadioSetting("keyhold", "Buttons hold-to-activate time",
+ RadioSettingValueList(options,
+ options[_settings.keyhold]))
+ pnlset.append(rs)
+
+ rs = RadioSetting("m_tune", "Memory tune",
+ RadioSettingValueBoolean(_settings.m_tune))
+ pnlset.append(rs)
+
+ rs = RadioSetting("peakhold", "S-Meter display hold (1sec)",
+ RadioSettingValueBoolean(_settings.peakhold))
+ pnlset.append(rs)
+
+ options = ["CW Sidetone", "CW Speed", "100KHz step", "1MHz Step",
+ "Mic Gain", "RF Power"]
+ rs = RadioSetting("seldial", "SEL dial 2nd function (push)",
+ RadioSettingValueList(options,
+ options[_settings.seldial]))
+ pnlset.append(rs)
+ # End _do_panel_settings
+
+ def _do_panel_buttons(self, pnlcfg): #- - - Current Panel Config
+ _settings = self._memobj.settings
+
+ rs = RadioSetting("pnl_cs", "C.S. Function",
+ RadioSettingValueList(self.FUNC_LIST,
+ self.FUNC_LIST[_settings.pnl_cs]))
+ pnlcfg.append(rs)
+
+ rs = RadioSetting("nb", "Noise blanker",
+ RadioSettingValueBoolean(_settings.nb))
+ pnlcfg.append(rs)
+
+ options = ["Auto", "Fast", "Slow", "Auto/Fast", "Auto/Slow", "?5?"]
+ rs = RadioSetting("agc", "AGC",
+ RadioSettingValueList(options,
+ options[_settings.agc]))
+ pnlcfg.append(rs)
+
+ rs = RadioSetting("keyer", "Keyer",
+ RadioSettingValueBoolean(_settings.keyer))
+ pnlcfg.append(rs)
+
+ rs = RadioSetting("fast", "Fast step",
+ RadioSettingValueBoolean(_settings.fast))
+ pnlcfg.append(rs)
+
+ rs = RadioSetting("lock", "Lock (per Lock Mode)",
+ RadioSettingValueBoolean(_settings.lock))
+ pnlcfg.append(rs)
+
+ options = ["PO", "ALC", "SWR"]
+ rs = RadioSetting("mtr_mode", "S-Meter mode",
+ RadioSettingValueList(options,
+ options[_settings.mtr_mode]))
+ pnlcfg.append(rs)
+ # End _do_panel_Buttons
+
+ def _do_vox_settings(self, voxdat): # - - VOX and DATA Settings
+ _settings = self._memobj.settings
+
+ rs = RadioSetting("vox_dly", "VOX delay (x 100 ms)",
+ RadioSettingValueInteger(1, 30, _settings.vox_dly))
+ voxdat.append(rs)
+
+ rs = RadioSetting("vox_gain", "VOX Gain",
+ RadioSettingValueInteger(0, 100,
+ _settings.vox_gain))
+ voxdat.append(rs)
+
+ rs = RadioSetting("dig_vox", "Digital VOX Gain",
+ RadioSettingValueInteger(0, 100,
+ _settings.dig_vox))
+ voxdat.append(rs)
+
+ rs = RadioSetting("d_disp", "User-L/U freq offset (Hz)",
+ RadioSettingValueInteger(-3000, 30000,
+ _settings.d_disp, 10))
+ voxdat.append(rs)
+
+ options = ["170Hz", "200Hz", "425Hz", "850Hz"]
+ rs = RadioSetting("rty_sft", "RTTY FSK Freq Shift",
+ RadioSettingValueList(options,
+ options[_settings.rty_sft]))
+ voxdat.append(rs)
+
+ options = ["1275Hz", "2125Hz"]
+ rs = RadioSetting("rty_ton", "RTTY FSK Mark tone",
+ RadioSettingValueList(options,
+ options[_settings.rty_ton]))
+ voxdat.append(rs)
+
+ options = ["Normal", "Reverse"]
+ rs = RadioSetting("rtyrpol", "RTTY Mark/Space RX polarity",
+ RadioSettingValueList(options,
+ options[_settings.rtyrpol]))
+ voxdat.append(rs)
+
+ rs = RadioSetting("rtytpol", "RTTY Mark/Space TX polarity",
+ RadioSettingValueList(options,
+ options[_settings.rtytpol]))
+ voxdat.append(rs)
+ # End _do_vox_settings
+
+ def _do_mic_settings(self, mic): # - - MIC Settings
+ _settings = self._memobj.settings
+
+ rs = RadioSetting("mic_eq", "Mic Equalizer",
+ RadioSettingValueInteger(0, 9, _settings.mic_eq))
+ mic.append(rs)
+
+ options = ["Low", "Normal", "High"]
+ rs = RadioSetting("micgain", "Mic Gain",
+ RadioSettingValueList(options,
+ options[_settings.micgain]))
+ mic.append(rs)
+
+ rs = RadioSetting("micscan", "Mic scan enabled",
+ RadioSettingValueBoolean(_settings.micscan))
+ rs.set_doc("Enables channel scanning via mic up/down buttons.")
+ mic.append(rs)
+
+ rs = RadioSetting("pm_dwn", "Mic Down button function",
+ RadioSettingValueList(self.FUNC_LIST,
+ self.FUNC_LIST[_settings.pm_dwn]))
+ mic.append(rs)
+
+ rs = RadioSetting("pm_fst", "Mic Fast button function",
+ RadioSettingValueList(self.FUNC_LIST,
+ self.FUNC_LIST[_settings.pm_fst]))
+ mic.append(rs)
+
+ rs = RadioSetting("pm_up", "Mic Up button function",
+ RadioSettingValueList(self.FUNC_LIST,
+ self.FUNC_LIST[_settings.pm_up]))
+ mic.append(rs)
+ # End _do_mic_settings
+
+ def _do_mymodes_settings(self, mymodes): # - - MYMODES
+ _settings = self._memobj.settings # Inverted Logic requires callback
+
+ bx = not _settings.mym_lsb
+ rs = RadioSetting("mym_lsb", "LSB", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "mym_lsb")
+ mymodes.append(rs)
+
+ bx = not _settings.mym_usb
+ rs = RadioSetting("mym_usb", "USB", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "mym_usb")
+ mymodes.append(rs)
+
+ bx = not _settings.mym_cw
+ rs = RadioSetting("mym_cw", "CW", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "mym_cw")
+ mymodes.append(rs)
+
+ bx = not _settings.mym_am
+ rs = RadioSetting("mym_am", "AM", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "mym_am")
+ mymodes.append(rs)
+
+ bx = not _settings.mym_fm
+ rs = RadioSetting("mym_fm", "FM", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "mym_fm")
+ mymodes.append(rs)
+
+ bx = not _settings.mym_data
+ rs = RadioSetting("mym_data", "DATA", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "mym_data")
+ mymodes.append(rs)
+ # End _do_mymodes_settings
+
+ def _do_mybands_settings(self, mybands): # - - MYBANDS Settings
+ _settings = self._memobj.settings # Inverted Logic requires callback
+
+ bx = not _settings.myb_1_8
+ rs = RadioSetting("myb_1_8", "1.8 MHz", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "myb_1_8")
+ mybands.append(rs)
+
+ bx = not _settings.myb_3_5
+ rs = RadioSetting("myb_3_5", "3.5 MHz", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "myb_3_5")
+ mybands.append(rs)
+
+ bx = not _settings.myb_7
+ rs = RadioSetting("myb_7", "7 MHz", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "myb_7")
+ mybands.append(rs)
+
+ bx = not _settings.myb_10
+ rs = RadioSetting("myb_10", "10 MHz", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "myb_10")
+ mybands.append(rs)
+
+ bx = not _settings.myb_14
+ rs = RadioSetting("myb_14", "14 MHz", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "myb_14")
+ mybands.append(rs)
+
+ bx = not _settings.myb_18
+ rs = RadioSetting("myb_18", "18 MHz", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "myb_18")
+ mybands.append(rs)
+
+ bx = not _settings.myb_21
+ rs = RadioSetting("myb_21", "21 MHz", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "myb_21")
+ mybands.append(rs)
+
+ bx = not _settings.myb_24
+ rs = RadioSetting("myb_24", "24 MHz", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "myb_24")
+ mybands.append(rs)
+
+ bx = not _settings.myb_28
+ rs = RadioSetting("myb_28", "28 MHz", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "myb_28")
+ mybands.append(rs)
+
+ bx = not _settings.myb_50
+ rs = RadioSetting("myb_50", "50 MHz", RadioSettingValueBoolean(bx))
+ rs.set_apply_callback(self._invert_me, _settings, "myb_50")
+ mybands.append(rs)
+ # End _do_mybands_settings
+
+ def set_settings(self, settings):
+ _settings = self._memobj.settings
+ _mem = self._memobj
+ for element in settings:
+ if not isinstance(element, RadioSetting):
+ self.set_settings(element)
+ continue
+ else:
+ try:
+ name = element.get_name()
+ if "." in name:
+ bits = name.split(".")
+ obj = self._memobj
+ for bit in bits[: -1]:
+ if "/" in bit:
+ bit, index = bit.split("/", 1)
+ index = int(index)
+ obj = getattr(obj, bit)[index]
+ else:
+ obj = getattr(obj, bit)
+ setting = bits[-1]
+ else:
+ obj = _settings
+ setting = element.get_name()
+
+ if element.has_apply_callback():
+ LOG.debug("Using apply callback")
+ element.run_apply_callback()
+ elif element.value.get_mutable():
+ LOG.debug("Setting %s = %s" % (setting, element.value))
+ setattr(obj, setting, element.value)
+ except Exception, e:
+ LOG.debug(element.get_name())
+ raise
diff --git a/chirp/drivers/ft70.py b/chirp/drivers/ft70.py new file mode 100644 index 0000000..20d1000 --- /dev/null +++ b/chirp/drivers/ft70.py @@ -0,0 +1,1191 @@ +# Copyright 2010 Dan Smith <dsmith@danplanet.com>
+# Copyright 2017 Nicolas Pike <nick@zbm2.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.drivers import yaesu_clone
+from chirp import chirp_common, directory, bitwise
+from chirp.settings import RadioSettingGroup, RadioSetting, RadioSettings, \
+ RadioSettingValueInteger, RadioSettingValueString, \
+ RadioSettingValueList, RadioSettingValueBoolean, \
+ InvalidValueError
+from textwrap import dedent
+import string
+LOG = logging.getLogger(__name__)
+
+# Testing
+
+# 37 PAG.ABK Turn the pager answer back Function ON/OFF
+# 38 PAG.CDR Specify a personal code (receive)
+# 39 PAG.CDT Specify a personal code (transmit)
+# 47 RX.MOD Select the receive mode. Auto FM AM
+
+MEM_SETTINGS_FORMAT = """
+
+// FT-70DE New Model #5329
+//
+// Communications Mode ? AMS,FM DN,DW TX vs RX?
+// Mode not currently correctly stored in memories ? - ALL show as FM in memories
+// SKIP test/where stored
+// Check storage of steps
+// Pager settings ?
+// Triple check/ understand _memsize and _block_lengths
+// Bank name label name size display 6 store 16? padded with 0xFF same for MYCALL and message
+// CHIRP mode DIG not supported - is there a CHIRP Fusion mode? Auto?
+// Check character set
+// Supported Modes ?
+// Supported Bands ?
+// rf.has_dtcs_polarity = False - think radio supports DTCS polarity
+// rf.memory_bounds = (1, 900) - should this be 0? as zero displays as blank
+// RPT offsets (stored per band) not included.
+// 59 Display radio firmware version info and Radio ID?
+// Front Panel settings power etc?
+// Banks and VFO?
+
+// Features Required
+// Default AMS and Memory name (in mem extras) to enabled.
+
+// Bugs
+// MYCALL and Opening Message errors if not 10 characters
+// Values greater than one sometimes stored as whole bytes, these need to be refactored into bit fields
+// to prevent accidental overwriting of adjacent values
+// Bank Name length not checked on gui input - but first 6 characters are saved correctly.
+// Extended characters entered as bank names on radio are corrupted in Chirp
+
+// Missing
+// 50 SCV.WTH Set the VFO scan frequency range. BAND / ALL - NOT FOUND
+// 49 SCM.WTH Set the memory scan frequency range. ALL / BAND - NOT FOUND
+
+// Radio Questions
+// Temp unit C/F not saved by radio, always goes back to C ?
+// 44 RF SQL Adjusts the RF Squelch threshold level. OFF / S1 - S9? Default is OFF - Based on RF strength - for AM? How
+// is this different from F, Monitor, Dial Squelch?
+// Password setting on radio allows letters (DTMF), but letters cannot be entered at the radio's password prompt?
+// 49 SCM.WTH Set the memory scan frequency range. ALL / BAND Defaults to ALL Not Band as stated in the manual.
+
+ #seekto 0x049a;
+ struct {
+ u8 unknown0:4,
+ squelch:4; // Squelch F, Monitor, Dial Adjust the Squelch level
+ } squelch_settings;
+
+ #seekto 0x04ba;
+ struct {
+ u8 unknown:3,
+ scan_resume:5; // 52 SCN.RSM Configure the scan stop mode settings. 2.0 S - 5.0 S - 10.0 S / BUSY / HOLD
+ u8 unknown1:3,
+ dw_resume_interval:5; // 22 DW RSM Configure the scan stop mode settings for Dual Receive. 2.0S-10.0S/BUSY/HOLD
+ u8 unknown2;
+ u8 unknown3:3,
+ apo:5; // 02 APO Set the length of time until the transceiver turns off automatically.
+ u8 unknown4:6,
+ gm_ring:2; // 24 GM RNG Select the beep option while receiving digital GM info. OFF/IN RNG/ALWAYS
+ u8 temp_cf; // Placeholder as not found
+ u8 unknown5;
+ } first_settings;
+
+ #seekto 0x04ed;
+ struct {
+ u8 unknown1:1,
+ unknown2:1,
+ unknown3:1,
+ unknown4:1,
+ unknown5:1,
+ unknown6:1,
+ unknown7:1,
+ unknown8:1;
+ } test_bit_field;
+
+ #seekto 0x04c0;
+ struct {
+ u8 unknown1:5,
+ beep_level:3; // 05 BEP.LVL Beep volume setting LEVEL1 - LEVEL4 - LEVEL7
+ u8 unknown2:6,
+ beep_select:2; // 04 BEEP Sets the beep sound function OFF / KEY+SC / KEY
+ } beep_settings;
+
+ #seekto 0x04ce;
+ struct {
+ u8 lcd_dimmer; // 14 DIMMER LCD Dimmer
+ u8 dtmf_delay; // 18 DT DLY DTMF delay
+ u8 unknown0[3];
+ u8 unknown1:4,
+ unknown1:4;
+ u8 lamp; // 28 LAMP Set the duration time of the backlight and keys to be lit
+ u8 lock; // 30 LOCK Configure the lock mode setting. KEY/DIAL/K+D/PTT/K+P/D+P/ALL
+ u8 unknown2_1;
+ u8 mic_gain; // 31 MCGAIN Adjust the microphone gain level
+ u8 unknown2_3;
+ u8 dw_interval; // 21 DW INT Set the priority memory ch mon int during Dual RX 0.1S-5.0S-10.0S
+ u8 ptt_delay; // 42 PTT.DLY Set the PTT delay time. OFF / 20 MS / 50 MS / 100 MS / 200 MS
+ u8 rx_save; // 48 RX.SAVE Set the battery save time. OFF / 0.2 S - 60.0 S
+ u8 scan_restart; // 53 SCN.STR Set the scanning restart time. 0.1 S - 2.0 S - 10.0 S
+ u8 unknown2_5;
+ u8 unknown2_6;
+ u8 unknown4[5];
+ u8 tot; // 56 TOT Set the transmission timeout timer
+ u8 unknown5[3]; // 26
+ u8 vfo_mode:1, // 60 VFO.MOD Set freq setting range in the VFO mode by DIAL knob. ALL / BAND
+ unknown7:1,
+ scan_lamp:1, // 51 SCN.LMP Set the scan lamp ON or OFF when scanning stops On/Off
+ unknown8:1,
+ ars:1, // 45 RPT.ARS Turn the ARS function on/off.
+ dtmf_speed:1, // 20 DT SPD Set DTMF speed
+ unknown8:1,
+ dtmf_mode:1; // DTMF Mode set from front panel
+ u8 busy_led:1, // Not Supported ?
+ unknown8_2:1,
+ unknown8_3:1,
+ bclo:1, // 03 BCLO Turns the busy channel lockout function on/off.
+ beep_edge:1, // 06 BEP.Edg Sets the beep sound ON or OFF when a band edge is encountered.
+ unknown8_6:1,
+ unknown8_7:1,
+ unknown8_8:1; // 28
+ u8 unknown9_1:1,
+ unknown9_2:1,
+ unknown9_3:1,
+ unknown9_4:1,
+ unknown9_5:1,
+ password:1, // Placeholder location
+ home_rev:1, // 26 HOME/REV Select the function of the [HOME/REV] key.
+ moni:1; // 32 Mon/T-Call Select the function of the [MONI/T-CALL] switch.
+ u8 gm_interval:4, // 30 // 25 GM INT Set tx interval of digital GM information. OFF / NORMAL / LONG
+ unknown10:4;
+ u8 unknown11;
+ u8 unknown12:1,
+ unknown12_2:1,
+ unknown12_3:1,
+ unknown12_4:1,
+ home_vfo:1, // 27 HOME->VFO Turn transfer VFO to the Home channel ON or OFF.
+ unknown12_6:1,
+ unknown12_7:1,
+ dw_rt:1; // 32 // 23 DW RVT Turn "Priority Channel Revert" feature ON or OFF during Dual Rx.
+ u8 unknown33;
+ u8 unknown34;
+ u8 unknown35;
+ u8 unknown36;
+ u8 unknown37;
+ u8 unknown38;
+ u8 unknown39;
+ u8 unknown40;
+ u8 unknown41;
+ u8 unknown42;
+ u8 unknown43;
+ u8 unknown44;
+ u8 unknown45;
+ u8 prog_key1; // P1 Set Mode Items to the Programmable Key
+ u8 prog_key2; // P2 Set Mode Items to the Programmable Key
+ u8 unknown48;
+ u8 unknown49;
+ u8 unknown50;
+ } scan_settings;
+
+ #seekto 0x064b;
+ struct {
+ u8 unknown1:1,
+ unknown2:1,
+ unknown3:1,
+ unknown4:1,
+ vfo_scan_width:1, // Placeholder as not found - 50 SCV.WTH Set the VFO scan frequency range. BAND / ALL
+ memory_scan_width:1, // Placeholder as not found - 49 SCM.WTH Set the memory scan frequency range. ALL / BAND
+ unknown7:1,
+ unknown8:1;
+ } scan_settings_1;
+
+ #seekto 0x06B6;
+ struct {
+ u8 unknown1:3,
+ volume:5; // # VOL and Dial Adjust the volume level
+ } scan_settings_2;
+
+ #seekto 0x0690; // Memory or VFO Settings Map?
+ struct {
+ u8 unknown[48]; // Array cannot be 64 elements!
+ u8 unknown1[16]; // Exception: Not implemented for chirp.bitwise.structDataElement
+ } vfo_info_1;
+
+ #seekto 0x0710; // Backup Memory or VFO Settings Map?
+ struct {
+ u8 unknown[48];
+ u8 unknown1[16];
+ } vfo_backup_info_1;
+
+ #seekto 0x047e;
+ struct {
+ u8 unknown1;
+ u8 flag;
+ u16 unknown2;
+ struct {
+ char padded_string[6]; // 36 OPN.MSG Select MSG then key vm to edit it
+ } message;
+ } opening_message; // 36 OPN.MSG Select the Opening Message when transceiver is ON. OFF/MSG/DC
+
+ #seekto 0x094a; // DTMF Memories
+ struct {
+ u8 memory[16];
+ } dtmf[10];
+
+ #seekto 0x154a;
+ struct {
+ u16 channel[100];
+ } bank_members[24];
+
+ #seekto 0x54a;
+ struct {
+ u16 in_use;
+ } bank_used[24];
+
+ #seekto 0x0EFE;
+ struct {
+ u8 unknown[2];
+ u8 name[6];
+ u8 unknown1[10];
+ } bank_info[24];
+
+ #seekto 0xCF30;
+ struct {
+ u8 unknown0;
+ u8 unknown1;
+ u8 unknown2;
+ u8 unknown3;
+ u8 unknown4;
+ u8 unknown5;
+ u8 unknown6;
+ u8 digital_popup; // 15 DIG.POP Call sign display pop up time
+ } digital_settings_more;
+
+ #seekto 0xCF7C;
+ struct {
+ u8 unknown0:6,
+ ams_tx_mode:2; // AMS TX Mode Short Press AMS button AMS TX Mode
+ u8 unknown1;
+ u8 unknown2:7,
+ standby_beep:1; // 07 BEP.STB Standby Beep in the digital C4FM mode. On/Off
+ u8 unknown3;
+ u8 unknown4:6,
+ gm_ring:2; // 24 GM RNG Select beep option while rx digital GM info. OFF/IN RNG/ALWAYS
+ u8 unknown5;
+ u8 rx_dg_id; // RX DG-ID Long Press Mode Key, Mode Key to select, Dial
+ u8 tx_dg_id; // TX DG-ID Long Press Mode Key, Dial
+ u8 unknown6:7,
+ vw_mode:1; // 16 DIG VW Turn the VW mode selection ON or OFF
+ u8 unknown7;
+ } digital_settings;
+
+ // ^^^ All above referenced U8's have been refactored to minimum number of bits.
+
+ """
+
+MEM_FORMAT = """
+ #seekto 0x2D4A;
+ struct { // 32 Bytes per memory entry
+ u8 display_tag:1, // 0 Display Freq, 1 Display Name
+ unknown0:1, // Mode if AMS not selected????????
+ deviation:1, // 0 Full deviation (Wide), 1 Half deviation (Narrow)
+ clock_shift:1, // 0 None, 1 CPU clock shifted
+ unknown1:4; // 1
+ u8 mode:2, // FM,AM,WFM only? - check
+ duplex:2, // Works
+ tune_step:4; // Works - check all steps? 7 = Auto // 1
+ bbcd freq[3]; // Works // 3
+ u8 power:2, // Works
+ unknown2:1, // 0 FM, 1 Digital - If AMS off
+ ams:1, // 0 AMS off, 1 AMS on ?
+ tone_mode:4; // Works // 1
+ u8 charsetbits[2]; // 2
+ char label[6]; // Works - Can only input 6 on screen // 6
+ char unknown7[10]; // Rest of label ??? // 10
+ bbcd offset[3]; // Works // 3
+ u8 unknown5:2,
+ tone:6; // Works // 1
+ u8 unknown6:1,
+ dcs:7; // Works // 1
+ u8 unknown9;
+ u8 ams_on_dn_vw_fm:2, // AMS DN, AMS VW, AMS FM
+ unknown8_3:1,
+ unknown8_4:1,
+ unknown8_5:1,
+ unknown8_6:1,
+ unknown8_7:1,
+ unknown8_8:1;
+ u8 unknown10;
+ } memory[%d]; // DN, VW, FM, AM
+ // AMS DN, AMS VW, AMS FM
+
+ #seekto 0x280A;
+ struct {
+ u8 nosubvfo:1,
+ unknown:3,
+ pskip:1, // PSkip (Select?)
+ skip:1, // Skip memory during scan
+ used:1, // Memory used
+ valid:1; // Aways 1?
+ } flag[%d];
+ """
+
+MEM_CALLSIGN_FORMAT = """
+#seekto 0x0ced0;
+ struct {
+ char callsign[10]; // 63 MYCALL Set the call sign. (up to 10 characters)
+ u16 charset; // character set ID
+ } my_call;
+ """
+
+MEM_CHECKSUM_FORMAT = """
+ #seekto 0xFECA;
+ u8 checksum;
+ """
+
+TMODES = ["", "Tone", "TSQL", "DTCS"]
+DUPLEX = ["", "-", "+", "split"]
+
+MODES = ["FM", "AM"]
+
+STEPS = [0, 5, 6.25, 10, 12.5, 15, 20, 25, 50, 100] # 0 = auto
+RFSQUELCH = ["OFF", "S1", "S2", "S3", "S4", "S5", "S6", "S7", "S8"]
+
+SKIPS = ["", "S", "P"]
+FT70_DTMF_CHARS = list("0123456789ABCDEF-")
+
+CHARSET = ["%i" % int(x) for x in range(0, 10)] + \
+ [chr(x) for x in range(ord("A"), ord("Z") + 1)] + \
+ [" ", ] + \
+ [chr(x) for x in range(ord("a"), ord("z") + 1)] + \
+ list(".,:;*#_-/&()@!?^ ") + list("\x00" * 100)
+
+POWER_LEVELS = [chirp_common.PowerLevel("Hi", watts=5.00),
+ chirp_common.PowerLevel("Mid", watts=2.00),
+ chirp_common.PowerLevel("Low", watts=.50)]
+
+
+class FT70Bank(chirp_common.NamedBank):
+ """A FT70 bank"""
+
+ def get_name(self):
+ _bank = self._model._radio._memobj.bank_info[self.index]
+ name = ""
+ for i in _bank.name:
+ if i == 0xff:
+ break
+ name += chr(i & 0xFF)
+ return name.rstrip()
+
+ def set_name(self, name):
+ _bank = self._model._radio._memobj.bank_info[self.index]
+ _bank.name = [ord(x) for x in name.ljust(6, chr(0xFF))[:6]]
+
+
+class FT70BankModel(chirp_common.BankModel):
+ """A FT70 bank model"""
+
+ def __init__(self, radio, name='Banks'):
+ super(FT70BankModel, self).__init__(radio, name)
+
+ _banks = self._radio._memobj.bank_info
+ self._bank_mappings = []
+ for index, _bank in enumerate(_banks):
+ bank = FT70Bank(self, "%i" % index, "BANK-%i" % index)
+ bank.index = index
+ self._bank_mappings.append(bank)
+
+ def get_num_mappings(self):
+ return len(self._bank_mappings)
+
+ def get_mappings(self):
+ return self._bank_mappings
+
+ def _channel_numbers_in_bank(self, bank):
+ _bank_used = self._radio._memobj.bank_used[bank.index]
+ if _bank_used.in_use == 0xFFFF:
+ return set()
+
+ _members = self._radio._memobj.bank_members[bank.index]
+ return set([int(ch) + 1 for ch in _members.channel if ch != 0xFFFF])
+
+ def _update_bank_with_channel_numbers(self, bank, channels_in_bank):
+ _members = self._radio._memobj.bank_members[bank.index]
+ if len(channels_in_bank) > len(_members.channel):
+ raise Exception("Too many entries in bank %d" % bank.index)
+
+ empty = 0
+ for index, channel_number in enumerate(sorted(channels_in_bank)):
+ _members.channel[index] = channel_number - 1
+ empty = index + 1
+ for index in range(empty, len(_members.channel)):
+ _members.channel[index] = 0xFFFF
+
+ def add_memory_to_mapping(self, memory, bank):
+ channels_in_bank = self._channel_numbers_in_bank(bank)
+ channels_in_bank.add(memory.number)
+ self._update_bank_with_channel_numbers(bank, channels_in_bank)
+
+ _bank_used = self._radio._memobj.bank_used[bank.index]
+ _bank_used.in_use = 0x06
+
+ def remove_memory_from_mapping(self, memory, bank):
+ channels_in_bank = self._channel_numbers_in_bank(bank)
+ try:
+ channels_in_bank.remove(memory.number)
+ except KeyError:
+ raise Exception("Memory %i is not in bank %s. Cannot remove" %
+ (memory.number, bank))
+ self._update_bank_with_channel_numbers(bank, channels_in_bank)
+
+ if not channels_in_bank:
+ _bank_used = self._radio._memobj.bank_used[bank.index]
+ _bank_used.in_use = 0xFFFF
+
+ def get_mapping_memories(self, bank):
+ memories = []
+ for channel in self._channel_numbers_in_bank(bank):
+ memories.append(self._radio.get_memory(channel))
+
+ return memories
+
+ def get_memory_mappings(self, memory):
+ banks = []
+ for bank in self.get_mappings():
+ if memory.number in self._channel_numbers_in_bank(bank):
+ banks.append(bank)
+
+ return banks
+
+
+@directory.register
+class FT70Radio(yaesu_clone.YaesuCloneModeRadio):
+ """Yaesu FT-70DE"""
+ BAUD_RATE = 38400
+ VENDOR = "Yaesu"
+ MODEL = "FT-70D"
+
+ _model = "AH51G"
+
+ _memsize = 65227 # 65227 read from dump
+ _block_lengths = [10, 65217]
+ _block_size = 32
+ _mem_params = (900, # size of memories array
+ 900, # size of flags array
+ )
+
+ _has_vibrate = False
+ _has_af_dual = True
+
+ _BEEP_SELECT = ("Off", "Key+Scan", "Key")
+ _OPENING_MESSAGE = ("Off", "DC", "Message")
+ _MIC_GAIN = ("Level 1", "Level 2", "Level 3", "Level 4", "Level 5", "Level 6", "Level 7", "Level 8", "Level 9")
+ _AMS_TX_MODE = ("TX Auto", "TX DIGITAL", "TX FM")
+ _VW_MODE = ("On", "Off")
+ _DIG_POP_UP = ("Off", "2sec", "4sec", "6sec", "8sec", "10sec", "20sec", "30sec", "60sec", "Continuous")
+ _STANDBY_BEEP = ("On", "Off")
+ _SCAN_RESUME = ["%.1fs" % (0.5 * x) for x in range(4, 21)] + \
+ ["Busy", "Hold"]
+ _SCAN_RESTART = ["%.1fs" % (0.1 * x) for x in range(1, 10)] + \
+ ["%.1fs" % (0.5 * x) for x in range(2, 21)]
+ _LAMP_KEY = ["Key %d sec" % x
+ for x in range(2, 11)] + ["Continuous", "OFF"]
+ _LCD_DIMMER = ["Level %d" % x for x in range(1, 7)]
+ _TOT_TIME = ["Off"] + ["%.1f min" % (0.5 * x) for x in range(1, 21)]
+ _OFF_ON = ("Off", "On")
+ _ON_OFF = ("On", "Off")
+ _DTMF_MODE = ("Manual", "Auto")
+ _DTMF_SPEED = ("50ms", "100ms")
+ _DTMF_DELAY = ("50ms", "250ms", "450ms", "750ms", "1000ms")
+ _TEMP_CF = ("Centigrade", "Fahrenheit")
+ _APO_SELECT = ("Off", "0.5H", "1.0H", "1.5H", "2.0H", "2.5H", "3.0H", "3.5H", "4.0H", "4.5H", "5.0H",
+ "5.5H", "6.0H", "6.5H", "7.0H", "7.5H", "8.0H", "8.5H", "9.0H", "9.5H", "10.0H", "10.5H",
+ "11.0H", "11.5H", "12.0H")
+ _MONI_TCALL = ("Monitor", "Tone-CALL")
+ _HOME_REV = ("Home", "Reverse")
+ _LOCK = ("KEY", "DIAL", "Key+Dial", "PTT", "Key+PTT", "Dial+PTT", "ALL")
+ _PTT_DELAY = ("Off", "20 MS", "50 MS", "100 MS", "200 MS")
+ _BEEP_LEVEL = ("Level 1", "Level 2", "Level 3", "Level 4", "Level 5", "Level 6", "Level 7")
+ _SET_MODE = ("Level 1", "Level 2", "Level 3", "Level 4", "Level 5", "Level 6", "Level 7")
+ _RX_SAVE = ("OFF", "0.2s", ".3s", ".4s", ".5s", ".6s", ".7s", ".8s", ".9s", "1.0s", "1.5s",
+ "2.0s", "2.5s", "3.0s", "3.5s", "4.0s", "4.5s", "5.0s", "5.5s", "6.0s", "6.5s", "7.0s",
+ "7.5s", "8.0s", "8.5s", "9.0s", "10.0s", "15s", "20s", "25s", "30s", "35s", "40s", "45s", "50s", "55s",
+ "60s")
+ _VFO_MODE = ("ALL", "BAND")
+ _VFO_SCAN_MODE = ("BAND", "ALL")
+ _MEMORY_SCAN_MODE = ("BAND", "ALL")
+
+ _VOLUME = ["Level %d" % x for x in range(0, 32)]
+ _SQUELCH = ["Level %d" % x for x in range(0, 16)]
+
+ _DG_ID = ["%d" % x for x in range(0, 100)]
+ _GM_RING = ("OFF", "IN RING", "AlWAYS")
+ _GM_INTERVAL = ("LONG", "NORMAL", "OFF")
+
+ _MYCALL_CHR_SET = list(string.uppercase) + list(string.digits) + ['-','/' ]
+
+ @classmethod
+ def get_prompts(cls):
+ rp = chirp_common.RadioPrompts()
+
+ rp.pre_download = _(dedent("""\
+ 1. Turn radio on.
+ 2. Connect cable to DATA terminal.
+ 3. Unclip battery.
+ 4. Press and hold in the [AMS] key and power key while clipping the battery back in
+ ("ADMS" will appear on the display).
+ 5. <b>After clicking OK</b>, press the [BAND] key."""
+ ))
+ rp.pre_upload = _(dedent("""\
+ 1. Turn radio on.
+ 2. Connect cable to DATA terminal.
+ 3. Unclip battery.
+ 4. Press and hold in the [AMS] key and power key while clipping the battery back in
+ ("ADMS" will appear on the display).
+ 5. Press the [MODE] key ("-WAIT-" will appear on the LCD). <b>Then click OK</b>"""))
+ return rp
+
+ def process_mmap(self):
+
+ mem_format = MEM_SETTINGS_FORMAT + MEM_FORMAT + MEM_CALLSIGN_FORMAT + MEM_CHECKSUM_FORMAT
+
+ self._memobj = bitwise.parse(mem_format % self._mem_params, self._mmap)
+
+ def get_features(self):
+ rf = chirp_common.RadioFeatures()
+ rf.has_dtcs_polarity = False
+ rf.valid_modes = list(MODES)
+ rf.valid_tmodes = list(TMODES)
+ rf.valid_duplexes = list(DUPLEX)
+ rf.valid_tuning_steps = list(STEPS)
+ rf.valid_bands = [(500000, 999900000)]
+ rf.valid_skips = SKIPS
+ rf.valid_power_levels = POWER_LEVELS
+ rf.valid_characters = "".join(CHARSET)
+ rf.valid_name_length = 6
+ rf.memory_bounds = (1, 900)
+ rf.can_odd_split = True
+ rf.has_ctone = False
+ rf.has_bank_names = True
+ rf.has_settings = True
+ return rf
+
+ def get_raw_memory(self, number):
+ return "\n".join([repr(self._memobj.memory[number - 1]),
+ repr(self._memobj.flag[number - 1])])
+
+ def _checksums(self):
+ return [yaesu_clone.YaesuChecksum(0x0000, 0xFEC9)] # The whole file -2 bytes
+
+ @staticmethod
+ def _add_ff_pad(val, length):
+ return val.ljust(length, "\xFF")[:length]
+
+ @classmethod
+ def _strip_ff_pads(cls, messages):
+ result = []
+ for msg_text in messages:
+ result.append(str(msg_text).rstrip("\xFF"))
+ return result
+
+ def get_memory(self, number):
+ flag = self._memobj.flag[number - 1]
+ _mem = self._memobj.memory[number - 1]
+
+ mem = chirp_common.Memory()
+ mem.number = number
+ if not flag.used:
+ mem.empty = True
+ if not flag.valid:
+ mem.empty = True
+ return mem
+ mem.freq = chirp_common.fix_rounded_step(int(_mem.freq) * 1000)
+ mem.offset = int(_mem.offset) * 1000
+ mem.rtone = mem.ctone = chirp_common.TONES[_mem.tone]
+ self._get_tmode(mem, _mem)
+ mem.duplex = DUPLEX[_mem.duplex]
+ if mem.duplex == "split":
+ mem.offset = chirp_common.fix_rounded_step(mem.offset)
+ mem.mode = self._decode_mode(_mem)
+ mem.dtcs = chirp_common.DTCS_CODES[_mem.dcs]
+ mem.tuning_step = STEPS[_mem.tune_step]
+ mem.power = self._decode_power_level(_mem)
+ mem.skip = flag.pskip and "P" or flag.skip and "S" or ""
+ mem.name = self._decode_label(_mem)
+
+ return mem
+
+ def _decode_label(self, mem):
+ return str(mem.label).rstrip("\xFF")
+
+ def _encode_label(self, mem):
+ return self._add_ff_pad(mem.name.rstrip(), 6)
+
+ def _encode_charsetbits(self, mem):
+ # We only speak english here in chirpville
+ return [0x00, 0x00]
+
+ def _decode_power_level(self, mem): # 3 High 2 Mid 1 Low
+ return POWER_LEVELS[3 - mem.power]
+
+ def _encode_power_level(self, mem):
+ return 3 - POWER_LEVELS.index(mem.power)
+
+ def _decode_mode(self, mem):
+ return MODES[mem.mode]
+
+ def _encode_mode(self, mem):
+ return MODES.index(mem.mode)
+
+ def _get_tmode(self, mem, _mem):
+ mem.tmode = TMODES[_mem.tone_mode]
+
+ def _set_tmode(self, _mem, mem):
+ _mem.tone_mode = TMODES.index(mem.tmode)
+
+ def _set_mode(self, _mem, mem):
+ _mem.mode = self._encode_mode(mem)
+
+ def _debank(self, mem):
+ bm = self.get_bank_model()
+ for bank in bm.get_memory_mappings(mem):
+ bm.remove_memory_from_mapping(mem, bank)
+
+ def set_memory(self, mem):
+ _mem = self._memobj.memory[mem.number - 1]
+ flag = self._memobj.flag[mem.number - 1]
+
+ self._debank(mem)
+
+ if not mem.empty and not flag.valid:
+ self._wipe_memory(_mem)
+
+ if mem.empty and flag.valid and not flag.used:
+ flag.valid = False
+ return
+ flag.used = not mem.empty
+ flag.valid = flag.used
+
+ if mem.empty:
+ return
+
+ if mem.freq < 30000000 or \
+ (mem.freq > 88000000 and mem.freq < 108000000) or \
+ mem.freq > 580000000:
+ flag.nosubvfo = True # Masked from VFO B
+ else:
+ flag.nosubvfo = False # Available in both VFOs
+
+ _mem.freq = int(mem.freq / 1000)
+ _mem.offset = int(mem.offset / 1000)
+ _mem.tone = chirp_common.TONES.index(mem.rtone)
+ self._set_tmode(_mem, mem)
+ _mem.duplex = DUPLEX.index(mem.duplex)
+ self._set_mode(_mem, mem)
+ _mem.dcs = chirp_common.DTCS_CODES.index(mem.dtcs)
+ _mem.tune_step = STEPS.index(mem.tuning_step)
+
+ if mem.power:
+ _mem.power = self._encode_power_level(mem)
+ else:
+ _mem.power = 3 # Set 3 - High power as the default
+
+ _mem.label = self._encode_label(mem)
+ charsetbits = self._encode_charsetbits(mem)
+ _mem.charsetbits[0], _mem.charsetbits[1] = charsetbits
+
+ flag.skip = mem.skip == "S"
+ flag.pskip = mem.skip == "P"
+
+ _mem.display_tag = 1 # Always Display Memory Name (For the moment..)
+
+ @classmethod
+ def _wipe_memory(cls, mem):
+ mem.set_raw("\x00" * (mem.size() / 8))
+ mem.unknown1 = 0x05
+
+ def get_bank_model(self):
+ return FT70BankModel(self)
+
+ def _get_dtmf_settings(self):
+ menu = RadioSettingGroup("dtmf_settings", "DTMF")
+ dtmf = self._memobj.scan_settings
+
+ val = RadioSettingValueList(
+ self._DTMF_MODE,
+ self._DTMF_MODE[dtmf.dtmf_mode])
+ rs = RadioSetting("scan_settings.dtmf_mode", "DTMF Mode", val)
+ menu.append(rs)
+
+ val = RadioSettingValueList(
+ self._DTMF_DELAY,
+ self._DTMF_DELAY[dtmf.dtmf_delay])
+ rs = RadioSetting(
+ "scan_settings.dtmf_delay", "DTMF Delay", val)
+ menu.append(rs)
+
+ val = RadioSettingValueList(
+ self._DTMF_SPEED,
+ self._DTMF_SPEED[dtmf.dtmf_speed])
+ rs = RadioSetting(
+ "scan_settings.dtmf_speed", "DTMF Speed", val)
+ menu.append(rs)
+
+ for i in range(10):
+
+ name = "dtmf_%02d" % (i + 1)
+ if i == 9:
+ name = "dtmf_%02d" % 0
+
+ dtmfsetting = self._memobj.dtmf[i]
+ dtmfstr = ""
+ for c in dtmfsetting.memory:
+ if c == 0xFF:
+ break
+ if c < len(FT70_DTMF_CHARS):
+ dtmfstr += FT70_DTMF_CHARS[c]
+ dtmfentry = RadioSettingValueString(0, 16, dtmfstr)
+ dtmfentry.set_charset(
+ FT70_DTMF_CHARS + list("abcdef ")) # Allow input in lowercase, space ? validation fails otherwise
+ rs = RadioSetting(name, name.upper(), dtmfentry)
+ rs.set_apply_callback(self.apply_dtmf, i)
+ menu.append(rs)
+
+ return menu
+
+ def _get_display_settings(self):
+ menu = RadioSettingGroup("display_settings", "Display")
+ scan_settings = self._memobj.scan_settings
+
+ val = RadioSettingValueList(
+ self._LAMP_KEY,
+ self._LAMP_KEY[scan_settings.lamp])
+ rs = RadioSetting("scan_settings.lamp", "Lamp", val)
+ menu.append(rs)
+
+ val = RadioSettingValueList(
+ self._LCD_DIMMER,
+ self._LCD_DIMMER[scan_settings.lcd_dimmer])
+ rs = RadioSetting("scan_settings.lcd_dimmer", "LCD Dimmer", val)
+ menu.append(rs)
+
+ opening_message = self._memobj.opening_message
+ val = RadioSettingValueList(
+ self._OPENING_MESSAGE,
+ self._OPENING_MESSAGE[opening_message.flag])
+ rs = RadioSetting("opening_message.flag", "Opening Msg Mode", val)
+ menu.append(rs)
+
+ return menu
+
+ def _get_config_settings(self):
+ menu = RadioSettingGroup("config_settings", "Config")
+ scan_settings = self._memobj.scan_settings
+
+ # 02 APO Set the length of time until the transceiver turns off automatically.
+
+ first_settings = self._memobj.first_settings
+ val = RadioSettingValueList(
+ self._APO_SELECT,
+ self._APO_SELECT[first_settings.apo])
+ rs = RadioSetting("first_settings.apo", "APO", val)
+ menu.append(rs)
+
+ # 03 BCLO Turns the busy channel lockout function on/off.
+
+ val = RadioSettingValueList(
+ self._OFF_ON,
+ self._OFF_ON[scan_settings.bclo])
+ rs = RadioSetting("scan_settings.bclo", "Busy Channel Lockout", val)
+ menu.append(rs)
+
+ # 04 BEEP Sets the beep sound function.
+
+ beep_settings = self._memobj.beep_settings
+ val = RadioSettingValueList(
+ self._BEEP_SELECT,
+ self._BEEP_SELECT[beep_settings.beep_select])
+ rs = RadioSetting("beep_settings.beep_select", "Beep", val)
+ menu.append(rs)
+
+ # 05 BEP.LVL Beep volume setting LEVEL1 - LEVEL4 - LEVEL7
+
+ val = RadioSettingValueList(
+ self._BEEP_LEVEL,
+ self._BEEP_LEVEL[beep_settings.beep_level])
+ rs = RadioSetting("beep_settings", "Beep Level", val)
+ menu.append(rs)
+
+ # 06 BEP.Edg Sets the beep sound ON or OFF when a band edge is encountered.
+
+ val = RadioSettingValueList(
+ self._OFF_ON,
+ self._OFF_ON[scan_settings.beep_edge])
+ rs = RadioSetting("scan_settings.beep_edge", "Beep Band Edge", val)
+ menu.append(rs)
+
+ # 10 Bsy.LED Turn the MODE/STATUS Indicator ON or OFF while receiving signals.
+
+ val = RadioSettingValueList(
+ self._ON_OFF,
+ self._ON_OFF[scan_settings.busy_led])
+ rs = RadioSetting("scan_settings.busy_led", "Busy LED", val)
+ menu.append(rs)
+
+ # 26 HOME/REV Select the function of the [HOME/REV] key.
+
+ val = RadioSettingValueList(
+ self._HOME_REV,
+ self._HOME_REV[scan_settings.home_rev])
+ rs = RadioSetting("scan_settings.home_rev", "HOME/REV", val)
+ menu.append(rs)
+
+ # 27 HOME->VFO Turn transfer VFO to the Home channel ON or OFF.
+
+ val = RadioSettingValueList(
+ self._OFF_ON,
+ self._OFF_ON[scan_settings.home_vfo])
+ rs = RadioSetting("scan_settings.home_vfo", "Home->VFO", val)
+ menu.append(rs)
+
+ # 30 LOCK Configure the lock mode setting. KEY / DIAL / K+D / PTT / K+P / D+P / ALL
+
+ val = RadioSettingValueList(
+ self._LOCK,
+ self._LOCK[scan_settings.lock])
+ rs = RadioSetting("scan_settings.lock", "Lock Mode", val)
+ menu.append(rs)
+
+ # 32 Mon/T-Call Select the function of the [MONI/T-CALL] switch.
+
+ val = RadioSettingValueList(
+ self._MONI_TCALL,
+ self._MONI_TCALL[scan_settings.moni])
+ rs = RadioSetting("scan_settings.moni", "MONI/T-CALL", val)
+ menu.append(rs)
+
+ # 42 PTT.DLY Set the PTT delay time. OFF / 20 MS / 50 MS / 100 MS / 200 MS
+
+ val = RadioSettingValueList(
+ self._PTT_DELAY,
+ self._PTT_DELAY[scan_settings.ptt_delay])
+ rs = RadioSetting("scan_settings.ptt_delay", "PTT Delay", val)
+ menu.append(rs)
+
+ # 45 RPT.ARS Turn the ARS function on/off.
+
+ val = RadioSettingValueList(
+ self._OFF_ON,
+ self._OFF_ON[scan_settings.ars])
+ rs = RadioSetting("scan_settings.ars", "ARS", val)
+ menu.append(rs)
+
+ # 48 RX.SAVE Set the battery save time. OFF / 0.2 S - 60.0 S
+
+ val = RadioSettingValueList(
+ self._RX_SAVE,
+ self._RX_SAVE[scan_settings.rx_save])
+ rs = RadioSetting("scan_settings.rx_save", "RX SAVE", val)
+ menu.append(rs)
+
+ # 60 VFO.MOD Set the frequency setting range in the VFO mode by DIAL knob. ALL / BAND
+
+ val = RadioSettingValueList(
+ self._VFO_MODE,
+ self._VFO_MODE[scan_settings.vfo_mode])
+ rs = RadioSetting("scan_settings.vfo_mode", "VFO MODE", val)
+ menu.append(rs)
+
+ # 56 TOT Set the timeout timer.
+
+ val = RadioSettingValueList(
+ self._TOT_TIME,
+ self._TOT_TIME[scan_settings.tot])
+ rs = RadioSetting("scan_settings.tot", "Transmit Timeout (TOT)", val)
+ menu.append(rs)
+
+ # 31 MCGAIN Adjust the microphone gain level
+
+ val = RadioSettingValueList(
+ self._MIC_GAIN,
+ self._MIC_GAIN[scan_settings.mic_gain])
+ rs = RadioSetting("scan_settings.mic_gain", "Mic Gain", val)
+ menu.append(rs)
+
+ # VOLUME Adjust the volume level
+
+ scan_settings_2 = self._memobj.scan_settings_2
+ val = RadioSettingValueList(
+ self._VOLUME,
+ self._VOLUME[scan_settings_2.volume])
+ rs = RadioSetting("scan_settings_2.volume", "Volume", val)
+ menu.append(rs)
+
+ # Squelch F key, Hold Monitor, Dial to adjust squelch level
+
+ squelch_settings = self._memobj.squelch_settings
+ val = RadioSettingValueList(
+ self._SQUELCH,
+ self._SQUELCH[squelch_settings.squelch])
+ rs = RadioSetting("squelch_settings.squelch", "Squelch", val)
+ menu.append(rs)
+
+ return menu
+
+ def _get_digital_settings(self):
+ menu = RadioSettingGroup("digital_settings", "Digital")
+
+ # MYCALL
+ mycall = self._memobj.my_call
+ mycallstr = str(mycall.callsign).rstrip("\xFF")
+
+ mycallentry = RadioSettingValueString(0, 10, mycallstr, False, charset=self._MYCALL_CHR_SET)
+ rs = RadioSetting('mycall.callsign', 'MYCALL', mycallentry)
+ rs.set_apply_callback(self.apply_mycall, mycall)
+ menu.append(rs)
+
+ # Short Press AMS button AMS TX Mode
+
+ digital_settings = self._memobj.digital_settings
+ val = RadioSettingValueList(
+ self._AMS_TX_MODE,
+ self._AMS_TX_MODE[digital_settings.ams_tx_mode])
+ rs = RadioSetting("digital_settings.ams_tx_mode", "AMS TX Mode", val)
+ menu.append(rs)
+
+ # 16 DIG VW Turn the VW mode selection ON or OFF.
+
+ val = RadioSettingValueList(
+ self._VW_MODE,
+ self._VW_MODE[digital_settings.vw_mode])
+ rs = RadioSetting("digital_settings.vw_mode", "VW Mode", val)
+ menu.append(rs)
+
+ # TX DG-ID Long Press Mode Key, Dial
+
+ val = RadioSettingValueList(
+ self._DG_ID,
+ self._DG_ID[digital_settings.tx_dg_id])
+ rs = RadioSetting("digital_settings.tx_dg_id", "TX DG-ID", val)
+ menu.append(rs)
+
+ # RX DG-ID Long Press Mode Key, Mode Key to select, Dial
+
+ val = RadioSettingValueList(
+ self._DG_ID,
+ self._DG_ID[digital_settings.rx_dg_id])
+ rs = RadioSetting("digital_settings.rx_dg_id", "RX DG-ID", val)
+ menu.append(rs)
+
+ # 15 DIG.POP Call sign display pop up time
+
+ # 00 OFF 00
+ # 0A 2s 10
+ # 0B 4s 11
+ # 0C 6s 12
+ # 0D 8s 13
+ # 0E 10s 14
+ # 0F 20s 15
+ # 10 30s 16
+ # 11 60s 17
+ # 12 CONT 18
+
+ digital_settings_more = self._memobj.digital_settings_more
+
+ val = RadioSettingValueList(
+ self._DIG_POP_UP,
+ self._DIG_POP_UP[
+ 0 if digital_settings_more.digital_popup == 0 else digital_settings_more.digital_popup - 9])
+
+ rs = RadioSetting("digital_settings_more.digital_popup", "Digital Popup", val)
+ rs.set_apply_callback(self.apply_digital_popup, digital_settings_more)
+ menu.append(rs)
+
+ # 07 BEP.STB Standby Beep in the digital C4FM mode. On/Off
+
+ val = RadioSettingValueList(
+ self._STANDBY_BEEP,
+ self._STANDBY_BEEP[digital_settings.standby_beep])
+ rs = RadioSetting("digital_settings.standby_beep", "Standby Beep", val)
+ menu.append(rs)
+
+ return menu
+
+ def _get_gm_settings(self):
+ menu = RadioSettingGroup("first_settings", "Group Monitor")
+
+ # 24 GM RNG Select the beep option while receiving digital GM information. OFF / IN RNG /ALWAYS
+
+ first_settings = self._memobj.first_settings
+ val = RadioSettingValueList(
+ self._GM_RING,
+ self._GM_RING[first_settings.gm_ring])
+ rs = RadioSetting("first_settings.gm_ring", "GM Ring", val)
+ menu.append(rs)
+
+ # 25 GM INT Set the transmission interval of digital GM information. OFF / NORMAL / LONG
+
+ scan_settings = self._memobj.scan_settings
+ val = RadioSettingValueList(
+ self._GM_INTERVAL,
+ self._GM_INTERVAL[scan_settings.gm_interval])
+ rs = RadioSetting("scan_settings.gm_interval", "GM Interval", val)
+ menu.append(rs)
+
+ return menu
+
+ def _get_scan_settings(self):
+ menu = RadioSettingGroup("scan_settings", "Scan")
+ scan_settings = self._memobj.scan_settings
+
+ # 23 DW RVT Turn the "Priority Channel Revert" feature ON or OFF during Dual Receive.
+
+ val = RadioSettingValueList(
+ self._OFF_ON,
+ self._OFF_ON[scan_settings.dw_rt])
+ rs = RadioSetting("scan_settings.dw_rt", "Dual Watch Priority Channel Revert", val)
+ menu.append(rs)
+
+ # 21 DW INT Set the priority memory channel monitoring interval during Dual Receive. 0.1S - 5.0S - 10.0S
+
+ val = RadioSettingValueList(
+ self._SCAN_RESTART,
+ self._SCAN_RESTART[scan_settings.dw_interval])
+ rs = RadioSetting("scan_settings.dw_interval", "Dual Watch Interval", val)
+ menu.append(rs)
+
+ # 22 DW RSM Configure the scan stop mode settings for Dual Receive. 2.0S - 10.0 S / BUSY / HOLD
+
+ first_settings = self._memobj.first_settings
+ val = RadioSettingValueList(
+ self._SCAN_RESUME,
+ self._SCAN_RESUME[first_settings.dw_resume_interval])
+ rs = RadioSetting("first_settings.dw_resume_interval", "Dual Watch Resume Interval", val)
+ menu.append(rs)
+
+ # 51 SCN.LMP Set the scan lamp ON or OFF when scanning stops. OFF / ON
+
+ val = RadioSettingValueList(
+ self._OFF_ON,
+ self._OFF_ON[scan_settings.scan_lamp])
+ rs = RadioSetting("scan_settings.scan_lamp", "Scan Lamp", val)
+ menu.append(rs)
+
+ # 53 SCN.STR Set the scanning restart time. 0.1 S - 2.0 S - 10.0 S
+
+ val = RadioSettingValueList(
+ self._SCAN_RESTART,
+ self._SCAN_RESTART[scan_settings.scan_restart])
+ rs = RadioSetting("scan_settings.scan_restart", "Scan Restart", val)
+ menu.append(rs)
+
+ # Scan Width Section
+
+ # 50 SCV.WTH Set the VFO scan frequency range. BAND / ALL - NOT FOUND!
+
+ # Scan Resume Section
+
+ # 52 SCN.RSM Configure the scan stop mode settings. 2.0 S - 5.0 S - 10.0 S / BUSY / HOLD
+
+ first_settings = self._memobj.first_settings
+ val = RadioSettingValueList(
+ self._SCAN_RESUME,
+ self._SCAN_RESUME[first_settings.scan_resume])
+ rs = RadioSetting("first_settings.scan_resume", "Scan Resume", val)
+ menu.append(rs)
+
+ return menu
+
+ def _get_settings(self):
+ top = RadioSettings(
+ self._get_config_settings(),
+ self._get_digital_settings(),
+ self._get_display_settings(),
+ self._get_dtmf_settings(),
+ self._get_gm_settings(),
+ self._get_scan_settings()
+ )
+ return top
+
+ def get_settings(self):
+ try:
+ return self._get_settings()
+ except:
+ import traceback
+ LOG.error("Failed to parse settings: %s", traceback.format_exc())
+ return None
+
+ @classmethod
+ def apply_ff_padded_string(cls, setting, obj):
+ setattr(obj, "padded_string", cls._add_ff_pad(setting.value.get_value().rstrip(), 6))
+
+ def set_settings(self, settings):
+ _mem = self._memobj
+ for element in settings:
+ if not isinstance(element, RadioSetting):
+ self.set_settings(element)
+ continue
+ if not element.changed():
+ continue
+ try:
+ if element.has_apply_callback():
+ LOG.debug("Using apply callback")
+ try:
+ element.run_apply_callback()
+ except NotImplementedError as e:
+ LOG.error(e)
+ continue
+
+ # Find the object containing setting.
+ obj = _mem
+ bits = element.get_name().split(".")
+ setting = bits[-1]
+ for name in bits[:-1]:
+ if name.endswith("]"):
+ name, index = name.split("[")
+ index = int(index[:-1])
+ obj = getattr(obj, name)[index]
+ else:
+ obj = getattr(obj, name)
+
+ try:
+ old_val = getattr(obj, setting)
+ LOG.debug("Setting %s(%r) <= %s" % (
+ element.get_name(), old_val, element.value))
+ setattr(obj, setting, element.value)
+ except AttributeError as e:
+ LOG.error("Setting %s is not in the memory map: %s" %
+ (element.get_name(), e))
+ except Exception, e:
+ LOG.debug(element.get_name())
+ raise
+
+ def apply_volume(cls, setting, vfo):
+ val = setting.value.get_value()
+ cls._memobj.vfo_info[(vfo * 2)].volume = val
+ cls._memobj.vfo_info[(vfo * 2) + 1].volume = val
+
+ def apply_dtmf(cls, setting, i):
+ rawval = setting.value.get_value().upper().rstrip()
+ val = [FT70_DTMF_CHARS.index(x) for x in rawval]
+ for x in range(len(val), 16):
+ val.append(0xFF)
+ cls._memobj.dtmf[i].memory = val
+
+ def apply_digital_popup(cls, setting, obj):
+ rawval = setting.value.get_value()
+ val = 0 if cls._DIG_POP_UP.index(rawval) == 0 else cls._DIG_POP_UP.index(rawval) + 9
+ obj.digital_popup = val
+
+ def apply_mycall(cls, setting, obj):
+ cs = setting.value.get_value()
+ if cs[0] in ('-', '/'):
+ raise InvalidValueError("First character of call sign can't be - or /: {0:s}".format(cs))
+ else:
+ obj.callsign = cls._add_ff_pad(cs.rstrip(), 10)
diff --git a/chirp/drivers/gmrsuv1.py b/chirp/drivers/gmrsuv1.py index ea197c6..d8fd594 100644 --- a/chirp/drivers/gmrsuv1.py +++ b/chirp/drivers/gmrsuv1.py @@ -40,6 +40,8 @@ MSTRING_GMRSV1 = "\x50\x5F\x20\x15\x12\x15\x4D" # BTECH GMRS-V1 GMRSV1_fp1 = "US32411" +GMRSV1_fp2 = "US32416" +GMRSV1_fp3 = "US32418" DTMF_CHARS = "0123456789 *#ABCD" STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0] @@ -69,6 +71,15 @@ LIST_TXPOWER = ["High", "Low"] LIST_VOICE = ["Off", "English", "Chinese"] LIST_WORKMODE = ["Frequency", "Channel"] +GMRS_FREQS1 = [462.5625, 462.5875, 462.6125, 462.6375, 462.6625, + 462.6875, 462.7125] +GMRS_FREQS2 = [467.5625, 467.5875, 467.6125, 467.6375, 467.6625, + 467.6875, 467.7125] +GMRS_FREQS3 = [462.5500, 462.5750, 462.6000, 462.6250, 462.6500, + 462.6750, 462.7000, 462.7250] +GMRS_FREQS_ORIG = GMRS_FREQS1 + GMRS_FREQS3 * 2 +GMRS_FREQS_2017 = GMRS_FREQS1 + GMRS_FREQS2 + GMRS_FREQS3 * 2 + def model_match(cls, data): """Match the opened/downloaded image to the correct version""" rid = data[0x1EF0:0x1EF7] @@ -79,26 +90,14 @@ def model_match(cls, data): return False -class MyRadioFeatures(chirp_common.RadioFeatures): - def validate_memory(self, mem): - # Run the normal validation - msgs = chirp_common.RadioFeatures.validate_memory(self, mem) - - # Run my validation - if mem.number <= 6 and mem.mode != "NFM": - msgs.append(chirp_common.ValidationError( - 'Only NFM is supported on this channel')) - - return msgs - - @directory.register class GMRSV1(baofeng_common.BaofengCommonHT): """BTech GMRS-V1""" VENDOR = "BTECH" MODEL = "GMRS-V1" - _fileid = [GMRSV1_fp1, ] + _fileid = [GMRSV1_fp3, GMRSV1_fp2, GMRSV1_fp1, ] + _is_orig = [GMRSV1_fp2, GMRSV1_fp1, ] _magic = [MSTRING_GMRSV1, ] _magic_response_length = 8 @@ -132,7 +131,7 @@ class GMRSV1(baofeng_common.BaofengCommonHT): def get_features(self): """Get the radio's features""" - rf = MyRadioFeatures() + rf = chirp_common.RadioFeatures() rf.has_settings = True rf.has_bank = False rf.has_tuning_step = False @@ -148,7 +147,7 @@ class GMRSV1(baofeng_common.BaofengCommonHT): rf.valid_modes = self.MODES rf.valid_characters = self.VALID_CHARS rf.valid_name_length = self.LENGTH_NAME - rf.valid_duplexes = [] + rf.valid_duplexes = ["", "-", "+"] rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross'] rf.valid_cross_modes = [ "Tone->Tone", @@ -403,6 +402,226 @@ class GMRSV1(baofeng_common.BaofengCommonHT): """Process the mem map into the mem object""" self._memobj = bitwise.parse(self.MEM_FORMAT, self._mmap) + def validate_memory(self, mem): + msgs = baofeng_common.BaofengCommonHT.validate_memory(self, mem) + + _mem = self._memobj.memory[mem.number] + _msg_freq = 'Memory location cannot change frequency' + _msg_nfm = 'Memory location only supports NFM' + _msg_txp = 'Memory location only supports Low' + + # Original GMRS-V1 models + if str(self._memobj.firmware_msg.line1) in self._is_orig: + # range of memories with values permanently set by FCC rules + if mem.number <= 22: + if mem.freq != int(GMRS_FREQS_ORIG[mem.number] * 1000000): + # warn user can't change frequency + msgs.append(chirp_common.ValidationError(_msg_freq)) + + if mem.number <= 6: + if mem.mode == "FM": + # warn user can't change mode + msgs.append(chirp_common.ValidationError(_msg_nfm)) + + # GMRS-V1 models supporting 2017 GMRS rules + else: + # range of memories with values permanently set by FCC rules + if mem.number >= 1 and mem.number <= 30: + if mem.freq != int(GMRS_FREQS_2017[mem.number - 1] * 1000000): + # warn user can't change frequency + msgs.append(chirp_common.ValidationError(_msg_freq)) + + if mem.number >= 8 and mem.number <= 14: + if mem.mode == "FM": + # warn user can't change mode + msgs.append(chirp_common.ValidationError(_msg_nfm)) + + if str(mem.power) == "High": + # warn user can't change power level + msgs.append(chirp_common.ValidationError(_msg_txp)) + + return msgs + + def get_memory(self, number): + _mem = self._memobj.memory[number] + _nam = self._memobj.names[number] + + mem = chirp_common.Memory() + mem.number = number + + if _mem.get_raw()[0] == "\xff": + mem.empty = True + return mem + + mem.freq = int(_mem.rxfreq) * 10 + + # TX freq set + offset = (int(_mem.txfreq) * 10) - mem.freq + if offset != 0: + if offset > 0: + mem.offset = offset + mem.duplex = "+" + else: + mem.offset = 0 + + for char in _nam.name: + if str(char) == "\xFF": + char = " " # The OEM software may have 0xFF mid-name + mem.name += str(char) + mem.name = mem.name.rstrip() + + dtcs_pol = ["N", "N"] + + if _mem.txtone in [0, 0xFFFF]: + txmode = "" + elif _mem.txtone >= 0x0258: + txmode = "Tone" + mem.rtone = int(_mem.txtone) / 10.0 + elif _mem.txtone <= 0x0258: + txmode = "DTCS" + if _mem.txtone > 0x69: + index = _mem.txtone - 0x6A + dtcs_pol[0] = "R" + else: + index = _mem.txtone - 1 + mem.dtcs = self.DTCS_CODES[index] + else: + LOG.warn("Bug: txtone is %04x" % _mem.txtone) + + if _mem.rxtone in [0, 0xFFFF]: + rxmode = "" + elif _mem.rxtone >= 0x0258: + rxmode = "Tone" + mem.ctone = int(_mem.rxtone) / 10.0 + elif _mem.rxtone <= 0x0258: + rxmode = "DTCS" + if _mem.rxtone >= 0x6A: + index = _mem.rxtone - 0x6A + dtcs_pol[1] = "R" + else: + index = _mem.rxtone - 1 + mem.rx_dtcs = self.DTCS_CODES[index] + else: + LOG.warn("Bug: rxtone is %04x" % _mem.rxtone) + + if txmode == "Tone" and not rxmode: + mem.tmode = "Tone" + elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone: + mem.tmode = "TSQL" + elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs: + mem.tmode = "DTCS" + elif rxmode or txmode: + mem.tmode = "Cross" + mem.cross_mode = "%s->%s" % (txmode, rxmode) + + mem.dtcs_polarity = "".join(dtcs_pol) + + if not _mem.scan: + mem.skip = "S" + + levels = self.POWER_LEVELS + try: + mem.power = levels[_mem.lowpower] + except IndexError: + LOG.error("Radio reported invalid power level %s (in %s)" % + (_mem.power, levels)) + mem.power = levels[0] + + mem.mode = _mem.wide and "FM" or "NFM" + + mem.extra = RadioSettingGroup("Extra", "extra") + + rs = RadioSetting("bcl", "BCL", + RadioSettingValueBoolean(_mem.bcl)) + mem.extra.append(rs) + + rs = RadioSetting("pttid", "PTT ID", + RadioSettingValueList(self.PTTID_LIST, + self.PTTID_LIST[_mem.pttid])) + mem.extra.append(rs) + + rs = RadioSetting("scode", "S-CODE", + RadioSettingValueList(self.SCODE_LIST, + self.SCODE_LIST[_mem.scode])) + mem.extra.append(rs) + + return mem + + def set_memory(self, mem): + _mem = self._memobj.memory[mem.number] + _nam = self._memobj.names[mem.number] + + if mem.empty: + _mem.set_raw("\xff" * 16) + _nam.set_raw("\xff" * 16) + return + + _mem.set_raw("\x00" * 16) + + _mem.rxfreq = mem.freq / 10 + + if str(self._memobj.firmware_msg.line1) in self._is_orig: + if mem.number > 22: + _mem.txfreq = mem.freq / 10 + else: + if mem.number < 1 or mem.number > 22: + _mem.txfreq = mem.freq / 10 + + _namelength = self.get_features().valid_name_length + for i in range(_namelength): + try: + _nam.name[i] = mem.name[i] + except IndexError: + _nam.name[i] = "\xFF" + + rxmode = txmode = "" + if mem.tmode == "Tone": + _mem.txtone = int(mem.rtone * 10) + _mem.rxtone = 0 + elif mem.tmode == "TSQL": + _mem.txtone = int(mem.ctone * 10) + _mem.rxtone = int(mem.ctone * 10) + elif mem.tmode == "DTCS": + rxmode = txmode = "DTCS" + _mem.txtone = self.DTCS_CODES.index(mem.dtcs) + 1 + _mem.rxtone = self.DTCS_CODES.index(mem.dtcs) + 1 + elif mem.tmode == "Cross": + txmode, rxmode = mem.cross_mode.split("->", 1) + if txmode == "Tone": + _mem.txtone = int(mem.rtone * 10) + elif txmode == "DTCS": + _mem.txtone = self.DTCS_CODES.index(mem.dtcs) + 1 + else: + _mem.txtone = 0 + if rxmode == "Tone": + _mem.rxtone = int(mem.ctone * 10) + elif rxmode == "DTCS": + _mem.rxtone = self.DTCS_CODES.index(mem.rx_dtcs) + 1 + else: + _mem.rxtone = 0 + else: + _mem.rxtone = 0 + _mem.txtone = 0 + + if txmode == "DTCS" and mem.dtcs_polarity[0] == "R": + _mem.txtone += 0x69 + if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R": + _mem.rxtone += 0x69 + + _mem.scan = mem.skip != "S" + _mem.wide = mem.mode == "FM" + + if mem.power: + _mem.lowpower = self.POWER_LEVELS.index(mem.power) + else: + _mem.lowpower = 0 + + # extra settings + if len(mem.extra) > 0: + # there are setting, parse + for setting in mem.extra: + setattr(_mem, setting.get_name(), setting.value) + def get_settings(self): """Translate the bit in the mem_struct into settings in the UI""" _mem = self._memobj diff --git a/chirp/drivers/h777.py b/chirp/drivers/h777.py index 48c657f..f542ad1 100644 --- a/chirp/drivers/h777.py +++ b/chirp/drivers/h777.py @@ -227,6 +227,16 @@ def do_upload(radio): _h777_exit_programming_mode(radio) +class ArcshellAR5(chirp_common.Alias): + VENDOR = 'Arcshell' + MODEL = 'AR-5' + + +class ArcshellAR6(chirp_common.Alias): + VENDOR = 'Arcshell' + MODEL = 'AR-6' + + @directory.register class H777Radio(chirp_common.CloneModeRadio): """HST H-777""" @@ -236,6 +246,8 @@ class H777Radio(chirp_common.CloneModeRadio): MODEL = "BF-888" BAUD_RATE = 9600 + ALIASES = [ArcshellAR5, ArcshellAR6] + # This code currently requires that ranges start at 0x0000 # and are continious. In the original program 0x0388 and 0x03C8 # are only written (all bytes 0xFF), not read. @@ -252,6 +264,8 @@ class H777Radio(chirp_common.CloneModeRadio): (0x0380, 0x03E0), ] _memsize = 0x03E0 + _has_fm = True + _has_sidekey = True def get_features(self): rf = chirp_common.RadioFeatures() @@ -461,9 +475,10 @@ class H777Radio(chirp_common.CloneModeRadio): # TODO: This should probably be called “FM Broadcast Band Radio” # or something. I'm not sure if the model actually has one though. - rs = RadioSetting("fmradio", "FM function", - RadioSettingValueBoolean(_settings.fmradio)) - basic.append(rs) + if self._has_fm: + rs = RadioSetting("fmradio", "FM function", + RadioSettingValueBoolean(_settings.fmradio)) + basic.append(rs) rs = RadioSetting("settings2.beep", "Beep", RadioSettingValueBoolean( @@ -480,12 +495,13 @@ class H777Radio(chirp_common.CloneModeRadio): 0, 9, self._memobj.settings2.squelchlevel)) basic.append(rs) - rs = RadioSetting("settings2.sidekeyfunction", "Side key function", - RadioSettingValueList( - SIDEKEYFUNCTION_LIST, - SIDEKEYFUNCTION_LIST[ - self._memobj.settings2.sidekeyfunction])) - basic.append(rs) + if self._has_sidekey: + rs = RadioSetting("settings2.sidekeyfunction", "Side key function", + RadioSettingValueList( + SIDEKEYFUNCTION_LIST, + SIDEKEYFUNCTION_LIST[ + self._memobj.settings2.sidekeyfunction])) + basic.append(rs) rs = RadioSetting("settings2.timeouttimer", "Timeout timer", RadioSettingValueList( @@ -572,3 +588,16 @@ class H777TestCase(unittest.TestCase): def test_encode_tone_none(self): self.driver._encode_tone(self.testdata.foo, '', 67.0, 'N') self.assertEqual(16665, int(self.testdata.foo)) + + +@directory.register +class ROGA2SRadio(H777Radio): + VENDOR = "Radioddity" + MODEL = "GA-2S" + _has_fm = False + _has_sidekey = False + + @classmethod + def match_model(cls, filedata, filename): + # This model is only ever matched via metadata + return False diff --git a/chirp/drivers/ic2730.py b/chirp/drivers/ic2730.py new file mode 100644 index 0000000..44af362 --- /dev/null +++ b/chirp/drivers/ic2730.py @@ -0,0 +1,273 @@ +# Copyright 2018 Rhett Robinson <rrhett@gmail.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +from chirp.drivers import icf +from chirp import chirp_common, util, directory, bitwise, memmap + + +# Still missing: +# - scan edges +# - priority watch +# - hope channel beep +# - DTMF memory +# - weather channel alert +MEM_FORMAT = """ +struct { + u24 freq; + u16 offset; + u8 tune_step:4, + unknown5:3, + mode:1; + u8 unknown6:2, + rtone:6; + u8 unknown7:2, + ctone:6; + u8 unknown8; + u8 dtcs; + u8 tmode:4, + duplex:2, + dtcs_polarity:2; + char name[6]; +} memory[1002]; + +#seekto 0x42c0; +u8 used_flags[125]; + +#seekto 0x433e; +u8 skip_flags[125]; +u8 pskip_flags[125]; + +#seekto 0x4440; +struct { + u8 bank; + u8 index; +} bank_info[1000]; + +#seekto 0x4c50; +struct { + char name[6]; +} bank_names[10]; + +#seekto 0x5004; +u8 unknown12:4, + autorptr:2, + unknown13:2; + +#seekto 0x5030; +u8 unknown14:6, + backlight:2; + +#seekto 0x5056; +u8 unknown15:6, + power:2; + +#seekto 0x5220; +u16 left_memory; +u16 right_memory; + +#seekto 0x5280; +u16 mem_writes_count; +""" + +# Guessing some of these intermediate values are with the Pocket Beep function, +# but I haven't reliably reproduced these. +TMODES = ["", "Tone", "??0", "TSQL", "??1", "DTCS", "TSQL-R", "DTCS-R", + "DTC.OFF", "TON.DTC", "DTC.TSQ", "TON.TSQ"] +DUPLEX = ["", "-", "+"] +MODES = ["FM", "NFM"] +DTCSP = ["NN", "NR", "RN", "RR"] + +AUTOREPEATER = ["OFF", "DUP", "DUP.TON"] + + +class IC2730Bank(icf.IcomNamedBank): + """An IC2730 bank""" + def get_name(self): + _banks = self._model._radio._memobj.bank_names + return str(_banks[self.index].name).rstrip() + + def set_name(self, name): + _banks = self._model._radio._memobj.bank_names + _banks[self.index].name = str(name).ljust(6)[:6] + + +def _get_special(): + special = {"C0": 1000, + "C1": 1001} + return special + + +def _resolve_memory_number(number): + if isinstance(number, str): + return _get_special()[number] + else: + return number + + +def _wipe_memory(mem, char): + mem.set_raw(char * (mem.size() / 8)) + + +@directory.register +class IC2730Radio(icf.IcomRawCloneModeRadio): + """Icom IC-2730A""" + VENDOR = "Icom" + MODEL = "IC-2730A" + + _model = "\x35\x98\x00\x01" + _memsize = 21312 # 0x5340 + _endframe = "Icom Inc\x2e4E" + + _ranges = [(0x0000, 0x5300, 64), + (0x5300, 0x5310, 16), + (0x5310, 0x5340, 48), + ] + + _num_banks = 10 + _bank_class = IC2730Bank + _can_hispeed = True + + def _get_bank(self, loc): + _bank = self._memobj.bank_info[loc] + if _bank.bank == 0x1F: + return None + else: + return _bank.bank + + def _set_bank(self, loc, bank): + _bank = self._memobj.bank_info[loc] + if bank is None: + _bank.bank = 0x1F + else: + _bank.bank = bank + + def _get_bank_index(self, loc): + _bank = self._memobj.bank_info[loc] + return _bank.index + + def _set_bank_index(self, loc, index): + _bank = self._memobj.bank_info[loc] + _bank.index = index + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.has_bank_index = True + rf.has_bank_names = True + rf.requires_call_lists = False + rf.memory_bounds = (0, 999) + rf.valid_modes = list(MODES) + rf.valid_tmodes = list(TMODES) + rf.valid_duplexes = list(set(DUPLEX)) + rf.valid_tuning_steps = list(chirp_common.TUNING_STEPS[0:9]) + rf.valid_bands = [(118000000, 174000000), + (375000000, 550000000), + ] + rf.valid_skips = ["", "S", "P"] + rf.valid_characters = chirp_common.CHARSET_ASCII + rf.valid_name_length = 6 + rf.valid_special_chans = sorted(_get_special().keys()) + + return rf + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def get_memory(self, number): + bitpos = (1 << (number % 8)) + bytepos = number / 8 + + _mem = self._memobj.memory[number] + _used = self._memobj.used_flags[bytepos] + + is_used = ((_used & bitpos) == 0) + + mem = chirp_common.Memory() + + mem.number = number + + _skip = self._memobj.skip_flags[bytepos] + _pskip = self._memobj.pskip_flags[bytepos] + if _skip & bitpos: + mem.skip = "S" + elif _pskip & bitpos: + mem.skip = "P" + + if not is_used: + mem.empty = True + return mem + + # Frequencies are stored as kHz/5 + mem.freq = int(_mem.freq) * 5000 + mem.offset = int(_mem.offset) * 5000 + mem.rtone = chirp_common.TONES[_mem.rtone] + mem.ctone = chirp_common.TONES[_mem.ctone] + mem.tmode = TMODES[_mem.tmode] + mem.duplex = DUPLEX[_mem.duplex] + mem.mode = MODES[_mem.mode] + mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs] + mem.dtcs_polarity = DTCSP[_mem.dtcs_polarity] + if _mem.tune_step > 8: + mem.tuning_step = 5.0 # Sometimes TS is garbage? + else: + mem.tuning_step = chirp_common.TUNING_STEPS[_mem.tune_step] + mem.name = str(_mem.name).rstrip() + + return mem + + def set_memory(self, mem): + bitpos = (1 << (mem.number % 8)) + bytepos = mem.number / 8 + + _mem = self._memobj.memory[mem.number] + _used = self._memobj.used_flags[bytepos] + + was_empty = _used & bitpos + + skip = self._memobj.skip_flags[bytepos] + pskip = self._memobj.pskip_flags[bytepos] + if mem.skip == "S": + skip |= bitpos + else: + skip &= ~bitpos + if mem.skip == "P": + pskip |= bitpos + else: + pskip &= ~bitpos + + if mem.empty: + _used |= bitpos + _wipe_memory(_mem, "\xFF") + self._set_bank(mem.number, None) + return + + _used &= ~bitpos + if was_empty: + _wipe_memory(_mem, "\x00") + + _mem.freq = mem.freq / 5000 + _mem.offset = mem.offset / 5000 + _mem.rtone = chirp_common.TONES.index(mem.rtone) + _mem.ctone = chirp_common.TONES.index(mem.ctone) + _mem.tmode = TMODES.index(mem.tmode) + _mem.duplex = DUPLEX.index(mem.duplex) + _mem.mode = MODES.index(mem.mode) + _mem.dtcs = chirp_common.DTCS_CODES.index(mem.dtcs) + _mem.dtcs_polarity = DTCSP.index(mem.dtcs_polarity) + _mem.tune_step = chirp_common.TUNING_STEPS.index(mem.tuning_step) + _mem.name = mem.name.ljust(6) + + def get_raw_memory(self, number): + return repr(self._memobj.memory[number]) diff --git a/chirp/drivers/icf.py b/chirp/drivers/icf.py index e544571..30eabcb 100644 --- a/chirp/drivers/icf.py +++ b/chirp/drivers/icf.py @@ -85,6 +85,7 @@ class RadioStream: def _process_frames(self): if not self.data.startswith("\xFE\xFE"): + LOG.error("Out of sync with radio:\n%s" % util.hexprint(self.data)) raise errors.InvalidDataError("Out of sync with radio") elif len(self.data) < 5: return [] # Not enough data for a full frame @@ -134,11 +135,11 @@ class RadioStream: return self._process_frames() -def get_model_data(pipe, mdata="\x00\x00\x00\x00"): - """Query the radio connected to @pipe for its model data""" - send_clone_frame(pipe, 0xe0, mdata, raw=True) +def get_model_data(radio, mdata="\x00\x00\x00\x00"): + """Query the @radio for its model data""" + send_clone_frame(radio, 0xe0, mdata, raw=True) - stream = RadioStream(pipe) + stream = RadioStream(radio.pipe) frames = stream.get_frames() if len(frames) != 1: @@ -164,27 +165,11 @@ def get_clone_resp(pipe, length=None): return resp -def send_clone_frame(pipe, cmd, data, raw=False, checksum=False): - """Send a clone frame with @cmd and @data to the radio attached - to @pipe""" - cs = 0 - - if raw: - hed = data - else: - hed = "" - for byte in data: - val = ord(byte) - hed += "%02X" % val - cs += val +def send_clone_frame(radio, cmd, data, raw=False, checksum=False): + """Send a clone frame with @cmd and @data to the @radio""" + payload = radio.get_payload(data, raw, checksum) - if checksum: - cs = ((cs ^ 0xFFFF) + 1) & 0xFF - cs = "%02X" % cs - else: - cs = "" - - frame = "\xfe\xfe\xee\xef%s%s%s\xfd" % (chr(cmd), hed, cs) + frame = "\xfe\xfe\xee\xef%s%s\xfd" % (chr(cmd), payload) if SAVE_PIPE: LOG.debug("Saving data...") @@ -197,32 +182,14 @@ def send_clone_frame(pipe, cmd, data, raw=False, checksum=False): # return frame pass - pipe.write(frame) - pipe.flush() - pipe.read(len(frame)) # discard echoback + radio.pipe.write(frame) return frame -def process_bcd(bcddata): - """Convert BCD-encoded data to raw""" - data = "" - i = 0 - while i < range(len(bcddata)) and i+1 < len(bcddata): - try: - val = int("%s%s" % (bcddata[i], bcddata[i+1]), 16) - i += 2 - data += struct.pack("B", val) - except ValueError, e: - LOG.error("Failed to parse byte: %s" % e) - break - - return data - - -def process_data_frame(frame, _mmap): +def process_data_frame(radio, frame, _mmap): """Process a data frame, adding the payload to @_mmap""" - _data = process_bcd(frame.payload) + _data = radio.process_frame_payload(frame.payload) if len(_mmap) >= 0x10000: saddr, = struct.unpack(">I", _data[0:4]) length, = struct.unpack("B", _data[4]) @@ -263,11 +230,10 @@ def start_hispeed_clone(radio, cmd): LOG.debug("Starting HiSpeed Clone:\n%s" % util.hexprint(buf)) radio.pipe.write(buf) radio.pipe.flush() - radio.pipe.read(len(buf)) # discard echoback def _clone_from_radio(radio): - md = get_model_data(radio.pipe) + md = get_model_data(radio) if md[0:4] != radio.get_model(): LOG.info("This model: %s" % util.hexprint(md[0:4])) @@ -277,8 +243,7 @@ def _clone_from_radio(radio): if radio.is_hispeed(): start_hispeed_clone(radio, CMD_CLONE_OUT) else: - send_clone_frame(radio.pipe, CMD_CLONE_OUT, - radio.get_model(), raw=True) + send_clone_frame(radio, CMD_CLONE_OUT, radio.get_model(), raw=True) LOG.debug("Sent clone frame") @@ -294,7 +259,7 @@ def _clone_from_radio(radio): for frame in frames: if frame.cmd == CMD_CLONE_DAT: - src, dst = process_data_frame(frame, _mmap) + src, dst = process_data_frame(radio, frame, _mmap) if last_size != (dst - src): LOG.debug("ICF Size change from %i to %i at %04x" % (last_size, dst - src, src)) @@ -345,9 +310,10 @@ def send_mem_chunk(radio, start, stop, bs=32): chunk = struct.pack(">HB", i, size) chunk += _mmap[i:i+size] - send_clone_frame(radio.pipe, + send_clone_frame(radio, CMD_CLONE_DAT, chunk, + raw=False, checksum=True) if radio.status_fn: @@ -363,22 +329,22 @@ def _clone_to_radio(radio): # Uncomment to save out a capture of what we actually write to the radio # SAVE_PIPE = file("pipe_capture.log", "w", 0) - md = get_model_data(radio.pipe) + md = get_model_data(radio) if md[0:4] != radio.get_model(): raise errors.RadioError("I can't talk to this model") # This mimics what the Icom software does, but isn't required and just # takes longer - # md = get_model_data(radio.pipe, model=md[0:2]+"\x00\x00") - # md = get_model_data(radio.pipe, model=md[0:2]+"\x00\x00") + # md = get_model_data(radio, mdata=md[0:2]+"\x00\x00") + # md = get_model_data(radio, mdata=md[0:2]+"\x00\x00") stream = RadioStream(radio.pipe) if radio.is_hispeed(): start_hispeed_clone(radio, CMD_CLONE_IN) else: - send_clone_frame(radio.pipe, CMD_CLONE_IN, radio.get_model(), raw=True) + send_clone_frame(radio, CMD_CLONE_IN, radio.get_model(), raw=True) frames = [] @@ -387,7 +353,7 @@ def _clone_to_radio(radio): break frames += stream.get_frames() - send_clone_frame(radio.pipe, CMD_CLONE_END, radio.get_endframe(), raw=True) + send_clone_frame(radio, CMD_CLONE_END, radio.get_endframe(), raw=True) if SAVE_PIPE: SAVE_PIPE.close() @@ -412,6 +378,7 @@ def clone_to_radio(radio): try: return _clone_to_radio(radio) except Exception, e: + logging.exception("Failed to communicate with the radio") raise errors.RadioError("Failed to communicate with the radio: %s" % e) @@ -582,6 +549,13 @@ class IcomIndexedBankModel(IcomBankModel, raise errors.RadioError("Out of slots in this bank") +def compute_checksum(data): + cs = 0 + for byte in data: + cs += ord(byte) + return ((cs ^ 0xFFFF) + 1) & 0xFF + + class IcomCloneModeRadio(chirp_common.CloneModeRadio): """Base class for Icom clone-mode radios""" VENDOR = "Icom" @@ -615,6 +589,33 @@ class IcomCloneModeRadio(chirp_common.CloneModeRadio): """Returns the ranges this radio likes to have in a clone""" return cls._ranges + def process_frame_payload(self, payload): + """Convert BCD-encoded data to raw""" + bcddata = payload + data = "" + i = 0 + while i+1 < len(bcddata): + try: + val = int("%s%s" % (bcddata[i], bcddata[i+1]), 16) + i += 2 + data += struct.pack("B", val) + except ValueError, e: + LOG.error("Failed to parse byte: %s" % e) + break + + return data + + def get_payload(self, data, raw, checksum): + """Returns the data with optional checksum BCD-encoded for the radio""" + if raw: + return data + payload = "" + for byte in data: + payload += "%02X" % ord(byte) + if checksum: + payload += "%02X" % compute_checksum(data) + return payload + def sync_in(self): self._mmap = clone_from_radio(self) self.process_mmap() @@ -649,6 +650,67 @@ class IcomCloneModeRadio(chirp_common.CloneModeRadio): return honor_speed_switch_setting(self, settings) +def flip_high_order_bit(data): + return [chr(ord(d) ^ 0x80) for d in list(data)] + + +def escape_raw_byte(byte): + """Escapes a raw byte for sending to the radio""" + # Certain bytes are used as control characters to the radio, so if one of + # these bytes is present in the stream to the radio, it gets escaped as + # 0xff followed by (byte & 0x0f) + if ord(byte) > 0xf9: + return "\xff%s" % (chr(ord(byte) & 0xf)) + return byte + + +def unescape_raw_bytes(escaped_data): + """Unescapes raw bytes from the radio.""" + data = "" + i = 0 + while i < len(escaped_data): + byte = escaped_data[i] + if byte == '\xff': + if i + 1 >= len(escaped_data): + raise errors.InvalidDataError( + "Unexpected escape character at end of data") + i += 1 + byte = chr(0xf0 | ord(escaped_data[i])) + data += byte + i += 1 + return data + + +class IcomRawCloneModeRadio(IcomCloneModeRadio): + """Subclass for Icom clone-mode radios using the raw data protocol.""" + + def process_frame_payload(self, payload): + """Payloads from a raw-clone-mode radio are already in raw format.""" + return unescape_raw_bytes(payload) + + def get_payload(self, data, raw, checksum): + """Returns the data with optional checksum in raw format.""" + if checksum: + cs = chr(compute_checksum(data)) + else: + cs = "" + payload = "%s%s" % (data, cs) + # Escape control characters. + escaped_payload = [escape_raw_byte(b) for b in payload] + return "".join(escaped_payload) + + def sync_in(self): + # The radio returns all the bytes with the high-order bit flipped. + _mmap = clone_from_radio(self) + _mmap = flip_high_order_bit(_mmap.get_packed()) + self._mmap = memmap.MemoryMap(_mmap) + self.process_mmap() + + def get_mmap(self): + _data = flip_high_order_bit(self._mmap.get_packed()) + return memmap.MemoryMap(_data) + + class IcomLiveRadio(chirp_common.LiveRadio): """Base class for an Icom Live-mode radio""" VENDOR = "Icom" diff --git a/chirp/drivers/icq7.py b/chirp/drivers/icq7.py index 04cf63e..45bd122 100644 --- a/chirp/drivers/icq7.py +++ b/chirp/drivers/icq7.py @@ -134,6 +134,12 @@ class ICQ7Radio(icf.IcomCloneModeRadio): return (repr(self._memobj.memory[number]) + repr(self._memobj.flags[number])) + def validate_memory(self, mem): + if mem.freq < 30000000 and mem.mode != 'AM': + return [chirp_common.ValidationError( + 'Only AM is allowed below 30MHz')] + return icf.IcomCloneModeRadio.validate_memory(self, mem) + def get_memory(self, number): _mem = self._memobj.memory[number] _flag = self._memobj.flags[number] diff --git a/chirp/drivers/id880.py b/chirp/drivers/id880.py index c3b8ebb..5236f82 100644 --- a/chirp/drivers/id880.py +++ b/chirp/drivers/id880.py @@ -144,7 +144,7 @@ def _decode_freq(freq, mult): def _encode_freq(freq): - for i, step in reversed(list(enumerate(FREQ_MULTIPLIER))): + for i, step in list(enumerate(FREQ_MULTIPLIER)): if freq % step == 0: return freq / step, i raise ValueError("%d cannot be factored by multiplier table." % freq) diff --git a/chirp/drivers/kenwood_hmk.py b/chirp/drivers/kenwood_hmk.py index ba3fe1a..bf3d5db 100644 --- a/chirp/drivers/kenwood_hmk.py +++ b/chirp/drivers/kenwood_hmk.py @@ -125,7 +125,7 @@ class HMKRadio(generic_csv.CSVRadio): if not good: for e in errors: - LOG.error(e) + LOG.error("kenwood_hmk: %s", e) raise errors.InvalidDataError("No channels found") @classmethod diff --git a/chirp/drivers/kenwood_itm.py b/chirp/drivers/kenwood_itm.py index 57c3076..ef5caff 100644 --- a/chirp/drivers/kenwood_itm.py +++ b/chirp/drivers/kenwood_itm.py @@ -129,7 +129,7 @@ class ITMRadio(generic_csv.CSVRadio): if not good: for e in errors: - LOG.error(e) + LOG.error("kenwood_itm: %s", e) raise errors.InvalidDataError("No channels found") @classmethod diff --git a/chirp/drivers/kguv8dplus.py b/chirp/drivers/kguv8dplus.py new file mode 100644 index 0000000..227f3fe --- /dev/null +++ b/chirp/drivers/kguv8dplus.py @@ -0,0 +1,1110 @@ +# Copyright 2017 Krystian Struzik <toner_82@tlen.pl> +# Based on Ron Wellsted driver for Wouxun KG-UV8D. +# KG-UV8D Plus model has all serial data encrypted. +# Figured out how the data is encrypted and implement +# serial data encryption and decryption functions. +# The algorithm of decryption works like this: +# - the first byte of data stream is XOR by const 57h +# - each next byte is encoded by previous byte using the XOR +# including the checksum (e.g data[i - 1] xor data[i]) +# I also changed the data structure to fit radio memory +# and implement set_settings function. +# +# 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/>. + +"""Wouxun KG-UV8D Plus radio management module""" + +import time +import os +import logging +from chirp import util, chirp_common, bitwise, memmap, errors, directory +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueBoolean, RadioSettingValueList, \ + RadioSettingValueInteger, RadioSettingValueString, \ + RadioSettings + +LOG = logging.getLogger(__name__) + +CMD_ID = 128 +CMD_END = 129 +CMD_RD = 130 +CMD_WR = 131 + +MEM_VALID = 158 + +AB_LIST = ["A", "B"] +STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0, 50.0, 100.0] +STEP_LIST = [str(x) for x in STEPS] +ROGER_LIST = ["Off", "Begin", "End", "Both"] +TIMEOUT_LIST = ["Off"] + [str(x) + "s" for x in range(15, 901, 15)] +VOX_LIST = ["Off"] + ["%s" % x for x in range(1, 10)] +BANDWIDTH_LIST = ["Narrow", "Wide"] +VOICE_LIST = ["Off", "On"] +LANGUAGE_LIST = ["Chinese", "English"] +SCANMODE_LIST = ["TO", "CO", "SE"] +PF1KEY_LIST = ["Call", "VFTX"] +PF3KEY_LIST = ["Disable", "Scan", "Lamp", "Tele Alarm", "SOS-CH", "Radio"] +WORKMODE_LIST = ["VFO", "Channel No.", "Ch. No.+Freq.", "Ch. No.+Name"] +BACKLIGHT_LIST = ["Always On"] + [str(x) + "s" for x in range(1, 21)] + \ + ["Always Off"] +OFFSET_LIST = ["+", "-"] +PONMSG_LIST = ["Bitmap", "Battery Volts"] +SPMUTE_LIST = ["QT", "QT+DTMF", "QT*DTMF"] +DTMFST_LIST = ["DT-ST", "ANI-ST", "DT-ANI", "Off"] +DTMF_TIMES = ["%s" % x for x in range(50, 501, 10)] +RPTSET_LIST = ["X-TWRPT", "X-DIRRPT"] +ALERTS = [1750, 2100, 1000, 1450] +ALERTS_LIST = [str(x) for x in ALERTS] +PTTID_LIST = ["Begin", "End", "Both"] +LIST_10 = ["Off"] + ["%s" % x for x in range(1, 11)] +SCANGRP_LIST = ["All"] + ["%s" % x for x in range(1, 11)] +SCQT_LIST = ["Decoder", "Encoder", "All"] +SMUTESET_LIST = ["Off", "Tx", "Rx", "Tx/Rx"] +POWER_LIST = ["Lo", "Hi"] +HOLD_TIMES = ["Off"] + ["%s" % x for x in range(100, 5001, 100)] +RPTMODE_LIST = ["Radio", "Repeater"] + +# memory slot 0 is not used, start at 1 (so need 1000 slots, not 999) +# structure elements whose name starts with x are currently unidentified + +_MEM_FORMAT = """ + #seekto 0x0044; + struct { + u32 rx_start; + u32 rx_stop; + u32 tx_start; + u32 tx_stop; + } uhf_limits; + + #seekto 0x0054; + struct { + u32 rx_start; + u32 rx_stop; + u32 tx_start; + u32 tx_stop; + } vhf_limits; + + #seekto 0x0400; + struct { + u8 oem1[8]; + u8 unknown[2]; + u8 unknown2[10]; + u8 unknown3[10]; + u8 unknown4[8]; + u8 model[10]; + u8 version[6]; + u8 date[8]; + u8 unknown5[1]; + u8 oem2[8]; + } oem_info; + + #seekto 0x0480; + struct { + u16 lower; + u16 upper; + } scan_groups[10]; + + #seekto 0x0500; + struct { + u8 call_code[6]; + } call_groups[20]; + + #seekto 0x0580; + struct { + char call_name[6]; + } call_group_name[20]; + + #seekto 0x0800; + struct { + u8 ponmsg; + char dispstr[15]; + u8 x0810; + u8 x0811; + u8 x0812; + u8 x0813; + u8 x0814; + u8 voice; + u8 timeout; + u8 toalarm; + u8 channel_menu; + u8 power_save; + u8 autolock; + u8 keylock; + u8 beep; + u8 stopwatch; + u8 vox; + u8 scan_rev; + u8 backlight; + u8 roger_beep; + u8 x0822[6]; + u8 x0823[6]; + u16 pri_ch; + u8 ani_sw; + u8 ptt_delay; + u8 ani_code[6]; + u8 dtmf_st; + u8 bcl_a; + u8 bcl_b; + u8 ptt_id; + u8 prich_sw; + u8 rpt_set; + u8 rpt_spk; + u8 rpt_ptt; + u8 alert; + u8 pf1_func; + u8 pf3_func; + u8 x0843; + u8 workmode_a; + u8 workmode_b; + u8 dtmf_tx_time; + u8 dtmf_interval; + u8 main_ab; + u16 work_cha; + u16 work_chb; + u8 x084d; + u8 x084e; + u8 x084f; + u8 x0850; + u8 x0851; + u8 x0852; + u8 x0853; + u8 x0854; + u8 rpt_mode; + u8 language; + u8 x0857; + u8 x0858; + u8 x0859; + u8 x085a; + u8 x085b; + u8 x085c; + u8 x085d; + u8 x085e; + u8 single_display; + u8 ring_time; + u8 scg_a; + u8 scg_b; + u8 x0863; + u8 rpt_tone; + u8 rpt_hold; + u8 scan_det; + u8 sc_qt; + u8 x0868; + u8 smuteset; + u8 callcode; + } settings; + + #seekto 0x0880; + struct { + u32 rxfreq; + u32 txoffset; + u16 rxtone; + u16 txtone; + u8 scrambler:4, + unknown1:2, + power:1, + unknown2:1; + u8 unknown3:1, + shift_dir:2 + unknown4:1, + compander:1, + mute_mode:2, + iswide:1; + u8 step; + u8 squelch; + } vfoa; + + #seekto 0x08c0; + struct { + u32 rxfreq; + u32 txoffset; + u16 rxtone; + u16 txtone; + u8 scrambler:4, + unknown1:2, + power:1, + unknown2:1; + u8 unknown3:1, + shift_dir:2 + unknown4:1, + compander:1, + mute_mode:2, + iswide:1; + u8 step; + u8 squelch; + } vfob; + + #seekto 0x0900; + struct { + u32 rxfreq; + u32 txfreq; + u16 rxtone; + u16 txtone; + u8 scrambler:4, + unknown1:2, + power:1, + unknown2:1; + u8 unknown3:2, + scan_add:1, + unknown4:1, + compander:1, + mute_mode:2, + iswide:1; + u16 padding; + } memory[1000]; + + #seekto 0x4780; + struct { + u8 name[8]; + u8 unknown[4]; + } names[1000]; + + #seekto 0x7670; + u8 valid[1000]; + """ + +# Support for the Wouxun KG-UV8D Plus radio +# Serial coms are at 19200 baud +# The data is passed in variable length records +# Record structure: +# Offset Usage +# 0 start of record (\x7a) +# 1 Command (\x80 Identify \x81 End/Reboot \x82 Read \x83 Write) +# 2 direction (\xff PC-> Radio, \x00 Radio -> PC) +# 3 length of payload (excluding header/checksum) (n) +# 4 payload (n bytes) +# 4+n+1 checksum - byte sum (% 256) of bytes 1 -> 4+n +# +# Memory Read Records: +# the payload is 3 bytes, first 2 are offset (big endian), +# 3rd is number of bytes to read +# Memory Write Records: +# the maximum payload size (from the Wouxun software) seems to be 66 bytes +# (2 bytes location + 64 bytes data). + +@directory.register +class KGUV8DPlusRadio(chirp_common.CloneModeRadio, + chirp_common.ExperimentalRadio): + + """Wouxun KG-UV8D Plus""" + VENDOR = "Wouxun" + MODEL = "KG-UV8D Plus" + _model = "KG-UV8D" + _file_ident = "kguv8dplus" + BAUD_RATE = 19200 + POWER_LEVELS = [chirp_common.PowerLevel("L", watts=1), + chirp_common.PowerLevel("H", watts=5)] + _mmap = "" + + def _checksum(self, data): + cs = 0 + for byte in data: + cs += ord(byte) + return chr(cs % 256) + + def _write_record(self, cmd, payload = None): + # build the packet + _header = '\x7a' + chr(cmd) + '\xff' + + _length = 0 + if payload: + _length = len(payload) + + # update the length field + _header += chr(_length) + if payload: + # calculate checksum then add it with the payload to the packet and encrypt + crc = self._checksum(_header[1:] + payload) + payload += crc + _header += self.encrypt(payload) + else: + # calculate and add encrypted checksum to the packet + crc = self._checksum(_header[1:]) + _header += self.strxor(crc, '\x57') + LOG.debug("Sent:\n%s" % util.hexprint(_header)) + self.pipe.write(_header) + + def _read_record(self): + # read 4 chars for the header + _header = self.pipe.read(4) + if len(_header) != 4: + raise errors.RadioError('Radio did not respond') + _length = ord(_header[3]) + _packet = self.pipe.read(_length) + _rcs_xor = _packet[-1] + _packet = self.decrypt(_packet) + _cs = ord(self._checksum(_header[1:] + _packet)) + # read the checksum and decrypt it + _rcs = ord(self.strxor(self.pipe.read(1), _rcs_xor)) + LOG.debug("_cs =%x", _cs) + LOG.debug("_rcs=%x", _rcs) + return (_rcs != _cs, _packet) + + def decrypt(self, data): + result = '' + for i in range(len(data)-1, 0, -1): + result += self.strxor(data[i], data[i - 1]) + result += self.strxor(data[0], '\x57') + return result[::-1] + + def encrypt(self, data): + result = self.strxor('\x57', data[0]) + for i in range(1, len(data), 1): + result += self.strxor(result[i - 1], data[i]) + return result + + def strxor (self, xora, xorb): + return chr(ord(xora) ^ ord(xorb)) + +# Identify the radio +# +# A Gotcha: the first identify packet returns a bad checksum, subsequent +# attempts return the correct checksum... (well it does on my radio!) +# +# The ID record returned by the radio also includes the current frequency range +# as 4 bytes big-endian in 10Hz increments +# +# Offset +# 0:10 Model, zero padded (Use first 7 chars for 'KG-UV8D') +# 11:14 UHF rx lower limit (in units of 10Hz) +# 15:18 UHF rx upper limit +# 19:22 UHF tx lower limit +# 23:26 UHF tx upper limit +# 27:30 VHF rx lower limit +# 31:34 VHF rx upper limit +# 35:38 VHF tx lower limit +# 39:42 VHF tx upper limit +# + @classmethod + def match_model(cls, filedata, filename): + return cls._file_ident in 'kg' + filedata[0x426:0x430].replace('(', '').replace(')', '').lower() + + def _identify(self): + """Do the identification dance""" + for _i in range(0, 10): + self._write_record(CMD_ID) + _chksum_err, _resp = self._read_record() + LOG.debug("Got:\n%s" % util.hexprint(_resp)) + if _chksum_err: + LOG.error("Checksum error: retrying ident...") + time.sleep(0.100) + continue + LOG.debug("Model %s" % util.hexprint(_resp[0:7])) + if _resp[0:7] == self._model: + return + if len(_resp) == 0: + raise Exception("Radio not responding") + else: + raise Exception("Unable to identify radio") + + def _finish(self): + self._write_record(CMD_END) + + def process_mmap(self): + self._memobj = bitwise.parse(_MEM_FORMAT, self._mmap) + + def sync_in(self): + try: + self._mmap = self._download() + except errors.RadioError: + raise + except Exception, e: + raise errors.RadioError("Failed to communicate with radio: %s" % e) + self.process_mmap() + + def sync_out(self): + self._upload() + + # TODO: Load all memory. + # It would be smarter to only load the active areas and none of + # the padding/unused areas. Padding still need to be investigated. + def _download(self): + """Talk to a wouxun KG-UV8D Plus and do a download""" + try: + self._identify() + return self._do_download(0, 32768, 64) + except errors.RadioError: + raise + except Exception, e: + LOG.exception('Unknown error during download process') + raise errors.RadioError("Failed to communicate with radio: %s" % e) + + def _do_download(self, start, end, blocksize): + # allocate & fill memory + image = "" + for i in range(start, end, blocksize): + req = chr(i / 256) + chr(i % 256) + chr(blocksize) + self._write_record(CMD_RD, req) + cs_error, resp = self._read_record() + if cs_error: + LOG.debug(util.hexprint(resp)) + raise Exception("Checksum error on read") + LOG.debug("Got:\n%s" % util.hexprint(resp)) + image += resp[2:] + if self.status_fn: + status = chirp_common.Status() + status.cur = i + status.max = end + status.msg = "Cloning from radio" + self.status_fn(status) + self._finish() + return memmap.MemoryMap(''.join(image)) + + def _upload(self): + """Talk to a wouxun KG-UV8D Plus and do a upload""" + try: + self._identify() + self._do_upload(0, 32768, 64) + except errors.RadioError: + raise + except Exception, e: + raise errors.RadioError("Failed to communicate with radio: %s" % e) + return + + def _do_upload(self, start, end, blocksize): + ptr = start + for i in range(start, end, blocksize): + req = chr(i / 256) + chr(i % 256) + chunk = self.get_mmap()[ptr:ptr + blocksize] + self._write_record(CMD_WR, req + chunk) + LOG.debug(util.hexprint(req + chunk)) + cserr, ack = self._read_record() + LOG.debug(util.hexprint(ack)) + j = ord(ack[0]) * 256 + ord(ack[1]) + if cserr or j != ptr: + raise Exception("Radio did not ack block %i" % ptr) + ptr += blocksize + if self.status_fn: + status = chirp_common.Status() + status.cur = i + status.max = end + status.msg = "Cloning to radio" + self.status_fn(status) + self._finish() + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.has_ctone = True + rf.has_rx_dtcs = True + rf.has_cross = True + rf.has_tuning_step = False + rf.has_bank = False + rf.can_odd_split = True + rf.valid_skips = ["", "S"] + rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] + rf.valid_cross_modes = [ + "Tone->Tone", + "Tone->DTCS", + "DTCS->Tone", + "DTCS->", + "->Tone", + "->DTCS", + "DTCS->DTCS", + ] + rf.valid_modes = ["FM", "NFM"] + rf.valid_power_levels = self.POWER_LEVELS + rf.valid_name_length = 8 + rf.valid_duplexes = ["", "-", "+", "split", "off"] + rf.valid_bands = [(134000000, 175000000), # supports 2m + (400000000, 520000000)] # supports 70cm + rf.valid_characters = chirp_common.CHARSET_ASCII + rf.memory_bounds = (1, 999) # 999 memories + return rf + + @classmethod + def get_prompts(cls): + rp = chirp_common.RadioPrompts() + rp.experimental = ("This radio driver is currently under development. " + "There are no known issues with it, but you should " + "proceed with caution.") + return rp + + def get_raw_memory(self, number): + return repr(self._memobj.memory[number]) + + def _get_tone(self, _mem, mem): + def _get_dcs(val): + code = int("%03o" % (val & 0x07FF)) + pol = (val & 0x8000) and "R" or "N" + return code, pol + + tpol = False + if _mem.txtone != 0xFFFF and (_mem.txtone & 0x2800) == 0x2800: + tcode, tpol = _get_dcs(_mem.txtone) + mem.dtcs = tcode + txmode = "DTCS" + elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0: + mem.rtone = (_mem.txtone & 0x7fff) / 10.0 + txmode = "Tone" + else: + txmode = "" + + rpol = False + if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x2800) == 0x2800: + rcode, rpol = _get_dcs(_mem.rxtone) + mem.rx_dtcs = rcode + rxmode = "DTCS" + elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0: + mem.ctone = (_mem.rxtone & 0x7fff) / 10.0 + rxmode = "Tone" + else: + rxmode = "" + + if txmode == "Tone" and not rxmode: + mem.tmode = "Tone" + elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone: + mem.tmode = "TSQL" + elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs: + mem.tmode = "DTCS" + elif rxmode or txmode: + mem.tmode = "Cross" + mem.cross_mode = "%s->%s" % (txmode, rxmode) + + # always set it even if no dtcs is used + mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N") + + LOG.debug("Got TX %s (%i) RX %s (%i)" % + (txmode, _mem.txtone, rxmode, _mem.rxtone)) + + def get_memory(self, number): + _mem = self._memobj.memory[number] + _nam = self._memobj.names[number] + + mem = chirp_common.Memory() + mem.number = number + _valid = self._memobj.valid[mem.number] + LOG.debug("%d %s", number, _valid == MEM_VALID) + if _valid != MEM_VALID: + mem.empty = True + return mem + else: + mem.empty = False + + mem.freq = int(_mem.rxfreq) * 10 + + if _mem.txfreq == 0xFFFFFFFF: + # TX freq not set + mem.duplex = "off" + mem.offset = 0 + elif int(_mem.rxfreq) == int(_mem.txfreq): + mem.duplex = "" + mem.offset = 0 + elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000: + mem.duplex = "split" + mem.offset = int(_mem.txfreq) * 10 + else: + mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+" + mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10 + + for char in _nam.name: + if char != 0: + mem.name += chr(char) + mem.name = mem.name.rstrip() + + self._get_tone(_mem, mem) + + mem.skip = "" if bool(_mem.scan_add) else "S" + + mem.power = self.POWER_LEVELS[_mem.power] + mem.mode = _mem.iswide and "FM" or "NFM" + return mem + + def _set_tone(self, mem, _mem): + def _set_dcs(code, pol): + val = int("%i" % code, 8) + 0x2800 + if pol == "R": + val += 0x8000 + return val + + rx_mode = tx_mode = None + rxtone = txtone = 0x0000 + + if mem.tmode == "Tone": + tx_mode = "Tone" + rx_mode = None + txtone = int(mem.rtone * 10) + 0x8000 + elif mem.tmode == "TSQL": + rx_mode = tx_mode = "Tone" + rxtone = txtone = int(mem.ctone * 10) + 0x8000 + elif mem.tmode == "DTCS": + tx_mode = rx_mode = "DTCS" + txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0]) + rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1]) + elif mem.tmode == "Cross": + tx_mode, rx_mode = mem.cross_mode.split("->") + if tx_mode == "DTCS": + txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0]) + elif tx_mode == "Tone": + txtone = int(mem.rtone * 10) + 0x8000 + if rx_mode == "DTCS": + rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1]) + elif rx_mode == "Tone": + rxtone = int(mem.ctone * 10) + 0x8000 + + _mem.rxtone = rxtone + _mem.txtone = txtone + + LOG.debug("Set TX %s (%i) RX %s (%i)" % + (tx_mode, _mem.txtone, rx_mode, _mem.rxtone)) + + def set_memory(self, mem): + number = mem.number + + _mem = self._memobj.memory[number] + _nam = self._memobj.names[number] + + if mem.empty: + _mem.set_raw("\x00" * (_mem.size() / 8)) + self._memobj.valid[number] = 0 + self._memobj.names[number].set_raw("\x00" * (_nam.size() / 8)) + return + + _mem.rxfreq = int(mem.freq / 10) + if mem.duplex == "off": + _mem.txfreq = 0xFFFFFFFF + elif mem.duplex == "split": + _mem.txfreq = int(mem.offset / 10) + elif mem.duplex == "off": + for i in range(0, 4): + _mem.txfreq[i].set_raw("\xFF") + elif mem.duplex == "+": + _mem.txfreq = int(mem.freq / 10) + int(mem.offset / 10) + elif mem.duplex == "-": + _mem.txfreq = int(mem.freq / 10) - int(mem.offset / 10) + else: + _mem.txfreq = int(mem.freq / 10) + _mem.scan_add = int(mem.skip != "S") + _mem.iswide = int(mem.mode == "FM") + # set the tone + self._set_tone(mem, _mem) + # set the scrambler and compander to off by default + _mem.scrambler = 0 + _mem.compander = 0 + # set the power + if mem.power: + _mem.power = self.POWER_LEVELS.index(mem.power) + else: + _mem.power = True + # set to mute mode to QT (not QT+DTMF or QT*DTMF) by default + _mem.mute_mode = 0 + + for i in range(0, len(_nam.name)): + if i < len(mem.name) and mem.name[i]: + _nam.name[i] = ord(mem.name[i]) + else: + _nam.name[i] = 0x0 + self._memobj.valid[mem.number] = MEM_VALID + + def _get_settings(self): + _settings = self._memobj.settings + _vfoa = self._memobj.vfoa + _vfob = self._memobj.vfob + cfg_grp = RadioSettingGroup("cfg_grp", "Configuration") + vfoa_grp = RadioSettingGroup("vfoa_grp", "VFO A Settings") + vfob_grp = RadioSettingGroup("vfob_grp", "VFO B Settings") + key_grp = RadioSettingGroup("key_grp", "Key Settings") + lmt_grp = RadioSettingGroup("lmt_grp", "Frequency Limits") + uhf_lmt_grp = RadioSettingGroup("uhf_lmt_grp", "UHF") + vhf_lmt_grp = RadioSettingGroup("vhf_lmt_grp", "VHF") + oem_grp = RadioSettingGroup("oem_grp", "OEM Info") + + lmt_grp.append(uhf_lmt_grp); + lmt_grp.append(vhf_lmt_grp); + group = RadioSettings(cfg_grp, vfoa_grp, vfob_grp, + key_grp, lmt_grp, oem_grp) + + # + # Configuration Settings + # + rs = RadioSetting("channel_menu", "Menu available in channel mode", + RadioSettingValueBoolean(_settings.channel_menu)) + cfg_grp.append(rs) + rs = RadioSetting("ponmsg", "Poweron message", + RadioSettingValueList( + PONMSG_LIST, PONMSG_LIST[_settings.ponmsg])) + cfg_grp.append(rs) + rs = RadioSetting("voice", "Voice Guide", + RadioSettingValueBoolean(_settings.voice)) + cfg_grp.append(rs) + rs = RadioSetting("language", "Language", + RadioSettingValueList(LANGUAGE_LIST, + LANGUAGE_LIST[_settings. + language])) + cfg_grp.append(rs) + rs = RadioSetting("timeout", "Timeout Timer", + RadioSettingValueList( + TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout])) + cfg_grp.append(rs) + rs = RadioSetting("toalarm", "Timeout Alarm", + RadioSettingValueInteger(0, 10, _settings.toalarm)) + cfg_grp.append(rs) + rs = RadioSetting("roger_beep", "Roger Beep", + RadioSettingValueList(ROGER_LIST, + ROGER_LIST[_settings.roger_beep])) + cfg_grp.append(rs) + rs = RadioSetting("power_save", "Power save", + RadioSettingValueBoolean(_settings.power_save)) + cfg_grp.append(rs) + rs = RadioSetting("autolock", "Autolock", + RadioSettingValueBoolean(_settings.autolock)) + cfg_grp.append(rs) + rs = RadioSetting("keylock", "Keypad Lock", + RadioSettingValueBoolean(_settings.keylock)) + cfg_grp.append(rs) + rs = RadioSetting("beep", "Keypad Beep", + RadioSettingValueBoolean(_settings.beep)) + cfg_grp.append(rs) + rs = RadioSetting("stopwatch", "Stopwatch", + RadioSettingValueBoolean(_settings.stopwatch)) + cfg_grp.append(rs) + rs = RadioSetting("backlight", "Backlight", + RadioSettingValueList(BACKLIGHT_LIST, + BACKLIGHT_LIST[_settings. + backlight])) + cfg_grp.append(rs) + rs = RadioSetting("dtmf_st", "DTMF Sidetone", + RadioSettingValueList(DTMFST_LIST, + DTMFST_LIST[_settings. + dtmf_st])) + cfg_grp.append(rs) + rs = RadioSetting("ani_sw", "ANI-ID Switch", + RadioSettingValueBoolean(_settings.ani_sw)) + cfg_grp.append(rs) + rs = RadioSetting("ptt_id", "PTT-ID Delay", + RadioSettingValueList(PTTID_LIST, + PTTID_LIST[_settings.ptt_id])) + cfg_grp.append(rs) + rs = RadioSetting("ring_time", "Ring Time", + RadioSettingValueList(LIST_10, + LIST_10[_settings.ring_time])) + cfg_grp.append(rs) + rs = RadioSetting("scan_rev", "Scan Mode", + RadioSettingValueList(SCANMODE_LIST, + SCANMODE_LIST[_settings. + scan_rev])) + cfg_grp.append(rs) + rs = RadioSetting("vox", "VOX", + RadioSettingValueList(LIST_10, + LIST_10[_settings.vox])) + cfg_grp.append(rs) + rs = RadioSetting("prich_sw", "Priority Channel Switch", + RadioSettingValueBoolean(_settings.prich_sw)) + cfg_grp.append(rs) + rs = RadioSetting("pri_ch", "Priority Channel", + RadioSettingValueInteger(1, 999, _settings.pri_ch)) + cfg_grp.append(rs) + rs = RadioSetting("rpt_mode", "Radio Mode", + RadioSettingValueList(RPTMODE_LIST, + RPTMODE_LIST[_settings. + rpt_mode])) + cfg_grp.append(rs) + rs = RadioSetting("rpt_set", "Repeater Setting", + RadioSettingValueList(RPTSET_LIST, + RPTSET_LIST[_settings. + rpt_set])) + cfg_grp.append(rs) + rs = RadioSetting("rpt_spk", "Repeater Mode Speaker", + RadioSettingValueBoolean(_settings.rpt_spk)) + cfg_grp.append(rs) + rs = RadioSetting("rpt_ptt", "Repeater PTT", + RadioSettingValueBoolean(_settings.rpt_ptt)) + cfg_grp.append(rs) + rs = RadioSetting("dtmf_tx_time", "DTMF Tx Duration", + RadioSettingValueList(DTMF_TIMES, + DTMF_TIMES[_settings. + dtmf_tx_time])) + cfg_grp.append(rs) + rs = RadioSetting("dtmf_interval", "DTMF Interval", + RadioSettingValueList(DTMF_TIMES, + DTMF_TIMES[_settings. + dtmf_interval])) + cfg_grp.append(rs) + rs = RadioSetting("alert", "Alert Tone", + RadioSettingValueList(ALERTS_LIST, + ALERTS_LIST[_settings.alert])) + cfg_grp.append(rs) + rs = RadioSetting("rpt_tone", "Repeater Tone", + RadioSettingValueBoolean(_settings.rpt_tone)) + cfg_grp.append(rs) + rs = RadioSetting("rpt_hold", "Repeater Hold Time", + RadioSettingValueList(HOLD_TIMES, + HOLD_TIMES[_settings. + rpt_hold])) + cfg_grp.append(rs) + rs = RadioSetting("scan_det", "Scan DET", + RadioSettingValueBoolean(_settings.scan_det)) + cfg_grp.append(rs) + rs = RadioSetting("sc_qt", "SC-QT", + RadioSettingValueList(SCQT_LIST, + SCQT_LIST[_settings.sc_qt])) + cfg_grp.append(rs) + rs = RadioSetting("smuteset", "SubFreq Mute", + RadioSettingValueList(SMUTESET_LIST, + SMUTESET_LIST[_settings. + smuteset])) + cfg_grp.append(rs) + + # + # VFO A Settings + # + rs = RadioSetting("workmode_a", "VFO A Workmode", + RadioSettingValueList(WORKMODE_LIST, WORKMODE_LIST[_settings.workmode_a])) + vfoa_grp.append(rs) + rs = RadioSetting("work_cha", "VFO A Channel", + RadioSettingValueInteger(1, 999, _settings.work_cha)) + vfoa_grp.append(rs) + rs = RadioSetting("vfoa.rxfreq", "VFO A Rx Frequency", + RadioSettingValueInteger( + 134000000, 520000000, _vfoa.rxfreq * 10, 5000)) + vfoa_grp.append(rs) + rs = RadioSetting("vfoa.txoffset", "VFO A Tx Offset", + RadioSettingValueInteger( + 0, 520000000, _vfoa.txoffset * 10, 5000)) + vfoa_grp.append(rs) + # u16 rxtone; + # u16 txtone; + rs = RadioSetting("vfoa.power", "VFO A Power", + RadioSettingValueList( + POWER_LIST, POWER_LIST[_vfoa.power])) + vfoa_grp.append(rs) + # shift_dir:2 + rs = RadioSetting("vfoa.iswide", "VFO A NBFM", + RadioSettingValueList( + BANDWIDTH_LIST, BANDWIDTH_LIST[_vfoa.iswide])) + vfoa_grp.append(rs) + rs = RadioSetting("vfoa.mute_mode", "VFO A Mute", + RadioSettingValueList( + SPMUTE_LIST, SPMUTE_LIST[_vfoa.mute_mode])) + vfoa_grp.append(rs) + rs = RadioSetting("vfoa.step", "VFO A Step (kHz)", + RadioSettingValueList( + STEP_LIST, STEP_LIST[_vfoa.step])) + vfoa_grp.append(rs) + rs = RadioSetting("vfoa.squelch", "VFO A Squelch", + RadioSettingValueList( + LIST_10, LIST_10[_vfoa.squelch])) + vfoa_grp.append(rs) + rs = RadioSetting("bcl_a", "Busy Channel Lock-out A", + RadioSettingValueBoolean(_settings.bcl_a)) + vfoa_grp.append(rs) + + # + # VFO B Settings + # + rs = RadioSetting("workmode_b", "VFO B Workmode", + RadioSettingValueList(WORKMODE_LIST, WORKMODE_LIST[_settings.workmode_b])) + vfob_grp.append(rs) + rs = RadioSetting("work_chb", "VFO B Channel", + RadioSettingValueInteger(1, 999, _settings.work_chb)) + vfob_grp.append(rs) + rs = RadioSetting("vfob.rxfreq", "VFO B Rx Frequency", + RadioSettingValueInteger( + 134000000, 520000000, _vfob.rxfreq * 10, 5000)) + vfob_grp.append(rs) + rs = RadioSetting("vfob.txoffset", "VFO B Tx Offset", + RadioSettingValueInteger( + 0, 520000000, _vfob.txoffset * 10, 5000)) + vfob_grp.append(rs) + # u16 rxtone; + # u16 txtone; + rs = RadioSetting("vfob.power", "VFO B Power", + RadioSettingValueList( + POWER_LIST, POWER_LIST[_vfob.power])) + vfob_grp.append(rs) + # shift_dir:2 + rs = RadioSetting("vfob.iswide", "VFO B NBFM", + RadioSettingValueList( + BANDWIDTH_LIST, BANDWIDTH_LIST[_vfob.iswide])) + vfob_grp.append(rs) + rs = RadioSetting("vfob.mute_mode", "VFO B Mute", + RadioSettingValueList( + SPMUTE_LIST, SPMUTE_LIST[_vfob.mute_mode])) + vfob_grp.append(rs) + rs = RadioSetting("vfob.step", "VFO B Step (kHz)", + RadioSettingValueList( + STEP_LIST, STEP_LIST[_vfob.step])) + vfob_grp.append(rs) + rs = RadioSetting("vfob.squelch", "VFO B Squelch", + RadioSettingValueList( + LIST_10, LIST_10[_vfob.squelch])) + vfob_grp.append(rs) + rs = RadioSetting("bcl_b", "Busy Channel Lock-out B", + RadioSettingValueBoolean(_settings.bcl_b)) + vfob_grp.append(rs) + + # + # Key Settings + # + _msg = str(_settings.dispstr).split("\0")[0] + val = RadioSettingValueString(0, 15, _msg) + val.set_mutable(True) + rs = RadioSetting("dispstr", "Display Message", val) + key_grp.append(rs) + + dtmfchars = "0123456789" + _codeobj = _settings.ani_code + _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x0A]) + val = RadioSettingValueString(3, 6, _code, False) + val.set_charset(dtmfchars) + rs = RadioSetting("ani_code", "ANI Code", val) + def apply_ani_id(setting, obj): + value = [] + for j in range(0, 6): + try: + value.append(dtmfchars.index(str(setting.value)[j])) + except IndexError: + value.append(0xFF) + obj.ani_code = value + rs.set_apply_callback(apply_ani_id, _settings) + key_grp.append(rs) + + rs = RadioSetting("pf1_func", "PF1 Key function", + RadioSettingValueList( + PF1KEY_LIST, + PF1KEY_LIST[_settings.pf1_func])) + key_grp.append(rs) + rs = RadioSetting("pf3_func", "PF3 Key function", + RadioSettingValueList( + PF3KEY_LIST, + PF3KEY_LIST[_settings.pf3_func])) + key_grp.append(rs) + + # + # Limits settings + # + rs = RadioSetting("uhf_limits.rx_start", "UHF RX Lower Limit", + RadioSettingValueInteger( + 400000000, 520000000, + self._memobj.uhf_limits.rx_start * 10, 5000)) + uhf_lmt_grp.append(rs) + rs = RadioSetting("uhf_limits.rx_stop", "UHF RX Upper Limit", + RadioSettingValueInteger( + 400000000, 520000000, + self._memobj.uhf_limits.rx_stop * 10, 5000)) + uhf_lmt_grp.append(rs) + rs = RadioSetting("uhf_limits.tx_start", "UHF TX Lower Limit", + RadioSettingValueInteger( + 400000000, 520000000, + self._memobj.uhf_limits.tx_start * 10, 5000)) + uhf_lmt_grp.append(rs) + rs = RadioSetting("uhf_limits.tx_stop", "UHF TX Upper Limit", + RadioSettingValueInteger( + 400000000, 520000000, + self._memobj.uhf_limits.tx_stop * 10, 5000)) + uhf_lmt_grp.append(rs) + rs = RadioSetting("vhf_limits.rx_start", "VHF RX Lower Limit", + RadioSettingValueInteger( + 134000000, 174997500, + self._memobj.vhf_limits.rx_start * 10, 5000)) + vhf_lmt_grp.append(rs) + rs = RadioSetting("vhf_limits.rx_stop", "VHF RX Upper Limit", + RadioSettingValueInteger( + 134000000, 174997500, + self._memobj.vhf_limits.rx_stop * 10, 5000)) + vhf_lmt_grp.append(rs) + rs = RadioSetting("vhf_limits.tx_start", "VHF TX Lower Limit", + RadioSettingValueInteger( + 134000000, 174997500, + self._memobj.vhf_limits.tx_start * 10, 5000)) + vhf_lmt_grp.append(rs) + rs = RadioSetting("vhf_limits.tx_stop", "VHF TX Upper Limit", + RadioSettingValueInteger( + 134000000, 174997500, + self._memobj.vhf_limits.tx_stop * 10, 5000)) + vhf_lmt_grp.append(rs) + + # + # OEM info + # + def _decode(lst): + _str = ''.join([chr(c) for c in lst + if chr(c) in chirp_common.CHARSET_ASCII]) + return _str + + def do_nothing(setting, obj): + return + + _str = _decode(self._memobj.oem_info.model) + val = RadioSettingValueString(0, 15, _str) + val.set_mutable(False) + rs = RadioSetting("oem_info.model", "Model", val) + rs.set_apply_callback(do_nothing, _settings) + oem_grp.append(rs) + _str = _decode(self._memobj.oem_info.oem1) + val = RadioSettingValueString(0, 15, _str) + val.set_mutable(False) + rs = RadioSetting("oem_info.oem1", "OEM String 1", val) + rs.set_apply_callback(do_nothing, _settings) + oem_grp.append(rs) + _str = _decode(self._memobj.oem_info.oem2) + val = RadioSettingValueString(0, 15, _str) + val.set_mutable(False) + rs = RadioSetting("oem_info.oem2", "OEM String 2", val) + rs.set_apply_callback(do_nothing, _settings) + oem_grp.append(rs) + _str = _decode(self._memobj.oem_info.version) + val = RadioSettingValueString(0, 15, _str) + val.set_mutable(False) + rs = RadioSetting("oem_info.version", "Software Version", val) + rs.set_apply_callback(do_nothing, _settings) + oem_grp.append(rs) + _str = _decode(self._memobj.oem_info.date) + val = RadioSettingValueString(0, 15, _str) + val.set_mutable(False) + rs = RadioSetting("oem_info.date", "OEM Date", val) + rs.set_apply_callback(do_nothing, _settings) + oem_grp.append(rs) + + return group + + def get_settings(self): + try: + return self._get_settings() + except: + import traceback + LOG.error("Failed to parse settings: %s", traceback.format_exc()) + return None + + def set_settings(self, settings): + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + continue + else: + try: + if "." in element.get_name(): + bits = element.get_name().split(".") + obj = self._memobj + for bit in bits[:-1]: + obj = getattr(obj, bit) + setting = bits[-1] + else: + obj = self._memobj.settings + setting = element.get_name() + + if element.has_apply_callback(): + LOG.debug("Using apply callback") + element.run_apply_callback() + else: + LOG.debug("Setting %s = %s" % (setting, element.value)) + if self._is_freq(element): + setattr(obj, setting, int(element.value)/10) + else: + setattr(obj, setting, element.value) + except Exception, e: + LOG.debug(element.get_name()) + raise + + def _is_freq(self, element): + return "rxfreq" in element.get_name() or "txoffset" in element.get_name() or "rx_start" in element.get_name() or "rx_stop" in element.get_name() or "tx_start" in element.get_name() or "tx_stop" in element.get_name()
\ No newline at end of file diff --git a/chirp/drivers/leixen.py b/chirp/drivers/leixen.py index 74225d4..16402f5 100644 --- a/chirp/drivers/leixen.py +++ b/chirp/drivers/leixen.py @@ -973,11 +973,14 @@ class JetstreamJT270MHRadio(LeixenVV898Radio): _file_ident = "Leixen" _model_ident = 'LX-\x89\x85\x85' _ranges = [(0x0C00, 0x2000)] - _mem_formatter = {'unknownormode': 'unknown6:1', - 'modeorpower': 'mode:1, power:1', + _mem_formatter = {'unknownormode': 'mode:1', + 'modeorpower': 'power:2', 'chanstart': 0x0C00, - 'namestart': 0x1930, + 'namestart': 0x1900, 'defaults': 6} + _power_levels = [chirp_common.PowerLevel("Low", watts=5), + chirp_common.PowerLevel("Mid", watts=10), + chirp_common.PowerLevel("High", watts=25)] def get_features(self): rf = super(JetstreamJT270MHRadio, self).get_features() diff --git a/chirp/drivers/lt725uv.py b/chirp/drivers/lt725uv.py index 2940cbb..ca4461f 100644 --- a/chirp/drivers/lt725uv.py +++ b/chirp/drivers/lt725uv.py @@ -1,6 +1,6 @@ # Copyright 2016: # * Jim Unroe KC9HI, <rock.unroe@gmail.com> -# +# Modified for Baojie BJ-218: 2018 by Rick DeWitt (RJD), <aa0rd@yahoo.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 @@ -26,15 +26,15 @@ from chirp import bitwise, errors, util from chirp.settings import RadioSettingGroup, RadioSetting, \ RadioSettingValueBoolean, RadioSettingValueList, \ RadioSettingValueString, RadioSettingValueInteger, \ - RadioSettingValueFloat, RadioSettings + RadioSettingValueFloat, RadioSettings,InvalidValueError from textwrap import dedent MEM_FORMAT = """ #seekto 0x0200; struct { - u8 unknown1; + u8 init_bank; u8 volume; - u8 unknown2[2]; + u16 fm_freq; u8 wtled; u8 rxled; u8 txled; @@ -43,16 +43,87 @@ struct { u8 ring; u8 bcl; u8 tot; + u16 sig_freq; + u16 dtmf_txms; + u8 init_sql; + u8 rptr_mode; } settings; +#seekto 0x0240; +struct { + u8 dtmf1_cnt; + u8 dtmf1[7]; + u8 dtmf2_cnt; + u8 dtmf2[7]; + u8 dtmf3_cnt; + u8 dtmf3[7]; + u8 dtmf4_cnt; + u8 dtmf4[7]; + u8 dtmf5_cnt; + u8 dtmf5[7]; + u8 dtmf6_cnt; + u8 dtmf6[7]; + u8 dtmf7_cnt; + u8 dtmf7[7]; + u8 dtmf8_cnt; + u8 dtmf8[7]; +} dtmf_tab; + +#seekto 0x0280; +struct { + u8 native_id_cnt; + u8 native_id_code[7]; + u8 master_id_cnt; + u8 master_id_code[7]; + u8 alarm_cnt; + u8 alarm_code[5]; + u8 id_disp_cnt; + u8 id_disp_code[5]; + u8 revive_cnt; + u8 revive_code[5]; + u8 stun_cnt; + u8 stun_code[5]; + u8 kill_cnt; + u8 kill_code[5]; + u8 monitor_cnt; + u8 monitor_code[5]; + u8 state_now; +} codes; + +#seekto 0x02d0; +struct { + u8 hello1_cnt; + char hello1[7]; + u8 hello2_cnt; + char hello2[7]; + u32 vhf_low; + u32 vhf_high; + u32 uhf_low; + u32 uhf_high; + u8 lims_on; +} hello_lims; + struct vfo { - u8 unknown1[2]; + u8 frq_chn_mode; + u8 chan_num; u32 rxfreq; - u8 unknown2[8]; - u8 power; - u8 unknown3[3]; - u24 offset; - u32 step; + u16 is_rxdigtone:1, + rxdtcs_pol:1, + rx_tone:14; + u8 rx_mode; + u8 unknown_ff; + u16 is_txdigtone:1, + txdtcs_pol:1, + tx_tone:14; + u8 launch_sig; + u8 tx_end_sig; + u8 bpower; + u8 fm_bw; + u8 cmp_nder; + u8 scrm_blr; + u8 shift; + u32 offset; + u16 step; u8 sql; }; @@ -84,8 +155,7 @@ struct mem { scrambler:1 unknown:4; u8 namelen; - u8 name[6]; - u8 unused; + u8 name[7]; }; #seekto 0x0400; @@ -94,22 +164,70 @@ struct mem upper_memory[128]; #seekto 0x1000; struct mem lower_memory[128]; +#seekto 0x1C00; +struct { + char mod_num[6]; +} mod_id; """ MEM_SIZE = 0x1C00 BLOCK_SIZE = 0x40 STIMEOUT = 2 +# Channel power: 2 levels +POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5.00), + chirp_common.PowerLevel("High", watts=30.00)] -LIST_RECVMODE = ["", "QT/DQT", "QT/DQT + Signaling"] +LIST_RECVMODE = ["QT/DQT", "QT/DQT + Signaling"] LIST_SIGNAL = ["Off"] + ["DTMF%s" % x for x in range(1, 9)] + \ ["DTMF%s + Identity" % x for x in range(1, 9)] + \ ["Identity code"] -LIST_POWER = ["Low", "Mid", "High"] +# Band Power settings, can be different than channel power +LIST_BPOWER = ["Low", "Mid", "High"] # Tri-power models LIST_COLOR = ["Off", "Orange", "Blue", "Purple"] LIST_LEDSW = ["Auto", "On"] -LIST_RING = ["Off"] + ["%s seconds" % x for x in range(1, 10)] -LIST_TIMEOUT = ["Off"] + ["%s seconds" % x for x in range(30, 630, 30)] - +LIST_RING = ["Off"] + ["%s" % x for x in range(1, 10)] +LIST_TDR_DEF = ["A-Upper", "B-Lower"] +LIST_TIMEOUT = ["Off"] + ["%s" % x for x in range(30, 630, 30)] +LIST_VFOMODE = ["Frequency Mode", "Channel Mode"] +# Tones are numeric, Defined in \chirp\chirp_common.py +TONES_CTCSS = sorted(chirp_common.TONES) +# Converted to strings +LIST_CTCSS = ["Off"] + [str(x) for x in TONES_CTCSS] +# Now append the DxxxN and DxxxI DTCS codes from chirp_common +for x in chirp_common.DTCS_CODES: + LIST_CTCSS.append("D{:03d}N".format(x)) +for x in chirp_common.DTCS_CODES: + LIST_CTCSS.append("D{:03d}R".format(x)) +LIST_BW = ["Narrow", "Wide"] +LIST_SHIFT = ["Off"," + ", " - "] +STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0] +LIST_STEPS = [str(x) for x in STEPS] +LIST_STATE = ["Normal", "Stun", "Kill"] +LIST_SSF = ["1000", "1450", "1750", "2100"] +LIST_DTMFTX = ["50", "100", "150", "200", "300","500"] + +SETTING_LISTS = { +"init_bank": LIST_TDR_DEF , +"tot": LIST_TIMEOUT, +"wtled": LIST_COLOR, +"rxled": LIST_COLOR, +"txled": LIST_COLOR, +"sig_freq": LIST_SSF, +"dtmf_txms": LIST_DTMFTX, +"ledsw": LIST_LEDSW, +"frq_chn_mode": LIST_VFOMODE, +"rx_tone": LIST_CTCSS, +"tx_tone": LIST_CTCSS, +"rx_mode": LIST_RECVMODE, +"launch_sig": LIST_SIGNAL, +"tx_end_sig": LIST_SIGNAL, +"bpower":LIST_BPOWER, +"fm_bw": LIST_BW, +"shift": LIST_SHIFT, +"step": LIST_STEPS, +"ring": LIST_RING, +"state_now": LIST_STATE +} def _clean_buffer(radio): radio.pipe.timeout = 0.005 @@ -131,7 +249,7 @@ def _rawrecv(radio, amount): if len(data) != amount: _exit_program_mode(radio) - msg = "Error reading data from radio: not the amount of data we want." + msg = "Error reading from radio: not the amount of data we want." raise errors.RadioError(msg) return data @@ -148,10 +266,10 @@ def _rawsend(radio, data): def _make_frame(cmd, addr, length, data=""): """Pack the info in the headder format""" frame = struct.pack(">4sHH", cmd, addr, length) - # add the data if set + # Add the data if set if len(data) != 0: frame += data - # return the data + # Return the data return frame @@ -169,12 +287,12 @@ def _recv(radio, addr, length): def _do_ident(radio): """Put the radio in PROGRAM mode & identify it""" - # set the serial discipline + # Set the serial discipline radio.pipe.baudrate = 19200 radio.pipe.parity = "N" radio.pipe.timeout = STIMEOUT - # flush input buffer + # Flush input buffer _clean_buffer(radio) magic = "PROM_LIN" @@ -199,7 +317,7 @@ def _exit_program_mode(radio): def _download(radio): """Get the memory map""" - # put radio in program mode and identify it + # Put radio in program mode and identify it _do_ident(radio) # UI progress @@ -216,13 +334,13 @@ def _download(radio): LOG.info("Request sent:") LOG.debug(util.hexprint(frame)) - # sending the read request + # Sending the read request _rawsend(radio, frame) - # now we read + # Now we read d = _recv(radio, addr, BLOCK_SIZE) - # aggregate the data + # Aggregate the data data += d # UI Update @@ -232,7 +350,7 @@ def _download(radio): _exit_program_mode(radio) - data += "LT-725UV" + data += radio.MODEL.ljust(8) return data @@ -240,7 +358,7 @@ def _download(radio): def _upload(radio): """Upload procedure""" - # put radio in program mode and identify it + # Put radio in program mode and identify it _do_ident(radio) # UI progress @@ -250,16 +368,16 @@ def _upload(radio): status.msg = "Cloning to radio..." radio.status_fn(status) - # the fun starts here + # The fun starts here for addr in range(0, MEM_SIZE, BLOCK_SIZE): - # sending the data + # Sending the data data = radio.get_mmap()[addr:addr + BLOCK_SIZE] frame = _make_frame("WRIE", addr, BLOCK_SIZE, data) _rawsend(radio, frame) - # receiving the response + # Receiving the response ack = _rawrecv(radio, 1) if ack != "\x06": _exit_program_mode(radio) @@ -276,57 +394,64 @@ def _upload(radio): def model_match(cls, data): """Match the opened/downloaded image to the correct version""" - rid = data[0x1C00:0x1C08] - - if rid == cls.MODEL: - return True - - return False + if len(data) == 0x1C08: + rid = data[0x1C00:0x1C08] + return rid.startswith(cls.MODEL) + else: + return False def _split(rf, f1, f2): """Returns False if the two freqs are in the same band (no split) or True otherwise""" - # determine if the two freqs are in the same band + # Determine if the two freqs are in the same band for low, high in rf.valid_bands: if f1 >= low and f1 <= high and \ f2 >= low and f2 <= high: - # if the two freqs are on the same Band this is not a split + # If the two freqs are on the same Band this is not a split return False - # if you get here is because the freq pairs are split + # If you get here is because the freq pairs are split return True @directory.register -class LT725UV(chirp_common.CloneModeRadio, - chirp_common.ExperimentalRadio): +class LT725UV(chirp_common.CloneModeRadio): """LUITON LT-725UV Radio""" VENDOR = "LUITON" MODEL = "LT-725UV" MODES = ["NFM", "FM"] TONES = chirp_common.TONES DTCS_CODES = sorted(chirp_common.DTCS_CODES + [645]) - NAME_LENGTH = 6 + NAME_LENGTH = 7 DTMF_CHARS = list("0123456789ABCD*#") VALID_BANDS = [(136000000, 176000000), (400000000, 480000000)] - # valid chars on the LCD + # Valid chars on the LCD VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \ "`{|}!\"#$%&'()*+,-./:;<=>?@[]^_" @classmethod def get_prompts(cls): rp = chirp_common.RadioPrompts() - rp.experimental = \ - ('The LT725UV driver is a beta version.\n' - '\n' - 'Please save an unedited copy of your first successful\n' - 'download to a CHIRP Radio Images(*.img) file.' + rp.info = \ + ('Some notes about POWER settings:\n' + '- The individual channel power settings are ignored' + ' by the radio.\n' + ' They are allowed to be set (and downloaded) in hopes of' + ' a future firmware update.\n' + '- Power settings done \'Live\' in the radio apply to the' + ' entire upper or lower band.\n' + '- Tri-power radio models will set and download the three' + ' band-power' + ' levels, but they are converted to just Low and High at' + ' upload.' + ' The Mid setting reverts to Low.' ) + rp.pre_download = _(dedent("""\ Follow this instructions to download your info: @@ -373,6 +498,7 @@ class LT725UV(chirp_common.CloneModeRadio, "->Tone", "DTCS->DTCS"] rf.valid_skips = [] + rf.valid_power_levels = POWER_LEVELS rf.valid_name_length = self.NAME_LENGTH rf.valid_dtcs_codes = self.DTCS_CODES rf.valid_bands = self.VALID_BANDS @@ -459,11 +585,11 @@ class LT725UV(chirp_common.CloneModeRadio, if _mem.rxtone == 0x3FFF: rxmode = "" elif _mem.is_rxdigtone == 0: - # ctcss + # CTCSS rxmode = "Tone" mem.ctone = int(_mem.rxtone) / 10.0 else: - # digital + # Digital rxmode = "DTCS" mem.rx_dtcs = self._get_dcs(_mem.rxtone) if _mem.rxdtcs_pol == 1: @@ -472,11 +598,11 @@ class LT725UV(chirp_common.CloneModeRadio, if _mem.txtone == 0x3FFF: txmode = "" elif _mem.is_txdigtone == 0: - # ctcss + # CTCSS txmode = "Tone" mem.rtone = int(_mem.txtone) / 10.0 else: - # digital + # Digital txmode = "DTCS" mem.dtcs = self._get_dcs(_mem.txtone) if _mem.txdtcs_pol == 1: @@ -494,7 +620,9 @@ class LT725UV(chirp_common.CloneModeRadio, mem.dtcs_polarity = "".join(dtcs_pol) - mem.mode = self.MODES[_mem.wide] + mem.mode = _mem.wide and "FM" or "NFM" + + mem.power = POWER_LEVELS[_mem.power] # Extra mem.extra = RadioSettingGroup("extra", "Extra") @@ -504,8 +632,8 @@ class LT725UV(chirp_common.CloneModeRadio, else: val = _mem.recvmode recvmode = RadioSetting("recvmode", "Receiving mode", - RadioSettingValueList(LIST_RECVMODE, - LIST_RECVMODE[val])) + RadioSettingValueList(LIST_RECVMODE, + LIST_RECVMODE[val])) mem.extra.append(recvmode) if _mem.botsignal == 0xFF: @@ -521,17 +649,17 @@ class LT725UV(chirp_common.CloneModeRadio, val = 0x00 else: val = _mem.eotsignal - eotsignal = RadioSetting("eotsignal", "Transmit end signaling", - RadioSettingValueList(LIST_SIGNAL, - LIST_SIGNAL[val])) + + rx = RadioSettingValueList(LIST_SIGNAL, LIST_SIGNAL[val]) + eotsignal = RadioSetting("eotsignal", "Transmit end signaling", rx) mem.extra.append(eotsignal) - compandor = RadioSetting("compandor", "Compandor", - RadioSettingValueBoolean(bool(_mem.compandor))) + rx = RadioSettingValueBoolean(bool(_mem.compandor)) + compandor = RadioSetting("compandor", "Compandor", rx) mem.extra.append(compandor) - scrambler = RadioSetting("scrambler", "Scrambler", - RadioSettingValueBoolean(bool(_mem.scrambler))) + rx = RadioSettingValueBoolean(bool(_mem.scrambler)) + scrambler = RadioSetting("scrambler", "Scrambler", rx) mem.extra.append(scrambler) return mem @@ -615,89 +743,623 @@ class LT725UV(chirp_common.CloneModeRadio, _mem.txtone = self._set_dcs(mem.dtcs) _mem.wide = self.MODES.index(mem.mode) + _mem.power = mem.power == POWER_LEVELS[1] - # extra settings + # Extra settings for setting in mem.extra: setattr(_mem, setting.get_name(), setting.value) def get_settings(self): """Translate the bit in the mem_struct into settings in the UI""" - _mem = self._memobj - basic = RadioSettingGroup("basic", "Basic Settings") - top = RadioSettings(basic) + # Define mem struct write-back shortcuts + _sets = self._memobj.settings + _vfoa = self._memobj.upper.vfoa + _vfob = self._memobj.lower.vfob + _lims = self._memobj.hello_lims + _codes = self._memobj.codes + _dtmf = self._memobj.dtmf_tab - # Basic + basic = RadioSettingGroup("basic", "Basic Settings") + a_band = RadioSettingGroup("a_band", "VFO A-Upper Settings") + b_band = RadioSettingGroup("b_band", "VFO B-Lower Settings") + codes = RadioSettingGroup("codes", "Codes & DTMF Groups") + lims = RadioSettingGroup("lims", "PowerOn & Freq Limits") + group = RadioSettings(basic, a_band, b_band, lims, codes) + + # Basic Settings + bnd_mode = RadioSetting("settings.init_bank", "TDR Band Default", + RadioSettingValueList(LIST_TDR_DEF, + LIST_TDR_DEF[ _sets.init_bank])) + basic.append(bnd_mode) volume = RadioSetting("settings.volume", "Volume", - RadioSettingValueInteger(0, 20, - _mem.settings.volume)) + RadioSettingValueInteger(0, 20, _sets.volume)) basic.append(volume) - powera = RadioSetting("upper.vfoa.power", "Power (Upper)", - RadioSettingValueList(LIST_POWER, LIST_POWER[ - _mem.upper.vfoa.power])) + val = _vfoa.bpower # 2bits values 0,1,2= Low, Mid, High + rx = RadioSettingValueList(LIST_BPOWER, LIST_BPOWER[val]) + powera = RadioSetting("upper.vfoa.bpower", "Power (Upper)", rx) basic.append(powera) - powerb = RadioSetting("lower.vfob.power", "Power (Lower)", - RadioSettingValueList(LIST_POWER, LIST_POWER[ - _mem.lower.vfob.power])) + val = _vfob.bpower + rx = RadioSettingValueList(LIST_BPOWER, LIST_BPOWER[val]) + powerb = RadioSetting("lower.vfob.bpower", "Power (Lower)", rx) basic.append(powerb) + def my_word2raw(setting, obj, atrb, mlt=10): + """Callback function to convert UI floating value to u16 int""" + if str(setting.value) == "Off": + frq = 0x0FFFF + else: + frq = int(float(str(setting.value)) * float(mlt)) + if frq == 0: + frq = 0xFFFF + setattr(obj, atrb, frq) + return + + def my_adjraw(setting, obj, atrb, fix): + """Callback: add or subtract fix from value.""" + vx = int(str(setting.value)) + value = vx + int(fix) + if value < 0: + value = 0 + if atrb == "frq_chn_mode" and int(str(setting.value)) == 2: + value = vx * 2 # Special handling for frq_chn_mode + setattr(obj, atrb, value) + return + + def my_dbl2raw(setting, obj, atrb, flg=1): + """Callback: convert from freq 146.7600 to 14760000 U32.""" + value = chirp_common.parse_freq(str(setting.value)) / 10 + # flg=1 means 0 becomes ff, else leave as possible 0 + if flg == 1 and value == 0: + value = 0xFFFFFFFF + setattr(obj, atrb, value) + return + + def my_val_list(setting, obj, atrb): + """Callback:from ValueList with non-sequential, actual values.""" + value = int(str(setting.value)) # Get the integer value + if atrb == "tot": + value = int(value / 30) # 30 second increments + setattr(obj, atrb, value) + return + + def my_spcl(setting, obj, atrb): + """Callback: Special handling based on atrb.""" + if atrb == "frq_chn_mode": + idx = LIST_VFOMODE.index (str(setting.value)) # Returns 0 or 1 + value = idx * 2 # Set bit 1 + setattr(obj, atrb, value) + return + + def my_tone_strn(obj, is_atr, pol_atr, tone_atr): + """Generate the CTCS/DCS tone code string.""" + vx = int(getattr(obj, tone_atr)) + if vx == 16383 or vx == 0: + return "Off" # 16383 is all bits set + if getattr(obj, is_atr) == 0: # Simple CTCSS code + tstr = str(vx / 10.0) + else: # DCS + if getattr(obj, pol_atr) == 0: + tstr = "D{:03x}R".format(vx) + else: + tstr = "D{:03x}N".format(vx) + return tstr + + def my_set_tone(setting, obj, is_atr, pol_atr, tone_atr): + """Callback- create the tone setting from string code.""" + sx = str(setting.value) # '131.8' or 'D231N' or 'Off' + if sx == "Off": + isx = 1 + polx = 1 + tonx = 0x3FFF + elif sx[0] == "D": # DCS + isx = 1 + if sx[4] == "N": + polx = 1 + else: + polx = 0 + tonx = int(sx[1:4], 16) + else: # CTCSS + isx = 0 + polx = 0 + tonx = int(float(sx) * 10.0) + setattr(obj, is_atr, isx) + setattr(obj, pol_atr, polx) + setattr(obj, tone_atr, tonx) + return + + val = _sets.fm_freq / 10.0 + if val == 0: + val = 88.9 # 0 is not valid + rx = RadioSettingValueFloat(65, 108.0, val, 0.1, 1) + rs = RadioSetting("settings.fm_freq", "FM Broadcast Freq (MHz)", rx) + rs.set_apply_callback(my_word2raw, _sets, "fm_freq") + basic.append(rs) + wtled = RadioSetting("settings.wtled", "Standby LED Color", RadioSettingValueList(LIST_COLOR, LIST_COLOR[ - _mem.settings.wtled])) + _sets.wtled])) basic.append(wtled) rxled = RadioSetting("settings.rxled", "RX LED Color", RadioSettingValueList(LIST_COLOR, LIST_COLOR[ - _mem.settings.rxled])) + _sets.rxled])) basic.append(rxled) txled = RadioSetting("settings.txled", "TX LED Color", RadioSettingValueList(LIST_COLOR, LIST_COLOR[ - _mem.settings.txled])) + _sets.txled])) basic.append(txled) ledsw = RadioSetting("settings.ledsw", "Back light mode", RadioSettingValueList(LIST_LEDSW, LIST_LEDSW[ - _mem.settings.ledsw])) + _sets.ledsw])) basic.append(ledsw) beep = RadioSetting("settings.beep", "Beep", - RadioSettingValueBoolean(bool(_mem.settings.beep))) + RadioSettingValueBoolean(bool(_sets.beep))) basic.append(beep) ring = RadioSetting("settings.ring", "Ring", RadioSettingValueList(LIST_RING, LIST_RING[ - _mem.settings.ring])) + _sets.ring])) basic.append(ring) bcl = RadioSetting("settings.bcl", "Busy channel lockout", - RadioSettingValueBoolean(bool(_mem.settings.bcl))) + RadioSettingValueBoolean(bool(_sets.bcl))) basic.append(bcl) - tot = RadioSetting("settings.tot", "Timeout Timer", - RadioSettingValueList(LIST_TIMEOUT, LIST_TIMEOUT[ - _mem.settings.tot])) - basic.append(tot) - - if _mem.upper.vfoa.sql == 0xFF: + if _vfoa.sql == 0xFF: val = 0x04 else: - val = _mem.upper.vfoa.sql + val = _vfoa.sql sqla = RadioSetting("upper.vfoa.sql", "Squelch (Upper)", RadioSettingValueInteger(0, 9, val)) basic.append(sqla) - if _mem.lower.vfob.sql == 0xFF: + if _vfob.sql == 0xFF: val = 0x04 else: - val = _mem.lower.vfob.sql + val = _vfob.sql sqlb = RadioSetting("lower.vfob.sql", "Squelch (Lower)", RadioSettingValueInteger(0, 9, val)) basic.append(sqlb) - return top + tmp = str(int(_sets.tot) * 30) # 30 sec step counter + rs = RadioSetting("settings.tot", "Transmit Timeout (Secs)", + RadioSettingValueList(LIST_TIMEOUT, tmp)) + rs.set_apply_callback(my_val_list, _sets, "tot") + basic.append(rs) + + tmp = str(int(_sets.sig_freq)) + rs = RadioSetting("settings.sig_freq", "Single Signaling Tone (Htz)", + RadioSettingValueList(LIST_SSF, tmp)) + rs.set_apply_callback(my_val_list, _sets, "sig_freq") + basic.append(rs) + + tmp = str(int(_sets.dtmf_txms)) + rs = RadioSetting("settings.dtmf_txms", "DTMF Tx Duration (mSecs)", + RadioSettingValueList(LIST_DTMFTX, tmp)) + rs.set_apply_callback(my_val_list, _sets, "dtmf_txms") + basic.append(rs) + + rs = RadioSetting("settings.rptr_mode", "Repeater Mode", + RadioSettingValueBoolean(bool(_sets.rptr_mode))) + basic.append(rs) + + # UPPER BAND SETTINGS + + # Freq Mode, convert bit 1 state to index pointer + val = _vfoa.frq_chn_mode / 2 + + rx = RadioSettingValueList(LIST_VFOMODE, LIST_VFOMODE[val]) + rs = RadioSetting("upper.vfoa.frq_chn_mode", "Default Mode", rx) + rs.set_apply_callback(my_spcl, _vfoa, "frq_chn_mode") + a_band.append(rs) + + val =_vfoa.chan_num + 1 # Add 1 for 1-128 displayed + rs = RadioSetting("upper.vfoa.chan_num", "Initial Chan", + RadioSettingValueInteger(1, 128, val)) + rs.set_apply_callback(my_adjraw, _vfoa, "chan_num", -1) + a_band.append(rs) + + val = _vfoa.rxfreq / 100000.0 + if (val < 136.0 or val > 176.0): + val = 146.520 # 2m calling + rs = RadioSetting("upper.vfoa.rxfreq ", "Default Recv Freq (MHz)", + RadioSettingValueFloat(136.0, 176.0, val, 0.001, 5)) + rs.set_apply_callback(my_dbl2raw, _vfoa, "rxfreq") + a_band.append(rs) + + tmp = my_tone_strn(_vfoa, "is_rxdigtone", "rxdtcs_pol", "rx_tone") + rs = RadioSetting("rx_tone", "Default Recv CTCSS (Htz)", + RadioSettingValueList(LIST_CTCSS, tmp)) + rs.set_apply_callback(my_set_tone, _vfoa, "is_rxdigtone", + "rxdtcs_pol", "rx_tone") + a_band.append(rs) + + rx = RadioSettingValueList(LIST_RECVMODE, + LIST_RECVMODE[_vfoa.rx_mode]) + rs = RadioSetting("upper.vfoa.rx_mode", "Default Recv Mode", rx) + a_band.append(rs) + + tmp = my_tone_strn(_vfoa, "is_txdigtone", "txdtcs_pol", "tx_tone") + rs = RadioSetting("tx_tone", "Default Xmit CTCSS (Htz)", + RadioSettingValueList(LIST_CTCSS, tmp)) + rs.set_apply_callback(my_set_tone, _vfoa, "is_txdigtone", + "txdtcs_pol", "tx_tone") + a_band.append(rs) + + rs = RadioSetting("upper.vfoa.launch_sig", "Launch Signaling", + RadioSettingValueList(LIST_SIGNAL, + LIST_SIGNAL[_vfoa.launch_sig])) + a_band.append(rs) + + rx = RadioSettingValueList(LIST_SIGNAL,LIST_SIGNAL[_vfoa.tx_end_sig]) + rs = RadioSetting("upper.vfoa.tx_end_sig", "Xmit End Signaling", rx) + a_band.append(rs) + + rx = RadioSettingValueList(LIST_BW, LIST_BW[_vfoa.fm_bw]) + rs = RadioSetting("upper.vfoa.fm_bw", "Wide/Narrow Band", rx) + a_band.append(rs) + + rx = RadioSettingValueBoolean(bool(_vfoa.cmp_nder)) + rs = RadioSetting("upper.vfoa.cmp_nder", "Compandor", rx) + a_band.append(rs) + + rs = RadioSetting("upper.vfoa.scrm_blr", "Scrambler", + RadioSettingValueBoolean(bool(_vfoa.scrm_blr))) + a_band.append(rs) + + rx = RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[_vfoa.shift]) + rs = RadioSetting("upper.vfoa.shift", "Xmit Shift", rx) + a_band.append(rs) + + val = _vfoa.offset / 100000.0 + rs = RadioSetting("upper.vfoa.offset", "Xmit Offset (MHz)", + RadioSettingValueFloat(0, 100.0, val, 0.001, 3)) + # Allow zero value + rs.set_apply_callback(my_dbl2raw, _vfoa, "offset", 0) + a_band.append(rs) + + tmp = str(_vfoa.step / 100.0) + rs = RadioSetting("step", "Freq step (KHz)", + RadioSettingValueList(LIST_STEPS, tmp)) + rs.set_apply_callback(my_word2raw, _vfoa,"step", 100) + a_band.append(rs) + + # LOWER BAND SETTINGS + + val = _vfob.frq_chn_mode / 2 + rx = RadioSettingValueList(LIST_VFOMODE, LIST_VFOMODE[val]) + rs = RadioSetting("lower.vfob.frq_chn_mode", "Default Mode", rx) + rs.set_apply_callback(my_spcl, _vfob, "frq_chn_mode") + b_band.append(rs) + + val = _vfob.chan_num + 1 + rs = RadioSetting("lower.vfob.chan_num", "Initial Chan", + RadioSettingValueInteger(0, 127, val)) + rs.set_apply_callback(my_adjraw, _vfob, "chan_num", -1) + b_band.append(rs) + + val = _vfob.rxfreq / 100000.0 + if (val < 400.0 or val > 480.0): + val = 446.0 # UHF calling + rs = RadioSetting("lower.vfob.rxfreq ", "Default Recv Freq (MHz)", + RadioSettingValueFloat(400.0, 480.0, val, 0.001, 5)) + rs.set_apply_callback(my_dbl2raw, _vfob, "rxfreq") + b_band.append(rs) + + tmp = my_tone_strn(_vfob, "is_rxdigtone", "rxdtcs_pol", "rx_tone") + rs = RadioSetting("rx_tone", "Default Recv CTCSS (Htz)", + RadioSettingValueList(LIST_CTCSS, tmp)) + rs.set_apply_callback(my_set_tone, _vfob, "is_rxdigtone", + "rxdtcs_pol", "rx_tone") + b_band.append(rs) + + rx = RadioSettingValueList(LIST_RECVMODE, LIST_RECVMODE[_vfob.rx_mode]) + rs = RadioSetting("lower.vfob.rx_mode", "Default Recv Mode", rx) + b_band.append(rs) + + tmp = my_tone_strn(_vfob, "is_txdigtone", "txdtcs_pol", "tx_tone") + rs = RadioSetting("tx_tone", "Default Xmit CTCSS (Htz)", + RadioSettingValueList(LIST_CTCSS, tmp)) + rs.set_apply_callback(my_set_tone, _vfob, "is_txdigtone", + "txdtcs_pol", "tx_tone") + b_band.append(rs) + + rx = RadioSettingValueList(LIST_SIGNAL,LIST_SIGNAL[_vfob.launch_sig]) + rs = RadioSetting("lower.vfob.launch_sig", "Launch Signaling", rx) + b_band.append(rs) + + rx = RadioSettingValueList(LIST_SIGNAL,LIST_SIGNAL[_vfob.tx_end_sig]) + rs = RadioSetting("lower.vfob.tx_end_sig", "Xmit End Signaling", rx) + b_band.append(rs) + + rx = RadioSettingValueList(LIST_BW, LIST_BW[_vfob.fm_bw]) + rs = RadioSetting("lower.vfob.fm_bw", "Wide/Narrow Band", rx) + b_band.append(rs) + + rs = RadioSetting("lower.vfob.cmp_nder", "Compandor", + RadioSettingValueBoolean(bool(_vfob.cmp_nder))) + b_band.append(rs) + + rs = RadioSetting("lower.vfob.scrm_blr", "Scrambler", + RadioSettingValueBoolean(bool(_vfob.scrm_blr))) + b_band.append(rs) + + rx = RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[_vfob.shift]) + rs = RadioSetting("lower.vfob.shift", "Xmit Shift", rx) + b_band.append(rs) + + val = _vfob.offset / 100000.0 + rs = RadioSetting("lower.vfob.offset", "Xmit Offset (MHz)", + RadioSettingValueFloat(0, 100.0, val, 0.001, 3)) + rs.set_apply_callback(my_dbl2raw, _vfob, "offset", 0) + b_band.append(rs) + + tmp = str(_vfob.step / 100.0) + rs = RadioSetting("step", "Freq step (KHz)", + RadioSettingValueList(LIST_STEPS, tmp)) + rs.set_apply_callback(my_word2raw, _vfob, "step", 100) + b_band.append(rs) + + # PowerOn & Freq Limits Settings + + def chars2str(cary, knt): + """Convert raw memory char array to a string: NOT a callback.""" + stx = "" + for char in cary[:knt]: + stx += chr(char) + return stx + + def my_str2ary(setting, obj, atrba, atrbc): + """Callback: convert 7-char string to char array with count.""" + ary = "" + knt = 7 + for j in range (6, -1, -1): # Strip trailing spaces + if str(setting.value)[j] == "" or str(setting.value)[j] == " ": + knt = knt - 1 + else: + break + for j in range(0, 7, 1): + if j < knt: ary += str(setting.value)[j] + else: ary += chr(0xFF) + setattr(obj, atrba, ary) + setattr(obj, atrbc, knt) + return + + tmp = chars2str(_lims.hello1, _lims.hello1_cnt) + rs = RadioSetting("hello_lims.hello1", "Power-On Message 1", + RadioSettingValueString(0, 7, tmp)) + rs.set_apply_callback(my_str2ary, _lims, "hello1", "hello1_cnt") + lims.append(rs) + + tmp = chars2str(_lims.hello2, _lims.hello2_cnt) + rs = RadioSetting("hello_lims.hello2", "Power-On Message 2", + RadioSettingValueString(0, 7, tmp)) + rs.set_apply_callback(my_str2ary, _lims,"hello2", "hello2_cnt") + lims.append(rs) + + # VALID_BANDS = [(136000000, 176000000),400000000, 480000000)] + + lval = _lims.vhf_low / 100000.0 + uval = _lims.vhf_high / 100000.0 + if lval >= uval: + lval = 144.0 + uval = 158.0 + + rs = RadioSetting("hello_lims.vhf_low", "Lower VHF Band Limit (MHz)", + RadioSettingValueFloat(136.0, 176.0, lval, 0.001, 3)) + rs.set_apply_callback(my_dbl2raw, _lims, "vhf_low") + lims.append(rs) + + rs = RadioSetting("hello_lims.vhf_high", "Upper VHF Band Limit (MHz)", + RadioSettingValueFloat(136.0, 176.0, uval, 0.001, 3)) + rs.set_apply_callback(my_dbl2raw, _lims, "vhf_high") + lims.append(rs) + + lval = _lims.uhf_low / 100000.0 + uval = _lims.uhf_high / 100000.0 + if lval >= uval: + lval = 420.0 + uval = 470.0 + + rs = RadioSetting("hello_lims.uhf_low", "Lower UHF Band Limit (MHz)", + RadioSettingValueFloat(400.0, 480.0, lval, 0.001, 3)) + rs.set_apply_callback(my_dbl2raw, _lims, "uhf_low") + lims.append(rs) + + rs = RadioSetting("hello_lims.uhf_high", "Upper UHF Band Limit (MHz)", + RadioSettingValueFloat(400.0, 480.0, uval, 0.001, 3)) + rs.set_apply_callback(my_dbl2raw, _lims, "uhf_high") + lims.append(rs) + + # Codes and DTMF Groups Settings + + def make_dtmf(ary, knt): + """Generate the DTMF code 1-8, NOT a callback.""" + tmp = "" + if knt > 0 and knt != 0xff: + for val in ary[:knt]: + if val > 0 and val <= 9: + tmp += chr(val + 48) + elif val == 0x0a: + tmp += "0" + elif val == 0x0d: + tmp += "A" + elif val == 0x0e: + tmp += "B" + elif val == 0x0f: + tmp += "C" + elif val == 0x00: + tmp += "D" + elif val == 0x0b: + tmp += "*" + elif val == 0x0c: + tmp += "#" + else: + msg = ("Invalid Character. Must be: 0-9,A,B,C,D,*,#") + raise InvalidValueError(msg) + return tmp + + def my_dtmf2raw(setting, obj, atrba, atrbc, syz=7): + """Callback: DTMF Code; sends 5 or 7-byte string.""" + draw = [] + knt = syz + for j in range (syz - 1, -1, -1): # Strip trailing spaces + if str(setting.value)[j] == "" or str(setting.value)[j] == " ": + knt = knt - 1 + else: + break + for j in range(0, syz): + bx = str(setting.value)[j] + obx = ord(bx) + dig = 0x0ff + if j < knt and knt > 0: # (Else) is pads + if bx == "0": + dig = 0x0a + elif bx == "A": + dig = 0x0d + elif bx == "B": + dig = 0x0e + elif bx == "C": + dig = 0x0f + elif bx == "D": + dig = 0x00 + elif bx == "*": + dig = 0x0b + elif bx == "#": + dig = 0x0c + elif obx >= 49 and obx <= 57: + dig = obx - 48 + else: + msg = ("Must be: 0-9,A,B,C,D,*,#") + raise InvalidValueError(msg) + # - End if/elif/else for bx + # - End if J<=knt + draw.append(dig) # Generate string of bytes + # - End for j + setattr(obj, atrba, draw) + setattr(obj, atrbc, knt) + return + + tmp = make_dtmf(_codes.native_id_code, _codes.native_id_cnt) + rs = RadioSetting("codes.native_id_code", "Native ID Code", + RadioSettingValueString(0, 7, tmp)) + rs.set_apply_callback(my_dtmf2raw, _codes, "native_id_code", + "native_id_cnt", 7) + codes.append(rs) + + tmp = make_dtmf(_codes.master_id_code, _codes.master_id_cnt) + rs = RadioSetting("codes.master_id_code", "Master Control ID Code", + RadioSettingValueString(0, 7, tmp)) + rs.set_apply_callback(my_dtmf2raw, _codes, "master_id_code", + "master_id_cnt",7) + codes.append(rs) + + tmp = make_dtmf(_codes.alarm_code, _codes.alarm_cnt) + rs = RadioSetting("codes.alarm_code", "Alarm Code", + RadioSettingValueString(0, 5, tmp)) + rs.set_apply_callback(my_dtmf2raw, _codes, "alarm_code", + "alarm_cnt", 5) + codes.append(rs) + + tmp = make_dtmf(_codes.id_disp_code, _codes.id_disp_cnt) + rs = RadioSetting("codes.id_disp_code", "Identify Display Code", + RadioSettingValueString(0, 5, tmp)) + rs.set_apply_callback(my_dtmf2raw, _codes, "id_disp_code", + "id_disp_cnt", 5) + codes.append(rs) + + tmp = make_dtmf(_codes.revive_code, _codes.revive_cnt) + rs = RadioSetting("codes.revive_code", "Revive Code", + RadioSettingValueString(0, 5, tmp)) + rs.set_apply_callback(my_dtmf2raw, _codes,"revive_code", + "revive_cnt", 5) + codes.append(rs) + + tmp = make_dtmf(_codes.stun_code, _codes.stun_cnt) + rs = RadioSetting("codes.stun_code", "Remote Stun Code", + RadioSettingValueString(0, 5, tmp)) + rs.set_apply_callback(my_dtmf2raw, _codes, "stun_code", + "stun_cnt", 5) + codes.append(rs) + + tmp = make_dtmf(_codes.kill_code, _codes.kill_cnt) + rs = RadioSetting("codes.kill_code", "Remote KILL Code", + RadioSettingValueString(0, 5, tmp)) + rs.set_apply_callback(my_dtmf2raw, _codes, "kill_code", + "kill_cnt", 5) + codes.append(rs) + + tmp = make_dtmf(_codes.monitor_code, _codes.monitor_cnt) + rs = RadioSetting("codes.monitor_code", "Monitor Code", + RadioSettingValueString(0, 5, tmp)) + rs.set_apply_callback(my_dtmf2raw, _codes, "monitor_code", + "monitor_cnt", 5) + codes.append(rs) + + val = _codes.state_now + if val > 2: + val = 0 + + rx = RadioSettingValueList(LIST_STATE, LIST_STATE[val]) + rs = RadioSetting("codes.state_now", "Current State", rx) + codes.append(rs) + + dtm = make_dtmf(_dtmf.dtmf1, _dtmf.dtmf1_cnt) + rs = RadioSetting("dtmf_tab.dtmf1", "DTMF1 String", + RadioSettingValueString(0, 7, dtm)) + rs.set_apply_callback(my_dtmf2raw, _dtmf, "dtmf1", "dtmf1_cnt") + codes.append(rs) + + dtm = make_dtmf(_dtmf.dtmf2, _dtmf.dtmf2_cnt) + rs = RadioSetting("dtmf_tab.dtmf2", "DTMF2 String", + RadioSettingValueString(0, 7, dtm)) + rs.set_apply_callback(my_dtmf2raw, _dtmf, "dtmf2", "dtmf2_cnt") + codes.append(rs) + + dtm = make_dtmf(_dtmf.dtmf3, _dtmf.dtmf3_cnt) + rs = RadioSetting("dtmf_tab.dtmf3", "DTMF3 String", + RadioSettingValueString(0, 7, dtm)) + rs.set_apply_callback(my_dtmf2raw, _dtmf, "dtmf3", "dtmf3_cnt") + codes.append(rs) + + dtm = make_dtmf(_dtmf.dtmf4, _dtmf.dtmf4_cnt) + rs = RadioSetting("dtmf_tab.dtmf4", "DTMF4 String", + RadioSettingValueString(0, 7, dtm)) + rs.set_apply_callback(my_dtmf2raw, _dtmf, "dtmf4", "dtmf4_cnt") + codes.append(rs) + + dtm = make_dtmf(_dtmf.dtmf5, _dtmf.dtmf5_cnt) + rs = RadioSetting("dtmf_tab.dtmf5", "DTMF5 String", + RadioSettingValueString(0, 7, dtm)) + rs.set_apply_callback(my_dtmf2raw, _dtmf, "dtmf5", "dtmf5_cnt") + codes.append(rs) + + dtm = make_dtmf(_dtmf.dtmf6, _dtmf.dtmf6_cnt) + rs = RadioSetting("dtmf_tab.dtmf6", "DTMF6 String", + RadioSettingValueString(0, 7, dtm)) + rs.set_apply_callback(my_dtmf2raw, _dtmf, "dtmf6", "dtmf6_cnt") + codes.append(rs) + + dtm = make_dtmf(_dtmf.dtmf7, _dtmf.dtmf7_cnt) + rs = RadioSetting("dtmf_tab.dtmf7", "DTMF7 String", + RadioSettingValueString(0, 7, dtm)) + rs.set_apply_callback(my_dtmf2raw, _dtmf, "dtmf7", "dtmf7_cnt") + codes.append(rs) + + dtm = make_dtmf(_dtmf.dtmf8, _dtmf.dtmf8_cnt) + rs = RadioSetting("dtmf_tab.dtmf8", "DTMF8 String", + RadioSettingValueString(0, 7, dtm)) + rs.set_apply_callback(my_dtmf2raw, _dtmf, "dtmf8", "dtmf8_cnt") + codes.append(rs) + + return group # END get_settings() + def set_settings(self, settings): _settings = self._memobj.settings @@ -740,11 +1402,11 @@ class LT725UV(chirp_common.CloneModeRadio, match_size = False match_model = False - # testing the file data size + # Testing the file data size if len(filedata) == MEM_SIZE + 8: match_size = True - # testing the firmware model fingerprint + # Testing the firmware model fingerprint match_model = model_match(cls, filedata) if match_size and match_model: @@ -761,3 +1423,23 @@ class LT725UVUpper(LT725UV): class LT725UVLower(LT725UV): VARIANT = "Lower" _vfo = "lower" + + +class Zastone(chirp_common.Alias): + """Declare BJ-218 alias for Zastone BJ-218.""" + VENDOR = "Zastone" + MODEL = "BJ-218" + + +class Hesenate(chirp_common.Alias): + """Declare BJ-218 alias for Hesenate BJ-218.""" + VENDOR = "Hesenate" + MODEL = "BJ-218" + + +@directory.register +class Baojie218(LT725UV): + """Baojie BJ-218""" + VENDOR = "Baojie" + MODEL = "BJ-218" + ALIASES = [Zastone, Hesenate, ] diff --git a/chirp/drivers/mursv1.py b/chirp/drivers/mursv1.py new file mode 100644 index 0000000..31fac7e --- /dev/null +++ b/chirp/drivers/mursv1.py @@ -0,0 +1,874 @@ +# Copyright 2018: +# * Jim Unroe KC9HI, <rock.unroe@gmail.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import time +import struct +import logging +import re + +LOG = logging.getLogger(__name__) + +from chirp.drivers import baofeng_common +from chirp import chirp_common, directory, memmap +from chirp import bitwise, errors, util +from chirp.settings import RadioSettingGroup, RadioSetting, \ + RadioSettingValueBoolean, RadioSettingValueList, \ + RadioSettingValueString, RadioSettingValueInteger, \ + RadioSettingValueFloat, RadioSettings, \ + InvalidValueError +from textwrap import dedent + +##### MAGICS ######################################################### + +# BTECH MURS-V1 magic string +MSTRING_MURSV1 = "\x50\x5F\x20\x15\x12\x15\x4D" + +##### ID strings ##################################################### + +# BTECH MURS-V1 +MURSV1_fp1 = "USM2402" + +DTMF_CHARS = "0123456789 *#ABCD" + +LIST_AB = ["A", "B"] +LIST_ALMOD = ["Off", "Site", "Tone", "Code"] +LIST_BANDWIDTH = ["Wide", "Narrow"] +LIST_COLOR = ["Off", "Blue", "Orange", "Purple"] +LIST_DTMFSPEED = ["%s ms" % x for x in range(50, 2010, 10)] +LIST_DTMFST = ["Off", "DT-ST", "ANI-ST", "DT+ANI"] +LIST_MODE = ["Channel", "Name", "Frequency"] +LIST_OFF1TO9 = ["Off"] + list("123456789") +LIST_OFF1TO10 = LIST_OFF1TO9 + ["10"] +LIST_OFFAB = ["Off"] + LIST_AB +LIST_RESUME = ["TO", "CO", "SE"] +LIST_PONMSG = ["Full", "Message"] +LIST_PTTID = ["Off", "BOT", "EOT", "Both"] +LIST_SCODE = ["%s" % x for x in range(1, 16)] +LIST_RPSTE = ["Off"] + ["%s" % x for x in range(1, 11)] +LIST_RTONE = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"] +LIST_SAVE = ["Off", "1:1", "1:2", "1:3", "1:4"] +LIST_SHIFTD = ["Off", "+", "-"] +LIST_STEDELAY = ["Off"] + ["%s ms" % x for x in range(100, 1100, 100)] +LIST_TIMEOUT = ["%s sec" % x for x in range(15, 615, 15)] +LIST_TXPOWER = ["High", "Low"] +LIST_VOICE = ["Off", "English", "Chinese"] +LIST_WORKMODE = ["Frequency", "Channel"] + +MURS_FREQS = [151.820, 151.880, 151.940, 154.570, 154.600] * 3 +FM_MODE = [3, 4, 8, 9, 13, 14] + +def model_match(cls, data): + """Match the opened/downloaded image to the correct version""" + rid = data[0x1EF0:0x1EF7] + + if rid in cls._fileid: + return True + + return False + + +@directory.register +class MURSV1(baofeng_common.BaofengCommonHT): + """BTech MURS-V1""" + VENDOR = "BTECH" + MODEL = "MURS-V1" + + _fileid = [MURSV1_fp1, ] + + _magic = [MSTRING_MURSV1, ] + _magic_response_length = 8 + _fw_ver_start = 0x1EF0 + _recv_block_size = 0x40 + _mem_size = 0x2000 + _ack_block = True + + _ranges = [(0x0000, 0x0DF0), + (0x0E00, 0x1800), + (0x1EE0, 0x1EF0), + (0x1F60, 0x1F70), + (0x1F80, 0x1F90), + (0x1FC0, 0x1FD0)] + _send_block_size = 0x10 + + MODES = ["NFM", "FM"] + VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \ + "!@#$%^&*()+-=[]:\";'<>?,./" + LENGTH_NAME = 7 + SKIP_VALUES = ["", "S"] + DTCS_CODES = sorted(chirp_common.DTCS_CODES + [645]) + POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.00), + chirp_common.PowerLevel("Low", watts=.50)] + VALID_BANDS = [(151820000, 154600250)] + PTTID_LIST = LIST_PTTID + SCODE_LIST = LIST_SCODE + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.has_bank = False + rf.has_tuning_step = False + rf.can_odd_split = False + rf.has_name = True + rf.has_offset = False + 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.valid_modes = self.MODES + rf.valid_characters = self.VALID_CHARS + rf.valid_name_length = self.LENGTH_NAME + rf.valid_duplexes = [] + rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross'] + rf.valid_cross_modes = [ + "Tone->Tone", + "DTCS->", + "->DTCS", + "Tone->DTCS", + "DTCS->Tone", + "->Tone", + "DTCS->DTCS"] + rf.valid_skips = self.SKIP_VALUES + rf.valid_dtcs_codes = self.DTCS_CODES + rf.memory_bounds = (1, 15) + rf.valid_power_levels = self.POWER_LEVELS + rf.valid_bands = self.VALID_BANDS + + return rf + + + MEM_FORMAT = """ + #seekto 0x0010; + struct { + lbcd rxfreq[4]; + lbcd txfreq[4]; + ul16 rxtone; + ul16 txtone; + u8 unknown0:4, + scode:4; + u8 unknown1; + u8 unknown2:7, + lowpower:1; + u8 unknown3:1, + wide:1, + unknown4:2, + bcl:1, + scan:1, + pttid:2; + } memory[15]; + + #seekto 0x0B00; + struct { + u8 code[5]; + u8 unused[11]; + } pttid[15]; + + #seekto 0x0CAA; + struct { + u8 code[5]; + u8 unused1:6, + aniid:2; + u8 unknown[2]; + u8 dtmfon; + u8 dtmfoff; + } ani; + + #seekto 0x0E20; + struct { + u8 unused01:4, + squelch:4; + u8 unused02; + u8 unused03; + u8 unused04:5, + save:3; + u8 unused05:4, + vox:4; + u8 unused06; + u8 unused07:4, + abr:4; + u8 unused08:7, + tdr:1; + u8 unused09:7, + beep:1; + u8 unused10:2, + timeout:6; + u8 unused11[4]; + u8 unused12:6, + voice:2; + u8 unused13; + u8 unused14:6, + dtmfst:2; + u8 unused15; + u8 unused16:6, + screv:2; + u8 unused17:6, + pttid:2; + u8 unused18:2, + pttlt:6; + u8 unused19:6, + mdfa:2; + u8 unused20:6, + mdfb:2; + u8 unused21; + u8 unused22:7, + sync:1; + u8 unused23[4]; + u8 unused24:6, + wtled:2; + u8 unused25:6, + rxled:2; + u8 unused26:6, + txled:2; + u8 unused27:6, + almod:2; + u8 unused28:7, + dbptt:1; + u8 unused29:6, + tdrab:2; + u8 unused30:7, + ste:1; + u8 unused31:4, + rpste:4; + u8 unused32:4, + rptrl:4; + u8 unused33:7, + ponmsg:1; + u8 unused34:7, + roger:1; + u8 unused35:6, + rtone:2; + u8 unused36; + u8 unused37:6, + rogerrx:2; + u8 unused38; + u8 displayab:1, + unknown1:2, + fmradio:1, + alarm:1, + unknown2:1, + reset:1, + menu:1; + u8 unused39; + u8 workmode; + u8 keylock; + u8 cht; + } settings; + + #seekto 0x0E76; + struct { + u8 unused1:1, + mrcha:7; + u8 unused2:1, + mrchb:7; + } wmchannel; + + #seekto 0x0F4E; + u16 fm_presets; + + #seekto 0x1010; + struct { + char name[7]; + u8 unknown1[9]; + } names[15]; + + #seekto 0x1ED0; + struct { + char line1[7]; + char line2[7]; + } sixpoweron_msg; + + #seekto 0x1EE0; + struct { + char line1[7]; + char line2[7]; + } poweron_msg; + + #seekto 0x1EF0; + struct { + char line1[7]; + char line2[7]; + } firmware_msg; + + struct squelch { + u8 sql0; + u8 sql1; + u8 sql2; + u8 sql3; + u8 sql4; + u8 sql5; + u8 sql6; + u8 sql7; + u8 sql8; + u8 sql9; + }; + + #seekto 0x1F60; + struct { + struct squelch vhf; + } squelch; + + """ + + @classmethod + def get_prompts(cls): + rp = chirp_common.RadioPrompts() + rp.experimental = \ + ('The BTech MURS-V1 driver is a beta version.\n' + '\n' + 'Please save an unedited copy of your first successful\n' + 'download to a CHIRP Radio Images(*.img) file.' + ) + rp.pre_download = _(dedent("""\ + Follow these instructions to download your info: + + 1 - Turn off your radio + 2 - Connect your interface cable + 3 - Turn on your radio + 4 - Do the download of your radio data + """)) + rp.pre_upload = _(dedent("""\ + Follow this instructions to upload your info: + + 1 - Turn off your radio + 2 - Connect your interface cable + 3 - Turn on your radio + 4 - Do the upload of your radio data + """)) + return rp + + def process_mmap(self): + """Process the mem map into the mem object""" + self._memobj = bitwise.parse(self.MEM_FORMAT, self._mmap) + + def _get_mem(self, number): + return self._memobj.memory[number - 1] + + def _get_nam(self, number): + return self._memobj.names[number - 1] + + def get_memory(self, number): + _mem = self._get_mem(number) + _nam = self._get_nam(number) + + mem = chirp_common.Memory() + mem.number = number + + mem.freq = int(_mem.rxfreq) * 10 + + for char in _nam.name: + if str(char) == "\xFF": + char = " " # The OEM software may have 0xFF mid-name + mem.name += str(char) + mem.name = mem.name.rstrip() + + dtcs_pol = ["N", "N"] + + if _mem.txtone in [0, 0xFFFF]: + txmode = "" + elif _mem.txtone >= 0x0258: + txmode = "Tone" + mem.rtone = int(_mem.txtone) / 10.0 + elif _mem.txtone <= 0x0258: + txmode = "DTCS" + if _mem.txtone > 0x69: + index = _mem.txtone - 0x6A + dtcs_pol[0] = "R" + else: + index = _mem.txtone - 1 + mem.dtcs = self.DTCS_CODES[index] + else: + LOG.warn("Bug: txtone is %04x" % _mem.txtone) + + if _mem.rxtone in [0, 0xFFFF]: + rxmode = "" + elif _mem.rxtone >= 0x0258: + rxmode = "Tone" + mem.ctone = int(_mem.rxtone) / 10.0 + elif _mem.rxtone <= 0x0258: + rxmode = "DTCS" + if _mem.rxtone >= 0x6A: + index = _mem.rxtone - 0x6A + dtcs_pol[1] = "R" + else: + index = _mem.rxtone - 1 + mem.rx_dtcs = self.DTCS_CODES[index] + else: + LOG.warn("Bug: rxtone is %04x" % _mem.rxtone) + + if txmode == "Tone" and not rxmode: + mem.tmode = "Tone" + elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone: + mem.tmode = "TSQL" + elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs: + mem.tmode = "DTCS" + elif rxmode or txmode: + mem.tmode = "Cross" + mem.cross_mode = "%s->%s" % (txmode, rxmode) + + mem.dtcs_polarity = "".join(dtcs_pol) + + if not _mem.scan: + mem.skip = "S" + + levels = self.POWER_LEVELS + try: + mem.power = levels[_mem.lowpower] + except IndexError: + LOG.error("Radio reported invalid power level %s (in %s)" % + (_mem.power, levels)) + mem.power = levels[0] + + mem.mode = _mem.wide and "FM" or "NFM" + + mem.extra = RadioSettingGroup("Extra", "extra") + + rs = RadioSetting("bcl", "BCL", + RadioSettingValueBoolean(_mem.bcl)) + mem.extra.append(rs) + + rs = RadioSetting("pttid", "PTT ID", + RadioSettingValueList(self.PTTID_LIST, + self.PTTID_LIST[_mem.pttid])) + mem.extra.append(rs) + + rs = RadioSetting("scode", "S-CODE", + RadioSettingValueList(self.SCODE_LIST, + self.SCODE_LIST[_mem.scode])) + mem.extra.append(rs) + + return mem + + def _set_mem(self, number): + return self._memobj.memory[number - 1] + + def _set_nam(self, number): + return self._memobj.names[number - 1] + + def validate_memory(self, mem): + msgs = baofeng_common.BaofengCommonHT.validate_memory(self, mem) + + if mem.freq != int(MURS_FREQS[mem.number - 1] * 1000000): + msgs.append(chirp_common.ValidationError( + 'Memory location cannot change frequency')) + + if mem.mode == "FM" and (mem.number - 1) not in FM_MODE: + msgs.append(chirp_common.ValidationError( + 'Memory location only supports NFM')) + + return msgs + + def set_memory(self, mem): + _mem = self._set_mem(mem.number) + _nam = self._set_nam(mem.number) + + _namelength = self.get_features().valid_name_length + for i in range(_namelength): + try: + _nam.name[i] = mem.name[i] + except IndexError: + _nam.name[i] = "\xFF" + + rxmode = txmode = "" + if mem.tmode == "Tone": + _mem.txtone = int(mem.rtone * 10) + _mem.rxtone = 0 + elif mem.tmode == "TSQL": + _mem.txtone = int(mem.ctone * 10) + _mem.rxtone = int(mem.ctone * 10) + elif mem.tmode == "DTCS": + rxmode = txmode = "DTCS" + _mem.txtone = self.DTCS_CODES.index(mem.dtcs) + 1 + _mem.rxtone = self.DTCS_CODES.index(mem.dtcs) + 1 + elif mem.tmode == "Cross": + txmode, rxmode = mem.cross_mode.split("->", 1) + if txmode == "Tone": + _mem.txtone = int(mem.rtone * 10) + elif txmode == "DTCS": + _mem.txtone = self.DTCS_CODES.index(mem.dtcs) + 1 + else: + _mem.txtone = 0 + if rxmode == "Tone": + _mem.rxtone = int(mem.ctone * 10) + elif rxmode == "DTCS": + _mem.rxtone = self.DTCS_CODES.index(mem.rx_dtcs) + 1 + else: + _mem.rxtone = 0 + else: + _mem.rxtone = 0 + _mem.txtone = 0 + + if txmode == "DTCS" and mem.dtcs_polarity[0] == "R": + _mem.txtone += 0x69 + if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R": + _mem.rxtone += 0x69 + + _mem.scan = mem.skip != "S" + _mem.wide = mem.mode == "FM" + + if mem.power: + _mem.lowpower = self.POWER_LEVELS.index(mem.power) + else: + _mem.lowpower = 0 + + # extra settings + if len(mem.extra) > 0: + # there are setting, parse + for setting in mem.extra: + setattr(_mem, setting.get_name(), setting.value) + else: + # there are no extra settings, load defaults + _mem.bcl = 0 + _mem.pttid = 0 + _mem.scode = 0 + + def get_settings(self): + """Translate the bit in the mem_struct into settings in the UI""" + _mem = self._memobj + basic = RadioSettingGroup("basic", "Basic Settings") + advanced = RadioSettingGroup("advanced", "Advanced Settings") + other = RadioSettingGroup("other", "Other Settings") + work = RadioSettingGroup("work", "Work Mode Settings") + fm_preset = RadioSettingGroup("fm_preset", "FM Preset") + dtmfe = RadioSettingGroup("dtmfe", "DTMF Encode Settings") + service = RadioSettingGroup("service", "Service Settings") + top = RadioSettings(basic, advanced, other, work, fm_preset, dtmfe, + service) + + # Basic settings + if _mem.settings.squelch > 0x09: + val = 0x00 + else: + val = _mem.settings.squelch + rs = RadioSetting("settings.squelch", "Squelch", + RadioSettingValueList( + LIST_OFF1TO9, LIST_OFF1TO9[val])) + basic.append(rs) + + if _mem.settings.save > 0x04: + val = 0x00 + else: + val = _mem.settings.save + rs = RadioSetting("settings.save", "Battery Saver", + RadioSettingValueList( + LIST_SAVE, LIST_SAVE[val])) + basic.append(rs) + + if _mem.settings.vox > 0x0A: + val = 0x00 + else: + val = _mem.settings.vox + rs = RadioSetting("settings.vox", "Vox", + RadioSettingValueList( + LIST_OFF1TO10, LIST_OFF1TO10[val])) + basic.append(rs) + + if _mem.settings.abr > 0x0A: + val = 0x00 + else: + val = _mem.settings.abr + rs = RadioSetting("settings.abr", "Backlight Timeout", + RadioSettingValueList( + LIST_OFF1TO10, LIST_OFF1TO10[val])) + basic.append(rs) + + rs = RadioSetting("settings.tdr", "Dual Watch", + RadioSettingValueBoolean(_mem.settings.tdr)) + basic.append(rs) + + rs = RadioSetting("settings.beep", "Beep", + RadioSettingValueBoolean(_mem.settings.beep)) + basic.append(rs) + + if _mem.settings.timeout > 0x27: + val = 0x03 + else: + val = _mem.settings.timeout + rs = RadioSetting("settings.timeout", "Timeout Timer", + RadioSettingValueList( + LIST_TIMEOUT, LIST_TIMEOUT[val])) + basic.append(rs) + + if _mem.settings.voice > 0x02: + val = 0x01 + else: + val = _mem.settings.voice + rs = RadioSetting("settings.voice", "Voice Prompt", + RadioSettingValueList( + LIST_VOICE, LIST_VOICE[val])) + basic.append(rs) + + rs = RadioSetting("settings.dtmfst", "DTMF Sidetone", + RadioSettingValueList(LIST_DTMFST, LIST_DTMFST[ + _mem.settings.dtmfst])) + basic.append(rs) + + if _mem.settings.screv > 0x02: + val = 0x01 + else: + val = _mem.settings.screv + rs = RadioSetting("settings.screv", "Scan Resume", + RadioSettingValueList( + LIST_RESUME, LIST_RESUME[val])) + basic.append(rs) + + rs = RadioSetting("settings.pttid", "When to send PTT ID", + RadioSettingValueList(LIST_PTTID, LIST_PTTID[ + _mem.settings.pttid])) + basic.append(rs) + + if _mem.settings.pttlt > 0x1E: + val = 0x05 + else: + val = _mem.settings.pttlt + rs = RadioSetting("pttlt", "PTT ID Delay", + RadioSettingValueInteger(0, 50, val)) + basic.append(rs) + + rs = RadioSetting("settings.mdfa", "Display Mode (A)", + RadioSettingValueList(LIST_MODE, LIST_MODE[ + _mem.settings.mdfa])) + basic.append(rs) + + rs = RadioSetting("settings.mdfb", "Display Mode (B)", + RadioSettingValueList(LIST_MODE, LIST_MODE[ + _mem.settings.mdfb])) + basic.append(rs) + + rs = RadioSetting("settings.sync", "Sync A & B", + RadioSettingValueBoolean(_mem.settings.sync)) + basic.append(rs) + + rs = RadioSetting("settings.wtled", "Standby LED Color", + RadioSettingValueList( + LIST_COLOR, LIST_COLOR[_mem.settings.wtled])) + basic.append(rs) + + rs = RadioSetting("settings.rxled", "RX LED Color", + RadioSettingValueList( + LIST_COLOR, LIST_COLOR[_mem.settings.rxled])) + basic.append(rs) + + rs = RadioSetting("settings.txled", "TX LED Color", + RadioSettingValueList( + LIST_COLOR, LIST_COLOR[_mem.settings.txled])) + basic.append(rs) + + val = _mem.settings.almod + rs = RadioSetting("settings.almod", "Alarm Mode", + RadioSettingValueList( + LIST_ALMOD, LIST_ALMOD[val])) + basic.append(rs) + + rs = RadioSetting("settings.dbptt", "Double PTT", + RadioSettingValueBoolean(_mem.settings.dbptt)) + basic.append(rs) + + rs = RadioSetting("settings.ste", "Squelch Tail Eliminate (HT to HT)", + RadioSettingValueBoolean(_mem.settings.ste)) + basic.append(rs) + + rs = RadioSetting("settings.ponmsg", "Power-On Message", + RadioSettingValueList(LIST_PONMSG, LIST_PONMSG[ + _mem.settings.ponmsg])) + basic.append(rs) + + rs = RadioSetting("settings.roger", "Roger Beep", + RadioSettingValueBoolean(_mem.settings.roger)) + basic.append(rs) + + rs = RadioSetting("settings.rtone", "Tone Burst Frequency", + RadioSettingValueList(LIST_RTONE, LIST_RTONE[ + _mem.settings.rtone])) + basic.append(rs) + + rs = RadioSetting("settings.rogerrx", "Roger Beep (RX)", + RadioSettingValueList( + LIST_OFFAB, LIST_OFFAB[ + _mem.settings.rogerrx])) + basic.append(rs) + + # Advanced settings + rs = RadioSetting("settings.reset", "RESET Menu", + RadioSettingValueBoolean(_mem.settings.reset)) + advanced.append(rs) + + rs = RadioSetting("settings.menu", "All Menus", + RadioSettingValueBoolean(_mem.settings.menu)) + advanced.append(rs) + + rs = RadioSetting("settings.fmradio", "Broadcast FM Radio", + RadioSettingValueBoolean(_mem.settings.fmradio)) + advanced.append(rs) + + rs = RadioSetting("settings.alarm", "Alarm Sound", + RadioSettingValueBoolean(_mem.settings.alarm)) + advanced.append(rs) + + # Other settings + def _filter(name): + filtered = "" + for char in str(name): + if char in chirp_common.CHARSET_ASCII: + filtered += char + else: + filtered += " " + return filtered + + _msg = _mem.firmware_msg + val = RadioSettingValueString(0, 7, _filter(_msg.line1)) + val.set_mutable(False) + rs = RadioSetting("firmware_msg.line1", "Firmware Message 1", val) + other.append(rs) + + val = RadioSettingValueString(0, 7, _filter(_msg.line2)) + val.set_mutable(False) + rs = RadioSetting("firmware_msg.line2", "Firmware Message 2", val) + other.append(rs) + + _msg = _mem.sixpoweron_msg + val = RadioSettingValueString(0, 7, _filter(_msg.line1)) + val.set_mutable(False) + rs = RadioSetting("sixpoweron_msg.line1", "6+Power-On Message 1", val) + other.append(rs) + val = RadioSettingValueString(0, 7, _filter(_msg.line2)) + val.set_mutable(False) + rs = RadioSetting("sixpoweron_msg.line2", "6+Power-On Message 2", val) + other.append(rs) + + _msg = _mem.poweron_msg + rs = RadioSetting("poweron_msg.line1", "Power-On Message 1", + RadioSettingValueString( + 0, 7, _filter(_msg.line1))) + other.append(rs) + rs = RadioSetting("poweron_msg.line2", "Power-On Message 2", + RadioSettingValueString( + 0, 7, _filter(_msg.line2))) + other.append(rs) + + # Work mode settings + rs = RadioSetting("settings.displayab", "Display", + RadioSettingValueList( + LIST_AB, LIST_AB[_mem.settings.displayab])) + work.append(rs) + + rs = RadioSetting("settings.keylock", "Keypad Lock", + RadioSettingValueBoolean(_mem.settings.keylock)) + work.append(rs) + + rs = RadioSetting("wmchannel.mrcha", "MR A Channel", + RadioSettingValueInteger(1, 15, + _mem.wmchannel.mrcha)) + work.append(rs) + + rs = RadioSetting("wmchannel.mrchb", "MR B Channel", + RadioSettingValueInteger(1, 15, + _mem.wmchannel.mrchb)) + work.append(rs) + + # broadcast FM settings + _fm_presets = self._memobj.fm_presets + if _fm_presets <= 108.0 * 10 - 650: + preset = _fm_presets / 10.0 + 65 + elif _fm_presets >= 65.0 * 10 and _fm_presets <= 108.0 * 10: + preset = _fm_presets / 10.0 + else: + preset = 76.0 + rs = RadioSetting("fm_presets", "FM Preset(MHz)", + RadioSettingValueFloat(65, 108.0, preset, 0.1, 1)) + fm_preset.append(rs) + + # DTMF settings + def apply_code(setting, obj, length): + code = [] + for j in range(0, length): + try: + code.append(DTMF_CHARS.index(str(setting.value)[j])) + except IndexError: + code.append(0xFF) + obj.code = code + + for i in range(0, 15): + _codeobj = self._memobj.pttid[i].code + _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F]) + val = RadioSettingValueString(0, 5, _code, False) + val.set_charset(DTMF_CHARS) + pttid = RadioSetting("pttid/%i.code" % i, + "Signal Code %i" % (i + 1), val) + pttid.set_apply_callback(apply_code, self._memobj.pttid[i], 5) + dtmfe.append(pttid) + + if _mem.ani.dtmfon > 0xC3: + val = 0x03 + else: + val = _mem.ani.dtmfon + rs = RadioSetting("ani.dtmfon", "DTMF Speed (on)", + RadioSettingValueList(LIST_DTMFSPEED, + LIST_DTMFSPEED[val])) + dtmfe.append(rs) + + if _mem.ani.dtmfoff > 0xC3: + val = 0x03 + else: + val = _mem.ani.dtmfoff + rs = RadioSetting("ani.dtmfoff", "DTMF Speed (off)", + RadioSettingValueList(LIST_DTMFSPEED, + LIST_DTMFSPEED[val])) + dtmfe.append(rs) + + _codeobj = self._memobj.ani.code + _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F]) + val = RadioSettingValueString(0, 5, _code, False) + val.set_charset(DTMF_CHARS) + rs = RadioSetting("ani.code", "ANI Code", val) + rs.set_apply_callback(apply_code, self._memobj.ani, 5) + dtmfe.append(rs) + + rs = RadioSetting("ani.aniid", "When to send ANI ID", + RadioSettingValueList(LIST_PTTID, + LIST_PTTID[_mem.ani.aniid])) + dtmfe.append(rs) + + # Service settings + for index in range(0, 10): + key = "squelch.vhf.sql%i" % (index) + _obj = self._memobj.squelch.vhf + val = RadioSettingValueInteger(0, 123, + getattr(_obj, "sql%i" % (index))) + if index == 0: + val.set_mutable(False) + name = "Squelch %i" % (index) + rs = RadioSetting(key, name, val) + service.append(rs) + + return top + + @classmethod + def match_model(cls, filedata, filename): + match_size = False + match_model = False + + # testing the file data size + if len(filedata) == 0x2008: + match_size = True + + # testing the firmware model fingerprint + match_model = model_match(cls, filedata) + + if match_size and match_model: + return True + else: + return False diff --git a/chirp/drivers/retevis_rt21.py b/chirp/drivers/retevis_rt21.py index 326fb03..35f0521 100644 --- a/chirp/drivers/retevis_rt21.py +++ b/chirp/drivers/retevis_rt21.py @@ -232,6 +232,13 @@ def do_upload(radio): _rt21_exit_programming_mode(radio) +def model_match(cls, data): + """Match the opened/downloaded image to the correct version""" + rid = data[0x01B8:0x01BE] + + return rid.startswith("P3207") + + @directory.register class RT21Radio(chirp_common.CloneModeRadio): """RETEVIS RT21""" @@ -556,3 +563,21 @@ class RT21Radio(chirp_common.CloneModeRadio): except Exception, e: LOG.debug(element.get_name()) raise + + @classmethod + def match_model(cls, filedata, filename): + match_size = False + match_model = False + + # testing the file data size + if len(filedata) in [0x0400, ]: + match_size = True + + # testing the model fingerprint + match_model = model_match(cls, filedata) + + if match_size and match_model: + return True + else: + return False + diff --git a/chirp/drivers/retevis_rt26.py b/chirp/drivers/retevis_rt26.py new file mode 100644 index 0000000..ab138e2 --- /dev/null +++ b/chirp/drivers/retevis_rt26.py @@ -0,0 +1,918 @@ +# Copyright 2017 Jim Unroe <rock.unroe@gmail.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import time +import struct +import logging +import re + +from chirp import chirp_common, directory, memmap +from chirp import bitwise, errors, util +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueInteger, RadioSettingValueList, \ + RadioSettingValueBoolean, RadioSettingValueString, \ + InvalidValueError, RadioSettings + +LOG = logging.getLogger(__name__) + +MEM_FORMAT = """ +#seekto 0x0010; +struct { + lbcd rxfreq[4]; + lbcd txfreq[4]; + lbcd rxtone[2]; + lbcd txtone[2]; + u8 unknown1:1, + pttid:2, // PTT ID + skip:1, // Scan Add + wide:1, // Bandwidth + bcl:1, // Busy Lock + epilogue:1, // Epilogue (STE) + highpower:1; // Power Level + u8 unknown2[3]; +} memory[16]; + +#seekto 0x0120; +struct { + u8 hivoltnotx:1, // TX Inhibit when voltage too high + lovoltnotx:1, // TX Inhibit when voltage too low + unknown1:1, + fmradio:1, // Broadcast FM Radio + unknown2:1, + tone:1, // Tone + voice:2; // Voice + u8 unknown3:1, + save:3, // Battery Save + squelch:4; // Squelch + u8 tot; // Time Out Timer + u8 voxi:1, // VOX Inhibit on Receive + voxd:2, // VOX Delay + vox:1, // VOX + voxg:4; // VOX Gain + u8 unknown4; + u8 unknown5:4, + scanspeed:4; // Scan Speed + u8 unknown6:3, + scandelay:5; // Scan Delay + u8 k1longp:4, // Key 1 Long Press + k1shortp:4; // Key 1 Short Press + u8 k2longp:4, // Key 2 Long Press + k2shortp:4; // Key 2 Short Press + u8 unknown7:4, + ssave:4; // Super Battery Save +} settings; + +#seekto 0x0140; +struct { + u8 unknown1:4, + dtmfspd:4; // DTMF Speed + u8 digdelay:4, // 1st Digit Delay + digtime:4; // 1st Digit Time + u8 stuntype:1, // Stun Type + sidetone:1, // DTMF Sidetone + starhash:2, // * and # Time + decodetone:1, // Decode Tone + txdecode:1, // TX Decode + unknown2:2; + u8 unknown3; + u8 unknown4:4, + groupcode:4; // Group Code + u8 unknown5:1, + resettone:1, // Reset Tone + resettime:6; // Reset Time + u8 codespace:4, // Code Space Time + decodeto:4; // Decode Tome Out + u8 unknown6; + u8 idcode[3]; // ID Code + u8 unknown7[2]; + u8 code1_len; // PTT ID length(begging of TX) + u8 code2_len; // PTT ID length(end of TX) + u8 unknown8; + u8 code3_len; // Stun Code length + u8 code3[5]; // Stun Code + u8 unknown9[10]; + u8 code1[8]; // PTT ID(beggining of TX) + u8 code2[8]; // PTT ID(end of TX) +} dtmf; + +#seekto 0x0170; +struct { + char fp[8]; +} fingerprint; +""" + +CMD_ACK = "\x06" + +NUMERIC_CHARSET = list("0123456789") +DTMF_CHARSET = NUMERIC_CHARSET + list("ABCD*#") + +RT26_POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5.00), + chirp_common.PowerLevel("High", watts=10.00)] + +RT26_DTCS = sorted(chirp_common.DTCS_CODES + [645]) + +LIST_PTTID = ["Off", "BOT", "EOT", "Both"] +LIST_SHORT_PRESS = ["Off", "Monitor On/Off", "", "Scan", "Alarm", + "Power High/Low"] +LIST_LONG_PRESS = ["Off", "Monitor On/Off", "Monitor(momentary)", + "Scan", "Alarm", "Power High/Low"] +LIST_VOXDELAY = ["0.5", "1.0", "2.0", "3.0"] +LIST_VOICE = ["Off", "English", "Chinese"] +LIST_TIMEOUTTIMER = ["Off"] + ["%s" % x for x in range(15, 615, 15)] +LIST_SAVE = ["Off", "1:1", "1:2", "1:3", "1:4"] +LIST_SSAVE = ["Off"] + ["%s" % x for x in range(1, 10)] +LIST_SCANSPEED = ["%s" % x for x in range(100, 550, 50)] +LIST_SCANDELAY = ["%s" % x for x in range(3, 31)] +LIST_DIGTIME = ["%s" % x for x in range(0, 1100, 100)] +LIST_DIGDELAY = ["%s" % x for x in range(100, 1100, 100)] +LIST_STARHASH = ["100", "500", "1000", "0"] +LIST_CODESPACE = ["None"] + ["%s" % x for x in range(600, 2100, 100)] +LIST_GROUPCODE = ["Off", "A", "B", "C", "D", "#", "*"] +LIST_RESETTIME = ["Off"] + ["%s" % x for x in range(1, 61)] +LIST_DECODETO = ["%s" % x for x in range(500, 1000, 50)] + \ + ["%s" % x for x in range(1000, 1600, 100)] +LIST_STUNTYPE = ["TX/RX Inhibit", "TX Inhibit"] + +SETTING_LISTS = { + "k1shortp": LIST_SHORT_PRESS, + "k1longp": LIST_LONG_PRESS, + "k2shortp": LIST_SHORT_PRESS, + "k2longp": LIST_LONG_PRESS, + "voxd": LIST_VOXDELAY, + "voice": LIST_VOICE, + "tot": LIST_TIMEOUTTIMER, + "save": LIST_SAVE, + "ssave": LIST_SSAVE, + "scanspeed": LIST_SCANSPEED, + "scandelay": LIST_SCANDELAY, + "digtime": LIST_DIGTIME, + "digdelay": LIST_DIGDELAY, + "starhash" : LIST_STARHASH, + "codespace" : LIST_CODESPACE, + "groupcode" : LIST_GROUPCODE, + "resettime" : LIST_RESETTIME, + "decodeto" : LIST_DECODETO, + "stuntype" : LIST_STUNTYPE, + } + +# Retevis RT26 fingerprints +RT26_UHF_fp = "PDK80" + "\xF3\x00\x00" # RT26 UHF model + +MODELS = [RT26_UHF_fp,] + + +def _model_from_data(data): + return data[0x0170:0x0178] + + +def _model_from_image(radio): + return _model_from_data(radio.get_mmap()) + + +def _get_radio_model(radio): + block = _rt26_read_block(radio, 0x0170, 0x10) + version = block[0:8] + return version + + +def _rt26_enter_programming_mode(radio): + serial = radio.pipe + + magic = ["PROGRAMa", "PROGRAMb"] + for i in range(0, 2): + + try: + LOG.debug("sending " + magic[i]) + serial.write(magic[i]) + ack = serial.read(1) + except: + _rt26_exit_programming_mode(radio) + raise errors.RadioError("Error communicating with radio") + + if not ack: + _rt26_exit_programming_mode(radio) + raise errors.RadioError("No response from radio") + elif ack != CMD_ACK: + LOG.debug("Incorrect response, got this:\n\n" + util.hexprint(ack)) + _rt26_exit_programming_mode(radio) + raise errors.RadioError("Radio refused to enter programming mode") + + try: + LOG.debug("sending " + util.hexprint("\x02")) + serial.write("\x02") + ident = serial.read(16) + except: + _rt26_exit_programming_mode(radio) + raise errors.RadioError("Error communicating with radio") + + if not ident.startswith("PDK80"): + LOG.debug("Incorrect response, got this:\n\n" + util.hexprint(ident)) + _rt26_exit_programming_mode(radio) + LOG.debug(util.hexprint(ident)) + raise errors.RadioError("Radio returned unknown identification string") + + try: + LOG.debug("sending " + util.hexprint("MDK8ECUMHS1X7BN/")) + serial.write("MXT8KCUMHS1X7BN/") + ack = serial.read(1) + except: + _rt26_exit_programming_mode(radio) + raise errors.RadioError("Error communicating with radio") + + if ack != "\xB2": + LOG.debug("Incorrect response, got this:\n\n" + util.hexprint(ack)) + _rt26_exit_programming_mode(radio) + raise errors.RadioError("Radio refused to enter programming mode") + + try: + LOG.debug("sending " + util.hexprint(CMD_ACK)) + serial.write(CMD_ACK) + ack = serial.read(1) + except: + _rt26_exit_programming_mode(radio) + raise errors.RadioError("Error communicating with radio") + + if ack != CMD_ACK: + LOG.debug("Incorrect response, got this:\n\n" + util.hexprint(ack)) + _rt26_exit_programming_mode(radio) + raise errors.RadioError("Radio refused to enter programming mode") + + # DEBUG + LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL)) + + +def _rt26_exit_programming_mode(radio): + serial = radio.pipe + try: + serial.write("E") + except: + raise errors.RadioError("Radio refused to exit programming mode") + + +def _rt26_read_block(radio, block_addr, block_size): + serial = radio.pipe + + cmd = struct.pack(">cHb", 'R', block_addr, block_size) + expectedresponse = "W" + cmd[1:] + LOG.debug("Reading block %04x..." % (block_addr)) + + try: + serial.write(cmd) + + response = serial.read(4 + block_size) + if response[:4] != expectedresponse: + _rt26_exit_programming_mode(radio) + raise Exception("Error reading block %04x." % (block_addr)) + + block_data = response[4:] + + serial.write(CMD_ACK) + ack = serial.read(1) + except: + _rt26_exit_programming_mode(radio) + raise errors.RadioError("Failed to read block at %04x" % block_addr) + + if ack != CMD_ACK: + _rt26_exit_programming_mode(radio) + raise Exception("No ACK reading block %04x." % (block_addr)) + + return block_data + + +def _rt26_write_block(radio, block_addr, block_size): + serial = radio.pipe + + cmd = struct.pack(">cHb", 'W', block_addr, block_size) + data = radio.get_mmap()[block_addr:block_addr + block_size] + + LOG.debug("Writing Data:") + LOG.debug(util.hexprint(cmd + data)) + + try: + serial.write(cmd + data) + if serial.read(1) != CMD_ACK: + raise Exception("No ACK") + except: + _rt26_exit_programming_mode(radio) + raise errors.RadioError("Failed to send block " + "to radio at %04x" % block_addr) + + +def do_download(radio): + LOG.debug("download") + _rt26_enter_programming_mode(radio) + + data = "" + + status = chirp_common.Status() + status.msg = "Cloning from radio" + + status.cur = 0 + status.max = radio._memsize + + for addr in range(0, radio._memsize, radio._block_size): + status.cur = addr + radio._block_size + radio.status_fn(status) + + block = _rt26_read_block(radio, addr, radio._block_size) + data += block + + LOG.debug("Address: %04x" % addr) + LOG.debug(util.hexprint(block)) + + _rt26_exit_programming_mode(radio) + + return memmap.MemoryMap(data) + + +def do_upload(radio): + status = chirp_common.Status() + status.msg = "Uploading to radio" + + _rt26_enter_programming_mode(radio) + + status.cur = 0 + status.max = 0x0190 + + for start_addr, end_addr, block_size in radio._ranges: + for addr in range(start_addr, end_addr, block_size): + status.cur = addr + block_size + radio.status_fn(status) + _rt26_write_block(radio, addr, block_size) + + _rt26_exit_programming_mode(radio) + + +def model_match(cls, data): + """Match the opened/downloaded image to the correct version""" + rid = data[0x0170:0x0176] + + return rid.startswith("PDK80") + + +@directory.register +class RT26Radio(chirp_common.CloneModeRadio): + """Retevis RT26""" + VENDOR = "Retevis" + MODEL = "RT26" + BAUD_RATE = 4800 + + _ranges = [ + (0x0000, 0x0190, 0x10), + ] + _memsize = 0x0400 + _block_size = 0x10 + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.has_bank = False + rf.has_ctone = True + rf.has_cross = True + rf.has_rx_dtcs = True + rf.has_tuning_step = False + rf.can_odd_split = True + rf.has_name = False + rf.valid_skips = ["", "S"] + rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] + rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone", + "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"] + rf.valid_power_levels = RT26_POWER_LEVELS + rf.valid_duplexes = ["", "-", "+", "split", "off"] + rf.valid_modes = ["NFM", "FM"] # 12.5 KHz, 25 kHz. + rf.memory_bounds = (1, 16) + rf.valid_bands = [(400000000, 520000000)] + + return rf + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def sync_in(self): + self._mmap = do_download(self) + self.process_mmap() + + def sync_out(self): + do_upload(self) + + def get_raw_memory(self, number): + return repr(self._memobj.memory[number - 1]) + + def decode_tone(self, val): + """Parse the tone data to decode from mem, it returns: + Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)""" + if val.get_raw() == "\xFF\xFF": + return '', None, None + + val = int(val) + if val >= 12000: + a = val - 12000 + return 'DTCS', a, 'R' + elif val >= 8000: + a = val - 8000 + return 'DTCS', a, 'N' + 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[0].set_raw(0xFF) + memval[1].set_raw(0xFF) + elif mode == 'Tone': + memval.set_value(int(value * 10)) + elif mode == 'DTCS': + flag = 0x80 if pol == 'N' else 0xC0 + memval.set_value(value) + memval[1].set_bits(flag) + else: + raise Exception("Internal error: invalid mode `%s'" % mode) + + def _my_band(self): + model_tag = _model_from_image(self) + return model_tag + + def get_memory(self, number): + _mem = self._memobj.memory[number - 1] + + mem = chirp_common.Memory() + + mem.number = number + mem.freq = int(_mem.rxfreq) * 10 + + # We'll consider any blank (i.e. 0MHz frequency) to be empty + if mem.freq == 0: + mem.empty = True + return mem + + if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF": + mem.freq = 0 + mem.empty = True + return mem + + if int(_mem.rxfreq) == int(_mem.txfreq): + mem.duplex = "" + mem.offset = 0 + else: + mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+" + mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10 + + mem.mode = _mem.wide and "FM" or "NFM" + + rxtone = txtone = None + txtone = self.decode_tone(_mem.txtone) + rxtone = self.decode_tone(_mem.rxtone) + chirp_common.split_tone_decode(mem, txtone, rxtone) + + mem.power = RT26_POWER_LEVELS[_mem.highpower] + + if _mem.skip: + mem.skip = "S" + + mem.extra = RadioSettingGroup("Extra", "extra") + + rs = RadioSetting("bcl", "BCL", + RadioSettingValueBoolean(not _mem.bcl)) + mem.extra.append(rs) + + rs = RadioSetting("epilogue", "Epilogue(STE)", + RadioSettingValueBoolean(_mem.epilogue)) + mem.extra.append(rs) + + val = 3 - _mem.pttid + rs = RadioSetting("pttid", "PTT ID", + RadioSettingValueList( + LIST_PTTID, LIST_PTTID[val])) + mem.extra.append(rs) + + return mem + + def set_memory(self, mem): + _mem = self._memobj.memory[mem.number - 1] + + if mem.empty: + _mem.set_raw("\xFF" * (_mem.size() / 8)) + return + + _mem.rxfreq = mem.freq / 10 + + if mem.duplex == "off": + for i in range(0, 4): + _mem.txfreq[i].set_raw("\xFF") + elif mem.duplex == "split": + _mem.txfreq = mem.offset / 10 + elif mem.duplex == "+": + _mem.txfreq = (mem.freq + mem.offset) / 10 + elif mem.duplex == "-": + _mem.txfreq = (mem.freq - mem.offset) / 10 + else: + _mem.txfreq = mem.freq / 10 + + _mem.wide = mem.mode == "FM" + + ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \ + chirp_common.split_tone_encode(mem) + self.encode_tone(_mem.txtone, txmode, txtone, txpol) + self.encode_tone(_mem.rxtone, rxmode, rxtone, rxpol) + + _mem.highpower = mem.power == RT26_POWER_LEVELS[1] + + _mem.skip = mem.skip == "S" + + for setting in mem.extra: + if setting.get_name() == "bcl": + setattr(_mem, setting.get_name(), not int(setting.value)) + elif setting.get_name() == "pttid": + setattr(_mem, setting.get_name(), 3 - int(setting.value)) + else: + setattr(_mem, setting.get_name(), int(setting.value)) + + def _bbcd2dtmf(self, bcdarr, strlen=16): + # doing bbcd, but with support for ABCD*# + LOG.debug(bcdarr.get_value()) + string = ''.join("%02X" % b for b in bcdarr) + LOG.debug("@_bbcd2dtmf, received: %s" % string) + string = string.replace('E', '#').replace('F', '*') + if strlen <= 16: + string = string[:strlen] + return string + + def _dtmf2bbcd(self, value, strlen): + dtmfstr = value.get_value() + dtmfstr = dtmfstr.replace('#', 'E').replace('*', 'F') + dtmfstr = str.ljust(dtmfstr.strip(), strlen, "F") + bcdarr = list(bytearray.fromhex(dtmfstr)) + LOG.debug("@_dtmf2bbcd, sending: %s" % bcdarr) + return bcdarr + + def _bbcd2num(self, bcdarr, strlen=6): + # doing bbcd + LOG.debug(bcdarr.get_value()) + string = ''.join("%02X" % b for b in bcdarr) + LOG.debug("@_bbcd2num, received: %s" % string) + if strlen <= 6: + string = string[:strlen] + return string + + def _num2bbcd(self, value): + numstr = value.get_value() + numstr = str.ljust(numstr.strip(), 6, "F") + bcdarr = list(bytearray.fromhex(numstr)) + LOG.debug("@_num2bbcd, sending: %s" % bcdarr) + return bcdarr + + def get_settings(self): + _settings = self._memobj.settings + _mem = self._memobj + basic = RadioSettingGroup("basic", "Basic Settings") + dtmf = RadioSettingGroup("dtmf", "DTMF Settings") + top = RadioSettings(basic, dtmf) + + if _settings.k1shortp > 5: + val = 4 + else: + val = _settings.k1shortp + rs = RadioSetting("k1shortp", "Key 1 Short Press", + RadioSettingValueList( + LIST_SHORT_PRESS, + LIST_SHORT_PRESS[val])) + basic.append(rs) + + if _settings.k1longp > 5: + val = 5 + else: + val = _settings.k1longp + rs = RadioSetting("k1longp", "Key 1 Long Press", + RadioSettingValueList( + LIST_LONG_PRESS, + LIST_LONG_PRESS[val])) + basic.append(rs) + + if _settings.k2shortp > 5: + val = 1 + else: + val = _settings.k2shortp + rs = RadioSetting("k2shortp", "Key 2 Short Press", + RadioSettingValueList( + LIST_SHORT_PRESS, + LIST_SHORT_PRESS[val])) + basic.append(rs) + + if _settings.k2longp > 5: + val = 3 + else: + val = _settings.k2longp + rs = RadioSetting("k2longp", "Key 2 Long Press", + RadioSettingValueList( + LIST_LONG_PRESS, + LIST_LONG_PRESS[val])) + basic.append(rs) + + rs = RadioSetting("vox", "VOX", + RadioSettingValueBoolean(not _settings.vox)) + basic.append(rs) + + if _settings.voxg > 8: + val = 4 + else: + val = _settings.voxg + 1 + rs = RadioSetting("voxg", "VOX Gain", + RadioSettingValueInteger(1, 9, val)) + basic.append(rs) + + rs = RadioSetting("voxd", "VOX Delay Time", + RadioSettingValueList( + LIST_VOXDELAY, + LIST_VOXDELAY[_settings.voxd])) + basic.append(rs) + + rs = RadioSetting("voxi", "VOX Inhibit on Receive", + RadioSettingValueBoolean(_settings.voxi)) + basic.append(rs) + + if _settings.squelch > 9: + val = 5 + else: + val = _settings.squelch + rs = RadioSetting("squelch", "Squelch Level", + RadioSettingValueInteger(0, 9, val)) + basic.append(rs) + + if _settings.voice == 3: + val = 1 + else: + val = _settings.voice + rs = RadioSetting("voice", "Voice Prompts", + RadioSettingValueList( + LIST_VOICE, + LIST_VOICE[val])) + basic.append(rs) + + rs = RadioSetting("tone", "Tone", + RadioSettingValueBoolean(_settings.tone)) + basic.append(rs) + + rs = RadioSetting("lovoltnotx", "TX Inhibit (when battery < 6 volts)", + RadioSettingValueBoolean(_settings.lovoltnotx)) + basic.append(rs) + + rs = RadioSetting("hivoltnotx", "TX Inhibit (when battery > 9 volts)", + RadioSettingValueBoolean(_settings.hivoltnotx)) + basic.append(rs) + + if _settings.tot > 0x28: + val = 6 + else: + val = _settings.tot + rs = RadioSetting("tot", "Time-out Timer[s]", + RadioSettingValueList( + LIST_TIMEOUTTIMER, + LIST_TIMEOUTTIMER[val])) + basic.append(rs) + + if _settings.save < 3: + val = 0 + else: + val = _settings.save - 3 + rs = RadioSetting("save", "Battery Saver", + RadioSettingValueList( + LIST_SAVE, + LIST_SAVE[val])) + basic.append(rs) + + rs = RadioSetting("ssave", "Super Battery Saver[s]", + RadioSettingValueList( + LIST_SSAVE, + LIST_SSAVE[_settings.ssave])) + basic.append(rs) + + rs = RadioSetting("fmradio", "Broadcast FM", + RadioSettingValueBoolean(_settings.fmradio)) + basic.append(rs) + + if _settings.scanspeed > 8: + val = 4 + else: + val = _settings.scanspeed + rs = RadioSetting("scanspeed", "Scan Speed[ms]", + RadioSettingValueList( + LIST_SCANSPEED, + LIST_SCANSPEED[val])) + basic.append(rs) + + if _settings.scandelay > 27: + val = 12 + else: + val = _settings.scandelay + rs = RadioSetting("scandelay", "Scan Droupout Delay Time[s]", + RadioSettingValueList( + LIST_SCANDELAY, + LIST_SCANDELAY[val])) + basic.append(rs) + + if _mem.dtmf.dtmfspd > 11: + val = 2 + else: + val = _mem.dtmf.dtmfspd + 4 + rs = RadioSetting("dtmf.dtmfspd", "DTMF Speed[digit/s]", + RadioSettingValueInteger(4, 15, val)) + dtmf.append(rs) + + if _mem.dtmf.digtime > 10: + val = 0 + else: + val = _mem.dtmf.digtime + rs = RadioSetting("dtmf.digtime", "1st Digit Time[ms]", + RadioSettingValueList( + LIST_DIGTIME, + LIST_DIGTIME[val])) + dtmf.append(rs) + + if _mem.dtmf.digdelay > 9: + val = 0 + else: + val = _mem.dtmf.digdelay + rs = RadioSetting("dtmf.digdelay", "1st Digit Delay[ms]", + RadioSettingValueList( + LIST_DIGDELAY, + LIST_DIGDELAY[val])) + dtmf.append(rs) + + rs = RadioSetting("dtmf.starhash", "* and # Time[ms]", + RadioSettingValueList( + LIST_STARHASH, + LIST_STARHASH[_mem.dtmf.starhash])) + dtmf.append(rs) + + rs = RadioSetting("dtmf.codespace", "Code Space Time[ms]", + RadioSettingValueList( + LIST_CODESPACE, + LIST_CODESPACE[_mem.dtmf.codespace])) + dtmf.append(rs) + + rs = RadioSetting("dtmf.sidetone", "DTMF Sidetone", + RadioSettingValueBoolean(_mem.dtmf.sidetone)) + dtmf.append(rs) + + # setup pttid entries + for i in range(0, 2): + objname = "code" + str(i + 1) + names = ["PTT ID(BOT)", "PTT ID(EOT)"] + strname = str(names[i]) + dtmfsetting = getattr(_mem.dtmf, objname) + dtmflen = getattr(_mem.dtmf, objname + "_len") + dtmfstr = self._bbcd2dtmf(dtmfsetting, dtmflen) + code = RadioSettingValueString(0, 16, dtmfstr) + code.set_charset(DTMF_CHARSET + list(" ")) + rs = RadioSetting("dtmf." + objname, strname, code) + dtmf.append(rs) + + def _filter(name): + filtered = "" + for char in str(name): + if char in NUMERIC_CHARSET: + filtered += char + else: + filtered += " " + return filtered + + # setup id code entry + codesetting = getattr(_mem.dtmf, "idcode") + codestr = self._bbcd2num(codesetting, 6) + code = RadioSettingValueString(0, 6, _filter(codestr)) + code.set_charset(NUMERIC_CHARSET + list(" ")) + rs = RadioSetting("dtmf.idcode", "ID Code", code) + dtmf.append(rs) + + if _mem.dtmf.groupcode > 6: + val = 0 + else: + val = _mem.dtmf.groupcode + rs = RadioSetting("dtmf.groupcode", "Group Code", + RadioSettingValueList( + LIST_GROUPCODE, + LIST_GROUPCODE[val])) + dtmf.append(rs) + + if _mem.dtmf.resettime > 60: + val = 0 + else: + val = _mem.dtmf.resettime + rs = RadioSetting("dtmf.resettime", "Auto Reset Time[s]", + RadioSettingValueList( + LIST_RESETTIME, + LIST_RESETTIME[_mem.dtmf.resettime])) + dtmf.append(rs) + + rs = RadioSetting("dtmf.txdecode", "TX Decode", + RadioSettingValueBoolean(_mem.dtmf.txdecode)) + dtmf.append(rs) + + rs = RadioSetting("dtmf.decodeto", "Decode Time Out[ms]", + RadioSettingValueList( + LIST_DECODETO, + LIST_DECODETO[_mem.dtmf.decodeto])) + dtmf.append(rs) + + rs = RadioSetting("dtmf.decodetone", "Decode Tone", + RadioSettingValueBoolean(_mem.dtmf.decodetone)) + dtmf.append(rs) + + rs = RadioSetting("dtmf.resettone", "Reset Tone", + RadioSettingValueBoolean(_mem.dtmf.resettone)) + dtmf.append(rs) + + rs = RadioSetting("dtmf.stuntype", "Stun Type", + RadioSettingValueList( + LIST_STUNTYPE, + LIST_STUNTYPE[_mem.dtmf.stuntype])) + dtmf.append(rs) + + ## setup stun entry + objname = "code3" + strname = "Stun Code" + dtmfsetting = getattr(_mem.dtmf, objname) + dtmflen = getattr(_mem.dtmf, objname + "_len") + dtmfstr = self._bbcd2dtmf(dtmfsetting, dtmflen) + code = RadioSettingValueString(0, 10, dtmfstr) + code.set_charset(DTMF_CHARSET + list(" ")) + rs = RadioSetting("dtmf." + objname, strname, code) + dtmf.append(rs) + + return top + + def set_settings(self, settings): + _mem = self._memobj + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + continue + else: + try: + if "." in element.get_name(): + bits = element.get_name().split(".") + obj = self._memobj + for bit in bits[:-1]: + obj = getattr(obj, bit) + setting = bits[-1] + else: + obj = self._memobj.settings + setting = element.get_name() + + if setting == "vox": + setattr(obj, setting, not int(element.value)) + elif setting == "voxg": + setattr(obj, setting, int(element.value) - 1) + elif setting == "save": + setattr(obj, setting, int(element.value) + 3) + elif setting == "dtmfspd": + setattr(obj, setting, int(element.value) - 4) + elif re.match('code\d', setting): + # set dtmf length field and then get bcd dtmf + if setting == "code3": + strlen = 10 + else: + strlen = 16 + codelen = len(str(element.value).strip()) + setattr(_mem.dtmf, setting + "_len", codelen) + dtmfstr = self._dtmf2bbcd(element.value, strlen) + setattr(_mem.dtmf, setting, dtmfstr) + elif setting == "idcode": + numstr = self._num2bbcd(element.value) + setattr(_mem.dtmf, setting, numstr) + elif element.value.get_mutable(): + LOG.debug("Setting %s = %s" % (setting, element.value)) + setattr(obj, setting, element.value) + except Exception, e: + LOG.debug(element.get_name()) + raise + + @classmethod + def match_model(cls, filedata, filename): + match_size = False + match_model = False + + # testing the file data size + if len(filedata) in [0x0400, ]: + match_size = True + + # testing the model fingerprint + match_model = model_match(cls, filedata) + + if match_size and match_model: + return True + else: + return False diff --git a/chirp/drivers/rfinder.py b/chirp/drivers/rfinder.py index 35dbe70..cedf835 100644 --- a/chirp/drivers/rfinder.py +++ b/chirp/drivers/rfinder.py @@ -262,7 +262,7 @@ class RFinderParser: import traceback LOG.error(traceback.format_exc()) LOG.error("Error in received data, cannot continue") - LOG.error(e) + LOG.error("rfinder.parse_data: %s", e) LOG.error(self.__cheat) LOG.error(line) diff --git a/chirp/drivers/th9800.py b/chirp/drivers/th9800.py index 9d21fd7..2dba301 100644 --- a/chirp/drivers/th9800.py +++ b/chirp/drivers/th9800.py @@ -189,6 +189,7 @@ class TYTTH9800Base(chirp_common.Radio): rf.valid_bands = [(26000000, 33000000), (47000000, 54000000), (108000000, 180000000), + (220000000, 260000000), (350000000, 399995000), (400000000, 512000000), (750000000, 950000000)] diff --git a/chirp/drivers/thd72.py b/chirp/drivers/thd72.py index 71614a3..59984e8 100644 --- a/chirp/drivers/thd72.py +++ b/chirp/drivers/thd72.py @@ -558,7 +558,7 @@ class THD72Radio(chirp_common.CloneModeRadio): try: element.run_apply_callback() except NotImplementedError as e: - LOG.error(e) + LOG.error("thd72: %s", e) continue # Find the object containing setting. diff --git a/chirp/drivers/uv5r.py b/chirp/drivers/uv5r.py index 0cb46bb..d2e8594 100644 --- a/chirp/drivers/uv5r.py +++ b/chirp/drivers/uv5r.py @@ -514,7 +514,7 @@ def _ident_radio(radio): data = _do_ident(radio, magic) return data except errors.RadioError, e: - LOG.error(e) + LOG.error("uv5r._ident_radio: %s", e) error = e time.sleep(2) @@ -728,6 +728,7 @@ class BaofengUV5R(chirp_common.CloneModeRadio, _ranges_aux = [ (0x1EC0, 0x2000), ] + _valid_chars = UV5R_CHARSET @classmethod def get_prompts(cls): @@ -764,7 +765,7 @@ class BaofengUV5R(chirp_common.CloneModeRadio, rf.has_tuning_step = False rf.can_odd_split = True rf.valid_name_length = 7 - rf.valid_characters = UV5R_CHARSET + rf.valid_characters = self._valid_chars rf.valid_skips = ["", "S"] rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone", @@ -1753,9 +1754,15 @@ class RH5RAlias(chirp_common.Alias): MODEL = "RH5R" +class ROUV5REXAlias(chirp_common.Alias): + VENDOR = "Radioddity" + MODEL = "UV-5R EX" + + @directory.register class BaofengUV5RGeneric(BaofengUV5R): - ALIASES = [UV5XAlias, RT5RAlias, RT5RVAlias, RT5Alias, RH5RAlias] + ALIASES = [UV5XAlias, RT5RAlias, RT5RVAlias, RT5Alias, RH5RAlias, + ROUV5REXAlias] @directory.register @@ -1777,6 +1784,7 @@ class BaofengUV82Radio(BaofengUV5R): _idents = [UV5R_MODEL_UV82] _vhf_range = (130000000, 176000000) _uhf_range = (400000000, 521000000) + _valid_chars = chirp_common.CHARSET_ASCII def _is_orig(self): # Override this for UV82 to always return False @@ -1835,11 +1843,16 @@ class IntekKT980Radio(BaofengUV5R): return False +class ROGA5SAlias(chirp_common.Alias): + VENDOR = "Radioddity" + MODEL = "GA-5S" + + @directory.register class BaofengBFF8HPRadio(BaofengUV5R): VENDOR = "Baofeng" MODEL = "BF-F8HP" - ALIASES = [RT5_TPAlias] + ALIASES = [RT5_TPAlias, ROGA5SAlias] _basetype = BASETYPE_F8HP _idents = [UV5R_MODEL_291, UV5R_MODEL_A58 @@ -1874,3 +1887,20 @@ class BaofengUV82HPRadio(BaofengUV5R): def _is_orig(self): # Override this for UV82HP to always return False return False + + +@directory.register +class RadioddityUV5RX3Radio(BaofengUV5R): + VENDOR = "Radioddity" + MODEL = "UV-5RX3" + + def get_features(self): + rf = BaofengUV5R.get_features(self) + rf.valid_bands = [self._vhf_range, + (200000000, 260000000), + self._uhf_range] + return rf + + @classmethod + def match_model(cls, filename, filedata): + return False diff --git a/chirp/drivers/uv5x3.py b/chirp/drivers/uv5x3.py index 1ca42a7..612dea0 100644 --- a/chirp/drivers/uv5x3.py +++ b/chirp/drivers/uv5x3.py @@ -36,6 +36,9 @@ from textwrap import dedent # BTECH UV-5X3 magic string MSTRING_UV5X3 = "\x50\x0D\x0C\x20\x16\x03\x28" +# MTC UV-5R-3 magic string +MSTRING_UV5R3 = "\x50\x0D\x0C\x20\x17\x09\x19" + ##### ID strings ##################################################### # BTECH UV-5X3 @@ -43,6 +46,9 @@ UV5X3_fp1 = "UVVG302" # BFB300 original UV5X3_fp2 = "UVVG301" # UVV300 original UV5X3_fp3 = "UVVG306" # UVV306 original +# MTC UV-5R-3 +UV5R3_fp1 = "5R31709" + DTMF_CHARS = " 1234567890*#ABCD" STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0] @@ -110,6 +116,7 @@ class UV5X3(baofeng_common.BaofengCommonHT): _ranges = [(0x0000, 0x0DF0), (0x0E00, 0x1800), (0x1EE0, 0x1EF0), + (0x1F60, 0x1F70), (0x1F80, 0x1F90), (0x1FA0, 0x1FB0), (0x1FE0, 0x2000)] @@ -351,11 +358,14 @@ class UV5X3(baofeng_common.BaofengCommonHT): u8 sql9; }; - #seekto 0x1F80; + #seekto 0x1F60; struct { struct squelch vhf; u8 unknown0[6]; u8 unknown1[16]; + struct squelch vhf2; + u8 unknown2[6]; + u8 unknown3[16]; struct squelch uhf; } squelch; @@ -384,9 +394,7 @@ class UV5X3(baofeng_common.BaofengCommonHT): def get_prompts(cls): rp = chirp_common.RadioPrompts() rp.experimental = \ - ('The BTech UV-5X3 driver is a beta version.\n' - '\n' - 'Please save an unedited copy of your first successful\n' + ('Please save an unedited copy of your first successful\n' 'download to a CHIRP Radio Images(*.img) file.' ) rp.pre_download = _(dedent("""\ @@ -664,7 +672,7 @@ class UV5X3(baofeng_common.BaofengCommonHT): 0, 7, _filter(_msg.line2))) other.append(rs) - if str(_mem.firmware_msg.line1) == "UVVG302": + if str(_mem.firmware_msg.line1) == ("UVVG302" or "5R31709"): lower = 136 upper = 174 else: @@ -683,6 +691,9 @@ class UV5X3(baofeng_common.BaofengCommonHT): if str(_mem.firmware_msg.line1) == "UVVG302": lower = 200 upper = 230 + elif str(_mem.firmware_msg.line1) == "5R31709": + lower = 200 + upper = 260 else: lower = 220 upper = 225 @@ -1167,18 +1178,23 @@ class UV5X3(baofeng_common.BaofengCommonHT): dtmfd.append(rs) # Service settings - for band in ["vhf", "uhf"]: + for band in ["vhf", "vhf2", "uhf"]: for index in range(0, 10): key = "squelch.%s.sql%i" % (band, index) if band == "vhf": _obj = self._memobj.squelch.vhf + _name = "VHF" + elif band == "vhf2": + _obj = self._memobj.squelch.vhf2 + _name = "220" elif band == "uhf": _obj = self._memobj.squelch.uhf + _name = "UHF" val = RadioSettingValueInteger(0, 123, getattr(_obj, "sql%i" % (index))) if index == 0: val.set_mutable(False) - name = "%s Squelch %i" % (band.upper(), index) + name = "%s Squelch %i" % (_name, index) rs = RadioSetting(key, name, val) service.append(rs) @@ -1200,3 +1216,17 @@ class UV5X3(baofeng_common.BaofengCommonHT): return True else: return False + + +@directory.register +class MTCUV5R3Radio(UV5X3): + VENDOR = "MTC" + MODEL = "UV-5R-3" + + _fileid = [UV5R3_fp1, ] + + _magic = [MSTRING_UV5R3, ] + + VALID_BANDS = [(136000000, 174000000), + (200000000, 260000000), + (400000000, 521000000)] diff --git a/chirp/drivers/uv6r.py b/chirp/drivers/uv6r.py index 10fedad..57f3456 100644 --- a/chirp/drivers/uv6r.py +++ b/chirp/drivers/uv6r.py @@ -40,6 +40,7 @@ MSTRING_UV6R = "\x50\xBB\xFF\x20\x14\x11\x22" # Baofeng UV-6R UV6R_fp1 = " BF230#1" +UV6R_fp2 = " BF230#2" DTMF_CHARS = "0123456789 *#ABCD" STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0] @@ -96,7 +97,7 @@ class UV6R(baofeng_common.BaofengCommonHT): VENDOR = "Baofeng" MODEL = "UV-6R" - _fileid = [UV6R_fp1, ] + _fileid = [UV6R_fp2, UV6R_fp1, ] _magic = [MSTRING_UV6R, ] _magic_response_length = 8 @@ -859,7 +860,7 @@ class UV6R(baofeng_common.BaofengCommonHT): match_model = False # testing the file data size - if len(filedata) == 0x2008: + if len(filedata) == 0x2008 or 0x2010: match_size = True # testing the firmware model fingerprint diff --git a/chirp/drivers/vx5.py b/chirp/drivers/vx5.py index fea8659..e14c1f2 100644 --- a/chirp/drivers/vx5.py +++ b/chirp/drivers/vx5.py @@ -19,6 +19,40 @@ from chirp import chirp_common, directory, errors, bitwise from textwrap import dedent MEM_FORMAT = """ +struct mem_struct { + u8 unknown1:2, + half_deviation:1, + cpu_shift:1, + unknown2:1, + sp_rx1:1, + unknown3:1, + sp_rx2:1; + u8 unknown4:4, + tuning_step:4; + bbcd freq[3]; + u8 icon:6, + mode:2; + char name[8]; + bbcd offset[3]; + u8 tmode:4, + power:2, + duplex:2; + u8 unknown5:2, + tone:6; + u8 unknown6:1, + dtcs:7; + u8 unknown7; + u8 unknown8; +}; + +struct flag_struct { + u8 zeros:4, + pskip:1, + skip:1, + visible:1, + used:1; +}; + #seekto 0x002A; struct { u8 current_member; @@ -33,36 +67,12 @@ struct { } bank_groups[5]; #seekto 0x012A; -struct { - u8 zeros:4, - pskip: 1, - skip: 1, - visible: 1, - used: 1; -} flag[220]; +struct flag_struct flag[220]; +struct flag_struct specialflag[20]; -#seekto 0x0269; -struct { - u8 unknown1; - u8 unknown2:2, - half_deviation:1, - unknown3:5; - u8 unknown4:4, - tuning_step:4; - bbcd freq[3]; - u8 icon:6, - mode:2; - char name[8]; - bbcd offset[3]; - u8 tmode:4, - power:2, - duplex:2; - u8 unknown7:2, - tone:6; - u8 unknown8:1, - dtcs:7; - u8 unknown9; -} memory[220]; +#seekto 0x026A; +struct mem_struct memory[220]; +struct mem_struct special[50]; #seekto 0x1D03; u8 current_bank; @@ -76,6 +86,7 @@ POWER_LEVELS = [chirp_common.PowerLevel("Hi", watts=5.00), chirp_common.PowerLevel("L3", watts=2.50), chirp_common.PowerLevel("L2", watts=1.00), chirp_common.PowerLevel("L1", watts=0.05)] +SPECIALS = ["%s%d" % (c, i + 1) for i in range(0, 10) for c in ('L', 'U')] class VX5BankModel(chirp_common.BankModel): @@ -183,6 +194,8 @@ class VX5Radio(yaesu_clone.YaesuCloneModeRadio): rf.valid_power_levels = POWER_LEVELS rf.valid_name_length = 8 rf.valid_characters = chirp_common.CHARSET_ASCII + rf.valid_special_chans = SPECIALS + return rf def process_mmap(self): @@ -192,11 +205,25 @@ class VX5Radio(yaesu_clone.YaesuCloneModeRadio): return repr(self._memobj.memory[number-1]) def get_memory(self, number): - _mem = self._memobj.memory[number-1] - _flg = self._memobj.flag[number-1] - mem = chirp_common.Memory() - mem.number = number + if isinstance(number, str): + mem.number = len(self._memobj.memory) + SPECIALS.index(number) + 1 + mem.extd_number = number + _mem = self._memobj.special[mem.number - + len(self._memobj.memory) - 1] + _flg = self._memobj.specialflag[mem.number - + len(self._memobj.memory) - 1] + elif number > len(self._memobj.memory): + mem.number = number + mem.extd_number = SPECIALS[number - len(self._memobj.memory) - 1] + _mem = self._memobj.special[mem.number - + len(self._memobj.memory) - 1] + _flg = self._memobj.specialflag[mem.number - + len(self._memobj.memory) - 1] + else: + mem.number = number + _mem = self._memobj.memory[mem.number - 1] + _flg = self._memobj.flag[mem.number - 1] if not _flg.visible: mem.empty = True @@ -224,20 +251,31 @@ class VX5Radio(yaesu_clone.YaesuCloneModeRadio): return mem def set_memory(self, mem): - _mem = self._memobj.memory[mem.number-1] - _flg = self._memobj.flag[mem.number-1] + if mem.number > len(self._memobj.memory): + _mem = self._memobj.special[mem.number - + len(self._memobj.memory) - 1] + _flg = self._memobj.specialflag[mem.number - + len(self._memobj.memory) - 1] + else: + _mem = self._memobj.memory[mem.number - 1] + _flg = self._memobj.flag[mem.number - 1] # initialize new channel to safe defaults if not mem.empty and not _flg.used: _flg.used = True _mem.unknown1 = 0x00 - _mem.unknown2 = 0x00 - _mem.unknown3 = 0x00 - _mem.unknown4 = 0x00 - _mem.icon = 12 # file cabinet icon + _mem.unknown2 = 0x0 + _mem.unknown3 = 0x0 + _mem.unknown4 = 0x0000 + _mem.unknown5 = 0x0 + _mem.unknown6 = 0x0 _mem.unknown7 = 0x00 _mem.unknown8 = 0x00 - _mem.unknown9 = 0x00 + _mem.cpu_shift = 0x0 + _mem.sp_rx1 = 0x0 + _mem.sp_rx2 = 0x0 + + _mem.icon = 12 # file cabinet icon if mem.empty and _flg.used and not _flg.visible: _flg.used = False diff --git a/chirp/drivers/vx6.py b/chirp/drivers/vx6.py index d37a94a..bfbc109 100644 --- a/chirp/drivers/vx6.py +++ b/chirp/drivers/vx6.py @@ -217,7 +217,7 @@ class VX6Radio(yaesu_clone.YaesuCloneModeRadio): _model = "AH021" _memsize = 32587 - _block_lengths = [10, 32578] + _block_lengths = [10, 32577] _block_size = 16 @classmethod diff --git a/chirp/drivers/vx8.py b/chirp/drivers/vx8.py index 4fc9836..a87e415 100644 --- a/chirp/drivers/vx8.py +++ b/chirp/drivers/vx8.py @@ -336,7 +336,7 @@ MODES = ["FM", "AM", "WFM"] STEPS = list(chirp_common.TUNING_STEPS) STEPS.remove(30.0) STEPS.append(100.0) -STEPS.insert(2, 0.0) # There is a skipped tuning step at index 2 (?) +STEPS.insert(2, 8.33) # Index 2 is 8.33kHz airband step SKIPS = ["", "S", "P"] VX8_DTMF_CHARS = list("0123456789ABCD*#-") @@ -1398,7 +1398,7 @@ class VX8Radio(yaesu_clone.YaesuCloneModeRadio): try: element.run_apply_callback() except NotImplementedError as e: - LOG.error(e) + LOG.error("vx8.set_settings: %s", e) continue # Find the object containing setting. diff --git a/chirp/drivers/yaesu_clone.py b/chirp/drivers/yaesu_clone.py index fd18507..6efa003 100644 --- a/chirp/drivers/yaesu_clone.py +++ b/chirp/drivers/yaesu_clone.py @@ -43,14 +43,24 @@ def _safe_read(pipe, count): def _chunk_read(pipe, count, status_fn): + timer = time.time() block = 32 data = "" - for _i in range(0, count, block): - data += pipe.read(block) - if data: + while len(data) < count: + # Don't read past the end of our block if we're not on a 32-byte + # boundary + chunk_size = min(block, count - len(data)) + chunk = pipe.read(chunk_size) + if chunk: + timer = time.time() + data += chunk if data[0] == chr(CMD_ACK): data = data[1:] # Chew an echo'd ack if using a 2-pin cable - # LOG.debug("Chewed an ack") + # LOG.debug("Chewed an ack") + if time.time() - timer > 2: + # It's been two seconds since we last saw data from the radio, + # so it's time to give up. + raise errors.RadioError("Timed out reading from radio") status = chirp_common.Status() status.msg = "Cloning from radio" status.max = count diff --git a/chirp/errors.py b/chirp/errors.py index f4d9324..311a1bb 100644 --- a/chirp/errors.py +++ b/chirp/errors.py @@ -42,3 +42,8 @@ class UnsupportedToneError(Exception): class ImageDetectFailed(Exception): """The driver for the supplied image could not be determined""" pass + + +class ImageMetadataInvalidModel(Exception): + """The image contains metadata but no suitable driver is found""" + pass diff --git a/chirp/logger.py b/chirp/logger.py index 6e841bc..6eee8a8 100644 --- a/chirp/logger.py +++ b/chirp/logger.py @@ -86,8 +86,9 @@ class Logger(object): # set CHIRP_DEBUG_LOG in the environment. console_stream = None console_format = '%(levelname)s: %(message)s' - if hasattr(sys, "frozen") or not os.isatty(0) \ - or os.getenv("CHIRP_DEBUG_LOG"): + if 'CHIRP_TESTENV' not in os.environ and ( + hasattr(sys, "frozen") or not os.isatty(0) or + os.getenv("CHIRP_DEBUG_LOG")): p = platform.get_platform() log = file(p.config_file("debug.log"), "w", 0) sys.stdout = log diff --git a/chirp/platform.py b/chirp/platform.py index 3c5bc2e..9b2922b 100644 --- a/chirp/platform.py +++ b/chirp/platform.py @@ -252,7 +252,8 @@ class Platform: "/usr/local/share", "/usr/share", ] - pkgshare_candidates = [os.path.join(i, "chirp") for i in share_candidates] + pkgshare_candidates = [os.path.join(i, "chirp") + for i in share_candidates] search_paths = [execpath] + pkgshare_candidates + share_candidates for path in search_paths: candidate = os.path.join(path, filename) diff --git a/chirp/ui/clone.py b/chirp/ui/clone.py index c5bf888..7245537 100644 --- a/chirp/ui/clone.py +++ b/chirp/ui/clone.py @@ -191,9 +191,16 @@ class CloneSettingsDialog(gtk.Dialog): for alias in rclass.ALIASES: if alias.MODEL == model: alias_match = rclass + alias_class = alias break if alias_match: - cs.radio_class = rclass + + class DynamicRadioAlias(rclass): + VENDOR = alias.VENDOR + MODEL = alias.MODEL + VARIANT = alias.VARIANT + + cs.radio_class = DynamicRadioAlias LOG.debug( 'Chose %s alias for %s because model %s selected' % ( alias_match, cs.radio_class, model)) diff --git a/chirp/ui/importdialog.py b/chirp/ui/importdialog.py index 2bc9899..b854c40 100644 --- a/chirp/ui/importdialog.py +++ b/chirp/ui/importdialog.py @@ -266,7 +266,7 @@ class ImportDialog(gtk.Dialog): "name": name, "comment": comm}) except import_logic.ImportError, e: - LOG.error(e) + LOG.error("Import error: %s", e) error_messages[new] = str(e) continue diff --git a/chirp/ui/mainapp.py b/chirp/ui/mainapp.py index 1ba9d51..e8904e7 100644 --- a/chirp/ui/mainapp.py +++ b/chirp/ui/mainapp.py @@ -351,6 +351,24 @@ of file. else: try: radio = directory.get_radio_by_image(fname) + except errors.ImageMetadataInvalidModel as e: + version = e.metadata.get('chirp_version') + if version: + newer = chirp_common.is_version_newer(version) + LOG.error('Image is from newer CHIRP with a model we ' + 'do not support') + common.show_error( + _('Unable to open this image. It was generated ' + 'with a newer version of CHIRP and thus may ' + 'be for a radio model that is not supported ' + 'by this version. Please update to the latest ' + 'version of CHIRP and try again.')) + else: + LOG.error('Image has metadata but has no chirp_version ' + 'and we do not support the model') + common.show_error( + _('Unable to open this image: unsupported model')) + return except errors.ImageDetectFailed: radio = self._do_manual_select(fname) if not radio: @@ -385,6 +403,7 @@ of file. num=len(eset.rthread.radio.errors)) common.show_error_text(msg, "\r\n".join(eset.rthread.radio.errors)) + self._show_information(radio) def do_live_warning(self, radio): d = gtk.MessageDialog(parent=self, buttons=gtk.BUTTONS_OK) @@ -626,6 +645,37 @@ of file. CONF.set_bool(sql_key, not squelch, "state") return resp == gtk.RESPONSE_YES + def _show_information(self, radio): + message = radio.get_prompts().info + if message is None: + return + + if CONF.get_bool("clone_information", "noconfirm"): + return + + d = gtk.MessageDialog(parent=self, buttons=gtk.BUTTONS_OK) + d.set_markup("<big><b>" + _("{name} Information").format( + name=radio.get_name()) + "</b></big>") + msg = _("{information}").format(information=message) + d.format_secondary_markup(msg) + + again = gtk.CheckButton( + _("Don't show information for any radio again")) + again.show() + again.connect("toggled", lambda action: + self.infomenu.set_active(not action.get_active())) + d.vbox.pack_start(again, 0, 0, 0) + h_button_box = d.vbox.get_children()[2] + try: + ok_button = h_button_box.get_children()[0] + ok_button.grab_default() + ok_button.grab_focus() + except AttributeError: + # don't grab focus on GTK+ 2.0 + pass + d.run() + d.destroy() + def _show_instructions(self, radio, message): if message is None: return @@ -695,6 +745,7 @@ of file. ct.start() else: self.do_open_live(radio) + self._show_information(rclass) # show Info prompt now def do_upload(self, port=None, rtype=None): eset = self.get_current_editorset() @@ -1520,6 +1571,10 @@ of file. devaction = self.menu_ag.get_action(name) devaction.set_visible(action.get_active()) + def do_toggle_clone_information(self, action): + CONF.set_bool("clone_information", + not action.get_active(), "noconfirm") + def do_toggle_clone_instructions(self, action): CONF.set_bool("clone_instructions", not action.get_active(), "noconfirm") @@ -1542,9 +1597,12 @@ of file. conf.set("language", d.choice.get_active_text(), "state") d.destroy() - def load_module(self): - types = [(_("Python Modules") + "*.py", "*.py")] - filen = platform.get_platform().gui_open_file(types=types) + def load_module(self, filen=None): + types = [(_("Python Modules") + " *.py", "*.py"), + (_("Modules") + " *.mod", "*.mod")] + + if filen is None: + filen = platform.get_platform().gui_open_file(types=types) if not filen: return @@ -1553,10 +1611,11 @@ of file. # its normal better judgement directory.enable_reregistrations() + self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color('#ea6262')) + try: - module = file(filen) - code = module.read() - module.close() + with file(filen) as module: + code = module.read() pyc = compile(code, filen, 'exec') # See this for why: # http://stackoverflow.com/questions/2904274/globals-and-locals-in-python-exec @@ -1620,6 +1679,8 @@ of file. self.do_toggle_no_smart_tmode(_action) elif action == "developer": self.do_toggle_developer(_action) + elif action == "clone_information": + self.do_toggle_clone_information(_action) elif action == "clone_instructions": self.do_toggle_clone_instructions(_action) elif action in ["cut", "copy", "paste", "delete", @@ -1714,6 +1775,7 @@ of file. <menuitem action="gethelp"/> <separator/> <menuitem action="report"/> + <menuitem action="clone_information"/> <menuitem action="clone_instructions"/> <menuitem action="developer"/> <separator/> @@ -1809,6 +1871,7 @@ of file. re = not conf.get_bool("no_report") hu = conf.get_bool("hide_unused", "memedit", default=True) dv = conf.get_bool("developer", "state") + cf = not conf.get_bool("clone_information", "noconfirm") ci = not conf.get_bool("clone_instructions", "noconfirm") st = not conf.get_bool("no_smart_tmode", "memedit") @@ -1818,6 +1881,8 @@ of file. None, None, self.mh, hu), ('no_smart_tmode', None, _("Smart Tone Modes"), None, None, self.mh, st), + ('clone_information', None, _("Show Information"), + None, None, self.mh, cf), ('clone_instructions', None, _("Show Instructions"), None, None, self.mh, ci), ('developer', None, _("Enable Developer Functions"), @@ -1834,6 +1899,9 @@ of file. self.add_accel_group(self.menu_uim.get_accel_group()) + self.infomenu = self.menu_uim.get_widget( + "/MenuBar/help/clone_information") + self.clonemenu = self.menu_uim.get_widget( "/MenuBar/help/clone_instructions") @@ -1906,7 +1974,8 @@ of file. def _set_icon(self): this_platform = platform.get_platform() path = (this_platform.find_resource("chirp.png") or - this_platform.find_resource(os.path.join("pixmaps", "chirp.png"))) + this_platform.find_resource(os.path.join("pixmaps", + "chirp.png"))) if os.path.exists(path): self.set_icon_from_file(path) else: @@ -1921,23 +1990,27 @@ of file. LOG.info("Server reports version %s is available" % version) - # Report new updates every seven days - intv = 3600 * 24 * 7 + # Report new updates every three days + intv = 3600 * 24 * 3 if CONF.is_defined("last_update_check", "state") and \ (time.time() - CONF.get_int("last_update_check", "state")) < intv: return CONF.set_int("last_update_check", int(time.time()), "state") - d = gtk.MessageDialog(buttons=gtk.BUTTONS_OK, parent=self, + d = gtk.MessageDialog(buttons=gtk.BUTTONS_OK_CANCEL, parent=self, type=gtk.MESSAGE_INFO) - d.set_property("text", - _("A new version of CHIRP is available: " + - "{ver}. ".format(ver=version) + - "It is recommended that you upgrade, so " + - "go to http://chirp.danplanet.com soon!")) - d.run() + d.label.set_markup( + _('A new version of CHIRP is available: ' + + '{ver}. '.format(ver=version) + + 'It is recommended that you upgrade as soon as possible. ' + 'Please go to: \r\n\r\n<a href="http://chirp.danplanet.com">' + + 'http://chirp.danplanet.com</a>')) + response = d.run() d.destroy() + if response == gtk.RESPONSE_OK: + webbrowser.open('http://chirp.danplanet.com/' + 'projects/chirp/wiki/Download') def _init_macos(self, menu_bar): macapp = None @@ -1962,7 +2035,8 @@ of file. this_platform = platform.get_platform() icon = (this_platform.find_resource("chirp.png") or - this_platform.find_resource(os.path.join("pixmaps", "chirp.png"))) + this_platform.find_resource(os.path.join("pixmaps", + "chirp.png"))) if os.path.exists(icon): icon_pixmap = gtk.gdk.pixbuf_new_from_file(icon) macapp.set_dock_icon_pixbuf(icon_pixmap) @@ -2061,7 +2135,12 @@ of file. CONF.set_bool("warned_about_reporting", True) self.update_recent_files() - self.update_stock_configs() + try: + self.update_stock_configs() + except UnicodeDecodeError: + LOG.exception('We hit bug #272 while working with unicode paths. ' + 'Not copying stock configs so we can continue ' + 'startup.') self.setup_extra_hotkeys() def updates_callback(ver): diff --git a/chirp/ui/memedit.py b/chirp/ui/memedit.py index 3c98c4c..df1f9da 100644 --- a/chirp/ui/memedit.py +++ b/chirp/ui/memedit.py @@ -179,7 +179,7 @@ class MemoryEditor(common.Editor): try: new = chirp_common.parse_freq(new) except ValueError, e: - LOG.error(e) + LOG.error("chirp_common.parse_freq error: %s", e) new = None if not self._features.has_nostep_tuning: @@ -961,15 +961,19 @@ class MemoryEditor(common.Editor): default_col_order = [x for x, y, z in self.cols if z] try: - col_order = self._config.get("column_order_%s" % - self.__class__.__name__).split(",") - if len(col_order) != len(default_col_order): - raise Exception() - for i in col_order: - if i not in default_col_order: + config_setting = self._config.get("column_order_%s" % + self.__class__.__name__) + if config_setting is None: + col_order = default_col_order + else: + col_order = config_setting.split(",") + if len(col_order) != len(default_col_order): raise Exception() + for i in col_order: + if i not in default_col_order: + raise Exception() except Exception, e: - LOG.error(e) + LOG.error("column order setting: %s", e) col_order = default_col_order non_editable = [_("Loc")] diff --git a/chirp/ui/settingsedit.py b/chirp/ui/settingsedit.py index 34707e4..10e9808 100644 --- a/chirp/ui/settingsedit.py +++ b/chirp/ui/settingsedit.py @@ -194,6 +194,8 @@ class SettingsEditor(common.Editor): LOG.error("Unsupported widget type: %s" % value.__class__) widget.set_sensitive(value.get_mutable()) + label.set_mnemonic_widget(widget) + widget.get_accessible().set_name(element.get_shortname()) widget.show() box.pack_start(widget, 1, 1, 1) @@ -112,6 +112,8 @@ else: parser = argparse.ArgumentParser() parser.add_argument("files", metavar="file", nargs='*', help="File to open") +parser.add_argument("--module", metavar="module", + help="Load module on startup") logger.add_version_argument(parser) parser.add_argument("--profile", action="store_true", help="Enable profiling") @@ -125,6 +127,10 @@ if True: from chirp.ui import mainapp a = mainapp.ChirpMain() +# Be sure to load module before opening files +if args.module: + a.load_module(args.module) + for i in args.files: LOG.info("Opening %s", i) a.do_open(i) diff --git a/debian/changelog b/debian/changelog deleted file mode 100644 index 9e2f347..0000000 --- a/debian/changelog +++ /dev/null @@ -1,177 +0,0 @@ -chirp (1:20170714-1) unstable; urgency=medium - - * New upstream version - - -- Iain R. Learmonth <irl@debian.org> Sun, 16 Jul 2017 00:45:28 +0100 - -chirp (1:20170124-1) unstable; urgency=medium - - * New Upstream Version - * debian/control - - Updated Standards Version - - Added myself to uploaders - - -- Dave Hibberd <d@vehibberd.com> Tue, 24 Jan 2017 20:35:53 +0000 - -chirp (1:20161123-1) unstable; urgency=medium - - * New upstream version - - -- Iain R. Learmonth <irl@debian.org> Sat, 03 Dec 2016 15:42:54 +0000 - -chirp (1:20161102-1) unstable; urgency=medium - - * New upstream version (Closes: #843195) - - -- Iain R. Learmonth <irl@debian.org> Tue, 08 Nov 2016 11:56:14 +0000 - -chirp (1:20160717-1) unstable; urgency=medium - - * New upstream version (Closes: #817237) - * Phoning home has been disabled (Closes: #829494) - - -- Iain R. Learmonth <irl@debian.org> Mon, 25 Jul 2016 19:38:03 +0100 - -chirp (1:20160419-1) unstable; urgency=medium - - * New upstream version - * Updates manpages to include working with files - - -- Ana Custura <ana@netstat.org.uk> Fri, 29 Apr 2016 10:42:18 +0100 - -chirp (1:20160415-1) unstable; urgency=medium - - * New upstream version. - * debian/patches: - - New patch to add more detail to the man page - - New patch for desktop file: - - Added Keywords field - - Added ability for files to be opened in CHIRP - - Removing deprecated Encoding field - * debian/control: - - Improving extended description - - -- Iain R. Learmonth <irl@debian.org> Fri, 15 Apr 2016 16:33:08 +0100 - -chirp (1:20160402-1) unstable; urgency=medium - - * New upstream version. - * debian/control: - - Updated standards version to 3.9.7 - - Removed versioned dependency for python - - Changed Vcs-* fields to secure URIs - * debian/copyright: - - Update locations, drivers now in chirp/drivers/ - - -- Iain R. Learmonth <irl@debian.org> Mon, 04 Apr 2016 19:03:59 +0100 - -chirp (1:20160110-1) unstable; urgency=medium - - * New upstream version. - - -- Iain R. Learmonth <irl@debian.org> Wed, 13 Jan 2016 13:00:32 +0000 - -chirp (1:20151225-1) unstable; urgency=medium - - * New upstream version. - - -- Iain R. Learmonth <irl@debian.org> Fri, 25 Dec 2015 11:40:15 +0000 - -chirp (1:20151212-1) unstable; urgency=medium - - * New upstream version. - * Refreshed patch: - - 04-remove-redundant-license.patch - - -- Iain R. Learmonth <irl@debian.org> Sun, 13 Dec 2015 13:07:06 +0000 - -chirp (1:20151023-1) unstable; urgency=medium - - * New upstream version (Closes: #798947) - * Refreshed patches: - - 01-fix-manifest.patch - - 02-fix-setup-py.patch - * d/control: - - Bumped standards version to 3.9.6 - - Added X-Python-Version (>=2.7) - - Removed inactive uploaders - - Added myself as uploader - - Moved Vcs-Git to pkg-hamradio - - Reformatted with cme - * d/watch: - - Fixed for new downloads location - * d/rules: - - Removed useless comments - - -- Iain R. Learmonth <irl@debian.org> Sun, 01 Nov 2015 15:57:22 +0000 - -chirp (0.4.1-1.1) unstable; urgency=medium - - * Non-maintainer upload. - * Drop python-support Build-Depend in favour of dh-python, it's already been - ported to dh_python2 (Closes: #785972). - - -- Stefano Rivera <stefanor@debian.org> Thu, 20 Aug 2015 15:10:55 +0200 - -chirp (0.4.1-1.0) unstable; urgency=medium - - * Non-maintainer upload - * new upstream version fixing critical issue with some Baofeng radios - (Closes: #767029) - - -- Antoine Beaupré <anarcat@debian.org> Mon, 27 Oct 2014 17:08:43 -0400 - -chirp (0.4.0-1) unstable; urgency=low - - * new upstream version, thanks to Christopher Knadle for his help with it - * debian/control: - - Standards-Version: update to 3.9.5 (no changes needed) - - Remove obsolete DM-Upload-Allowed entry - - Cononicalize VCS links - * debian/source/lintian-overrides: - - add override debian-watch-may-check-gpg-signature - upstream does not sign tarballs - - -- Bdale Garbee <bdale@gag.com> Thu, 26 Jun 2014 12:55:21 -0600 - -chirp (0.3.1-3) unstable; urgency=low - - * change architecture to linux-any in control due to #723873 in python-serial - breaking non-linux builds - - -- Bdale Garbee <bdale@gag.com> Sat, 21 Sep 2013 00:44:46 -0600 - -chirp (0.3.1-2) unstable; urgency=low - - * move python dependency to >=2.7, hopefully will resolve kfreebsd build - failures so we can promote to testing .. thanks to Colin Tuckley for - pointing this out. - - -- Bdale Garbee <bdale@gag.com> Sat, 07 Sep 2013 15:41:32 -0600 - -chirp (0.3.1-1) unstable; urgency=low - - * new upstream version, closes: #672318 - * add myself to the Uploaders list - * create a collab-maint git repo to host chirp packaging henceforth - - -- Bdale Garbee <bdale@gag.com> Wed, 07 Aug 2013 22:51:41 -0600 - -chirp (0.3.0-0.1) unstable; urgency=low - - * Non-maintainer upload. - * New upstream version (Closes: #672318) - * updated debian/copyright for 1.0 format - * updated to debhelper compat 9 - * update Standards-Version to 3.9.4 (no changes required) - * add dependencies python-libxml2 and python-serial - * update patches for new upstream version - - -- Christopher Knadle <Chris.Knadle@coredump.us> Sun, 24 Mar 2013 16:19:14 -0400 - -chirp (0.1.12-1) unstable; urgency=low - - * Latest release from upstream - * Ready for initial debian upload (Closes: 612965) - - -- Steve Conklin <steve@conklinhouse.com> Mon, 26 Sep 2011 12:55:16 -0600 diff --git a/debian/clean b/debian/clean deleted file mode 100644 index 2a22c69..0000000 --- a/debian/clean +++ /dev/null @@ -1 +0,0 @@ -MANIFEST.in diff --git a/debian/compat b/debian/compat deleted file mode 100644 index ec63514..0000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -9 diff --git a/debian/control b/debian/control deleted file mode 100644 index c05ceb3..0000000 --- a/debian/control +++ /dev/null @@ -1,41 +0,0 @@ -Source: chirp -Maintainer: Debian Hamradio Maintainers <debian-hams@lists.debian.org> -Uploaders: Iain R. Learmonth <irl@debian.org>, Ana Custura <ana@netstat.org.uk>, Dave Hibberd <d@vehibberd.com> -Section: hamradio -Priority: optional -Build-Depends: debhelper (>= 9), - dh-python, - python, - python-libxml2, - python-serial -Standards-Version: 4.2.0 -Vcs-Browser: https://salsa.debian.org/debian-hamradio-team/chirp -Vcs-Git: https://salsa.debian.org/debian-hamradio-team/chirp.git -Homepage: http://chirp.danplanet.com/ - -Package: chirp -Architecture: linux-any -Depends: ${misc:Depends}, - ${python:Depends}, - python-libxslt1, - python-gtk2, - python-libxml2, - python-serial -Description: Configuration tool for amateur radios - CHIRP is a free, open-source tool for programming your amateur radio. It - supports a large number of manufacturers and models, as well as provides a way - to interface with multiple data sources and formats. - . - CHIRP can handle data in the following formats: - - Comma Separated Values (.csv) - - Comma Separated Values generated by RT Systems (.csv) - - EVE for Yaesu VX-5 (.eve) - - Kenwood HMK format (.hmk) - - Kenwood commercial ITM format (.itm) - - Icom Data Files (.icf) - - ARRL TravelPlus (.tpe) - - VX5 Commander Files (.vx5) - - VX7 Commander Files (.vx7) - . - Most popular modern amateur radios are supported by CHIRP via their interface - cables. diff --git a/debian/copyright b/debian/copyright deleted file mode 100644 index 798a964..0000000 --- a/debian/copyright +++ /dev/null @@ -1,53 +0,0 @@ -Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ -Upstream-Name: chirp -Upstream-Contact: Dan Smith <dsmith@danplanet.com> -Source: http://trac.chirp.danplanet.com/chirp_daily/LATEST/chirp-daily-20151225.tar.gz -Copyright: GPL-3+ - -Files: * -Copyright: 2012 Dan Smith <dsmith@danplanet.com> -License: GPL-3+ - -Files: debian/* -Copyright: 2013 Christopher Knadle <Chris.Knadle@coredump.us> - 2011 Steve Conklin AI4QR <steve@conklinhouse.com> -License: GPL-3+ - -Files: chirp/settings.py chirp/drivers/template.py chirp/drivers/thuv1f.py - chirp/drivers/uv5r.py chirp/drivers/vx3.py -Copyright: 2012 Dan Smith <dsmith@danplanet.com> -License: GPL-2+ - -License: GPL-2+ - 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 package 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/>. - . - On Debian systems, the complete text of the GNU General Public - License version 2 can be found in "/usr/share/common-licenses/GPL-2". - -License: GPL-3+ - 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 package 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/>. - . - On Debian systems, the complete text of the GNU General Public - License version 3 can be found in "/usr/share/common-licenses/GPL-3". diff --git a/debian/patches/01-fix-manifest.patch b/debian/patches/01-fix-manifest.patch deleted file mode 100644 index 4ded6f9..0000000 --- a/debian/patches/01-fix-manifest.patch +++ /dev/null @@ -1,11 +0,0 @@ -Description: Add required pieces to MANIFEST.IN file -Author: Steve Conklin <steve@conklinhouse.com> - ---- /dev/null -+++ b/MANIFEST.IN -@@ -0,0 +1,5 @@ -+include *.xsd -+include share/*.desktop -+include share/chirp.png -+include share/*.1 -+include stock_configs/* diff --git a/debian/patches/02-fix-setup-py.patch b/debian/patches/02-fix-setup-py.patch deleted file mode 100644 index 44f635f..0000000 --- a/debian/patches/02-fix-setup-py.patch +++ /dev/null @@ -1,53 +0,0 @@ -Description: Remove unneeded bits of the setup.py file which - are used to build an entirely different package. -Author: Steve Conklin <steve@conklinhouse.com> - ---- a/setup.py -+++ b/setup.py -@@ -136,45 +136,9 @@ - ] + locale_files) - - --def rpttool_build(): -- from distutils.core import setup -- -- setup(name="rpttool", -- packages=["chirp"], -- version="0.3", -- scripts=["rpttool"], -- description="A frequency tool for ICOM D-STAR Repeaters", -- data_files=[('/usr/sbin', ["tools/icomsio.sh"])], -- ) -- -- --def nuke_manifest(*files): -- for i in ["MANIFEST", "MANIFEST.in"]: -- if os.path.exists(i): -- os.remove(i) -- -- if not files: -- return -- -- f = file("MANIFEST.in", "w") -- for fn in files: -- print >>f, fn -- f.close() -- -- - if sys.platform == "darwin": - macos_build() - elif sys.platform == "win32": - win32_build() - else: -- if os.path.exists("rpttool"): -- nuke_manifest("include tools/icomsio.sh", "include README.rpttool") -- rpttool_build() -- if os.path.exists("chirp/ui"): -- nuke_manifest("include *.xsd", -- "include share/*.desktop", -- "include share/chirp.png", -- "include share/*.1", -- "include stock_configs/*", -- "include COPYING") -- default_build() -+ default_build() diff --git a/debian/patches/04-remove-redundant-license.patch b/debian/patches/04-remove-redundant-license.patch deleted file mode 100644 index bac537f..0000000 --- a/debian/patches/04-remove-redundant-license.patch +++ /dev/null @@ -1,14 +0,0 @@ -Description: The author includes a copy of the Copyright, - but it's not needed as it's the same as one we can reference. -Author: Steve Conklin <steve@conklinhouse.com> - ---- a/setup.py -+++ b/setup.py -@@ -129,7 +129,6 @@ - data_files=[('share/applications', desktop_files), - ('share/chirp/images', image_files), - ('share/chirp', xsd_files), -- ('share/doc/chirp', ['COPYING']), - ('share/pixmaps', ['share/chirp.png']), - ('share/man/man1', ["share/chirpw.1"]), - ('share/chirp/stock_configs', stock_configs), diff --git a/debian/patches/05-manpage-updates.patch b/debian/patches/05-manpage-updates.patch deleted file mode 100644 index 42ccfdc..0000000 --- a/debian/patches/05-manpage-updates.patch +++ /dev/null @@ -1,61 +0,0 @@ -Author: Iain R. Learmonth <irl@debian.org> -Last-Update: 2016-04-15 -Description: Updates to the man page for new CLI options available. - -Index: chirp/share/chirpw.1 -=================================================================== ---- chirp.orig/share/chirpw.1 -+++ chirp/share/chirpw.1 -@@ -2,7 +2,7 @@ - .\" First parameter, NAME, should be all caps - .\" Second parameter, SECTION, should be 1-8, maybe w/ subsection - .\" other parameters are allowed: see man(7), man(1) --.TH CHIRP 1 "February 12, 2011" -+.TH CHIRP 1 "April 28, 2016" - .\" Please adjust this date whenever revising the manpage. - .\" - .\" Some roff macros, for reference: -@@ -19,7 +19,7 @@ - chirpw \- A tool for programming two-way radio equipment - .SH SYNOPSIS - .B chirpw --.RI [ options ] -+.RI [ options ][ file ] - .br - .SH DESCRIPTION - This manual page documents briefly the -@@ -37,10 +37,32 @@ A summary of options is included below. - .B \-\-help - Show summary of options. - .TP -+.B \-h, \-\-help -+Show summary of options. -+.TP -+.B \--version -+Print version and exit -+.TP - .B \-\-profile - Enable Profiling. -+.TP -+.B \-\-quiet -+Decrease verbosity -+.TP -+.B \-v, \-\-verbose -+Increase verbosity -+.TP -+.B \-\-log LOG_FILE -+Log messages to a file -+.TP -+.B \-\-log-level LOG_LEVEL -+Log file verbosity (critical, error, warn, info, debug). Defaults to 'debug'. -+.TP -+.B FILE -+Loads the specified configuration file. Accepted formats: .csv, .eve, .hmk, .itm, .icf, .tpe, .vx5 and .vx7. - .SH AUTHOR - chirpw was written by Dan Smith. - .PP --This manual page was written by Dan Smith (with help from Steve Conklin), --for the Debian project (and may be used by others). -+This manual page was written by Dan Smith (with help from Steve Conklin) and -+updated by Iain R. Learmonth, for the Debian project (and may be used by -+others). diff --git a/debian/patches/06-open-with-desktop.patch b/debian/patches/06-open-with-desktop.patch deleted file mode 100644 index f3a2dd7..0000000 --- a/debian/patches/06-open-with-desktop.patch +++ /dev/null @@ -1,21 +0,0 @@ -Author: Iain R. Learmonth <irl@debian.org> -Last-Update: 2016-04-15 -Description: Allow for files to be opened with chirpw - ---- a/share/chirp.desktop -+++ b/share/chirp.desktop -@@ -1,8 +1,7 @@ - [Desktop Entry] - Version=0.1 --Encoding=UTF-8 - Type=Application --Exec=chirpw -+Exec=chirpw %F - Icon=chirp.png - StartupNotify=true - Terminal=false -@@ -11,3 +10,4 @@ - Name=CHIRP - Comment=CHIRP Radio Programming Tool - GenericName=CHIRP Radio Programming Tool -+Keywords=Hamradio;Programming;Handheld;Radio;Amateur;Programmer diff --git a/debian/patches/07-disable-reporting.patch b/debian/patches/07-disable-reporting.patch deleted file mode 100644 index 368372b..0000000 --- a/debian/patches/07-disable-reporting.patch +++ /dev/null @@ -1,19 +0,0 @@ -Description: Disables all reporting - Prevent chirp from "phoning home" without informed consent. This also - has the nice side-effect of disabling the update nag screen, as chirp no - longer has a concept of releases upstream. -Author: Iain R. Learmonth <irl@debian.org> -Bug-Debian: https://bugs.debian.org/829494 -Last-Update: 2016-07-25 - ---- chirp-20160717.orig/chirp/ui/reporting.py -+++ chirp-20160717/chirp/ui/reporting.py -@@ -33,7 +33,7 @@ import logging - from chirp import CHIRP_VERSION, platform - - REPORT_URL = "http://chirp.danplanet.com/report/report.php?do_report" --ENABLED = True -+ENABLED = False - THREAD_SEM = threading.Semaphore(10) # Maximum number of outstanding threads - LAST = 0 - LAST_TYPE = None diff --git a/debian/patches/series b/debian/patches/series deleted file mode 100644 index 6e329c9..0000000 --- a/debian/patches/series +++ /dev/null @@ -1,6 +0,0 @@ -01-fix-manifest.patch -02-fix-setup-py.patch -04-remove-redundant-license.patch -05-manpage-updates.patch -06-open-with-desktop.patch -07-disable-reporting.patch diff --git a/debian/rules b/debian/rules deleted file mode 100755 index 20c38c8..0000000 --- a/debian/rules +++ /dev/null @@ -1,4 +0,0 @@ -#!/usr/bin/make -f - -%: - dh $@ --with python2 diff --git a/debian/source/format b/debian/source/format deleted file mode 100644 index 163aaf8..0000000 --- a/debian/source/format +++ /dev/null @@ -1 +0,0 @@ -3.0 (quilt) diff --git a/debian/source/lintian-overrides b/debian/source/lintian-overrides deleted file mode 100644 index 94f09ef..0000000 --- a/debian/source/lintian-overrides +++ /dev/null @@ -1,2 +0,0 @@ -# upstream does not GPG sign tarballs at this time -chirp source: debian-watch-may-check-gpg-signature diff --git a/debian/watch b/debian/watch deleted file mode 100644 index 167ce3a..0000000 --- a/debian/watch +++ /dev/null @@ -1,2 +0,0 @@ -version=3 -http://trac.chirp.danplanet.com/chirp_daily/LATEST/ chirp-daily-(\d.*).(?:tgz|tbz2|txz|tar\.(?:gz|bz2|xz)) @@ -0,0 +1,148 @@ +#!/usr/bin/env python +# +# Copyright 2009 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 os +import sys +import serial +import commands + +from chirp import idrp, chirp_common + + +def open_device(): + try: + s = serial.Serial(port="/dev/icom", + baudrate=idrp.IDRPx000V.BAUD_RATE, + timeout=0.1) + except Exception, e: + print "Unable to open serial port %s: %s" % ("/dev/icom", e) + return None + + rp = idrp.IDRPx000V(s) + + return rp + + +def read_freq(): + rp = open_device() + if not rp: + return 0 + + try: + mem = rp.get_memory(0) + except Exception, e: + print "Unable to read memory from device: %s" % e + return 0 + + rp.pipe.close() + + return mem.freq + + +def _set_freq(rp): + try: + mem = rp.get_memory(0) + except Exception, e: + print "Unable to read memory from device: %s" % e + return False + + print "\nNew frequency [%s]: " % chirp_common.format_freq(mem.freq), + input = sys.stdin.readline().strip() + + if not input: + print "Frequency unchanged" + return False + + try: + mem.freq = chirp_common.parse_freq(input) + except Exception: + print "Invalid entry `%s'" % input + return False + + try: + rp.set_memory(mem) + except Exception, e: + print "Failed to set frequency to %s: %s" % \ + (chirp_common.format_freq(mem.freq), e) + return False + + print "Successfully set frequency to %s" % \ + chirp_common.format_freq(mem.freq) + return True + + +def set_freq(): + rp = open_device() + if not rp: + return + + try: + res = _set_freq(rp) + except Exception, e: + print "Unknown error while setting frequency: %s" % e + res = False + + rp.pipe.close() + return res + + +def main_menu(): + print "Looking for a repeater...", + sys.stdout.flush() + freq = read_freq() + if not freq: + return 1 + print "\r \r", + + cmd = "" + while cmd != "3": + print """ +KK7DS ID-RP* Frequency Tool +Current Setting: %s +-------------------------------- +1. Set repeater frequency +2. Re-read current frequency +3. Quit +-------------------------------- +> """ % chirp_common.format_freq(freq), + + cmd = sys.stdin.readline().strip() + + if cmd == "1": + if set_freq(): + freq = read_freq() + elif cmd == "2": + freq = read_freq() + elif cmd != "3": + print "Invalid entry" + + return 0 + + +if __name__ == "__main__": + if os.path.exists("tools/icomsio.sh"): + path = "tools/icomsio.sh" + else: + path = "icomsio.sh" + r = os.system(path) + if r: + sys.exit(r) + + if not os.geteuid() == 0: + print "Sorry, this must be run as root" + sys.exit(1) + sys.exit(main_menu()) @@ -125,7 +125,7 @@ def default_build(): name="chirp", packages=["chirp", "chirp.drivers", "chirp.ui"], version=CHIRP_VERSION, - scripts=["chirpw"], + scripts=["chirpw", "rpttool"], data_files=[('share/applications', desktop_files), ('share/chirp/images', image_files), ('share/chirp', xsd_files), @@ -136,18 +136,6 @@ def default_build(): ] + locale_files) -def rpttool_build(): - from distutils.core import setup - - setup(name="rpttool", - packages=["chirp"], - version="0.3", - scripts=["rpttool"], - description="A frequency tool for ICOM D-STAR Repeaters", - data_files=[('/usr/sbin', ["tools/icomsio.sh"])], - ) - - def nuke_manifest(*files): for i in ["MANIFEST", "MANIFEST.in"]: if os.path.exists(i): @@ -167,14 +155,4 @@ if sys.platform == "darwin": elif sys.platform == "win32": win32_build() else: - if os.path.exists("rpttool"): - nuke_manifest("include tools/icomsio.sh", "include README.rpttool") - rpttool_build() - if os.path.exists("chirp/ui"): - nuke_manifest("include *.xsd", - "include share/*.desktop", - "include share/chirp.png", - "include share/*.1", - "include stock_configs/*", - "include COPYING") - default_build() + default_build() diff --git a/share/chirp.desktop b/share/chirp.desktop index a65edee..966e2a0 100644 --- a/share/chirp.desktop +++ b/share/chirp.desktop @@ -1,13 +1,13 @@ [Desktop Entry] -Version=0.1 -Encoding=UTF-8 Type=Application -Exec=chirpw -Icon=chirp.png -StartupNotify=true +Version=1.0 +Name=CHIRP +GenericName=Radio Programming Tool +Comment=Program amateur radios +Icon=chirp +Exec=chirpw %F Terminal=false -Categories=Application;HamRadio MimeType=inode/directory -Name=CHIRP -Comment=CHIRP Radio Programming Tool -GenericName=CHIRP Radio Programming Tool +Categories=Utility;HamRadio +Keywords=Hamradio;Programming;Handheld;Radio;Amateur;Programmer +StartupNotify=true |
