Skip to content

Commit

Permalink
fix typos and other logic errors caught by review
Browse files Browse the repository at this point in the history
  • Loading branch information
Patronics committed Dec 14, 2024
1 parent d195c84 commit f22a50f
Showing 1 changed file with 58 additions and 82 deletions.
140 changes: 58 additions & 82 deletions chirp/drivers/tk690.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,6 @@
chirp_common.PowerLevel("Low", watts=5)]
MODES = ["NFM", "FM"] # 12.5 / 25 Khz
VALID_CHARS = chirp_common.CHARSET_UPPER_NUMERIC + "()/\\*@-+,.#_"
NAME_CHARS = 8
SKIP_VALUES = ["S", ""]
TONES = chirp_common.TONES
DTCS_CODES = chirp_common.DTCS_CODES
Expand All @@ -189,7 +188,11 @@

def _close_radio(radio):
"""Get the radio out of program mode"""
radio.pipe.write(b"E")
try:
radio.pipe.write(b"E")
except Exception:
LOG.debug("Failed to close radio, serial error")
raise errors.RadioError("Serial Connection Error while closing radio")


def _checksum(data):
Expand Down Expand Up @@ -228,7 +231,6 @@ def _handshake(radio, msg="", full=True):
ack = radio.pipe.read(1)
# check ACK
if ack != ACK_CMD:
_close_radio(radio)
mesg = "Handshake failed, got ack: '0x%02x': %s" % (ord(ack), msg)
LOG.debug(mesg)
raise errors.RadioError("Radio failed to acknowledge our command")
Expand All @@ -254,7 +256,6 @@ def _recvl(radio):
(rcs, ccs)
LOG.error(msg)
_handshake(radio)
_close_radio(radio)
raise errors.RadioError("Error communicating with radio")

_handshake(radio, "After checksum in Low Mem")
Expand All @@ -280,7 +281,6 @@ def _recvh(radio):
_handshake(radio, "After data in High Mem")
return data
else:
_close_radio(radio)
raise errors.RadioError("Unexpected communication from radio")


Expand Down Expand Up @@ -313,17 +313,12 @@ def _open_radio(radio):
radio.pipe.write(b"\x02\x0F")
rid = radio.pipe.read(10)

if not rid.startswith(bytes(radio.TYPE, 'utf-8')):
if not rid.startswith(radio.TYPE):
# bad response, properly close the radio before exception
_close_radio(radio)

# DEBUG
LOG.debug("Incorrect model ID:")
LOG.debug(util.hexprint(rid))

raise errors.RadioError(
"Incorrect model ID, got %s, it not contains %s" %
(rid.strip(b"\xff"), bytes(radio.TYPE, 'utf-8')))
LOG.debug("expected %s" % radio.TYPE)
raise errors.RadioError("Radio Model Incorrect")

# DEBUG
LOG.debug("Full radio identity string is:\n%s" % util.hexprint(rid))
Expand Down Expand Up @@ -397,7 +392,6 @@ def do_download(radio):
status.msg = "Cloning from Head (High mem)..."
radio.status_fn(status)

_close_radio(radio)
return memmap.MemoryMapBytes(data)


Expand Down Expand Up @@ -492,8 +486,6 @@ def do_upload(radio):
status.msg = "Cloning to Head MCU (high mem)..."
radio.status_fn(status)

_close_radio(radio)


def model_match(cls, data, rid_index=0x03EE0):
"""Match the opened/downloaded image to the correct version"""
Expand Down Expand Up @@ -551,7 +543,7 @@ def get_memory_mappings(self, memory):
return [self.get_mappings()[index]]


class memBank(chirp_common.Bank):
class MemBank(chirp_common.Bank):
"""A bank model for kenwood"""
# Integral index of the bank, not to be confused with per-memory
# bank indexes
Expand All @@ -564,14 +556,14 @@ class Kenwoodx90(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
BAUD_RATE = 9600
VARIANT = ""
MODEL = ""
NAME_LENGTH = 6
_name_chars = 8
# others
_memsize = MEM_SIZE
_range = [136000000, 162000000]
_upper = 160
_banks = dict()
_banks = None
_num_banks = 160
_bclass = memBank
_bclass = MemBank
_kind = ""
FORMATS = [directory.register_format('Kenwood KPG-44D', '*.dat')]

Expand Down Expand Up @@ -624,7 +616,7 @@ def get_features(self):
rf.valid_skips = SKIP_VALUES
rf.valid_dtcs_codes = DTCS_CODES
rf.valid_bands = [self._range]
rf.valid_name_length = NAME_CHARS
rf.valid_name_length = self._name_chars
rf.memory_bounds = (1, self._upper)
return rf

Expand All @@ -634,10 +626,9 @@ def _fill(self, offset, data):
self._mmap[offset + addr] = data[addr]

def _prep_data(self):
"""Prepare the areas in the memmap to do a consistend write
it has to make an update on the x1600 area with banks and channel
info; other in the x1000 with banks and channel counts
and a last one in x7000 with flog data"""
"""Prepare the areas in the memmap to do a consistent write
it has to update the x1600 area with banks and channel
info; other in the x1000 with banks and channel counts"""
rchs = 0
data = dict()

Expand All @@ -647,11 +638,8 @@ def _prep_data(self):
bnumb = int(mem.bnumb)
bank = int(mem.bank)
if bnumb != 255 and (bank != 255 and bank != 0):
try:
data[bank].append(ch)
except KeyError:
data[bank] = list()
data[bank].append(ch)
data.setdefault(bank, list())
data[bank].append(ch)
data[bank].sort()
# counting the real channels
rchs = rchs + 1
Expand All @@ -665,7 +653,7 @@ def _prep_data(self):
fdata = b""

for k, v in data.iteritems():
# posible bad data
# possible bad data
if k == 0:
k = 1
raise errors.InvalidValueError(
Expand All @@ -691,56 +679,42 @@ def _prep_data(self):
line += b"\xff" * 14
bdata += line

# fill to match a full 256 bytes block
# fill remainder of our current block with default values
bdata += (256 - (len(bdata)) % 256) * b"\xFF"

# fill to match the whole area
# fill remaining empty blocks
bdata += (16 - len(bdata) / 256) * EMPTY_BLOCK

# updating the data in the memmap [x1000]
self._fill(0x1000, bdata)

# DTMF id for each channel, 5 bytes lbcd at x7000
# ############## TODO ###################
fldata = "\x00\xf0\xff\xff\xff" * self._chs_progs + \
"\xff" * (5 * (self._upper - self._chs_progs))

# write it
# updating the data in the memmap [x7000]
self._fill(0x7000, fldata)

def _set_variant(self):
"""Select and set the correct variables for the class acording
to the correct variant of the radio, and other runtime data"""
"""Select and set the correct variables for the class according
to the identified variant of the radio, and other runtime data"""
rid = _get_rid(self.get_mmap())

# indentify the radio variant and set the enviroment to it's values
self._banks = dict()
# identify the radio variant and set the environment to correct values
try:
self._upper, low, high, self._kind = self.VARIANTS[rid]
self._range = [low * 1000000, high * 1000000]

# put the VARIANT in the class, clean the model / CHs / Type
# in the same layout as the KPG program
self._VARIANT = self.MODEL + " [" + str(self._upper) + "CH]: "
self._VARIANT += self._kind + ", " + \
str(self._range[0]/1000000) + "-"
self._VARIANT += str(self._range[1]/1000000) + " Mhz"

except KeyError:
# LOG.debug("Wrong Kenwood radio, ID or unknown variant")
# LOG.debug(util.hexprint(rid))
LOG.debug("Wrong Kenwood radio, ID or unknown variant")
LOG.debug(util.hexprint(rid))
raise errors.RadioError(
"Wrong Kenwood radio, ID or unknown variant, see LOG output.")

global NAME_CHARS
# the channel name length is a variable in the radio settings
NAME_CHARS = int(self._memobj.settings.ch_name_length)
self._name_chars = int(self._memobj.settings.ch_name_length)

def sync_in(self):
"""Do a download of the radio eeprom"""
self._mmap = do_download(self)
try:
self._mmap = do_download(self)
finally:
_close_radio(self)
self.process_mmap()
self._datHeaderMmap = None
self._dat_header_mmap = None

def sync_out(self):
"""Do an upload to the radio eeprom"""
Expand All @@ -750,6 +724,8 @@ def sync_out(self):
raise
except Exception as e:
raise errors.RadioError("Failed to communicate with radio: %s" % e)
finally:
_close_radio(self)

def _get_bank_struct(self):
"""Parse the bank data in the mem into the self.bank variable"""
Expand Down Expand Up @@ -785,21 +761,20 @@ def process_mmap(self):
# load the memobj
self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)

# to ser the vars on the class to the correct ones
# set the vars on the class to the correct ones
self._set_variant()

# load the bank data
self._get_bank_struct()

def load_mmap(self, filename):
# LOG.info('loading'+filename)
if filename.lower().endswith('.dat'):
with open(filename, "rb") as f:
self._datHeaderMmap = memmap.MemoryMapBytes(f.read(0x40))
self._dat_header_mmap = memmap.MemoryMapBytes(f.read(0x40))
self._mmap = memmap.MemoryMapBytes(f.read())
self.process_mmap()
else:
self._datHeaderMmap = None
self._dat_header_mmap = None
chirp_common.CloneModeRadio.load_mmap(self, filename)

def save_mmap(self, filename):
Expand All @@ -812,17 +787,18 @@ def save_mmap(self, filename):
chirp_common.CloneModeRadio.save_mmap(self, filename)

def _prep_dat_header(self):
if self._datHeaderMmap is not None: # if dat header imported with file
return self._datHeaderMmap
# if dat header imported with file
if self._dat_header_mmap is not None:
return self._dat_header_mmap
# otherwise build our own header
datHeaderMap = memmap.MemoryMapBytes(bytes([255]*0x40))
dat_header_map = memmap.MemoryMapBytes(bytes([255]*0x40))
softwareName = self._mmap.get(0x3EDA, 6)
softwareVer = self._mmap.get(0x3EFB, 5)
rid = self._mmap.get(0x3EE0, 10)
datHeaderMap.set(0x00, softwareName)
datHeaderMap.set(0x0A, softwareVer)
datHeaderMap.set(0x0F, rid)
return datHeaderMap
dat_header_map.set(0x00, softwareName)
dat_header_map.set(0x0A, softwareVer)
dat_header_map.set(0x0F, rid)
return dat_header_map

def get_raw_memory(self, number):
"""Return a raw representation of the memory object, which
Expand Down Expand Up @@ -893,7 +869,7 @@ def get_memory(self, number):
mem.offset = 0

# name TAG of the channel
mem.name = str(_chs_names.name).rstrip(" ")[:NAME_CHARS + 1]
mem.name = str(_chs_names.name).rstrip(" ")[:self._name_chars + 1]

# power (0 = high, 1 = low)
mem.power = POWER_LEVELS[int(_mem.power)]
Expand Down Expand Up @@ -1058,7 +1034,7 @@ def _set_bank(self, loc, bank=0):
if b == bank:
return

# if another bank already asigned, delete from old location
# if another bank already assigned, delete from old location
if b is not None:
self._del_channel_from_bank(loc, b)

Expand Down Expand Up @@ -1100,7 +1076,7 @@ def _update_bank_memmap(self):
continue

# channel index inside the bank, starting at 1
# aka channel in group index
# aka channel group index
cgi = 1
for channel in range(0, len(self._banks[bank])):
# update bb
Expand Down Expand Up @@ -1175,10 +1151,10 @@ def set_settings(self, settings):


@directory.register
class TK690_Radios(Kenwoodx90):
class TK690Radio(Kenwoodx90):
"""Kenwood TK-690 """
MODEL = "TK-690"
TYPE = "M0690"
TYPE = b"M0690"
VARIANTS = {
b"M0690\x01": (160, 28, 37, "K"), # see note below
b"M0690\x02": (160, 35, 43, "K2"),
Expand All @@ -1187,21 +1163,21 @@ class TK690_Radios(Kenwoodx90):


@directory.register
class TK790_Radios(Kenwoodx90):
class TK790Radio(Kenwoodx90):
"""Kenwood TK-790 K/K2"""
MODEL = "TK-790"
TYPE = "M0790"
TYPE = b"M0790"
VARIANTS = {
b"M0790\x04": (160, 144, 174, "K"), # see note below
b"M0790\x05": (160, 136, 156, "K2")
}


@directory.register
class TK890_Radios(Kenwoodx90):
class TK890Radio(Kenwoodx90):
"""Kenwood TK-890 """
MODEL = "TK-890"
TYPE = "M0890"
TYPE = b"M0890"
VARIANTS = {
b"M0890\x06": (160, 450, 490, "K"),
b"M0890\x07": (160, 480, 512, "K2"),
Expand All @@ -1210,10 +1186,10 @@ class TK890_Radios(Kenwoodx90):
}

# Note:
# These radios originaly are constrained to some band segments but the
# original software doesn't care much about it, so in order to match a
# These radios originally are constrained to certain band segments but the
# original software doesn't care about it, so in order to match a
# feature many will miss from the factory software and to help
# the use of this radios in the ham bands I'm expanding the range
# the use of this radios in the ham bands we expanded the range
# of the "K" version of the TK-790 from 148 to 144, as well as the
# range of the TK-690 "F1" (from 29.7 to 28) and "F3" (from 50 to 54)
# versions (note that F3 also needs physical modifications for use with
Expand Down

0 comments on commit f22a50f

Please sign in to comment.