Project

General

Profile

New Model #10354 » mml_jc_8810-v0.1.py

Test driver. Download only. - Jim Unroe, 03/27/2023 05:45 PM

 
# Copyright 2021-2022 Jim Unroe <rock.unroe@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import logging
import os
import struct
import time

from chirp import (
bitwise,
chirp_common,
directory,
errors,
memmap,
util,
)
from chirp.settings import (
RadioSetting,
RadioSettingGroup,
RadioSettings,
RadioSettingValueBoolean,
RadioSettingValueFloat,
RadioSettingValueInteger,
RadioSettingValueList,
RadioSettingValueString,
)

LOG = logging.getLogger(__name__)

MEM_FORMAT = """
#seekto 0x0000;
struct {
lbcd rxfreq[4]; // 0-3 /
lbcd txfreq[4]; // 4-7 /
ul16 rxtone; // 8-9 /
ul16 txtone; // A-B /
u8 unknown1:4, // C
scode:4; // Signaling /
u8 unknown2:6, // D
pttid:2; // PTT-ID /
u8 unknown3:6, // E
txpower:2; // Power Level 0 = H, 1 = L, 2 = M /
u8 unknown4:1, // F
narrow:1, // Bandwidth 0 = Wide, 1 = Narrow /
encrypt:2, // Encrypt /
bcl:1, // BCL /
scan:1, // Scan 0 = Skip, 1 = Scan /
unknown5:1,
learning:1; // Learning /
lbcd code[3]; // Code /
u8 unknown6; //
char name[12]; // 12-character Alpha Tag /
} memory[256];
"""


CMD_ACK = b"\x06"

DTCS = tuple(sorted(chirp_common.DTCS_CODES + (645,)))

DTMF_CHARS = "0123456789 *#ABCD"

TXPOWER_HIGH = 0x00
TXPOWER_LOW = 0x01
TXPOWER_MID = 0x02

ENCRYPT_LIST = ["Off", "DCP1", "DCP2", "DCP3"]
PTTID_LIST = ["Off", "BOT", "EOT", "Both"]
PTTIDCODE_LIST = ["%s" % x for x in range(1, 16)]


def _enter_programming_mode(radio):
serial = radio.pipe

exito = False
for i in range(0, 5):
serial.write(radio._magic)
ack = serial.read(1)

try:
if ack == CMD_ACK:
exito = True
break
except errors.RadioError:
LOG.debug("Attempt #%s, failed, trying again" % i)
pass

# check if we had EXITO
if exito is False:
msg = "The radio did not accept program mode after five tries.\n"
msg += "Check you interface cable and power cycle your radio."
raise errors.RadioError(msg)

try:
serial.write(b"F")
ident = serial.read(8)
except errors.RadioError:
raise errors.RadioError("Error communicating with radio")

if not ident == radio._fingerprint:
LOG.debug(util.hexprint(ident))
raise errors.RadioError("Radio returned unknown identification string")


def _exit_programming_mode(radio):
serial = radio.pipe
try:
serial.write(b"E")
except errors.RadioError:
raise errors.RadioError("Radio refused to exit programming mode")


def _read_block(radio, block_addr, block_size):
serial = radio.pipe

cmd = struct.pack(">cHb", b'R', block_addr, block_size)
expectedresponse = b"R" + cmd[1:]
LOG.debug("Reading block %04x..." % (block_addr))

try:
serial.write(cmd)
response = serial.read(4 + block_size)
if response[:4] != expectedresponse:
raise Exception("Error reading block %04x." % (block_addr))

block_data = response[4:]
except errors.RadioError:
raise errors.RadioError("Failed to read block at %04x" % block_addr)

return block_data


def _write_block(radio, block_addr, block_size):
serial = radio.pipe

cmd = struct.pack(">cHb", b'W', block_addr, block_size)
data = radio.get_mmap()[block_addr:block_addr + block_size]

LOG.debug("Writing Data:")
LOG.debug(util.hexprint(cmd + data))

try:
serial.write(cmd + data)
if serial.read(1) != CMD_ACK:
raise Exception("No ACK")
except errors.RadioError:
raise errors.RadioError("Failed to send block "
"to radio at %04x" % block_addr)


def do_download(radio):
LOG.debug("download")
_enter_programming_mode(radio)

data = b""

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 = _read_block(radio, addr, radio.BLOCK_SIZE)
data += block

LOG.debug("Address: %04x" % addr)
LOG.debug(util.hexprint(block))

_exit_programming_mode(radio)

return memmap.MemoryMapBytes(data)


def do_upload(radio):
status = chirp_common.Status()
status.msg = "Uploading to radio"

_enter_programming_mode(radio)

status.cur = 0
status.max = radio._memsize

for start_addr, end_addr in radio._ranges:
for addr in range(start_addr, end_addr, radio.BLOCK_SIZE_UP):
status.cur = addr + radio.BLOCK_SIZE_UP
radio.status_fn(status)
_write_block(radio, addr, radio.BLOCK_SIZE_UP)

_exit_programming_mode(radio)


class JC8810base(chirp_common.CloneModeRadio):
"""MML JC-8810"""
VENDOR = "MML"
MODEL = "JC-8810base"
BAUD_RATE = 57600
NEEDS_COMPAT_SERIAL = False
BLOCK_SIZE = 0x40
BLOCK_SIZE_UP = 0x40

POWER_LEVELS = [chirp_common.PowerLevel("H", watts=10.00),
chirp_common.PowerLevel("M", watts=8.00),
chirp_common.PowerLevel("L", watts=4.00)]

_magic = b"PROGRAMJC81U"
_fingerprint = b"\x00\x00\x00\x26\x00\x20\xD8\x04"

_ranges = [
(0x0000, 0x2000),
(0x8000, 0x8040),
(0x9000, 0x9040),
(0xA000, 0xA140),
(0xB000, 0xB300)
]
_memsize = 0xB300
_valid_chars = chirp_common.CHARSET_ALPHANUMERIC + \
"`~!@#$%^&*()-=_+[]\\{}|;':\",./<>?"

def get_features(self):
rf = chirp_common.RadioFeatures()
rf.has_settings = False
rf.has_bank = False
rf.has_ctone = True
rf.has_cross = True
rf.has_rx_dtcs = True
rf.has_tuning_step = False
rf.can_odd_split = True
rf.has_name = True
rf.valid_name_length = 12
rf.valid_characters = self._valid_chars
rf.valid_skips = ["", "S"]
rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
"->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
rf.valid_power_levels = self.POWER_LEVELS
rf.valid_duplexes = ["", "-", "+", "split", "off"]
rf.valid_modes = ["FM", "NFM"] # 25 kHz, 12.5 KHz.
rf.valid_dtcs_codes = DTCS
rf.memory_bounds = (1, 256)
rf.valid_tuning_steps = [2.5, 5., 6.25, 10., 12.5, 20., 25., 50.]
rf.valid_bands = [(108000000, 136000000),
(136000000, 174000000),
(220000000, 260000000),
(350000000, 390000000),
(400000000, 520000000)]
return rf

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

def sync_in(self):
"""Download from radio"""
try:
data = do_download(self)
except errors.RadioError:
# Pass through any real errors we raise
raise
except Exception:
# 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 Exception:
# 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 _is_txinh(self, _mem):
raw_tx = ""
for i in range(0, 4):
raw_tx += _mem.txfreq[i].get_raw()
return raw_tx == "\xFF\xFF\xFF\xFF"

def get_memory(self, number):
_mem = self._memobj.memory[number - 1]

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

if _mem.get_raw()[0] == "\xff":
mem.empty = True
return mem

mem.freq = int(_mem.rxfreq) * 10

if self._is_txinh(_mem):
# TX freq not set
mem.duplex = "off"
mem.offset = 0
else:
# TX freq set
offset = (int(_mem.txfreq) * 10) - mem.freq
if offset != 0:
if offset > 0:
mem.duplex = "+"
mem.offset = 5000000
else:
mem.duplex = ""
mem.offset = 0

for char in _mem.name:
if str(char) == "\xFF":
char = " " # may have 0xFF mid-name
mem.name += str(char)
mem.name = mem.name.rstrip()

dtcs_pol = ["N", "N"]

if _mem.txtone in [0, 0xFFFF]:
txmode = ""
elif _mem.txtone >= 0x0258:
txmode = "Tone"
mem.rtone = int(_mem.txtone) / 10.0
elif _mem.txtone <= 0x0258:
txmode = "DTCS"
if _mem.txtone > 0x69:
index = _mem.txtone - 0x6A
dtcs_pol[0] = "R"
else:
index = _mem.txtone - 1
mem.dtcs = DTCS[index]
else:
LOG.warn("Bug: txtone is %04x" % _mem.txtone)

if _mem.rxtone in [0, 0xFFFF]:
rxmode = ""
elif _mem.rxtone >= 0x0258:
rxmode = "Tone"
mem.ctone = int(_mem.rxtone) / 10.0
elif _mem.rxtone <= 0x0258:
rxmode = "DTCS"
if _mem.rxtone >= 0x6A:
index = _mem.rxtone - 0x6A
dtcs_pol[1] = "R"
else:
index = _mem.rxtone - 1
mem.rx_dtcs = DTCS[index]
else:
LOG.warn("Bug: rxtone is %04x" % _mem.rxtone)

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

mem.dtcs_polarity = "".join(dtcs_pol)

if not _mem.scan:
mem.skip = "S"

_levels = self.POWER_LEVELS
if _mem.txpower == TXPOWER_HIGH:
mem.power = _levels[0]
elif _mem.txpower == TXPOWER_MID:
mem.power = _levels[1]
elif _mem.txpower == TXPOWER_LOW:
mem.power = _levels[2]
else:
LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
(mem.name, _mem.txpower))

mem.mode = _mem.narrow and "NFM" or "FM"

mem.extra = RadioSettingGroup("Extra", "extra")

# BCL (Busy Channel Lockout)
rs = RadioSettingValueBoolean(_mem.bcl)
rset = RadioSetting("bcl", "BCL", rs)
mem.extra.append(rset)

# PTT-ID
rs = RadioSettingValueList(PTTID_LIST, PTTID_LIST[_mem.pttid])
rset = RadioSetting("pttid", "PTT ID", rs)
mem.extra.append(rset)

# Signal (DTMF Encoder Group #)
rs = RadioSettingValueList(PTTIDCODE_LIST, PTTIDCODE_LIST[_mem.scode])
rset = RadioSetting("scode", "PTT ID Code", rs)
mem.extra.append(rset)

# # Encrypt
# rs = RadioSettingValueList(ENCRYPT_LIST, ENCRYPT_LIST[_mem.encrypt])
# rset = RadioSetting("encrypt", "Encrypt", rs)
# mem.extra.append(rset)

# # Learning
# rs = RadioSettingValueBoolean(_mem.learning)
# rset = RadioSetting("learning", "Learning", rs)
# mem.extra.append(rset)

# # CODE
# rs = RadioSettingValueInteger(0, 999999, _mem.code)
# rset = RadioSetting("code", "Code", rs)
# mem.extra.append(rset)

# # ANI
# rs = RadioSettingValueBoolean(_mem.ani)
# rset = RadioSetting("ani", "ANI", rs)
# mem.extra.append(rset)

return mem

def set_memory(self, mem):
_mem = self._memobj.memory[mem.number - 1]

if mem.empty:
_mem.set_raw("\xff" * 32)
return

_mem.set_raw("\x00" * 16 + "\xFF" * 16)

_mem.rxfreq = mem.freq / 10

if mem.duplex == "off":
for i in range(0, 4):
_mem.txfreq[i].set_raw("\xFF")
elif mem.duplex == "split":
_mem.txfreq = mem.offset / 10
elif mem.duplex == "+":
_mem.txfreq = (mem.freq + mem.offset) / 10
elif mem.duplex == "-":
_mem.txfreq = (mem.freq - mem.offset) / 10
else:
_mem.txfreq = mem.freq / 10

_namelength = self.get_features().valid_name_length
for i in range(_namelength):
try:
_mem.name[i] = mem.name[i]
except IndexError:
_mem.name[i] = "\xFF"

rxmode = txmode = ""
if mem.tmode == "Tone":
_mem.txtone = int(mem.rtone * 10)
_mem.rxtone = 0
elif mem.tmode == "TSQL":
_mem.txtone = int(mem.ctone * 10)
_mem.rxtone = int(mem.ctone * 10)
elif mem.tmode == "DTCS":
rxmode = txmode = "DTCS"
_mem.txtone = DTCS.index(mem.dtcs) + 1
_mem.rxtone = DTCS.index(mem.dtcs) + 1
elif mem.tmode == "Cross":
txmode, rxmode = mem.cross_mode.split("->", 1)
if txmode == "Tone":
_mem.txtone = int(mem.rtone * 10)
elif txmode == "DTCS":
_mem.txtone = DTCS.index(mem.dtcs) + 1
else:
_mem.txtone = 0
if rxmode == "Tone":
_mem.rxtone = int(mem.ctone * 10)
elif rxmode == "DTCS":
_mem.rxtone = DTCS.index(mem.rx_dtcs) + 1
else:
_mem.rxtone = 0
else:
_mem.rxtone = 0
_mem.txtone = 0

if txmode == "DTCS" and mem.dtcs_polarity[0] == "R":
_mem.txtone += 0x69
if rxmode == "DTCS" and mem.dtcs_polarity[1] == "R":
_mem.rxtone += 0x69

_mem.scan = mem.skip != "S"
_mem.narrow = mem.mode == "NFM"

_levels = self.POWER_LEVELS
if mem.power is None:
_mem.txpower = TXPOWER_HIGH
elif mem.power == _levels[0]:
_mem.txpower = TXPOWER_HIGH
elif mem.power == _levels[1]:
_mem.txpower = TXPOWER_MID
elif mem.power == _levels[2]:
_mem.txpower = TXPOWER_LOW
else:
LOG.error('%s: set_mem: unhandled power level: %s' %
(mem.name, mem.power))

for setting in mem.extra:
if setting.get_name() == "scramble_type":
setattr(_mem, setting.get_name(), int(setting.value) + 8)
setattr(_mem, "scramble_type2", int(setting.value) + 8)
else:
setattr(_mem, setting.get_name(), setting.value)

def set_settings(self, settings):
_settings = self._memobj.settings
for element in settings:
if not isinstance(element, RadioSetting):
self.set_settings(element)
continue
else:
try:
name = element.get_name()
if "." in name:
bits = name.split(".")
obj = self._memobj
for bit in bits[:-1]:
if "/" in bit:
bit, index = bit.split("/", 1)
index = int(index)
obj = getattr(obj, bit)[index]
else:
obj = getattr(obj, bit)
setting = bits[-1]
else:
obj = _settings
setting = element.get_name()

if element.has_apply_callback():
LOG.debug("Using apply callback")
element.run_apply_callback()
elif setting == "fmradio":
setattr(obj, setting, not int(element.value))
elif setting == "tot":
setattr(obj, setting, int(element.value) + 1)
elif element.value.get_mutable():
LOG.debug("Setting %s = %s" % (setting, element.value))
setattr(obj, setting, element.value)
except Exception as e:
LOG.debug(element.get_name(), e)
raise

@classmethod
def match_model(cls, filedata, filename):
# This radio has always been post-metadata, so never do
# old-school detection
return False


@directory.register
class RT470Radio(JC8810base):
"""Radtel RT-470"""
VENDOR = "Radtel"
MODEL = "RT-470"
(1-1/5)