diff options
| author | Ana C. Custura <ana@netstat.org.uk> | 2019-01-06 21:53:49 +0000 |
|---|---|---|
| committer | Ana C. Custura <ana@netstat.org.uk> | 2019-01-06 21:53:49 +0000 |
| commit | 96512af6a4dbc30c7b1149e38d8dad56b3622fd3 (patch) | |
| tree | 3e76360c1ec76751b9e38df71a0cfc14ede9a66c | |
| parent | 419fb7a940ff1ae9db0cd0d4826c34320b01ed4f (diff) | |
New upstream version 20190104upstream/20190104
| -rw-r--r-- | PKG-INFO | 2 | ||||
| -rw-r--r-- | chirp/__init__.py | 2 | ||||
| -rw-r--r-- | chirp/drivers/bf-t1.py | 8 | ||||
| -rw-r--r-- | chirp/drivers/boblov_x3plus.py | 572 | ||||
| -rw-r--r-- | chirp/drivers/btech.py | 3 | ||||
| -rw-r--r-- | chirp/drivers/ft1d.py | 21 | ||||
| -rw-r--r-- | chirp/drivers/ft2d.py | 3 | ||||
| -rw-r--r-- | chirp/drivers/ft7100.py | 1230 | ||||
| -rw-r--r-- | chirp/drivers/ft7800.py | 3 | ||||
| -rwxr-xr-x | chirp/drivers/ft818.py | 342 | ||||
| -rw-r--r-- | chirp/drivers/kenwood_live.py | 22 | ||||
| -rw-r--r-- | chirp/drivers/kguv9dplus.py | 1890 | ||||
| -rw-r--r-- | chirp/drivers/radioddity_r2.py | 620 | ||||
| -rw-r--r-- | chirp/drivers/retevis_rt22.py | 17 | ||||
| -rw-r--r-- | chirp/drivers/ts850.py | 254 |
15 files changed, 4966 insertions, 23 deletions
@@ -1,6 +1,6 @@ Metadata-Version: 1.0 Name: chirp -Version: daily-20180815 +Version: daily-20190104 Summary: UNKNOWN Home-page: UNKNOWN Author: UNKNOWN diff --git a/chirp/__init__.py b/chirp/__init__.py index f9b8f31..03a22a2 100644 --- a/chirp/__init__.py +++ b/chirp/__init__.py @@ -17,7 +17,7 @@ import os import sys from glob import glob -CHIRP_VERSION="daily-20180815" +CHIRP_VERSION="daily-20190104" module_dir = os.path.dirname(sys.modules["chirp"].__file__) __all__ = [] diff --git a/chirp/drivers/bf-t1.py b/chirp/drivers/bf-t1.py index 9d29640..2f6c393 100644 --- a/chirp/drivers/bf-t1.py +++ b/chirp/drivers/bf-t1.py @@ -841,25 +841,25 @@ class BFT1(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): setattr(obj, setting.get_name(), int(setting.value) * 10) rs = RadioSetting("vhfl", "VHF Low Limit", - RadioSettingValueInteger(136, 174, int( + RadioSettingValueInteger(130, 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( + RadioSettingValueInteger(130, 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( + RadioSettingValueInteger(400, 520, int( _settings.uhfl) / 10)) rs.set_apply_callback(apply_limit, _settings) adv.append(rs) rs = RadioSetting("uhfh", "UHF High Limit", - RadioSettingValueInteger(400, 470, int( + RadioSettingValueInteger(400, 520, int( _settings.uhfh) / 10)) rs.set_apply_callback(apply_limit, _settings) adv.append(rs) diff --git a/chirp/drivers/boblov_x3plus.py b/chirp/drivers/boblov_x3plus.py new file mode 100644 index 0000000..309f055 --- /dev/null +++ b/chirp/drivers/boblov_x3plus.py @@ -0,0 +1,572 @@ +""" +Radio driver for the Boblov X3 Plus Motorcycle Helmet Radio +""" +# Copyright 2018 Robert C Jennings <rcj4747@gmail.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import logging +import struct +import time + +from datetime import datetime +from textwrap import dedent + +from chirp import ( + bitwise, + chirp_common, + directory, + errors, + memmap, + util, +) +from chirp.settings import ( + RadioSetting, + RadioSettingGroup, + RadioSettings, + RadioSettingValueBoolean, + RadioSettingValueInteger, + RadioSettingValueList, +) + +LOG = logging.getLogger(__name__) + + +@directory.register +class BoblovX3Plus(chirp_common.CloneModeRadio, + chirp_common.ExperimentalRadio): + """Boblov X3 Plus motorcycle/cycling helmet radio""" + + VENDOR = 'Boblov' + MODEL = 'X3Plus' + BAUD_RATE = 9600 + CHANNELS = 16 + + MEM_FORMAT = """ + #seekto 0x0010; + struct { + lbcd rxfreq[4]; + lbcd txfreq[4]; + lbcd rxtone[2]; + lbcd txtone[2]; + u8 unknown1:1, + compander:1, + scramble:1, + skip:1, + highpower:1, + narrow:1, + unknown2:1, + bcl:1; + u8 unknown3[3]; + } memory[16]; + #seekto 0x03C0; + struct { + u8 unknown1:4, + voiceprompt:2, + batterysaver:1, + beep:1; + u8 squelchlevel; + u8 unknown2; + u8 timeouttimer; + u8 voxlevel; + u8 unknown3; + u8 unknown4; + u8 voxdelay; + } settings; + """ + + # Radio command data + CMD_ACK = '\x06' + CMD_IDENTIFY = '\x02' + CMD_PROGRAM_ENTER = '.VKOGRAM' + CMD_PROGRAM_EXIT = '\x62' # 'b' + CMD_READ = 'R' + CMD_WRITE = 'W' + + BLOCK_SIZE = 0x08 + + VOICE_LIST = ['Off', 'Chinese', 'English'] + TIMEOUTTIMER_LIST = ['Off', '30 seconds', '60 seconds', '90 seconds', + '120 seconds', '150 seconds', '180 seconds', + '210 seconds', '240 seconds', '270 seconds', + '300 seconds'] + VOXLEVEL_LIST = ['Off', '1', '2', '3', '4', '5', '6', '7', '8', '9'] + VOXDELAY_LIST = ['1 seconds', '2 seconds', + '3 seconds', '4 seconds', '5 seconds'] + X3P_POWER_LEVELS = [chirp_common.PowerLevel('Low', watts=0.5), + chirp_common.PowerLevel('High', watts=2.00)] + + _memsize = 0x03F0 + _ranges = [ + (0x0000, 0x03F0), + ] + + @classmethod + def get_prompts(cls): + rp = chirp_common.RadioPrompts() + rp.experimental = _(dedent("""\ + The X3Plus driver is currently experimental. + + There are no known issues but you should proceed with caution. + + Please save an unedited copy of your first successful + download to a CHIRP Radio Images (*.img) file. + """)) + return rp + + @classmethod + def match_model(cls, filedata, filename): + """Given contents of a stored file (@filedata), return True if + this radio driver handles the represented model""" + + if len(filedata) != cls._memsize: + LOG.debug('Boblov_x3plus: match_model: size mismatch') + return False + + LOG.debug('Boblov_x3plus: match_model: size matches') + + if 'P310' in filedata[0x03D0:0x03D8]: + LOG.debug('Boblov_x3plus: match_model: radio ID matches') + return True + + LOG.debug('Boblov_x3plus: match_model: no radio ID match') + return False + + def get_features(self): + """Return a RadioFeatures object for this radio""" + + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.valid_modes = ['NFM', 'FM'] # 12.5 KHz, 25 kHz. + rf.valid_power_levels = self.X3P_POWER_LEVELS + rf.valid_skips = ['', 'S'] + rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross'] + rf.valid_duplexes = ['', '-', '+', 'split', 'off'] + rf.can_odd_split = True + rf.has_rx_dtcs = True + rf.has_ctone = True + rf.has_cross = True + rf.valid_cross_modes = [ + 'Tone->Tone', + 'DTCS->', + '->DTCS', + 'Tone->DTCS', + 'DTCS->Tone', + '->Tone', + 'DTCS->DTCS'] + rf.has_tuning_step = False + rf.has_bank = False + rf.has_name = False + rf.memory_bounds = (1, self.CHANNELS) + rf.valid_bands = [(400000000, 470000000)] + return rf + + def process_mmap(self): + """Process a newly-loaded or downloaded memory map""" + self._memobj = bitwise.parse(self.MEM_FORMAT, self._mmap) + + def sync_in(self): + "Initiate a radio-to-PC clone operation" + + LOG.debug('Cloning from radio') + status = chirp_common.Status() + status.msg = 'Cloning from radio' + status.cur = 0 + status.max = self._memsize + self.status_fn(status) + + self._enter_programming_mode() + + data = '' + for addr in range(0, self._memsize, self.BLOCK_SIZE): + status.cur = addr + self.BLOCK_SIZE + self.status_fn(status) + + block = self._read_block(addr, self.BLOCK_SIZE) + data += block + + LOG.debug('Address: %04x', addr) + LOG.debug(util.hexprint(block)) + + self._exit_programming_mode() + + self._mmap = memmap.MemoryMap(data) + self.process_mmap() + + def sync_out(self): + "Initiate a PC-to-radio clone operation" + + LOG.debug('Upload to radio') + status = chirp_common.Status() + status.msg = 'Uploading to radio' + status.cur = 0 + status.max = self._memsize + self.status_fn(status) + + self._enter_programming_mode() + + for start_addr, end_addr in self._ranges: + for addr in range(start_addr, end_addr, self.BLOCK_SIZE): + status.cur = addr + self.BLOCK_SIZE + self.status_fn(status) + + self._write_block(addr, self.BLOCK_SIZE) + + self._exit_programming_mode() + + def get_raw_memory(self, number): + """Return a raw string describing the memory at @number""" + return repr(self._memobj.memory[number - 1]) + + @staticmethod + def _decode_tone(val): + val = int(val) + if val == 16665: + return '', None, None + elif val >= 12000: + return 'DTCS', val - 12000, 'R' + elif val >= 8000: + return 'DTCS', val - 8000, 'N' + + return 'Tone', val / 10.0, None + + @staticmethod + def _encode_tone(memval, mode, value, pol): + 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 get_memory(self, number): + """Return a Memory object for the memory at location @number""" + try: + rmem = self._memobj.memory[number - 1] + except KeyError: + raise errors.InvalidMemoryLocation('Unknown channel %s' % number) + + if number < 1 or number > self.CHANNELS: + raise errors.InvalidMemoryLocation( + 'Channel number must be 1 and %s' % self.CHANNELS) + + mem = chirp_common.Memory() + mem.number = number + mem.freq = int(rmem.rxfreq) * 10 + + # A blank (0MHz) or 0xFFFFFFFF frequency is considered empty + if mem.freq == 0 and rmem.rxfreq.get_raw() == '\xFF\xFF\xFF\xFF': + LOG.debug('empty channel %d', number) + mem.freq = 0 + mem.empty = True + return mem + + if rmem.txfreq.get_raw() == '\xFF\xFF\xFF\xFF': + mem.duplex = 'off' + mem.offset = 0 + elif int(rmem.rxfreq) == int(rmem.txfreq): + mem.duplex = '' + mem.offset = 0 + else: + mem.duplex = '-' if int(rmem.rxfreq) > int(rmem.txfreq) else '+' + mem.offset = abs(int(rmem.rxfreq) - int(rmem.txfreq)) * 10 + + mem.mode = 'NFM' if rmem.narrow else 'FM' + mem.skip = 'S' if rmem.skip else '' + mem.power = self.X3P_POWER_LEVELS[rmem.highpower] + + txtone = self._decode_tone(rmem.txtone) + rxtone = self._decode_tone(rmem.rxtone) + chirp_common.split_tone_decode(mem, txtone, rxtone) + + mem.extra = RadioSettingGroup('Extra', 'extra') + mem.extra.append(RadioSetting('bcl', 'Busy Channel Lockout', + RadioSettingValueBoolean( + current=(not rmem.bcl)))) + mem.extra.append(RadioSetting('scramble', 'Scramble', + RadioSettingValueBoolean( + current=(not rmem.scramble)))) + mem.extra.append(RadioSetting('compander', 'Compander', + RadioSettingValueBoolean( + current=(not rmem.compander)))) + + return mem + + def set_memory(self, memory): + """Set the memory object @memory""" + rmem = self._memobj.memory[memory.number - 1] + + if memory.empty: + rmem.set_raw('\xFF' * (rmem.size() / 8)) + return + + rmem.rxfreq = memory.freq / 10 + + set_txtone = True + if memory.duplex == 'off': + for i in range(0, 4): + rmem.txfreq[i].set_raw('\xFF') + # If recieve only then txtone value should be none + self._encode_tone(rmem.txtone, mode='', value=None, pol=None) + set_txtone = False + elif memory.duplex == 'split': + rmem.txfreq = memory.offset / 10 + elif memory.duplex == '+': + rmem.txfreq = (memory.freq + memory.offset) / 10 + elif memory.duplex == '-': + rmem.txfreq = (memory.freq - memory.offset) / 10 + else: + rmem.txfreq = memory.freq / 10 + + txtone, rxtone = chirp_common.split_tone_encode(memory) + if set_txtone: + self._encode_tone(rmem.txtone, *txtone) + self._encode_tone(rmem.rxtone, *rxtone) + + rmem.narrow = 'N' in memory.mode + rmem.skip = memory.skip == 'S' + + for setting in memory.extra: + # NOTE: Only three settings right now, all are inverted + setattr(rmem, setting.get_name(), not int(setting.value)) + + def get_settings(self): + """ + Return a RadioSettings list containing one or more RadioSettingGroup + or RadioSetting objects. These represent general settings that can + be adjusted on the radio. + """ + cur = self._memobj.settings + basic = RadioSettingGroup('basic', 'Basic Settings') + rs = RadioSetting('squelchlevel', 'Squelch level', + RadioSettingValueInteger( + minval=0, maxval=9, + current=cur.squelchlevel)) + basic.append(rs) + rs = RadioSetting('timeouttimer', 'Timeout timer', + RadioSettingValueList( + options=self.TIMEOUTTIMER_LIST, + current=self.TIMEOUTTIMER_LIST[cur.timeouttimer])) + basic.append(rs) + rs = RadioSetting('voiceprompt', 'Voice prompt', + RadioSettingValueList( + options=self.VOICE_LIST, + current=self.VOICE_LIST[cur.voiceprompt])) + basic.append(rs) + rs = RadioSetting('voxlevel', 'Vox level', + RadioSettingValueList( + options=self.VOXLEVEL_LIST, + current=self.VOXLEVEL_LIST[cur.voxlevel])) + basic.append(rs) + rs = RadioSetting('voxdelay', 'VOX delay', + RadioSettingValueList( + options=self.VOXDELAY_LIST, + current=self.VOXDELAY_LIST[cur.voxdelay])) + basic.append(rs) + basic.append(RadioSetting('batterysaver', 'Battery saver', + RadioSettingValueBoolean( + current=cur.batterysaver))) + basic.append(RadioSetting('beep', 'Beep', + RadioSettingValueBoolean( + current=cur.beep))) + return RadioSettings(basic) + + def set_settings(self, settings): + """ + Accepts the top-level RadioSettingGroup returned from + get_settings() and adjusts the values in the radio accordingly. + This function expects the entire RadioSettingGroup hierarchy + returned from get_settings(). + """ + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + 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) + setattr(obj, setting, element.value) + except Exception: + LOG.debug(element.get_name()) + raise + + def _write(self, data, timeout=3): + """ + Write data to the serial port and consume the echoed response + + The radio echos the data it is sent before replying. Send the + data to the radio, consume the reply, and ensure that the reply + is the same as the data sent. + """ + + serial = self.pipe + expected = len(data) + resp = b'' + start = datetime.now() + + # LOG.debug('WRITE(%02d): %s', expected, util.hexprint(data).rstrip()) + serial.write(data) + while True: + if not expected: + break + rbytes = serial.read(expected) + resp += rbytes + expected -= len(rbytes) + if (datetime.now() - start).seconds > timeout: + raise errors.RadioError('Timeout while reading from radio') + if resp != data: + raise errors.RadioError('Echoed response did not match sent data') + + def _read(self, length, timeout=3): + """Read data from the serial port""" + + resp = b'' + serial = self.pipe + remaining = length + start = datetime.now() + + if not remaining: + return resp + + while True: + rbytes = serial.read(remaining) + resp += rbytes + remaining -= len(rbytes) + if not remaining: + break + if (datetime.now() - start).seconds > timeout: + raise errors.RadioError('Timeout while reading from radio') + time.sleep(0.1) + + # LOG.debug('READ(%02d): %s', length, util.hexprint(resp).rstrip()) + return resp + + def _read_block(self, block_addr, block_size): + + LOG.debug('Reading block %04x...', block_addr) + cmd = struct.pack('>cHb', self.CMD_READ, block_addr, + block_size) + resp_prefix = self.CMD_WRITE + cmd[1:] + + try: + msg = ('Failed to write command to radio for block ' + 'read at %04x' % block_addr) + self._write(cmd) + + msg = ('Failed to read response from radio for block ' + 'read at %04x' % block_addr) + response = self._read(len(cmd) + block_size) + + if response[:len(cmd)] != resp_prefix: + raise errors.RadioError('Error reading block %04x, ' + 'Command not returned.' % (block_addr)) + + msg = ('Failed to write ACK to radio after block read at ' + '%04x' % block_addr) + self._write(self.CMD_ACK) + + msg = ('Failed to read ACK from radio after block read at ' + '%04x' % block_addr) + ack = self._read(1) + except Exception: + LOG.debug(msg, exc_info=True) + raise errors.RadioError(msg) + + if ack != self.CMD_ACK: + raise errors.RadioError('No ACK reading block ' + '%04x.' % (block_addr)) + + return response[len(cmd):] + + def _write_block(self, block_addr, block_size): + + cmd = struct.pack('>cHb', self.CMD_WRITE, block_addr, block_size) + data = self.get_mmap()[block_addr:block_addr + 8] + + LOG.debug('Writing Data:\n%s%s', + util.hexprint(cmd), util.hexprint(data)) + + try: + self._write(cmd + data) + if self._read(1) != self.CMD_ACK: + raise Exception('No ACK') + except Exception: + msg = 'Failed to send block to radio at %04x' % block_addr + LOG.debug(msg, exc_info=True) + raise errors.RadioError(msg) + + def _enter_programming_mode(self): + + LOG.debug('Entering programming mode') + try: + msg = 'Error communicating with radio entering programming mode.' + self._write(self.CMD_PROGRAM_ENTER) + time.sleep(0.5) + ack = self._read(1) + + if not ack: + raise errors.RadioError('No response from radio') + elif ack != self.CMD_ACK: + raise errors.RadioError('Radio refused to enter ' + 'programming mode') + + msg = 'Error communicating with radio during identification' + self._write(self.CMD_IDENTIFY) + ident = self._read(8) + + if not ident.startswith('SMP558'): + LOG.debug(util.hexprint(ident)) + raise errors.RadioError('Radio returned unknown ID string') + + msg = ('Error communicating with radio while querying ' + 'model identifier') + self._write(self.CMD_ACK) + + msg = 'Error communicating with radio on final handshake' + ack = self._read(1) + + if ack != self.CMD_ACK: + raise errors.RadioError('Radio refused to enter programming ' + 'mode failed on final handshake.') + except Exception: + LOG.debug(msg, exc_info=True) + raise errors.RadioError(msg) + + def _exit_programming_mode(self): + try: + self._write(self.CMD_PROGRAM_EXIT) + except Exception: + msg = 'Radio refused to exit programming mode' + LOG.debug(msg, exc_info=True) + raise errors.RadioError(msg) + LOG.debug('Exited programming mode') diff --git a/chirp/drivers/btech.py b/chirp/drivers/btech.py index f49a484..23af957 100644 --- a/chirp/drivers/btech.py +++ b/chirp/drivers/btech.py @@ -220,6 +220,7 @@ QB25_fp = "QB-25" # KT8900D (dual band) KT8900D_fp = "VC2002" +KT8900D_fp1 = "VC8632" # LUITON LT-588UV LT588UV_fp = "V2G1F4" @@ -3696,4 +3697,4 @@ class KT8900D(BTechColor): _vhf_range = (136000000, 175000000) _uhf_range = (400000000, 481000000) _magic = MSTRING_KT8900D - _fileid = [KT8900D_fp, ] + _fileid = [KT8900D_fp, KT8900D_fp1] diff --git a/chirp/drivers/ft1d.py b/chirp/drivers/ft1d.py index 0f79f8e..06a20ed 100644 --- a/chirp/drivers/ft1d.py +++ b/chirp/drivers/ft1d.py @@ -122,12 +122,21 @@ struct { } message; } opening_message; -#seekto 0x0e4a; +#seekto 0x%04X; // FT-1D:0e4a, FT2D:094a struct { u8 memory[16]; } dtmf[10]; #seekto 0x154a; +// These "channels" seem to actually be a structure: +// first five bits are flags +// 0 Unused (1=entry is unused) +// 1 SW Broadcast +// 2 VHF Marine +// 3 WX (weather) +// 4 ? a mode? ? +// 11 bits of index into frequency tables +// struct { u16 channel[100]; } bank_members[24]; @@ -449,6 +458,9 @@ class FT1BankModel(chirp_common.BankModel): for channel in self._channel_numbers_in_bank(bank): chosen_bank[0] = bank.index chosen_mr[0] = channel + if channel & 0x7000 != 0: + # Ignore preset channels without comment DAR + break if not flags[channel].nosubvfo: chosen_bank[1] = bank.index chosen_mr[1] = channel @@ -488,6 +500,10 @@ class FT1BankModel(chirp_common.BankModel): empty = 0 for index, channel_number in enumerate(sorted(channels_in_bank)): _members.channel[index] = channel_number - 1 + if channel_number & 0x7000 != 0: + LOG.warn("Bank %d uses Yaesu preset frequency id=%04X. " + "Chirp cannot see or change that entry." % ( + bank.index, channel_number)) empty = index + 1 for index in range(empty, len(_members.channel)): _members.channel[index] = 0xFFFF @@ -546,7 +562,8 @@ class FT1Radio(yaesu_clone.YaesuCloneModeRadio): _memsize = 130507 _block_lengths = [10, 130497] _block_size = 32 - _mem_params = (900, # size of memories array + _mem_params = (0xe4a, # location of DTMF storage + 900, # size of memories array 900, # size of flags array 0xFECA, # APRS beacon metadata address. 60, # Number of beacons stored. diff --git a/chirp/drivers/ft2d.py b/chirp/drivers/ft2d.py index 50476cc..f832af8 100644 --- a/chirp/drivers/ft2d.py +++ b/chirp/drivers/ft2d.py @@ -69,7 +69,8 @@ class FT2D(ft1d.FT1Radio): _model = "AH60M" # Get this from chirp .img file after saving once _has_vibrate = True - _mem_params = (999, # size of memories array + _mem_params = (0x94a, # Location of DTMF storage + 999, # size of memories array 999, # size of flags array 0xFECA, # APRS beacon metadata address. 60, # Number of beacons stored. diff --git a/chirp/drivers/ft7100.py b/chirp/drivers/ft7100.py new file mode 100644 index 0000000..aef5d6a --- /dev/null +++ b/chirp/drivers/ft7100.py @@ -0,0 +1,1230 @@ +# Copyright 2011 Dan Smith <dsmith@danplanet.com> +# +# FT-2900-specific modifications by Richard Cochran, <ag6qr@sonic.net> +# Initial work on settings by Chris Fosnight, <chris.fosnight@gmail.com> +# FT-7100-specific modifications by Bruno Maire, <bruno@e48.ch> +# +# 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 time +import logging +import copy + +from chirp import util, memmap, chirp_common, bitwise, directory, errors +from chirp.drivers.yaesu_clone import YaesuCloneModeRadio +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueList, RadioSettingValueString, RadioSettings, \ + RadioSettingValueInteger, RadioSettingValueBoolean + +from textwrap import dedent + +LOG = logging.getLogger(__name__) + +ACK = "\x06" +NB_OF_BLOCKS = 248 +BLOCK_LEN = 32 + +def _send(pipe, data): + time.sleep(0.035) # Same delay as "FT7100 Programmer" from RT Systems + #pipe.write(data) --> It seems, that the single bytes are sent too fast + for ch in data: + pipe.write(ch) + time.sleep(0.0012) # Ok + #time.sleep(0.0011) Too short. No ACK after a few packets + echo = pipe.read(len(data)) + if data == "": + raise Exception("Failed to read echo. Maybe serial hardware not connected." + " Maybe radio not powered or not in receiving mode.") + if data != echo: + LOG.debug("expecting echo\n%s\n", util.hexprint(data)) + LOG.debug("got echo\n%s\n", util.hexprint(echo)) + raise Exception("Got false echo. Expected: '{}', got: '{}'." + .format(data, echo)) + +def _send_ack(pipe): + time.sleep(0.01) # Wait for radio input buffer ready + #time.sleep(0.0003) Absolute working minimum + _send(pipe, ACK) + +def _wait_for_ack(pipe): + echo = pipe.read(1) + if echo == "": + raise Exception("Failed to read ACK. No response from radio.") + if echo != ACK: + raise Exception("Failed to read ACK. Expected: '{}', got: '{}'." + .format(util.hexprint(ACK), util.hexprint(echo))) + +def _download(radio): + LOG.debug("in _download\n") + +# import ipdb; ipdb.set_trace() + + data = "" + for _i in range(0, 60): + data = radio.pipe.read(BLOCK_LEN) + LOG.debug("Header:\n%s", util.hexprint(data)) + LOG.debug("len(header) = %s\n", len(data)) + + if data == radio.IDBLOCK: + break + + if data == "": + raise Exception("Got no data from radio.") + if data != radio.IDBLOCK: + raise Exception("Got false header. Expected: '{}', got: '{}'." + .format(radio.IDBLOCK, data)) + + _send_ack(radio.pipe) + + # read 16 Byte block + data = radio.pipe.read(16) + #LOG.debug("16 Byte bloc:\n%s", util.hexprint(data)) + #LOG.debug("len(data) = %s\n", len(data)) + _send_ack(radio.pipe) + + # initialize data, the big var that holds all memory + data = "" + + for block_nr in range(NB_OF_BLOCKS): + chunk = radio.pipe.read(BLOCK_LEN) + #LOG.debug("Block %i ", (block_nr)) + #LOG.debug("Got: %i:\n%s", (len(chunk), util.hexprint(chunk))) + if len(chunk) != BLOCK_LEN: + LOG.debug("len chunk is %i\n", (len(chunk))) + raise Exception("Failed to get full data block") + else: + data += chunk + _send_ack(radio.pipe) + + if radio.status_fn: + status = chirp_common.Status() + status.max = NB_OF_BLOCKS * BLOCK_LEN + status.cur = len(data) + status.msg = "Cloning from radio" + radio.status_fn(status) + + LOG.debug("Total: %i", len(data)) + _send_ack(radio.pipe) + + # for debugging purposes, dump the channels, in hex. + for _i in range(0, (NB_OF_BLOCKS * BLOCK_LEN) / 26): + _start_data = 4 + 26 * _i + chunk = data[_start_data:_start_data + 26] + LOG.debug("channel %i:\n%s", _i-21, util.hexprint(chunk)) + + return memmap.MemoryMap(data) + + +def _upload(radio): + +# import ipdb; ipdb.set_trace() + + data = radio.pipe.read(256) # Clear buffer + _send(radio.pipe, radio.IDBLOCK) + _wait_for_ack(radio.pipe) + + # write 16 Byte block + _send(radio.pipe, "\xCC\x77\x01\x00\x0C\x07\x0C\x07" + "\x00\x00\x00\x00\x00\x00\x00\x00") + _wait_for_ack(radio.pipe) + + for block_nr in range(NB_OF_BLOCKS): + data = radio.get_mmap()[block_nr * BLOCK_LEN:(block_nr + 1) * BLOCK_LEN] + + LOG.debug("Writing block_nr %i:\n%s", block_nr, util.hexprint(data)) + + _send(radio.pipe, data) + _wait_for_ack(radio.pipe) + + if radio.status_fn: + status = chirp_common.Status() + status.max = NB_OF_BLOCKS * BLOCK_LEN + status.cur = block_nr * BLOCK_LEN + status.msg = "Cloning to radio" + radio.status_fn(status) + block_nr += 1 + +MEM_FORMAT = """ +struct mem { + u8 is_used:1, + is_masked:1, + is_skip:1, + unknown11:3, + show_name:1, + is_split:1; + u8 unknown2; + ul32 freq_rx_Hz; + ul32 freq_tx_Hz; + ul16 offset_10khz; + u8 unknown_dependent_of_band_144_b0000_430_b0101:4, + tuning_step_index_1_2:4; + u8 unknown51:2, + is_offset_minus:1, + is_offset_plus:1, + unknown52:1, + tone_mode_index:3; + u8 tone_index; + u8 dtcs_index; + u8 is_mode_am:1, + unknown71:2, + is_packet96:1 + unknown72:2, + power_index:2; + u8 unknown81:2, + tuning_step_index_2_2:4, + unknown82:2; + char name[6]; + u8 unknown9; + u8 unknownA; +}; + +// Settings are often present multiple times. +// The memories which is written to are mapped here +struct +{ +#seekto 0x41; + u8 current_band; +#seekto 0xa1; + u8 apo; +#seekto 0xa2; + u8 ars_vhf; +#seekto 0xe2; + u8 ars_uhf; +#seekto 0xa3; + u8 arts_vhf; +#seekto 0xa3; + u8 arts_uhf; +#seekto 0xa4; + u8 beep; +#seekto 0xa5; + u8 cwid; +#seekto 0x80; + char cwidw[6]; +#seekto 0xa7; + u8 dim; +#seekto 0xaa; + u8 dcsnr_vhf; +#seekto 0xea; + u8 dcsnr_uhf; +#seekto 0xab; + u8 disp; +#seekto 0xac; + u8 dtmfd; +#seekto 0xad; + u8 dtmfs; +#seekto 0xae; + u8 dtmfw; +#seekto 0xb0; + u8 lockt; +#seekto 0xb1; + u8 mic; +#seekto 0xb2; + u8 mute; +#seekto 0xb4; + u8 button[4]; +#seekto 0xb8; + u8 rf_sql_vhf; +#seekto 0xf8; + u8 rf_sql_uhf; +#seekto 0xb9; + u8 scan_vhf; +#seekto 0xf9; + u8 scan_uhf; +#seekto 0xbc; + u8 speaker_cnt; +#seekto 0xff; + u8 tot; +#seekto 0xc0; + u8 txnar_vhf; +#seekto 0x100; + u8 txnar_uhf; +#seekto 0xc1; + u8 vfotr; +#seekto 0xc2; + u8 am; +} overlay; + +// All known memories +#seekto 0x20; + u8 nb_mem_used_vhf; +#seekto 0x22; + u8 nb_mem_used_vhf_and_limits; +#seekto 0x24; + u8 nb_mem_used_uhf; +#seekto 0x26; + u8 nb_mem_used_uhf_and_limits; + +#seekto 0x41; + u8 current_band; + +#seekto 0x42; + u8 current_nb_mem_used_vhf_maybe_not; + +#seekto 0x4c; + u8 priority_channel_maybe_1; // not_implemented + u8 priority_channel_maybe_2; // not_implemented + u8 priority_channel; // not_implemented + +#seekto 0x87; + u8 opt_01_apo_1_4; +#seekto 0xa1; + u8 opt_01_apo_2_4; +#seekto 0xc5; + u8 opt_01_apo_3_4; +#seekto 0xe1; + u8 opt_01_apo_4_4; + +#seekto 0x88; + u8 opt_02_ars_vhf_1_2; +#seekto 0xa2; + u8 opt_02_ars_vhf_2_2; +#seekto 0xc6; + u8 opt_02_ars_uhf_1_2; +#seekto 0xe2; + u8 opt_02_ars_uhf_2_2; + +#seekto 0x89; + u8 opt_03_arts_mode_vhf_1_2; +#seekto 0xa3; + u8 opt_03_arts_mode_vhf_2_2; +#seekto 0xc7; + u8 opt_03_arts_mode_uhf_1_2; +#seekto 0xa3; + u8 opt_03_arts_mode_vhf_2_2; + +#seekto 0x8a; + u8 opt_04_beep_1_2; +#seekto 0xa4; + u8 opt_04_beep_2_2; + +#seekto 0x8b; + u8 opt_05_cwid_on_1_4; +#seekto 0xa5; + u8 opt_05_cwid_on_2_4; +#seekto 0xc9; + u8 opt_05_cwid_on_3_4; +#seekto 0xe5; + u8 opt_05_cwid_on_4_4; + +#seekto 0x80; + char opt_06_cwidw[6]; + +#seekto 0x8d; + u8 opt_07_dim_1_4; +#seekto 0xa7; + u8 opt_07_dim_2_4; +#seekto 0xcb; + u8 opt_07_dim_3_4; +#seekto 0xe7; + u8 opt_07_dim_4_4; + +#seekto 0x90; + u8 opt_10_dcsnr_vhf_1_2; +#seekto 0xaa; + u8 opt_10_dcsnr_vhf_2_2; +#seekto 0xce; + u8 opt_10_dcsnr_uhf_1_2; +#seekto 0xea; + u8 opt_10_dcsnr_uhf_2_2; + +#seekto 0x91; + u8 opt_11_disp_1_4; +#seekto 0xab; + u8 opt_11_disp_2_4; +#seekto 0xcf; + u8 opt_11_disp_3_4; +#seekto 0xeb; + u8 opt_11_disp_4_4; + +#seekto 0x92; + u8 opt_12_dtmf_delay_1_4; +#seekto 0xac; + u8 opt_12_dtmf_delay_2_4; +#seekto 0xd0; + u8 opt_12_dtmf_delay_3_4; +#seekto 0xec; + u8 opt_12_dtmf_delay_4_4; + +#seekto 0x93; + u8 opt_13_dtmf_speed_1_4; +#seekto 0xad; + u8 opt_13_dtmf_speed_2_4; +#seekto 0xd1; + u8 opt_13_dtmf_speed_3_4; +#seekto 0xed; + u8 opt_13_dtmf_speed_4_4; + +#seekto 0x94; + u8 opt_14_dtmfw_index_1_4; +#seekto 0xae; + u8 opt_14_dtmfw_index_2_4; +#seekto 0xd2; + u8 opt_14_dtmfw_index_3_4; +#seekto 0xee; + u8 opt_14_dtmfw_index_4_4; + +#seekto 0x96; + u8 opt_16_lockt_1_4; +#seekto 0xb0; + u8 opt_16_lockt_2_4; +#seekto 0xd4; + u8 opt_16_lockt_3_4; +#seekto 0xf0; + u8 opt_16_lockt_4_4; + +#seekto 0x97; + u8 opt_17_mic_MH48_1_4; +#seekto 0xb1; + u8 opt_17_mic_MH48_2_4; +#seekto 0xd5; + u8 opt_17_mic_MH48_3_4; +#seekto 0xf1; + u8 opt_17_mic_MH48_4_4; + +#seekto 0x98; + u8 opt_18_mute_1_4; +#seekto 0xb2; + u8 opt_18_mute_2_4; +#seekto 0xd6; + u8 opt_18_mute_3_4; +#seekto 0xf2; + u8 opt_18_mute_4_4; + +#seekto 0x9a; + u8 opt_20_pg_p_1_4[4]; +#seekto 0xb4; + u8 opt_20_pg_p_2_4[4]; +#seekto 0xd8; + u8 opt_20_pg_p_3_4[4]; +#seekto 0xf4; + u8 opt_20_pg_p_4_4[4]; + +#seekto 0x9e; + u8 opt_24_rf_sql_vhf_1_2; +#seekto 0xb8; + u8 opt_24_rf_sql_vhf_2_2; +#seekto 0xdc; + u8 opt_24_rf_sql_uhf_1_2; +#seekto 0xf8; + u8 opt_24_rf_sql_uhf_2_2; + +#seekto 0x9f; + u8 opt_25_scan_resume_vhf_1_2; +#seekto 0xb9; + u8 opt_25_scan_resume_vhf_2_2; +#seekto 0xdd; + u8 opt_25_scan_resume_uhf_1_2; +#seekto 0xf9; + u8 opt_25_scan_resume_uhf_2_2; + +#seekto 0xbc; + u8 opt_28_speaker_cnt_1_2; +#seekto 0xfc; + u8 opt_28_speaker_cnt_2_2; + +#seekto 0xbf; + u8 opt_31_tot_1_2; +#seekto 0xff; + u8 opt_31_tot_2_2; + +#seekto 0xc0; + u8 opt_32_tx_nar_vhf; +#seekto 0x100; + u8 opt_32_tx_nar_uhf; + +#seekto 0xc1; + u8 opt_33_vfo_tr; + +#seekto 0xc2; + u8 opt_34_am_1_2; +#seekto 0x102; + u8 opt_34_am_2_2; + +#seekto 260; +struct { + struct mem mem_struct; + char fill_ff[2]; +} unknown00; + +struct { + struct mem mem_struct; + char fill_00[6]; +} current_vfo_vhf_uhf[2]; + +struct { + struct mem mem_struct; + char fill_ff[6]; +} current_mem_vhf_uhf[2]; + +struct { + struct mem mem_struct; + char fill_ff[6]; +} home_vhf_uhf[2]; + +struct { + struct mem mem_struct; + char fill_010003000000[6]; +} vhome; + +struct { + struct mem mem_struct; + char fill_010001000000[6]; +} unknown01; + +struct { + char name[32]; +} Vertex_Standard_AH003M_Backup_DT; + +struct mem + memory[260]; + +struct { + char name[24]; +} Vertex_Standard_AH003M; + +struct { + u8 dtmf[16]; +} dtmf_mem[16]; +""" + +MODES_VHF = ["FM", "AM"] +MODES_UHF = ["FM"] # AM can be set but is ignored by the radio +DUPLEX = ["", "-", "+", "split"] +TONE_MODES_RADIO = ["", "Tone", "TSQL", "CTCSS Bell", "DTCS"] +TONE_MODES = ["", "Tone", "TSQL", "DTCS"] +POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5), + chirp_common.PowerLevel("Low2", watts=10), + chirp_common.PowerLevel("Low3", watts=20), + chirp_common.PowerLevel("High", watts=35), + ] +TUNING_STEPS = [5.0, 10.0, 12.5, 15.0, 20.0, 25.0, 50.0] +SKIP_VALUES = ["", "S"] +CHARSET = r"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^ _" +DTMF_CHARSET = "0123456789*# " +SPECIAL_CHANS = ['VFO-VHF', 'VFO-UHF', 'Home-VHF', 'Home-UHF', 'VFO', 'Home'] +SCAN_LIMITS = ["L1", "U1", "L2", "U2", "L3", "U3", "L4", "U4", "L5", "U5"] + +def do_download(radio): + """This is your download function""" + return _download(radio) + +@directory.register +class FT7100Radio(YaesuCloneModeRadio): + + """Yaesu FT-7100M""" + MODEL = "FT-7100M" + VARIANT = "" + IDBLOCK = "Vartex Standard AH003M M-Map V04" + BAUD_RATE = 9600 + + # Return information about this radio's features, including + # how many memories it has, what bands it supports, etc + def get_features(self): + LOG.debug("get_features") + +# import ipdb; ipdb.set_trace() + + rf = chirp_common.RadioFeatures() + rf.has_bank = False + + rf.memory_bounds = (0, 259) # This radio supports 120 + 10 + 120 + 10 = 260 memories, zero based for chirpc + rf.valid_bands = [(108000000, 180000000), # Supports 2-meters tx + (320000000, 999990000), # Supports 70-centimeters tx + ] + rf.can_odd_split = True + rf.has_ctone = True + rf.has_rx_dtcs = True + rf.has_cross = False + rf.has_dtcs_polarity = False + rf.has_bank = False + rf.has_bank_names = False + rf.has_settings = True + rf.has_sub_devices = True + rf.valid_tuning_steps = TUNING_STEPS + rf.valid_modes = MODES_VHF + rf.valid_tmodes = TONE_MODES + #rf.valid_cross_modes = CROSS_MODES + rf.valid_power_levels = POWER_LEVELS + rf.valid_duplexes = DUPLEX + rf.valid_skips = SKIP_VALUES + rf.valid_name_length = 6 + rf.valid_characters = CHARSET + rf.valid_special_chans = SPECIAL_CHANS + + return rf + + def sync_in(self): + start = time.time() + try: + self._mmap = _download(self) + except errors.RadioError: + raise + except Exception, e: + raise errors.RadioError("Failed to communicate with radio: %s" % e) + LOG.info("Downloaded in %.2f sec", (time.time() - start)) + self.process_mmap() + + def sync_out(self): + self.pipe.timeout = 1 + start = time.time() + try: + _upload(self) + except errors.RadioError: + raise + except Exception, e: + raise errors.RadioError("Failed to communicate with radio: %s" % e) + LOG.info("Uploaded in %.2f sec", (time.time() - start)) + + def process_mmap(self): + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + + def get_raw_memory(self, number): + return repr(self._memobj.memory[number]) + + def get_memory(self, number): + LOG.debug("get_memory Number: {}".format(number)) + + # Create a high-level memory object to return to the UI + mem = chirp_common.Memory() + + # Get a low-level memory object mapped to the image + if number < 0: + number = SPECIAL_CHANS[number + 10] + if isinstance(number, str): + mem.number = -10 + SPECIAL_CHANS.index(number) + mem.extd_number = number + band = 0 + if self._memobj.overlay.current_band != 0: + band = 1 + if number == 'VFO-VHF': + _mem = self._memobj.current_vfo_vhf_uhf[0].mem_struct + elif number == 'VFO-UHF': + _mem = self._memobj.current_vfo_vhf_uhf[1].mem_struct + elif number == 'Home-VHF': + _mem = self._memobj.home_vhf_uhf[0].mem_struct + elif number == 'Home-UHF': + _mem = self._memobj.home_vhf_uhf[1].mem_struct + elif number == 'VFO': + _mem = self._memobj.current_vfo_vhf_uhf[band].mem_struct + elif number == 'Home': + _mem = self._memobj.home_vhf_uhf[band].mem_struct + _mem.is_used = True + else: + mem.number = number # Set the memory number + _mem = self._memobj.memory[number] + upper_channel = self._memobj.nb_mem_used_vhf + upper_limit = self._memobj.nb_mem_used_vhf_and_limits + if number >= upper_channel and number < upper_limit: + i = number - upper_channel + mem.extd_number = SCAN_LIMITS[i] + if number >= 260-10: + i = number - (260-10) + mem.extd_number = SCAN_LIMITS[i] + + # Convert your low-level frequency to Hertz + mem.freq = int(_mem.freq_rx_Hz) + mem.name = str(_mem.name).rstrip() # Set the alpha tag + + mem.rtone = chirp_common.TONES[_mem.tone_index] + mem.ctone = chirp_common.TONES[_mem.tone_index] + + mem.dtcs = chirp_common.DTCS_CODES[_mem.dtcs_index] + mem.rx_dtcs = chirp_common.DTCS_CODES[_mem.dtcs_index] + + tmode_radio = TONE_MODES_RADIO[_mem.tone_mode_index] + # CTCSS Bell is TSQL plus a flag in the extra setting + is_ctcss_bell = tmode_radio == "CTCSS Bell" + if is_ctcss_bell: + mem.tmode = "TSQL" + else: + mem.tmode = tmode_radio + + #mem.cross_mode = "Tone->Tone" + #mem.dtcs_polarity = "NN" + + mem.duplex = "" + if _mem.is_offset_plus: + mem.duplex = "+" + elif _mem.is_offset_minus: + mem.duplex = "-" + elif _mem.is_split: + mem.duplex = "split" + + if _mem.is_split: + mem.offset = int(_mem.freq_tx_Hz) + else: + mem.offset = int(_mem.offset_10khz)*10000 # 10kHz to Hz + + if _mem.is_mode_am: + mem.mode = "AM" + else: + mem.mode = "FM" + + mem.power = POWER_LEVELS[_mem.power_index] + + mem.tuning_step = TUNING_STEPS[_mem.tuning_step_index_1_2] + + if _mem.is_skip: + mem.skip = "S" + else: + mem.skip = "" + + #mem.comment = "" + + mem.empty = not _mem.is_used + + mem.extra = RadioSettingGroup("Extra", "extra") + + rs = RadioSetting("show_name", "Show Name", + RadioSettingValueBoolean(_mem.show_name)) + mem.extra.append(rs) + rs = RadioSetting("is_masked", "Is Masked", + RadioSettingValueBoolean(_mem.is_masked)) + mem.extra.append(rs) + rs = RadioSetting("is_packet96", "Packet 9600", + RadioSettingValueBoolean(_mem.is_packet96)) + mem.extra.append(rs) + rs = RadioSetting("is_ctcss_bell", "CTCSS Bell", + RadioSettingValueBoolean(is_ctcss_bell)) + mem.extra.append(rs) + + return mem + + def set_memory(self, mem): + LOG.debug("set_memory Number: {}".format(mem.number)) + if mem.number < 0: + number = SPECIAL_CHANS[mem.number+10] + if number == 'VFO-VHF': + _mem = self._memobj.current_vfo_vhf_uhf[0].mem_struct + elif number == 'VFO-UHF': + _mem = self._memobj.current_vfo_vhf_uhf[1].mem_struct + elif number == 'Home-VHF': + _mem = self._memobj.home_vhf_uhf[0].mem_struct + elif number == 'Home-UHF': + _mem = self._memobj.home_vhf_uhf[1].mem_struct + else: + raise errors.RadioError("Unexpected Memory Number: {}".format(mem.number)) + else: + _mem = self._memobj.memory[mem.number] + + _mem.name = mem.name.ljust(6) + + _mem.tone_index = chirp_common.TONES.index(mem.rtone) + _mem.dtcs_index = chirp_common.DTCS_CODES.index(mem.dtcs) + if mem.tmode == "TSQL": + _mem.tone_index = chirp_common.TONES.index(mem.ctone) + if mem.tmode == "DTSC-R": + _mem.dtcs_index = chirp_common.DTCS_CODES.index(mem.rx_dtcs) + + _mem.is_offset_plus = 0 + _mem.is_offset_minus = 0 + _mem.is_split = 0 + _mem.freq_rx_Hz = mem.freq + _mem.freq_tx_Hz = mem.freq + if mem.duplex == "+": + _mem.is_offset_plus = 1 + _mem.freq_tx_Hz = mem.freq + mem.offset + _mem.offset_10khz = int(mem.offset/10000) + elif mem.duplex == "-": + _mem.is_offset_minus = 1 + _mem.freq_tx_Hz = mem.freq - mem.offset + _mem.offset_10khz = int(mem.offset/10000) + elif mem.duplex == "split": + _mem.is_split = 1 + _mem.freq_tx_Hz = mem.offset + # No change to _mem.offset_10khz + + _mem.is_mode_am = mem.mode == "AM" + + if mem.power: + _mem.power_index = POWER_LEVELS.index(mem.power) + + _mem.tuning_step_index_1_2 = TUNING_STEPS.index(mem.tuning_step) + + _mem.is_skip = mem.skip == "S" + + _mem.is_used = not mem.empty + + # if name not empty: show name + _mem.show_name = mem.name.strip() != "" + + + # In testmode there is no setting in mem.extra + # This is why the following line is not located in the else part of + # the if structure below + _mem.tone_mode_index = TONE_MODES_RADIO.index(mem.tmode) + + for setting in mem.extra: + if setting.get_name() == "is_ctcss_bell": + if mem.tmode == "TSQL" and setting.value: + _mem.tone_mode_index = TONE_MODES_RADIO.index("CTCSS Bell") + #else: + #_mem.tone_mode_index = TONE_MODES_RADIO.index(mem.tmode) + else: + setattr(_mem, setting.get_name(), setting.value) + + LOG.debug("encoded mem\n%s\n", (util.hexprint(_mem.get_raw()[0:25]))) + LOG.debug(repr(_mem)) + + def get_settings(self): + common = RadioSettingGroup("common", "Common Settings") + band = RadioSettingGroup("band", "Band dependent Settings") + arts = RadioSettingGroup("arts", "Auto Range Transponder System (ARTS)") + dtmf = RadioSettingGroup("dtmf", "DTMF Settings") + mic_button = RadioSettingGroup("mic_button", "Microphone Buttons") + setmode = RadioSettings(common, band, arts, dtmf, mic_button) + + _overlay = self._memobj.overlay + + # numbers and names of settings refer to the way they're + # presented in the set menu, as well as the list starting on + # page 49 of the manual + + # 1 Automatic Power Off + opts = ["Off", "30 Min", + "1 Hour", "1.5 Hours", + "2 Hours", "2.5 Hours", + "3 Hours", "3.5 Hours", + "4 Hours", "4.5 Hours", + "5 Hours", "5.5 Hours", + "6 Hours", "6.5 Hours", + "7 Hours", "7.5 Hours", + "8 Hours", "8.5 Hours", + "9 Hours", "9.5 Hours", + "10 Hours", "10.5 Hours", + "11 Hours", "11.5 Hours", + "12 Hours", + ] + common.append( + RadioSetting( + "apo", "Automatic Power Off", + RadioSettingValueList(opts, opts[_overlay.apo]))) + + # 2 Automatic Repeater Shift function + opts = ["Off", "On"] + band.append( + RadioSetting( + "ars_vhf", "Automatic Repeater Shift VHF", + RadioSettingValueList(opts, opts[_overlay.ars_vhf]))) + band.append( + RadioSetting( + "ars_uhf", "Automatic Repeater Shift UHF", + RadioSettingValueList(opts, opts[_overlay.ars_uhf]))) + + # 3 Selects the ARTS mode. + # -> Only useful to set it on radio directly + #opts = ["Off", "Range", "All"] + #arts.append( + #RadioSetting( + #"arts_vhf", "ARTS Mode VHF", + #RadioSettingValueList(opts, opts[_overlay.arts_vhf]))) + #arts.append( + #RadioSetting( + #"arts_uhf", "ARTS Mode UHF", + #RadioSettingValueList(opts, opts[_overlay.arts_uhf]))) + + # 4 Enables/disables the key/button beeper. + opts = ["Off", "On"] + common.append( + RadioSetting( + "beep", "Key/Button Beep", + RadioSettingValueList(opts, opts[_overlay.beep]))) + + # 5 Enables/disables the CW IDer during ARTS operation. + opts = ["Off", "On"] + arts.append( + RadioSetting( + "cwid", "Enables/Disables the CW ID", + RadioSettingValueList(opts, opts[_overlay.cwid]))) + + # 6 Callsign during ARTS operation. + cwidw = _overlay.cwidw.get_raw() + cwidw = cwidw.rstrip('\x00') + val = RadioSettingValueString(0, 6, cwidw) + val.set_charset(CHARSET) + rs = RadioSetting( + "cwidw", "CW Identifier Callsign", val) + def apply_cwid(setting): + value_string = setting.value.get_value() + _overlay.cwidw.set_value(value_string) + rs.set_apply_callback(apply_cwid) + arts.append(rs) + + # 7 Front panel display's illumination level. + opts = ["0: Off", "1: Max", "2", "3", "4", "5", "6", "7: Min"] + common.append( + RadioSetting( + "dim", "Display Illumination", + RadioSettingValueList(opts, opts[_overlay.dim]))) + + # 8 Setting the DCS code number. + # Note: This Menu item can be set independently for each band, + # and independently in each memory. + + # 9 Activates the DCS Code Search + # -> Only useful if set on radio itself + + # 10 Selects 'Normal' or 'Inverted' DCS coding. + opts = ["TRX Normal", "RX Reversed", "TX Reversed", "TRX Reversed"] + band.append( + RadioSetting( + "dcsnr_vhf", "DCS coding VHF", + RadioSettingValueList(opts, opts[_overlay.dcsnr_vhf]))) + band.append( + RadioSetting( + "dcsnr_uhf", "DCS coding UHF", + RadioSettingValueList(opts, opts[_overlay.dcsnr_uhf]))) + + # 11 Selects the 'sub' band display format + opts = ["Frequency", "Off / Sub Band disabled", "DC Input Voltage", "CW ID"] + common.append( + RadioSetting( + "disp", "Sub Band Display Format", + RadioSettingValueList(opts, opts[_overlay.disp]))) + + # 12 Setting the DTMF Autodialer delay time + opts = ["50 ms", "250 ms", "450 ms", "750 ms", "1 s"] + dtmf.append( + RadioSetting( + "dtmfd", "Autodialer delay time", + RadioSettingValueList(opts, opts[_overlay.dtmfd]))) + + # 13 Setting the DTMF Autodialer sending speed + opts = ["50 ms", "75 ms", "100 ms"] + dtmf.append( + RadioSetting( + "dtmfs", "Autodialer sending speed", + RadioSettingValueList(opts, opts[_overlay.dtmfs]))) + + # 14 Current DTMF Autodialer memory + rs = RadioSetting( + "dtmfw", "Current Autodialer memory", + RadioSettingValueInteger(1, 16, _overlay.dtmfw + 1)) + def apply_dtmfw(setting): + _overlay.dtmfw = setting.value.get_value() - 1 + rs.set_apply_callback(apply_dtmfw) + dtmf.append(rs) + + # DTMF Memory + for i in range(16): + dtmf_string = "" + for j in range(16): + dtmf_char = '' + dtmf_int = int(self._memobj.dtmf_mem[i].dtmf[j]) + if dtmf_int < 10: + dtmf_char = str(dtmf_int) + elif dtmf_int == 14: + dtmf_char = '*' + elif dtmf_int == 15: + dtmf_char = '#' + elif dtmf_int == 255: + break + dtmf_string += dtmf_char + radio_setting_value_string = RadioSettingValueString(0, 16, dtmf_string) + radio_setting_value_string.set_charset(DTMF_CHARSET) + rs = RadioSetting("dtmf_{0:02d}".format(i), + "DTMF Mem " + str(i+1), + radio_setting_value_string) + def apply_dtmf(setting, index): + radio_setting_value_string = setting.value.get_value().rstrip() + j = 0 + for dtmf_char in radio_setting_value_string: + dtmf_int = 255 + if dtmf_char in "0123456789": + dtmf_int = int(dtmf_char) + elif dtmf_char == '*': + dtmf_int = 14 + elif dtmf_char == '#': + dtmf_int = 15 + if dtmf_int < 255: + self._memobj.dtmf_mem[index].dtmf[j] = dtmf_int + j += 1 + if j < 16: + self._memobj.dtmf_mem[index].dtmf[j] = 255 + rs.set_apply_callback(apply_dtmf, i) + dtmf.append(rs) + + # 16 Enables/disables the PTT switch lock + opts = ["Off", "Band A", "Band B", "Both"] + common.append( + RadioSetting( + "lockt", "PTT switch lock", + RadioSettingValueList(opts, opts[_overlay.lockt]))) + + # 17 Selects the Microphone type to be used + opts = ["MH-42", "MH-48"] + common.append( + RadioSetting( + "mic", "Microphone type", + RadioSettingValueList(opts, opts[_overlay.mic]))) + + # 18 Reduces the audio level on the sub receiver when the main receiver is active + opts = ["Off", "On"] + common.append( + RadioSetting( + "mute", "Mute Sub Receiver", + RadioSettingValueList(opts, opts[_overlay.mute]))) + + # 20 - 23 Programming the microphones button assignment + buttons = ["ACC / P1", + "P / P2", + "P1 / P3", + "P2 / P4", + ] + opts_button = ["Low", "Tone", "MHz", "Rev", "Home", "Band", "VFO / Memory", + "Sql Off", "1750 Hz Tone Call", "Repeater", "Priority"] + for i, button in enumerate(buttons): + rs = RadioSetting( + "button" + str(i), button, + RadioSettingValueList(opts_button, opts_button[_overlay.button[i]])) + def apply_button(setting, index): + value_string = setting.value.get_value() + value_int = opts_button.index(value_string) + _overlay.button[index] = value_int + rs.set_apply_callback(apply_button, i) + mic_button.append(rs) + + # 24 Adjusts the RF SQL threshold level + opts = ["Off", "S-1", "S-5", "S-9", "S-FULL"] + band.append( + RadioSetting( + "rf_sql_vhf", "RF Sql VHF", + RadioSettingValueList(opts, opts[_overlay.rf_sql_vhf]))) + band.append( + RadioSetting( + "rf_sql_uhf", "RF Sql UHF", + RadioSettingValueList(opts, opts[_overlay.rf_sql_uhf]))) + + # 25 Selects the Scan-Resume mode + opts = ["Busy", "Time"] + band.append( + RadioSetting( + "scan_vhf", "Scan-Resume VHF", + RadioSettingValueList(opts, opts[_overlay.scan_vhf]))) + band.append( + RadioSetting( + "scan_uhf", "Scan-Resume UHF", + RadioSettingValueList(opts, opts[_overlay.scan_uhf]))) + + # 28 Defining the audio path to the external speaker + opts = ["Off", "Band A", "Band B", "Both"] + common.append( + RadioSetting( + "speaker_cnt", "External Speaker", + RadioSettingValueList(opts, opts[_overlay.speaker_cnt]))) + + # 31 Sets the Time-Out Timer + opts = ["Off", "Band A", "Band B", "Both"] + common.append( + RadioSetting( + "tot", "TX Time-Out [Min.] (0 = Off)", + RadioSettingValueInteger(0, 30, _overlay.tot))) + + # 32 Reducing the MIC Gain (and Deviation) + opts = ["Off", "On"] + band.append( + RadioSetting( + "txnar_vhf", "TX Narrowband VHF", + RadioSettingValueList(opts, opts[_overlay.txnar_vhf]))) + band.append( + RadioSetting( + "txnar_uhf", "TX Narrowband UHF", + RadioSettingValueList(opts, opts[_overlay.txnar_uhf]))) + + # 33 Enables/disables the VFO Tracking feature + opts = ["Off", "On"] + common.append( + RadioSetting( + "vfotr", "VFO Tracking", + RadioSettingValueList(opts, opts[_overlay.vfotr]))) + + # 34 Selects the receiving mode on the VHF band + opts = ["Inhibit (only FM)", "AM", "Auto"] + common.append( + RadioSetting( + "am", "AM Mode", + RadioSettingValueList(opts, opts[_overlay.am]))) + + # Current Band + opts = ["VHF", "UHF"] + common.append( + RadioSetting( + "current_band", "Current Band", + RadioSettingValueList(opts, opts[_overlay.current_band]))) + + # Show number of VHF and UHF channels + val = RadioSettingValueString(0, 7, str(int(self._memobj.nb_mem_used_vhf))) + val.set_mutable(False) + rs = RadioSetting("num_chan_vhf", "Number of VHF channels", val) + common.append(rs) + val = RadioSettingValueString(0, 7, str(int(self._memobj.nb_mem_used_uhf))) + val.set_mutable(False) + rs = RadioSetting("num_chan_uhf", "Number of UHF channels", val) + common.append(rs) + + return setmode + + def set_settings(self, uisettings): + _overlay = self._memobj.overlay + 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(_overlay, name) + setattr(_overlay, name, value) + + LOG.debug("Setting %s: %s", name, value) + except Exception, e: + LOG.debug(element.get_name()) + raise + + def _get_upper_vhf_limit(self): + if self._memobj == None: + # test with tox has no _memobj + upper_vhf_limit = 130 + else: + upper_vhf_limit = int(self._memobj.nb_mem_used_vhf_and_limits) + return upper_vhf_limit + + def _get_upper_uhf_limit(self): + if self._memobj == None: + # test with tox has no _memobj + upper_uhf_limit = 130 + else: + upper_uhf_limit = int(self._memobj.nb_mem_used_uhf_and_limits) + return upper_uhf_limit + + @classmethod + def match_model(cls, filedata, filename): + #return len(filedata) == 7936 --> Filelength changed due to MAGIC appended at end of file + return filedata[0x1ec0:0x1ec0+len(cls.IDBLOCK)] == cls.IDBLOCK + + @classmethod + def get_prompts(cls): + rp = chirp_common.RadioPrompts() + rp.pre_download = _(dedent("""\ + 1. Turn Radio off. + 2. Connect data cable. + 3. While holding "TONE" and "REV" buttons, turn radio on. + 4. <b>After clicking OK</b>, press "TONE" to send image.""")) + rp.pre_upload = _(dedent("""\ + 1. Turn Radio off. + 2. Connect data cable. + 3. While holding "TONE" and "REV" buttons, turn radio on. + 4. Press "REV" to receive image. + 5. Make sure display says "CLONE RX" and green led is blinking + 6. Click OK to start transfer.""")) + return rp + + def get_sub_devices(self): + return [FT7100RadioVHF(self._mmap), + FT7100RadioUHF(self._mmap)] + +class FT7100RadioVHF(FT7100Radio): + VARIANT = "VHF Band" + + def get_features(self): + LOG.debug("VHF get_features") + upper_vhf_limit = self._get_upper_vhf_limit() + rf = FT7100Radio.get_features(self) + rf.memory_bounds = (1, upper_vhf_limit) # Normally this band supports 120 + 10 memories. 1 based for chirpw + rf.valid_bands = [(108000000, 180000000)] # Supports 2-meters tx + rf.valid_modes = MODES_VHF + rf.valid_special_chans = ['VFO', 'Home'] + return rf + + def get_memory(self, number): + LOG.debug("get_memory VHF Number: {}".format(number)) + if isinstance(number, int): + if number >= 0: + mem = FT7100Radio.get_memory(self, number + 0 - 1) + else: + mem = FT7100Radio.get_memory(self, number) + mem.number = number + else: + mem = FT7100Radio.get_memory(self, number + '-VHF') + mem.extd_number = number + #TODO immutable does not work + mem.immutable = ["number", "extd_number", "skip"] + return mem + + def set_memory(self, mem): + LOG.debug("set_memory VHF Number: {}".format(mem.number)) + # mem is used further in test by tox. So save the modified members. + _number = mem.number + if isinstance(mem.number, int): + if mem.number >= 0: + mem.number += -1 + else: + mem.number += '-VHF' + super(FT7100RadioVHF, self).set_memory(mem) + # Restore modified members + mem.number = _number + return + +class FT7100RadioUHF(FT7100Radio): + VARIANT = "UHF Band" + + def get_features(self): + LOG.debug("UHF get_features") + upper_uhf_limit = self._get_upper_uhf_limit() + rf = FT7100Radio.get_features(self) + rf.memory_bounds = (1, upper_uhf_limit) # Normally this band supports 120 + 10 memories. 1 based for chirpw + rf.valid_bands = [(320000000, 999990000)] # Supports 70-centimeters tx + rf.valid_modes = MODES_UHF + rf.valid_special_chans = ['VFO', 'Home'] + return rf + + def get_memory(self, number): + LOG.debug("get_memory UHF Number: {}".format(number)) + upper_vhf_limit = self._get_upper_vhf_limit() + if isinstance(number, int): + if number >= 0: + mem = FT7100Radio.get_memory(self, number + upper_vhf_limit - 1) + else: + mem = FT7100Radio.get_memory(self, number) + mem.number = number + else: + mem = FT7100Radio.get_memory(self, number + '-UHF') + mem.extd_number = number + #TODO immutable does not work + mem.immutable = ["number", "extd_number", "skip"] + return mem + + def set_memory(self, mem): + LOG.debug("set_memory UHF Number: {}".format(mem.number)) + # mem is used further in test by tox. So save the modified members. + _number = mem.number + upper_vhf_limit = self._get_upper_vhf_limit() + if isinstance(mem.number, int): + if mem.number >= 0: + mem.number += upper_vhf_limit - 1 + else: + mem.number += '-UHF' + super(FT7100RadioUHF, self).set_memory(mem) + # Restore modified members + mem.number = _number + return + diff --git a/chirp/drivers/ft7800.py b/chirp/drivers/ft7800.py index a391a8b..1a95bb3 100644 --- a/chirp/drivers/ft7800.py +++ b/chirp/drivers/ft7800.py @@ -977,6 +977,9 @@ class FT8900Radio(FT8800Radio): MODES = ["FM", "NFM", "AM"] + def get_bank_model(self): + return + def process_mmap(self): self._memobj = bitwise.parse(MEM_FORMAT_8900, self._mmap) diff --git a/chirp/drivers/ft818.py b/chirp/drivers/ft818.py new file mode 100755 index 0000000..4263a8b --- /dev/null +++ b/chirp/drivers/ft818.py @@ -0,0 +1,342 @@ +# +# Copyright 2012 Filippi Marco <iz3gme.marco@gmail.com> +# Copyright 2018 Vinny Stipo <v@xpctech.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/>. + +"""FT818 management module""" + +from chirp.drivers import ft817 +from chirp import chirp_common, errors, directory +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueInteger, RadioSettingValueList, \ + RadioSettingValueBoolean, RadioSettingValueString, \ + RadioSettings +import os +import logging +from textwrap import dedent +from chirp.util import safe_charset_string + +LOG = logging.getLogger(__name__) + + +@directory.register +class FT818Radio(ft817.FT817Radio): + + """Yaesu FT-818""" + BAUD_RATE = 9600 + MODEL = "FT-818" + _model = "" + _memsize = 6573 + _block_lengths = [2, 40, 208, 208, 208, 208, 198, 53, 130, 118, 130] + + MEM_FORMAT = """ + struct mem_struct { + u8 tag_on_off:1, + tag_default:1, + unknown1:3, + mode:3; + u8 duplex:2, + is_duplex:1, + is_cwdig_narrow:1, + is_fm_narrow:1, + freq_range:3; + u8 skip:1, + unknown2:1, + ipo:1, + att:1, + unknown3:4; + u8 ssb_step:2, + am_step:3, + fm_step:3; + u8 unknown4:6, + tmode:2; + u8 unknown5:2, + tx_mode:3, + tx_freq_range:3; + u8 unknown6:1, + unknown_toneflag:1, + tone:6; + u8 unknown7:1, + dcs:7; + ul16 rit; + u32 freq; + u32 offset; + u8 name[8]; + }; + + #seekto 0x4; + struct { + u8 fst:1, + lock:1, + nb:1, + pbt:1, + unknownb:1, + dsp:1, + agc:2; + u8 vox:1, + vlt:1, + bk:1, + kyr:1, + unknown5:1, + cw_paddle:1, + pwr_meter_mode:2; + u8 vfob_band_select:4, + vfoa_band_select:4; + u8 unknowna; + u8 backlight:2, + color:2, + contrast:4; + u8 beep_freq:1, + beep_volume:7; + u8 arts_beep:2, + main_step:1, + cw_id:1, + scope:1, + pkt_rate:1, + resume_scan:2; + u8 op_filter:2, + lock_mode:2, + cw_pitch:4; + u8 sql_rf_gain:1, + ars_144:1, + ars_430:1, + cw_weight:5; + u8 cw_delay; + u8 unknown8:1, + sidetone:7; + u8 batt_chg:2, + cw_speed:6; + u8 disable_amfm_dial:1, + vox_gain:7; + u8 cat_rate:2, + emergency:1, + vox_delay:5; + u8 dig_mode:3, + mem_group:1, + unknown9:1, + apo_time:3; + u8 dcs_inv:2, + unknown10:1, + tot_time:5; + u8 mic_scan:1, + ssb_mic:7; + u8 mic_key:1, + am_mic:7; + u8 unknown11:1, + fm_mic:7; + u8 unknown12:1, + dig_mic:7; + u8 extended_menu:1, + pkt_mic:7; + u8 unknown14:1, + pkt9600_mic:7; + il16 dig_shift; + il16 dig_disp; + i8 r_lsb_car; + i8 r_usb_car; + i8 t_lsb_car; + i8 t_usb_car; + u8 unknown15:2, + menu_item:6; + u8 unknown16:4, + menu_sel:4; + u16 unknown17; + u8 art:1, + scn_mode:2, + dw:1, + pri:1, + unknown18:1, + tx_power:2; + u8 spl:1, + unknown:1, + uhf_antenna:1, + vhf_antenna:1, + air_antenna:1, + bc_antenna:1, + sixm_antenna:1, + hf_antenna:1; + } settings; + + #seekto 0x2A; + struct mem_struct vfoa[16]; + struct mem_struct vfob[16]; + struct mem_struct home[4]; + struct mem_struct qmb; + struct mem_struct mtqmb; + struct mem_struct mtune; + + #seekto 0x431; + u8 visible[25]; + u8 pmsvisible; + + #seekto 0x44B; + u8 filled[25]; + u8 pmsfilled; + + #seekto 0x465; + struct mem_struct memory[200]; + struct mem_struct pms[2]; + + #seekto 0x1903; + u8 callsign[7]; + + #seekto 0x19AD; + struct mem_struct sixtymeterchannels[5]; + """ + + SPECIAL_MEMORIES = { + "VFOa-1.8M": -37, + "VFOa-3.5M": -36, + "VFOa-5M": -35, + "VFOa-7M": -34, + "VFOa-10M": -33, + "VFOa-14M": -32, + "VFOa-18M": -31, + "VFOa-21M": -30, + "VFOa-24M": -29, + "VFOa-28M": -28, + "VFOa-50M": -27, + "VFOa-FM": -26, + "VFOa-AIR": -25, + "VFOa-144": -24, + "VFOa-430": -23, + "VFOa-HF": -22, + "VFOb-1.8M": -21, + "VFOb-3.5M": -20, + "VFOb-5M": -19, + "VFOb-7M": -18, + "VFOb-10M": -17, + "VFOb-14M": -16, + "VFOb-18M": -15, + "VFOb-21M": -14, + "VFOb-24M": -13, + "VFOb-28M": -12, + "VFOb-50M": -11, + "VFOb-FM": -10, + "VFOb-AIR": -9, + "VFOb-144M": -8, + "VFOb-430M": -7, + "VFOb-HF": -6, + "HOME HF": -5, + "HOME 50M": -4, + "HOME 144M": -3, + "HOME 430M": -2, + "QMB": -1, + } + FIRST_VFOB_INDEX = -6 + LAST_VFOB_INDEX = -21 + FIRST_VFOA_INDEX = -22 + LAST_VFOA_INDEX = -37 + + SPECIAL_PMS = { + "PMS-L": -39, + "PMS-U": -38, + } + LAST_PMS_INDEX = -39 + + SPECIAL_MEMORIES.update(SPECIAL_PMS) + + SPECIAL_MEMORIES_REV = dict(zip(SPECIAL_MEMORIES.values(), + SPECIAL_MEMORIES.keys())) + +@directory.register +class FT818NDUSRadio(FT818Radio): + + """Yaesu FT-818ND (US version)""" + MODEL = "FT-818ND (US)" + + _model = "" + _US_model = True + _memsize = 6703 + + _block_lengths = [2, 40, 208, 208, 208, 208, 198, 53, 130, 118, 130, 130] + + SPECIAL_60M = { + "M-601": -42, + "M-602": -41, + "M-603": -40, + "M-604": -39, + "M-605": -38, + } + LAST_SPECIAL60M_INDEX = -42 + + SPECIAL_MEMORIES = dict(FT818Radio.SPECIAL_MEMORIES) + SPECIAL_MEMORIES.update(SPECIAL_60M) + + SPECIAL_MEMORIES_REV = dict(zip(SPECIAL_MEMORIES.values(), + SPECIAL_MEMORIES.keys())) + + def _get_special_60m(self, number): + mem = chirp_common.Memory() + mem.number = self.SPECIAL_60M[number] + mem.extd_number = number + + _mem = self._memobj.sixtymeterchannels[-self.LAST_SPECIAL60M_INDEX + + mem.number] + + mem = self._get_memory(mem, _mem) + + mem.immutable = ["number", "rtone", "ctone", + "extd_number", "name", "dtcs", "tmode", "cross_mode", + "dtcs_polarity", "power", "duplex", "offset", + "comment", "empty"] + + return mem + + def _set_special_60m(self, mem): + if mem.empty: + # can't delete 60M memories! + raise Exception("Sorry, 60M memory can't be deleted") + + cur_mem = self._get_special_60m(self.SPECIAL_MEMORIES_REV[mem.number]) + + for key in cur_mem.immutable: + if cur_mem.__dict__[key] != mem.__dict__[key]: + raise errors.RadioError("Editing field `%s' " % key + + "is not supported on M-60x channels") + + if mem.mode not in ["USB", "LSB", "CW", "CWR", "NCW", "NCWR", "DIG"]: + raise errors.RadioError("Mode {mode} is not valid " + "in 60m channels".format(mode=mem.mode)) + _mem = self._memobj.sixtymeterchannels[-self.LAST_SPECIAL60M_INDEX + + mem.number] + self._set_memory(mem, _mem) + + def get_memory(self, number): + if number in self.SPECIAL_60M.keys(): + return self._get_special_60m(number) + elif number < 0 and \ + self.SPECIAL_MEMORIES_REV[number] in self.SPECIAL_60M.keys(): + # I can't stop delete operation from loosing extd_number but + # I know how to get it back + return self._get_special_60m(self.SPECIAL_MEMORIES_REV[number]) + else: + return FT818Radio.get_memory(self, number) + + def set_memory(self, memory): + if memory.number in self.SPECIAL_60M.values(): + return self._set_special_60m(memory) + else: + return FT818Radio.set_memory(self, memory) + + def get_settings(self): + top = FT818Radio.get_settings(self) + basic = top[0] + rs = RadioSetting("emergency", "Emergency", + RadioSettingValueBoolean( + self._memobj.settings.emergency)) + basic.append(rs) + return top + diff --git a/chirp/drivers/kenwood_live.py b/chirp/drivers/kenwood_live.py index a30619a..face3fe 100644 --- a/chirp/drivers/kenwood_live.py +++ b/chirp/drivers/kenwood_live.py @@ -45,14 +45,19 @@ KENWOOD_TONES.remove(199.5) THF6_MODES = ["FM", "WFM", "AM", "LSB", "USB", "CW"] +RADIO_IDS = { + "ID019": "TS-2000", + "ID009": "TS-850", +} + LOCK = threading.Lock() COMMAND_RESP_BUFSIZE = 8 -LAST_BAUD = 9600 +LAST_BAUD = 4800 LAST_DELIMITER = ("\r", " ") -# The Kenwood TS-2000 uses ";" as a CAT command message delimiter, and all -# others use "\n". Also, TS-2000 doesn't space delimite the command fields, -# but others do. +# The Kenwood TS-2000 & TS-850 uses ";" as a CAT command message delimiter, +# and all others use "\n". Also, TS-2000 doesn't space delimite the command +# fields, but others do. def command(ser, cmd, *args): @@ -91,7 +96,7 @@ def command(ser, cmd, *args): def get_id(ser): """Get the ID of the radio attached to @ser""" global LAST_BAUD - bauds = [9600, 19200, 38400, 57600] + bauds = [4800, 9600, 19200, 38400, 57600] bauds.remove(LAST_BAUD) bauds.insert(0, LAST_BAUD) @@ -113,10 +118,9 @@ def get_id(ser): LAST_BAUD = i return resp.split(" ")[1] - # TS-2000 - if "ID019" == resp: - LAST_BAUD = i - return "TS-2000" + # Kenwood radios that return ID numbers + if resp in RADIO_IDS.keys(): + return RADIO_IDS[resp] raise errors.RadioError("No response from radio") diff --git a/chirp/drivers/kguv9dplus.py b/chirp/drivers/kguv9dplus.py new file mode 100644 index 0000000..e7bfa30 --- /dev/null +++ b/chirp/drivers/kguv9dplus.py @@ -0,0 +1,1890 @@ +# Copyright 2018 Jim Lieb <lieb@sea-troll.net> +# +# Driver for Wouxon KG-UV9D Plus +# +# Borrowed from other chirp drivers, especially the KG-UV8D Plus +# by Krystian Struzik <toner_82@tlen.pl> +# +# 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-UV9D Plus radio management module""" + +import time +import os +import logging +import struct +import string +from chirp import util, chirp_common, bitwise, memmap, errors, directory +from chirp.settings import RadioSetting, RadioSettingValue, \ + RadioSettingGroup, \ + RadioSettingValueBoolean, RadioSettingValueList, \ + RadioSettingValueInteger, RadioSettingValueString, \ + RadioSettings, InvalidValueError + +LOG = logging.getLogger(__name__) + +CMD_IDENT = 0x80 +CMD_HANGUP = 0x81 +CMD_RCONF = 0x82 +CMD_WCONF = 0x83 +CMD_RCHAN = 0x84 +CMD_WCHAN = 0x85 + +cmd_name = { + CMD_IDENT: "ident", + CMD_HANGUP: "hangup", + CMD_RCONF: "read config", + CMD_WCONF: "write config", + CMD_RCHAN: "read channel memory", # Unused + CMD_WCHAN: "write channel memory" # Unused because it is a hack. + } + +# This is used to write the configuration of the radio base on info +# gleaned from the downloaded app. There are empty spaces and we honor +# them because we don't know what they are (yet) although we read the +# whole of memory. +# +# Channel memory is separate. There are 1000 (1-999) channels. +# These are read/written to the radio in 4 channel (96 byte) +# records starting at address 0xa00 and ending at +# 0x4800 (presuming the end of channel 1000 is 0x4860-1 + +config_map = ( # map address, write size, write count + (0x40, 16, 1), # Passwords + (0x740, 40, 1), # FM chan 1-20 + (0x780, 16, 1), # vfo-b-150 + (0x790, 16, 1), # vfo-b-450 + (0x800, 16, 1), # vfo-a-150 + (0x810, 16, 1), # vfo-a-450 + (0x820, 16, 1), # vfo-a-300 + (0x830, 16, 1), # vfo-a-700 + (0x840, 16, 1), # vfo-a-200 + (0x860, 16, 1), # area-a-conf + (0x870, 16, 1), # area-b-conf + (0x880, 16, 1), # radio conf 0 + (0x890, 16, 1), # radio conf 1 + (0x8a0, 16, 1), # radio conf 2 + (0x8b0, 16, 1), # radio conf 3 + (0x8c0, 16, 1), # PTT-ANI + (0x8d0, 16, 1), # SCC + (0x8e0, 16, 1), # power save + (0x8f0, 16, 1), # Display banner + (0x940, 64, 2), # Scan groups and names + (0xa00, 64, 249), # Memory Channels 1-996 + (0x4840, 48, 1), # Memory Channels 997-999 + (0x4900, 32, 249), # Memory Names 1-996 + (0x6820, 24, 1), # Memory Names 997-999 + (0x7400, 64, 5), # CALL-ID 1-20, names 1-20 + ) + + +MEM_VALID = 0xfc +MEM_INVALID = 0xff + +# Radio memory map. This matches the reads/writes above. +# structure elements whose name starts with x are currently unidentified + +_MEM_FORMAT02 = """ +#seekto 0x40; + +struct { + char reset[6]; + char x46[2]; + char mode_sw[6]; + char x4e; +} passwords; + +#seekto 0x740; + +struct { + u16 fm_freq; +} fm_chans[20]; + +// each band has its own configuration, essentially its default params + +struct vfo { + u32 freq; + u32 offset; + u16 encqt; + u16 decqt; + u8 bit7_4:3, + qt:3, + bit1_0:2; + u8 bit7:1, + scan:1, + bit5:1, + pwr:2, + mod:1, + fm_dev:2; + u8 pad2:6, + shift:2; + u8 zeros; +}; + +#seekto 0x780; + +struct { + struct vfo band_150; + struct vfo band_450; +} vfo_b; + +#seekto 0x800; + +struct { + struct vfo band_150; + struct vfo band_450; + struct vfo band_300; + struct vfo band_700; + struct vfo band_200; +} vfo_a; + +// There are two independent radios, aka areas (as described +// in the manual as the upper and lower portions of the display... + +struct area_conf { + u8 w_mode; + u8 x861; + u8 w_chan; + u8 scan_grp; + u8 bcl; + u8 sql; + u8 cset; + u8 step; + u8 scan_mode; + u8 x869; + u8 scan_range; + u8 x86b; + u8 x86c; + u8 x86d; + u8 x86e; + u8 x86f; +}; + +#seekto 0x860; + +struct area_conf a_conf; + +#seekto 0x870; + +struct area_conf b_conf; + +#seekto 0x880; + +struct { + u8 menu_avail; + u8 reset_avail; + u8 x882; + u8 x883; + u8 lang; + u8 x885; + u8 beep; + u8 auto_am; + u8 qt_sw; + u8 lock; + u8 x88a; + u8 pf1; + u8 pf2; + u8 pf3; + u8 s_mute; + u8 type_set; + u8 tot; + u8 toa; + u8 ptt_id; + u8 x893; + u8 id_dly; + u8 x895; + u8 voice_sw; + u8 s_tone; + u8 abr_lvl; + u8 ring_time; + u8 roger; + u8 x89b; + u8 abr; + u8 save_m; + u8 lock_m; + u8 auto_lk; + u8 rpt_ptt; + u8 rpt_spk; + u8 rpt_rct; + u8 prich_sw; + u16 pri_ch; + u8 x8a6; + u8 x8a7; + u8 dtmf_st; + u8 dtmf_tx; + u8 x8aa; + u8 sc_qt; + u8 apo_tmr; + u8 vox_grd; + u8 vox_dly; + u8 rpt_kpt; + struct { + u16 scan_st; + u16 scan_end; + } a; + struct { + u16 scan_st; + u16 scan_end; + } b; + u8 x8b8; + u8 x8b9; + u8 x8ba; + u8 ponmsg; + u8 blcdsw; + u8 bledsw; + u8 x8be; + u8 x8bf; +} settings; + + +#seekto 0x8c0; +struct { + u8 code[6]; + char x8c6[10]; +} my_callid; + +#seekto 0x8d0; +struct { + u8 scc[6]; + char x8d6[10]; +} stun; + +#seekto 0x8e0; +struct { + u16 wake; + u16 sleep; +} save[4]; + +#seekto 0x8f0; +struct { + char banner[16]; +} display; + +#seekto 0x940; +struct { + struct { + i16 scan_st; + i16 scan_end; + } addrs[10]; + u8 x0968[8]; + struct { + char name[8]; + } names[10]; +} scn_grps; + +// this array of structs is marshalled via the R/WCHAN commands +#seekto 0xa00; +struct { + u32 rxfreq; + u32 txfreq; + u16 encQT; + u16 decQT; + u8 bit7_5:3, // all ones + qt:3, + bit1_0:2; + u8 bit7:1, + scan:1, + bit5:1, + pwr:2, + mod:1, + fm_dev:2; + u8 state; + u8 c3; +} chan_blk[999]; + +// nobody really sees this. It is marshalled with chan_blk +// in 4 entry chunks +#seekto 0x4900; + +// Tracks with the index of chan_blk[] +struct { + char name[8]; +} chan_name[999]; + +#seekto 0x7400; +struct { + u8 cid[6]; + u8 pad[2]; +}call_ids[20]; + +// This array tracks with the index of call_ids[] +struct { + char name[6]; + char pad[2]; +} cid_names[20]; + """ + + +# Support for the Wouxun KG-UV9D Plus radio +# Serial coms are at 19200 baud +# The data is passed in variable length records +# Record structure: +# Offset Usage +# 0 start of record (\x7d) +# 1 Command (6 commands, see above) +# 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). + +def _pkt_encode(op, payload): + """Assemble a packet for the radio and encode it for transmission. + Yes indeed, the checksum we store is only 4 bits. Why? + I suspect it's a bug in the radio firmware guys didn't want to fix, + i.e. a typo 0xff -> 0xf...""" + + data = bytearray() + data.append(0x7d) # tag that marks the beginning of the packet + data.append(op) + data.append(0xff) # 0xff is from app to radio + # calc checksum from op to end + cksum = op + 0xff + if (payload): + data.append(len(payload)) + cksum += len(payload) + for byte in payload: + cksum += byte + data.append(byte) + else: + data.append(0x00) + # Yea, this is a 4 bit cksum (also known as a bug) + data.append(cksum & 0xf) + + # now obfuscate by an xor starting with first payload byte ^ 0x52 + # including the trailing cksum. + xorbits = 0x52 + for i, byte in enumerate(data[4:]): + xord = xorbits ^ byte + data[i + 4] = xord + xorbits = xord + return(data) + + +def _pkt_decode(data): + """Take a packet hot off the wire and decode it into clear text + and return the fields. We say <<cleartext>> here because all it + turns out to be is annoying obfuscation. + This is the inverse of pkt_decode""" + + # we don't care about data[0]. + # It is always 0x7d and not included in checksum + op = data[1] + direction = data[2] + bytecount = data[3] + + # First un-obfuscate the payload and cksum + payload = bytearray() + xorbits = 0x52 + for i, byte in enumerate(data[4:]): + payload.append(xorbits ^ byte) + xorbits = byte + + # Calculate the checksum starting with the 3 bytes of the header + cksum = op + direction + bytecount + for byte in payload[:-1]: + cksum += byte + # yes, a 4 bit cksum to match the encode + cksum_match = (cksum & 0xf) == payload[-1] + if (not cksum_match): + LOG.debug( + "Checksum missmatch: %x != %x; " % (cksum, payload[-1])) + return (cksum_match, op, payload[:-1]) + +# UI callbacks to process input for mapping UI fields to memory cells + + +def freq2int(val, min, max): + """Convert a frequency as a string to a u32. Units is Hz + """ + _freq = chirp_common.parse_freq(str(val)) + if _freq > max or _freq < min: + raise InvalidValueError("Frequency %s is not with in %s-%s" % + (chirp_common.format_freq(_freq), + chirp_common.format_freq(min), + chirp_common.format_freq(max))) + return _freq + + +def int2freq(freq): + """ + Convert a u32 frequency to a string for UI data entry/display + This is stored in the radio as units of 10Hz which we compensate to Hz. + A value of -1 indicates <no freqency>, i.e. unused channel. + """ + if (int(freq) > 0): + f = chirp_common.format_freq(freq) + return f + else: + return "" + + +def freq2short(val, min, max): + """Convert a frequency as a string to a u16 which is units of 10KHz + """ + _freq = chirp_common.parse_freq(str(val)) + if _freq > max or _freq < min: + raise InvalidValueError("Frequency %s is not with in %s-%s" % + (chirp_common.format_freq(_freq), + chirp_common.format_freq(min), + chirp_common.format_freq(max))) + return _freq/100000 & 0xFFFF + + +def short2freq(freq): + """ + Convert a short frequency to a string for UI data entry/display + This is stored in the radio as units of 10KHz which we + compensate to Hz. + A value of -1 indicates <no frequency>, i.e. unused channel. + """ + if (int(freq) > 0): + f = chirp_common.format_freq(freq * 100000) + return f + else: + return "" + + +def tone2short(t): + """Convert a string tone or DCS to an encoded u16 + """ + tone = str(t) + if tone == "----": + u16tone = 0x0000 + elif tone[0] == 'D': # This is a DCS code + c = tone[1: -1] + code = int(c, 8) + if tone[-1] == 'I': + code |= 0x4000 + u16tone = code | 0x8000 + else: # This is an analog CTCSS + u16tone = int(tone[0:-2]+tone[-1]) & 0xffff # strip the '.' + return u16tone + + +def short2tone(tone): + """ Map a binary CTCSS/DCS to a string name for the tone + """ + if tone == 0 or tone == 0xffff: + ret = "----" + else: + code = tone & 0x3fff + if tone & 0x8000: # This is a DCS + if tone & 0x4000: # This is an inverse code + ret = "D%0.3oI" % code + else: + ret = "D%0.3oN" % code + else: # Just plain old analog CTCSS + ret = "%4.1f" % (code / 10.0) + return ret + + +def callid2str(cid): + """Caller ID per MDC-1200 spec? Must be 3-6 digits (100 - 999999). + One digit (binary) per byte, terminated with '0xc' + """ + + bin2ascii = " 1234567890" + cidstr = "" + for i in range(0, 6): + b = cid[i].get_value() + if b == 0xc: # the cid EOL + break + if b == 0 or b > 0xa: + raise InvalidValueError( + "Caller ID code has illegal byte 0x%x" % b) + cidstr += bin2ascii[b] + return cidstr + + +def str2callid(val): + """ Convert caller id strings from callid2str. + """ + ascii2bin = "0123456789" + s = str(val).strip() + if len(s) < 3 or len(s) > 6: + raise InvalidValueError( + "Caller ID must be at least 3 and no more than 6 digits") + if s[0] == '0': + raise InvalidValueError( + "First digit of a Caller ID cannot be a zero '0'") + blk = bytearray() + for c in s: + if c not in ascii2bin: + raise InvalidValueError( + "Caller ID must be all digits 0x%x" % c) + b = (0xa, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9)[int(c)] + blk.append(b) + if len(blk) < 6: + blk.append(0xc) # EOL a short ID + if len(blk) < 6: + for i in range(0, (6 - len(blk))): + blk.append(0xf0) + return blk + + +def digits2str(digits, padding=' ', width=6): + """Convert a password or SCC digit string to a string + Passwords are expanded to and must be 6 chars. Fill them with '0' + """ + + bin2ascii = "0123456789" + digitsstr = "" + for i in range(0, 6): + b = digits[i].get_value() + if b == 0xc: # the digits EOL + break + if b >= 0xa: + raise InvalidValueError( + "Value has illegal byte 0x%x" % ord(b)) + digitsstr += bin2ascii[b] + digitsstr = digitsstr.ljust(width, padding) + return digitsstr + + +def str2digits(val): + """ Callback for edited strings from digits2str. + """ + ascii2bin = " 0123456789" + s = str(val).strip() + if len(s) < 3 or len(s) > 6: + raise InvalidValueError( + "Value must be at least 3 and no more than 6 digits") + blk = bytearray() + for c in s: + if c not in ascii2bin: + raise InvalidValueError("Value must be all digits 0x%x" % c) + blk.append(int(c)) + for i in range(len(blk), 6): + blk.append(0xc) # EOL a short ID + return blk + + +def name2str(name): + """ Convert a callid or scan group name to a string + Deal with fixed field padding (\0 or \0xff) + """ + + namestr = "" + for i in range(0, len(name)): + b = ord(name[i].get_value()) + if b != 0 and b != 0xff: + namestr += chr(b) + return namestr + + +def str2name(val, size=6, fillchar='\0', emptyfill='\0'): + """ Convert a string to a name. A name is a 6 element bytearray + with ascii chars. + """ + val = str(val).rstrip(' \t\r\n\0\0xff') + if len(val) == 0: + name = "".ljust(size, emptyfill) + else: + name = val.ljust(size, fillchar) + return name + + +def pw2str(pw): + """Convert a password string (6 digits) to a string + Passwords must be 6 digits. If it is shorter, pad right with '0' + """ + pwstr = "" + ascii2bin = "0123456789" + for i in range(0, len(pw)): + b = pw[i].get_value() + if b not in ascii2bin: + raise InvalidValueError("Value must be digits 0-9") + pwstr += b + pwstr = pwstr.ljust(6, '0') + return pwstr + + +def str2pw(val): + """Store a password from UI to memory obj + If we clear the password (make it go away), change the + empty string to '000000' since the radio must have *something* + Also, fill a < 6 digit pw with 0's + """ + ascii2bin = "0123456789" + val = str(val).rstrip(' \t\r\n\0\0xff') + if len(val) == 0: # a null password + val = "000000" + for i in range(0, len(val)): + b = val[i] + if b not in ascii2bin: + raise InvalidValueError("Value must be digits 0-9") + if len(val) == 0: + pw = "".ljust(6, '\0') + else: + pw = val.ljust(6, '0') + return pw + + +# Helpers to replace python2 things like confused str/byte + +def _hex_print(data, addrfmt=None): + """Return a hexdump-like encoding of @data + We expect data to be a bytearray, not a string. + Expanded from borrowed code to use the first 2 bytes as the address + per comm packet format. + """ + if addrfmt is None: + addrfmt = '%(addr)03i' + addr = 0 + else: # assume first 2 bytes are address + a = struct.unpack(">H", data[0:2]) + addr = a[0] + data = data[2:] + + block_size = 16 + + lines = (len(data) / block_size) + if (len(data) % block_size > 0): + lines += 1 + + out = "" + left = len(data) + for block in range(0, lines): + addr += block * block_size + try: + out += addrfmt % locals() + except (OverflowError, ValueError, TypeError, KeyError): + out += "%03i" % addr + out += ': ' + + if left < block_size: + limit = left + else: + limit = block_size + + for j in range(0, block_size): + if (j < limit): + out += "%02x " % data[(block * block_size) + j] + else: + out += " " + + out += " " + + for j in range(0, block_size): + + if (j < limit): + _byte = data[(block * block_size) + j] + if _byte >= 0x20 and _byte < 0x7F: + out += "%s" % chr(_byte) + else: + out += "." + else: + out += " " + out += "\n" + if (left > block_size): + left -= block_size + + return out + + +# Useful UI lists +STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0, 50.0, 100.0] +S_TONES = [str(x) for x in [1000, 1450, 1750, 2100]] +STEP_LIST = [str(x)+"kHz" for x in STEPS] +ROGER_LIST = ["Off", "Begin", "End", "Both"] +TIMEOUT_LIST = [str(x) + "s" for x in range(15, 601, 15)] +TOA_LIST = ["Off"] + ["%ds" % t for t in range(1, 10)] +BANDWIDTH_LIST = ["Wide", "Narrow"] +LANGUAGE_LIST = ["English", "Chinese"] +PF1KEY_LIST = ["OFF", "call id", "r-alarm", "SOS", "SF-TX"] +PF2KEY_LIST = ["OFF", "Scan", "Second", "lamp", "SDF-DIR", "K-lamp"] +PF3KEY_LIST = ["OFF", "Call ID", "R-ALARM", "SOS", "SF-TX"] +WORKMODE_LIST = ["VFO freq", "Channel No.", "Ch. No.+Freq.", + "Ch. No.+Name"] +BACKLIGHT_LIST = ["Off"] + ["%sS" % t for t in range(1, 31)] + \ + ["Always On"] +SAVE_MODES = ["Off", "1", "2", "3", "4"] +LOCK_MODES = ["key-lk", "key+pg", "key+ptt", "all"] +APO_TIMES = ["Off"] + ["%dm" % t for t in range(15, 151, 15)] +OFFSET_LIST = ["none", "+", "-"] +PONMSG_LIST = ["Battery Volts", "Bitmap"] +SPMUTE_LIST = ["QT", "QT*T", "QT&T"] +DTMFST_LIST = ["Off", "DT-ST", "ANI-ST", "DT-ANI"] +DTMF_TIMES = ["%d" % x for x in range(80, 501, 20)] +PTTID_LIST = ["Off", "Begin", "End", "Both"] +ID_DLY_LIST = ["%dms" % t for t in range(100, 3001, 100)] +VOX_GRDS = ["Off"] + ["%dlevel" % l for l in range(1, 11)] +VOX_DLYS = ["Off"] + ["%ds" % t for t in range(1, 5)] +RPT_KPTS = ["Off"] + ["%dms" % t for t in range(100, 5001, 100)] +LIST_1_5 = ["%s" % x for x in range(1, 6)] +LIST_0_9 = ["%s" % x for x in range(0, 10)] +LIST_1_20 = ["%s" % x for x in range(1, 21)] +LIST_OFF_10 = ["Off"] + ["%s" % x for x in range(1, 11)] +SCANGRP_LIST = ["All"] + ["%s" % x for x in range(1, 11)] +SCANMODE_LIST = ["TO", "CO", "SE"] +SCANRANGE_LIST = ["Current band", "freq range", "ALL"] +SCQT_LIST = ["Decoder", "Encoder", "Both"] +S_MUTE_LIST = ["off", "rx mute", "tx mute", "r/t mute"] +POWER_LIST = ["Low", "Med", "High"] +RPTMODE_LIST = ["Radio", "One direction Repeater", + "Two direction repeater"] +TONE_LIST = ["----"] + ["%s" % str(t) for t in chirp_common.TONES] + \ + ["D%0.3dN" % dts for dts in chirp_common.DTCS_CODES] + \ + ["D%0.3dI" % dts for dts in chirp_common.DTCS_CODES] + + +@directory.register +class KGUV9DPlusRadio(chirp_common.CloneModeRadio, + chirp_common.ExperimentalRadio): + + """Wouxun KG-UV9D Plus""" + VENDOR = "Wouxun" + MODEL = "KG-UV9D Plus" + _model = "KG-UV9D" + _rev = "00" # default rev for the radio I know about... + _file_ident = "kg-uv9d" + BAUD_RATE = 19200 + POWER_LEVELS = [chirp_common.PowerLevel("L", watts=1), + chirp_common.PowerLevel("M", watts=2), + chirp_common.PowerLevel("H", watts=5)] + _mmap = "" + + def _read_record(self): + """ Read and validate the header of a radio reply. + A record is a formatted byte stream as follows: + 0x7D All records start with this + opcode This is in the set of legal commands. + The radio reply matches the request + dir This is the direction, 0xFF to the radio, + 0x00 from the radio. + cnt Count of bytes in payload + (not including the trailing checksum byte) + <cnt bytes> + <checksum byte> + """ + + # first get the header and validate it + data = bytearray(self.pipe.read(4)) + if (len(data) < 4): + raise errors.RadioError('Radio did not respond') + if (data[0] != 0x7D): + raise errors.RadioError( + 'Radio reply garbled (%02x)' % data[0]) + if (data[1] not in cmd_name): + raise errors.RadioError( + "Unrecognized opcode (%02x)" % data[1]) + if (data[2] != 0x00): + raise errors.RadioError( + "Direction incorrect. Got (%02x)" % data[2]) + payload_len = data[3] + # don't forget to read the checksum byte + data.extend(self.pipe.read(payload_len + 1)) + if (len(data) != (payload_len + 5)): # we got a short read + raise errors.RadioError( + "Radio reply wrong size. Wanted %d, got %d" % + ((payload_len + 1), (len(data) - 4))) + return _pkt_decode(data) + + def _write_record(self, cmd, payload=None): + """ Write a request packet to the radio. + """ + + packet = _pkt_encode(cmd, payload) + self.pipe.write(packet) + + @classmethod + def match_model(cls, filedata, filename): + """Look for bits in the file image and see if it looks + like ours... + TODO: there is a bunch of rubbish between 0x50 and 0x160 + that is still a known unknown + """ + return cls._file_ident in filedata[0x51:0x59].lower() + + def _identify(self): + """ Identify the radio + The ident block identifies the radio and its capabilities. + This block is always 78 bytes. The rev == '01' is the base + radio and '02' seems to be the '-Plus' version. + I don't really trust the content after the model and revision. + One would assume this is pretty much constant data but I have + seen differences between my radio and the dump named + KG-UV9D-Plus-OutOfBox-Read.txt from bug #3509. The first + five bands match the OEM windows + app except the 350-400 band. The OOB trace has the 700MHz + band different. This is speculation at this point. + + TODO: This could be smarter and reject a radio not actually + a UV9D... + """ + + for _i in range(0, 10): # retry 10 times if we get junk + self._write_record(CMD_IDENT) + chksum_match, op, _resp = self._read_record() + if len(_resp) == 0: + raise Exception("Radio not responding") + if len(_resp) != 74: + LOG.error( + "Expected and IDENT reply of 78 bytes. Got (%d)" % + len(_resp)) + continue + if not chksum_match: + LOG.error("Checksum error: retrying ident...") + time.sleep(0.100) + continue + if op != CMD_IDENT: + LOG.error("Expected IDENT reply. Got (%02x)" % op) + continue + LOG.debug("Got:\n%s" % _hex_print(_resp)) + (mod, rev) = struct.unpack(">7s2s", _resp[0:9]) + LOG.debug("Model %s, rev %s" % (mod, rev)) + if mod == self._model: + self._rev = rev + return + else: + raise Exception("Unable to identify radio") + raise Exception("All retries to identify failed") + + def process_mmap(self): + if self._rev == "02" or self._rev == "00": + self._memobj = bitwise.parse(_MEM_FORMAT02, self._mmap) + else: # this is where you elif the other variants and non-Plus radios + raise errors.RadioError( + "Unrecognized model variation (%s). No memory map for it" % + self._rev) + + def sync_in(self): + """ Public sync_in + Download contents of the radio. Throw errors back + to the core if the radio does not respond. + """ + try: + self._identify() + self._mmap = self._do_download() + self._write_record(CMD_HANGUP) + except errors.RadioError: + raise + except Exception, e: + LOG.exception('Unknown error during download process') + raise errors.RadioError( + "Failed to communicate with radio: %s" % e) + self.process_mmap() + + def sync_out(self): + """ Public sync_out + Upload the modified memory image into the radio. + """ + + try: + self._identify() + self._do_upload() + self._write_record(CMD_HANGUP) + except errors.RadioError: + raise + except Exception, e: + raise errors.RadioError( + "Failed to communicate with radio: %s" % e) + return + + def _do_download(self): + """ Read the whole of radio memory in 64 byte chunks. + We load the config space followed by loading memory channels. + The radio seems to be a "clone" type and the memory channels + are actually within the config space. There are separate + commands (CMD_RCHAN, CMD_WCHAN) for reading channel memory but + these seem to be a hack that can only do 4 channels at a time. + Since the radio only supports 999, (can only support 3 chars + in the display UI?) although the vendors app reads 1000 + channels, it hacks back to config writes (CMD_WCONF) for the + last 3 channels and names. We keep it simple and just read + the whole thing even though the vendor app doesn't. Channels + are separate in their app simply because the radio protocol + has read/write commands to access it. What they do is simply + marshal the frequency+mode bits in 4 channel chunks followed + by a separate chunk of for names. In config space, they are two + separate arrays 1..999. Given that this space is not a + multiple of 4, there is hackery on upload to do the writes to + config space. See upload for this. + """ + + mem = bytearray(0x8000) # The radio's memory map is 32k + for addr in range(0, 0x8000, 64): + req = bytearray(struct.pack(">HB", addr, 64)) + self._write_record(CMD_RCONF, req) + chksum_match, op, resp = self._read_record() + if not chksum_match: + LOG.debug(_hex_print(resp)) + raise Exception( + "Checksum error while reading configuration (0x%x)" % + addr) + pa = struct.unpack(">H", resp[0:2]) + pkt_addr = pa[0] + payload = resp[2:] + if op != CMD_RCONF or addr != pkt_addr: + raise Exception( + "Expected CMD_RCONF (%x) reply. Got (%02x: %x)" % + (addr, op, pkt_addr)) + LOG.debug("Config read (0x%x):\n%s" % + (addr, _hex_print(resp, '0x%(addr)04x'))) + for i in range(0, len(payload) - 1): + mem[addr + i] = payload[i] + if self.status_fn: + status = chirp_common.Status() + status.cur = addr + status.max = 0x8000 + status.msg = "Cloning from radio" + self.status_fn(status) + strmem = "".join([chr(x) for x in mem]) + return memmap.MemoryMap(strmem) + + def _do_upload(self): + """Walk through the config map and write updated records to + the radio. The config map contains only the regions we know + about. We don't use the channel memory commands to avoid the + hackery of using config write commands to fill in the last + 3 channel memory and names slots. As we discover other useful + goodies in the map, we can add more slots... + """ + for ar, size, count in config_map: + for addr in range(ar, ar + (size*count), size): + req = bytearray(struct.pack(">H", addr)) + req.extend(self.get_mmap()[addr:addr + size]) + self._write_record(CMD_WCONF, req) + LOG.debug("Config write (0x%x):\n%s" % + (addr, _hex_print(req))) + chksum_match, op, ack = self._read_record() + LOG.debug("Config write ack [%x]\n%s" % + (addr, _hex_print(ack))) + a = struct.unpack(">H", ack) # big endian short... + ack = a[0] + if not chksum_match or op != CMD_WCONF or addr != ack: + msg = "" + if not chksum_match: + msg += "Checksum err, " + if op != CMD_WCONF: + msg += "cmd mismatch %x != %x, " % \ + (op, CMD_WCONF) + if addr != ack: + msg += "ack error %x != %x, " % (addr, ack) + raise Exception("Radio did not ack block: %s error" % msg) + if self.status_fn: + status = chirp_common.Status() + status.cur = addr + status.max = 0x8000 + status.msg = "Update radio" + self.status_fn(status) + + def get_features(self): + """ Public get_features + Return the features of this radio once we have identified + it and gotten its bits + """ + 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", "AM"] + rf.valid_power_levels = self.POWER_LEVELS + rf.valid_name_length = 8 + rf.valid_duplexes = ["", "-", "+", "split", "off"] + rf.valid_bands = [(108000000, 136000000), # Aircraft AM + (136000000, 180000000), # supports 2m + (230000000, 250000000), + (350000000, 400000000), + (400000000, 520000000), # supports 70cm + (700000000, 985000000)] + 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.chan_blk[number]) + + def _get_tone(self, _mem, mem): + """Decode both the encode and decode CTSS/DCS codes from + the memory channel and stuff them into the UI + memory channel row. + """ + txtone = short2tone(_mem.encQT) + rxtone = short2tone(_mem.decQT) + pt = "N" + pr = "N" + + if txtone == "----": + txmode = "" + elif txtone[0] == "D": + mem.dtcs = int(txtone[1:4]) + if txtone[4] == "I": + pt = "R" + txmode = "DTCS" + else: + mem.rtone = float(txtone) + txmode = "Tone" + + if rxtone == "----": + rxmode = "" + elif rxtone[0] == "D": + mem.rx_dtcs = int(rxtone[1:4]) + if rxtone[4] == "I": + pr = "R" + rxmode = "DTCS" + else: + mem.ctone = float(rxtone) + rxmode = "Tone" + + if txmode == "Tone" and len(rxmode) == 0: + mem.tmode = "Tone" + elif (txmode == rxmode and txmode == "Tone" and + mem.rtone == mem.ctone): + mem.tmode = "TSQL" + elif (txmode == rxmode and txmode == "DTCS" and + mem.dtcs == mem.rx_dtcs): + mem.tmode = "DTCS" + elif (len(rxmode) + len(txmode)) > 0: + mem.tmode = "Cross" + mem.cross_mode = "%s->%s" % (txmode, rxmode) + + mem.dtcs_polarity = pt + pr + + LOG.debug("_get_tone: Got TX %s (%i) RX %s (%i)" % + (txmode, _mem.encQT, rxmode, _mem.decQT)) + + def get_memory(self, number): + """ Public get_memory + Return the channel memory referenced by number to the UI. + """ + _mem = self._memobj.chan_blk[number - 1] + _nam = self._memobj.chan_name[number - 1] + + mem = chirp_common.Memory() + mem.number = number + _valid = _mem.state + 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 + + mem.name = name2str(_nam.name) + + self._get_tone(_mem, mem) + + mem.skip = "" if bool(_mem.scan) else "S" + + mem.power = self.POWER_LEVELS[_mem.pwr] + if _mem.mod == 1: + mem.mode = "AM" + elif _mem.fm_dev == 0: + mem.mode = "FM" + else: + mem.mode = "NFM" + # qt has no home in the UI + return mem + + def _set_tone(self, mem, _mem): + """Update the memory channel block CTCC/DCS tones + from the UI fields + """ + def _set_dcs(code, pol): + val = int("%i" % code, 8) | 0x8000 + if pol == "R": + val |= 0x4000 + return val + + rx_mode = tx_mode = None + rxtone = txtone = 0x0000 + + if mem.tmode == "Tone": + tx_mode = "Tone" + txtone = int(mem.rtone * 10) + elif mem.tmode == "TSQL": + rx_mode = tx_mode = "Tone" + rxtone = txtone = int(mem.ctone * 10) + elif mem.tmode == "DTCS": + tx_mode = rx_mode = "DTCS" + txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0]) + rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1]) + elif mem.tmode == "Cross": + tx_mode, rx_mode = mem.cross_mode.split("->") + if tx_mode == "DTCS": + txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0]) + elif tx_mode == "Tone": + txtone = int(mem.rtone * 10) + if rx_mode == "DTCS": + rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1]) + elif rx_mode == "Tone": + rxtone = int(mem.ctone * 10) + + _mem.decQT = rxtone + _mem.encQT = txtone + + LOG.debug("Set TX %s (%i) RX %s (%i)" % + (tx_mode, _mem.encQT, rx_mode, _mem.decQT)) + + def set_memory(self, mem): + """ Public set_memory + Inverse of get_memory. Update the radio memory image + from the mem object + """ + number = mem.number + + _mem = self._memobj.chan_blk[number - 1] + _nam = self._memobj.chan_name[number - 1] + + if mem.empty: + _mem.set_raw("\xFF" * (_mem.size() / 8)) + _nam.name = str2name("", 8, '\0', '\0') + _mem.state = MEM_INVALID + 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 == "+": + _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 = int(mem.skip != "S") + if mem.mode == "FM": + _mem.mod = 0 # make sure forced AM is off + _mem.fm_dev = 0 + elif mem.mode == "NFM": + _mem.mod = 0 + _mem.fm_dev = 1 + elif mem.mode == "AM": + _mem.mod = 1 # AM on + _mem.fm_dev = 1 # set NFM bandwidth + else: + _mem.mod = 0 + _mem.fm_dev = 0 # Catchall default is FM + # set the tone + self._set_tone(mem, _mem) + # set the power + if mem.power: + _mem.pwr = self.POWER_LEVELS.index(mem.power) + else: + _mem.pwr = True + + # Set fields we can't access via the UI table to safe defaults + _mem.qt = 0 # mute mode to QT + + _nam.name = str2name(mem.name, 8, '\0', '\0') + _mem.state = MEM_VALID + +# Build the UI configuration tabs +# the channel memory tab is built by the core. +# We have no control over it + + def _core_tab(self): + """ Build Core Configuration tab + Radio settings common to all modes and areas go here. + """ + s = self._memobj.settings + + cf = RadioSettingGroup("cfg_grp", "Configuration") + + cf.append(RadioSetting("auto_am", + "Auto detect AM(53)", + RadioSettingValueBoolean(s.auto_am))) + cf.append(RadioSetting("qt_sw", + "Scan tone detect(59)", + RadioSettingValueBoolean(s.qt_sw))) + cf.append( + RadioSetting("s_mute", + "SubFreq Mute(60)", + RadioSettingValueList(S_MUTE_LIST, + S_MUTE_LIST[s.s_mute]))) + cf.append( + RadioSetting("tot", + "Transmit timeout Timer(10)", + RadioSettingValueList(TIMEOUT_LIST, + TIMEOUT_LIST[s.tot]))) + cf.append( + RadioSetting("toa", + "Transmit Timeout Alarm(11)", + RadioSettingValueList(TOA_LIST, + TOA_LIST[s.toa]))) + cf.append( + RadioSetting("ptt_id", + "PTT Caller ID mode(23)", + RadioSettingValueList(PTTID_LIST, + PTTID_LIST[s.ptt_id]))) + cf.append( + RadioSetting("id_dly", + "Caller ID Delay time(25)", + RadioSettingValueList(ID_DLY_LIST, + ID_DLY_LIST[s.id_dly]))) + cf.append(RadioSetting("voice_sw", + "Voice Guide(12)", + RadioSettingValueBoolean(s.voice_sw))) + cf.append(RadioSetting("beep", + "Keypad Beep(13)", + RadioSettingValueBoolean(s.beep))) + cf.append( + RadioSetting("s_tone", + "Side Tone(36)", + RadioSettingValueList(S_TONES, + S_TONES[s.s_tone]))) + cf.append( + RadioSetting("ring_time", + "Ring Time(26)", + RadioSettingValueList( + LIST_OFF_10, + LIST_OFF_10[s.ring_time]))) + cf.append( + RadioSetting("roger", + "Roger Beep(9)", + RadioSettingValueList(ROGER_LIST, + ROGER_LIST[s.roger]))) + cf.append(RadioSetting("blcdsw", + "Backlight(41)", + RadioSettingValueBoolean(s.blcdsw))) + cf.append( + RadioSetting("abr", + "Auto Backlight Time(1)", + RadioSettingValueList(BACKLIGHT_LIST, + BACKLIGHT_LIST[s.abr]))) + cf.append( + RadioSetting("abr_lvl", + "Backlight Brightness(27)", + RadioSettingValueList(LIST_1_5, + LIST_1_5[s.abr_lvl]))) + cf.append(RadioSetting("lock", + "Keypad Lock", + RadioSettingValueBoolean(s.lock))) + cf.append( + RadioSetting("lock_m", + "Keypad Lock Mode(35)", + RadioSettingValueList(LOCK_MODES, + LOCK_MODES[s.lock_m]))) + cf.append(RadioSetting("auto_lk", + "Keypad Autolock(34)", + RadioSettingValueBoolean(s.auto_lk))) + cf.append(RadioSetting("prich_sw", + "Priority Channel Scan(33)", + RadioSettingValueBoolean(s.prich_sw))) + cf.append(RadioSetting("pri_ch", + "Priority Channel(32)", + RadioSettingValueInteger(1, 999, + s.pri_ch))) + cf.append( + RadioSetting("dtmf_st", + "DTMF Sidetone(22)", + RadioSettingValueList(DTMFST_LIST, + DTMFST_LIST[s.dtmf_st]))) + cf.append(RadioSetting("sc_qt", + "Scan QT Save Mode(38)", + RadioSettingValueList( + SCQT_LIST, + SCQT_LIST[s.sc_qt]))) + cf.append( + RadioSetting("apo_tmr", + "Automatic Power-off(39)", + RadioSettingValueList(APO_TIMES, + APO_TIMES[s.apo_tmr]))) + cf.append( # VOX "guard" is really VOX trigger audio level + RadioSetting("vox_grd", + "VOX level(7)", + RadioSettingValueList(VOX_GRDS, + VOX_GRDS[s.vox_grd]))) + cf.append( + RadioSetting("vox_dly", + "VOX Delay(37)", + RadioSettingValueList(VOX_DLYS, + VOX_DLYS[s.vox_dly]))) + cf.append( + RadioSetting("lang", + "Menu Language(14)", + RadioSettingValueList(LANGUAGE_LIST, + LANGUAGE_LIST[s.lang]))) + cf.append(RadioSetting("ponmsg", + "Poweron message(40)", + RadioSettingValueList( + PONMSG_LIST, PONMSG_LIST[s.ponmsg]))) + cf.append(RadioSetting("bledsw", + "Receive LED(42)", + RadioSettingValueBoolean(s.bledsw))) + return cf + + def _repeater_tab(self): + """Repeater mode functions + """ + s = self._memobj.settings + cf = RadioSettingGroup("repeater", "Repeater Functions") + + cf.append( + RadioSetting("type_set", + "Radio Mode(43)", + RadioSettingValueList( + RPTMODE_LIST, + RPTMODE_LIST[s.type_set]))) + cf.append(RadioSetting("rpt_ptt", + "Repeater PTT(45)", + RadioSettingValueBoolean(s.rpt_ptt))) + cf.append(RadioSetting("rpt_spk", + "Repeater Mode Speaker(44)", + RadioSettingValueBoolean(s.rpt_spk))) + cf.append( + RadioSetting("rpt_kpt", + "Repeater Hold Time(46)", + RadioSettingValueList(RPT_KPTS, + RPT_KPTS[s.rpt_kpt]))) + cf.append(RadioSetting("rpt_rct", + "Repeater Receipt Tone(47)", + RadioSettingValueBoolean(s.rpt_rct))) + return cf + + def _admin_tab(self): + """Admin functions not present in radio menu... + These are admin functions not radio operation configuration + """ + + def apply_cid(setting, obj): + c = str2callid(setting.value) + obj.code = c + + def apply_scc(setting, obj): + c = str2digits(setting.value) + obj.scc = c + + def apply_mode_sw(setting, obj): + pw = str2pw(setting.value) + obj.mode_sw = pw + setting.value = pw2str(obj.mode_sw) + + def apply_reset(setting, obj): + pw = str2pw(setting.value) + obj.reset = pw + setting.value = pw2str(obj.reset) + + def apply_wake(setting, obj): + obj.wake = int(setting.value)/10 + + def apply_sleep(setting, obj): + obj.sleep = int(setting.value)/10 + + pw = self._memobj.passwords # admin passwords + s = self._memobj.settings + + cf = RadioSettingGroup("admin", "Admin Functions") + + cf.append(RadioSetting("menu_avail", + "Menu available in channel mode", + RadioSettingValueBoolean(s.menu_avail))) + mode_sw = RadioSettingValueString(0, 6, + pw2str(pw.mode_sw), False) + rs = RadioSetting("passwords.mode_sw", + "Mode Switch Password", mode_sw) + rs.set_apply_callback(apply_mode_sw, pw) + cf.append(rs) + + cf.append(RadioSetting("reset_avail", + "Radio Reset Available", + RadioSettingValueBoolean(s.reset_avail))) + reset = RadioSettingValueString(0, 6, pw2str(pw.reset), False) + rs = RadioSetting("passwords.reset", + "Radio Reset Password", reset) + rs.set_apply_callback(apply_reset, pw) + cf.append(rs) + + cf.append( + RadioSetting("dtmf_tx", + "DTMF Tx Duration", + RadioSettingValueList(DTMF_TIMES, + DTMF_TIMES[s.dtmf_tx]))) + cid = self._memobj.my_callid + my_callid = RadioSettingValueString(3, 6, + callid2str(cid.code), False) + rs = RadioSetting("my_callid.code", + "PTT Caller ID code(24)", my_callid) + rs.set_apply_callback(apply_cid, cid) + cf.append(rs) + + stun = self._memobj.stun + st = RadioSettingValueString(0, 6, digits2str(stun.scc), False) + rs = RadioSetting("stun.scc", "Security code", st) + rs.set_apply_callback(apply_scc, stun) + cf.append(rs) + + cf.append( + RadioSetting("settings.save_m", + "Save Mode (2)", + RadioSettingValueList(SAVE_MODES, + SAVE_MODES[s.save_m]))) + for i in range(0, 4): + sm = self._memobj.save[i] + wake = RadioSettingValueInteger(0, 18000, sm.wake * 10, 1) + wf = RadioSetting("save[%i].wake" % i, + "Save Mode %d Wake Time" % (i+1), wake) + wf.set_apply_callback(apply_wake, sm) + cf.append(wf) + + slp = RadioSettingValueInteger(0, 18000, sm.sleep * 10, 1) + wf = RadioSetting("save[%i].sleep" % i, + "Save Mode %d Sleep Time" % (i+1), slp) + wf.set_apply_callback(apply_sleep, sm) + cf.append(wf) + + _msg = str(self._memobj.display.banner).split("\0")[0] + val = RadioSettingValueString(0, 16, _msg) + val.set_mutable(True) + cf.append(RadioSetting("display.banner", + "Display Message", val)) + return cf + + def _fm_tab(self): + """FM Broadcast channels + """ + def apply_fm(setting, obj): + f = freq2short(setting.value, 76000000, 108000000) + obj.fm_freq = f + + fm = RadioSettingGroup("fm_chans", "FM Broadcast") + for ch in range(0, 20): + chan = self._memobj.fm_chans[ch] + freq = RadioSettingValueString(0, 20, + short2freq(chan.fm_freq)) + rs = RadioSetting("fm_%d" % (ch + 1), + "FM Channel %d" % (ch + 1), freq) + rs.set_apply_callback(apply_fm, chan) + fm.append(rs) + return fm + + def _scan_grp(self): + """Scan groups + """ + def apply_name(setting, obj): + name = str2name(setting.value, 8, '\0', '\0') + obj.name = name + + def apply_start(setting, obj): + """Do a callback to deal with RadioSettingInteger limitation + on memory address resolution + """ + obj.scan_st = int(setting.value) + + def apply_end(setting, obj): + """Do a callback to deal with RadioSettingInteger limitation + on memory address resolution + """ + obj.scan_end = int(setting.value) + + sgrp = self._memobj.scn_grps + scan = RadioSettingGroup("scn_grps", "Channel Scanner Groups") + for i in range(0, 10): + s_grp = sgrp.addrs[i] + s_name = sgrp.names[i] + rs_name = RadioSettingValueString(0, 8, + name2str(s_name.name)) + rs = RadioSetting("scn_grps.names[%i].name" % i, + "Group %i Name" % (i + 1), rs_name) + rs.set_apply_callback(apply_name, s_name) + scan.append(rs) + rs_st = RadioSettingValueInteger(1, 999, s_grp.scan_st) + rs = RadioSetting("scn_grps.addrs[%i].scan_st" % i, + "Starting Channel", rs_st) + rs.set_apply_callback(apply_start, s_grp) + scan.append(rs) + rs_end = RadioSettingValueInteger(1, 999, s_grp.scan_end) + rs = RadioSetting("scn_grps.addrs[%i].scan_end" % i, + "Last Channel", rs_end) + rs.set_apply_callback(apply_end, s_grp) + scan.append(rs) + return scan + + def _callid_grp(self): + """Caller IDs to be recognized by radio + This really should be a table in the UI + """ + def apply_callid(setting, obj): + c = str2callid(setting.value) + obj.cid = c + + def apply_name(setting, obj): + name = str2name(setting.value, 6, '\0', '\xff') + obj.name = name + + cid = RadioSettingGroup("callids", "Caller IDs") + for i in range(0, 20): + callid = self._memobj.call_ids[i] + name = self._memobj.cid_names[i] + c_name = RadioSettingValueString(0, 6, name2str(name.name)) + rs = RadioSetting("cid_names[%i].name" % i, + "Caller ID %i Name" % (i + 1), c_name) + rs.set_apply_callback(apply_name, name) + cid.append(rs) + c_id = RadioSettingValueString(0, 6, + callid2str(callid.cid), + False) + rs = RadioSetting("call_ids[%i].cid" % i, + "Caller ID Code", c_id) + rs.set_apply_callback(apply_callid, callid) + cid.append(rs) + return cid + + def _band_tab(self, area, band): + """ Build a band tab inside a VFO/Area + """ + def apply_freq(setting, lo, hi, obj): + f = freq2int(setting.value, lo, hi) + obj.freq = f/10 + + def apply_offset(setting, obj): + f = freq2int(setting.value, 0, 5000000) + obj.offset = f/10 + + def apply_enc(setting, obj): + t = tone2short(setting.value) + obj.encqt = t + + def apply_dec(setting, obj): + t = tone2short(setting.value) + obj.decqt = t + + if area == "a": + if band == 150: + c = self._memobj.vfo_a.band_150 + lo = 108000000 + hi = 180000000 + elif band == 200: + c = self._memobj.vfo_a.band_200 + lo = 230000000 + hi = 250000000 + elif band == 300: + c = self._memobj.vfo_a.band_300 + lo = 350000000 + hi = 400000000 + elif band == 450: + c = self._memobj.vfo_a.band_450 + lo = 400000000 + hi = 512000000 + else: # 700 + c = self._memobj.vfo_a.band_700 + lo = 700000000 + hi = 985000000 + else: # area 'b' + if band == 150: + c = self._memobj.vfo_b.band_150 + lo = 136000000 + hi = 180000000 + else: # 450 + c = self._memobj.vfo_b.band_450 + lo = 400000000 + hi = 512000000 + + prefix = "vfo_%s.band_%d" % (area, band) + bf = RadioSettingGroup(prefix, "%dMHz Band" % band) + freq = RadioSettingValueString(0, 15, int2freq(c.freq * 10)) + rs = RadioSetting(prefix + ".freq", "Rx Frequency", freq) + rs.set_apply_callback(apply_freq, lo, hi, c) + bf.append(rs) + + off = RadioSettingValueString(0, 15, int2freq(c.offset * 10)) + rs = RadioSetting(prefix + ".offset", "Tx Offset(28)", off) + rs.set_apply_callback(apply_offset, c) + bf.append(rs) + + rs = RadioSetting(prefix + ".encqt", + "Encode QT(17,19)", + RadioSettingValueList(TONE_LIST, + short2tone(c.encqt))) + rs.set_apply_callback(apply_enc, c) + bf.append(rs) + + rs = RadioSetting(prefix + ".decqt", + "Decode QT(16,18)", + RadioSettingValueList(TONE_LIST, + short2tone(c.decqt))) + rs.set_apply_callback(apply_dec, c) + bf.append(rs) + + bf.append(RadioSetting(prefix + ".qt", + "Mute Mode(21)", + RadioSettingValueList(SPMUTE_LIST, + SPMUTE_LIST[c.qt]))) + bf.append(RadioSetting(prefix + ".scan", + "Scan this(48)", + RadioSettingValueBoolean(c.scan))) + bf.append(RadioSetting(prefix + ".pwr", + "Power(5)", + RadioSettingValueList( + POWER_LIST, POWER_LIST[c.pwr]))) + bf.append(RadioSetting(prefix + ".mod", + "AM Modulation(54)", + RadioSettingValueBoolean(c.mod))) + bf.append(RadioSetting(prefix + ".fm_dev", + "FM Deviation(4)", + RadioSettingValueList( + BANDWIDTH_LIST, + BANDWIDTH_LIST[c.fm_dev]))) + bf.append( + RadioSetting(prefix + ".shift", + "Frequency Shift(6)", + RadioSettingValueList(OFFSET_LIST, + OFFSET_LIST[c.shift]))) + return bf + + def _area_tab(self, area): + """Build a VFO tab + """ + def apply_scan_st(setting, scan_lo, scan_hi, obj): + f = freq2short(setting.value, scan_lo, scan_hi) + obj.scan_st = f + + def apply_scan_end(setting, scan_lo, scan_hi, obj): + f = freq2short(setting.value, scan_lo, scan_hi) + obj.scan_end = f + + if area == "a": + desc = "Area A Settings" + c = self._memobj.a_conf + scan_lo = 108000000 + scan_hi = 985000000 + scan_rng = self._memobj.settings.a + band_list = (150, 200, 300, 450, 700) + else: + desc = "Area B Settings" + c = self._memobj.b_conf + scan_lo = 136000000 + scan_hi = 512000000 + scan_rng = self._memobj.settings.b + band_list = (150, 450) + + prefix = "%s_conf" % area + af = RadioSettingGroup(prefix, desc) + af.append( + RadioSetting(prefix + ".w_mode", + "Workmode", + RadioSettingValueList( + WORKMODE_LIST, + WORKMODE_LIST[c.w_mode]))) + af.append(RadioSetting(prefix + ".w_chan", + "Channel", + RadioSettingValueInteger(1, 999, + c.w_chan))) + af.append( + RadioSetting(prefix + ".scan_grp", + "Scan Group(49)", + RadioSettingValueList( + SCANGRP_LIST, + SCANGRP_LIST[c.scan_grp]))) + af.append(RadioSetting(prefix + ".bcl", + "Busy Channel Lock-out(15)", + RadioSettingValueBoolean(c.bcl))) + af.append( + RadioSetting(prefix + ".sql", + "Squelch Level(8)", + RadioSettingValueList(LIST_0_9, + LIST_0_9[c.sql]))) + af.append( + RadioSetting(prefix + ".cset", + "Call ID Group(52)", + RadioSettingValueList(LIST_1_20, + LIST_1_20[c.cset]))) + af.append( + RadioSetting(prefix + ".step", + "Frequency Step(3)", + RadioSettingValueList( + STEP_LIST, STEP_LIST[c.step]))) + af.append( + RadioSetting(prefix + ".scan_mode", + "Scan Mode(20)", + RadioSettingValueList( + SCANMODE_LIST, + SCANMODE_LIST[c.scan_mode]))) + af.append( + RadioSetting(prefix + ".scan_range", + "Scan Range(50)", + RadioSettingValueList( + SCANRANGE_LIST, + SCANRANGE_LIST[c.scan_range]))) + st = RadioSettingValueString(0, 15, + short2freq(scan_rng.scan_st)) + rs = RadioSetting("settings.%s.scan_st" % area, + "Frequency Scan Start", st) + rs.set_apply_callback(apply_scan_st, scan_lo, scan_hi, scan_rng) + af.append(rs) + + end = RadioSettingValueString(0, 15, + short2freq(scan_rng.scan_end)) + rs = RadioSetting("settings.%s.scan_end" % area, + "Frequency Scan End", end) + rs.set_apply_callback(apply_scan_end, scan_lo, scan_hi, + scan_rng) + af.append(rs) + # Each area has its own set of bands + for band in (band_list): + af.append(self._band_tab(area, band)) + return af + + def _key_tab(self): + """Build radio key/button menu + """ + s = self._memobj.settings + kf = RadioSettingGroup("key_grp", "Key Settings") + + kf.append(RadioSetting("settings.pf1", + "PF1 Key function(55)", + RadioSettingValueList( + PF1KEY_LIST, + PF1KEY_LIST[s.pf1]))) + kf.append(RadioSetting("settings.pf2", + "PF2 Key function(56)", + RadioSettingValueList( + PF2KEY_LIST, + PF2KEY_LIST[s.pf2]))) + kf.append(RadioSetting("settings.pf3", + "PF3 Key function(57)", + RadioSettingValueList( + PF3KEY_LIST, + PF3KEY_LIST[s.pf3]))) + return kf + + def _get_settings(self): + """Build the radio configuration settings menus + """ + + core_grp = self._core_tab() + fm_grp = self._fm_tab() + area_a_grp = self._area_tab("a") + area_b_grp = self._area_tab("b") + key_grp = self._key_tab() + scan_grp = self._scan_grp() + callid_grp = self._callid_grp() + admin_grp = self._admin_tab() + rpt_grp = self._repeater_tab() + + core_grp.append(key_grp) + core_grp.append(admin_grp) + core_grp.append(rpt_grp) + group = RadioSettings(core_grp, + area_a_grp, + area_b_grp, + fm_grp, + scan_grp, + callid_grp + ) + return group + + def get_settings(self): + """ Public build out linkage between radio settings and UI + """ + try: + return self._get_settings() + except Exception: + import traceback + LOG.error("Failed to parse settings: %s", + traceback.format_exc()) + return None + + def _is_freq(self, element): + """This is a hack to smoke out whether we need to do + frequency translations for otherwise innocent u16s and u32s + """ + return "rxfreq" in element.get_name() or \ + "txfreq" in element.get_name() or \ + "scan_st" in element.get_name() or \ + "scan_end" in element.get_name() or \ + "offset" in element.get_name() or \ + "fm_stop" in element.get_name() + + def set_settings(self, settings): + """ Public update radio settings via UI callback + A lot of this should be in common code.... + """ + + for element in settings: + if not isinstance(element, RadioSetting): + LOG.debug("set_settings: not instance %s" % + element.get_name()) + 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]: + # decode an array index + if "[" in bit and "]" in bit: + bit, index = bit.split("[", 1) + index, junk = index.split("]", 1) + index = int(index) + obj = getattr(obj, bit)[index] + else: + obj = getattr(obj, bit) + setting = bits[-1] + else: + obj = self._memobj.settings + setting = element.get_name() + + if element.has_apply_callback(): + LOG.debug("Using apply callback") + element.run_apply_callback() + 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("set_settings: Exception with %s" % + element.get_name()) + raise diff --git a/chirp/drivers/radioddity_r2.py b/chirp/drivers/radioddity_r2.py new file mode 100644 index 0000000..d28696a --- /dev/null +++ b/chirp/drivers/radioddity_r2.py @@ -0,0 +1,620 @@ +# Copyright August 2018 Klaus Ruebsam <dg5eau@ruebsam.eu> +# +# 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 os +import struct +import logging + +from chirp import chirp_common, directory, memmap +from chirp import bitwise, errors, util +from chirp.settings import RadioSetting, RadioSettingGroup, \ + RadioSettingValueInteger, RadioSettingValueList, \ + RadioSettingValueBoolean, RadioSettings, \ + RadioSettingValueString + +LOG = logging.getLogger(__name__) + +# memory map +# 0000 copy of channel 16: 0100 - 010F +# 0010 Channel 1 +# 0020 Channel 2 +# 0030 Channel 3 +# 0040 Channel 4 +# 0050 Channel 5 +# 0060 Channel 6 +# 0070 Channel 7 +# 0080 Channel 8 +# 0090 Channel 9 +# 00A0 Channel 10 +# 00B0 Channel 11 +# 00C0 Channel 12 +# 00D0 Channel 13 +# 00E0 Channel 14 +# 00F0 Channel 15 +# 0100 Channel 16 +# 03C0 various settings + +# the last three bytes of every channel are identical +# to the first three bytes of the next channel in row. +# However it will automatically be filled by the radio itself + +MEM_FORMAT = """ +#seekto 0x0010; +struct { + lbcd rx_freq[4]; + lbcd tx_freq[4]; + lbcd rx_tone[2]; + lbcd tx_tone[2]; + u8 unknown1:1, + compand:1, + scramb:1, + scanadd:1, + power:1, + mode:1, + unknown2:1, + bclo:1; + u8 unknown3[3]; +} memory[16]; + +#seekto 0x03C0; +struct { + u8 unknown3c08:1, + scanmode:1, + unknown3c06:1, + unknown3c05:1, + voice:2, + save:1, + beep:1; + u8 squelch; + u8 unknown3c2; + u8 timeout; + u8 voxgain; + u8 specialcode; + u8 unknown3c6; + u8 voxdelay; +} settings; + +""" + +CMD_ACK = "\x06" +CMD_STX = "\x02" +CMD_ENQ = "\x05" + +POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50), + chirp_common.PowerLevel("High", watts=3.00)] +TIMEOUT_LIST = ["Off"] + ["%s seconds" % x for x in range(30, 330, 30)] +SCANMODE_LIST = ["Carrier", "Timer"] +VOICE_LIST = ["Off", "Chinese", "English"] +VOX_LIST = ["Off"] + ["%s" % x for x in range(1, 9)] +VOXDELAY_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0"] +MODE_LIST = ["WFM", "NFM"] + +TONES = chirp_common.TONES +DTCS_CODES = chirp_common.DTCS_CODES + +SETTING_LISTS = { + "tot": TIMEOUT_LIST, + "scanmode": SCANMODE_LIST, + "voice": VOICE_LIST, + "vox": VOX_LIST, + "voxdelay": VOXDELAY_LIST, + "mode": MODE_LIST, + } + +VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \ + "`{|}!\"#$%&'()*+,-./:;<=>?@[]^_" + + +def _r2_enter_programming_mode(radio): + serial = radio.pipe + + magic = "TYOGRAM" + exito = False + serial.write(CMD_STX) + for i in range(0, 5): + for j in range(0, len(magic)): + serial.write(magic[j]) + ack = serial.read(1) + if ack == CMD_ACK: + exito = True + break + + # check if we had EXITO + if exito is False: + msg = "The radio did not accept program mode after five tries.\n" + msg += "Check your interface cable and power cycle your radio." + raise errors.RadioError(msg) + + try: + serial.write(CMD_STX) + ident = serial.read(8) + except: + _r2_exit_programming_mode(radio) + raise errors.RadioError("Error communicating with radio") + + # No idea yet what the next 7 bytes stand for + # as long as they start with ACK we are fine + if not ident.startswith(CMD_ACK): + _r2_exit_programming_mode(radio) + LOG.debug(util.hexprint(ident)) + raise errors.RadioError("Radio returned unknown identification string") + + try: + serial.write(CMD_ACK) + ack = serial.read(1) + except: + _r2_exit_programming_mode(radio) + raise errors.RadioError("Error communicating with radio") + + if ack != CMD_ACK: + _r2_exit_programming_mode(radio) + raise errors.RadioError("Radio refused to enter programming mode") + + # the next 6 bytes represent the 6 digit password + # they are somehow coded where '1' becomes x01 and 'a' becomes x25 + try: + serial.write(CMD_ENQ) + ack = serial.read(6) + except: + _r2_exit_programming_mode(radio) + raise errors.RadioError("Error communicating with radio") + + # we will only read if no password is set + if ack != "\xFF\xFF\xFF\xFF\xFF\xFF": + _r2_exit_programming_mode(radio) + raise errors.RadioError("Radio is password protected") + try: + serial.write(CMD_ACK) + ack = serial.read(6) + + except: + _r2_exit_programming_mode(radio) + raise errors.RadioError("Error communicating with radio 2") + + if ack != CMD_ACK: + _r2_exit_programming_mode(radio) + raise errors.RadioError("Radio refused to enter programming mode 2") + + +def _r2_exit_programming_mode(radio): + serial = radio.pipe + try: + serial.write(CMD_ACK) + except: + raise errors.RadioError("Radio refused to exit programming mode") + + +def _r2_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: + for j in range(0, len(cmd)): + serial.write(cmd[j]) + + response = serial.read(4 + block_size) + if response[:4] != expectedresponse: + _r2_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: + _r2_exit_programming_mode(radio) + raise errors.RadioError("Failed to read block at %04x" % block_addr) + + if ack != CMD_ACK: + _r2_exit_programming_mode(radio) + raise Exception("No ACK reading block %04x." % (block_addr)) + + return block_data + + +def _r2_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 block %04x..." % (block_addr)) + LOG.debug(util.hexprint(cmd + data)) + + try: + for j in range(0, len(cmd)): + serial.write(cmd[j]) + for j in range(0, len(data)): + serial.write(data[j]) + if serial.read(1) != CMD_ACK: + raise Exception("No ACK") + except: + _r2_exit_programming_mode(radio) + raise errors.RadioError("Failed to send block " + "%04x to radio" % block_addr) + + +def do_download(radio): + LOG.debug("download") + _r2_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 = _r2_read_block(radio, addr, radio._block_size) + data += block + + LOG.debug("Address: %04x" % addr) + LOG.debug(util.hexprint(block)) + + data += radio.MODEL.ljust(8) + + _r2_exit_programming_mode(radio) + + return memmap.MemoryMap(data) + + +def do_upload(radio): + status = chirp_common.Status() + status.msg = "Uploading to radio" + + _r2_enter_programming_mode(radio) + + status.cur = 0 + status.max = radio._memsize + + 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) + _r2_write_block(radio, addr, block_size) + + _r2_exit_programming_mode(radio) + + +@directory.register +class RadioddityR2Radio(chirp_common.CloneModeRadio): + """Radioddity R2""" + VENDOR = "Radioddity" + MODEL = "R2" + BAUD_RATE = 9600 + + # definitions on how to read StartAddr EndAddr BlockZize + _ranges = [ + (0x0000, 0x01F8, 0x08), + (0x01F8, 0x03F0, 0x08) + ] + _memsize = 0x03F0 + # never read more than 8 bytes at once + _block_size = 0x08 + # frequency range is 400-470MHz + _range = [400000000, 470000000] + # maximum 16 channels + _upper = 16 + + def get_features(self): + rf = chirp_common.RadioFeatures() + rf.has_settings = True + rf.has_bank = False + rf.has_tuning_step = False + rf.has_name = False + rf.has_offset = True + rf.has_mode = True + rf.has_dtcs = True + rf.has_rx_dtcs = True + rf.has_dtcs_polarity = True + rf.has_ctone = True + rf.has_cross = True + rf.can_odd_split = False + rf.valid_modes = MODE_LIST + rf.valid_duplexes = ["", "-", "+", "off"] + rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"] + rf.valid_cross_modes = [ + "Tone->DTCS", + "DTCS->Tone", + "->Tone", + "Tone->Tone", + "->DTCS", + "DTCS->", + "DTCS->DTCS"] + rf.valid_power_levels = POWER_LEVELS + rf.valid_skips = [] + rf.valid_bands = [self._range] + rf.memory_bounds = (1, self._upper) + return rf + + def process_mmap(self): + """Process the mem map into the mem object""" + self._memobj = bitwise.parse(MEM_FORMAT, self._mmap) + # to set the vars on the class to the correct ones + + def sync_in(self): + """Download from radio""" + try: + data = do_download(self) + except errors.RadioError: + # Pass through any real errors we raise + raise + except: + # If anything unexpected happens, make sure we raise + # a RadioError and log the problem + LOG.exception('Unexpected error during download') + raise errors.RadioError('Unexpected error communicating ' + 'with the radio') + self._mmap = data + self.process_mmap() + + def sync_out(self): + """Upload to radio""" + try: + do_upload(self) + except: + # If anything unexpected happens, make sure we raise + # a RadioError and log the problem + LOG.exception('Unexpected error during upload') + raise errors.RadioError('Unexpected error communicating ' + 'with the radio') + + def 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 get_memory(self, number): + bitpos = (1 << ((number - 1) % 8)) + bytepos = ((number - 1) / 8) + LOG.debug("bitpos %s" % bitpos) + LOG.debug("bytepos %s" % bytepos) + + _mem = self._memobj.memory[number - 1] + + mem = chirp_common.Memory() + + mem.number = number + + mem.freq = int(_mem.rx_freq) * 10 + + txfreq = int(_mem.tx_freq) * 10 + if txfreq == mem.freq: + mem.duplex = "" + elif txfreq == 0: + mem.duplex = "off" + mem.offset = 0 + # 166666665*10 is the equivalent for FF FF FF FF + # stored in the TX field + elif txfreq == 1666666650: + mem.duplex = "off" + mem.offset = 0 + elif txfreq < mem.freq: + mem.duplex = "-" + mem.offset = mem.freq - txfreq + elif txfreq > mem.freq: + mem.duplex = "+" + mem.offset = txfreq - mem.freq + + # get bandwith FM or NFM + mem.mode = MODE_LIST[_mem.mode] + + # tone data + txtone = self.decode_tone(_mem.tx_tone) + rxtone = self.decode_tone(_mem.rx_tone) + chirp_common.split_tone_decode(mem, txtone, rxtone) + + mem.power = POWER_LEVELS[_mem.power] + + # add extra channel settings to the OTHER tab of the properties + # extra settings are unfortunately inverted + mem.extra = RadioSettingGroup("extra", "Extra") + + scanadd = RadioSetting("scanadd", "Scan Add", + RadioSettingValueBoolean( + not bool(_mem.scanadd))) + scanadd.set_doc("Add channel for scanning") + mem.extra.append(scanadd) + + bclo = RadioSetting("bclo", "Busy Lockout", + RadioSettingValueBoolean(not bool(_mem.bclo))) + bclo.set_doc("Busy Lockout") + mem.extra.append(bclo) + + scramb = RadioSetting("scramb", "Scramble", + RadioSettingValueBoolean(not bool(_mem.scramb))) + scramb.set_doc("Scramble Audio Signal") + mem.extra.append(scramb) + + compand = RadioSetting("compand", "Compander", + RadioSettingValueBoolean( + not bool(_mem.compand))) + compand.set_doc("Compress Audio for TX") + mem.extra.append(compand) + + return mem + + def set_memory(self, mem): + bitpos = (1 << ((mem.number - 1) % 8)) + bytepos = ((mem.number - 1) / 8) + LOG.debug("bitpos %s" % bitpos) + LOG.debug("bytepos %s" % bytepos) + + # Get a low-level memory object mapped to the image + _mem = self._memobj.memory[mem.number - 1] + + if mem.empty: + LOG.debug("initializing memory channel %d" % mem.number) + _mem.set_raw(BLANK_MEMORY) + + if mem.empty: + return + + _mem.rx_freq = mem.freq / 10 + + if mem.duplex == "off": + for i in range(0, 4): + _mem.tx_freq[i].set_raw("\xFF") + elif mem.duplex == "+": + _mem.tx_freq = (mem.freq + mem.offset) / 10 + elif mem.duplex == "-": + _mem.tx_freq = (mem.freq - mem.offset) / 10 + else: + _mem.tx_freq = mem.freq / 10 + + # power, default power is low + if mem.power: + _mem.power = POWER_LEVELS.index(mem.power) + else: + _mem.power = 0 # low + + # tone data + ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \ + chirp_common.split_tone_encode(mem) + self.encode_tone(_mem.tx_tone, txmode, txtone, txpol) + self.encode_tone(_mem.rx_tone, rxmode, rxtone, rxpol) + + _mem.mode = MODE_LIST.index(mem.mode) + + # extra settings are unfortunately inverted + for setting in mem.extra: + LOG.debug("@set_mem:", setting.get_name(), setting.value) + setattr(_mem, setting.get_name(), not setting.value) + + def get_settings(self): + _settings = self._memobj.settings + basic = RadioSettingGroup("basic", "Basic Settings") + top = RadioSettings(basic) + + rs = RadioSetting("settings.squelch", "Squelch Level", + RadioSettingValueInteger(0, 9, _settings.squelch)) + basic.append(rs) + + rs = RadioSetting("settings.timeout", "Timeout Timer", + RadioSettingValueList( + TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout])) + + basic.append(rs) + + rs = RadioSetting("settings.scanmode", "Scan Mode", + RadioSettingValueList( + SCANMODE_LIST, + SCANMODE_LIST[_settings.scanmode])) + basic.append(rs) + + rs = RadioSetting("settings.voice", "Voice Prompts", + RadioSettingValueList( + VOICE_LIST, VOICE_LIST[_settings.voice])) + basic.append(rs) + + rs = RadioSetting("settings.voxgain", "VOX Level", + RadioSettingValueList( + VOX_LIST, VOX_LIST[_settings.voxgain])) + basic.append(rs) + + rs = RadioSetting("settings.voxdelay", "VOX Delay Time", + RadioSettingValueList( + VOXDELAY_LIST, + VOXDELAY_LIST[_settings.voxdelay])) + basic.append(rs) + + rs = RadioSetting("settings.save", "Battery Save", + RadioSettingValueBoolean(_settings.save)) + basic.append(rs) + + rs = RadioSetting("settings.beep", "Beep Tone", + RadioSettingValueBoolean(_settings.beep)) + basic.append(rs) + + def _filter(name): + filtered = "" + for char in str(name): + if char in VALID_CHARS: + filtered += char + else: + filtered += " " + return filtered + + return top + + def set_settings(self, settings): + for element in settings: + if not isinstance(element, RadioSetting): + self.set_settings(element) + continue + else: + try: + if "." in element.get_name(): + bits = element.get_name().split(".") + obj = self._memobj + for bit in bits[:-1]: + obj = getattr(obj, bit) + setting = bits[-1] + else: + obj = self._memobj.settings + setting = element.get_name() + + 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): + # This radio has always been post-metadata, so never do + # old-school detection + return False diff --git a/chirp/drivers/retevis_rt22.py b/chirp/drivers/retevis_rt22.py index 0aa1370..c9bf0e1 100644 --- a/chirp/drivers/retevis_rt22.py +++ b/chirp/drivers/retevis_rt22.py @@ -125,10 +125,18 @@ def _rt22_enter_programming_mode(radio): _rt22_exit_programming_mode(radio) raise errors.RadioError("Error communicating with radio") - if not ident.startswith("P32073"): - _rt22_exit_programming_mode(radio) - LOG.debug(util.hexprint(ident)) - raise errors.RadioError("Radio returned unknown identification string") + # check if ident is OK + itis = False + for fp in radio._fileid: + if fp in ident: + # got it! + itis = True + + break + + if itis is False: + LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident)) + raise errors.RadioError("Radio identification failed.") try: serial.write(CMD_ACK) @@ -289,6 +297,7 @@ class RT22Radio(chirp_common.CloneModeRadio): ] _memsize = 0x0400 _block_size = 0x40 + _fileid = ["P32073", "P3" + "\x00\x00\x00" + "3"] def get_features(self): rf = chirp_common.RadioFeatures() diff --git a/chirp/drivers/ts850.py b/chirp/drivers/ts850.py new file mode 100644 index 0000000..4520aca --- /dev/null +++ b/chirp/drivers/ts850.py @@ -0,0 +1,254 @@ +# Copyright 2018 Antony Jordan <me6kxv@gmail.com> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see <http://www.gnu.org/licenses/>. + +import logging + +from chirp import chirp_common, directory, errors +from chirp.drivers.kenwood_live import KenwoodLiveRadio, \ + command, iserr, NOCACHE + +LOG = logging.getLogger(__name__) + +TS850_DUPLEX = ["off", "split"] +TS850_TMODES = ["", "Tone"] +TS850_SKIP = ["", "S"] + +TS850_MODES = { + "N/A": " ", + "N/A": "0", + "LSB": "1", + "USB": "2", + "CW": "3", + "FM": "4", + "AM": "5", + "FSK": "6", + "CW-R": "7", + "FSK-R": "9", +} +TS850_MODES_REV = {val: mode for mode, val in TS850_MODES.iteritems()} + +TS850_TONES = list(chirp_common.OLD_TONES) +TS850_TONES.remove(69.3) + +TS850_BANDS = [ + (1800000, 2000000), # 160M Band + (3500000, 4000000), # 80M Band + (7000000, 7300000), # 40M Band + (10100000, 10150000), # 30M Band + (14000000, 14350000), # 20M Band + (18068000, 18168000), # 17M Band + (21000000, 21450000), # 15M Band + (24890000, 24990000), # 12M Band + (28000000, 29700000) # 10M Band +] + + +@directory.register +class TS850Radio(KenwoodLiveRadio): + """Kenwood TS-850""" + MODEL = "TS-850" + BAUD_RATE = 4800 + + _upper = 99 + _kenwood_valid_tones = list(TS850_TONES) + + def get_features(self): + rf = chirp_common.RadioFeatures() + + rf.can_odd_split = True + + rf.has_bank = False + rf.has_ctone = False + rf.has_dtcs = False + rf.has_dtcs_polarity = False + rf.has_name = False + rf.has_tuning_step = False + + rf.memory_bounds = (0, self._upper) + + rf.valid_bands = TS850_BANDS + rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + rf.valid_duplexes = TS850_DUPLEX + rf.valid_modes = TS850_MODES.keys() + rf.valid_skips = TS850_SKIP + rf.valid_tmodes = TS850_TMODES + + return rf + + def get_memory(self, number): + if number < 0 or number > self._upper: + raise errors.InvalidMemoryLocation( + "Number must be between 0 and %i" % self._upper) + if number in self._memcache and not NOCACHE: + return self._memcache[number] + + result = command(self.pipe, *self._cmd_get_memory(number)) + + if result == "N": + mem = chirp_common.Memory() + mem.number = number + mem.empty = True + self._memcache[mem.number] = mem + return mem + + mem = self._parse_mem_spec(result) + self._memcache[mem.number] = mem + + # check for split frequency operation + result = command(self.pipe, *self._cmd_get_split(number)) + self._parse_split_spec(mem, result) + + return mem + + def set_memory(self, memory): + if memory.number < 0 or memory.number > self._upper: + raise errors.InvalidMemoryLocation( + "Number must be between 0 and %i" % self._upper) + + if memory.number > 90: + if memory.duplex == TS850_DUPLEX[0]: + memory.duplex = TS850_DUPLEX[1] + memory.offset = memory.freq + else: + if memory.freq > memory.offset: + temp = memory.freq + memory.freq = memory.offset + memory.offset = temp + + # Clear out memory contents to prevent errors + spec = self._make_base_spec(memory, 0) + spec = "".join(spec) + result = command(self.pipe, *self._cmd_set_memory(memory.number, spec)) + + if iserr(result): + raise errors.InvalidDataError("Radio refused %i" % + memory.number) + + # If we have a split set the transmit frequency first. + if memory.duplex == TS850_DUPLEX[1]: + spec = "".join(self._make_split_spec(memory)) + result = command(self.pipe, *self._cmd_set_split(memory.number, + spec)) + if iserr(result): + raise errors.InvalidDataError("Radio refused %i" % + memory.number) + + spec = self._make_mem_spec(memory) + spec = "".join(spec) + result = command(self.pipe, *self._cmd_set_memory(memory.number, spec)) + if iserr(result): + raise errors.InvalidDataError("Radio refused %i" % memory.number) + + def erase_memory(self, number): + if number not in self._memcache: + return + + resp = command(self.pipe, *self._cmd_erase_memory(number)) + if iserr(resp): + raise errors.RadioError("Radio refused delete of %i" % number) + + del self._memcache[number] + + def _cmd_get_memory(self, number): + return "MR", "0 %02i" % number + + def _cmd_get_split(self, number): + return "MR", "1 %02i" % number + + def _cmd_get_memory_name(self, number): + LOG.error("TS-850 does not support memory channel names") + return "" + + def _cmd_set_memory(self, number, spec): + return "MW", "0 %02i%s" % (number, spec) + + def _cmd_set_split(self, number, spec): + return "MW", "1 %02i%s" % (number, spec) + + def _cmd_set_memory_name(self, number, name): + LOG.error("TS-850 does not support memory channel names") + return "" + + def _cmd_erase_memory(self, number): + return "MW0 %02i%014i " % (number, 0) + + def _parse_mem_spec(self, spec): + mem = chirp_common.Memory() + + # pad string so indexes match Kenwood docs + spec = " " + spec # Param Format Function + + _p1 = spec[3] # P1 9 Split Specification + # _p2 = spec[4] # P2 - Blank + _p3 = spec[5:7] # P3 7 Memory Channel + _p4 = spec[7:18] # P4 4 Frequency + _p5 = spec[18] # P5 2 Mode + _p6 = spec[19] # P6 10 Memory Lockout + _p7 = spec[20] # P7 1 Tone On/Off + _p8 = spec[21:23] # P8 14 Tone Frequency + # _p9 = spec[23] # P9 - Blank + + mem.duplex = TS850_DUPLEX[int(_p1)] + mem.number = int(_p3) + mem.freq = int(_p4) + mem.mode = TS850_MODES_REV[_p5] + mem.skip = TS850_SKIP[int(_p6)] + mem.tmode = TS850_TMODES[int(_p7)] + + if mem.tmode == TS850_TMODES[1]: + mem.rtone = TS850_TONES[int(_p8)-1] + + return mem + + def _parse_split_spec(self, mem, spec): + + # pad string so indexes match Kenwood docs + spec = " " + spec + + split_freq = int(spec[7:18]) # P4 + + if mem.freq != 0: + mem.duplex = "split" + mem.offset = split_freq + + return mem + + def _make_base_spec(self, mem, freq): + if mem.mode == "FM" \ + and mem.duplex == TS850_DUPLEX[1] \ + and mem.tmode == TS850_TMODES[1]: + tmode = "1" + tone = "%02i" % (TS850_TONES.index(mem.rtone)+1) + else: + tmode = "0" + tone = " " + + spec = ( # Param Format Function + "%011i" % freq, # P4 4 Frequency + TS850_MODES[mem.mode], # P5 2 Mode + # (Except Tune) + "%i" % (mem.skip == TS850_SKIP[1]), # P6 10 Memory Lockout + tmode, # P7 1 Tone On/Off + tone, # P8 1 Tone Frequency + " " # P9 14 Padding + ) + + return spec + + def _make_mem_spec(self, mem): + return self._make_base_spec(mem, mem.freq) + + def _make_split_spec(self, mem): + return self._make_base_spec(mem, mem.offset) |
