Project

General

Profile

New Model #3363 » tk790.py

Tom Hayward, 02/20/2016 07:58 PM

 
# Copyright 2013 Tom Hayward <tom@tomh.us>
#
# 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 struct
import os

from chirp import chirp_common, directory, memmap, errors, util
from chirp import bitwise
from chirp.settings import RadioSettingGroup, RadioSetting
from chirp.settings import RadioSettingValueBoolean, RadioSettingValueList
from chirp.settings import RadioSettingValueString

MEM_FORMAT = """
#seekto 0x0040;
struct {
u8 unknown40[16];
u8 channel_name_max;
u8 group_name_max;
u8 unknown52[4];
u8 min_volume; // 0-31
u8 bcl_override;
u8 squelch; // 0-15
u8 unknown59[2];
u8 clear_to_transpond;
u8 unknown5c[4];
u8 unknown60[3];
u8 small_lcd_display; // [Off, Group, Channel]
u8 unknown64[4];
u8 unknown68[4];
u8 roll_over; // 0 == dead end
u8 off_hook_decode;
u8 off_hook_horn_alert;
u8 unknown6f;
u8 unknown70[8];
u8 horn_alert_backup; // Enabled: 0x00, Disabled: 0xFF
u8 horn_alert_logic_signal; // 1-30 sec, 0 is pulse, FF is "until reset"
u8 timed_power_off; // hours
u8 channel_tracking;
u8 unknown7c;
u8 ext_ptt_with_squelch_tail_eliminator;
u8 ext_ptt_with_mic_mute;
u8 ext_ptt_with_qt;
u8 unknown80[16];
} settings;

#seekto 0x0440;
struct {
u8 tot; // * 10 seconds, 30 sec increments
u8 tot_pre_alert; // seconds, off - 10, default 5
u8 tot_rekey_time; // seconds, off - 60, default off
u8 tot_reset_time; // seconds, off - 15, default off
u8 unknown[4];
} group_settings[160];
// end 0x0940

#seekto 0x14c0;
struct {
u8 start;
u8 length;
} group_boundary[160];
// end 0x1600

#seekto 0x1640;
struct {
u8 channel_number; // relative to group, 1-160
u8 channel_index; // memory[channel_index]
} group_membership[160];
// end 0x1780

#seekto 0x1840;
struct {
lbcd rx_freq[4];
lbcd tx_freq[4];
ul16 rx_tone;
ul16 tx_tone;
u8 unknown1:1,
lowpower:1,
beatshift:1,
bcl:1,
pttid:1,
signaling:3;
u8 unknown2:4,
scan:1,
wide:1,
unknown2b:2;
u8 unknown3;
u8 unknown4a:6,
companderoff:1,
unknown5b:1;
} memory[160];

#seekto 0x3e30;
char power_on_msg[14];

#seekto 0x3ec0;
struct {
char line[16];
} embedded_message[2];

#seekto 0x3f1a;
char kenwood_software[6];
char ident[5];

#seekto 0x3f3b;
char kenwood_software_ver[5];

#seekto 0x40e0;
struct {
char name[16];
} group_name[160];

struct {
char name[16];
} channel_name[160];

"""

POWER_LEVELS = [chirp_common.PowerLevel("High", watts=100),
chirp_common.PowerLevel("Low", watts=50)]
MODES = ["NFM", "FM"]
SIGNAL = ["", "DTMF", "2-Tone 1", "2-Tone 2", "2-Tone 3"]

def make_frame(cmd, unk, addr, data=""):
return struct.pack(">BBH", ord(cmd), ord(unk), addr) + data

def send(radio, frame):
print "%04i P>R: %s" % (len(frame), util.hexprint(frame))
radio.pipe.write(frame)

def recv(radio, readdata=True):
hdr = radio.pipe.read(4)
cmd, addr, length = struct.unpack(">BHB", hdr)
if readdata:
data = radio.pipe.read(length)
#print " P<R: %s" % util.hexprint(hdr + data)
if len(data) != length:
raise errors.RadioError("Radio sent %i bytes (expected %i)" % (
len(data), length))
else:
data = ""
send(radio, "\x06")
return addr, data

def do_ident(radio):
print "clear", util.hexprint(radio.pipe.read(2000), " ")
send(radio, "PROGRAM")
ack = radio.pipe.read(1)
if ack != "\x06":
raise errors.RadioError("Radio refused program mode")
send(radio, "\x02")
send(radio, "\x0F")
ident = radio.pipe.read(10)
print "ident:", ident
print "ident:", ident[:5]
if ident[:5] != radio._ident:
raise errors.RadioError("Incorrect model: %s, expected %s" % (
ident[:5], radio._ident))
print "Model: %s" % util.hexprint(ident)
send(radio, "\x06")
ack = radio.pipe.read(1)

def do_download(radio):
radio.pipe.setTimeout(1)
do_ident(radio)

data = "\xFF" * 0x40
for addr in range(0x380, 0x400):
send(radio, make_frame("R", "\x0F", addr))
cmd = radio.pipe.read(1)
if cmd == "W":
_data = radio.pipe.read(128)
print " P<R: %s" % util.hexprint(_data, " ")
data += _data
wtf = radio.pipe.read(1)
print " P<R: %s" % util.hexprint(wtf, " ")
elif cmd == "Z":
print " P<R: %s" % util.hexprint(radio.pipe.read(1))
data += "\xFF" * 128
else:
raise errors.RadioError("Unknown reply: %s" % util.hexprint(cmd))
send(radio, "\x06")
ack = radio.pipe.read(1)
if ack != "\x06":
raise errors.RadioError("Radio refused block at %04x" % addr)

status = chirp_common.Status()
status.cur = addr - 0x380
status.max = 0x0400 - 0x0380
status.msg = "Reading channels from radio"
radio.status_fn(status)

# FIXME: Download this data from radio
data += "\xFF" * 160

length = 0x20
for addr in range(0x0000, 0x1fe0, length):
send(radio, make_frame("S", "\x8F", addr, chr(length)))
cmd, _addr = struct.unpack(">BH", radio.pipe.read(3))
cmd = chr(cmd)
if addr != _addr:
raise errors.RadioError("Wrong addr in reply")
elif cmd == "X":
_data = radio.pipe.read(length)
data += _data
elif cmd == "[":
radio.pipe.read(1)
data += "\xFF" * length
else:
raise errors.RadioError("Unknown reply: %s" % util.hexprint(cmd))
send(radio, "\x06")
ack = radio.pipe.read(1)
if ack != "\x06":
raise errors.RadioError("Radio refused block at %04x" % addr)

status = chirp_common.Status()
status.cur = addr
status.max = 0x1fe0
status.msg = "Reading other stuff from radio"
radio.status_fn(status)

send(radio, "E")

return memmap.MemoryMap(data)

def do_upload(radio):
radio.pipe.setTimeout(1)
do_ident(radio)

for addr in range(0, 0x0400, 8):
eaddr = addr + 16
send(radio, make_frame("W", addr, 8, radio._mmap[eaddr:eaddr + 8]))
ack = radio.pipe.read(1)
if ack != "\x06":
raise errors.RadioError("Radio refused block at %04x" % addr)
send(radio, "\x06")

status = chirp_common.Status()
status.cur = addr
status.max = 0x0400
status.msg = "Cloning to radio"
radio.status_fn(status)

send(radio, "\x45")


class KenwoodTKx90Radio(chirp_common.CloneModeRadio):
"""Kenwood TK-x90"""
VENDOR = "Kenwood"
MODEL = "TK-x90"
BAUD_RATE = 9600

_memsize = 0x60E0

def get_features(self):
rf = chirp_common.RadioFeatures()
rf.has_settings = True
rf.has_cross = True
rf.has_bank = False
rf.has_tuning_step = False
rf.has_name = True
rf.has_rx_dtcs = True
rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
rf.valid_modes = MODES
rf.valid_power_levels = POWER_LEVELS
rf.valid_skips = ["", "S"]
rf.valid_duplexes = ["", "-", "+", "split", "off"]
rf.valid_bands = [self._range]
rf.memory_bounds = (1, self._upper)

rf.has_comment = True
return rf

def sync_in(self):
try:
self._mmap = do_download(self)
except errors.RadioError:
self.pipe.write("E")
raise
# except Exception, e:
# raise errors.RadioError("Failed to download from radio: %s" % e)
self.process_mmap()

def process_mmap(self):
self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)

def sync_out(self):
try:
do_upload(self)
except errors.RadioError:
self.pipe.write("E")
raise
except Exception, e:
raise errors.RadioError("Failed to upload to radio: %s" % e)

def get_raw_memory(self, number):
_group_member = self._memobj.group_membership[number - 1]
_num = _group_member.channel_index
return "\n".join([repr(_group_member),
repr(self._memobj.memory[_num]),
repr(self._memobj.channel_name[_num])])

def _get_tone(self, _mem, mem):
def _get_dcs(val):
code = int("%03o" % (val & 0x07FF))
pol = (val & 0x8000) and "R" or "N"
return code, pol
if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
tcode, tpol = _get_dcs(_mem.tx_tone)
mem.dtcs = tcode
txmode = "DTCS"
elif _mem.tx_tone != 0xFFFF:
mem.rtone = _mem.tx_tone / 10.0
txmode = "Tone"
else:
txmode = ""

if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
rcode, rpol = _get_dcs(_mem.rx_tone)
mem.rx_dtcs = rcode
rxmode = "DTCS"
elif _mem.rx_tone != 0xFFFF:
mem.ctone = _mem.rx_tone / 10.0
rxmode = "Tone"
else:
rxmode = ""

if txmode == "Tone" and not rxmode:
mem.tmode = "Tone"
elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
mem.tmode = "TSQL"
elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
mem.tmode = "DTCS"
elif rxmode or txmode:
mem.tmode = "Cross"
mem.cross_mode = "%s->%s" % (txmode, rxmode)

if mem.tmode == "DTCS":
mem.dtcs_polarity = "%s%s" % (tpol, rpol)

def _get_group(self, index):
"""Returns the group number for a given channel number"""
for i, group in enumerate(self._memobj.group_boundary, 1):
if group.start <= index and (group.start + group.length) >= index:
return i
raise ValueError("Channel index out of group range.")

def get_memory(self, number):
_group_member = self._memobj.group_membership[number - 1]
_num = _group_member.channel_index

mem = chirp_common.Memory()
mem.number = number

if _num == 0xFF:
mem.empty = True
return mem

_mem = self._memobj.memory[_num]

mem.name = str(self._memobj.channel_name[_num].name).rstrip()
group = self._get_group(number)
mem.comment = "%d %s %d" % (group,
str(self._memobj.group_name[group - 1].name).rstrip(),
_group_member.channel_number)

mem.freq = int(_mem.rx_freq) * 10
offset = (int(_mem.tx_freq) * 10) - mem.freq
if _mem.tx_freq.get_raw() == "\xFF" * 4:
mem.offset = 0
mem.duplex = "off"
elif offset < 0:
mem.offset = abs(offset)
mem.duplex = "-"
elif offset > 0:
mem.offset = offset
mem.duplex = "+"
else:
mem.offset = 0

self._get_tone(_mem, mem)
mem.power = POWER_LEVELS[_mem.lowpower]
mem.mode = MODES[_mem.wide]
mem.skip = not _mem.scan and "S" or ""

mem.extra = RadioSettingGroup("all", "All Settings")

bcl = RadioSetting("bcl", "Busy Channel Lockout",
RadioSettingValueBoolean(bool(_mem.bcl)))
mem.extra.append(bcl)

beat = RadioSetting("beatshift", "Beat Shift",
RadioSettingValueBoolean(bool(_mem.beatshift)))
mem.extra.append(beat)

pttid = RadioSetting("pttid", "PTT ID",
RadioSettingValueBoolean(bool(_mem.pttid)))
mem.extra.append(pttid)

signal = RadioSetting("signaling", "Signaling",
RadioSettingValueList(SIGNAL,
SIGNAL[_mem.signaling]))
mem.extra.append(signal)

return mem

def _set_tone(self, mem, _mem):
def _set_dcs(code, pol):
val = int("%i" % code, 8) + 0x2800
if pol == "R":
val += 0xA000
return val

if mem.tmode == "Cross":
tx_mode, rx_mode = mem.cross_mode.split("->")
elif mem.tmode == "Tone":
tx_mode = mem.tmode
rx_mode = None
else:
tx_mode = rx_mode = mem.tmode

if tx_mode == "DTCS":
_mem.tx_tone = mem.tmode != "DTCS" and \
_set_dcs(mem.dtcs, mem.dtcs_polarity[0]) or \
_set_dcs(mem.rx_dtcs, mem.dtcs_polarity[0])
elif tx_mode:
_mem.tx_tone = tx_mode == "Tone" and \
int(mem.rtone * 10) or int(mem.ctone * 10)
else:
_mem.tx_tone = 0xFFFF

if rx_mode == "DTCS":
_mem.rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
elif rx_mode:
_mem.rx_tone = int(mem.ctone * 10)
else:
_mem.rx_tone = 0xFFFF

if os.getenv("CHIRP_DEBUG"):
print "Set TX %s (%i) RX %s (%i)" % (tx_mode, _mem.tx_tone,
rx_mode, _mem.rx_tone)
def set_memory(self, mem):
_mem = self._memobj.memory[mem.number - 1]

if mem.empty:
_mem.set_raw("\xFF" * 16)
return

_mem.unknown3[0] = 0x07
_mem.unknown3[1] = 0x22
_mem.rx_freq = mem.freq / 10
if mem.duplex == "+":
_mem.tx_freq = (mem.freq + mem.offset) / 10
elif mem.duplex == "-":
_mem.tx_freq = (mem.freq - mem.offset) / 10
else:
_mem.tx_freq = mem.freq / 10

self._set_tone(mem, _mem)

_mem.highpower = mem.power == POWER_LEVELS[1]
_mem.wide = mem.mode == "FM"
_mem.scan = mem.skip != "S"

for setting in mem.extra:
if setting.get_name == "signaling":
if setting.value == "DTMF":
_mem.signaling = 0x03
else:
_mem.signaling = 0x00
else:
setattr(_mem, setting.get_name(), setting.value)

# def get_settings(self):
# _mem = self._memobj
# top = RadioSettingGroup("all", "All Settings")

# def _f(val):
# string = ""
# for char in str(val):
# if char == "\xFF":
# break
# string += char
# return string

# line1 = RadioSetting("messages.line1", "Message Line 1",
# RadioSettingValueString(0, 32,
# _f(_mem.messages.line1),
# autopad=False))
# top.append(line1)

# line2 = RadioSetting("messages.line2", "Message Line 2",
# RadioSettingValueString(0, 32,
# _f(_mem.messages.line2),
# autopad=False))
# top.append(line2)

# return top

# def set_settings(self, settings):
# for element in settings:
# 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 = _settings
# setting = element.get_name()

# if "line" in setting:
# value = str(element.value).ljust(32, "\xFF")
# else:
# value = element.value
# setattr(obj, setting, value)
@classmethod
def match_model(cls, filedata, filename):
model = filedata[0x3f20:0x3f25]
return model == cls._ident


@directory.register
class KenwoodTK790Radio(KenwoodTKx90Radio):
MODEL = "TK-790"
_ident = "M0790"
_range = (136000000, 174000000)
_upper = 160
(2-2/8)