# Copyright 2013 Dan Smith # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import os import struct import time import logging from chirp import bitwise from chirp import chirp_common from chirp import directory from chirp import errors from chirp import memmap from chirp import util from chirp.settings import RadioSettingGroup, RadioSetting, RadioSettings, \ RadioSettingValueList, RadioSettingValueString, RadioSettingValueBoolean LOG = logging.getLogger(__name__) mem_format = """ struct memory { bbcd freq[4]; // 0123 bbcd offset[4]; // 4567 u8 unknownA:4, // 8 tune_step:4; u8 rxdcsextra:1, // 9 txdcsextra:1, rxinv:1, txinv:1, channel_width:2, unknownB:1, tx_off:1; u8 unknown8:4, // A power:2, duplex:2; u8 unknown4:4, // B rxtmode:2, txtmode:2; u8 unknown5:2, // C txtone:6; u8 unknown6:2, // D rxtone:6; u8 txcode; // E u8 rxcode; // F u8 unknown7[3]; // 012 char name[6]; // 345678 u8 unknown1:1, // 9 squelch:3, unknown2:4; u8 unknownZ[6]; // ABCDEF }; #seekto 0x0100; u8 used_flags[50]; #seekto 0x0120; u8 skip_scan[50]; #seekto 0x0220; struct { u8 unknown1:6, display:2; u8 unknown2[19]; u8 unknown3:3, apo:5; } settings; #seekto 0x2000; struct memory memory[200]; """ def _echo_write(radio, data): try: radio.pipe.write(data) except Exception, e: LOG.error("Error writing to radio: %s" % e) raise errors.RadioError("Unable to write to radio") def _read(radio, length): try: data = radio.pipe.read(length) except Exception, e: LOG.error("Error reading from radio: %s" % e) raise errors.RadioError("Unable to read from radio") if len(data) != length: LOG.error("Short read from radio (%i, expected %i)" % (len(data), length)) LOG.debug(util.hexprint(data)) raise errors.RadioError("Short read from radio") return data valid_model = ['TERMN8R', 'OBLTR8R', 'NSTIG8R'] def _ident(radio): radio.pipe.setTimeout(1) _echo_write(radio, "PROGRAM") response = radio.pipe.read(3) if response != "QX\x06": LOG.debug("Response was:\n%s" % util.hexprint(response)) raise errors.RadioError("Unsupported model") _echo_write(radio, "\x02") response = radio.pipe.read(16) LOG.debug(util.hexprint(response)) if response[1:8] not in valid_model: LOG.debug("Response was:\n%s" % util.hexprint(response)) raise errors.RadioError("Unsupported model") def _finish(radio): endframe = "\x45\x4E\x44" _echo_write(radio, endframe) result = radio.pipe.read(1) if result != "\x06": LOG.debug("Got:\n%s" % util.hexprint(result)) raise errors.RadioError("Radio did not finish cleanly") def _checksum(data): cs = 0 for byte in data: cs += ord(byte) return cs % 256 def _send(radio, cmd, addr, length, data=None): frame = struct.pack(">cHb", cmd, addr, length) if data: frame += data frame += chr(_checksum(frame[1:])) frame += "\x06" _echo_write(radio, frame) LOG.debug("Sent:\n%s" % util.hexprint(frame)) if data: result = radio.pipe.read(1) if result != "\x06": LOG.debug("Ack was: %s" % repr(result)) raise errors.RadioError( "Radio did not accept block at %04x" % addr) return result = _read(radio, length + 6) LOG.debug("Got:\n%s" % util.hexprint(result)) header = result[0:4] data = result[4:-2] ack = result[-1] if ack != "\x06": LOG.debug("Ack was: %s" % repr(ack)) raise errors.RadioError("Radio NAK'd block at %04x" % addr) _cmd, _addr, _length = struct.unpack(">cHb", header) if _addr != addr or _length != _length: LOG.debug("Expected/Received:") LOG.debug(" Length: %02x/%02x" % (length, _length)) LOG.debug(" Addr: %04x/%04x" % (addr, _addr)) raise errors.RadioError("Radio send unexpected block") cs = _checksum(result[1:-2]) if cs != ord(result[-2]): LOG.debug("Calculated: %02x" % cs) LOG.debug("Actual: %02x" % ord(result[-2])) raise errors.RadioError("Block at 0x%04x failed checksum" % addr) return data def _download(radio): _ident(radio) memobj = None data = "" for start, end in radio._ranges: for addr in range(start, end, 0x10): block = _send(radio, 'R', addr, 0x10) data += block status = chirp_common.Status() status.cur = len(data) status.max = end status.msg = "Cloning from radio" radio.status_fn(status) _finish(radio) return memmap.MemoryMap(data) def _upload(radio): _ident(radio) for start, end in radio._ranges: for addr in range(start, end, 0x10): if addr < 0x0100: continue block = radio._mmap[addr:addr + 0x10] _send(radio, 'W', addr, len(block), block) status = chirp_common.Status() status.cur = addr status.max = end status.msg = "Cloning to radio" radio.status_fn(status) _finish(radio) TONES = [62.5] + list(chirp_common.TONES) TMODES = ['', 'Tone', 'DTCS', ''] DUPLEXES = ['', '', '-', '+', 'split', 'off'] MODES = ["NFM", "FM"] POWER_LEVELS = [chirp_common.PowerLevel("High", watts=5), chirp_common.PowerLevel("Mid", watts=2), chirp_common.PowerLevel("Low", watts=1)] @directory.register class AnyToneTERMN8RRadio(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio): """AnyTone TERMN8R""" VENDOR = "AnyTone" MODEL = "TERMN8R" BAUD_RATE = 9600 _file_ident = "TERMN8R" # May try to mirror the OEM behavior later _ranges = [ (0x0000, 0x8000), ] @classmethod def get_prompts(cls): rp = chirp_common.RadioPrompts() rp.experimental = ("The Anytone driver is currently experimental. " "There are no known issues with it, but you should " "proceed with caution.") return rp def get_features(self): rf = chirp_common.RadioFeatures() rf.has_settings = True rf.has_bank = False rf.has_cross = True rf.has_tuning_step = False rf.has_rx_dtcs = True rf.valid_skips = ["", "S"] rf.valid_modes = ["NFM", "FM"] rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross'] rf.valid_cross_modes = ['Tone->DTCS', 'DTCS->Tone', '->Tone', '->DTCS', 'Tone->Tone'] rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES rf.valid_bands = [(108000000, 520000000)] rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + "-" rf.valid_name_length = 6 rf.valid_power_levels = POWER_LEVELS rf.valid_duplexes = DUPLEXES rf.can_odd_split = True rf.memory_bounds = (0, 199) return rf def sync_in(self): self._mmap = _download(self) self.process_mmap() def sync_out(self): _upload(self) def process_mmap(self): self._memobj = bitwise.parse(mem_format, self._mmap) def _get_dcs_index(self, _mem, which): base = getattr(_mem, '%scode' % which) extra = getattr(_mem, '%sdcsextra' % which) return (int(extra) << 8) | int(base) def _set_dcs_index(self, _mem, which, index): base = getattr(_mem, '%scode' % which) extra = getattr(_mem, '%sdcsextra' % which) base.set_value(index & 0xFF) extra.set_value(index >> 8) def get_memory(self, number): bitpos = (1 << (number % 8)) bytepos = (number / 8) _mem = self._memobj.memory[number] _skp = self._memobj.skip_scan[bytepos] _usd = self._memobj.used_flags[bytepos] mem = chirp_common.Memory() mem.number = number if _usd & bitpos: mem.empty = True return mem mem.freq = int(_mem.freq) * 100 mem.offset = int(_mem.offset) * 100 mem.name = str(_mem.name).rstrip() mem.duplex = DUPLEXES[_mem.duplex] mem.mode = _mem.channel_width and "NFM" or "FM" if _mem.tx_off == True: mem.duplex = "off" mem.offset = 0 rxtone = txtone = None rxmode = TMODES[_mem.rxtmode] txmode = TMODES[_mem.txtmode] if txmode == "Tone": txtone = TONES[_mem.txtone] elif txmode == "DTCS": txtone = chirp_common.ALL_DTCS_CODES[self._get_dcs_index(_mem, 'tx')] if rxmode == "Tone": rxtone = TONES[_mem.rxtone] elif rxmode == "DTCS": rxtone = chirp_common.ALL_DTCS_CODES[self._get_dcs_index(_mem, 'rx')] rxpol = _mem.rxinv and "R" or "N" txpol = _mem.txinv and "R" or "N" chirp_common.split_tone_decode(mem, (txmode, txtone, txpol), (rxmode, rxtone, rxpol)) if _skp & bitpos: mem.skip = "S" mem.power = POWER_LEVELS[_mem.power] return mem def set_memory(self, mem): bitpos = (1 << (mem.number % 8)) bytepos = (mem.number / 8) _mem = self._memobj.memory[mem.number] _skp = self._memobj.skip_scan[bytepos] _usd = self._memobj.used_flags[bytepos] if mem.empty: _usd |= bitpos _mem.set_raw("\xFF" * 32) return _usd &= ~bitpos #if _mem.get_raw() == ("\xFF" * 32): if not mem.empty: LOG.debug("Initializing empty memory") _mem.set_raw("\x00" * 32) _mem.freq = mem.freq / 100 if mem.duplex == "off": _mem.duplex = DUPLEXES.index("") _mem.offset = 0 _mem.tx_off = True elif mem.duplex == "split": diff = mem.offset - mem.freq _mem.duplex = DUPLEXES.index("-") if diff < 0 else DUPLEXES.index("+") _mem.offset = abs(diff) / 100 else: _mem.offset = mem.offset / 100 _mem.duplex = DUPLEXES.index(mem.duplex) _mem.name = mem.name.ljust(6) _mem.channel_width = mem.mode == "FM" try: _mem.channel_width = MODES.index(mem.mode) except ValueError: _mem.channel_width = 0 ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = chirp_common.split_tone_encode(mem) _mem.txtmode = TMODES.index(txmode) _mem.rxtmode = TMODES.index(rxmode) if txmode == "Tone": _mem.txtone = TONES.index(txtone) elif txmode == "DTCS": self._set_dcs_index(_mem, 'tx', chirp_common.ALL_DTCS_CODES.index(txtone)) if rxmode == "Tone": _mem.rxtone = TONES.index(rxtone) elif rxmode == "DTCS": self._set_dcs_index(_mem, 'rx', chirp_common.ALL_DTCS_CODES.index(rxtone)) _mem.txinv = txpol == "R" _mem.rxinv = rxpol == "R" if mem.skip: _skp |= bitpos else: _skp &= ~bitpos if mem.power: _mem.power = POWER_LEVELS.index(mem.power) else: _mem.power = 0 def get_settings(self): _settings = self._memobj.settings basic = RadioSettingGroup("basic", "Basic") settings = RadioSettings(basic) display = ["Frequency", "Channel", "Name"] rs = RadioSetting("display", "Display", RadioSettingValueList(display, display[_settings.display])) basic.append(rs) apo = ["Off", "30 Min", "1 Hour", "2 Hours"] rs = RadioSetting("apo", "Automatic Power Off", RadioSettingValueList(apo, apo[_settings.apo])) basic.append(rs) return settings def set_settings(self, settings): _settings = self._memobj.settings for element in settings: if not isinstance(element, RadioSetting): self.set_settings(element) continue name = element.get_name() setattr(_settings, name, element.value) @classmethod def match_model(cls, filedata, filename): return cls._file_ident in filedata[0x10:0x20] @directory.register class AnyToneOBLTR8RRadio(AnyToneTERMN8RRadio): """AnyTone OBLTR8R""" VENDOR = "AnyTone" MODEL = "OBLTR8R" _file_ident = "OBLTR8R" @directory.register class AnyToneNSTIG8RRadio(AnyToneTERMN8RRadio): """AnyTone NSTIG8R""" VENDOR = "AnyTone" MODEL = "NSTIG8R" _file_ident = "NSTIG8R"