Project

General

Profile

New Model #10871 ยป retevis_ra87_v0.1.py

1st draft - per-channel settings only - Jim Unroe, 01/11/2024 03:12 PM

 
# Copyright 2024 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 struct
import logging

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

LOG = logging.getLogger(__name__)

MEM_FORMAT = """
struct mem {
bbcd rxfreq[5]; // RX Frequency // 0-4
u8 step:4, // STEP // 5
unk1:2,
duplex:2; // Duplex 0: Simplex, 1: Plus, 2: Minus
u8 unk2:3, // 6
reverse:1, // Reverse
unk3:4;

ul16 rxdtcs_pol:1, // 7-8
unk4:1,
is_rxdigtone:1,
unk5:1,
rxtone:12;
ul16 txdtcs_pol:1, // 9-A
unk6:1,
is_txdigtone:1,
unk7:1,
txtone:12;

u8 unknown3; // B
bbcd offset[2]; // Offset 00.05 - 69.95 MHz // C-D
u8 unknown4; // E
u8 unk8:7, // F
narrow:1; // FM Narrow

u8 unk9:3, // // 0
beatshift:1, // Beat Shift
unk10:4;
bbcd txfreq[4]; // 1-4
u8 unk11:4, // 5
txstep:4; // TX STEP
u8 unk12:1, // 6
txpower:3, // Power
unk13:4;
u8 unknown5; // 7
u8 compand:1, // Compand // 8
scramble:3, // Scramble
unk14:4;
char name[6]; // Name // 9-E
u8 hide:1, // Channel Hide 0: Show, 1: Hide // F
unk15:6,
skip:1; // Lockout
};

// #seekto 0x0000;
struct mem left_memory[100];

#seekto 0x0D40;
struct mem right_memory[100];

#seekto 0x1CC0;
struct {
u8 unknown_1cc0[7]; // 0x1CC0-0x1CC6
u8 unk1:4, // 0x1CC7
sql:4; // Squelch
u8 unknown_1cc8[35]; // 0x1CC8-0x1CFA
u8 unk2:4, // 0x1CEB
wfclr:4; // Background Color - Wait
u8 unk3:4, // 0x1CEC
rxclr:4; // Background Color - RX
u8 unk4:4, // 0x1CED
txclr:4; // Background Color - TX
} settings;
"""

CMD_ACK = b"\x06"

TXPOWER_LOW = 0x00
TXPOWER_LOW2 = 0x01
TXPOWER_LOW3 = 0x02
TXPOWER_MID = 0x03
TXPOWER_HIGH = 0x04

DUPLEX_NOSPLIT = 0x00
DUPLEX_POSSPLIT = 0x01
DUPLEX_NEGSPLIT = 0x02

DUPLEX = ["", "+", "-"]
TUNING_STEPS = [5., 6.25, 10., 12.5, 15., 20., 25., 30., 50., 100.]

SCRAMBLE_LIST = ["Off", "Freq 1", "Freq 2", "Freq 3", "Freq 4", "Freq 5",
"Freq 6", "User"]
SQUELCH_LIST = ["Off", "S0", "S1", "S2", "S3", "S4", "S5", "S6", "S7"]


def _enter_programming_mode_download(radio):
serial = radio.pipe

_magic = radio._magic

try:
serial.write(_magic)
if radio._echo:
serial.read(len(_magic)) # Chew the echo
ack = serial.read(1)
except Exception:
raise errors.RadioError("Error communicating with radio")

if not ack:
raise errors.RadioError("No response from radio")
elif ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")

try:
serial.write(b"\x02")
if radio._echo:
serial.read(1) # Chew the echo
ident = serial.read(8)
except Exception:
raise errors.RadioError("Error communicating with radio")

# check if ident is OK
for fp in radio._fingerprint:
if ident.startswith(fp):
break
else:
LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
raise errors.RadioError("Radio identification failed.")

try:
serial.write(CMD_ACK)
if radio._echo:
serial.read(1) # Chew the echo
ack = serial.read(1)
except Exception:
raise errors.RadioError("Error communicating with radio")

# check if ident is OK
for fp in radio._fingerprint:
if ident.startswith(fp):
break
else:
LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
raise errors.RadioError("Radio identification failed.")

try:
serial.write(CMD_ACK)
serial.read(1) # Chew the echo
ack = serial.read(1)
except Exception:
raise errors.RadioError("Error communicating with radio")

if ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")


def _enter_programming_mode_upload(radio):
serial = radio.pipe

_magic = radio._magic

try:
serial.write(_magic)
if radio._echo:
serial.read(len(_magic)) # Chew the echo
ack = serial.read(1)
except Exception:
raise errors.RadioError("Error communicating with radio")

if not ack:
raise errors.RadioError("No response from radio")
elif ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")

try:
serial.write(b"\x52\x1F\x05\x01")
if radio._echo:
serial.read(4) # Chew the echo
ident = serial.read(5)
except Exception:
raise errors.RadioError("Error communicating with radio")

if ident != b"\x57\x1F\x05\x01\xA5":
LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
raise errors.RadioError("Radio identification failed.")

try:
serial.write(CMD_ACK)
if radio._echo:
serial.read(1) # Chew the echo
ack = serial.read(1)
except Exception:
raise errors.RadioError("Error communicating with radio")

if ack != CMD_ACK:
raise errors.RadioError("Radio refused to enter programming mode")


def _exit_programming_mode(radio):
serial = radio.pipe
try:
serial.write(radio.CMD_EXIT)
if radio._echo:
serial.read(7) # Chew the echo
except Exception:
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"W" + cmd[1:]
LOG.debug("Reading block %04x..." % (block_addr))

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

block_data = response[4:]

except Exception:
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 radio._echo:
serial.read(4 + len(data)) # Chew the echo
if serial.read(1) != CMD_ACK:
raise Exception("No ACK")
except Exception:
raise errors.RadioError("Failed to send block "
"to radio at %04x" % block_addr)


def do_download(radio):
LOG.debug("download")
_enter_programming_mode_download(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))

return data


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

_enter_programming_mode_upload(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):
status.cur = addr + radio.BLOCK_SIZE
radio.status_fn(status)
_write_block(radio, addr, radio.BLOCK_SIZE)

_exit_programming_mode(radio)


class RA87StyleRadio(chirp_common.CloneModeRadio):
"""Retevis RA87"""
VENDOR = "Retevis"
NEEDS_COMPAT_SERIAL = False
BAUD_RATE = 9600
BLOCK_SIZE = 0x40
CMD_EXIT = b"EZ" + b"\xA5" + b"2#E" + b"\xF2"
NAME_LENGTH = 6

VALID_BANDS = [(400000000, 480000000)]

_magic = b"PROGRAM"
_fingerprint = [b"\xFF\xFF\xFF\xFF\xFF\xA5\x2C\xFF"]
_upper = 99
_gmrs = True
_echo = True

_ranges = [
(0x0000, 0x2000),
]
_memsize = 0x2000

def get_features(self):
rf = chirp_common.RadioFeatures()
rf.can_odd_split = True
rf.has_bank = False
rf.has_ctone = True
rf.has_cross = True
rf.has_name = True
rf.has_sub_devices = self.VARIANT == ""
rf.has_tuning_step = False
rf.has_rx_dtcs = True
rf.has_settings = False
rf.memory_bounds = (0, self._upper)
rf.valid_bands = self.VALID_BANDS
rf.valid_cross_modes = [
"Tone->Tone",
"DTCS->",
"->DTCS",
"Tone->DTCS",
"DTCS->Tone",
"->Tone",
"DTCS->DTCS"]
rf.valid_duplexes = DUPLEX + ["split"]
rf.valid_power_levels = self.POWER_LEVELS
rf.valid_modes = ["NFM", "FM"] # 12.5 kHz, 25 kHz.
rf.valid_name_length = self.NAME_LENGTH
rf.valid_skips = ["", "S"]
rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
rf.valid_tuning_steps = TUNING_STEPS
return rf

def get_sub_devices(self):
return [RA87RadioLeft(self._mmap), RA87RadioRight(self._mmap)]

def process_mmap(self):
"""Process the mem map into the mem object"""
self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)

def sync_in(self):
try:
data = do_download(self)
self._mmap = memmap.MemoryMapBytes(data)
except errors.RadioError:
raise
except Exception as e:
LOG.exception('General failure')
raise errors.RadioError('Failed to download from radio: %s' % e)
finally:
_exit_programming_mode(self)
self.process_mmap()

def sync_out(self):
try:
do_upload(self)
except errors.RadioError:
raise
except Exception as e:
LOG.exception('General failure')
raise errors.RadioError('Failed to upload to radio: %s' % e)
finally:
_exit_programming_mode(self)

def get_raw_memory(self, number):
return repr(self._memobj.memory[number - 1])

def _get_dcs(self, val):
return int(str(val)[2:-16])

def _set_dcs(self, val):
return int(str(val), 16)

def _memory_obj(self, suffix=""):
return getattr(self._memobj, "%s_memory%s" % (self._vfo, suffix))

def get_memory(self, number):
_mem = self._memory_obj()[number]

mem = chirp_common.Memory()

mem.number = number

if _mem.rxfreq.get_raw() == b"\xFF\xFF\xFF\xFF\xFF":
mem.freq = 0
mem.empty = True
return mem

mem.freq = int(_mem.rxfreq)

# We'll consider any blank (i.e. 0 MHz frequency) to be empty
if mem.freq == 0:
mem.empty = True
return mem

if int(_mem.txfreq) != 0: # DUPLEX_ODDSPLIT
mem.duplex = "split"
mem.offset = int(_mem.txfreq) * 10
elif _mem.duplex == DUPLEX_POSSPLIT:
mem.duplex = '+'
mem.offset = int(_mem.offset) * 1000
elif _mem.duplex == DUPLEX_NEGSPLIT:
mem.duplex = '-'
mem.offset = int(_mem.offset) * 1000
elif _mem.duplex == DUPLEX_NOSPLIT:
mem.duplex = ''
mem.offset = 0
else:
LOG.error('%s: get_mem: unhandled duplex: %02x' %
(mem.name, _mem.duplex))

mem.tuning_step = TUNING_STEPS[_mem.step]

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

mem.skip = _mem.skip and "S" or ""

mem.name = str(_mem.name).strip("\xFF")

dtcs_pol = ["N", "N"]

if _mem.rxtone == 0xFFF:
rxmode = ""
elif _mem.rxtone == 0x800 and _mem.is_rxdigtone == 0:
rxmode = ""
elif _mem.is_rxdigtone == 0:
# CTCSS
rxmode = "Tone"
mem.ctone = int(_mem.rxtone) / 10.0
else:
# Digital
rxmode = "DTCS"
mem.rx_dtcs = self._get_dcs(_mem.rxtone)
if _mem.rxdtcs_pol == 1:
dtcs_pol[1] = "R"

if _mem.txtone == 0xFFF:
txmode = ""
elif _mem.txtone == 0x08 and _mem.is_txdigtone == 0:
txmode = ""
elif _mem.is_txdigtone == 0:
# CTCSS
txmode = "Tone"
mem.rtone = int(_mem.txtone) / 10.0
else:
# Digital
txmode = "DTCS"
mem.dtcs = self._get_dcs(_mem.txtone)
if _mem.txdtcs_pol == 1:
dtcs_pol[0] = "R"

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)

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

mem.extra = RadioSettingGroup("Extra", "extra")
rs = RadioSetting("beatshift", "Beat Shift",
RadioSettingValueBoolean(_mem.beatshift))
mem.extra.append(rs)
rs = RadioSetting("compand", "Compand",
RadioSettingValueBoolean(_mem.compand))
mem.extra.append(rs)
scramble_options = ['Off', 'Freq 1', 'Freq 2', 'Freq 3', 'Freq 4',
'Freq 5', 'Freq 6', 'User']
scramble_option = scramble_options[_mem.scramble]
rs = RadioSetting("scramble", "Scramble",
RadioSettingValueList(scramble_options,
scramble_option))
mem.extra.append(rs)
rs = RadioSetting("hide", "Hide Channel",
RadioSettingValueBoolean(_mem.hide))
mem.extra.append(rs)
rs = RadioSetting("reverse", "Reverse",
RadioSettingValueBoolean(_mem.reverse))
mem.extra.append(rs)

return mem

def set_memory(self, mem):
# Get a low-level memory object mapped to the image
_mem = self._memory_obj()[mem.number]

if mem.empty:
_mem.set_raw(b"\xFF" * 31 + b"\x80")

return

_mem.set_raw(b"\x00" * 25 + b"\xFF" * 6 + b"\x00")

_mem.rxfreq = mem.freq

if mem.duplex == 'split':
_mem.txfreq = mem.offset / 10
elif mem.duplex == '+':
_mem.duplex = DUPLEX_POSSPLIT
_mem.offset = mem.offset / 1000
elif mem.duplex == '-':
_mem.duplex = DUPLEX_NEGSPLIT
_mem.offset = mem.offset / 1000
elif mem.duplex == '':
_mem.duplex = DUPLEX_NOSPLIT
else:
LOG.error('%s: set_mem: unhandled duplex: %s' %
(mem.name, mem.duplex))

rxmode = ""
txmode = ""

if mem.tmode == "Tone":
txmode = "Tone"
elif mem.tmode == "TSQL":
rxmode = "Tone"
txmode = "TSQL"
elif mem.tmode == "DTCS":
rxmode = "DTCSSQL"
txmode = "DTCS"
elif mem.tmode == "Cross":
txmode, rxmode = mem.cross_mode.split("->", 1)

if rxmode == "":
_mem.rxdtcs_pol = 0
_mem.is_rxdigtone = 0
_mem.rxtone = 0x800
elif rxmode == "Tone":
_mem.rxdtcs_pol = 0
_mem.is_rxdigtone = 0
_mem.rxtone = int(mem.ctone * 10)
elif rxmode == "DTCSSQL":
_mem.rxdtcs_pol = 1 if mem.dtcs_polarity[1] == "R" else 0
_mem.is_rxdigtone = 1
_mem.rxtone = self._set_dcs(mem.dtcs)
elif rxmode == "DTCS":
_mem.rxdtcs_pol = 1 if mem.dtcs_polarity[1] == "R" else 0
_mem.is_rxdigtone = 1
_mem.rxtone = self._set_dcs(mem.rx_dtcs)

if txmode == "":
_mem.txdtcs_pol = 0
_mem.is_txdigtone = 0
_mem.txtone = 0x08
elif txmode == "Tone":
_mem.txdtcs_pol = 0
_mem.is_txdigtone = 0
_mem.txtone = int(mem.rtone * 10)
elif txmode == "TSQL":
_mem.txdtcs_pol = 0
_mem.is_txdigtone = 0
_mem.txtone = int(mem.ctone * 10)
elif txmode == "DTCS":
_mem.txdtcs_pol = 1 if mem.dtcs_polarity[0] == "R" else 0
_mem.is_txdigtone = 1
_mem.txtone = self._set_dcs(mem.dtcs)

# name TAG of the channel
_mem.name = mem.name.rstrip().ljust(6, "\xFF")

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

_mem.narrow = 'N' in mem.mode
_mem.skip = mem.skip == "S"
_mem.step = TUNING_STEPS.index(mem.tuning_step)

for setting in mem.extra:
setattr(_mem, setting.get_name(), int(setting.value))

@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 RA87Radio(RA87StyleRadio):
"""Retevis RA87"""
MODEL = "RA87"

POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=5.00),
chirp_common.PowerLevel("Low2", watts=10.00),
chirp_common.PowerLevel("Low3", watts=15.00),
chirp_common.PowerLevel("Mid", watts=20.00),
chirp_common.PowerLevel("High", watts=40.00)]


class RA87RadioLeft(RA87Radio):
"""Retevis RA87 Left VFO subdevice"""
VARIANT = "Left"
_vfo = "left"


class RA87RadioRight(RA87Radio):
"""Retevis RA87 Right VFO subdevice"""
VARIANT = "Right"
_vfo = "right"
    (1-1/1)