Project

General

Profile

New Model #10865 » baofeng_uv17.py

Latest version also in pull request - Sander van der Wel, 11/24/2023 08:45 AM

 
# Copyright 2023:
# * Sander van der Wel, <svdwel@icloud.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

from chirp import chirp_common, directory, memmap
from chirp.settings import RadioSettingGroup, RadioSetting, \
RadioSettingValueBoolean, RadioSettingValueList, \
RadioSettings, RadioSettingValueString
import struct
from chirp.drivers import baofeng_common, baofeng_uv17Pro
from chirp import errors, util

LOG = logging.getLogger(__name__)

DTMF_CHARS = "0123456789 *#ABCD"
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 20.0, 25.0, 50.0]

LIST_AB = ["A", "B"]
LIST_BANDWIDTH = ["Wide", "Narrow"]
LIST_DTMFST = ["Off", "DT-ST", "ANI-ST", "DT+ANI"]
LIST_MODE = ["Name", "Frequency"]
LIST_OFF1TO9 = ["Off"] + list("123456789")
LIST_PONMSG = ["Full", "Message", "Voltage"]
LIST_PTTID = ["Off", "BOT", "EOT", "Both"]
LIST_SCODE = ["%s" % x for x in range(1, 16)]
LIST_SAVE = ["Off", "1:1", "1:2", "1:3", "1:4"]
LIST_TIMEOUT = ["Off"] + ["%s sec" % x for x in range(15, 615, 15)]
LIST_VOICE = ["Chinese", "English"]
LIST_BCKLIGHT_TIMEOUT = ["Always On"] + ["%s sec" % x for x in range(1, 11)]
LIST_SCANMODE = ["Time", "Carrier", "Search"]


def _make_read_frame(addr, length):
"""Pack the info in the header format"""
frame = _make_frame(b'\x52', addr, length)
# Return the data
return frame


def _make_frame(cmd, addr, length, data=""):
"""Pack the info in the header format"""
frame = struct.pack("<cH", cmd, addr) + struct.pack(">H", length)
# add the data if set
if len(data) != 0:
frame += data
# return the data
return frame


def _sendmagic(radio, magic, response_len):
baofeng_common._rawsend(radio, magic)
baofeng_common._rawrecv(radio, response_len)


def _do_ident(radio):
"""Put the radio in PROGRAM mode & identify it"""
# Flush input buffer
baofeng_common._clean_buffer(radio)

# Ident radio
magic = radio._ident
baofeng_common._rawsend(radio, magic)
ack = baofeng_common._rawrecv(radio, 8)

if not ack.startswith(radio._fingerprint):
if ack:
LOG.debug(repr(ack))
raise errors.RadioError("Radio did not respond as expected.")

return True


# Locations of memory may differ each time, so a mapping has to be made first
def _get_memory_map(radio):
# Get memory map
memory_map = []
for addr in range(0x1FFF, 0x10FFF, 0x1000):
frame = _make_frame(b"R", addr, 1)
baofeng_common._rawsend(radio, frame)
blocknr = ord(baofeng_common._rawrecv(radio, 6)[5:])
blocknr = (blocknr >> 4 & 0xf) * 10 + (blocknr & 0xf)
memory_map += [blocknr]
_sendmagic(radio, b"\x06", 1)
return memory_map


def _start_communication(radio):
for magic in radio._magics:
_sendmagic(radio, magic[0], magic[1])


def _download(radio):
"""Get the memory map"""

# Put radio in program mode and identify it
_do_ident(radio)

data = b""
# Start communication
_start_communication(radio)

# Get memory map
memory_map = _get_memory_map(radio)

# UI progress
status = chirp_common.Status()
status.cur = 0
status.max = radio.MEM_TOTAL // radio.BLOCK_SIZE
status.msg = "Cloning from radio..."
radio.status_fn(status)

for block_number in radio.BLOCK_ORDER:
block_index = memory_map.index(block_number) + 1
start_addr = block_index * 0x1000
for addr in range(start_addr, start_addr + 0x1000, radio.BLOCK_SIZE):
frame = _make_read_frame(addr, radio.BLOCK_SIZE)
# DEBUG
LOG.debug("Frame=" + util.hexprint(frame))

# Sending the read request
baofeng_common._rawsend(radio, frame)

# Now we read data
d = baofeng_common._rawrecv(radio, radio.BLOCK_SIZE + 5)

LOG.debug("Response Data= " + util.hexprint(d))

# Aggregate the data
data += d[5:]

# UI Update
status.cur = len(data) // radio.BLOCK_SIZE
status.msg = "Cloning from radio..."
radio.status_fn(status)

# ACK ACK
_sendmagic(radio, b"\x06", 1)
data += bytes(radio.MODEL, 'ascii')
return data


def _upload(radio):
"""Upload procedure"""
# Put radio in program mode and identify it
_do_ident(radio)

# Start communication
_start_communication(radio)

# Get memory map
memory_map = _get_memory_map(radio)

# UI progress
status = chirp_common.Status()
status.cur = 0
status.max = radio.WRITE_MEM_TOTAL // radio.BLOCK_SIZE
status.msg = "Cloning to radio..."
radio.status_fn(status)

for block_number in radio.BLOCK_ORDER:
# Choose a block number is memory map is corrupt
# This happens when te upload process is interrupted
if block_number not in memory_map:
memory_map[memory_map.index(165)] = block_number
block_index = memory_map.index(block_number) + 1
start_addr = block_index * 0x1000
data_start_addr = radio.BLOCK_ORDER.index(block_number) * 0x1000
for addr in range(start_addr, start_addr + 0x1000, radio.BLOCK_SIZE):

# sending the data
data_addr = data_start_addr + addr - start_addr
data = radio.get_mmap()[data_addr:data_addr + radio.BLOCK_SIZE]
frame = _make_frame(b"W", addr, radio.BLOCK_SIZE, data)
baofeng_common._rawsend(radio, frame)

# receiving the response
ack = baofeng_common._rawrecv(radio, 1)
if ack != b"\x06":
msg = "Bad ack writing block 0x%04x" % addr
raise errors.RadioError(msg)

# UI Update
status.cur = (data_addr) // radio.BLOCK_SIZE
status.msg = "Cloning to radio..."
radio.status_fn(status)


@directory.register
class UV17(baofeng_uv17Pro.UV17Pro):
"""Baofeng UV-17"""
VENDOR = "Baofeng"
MODEL = "UV-17"
NEEDS_COMPAT_SERIAL = False

BLOCK_ORDER = [16, 17, 18, 19, 24, 25, 26, 4, 6]

MEM_TOTAL = 0x9000
WRITE_MEM_TOTAL = 0x9000
BLOCK_SIZE = 0x40
BAUD_RATE = 57600
_ident = b"PSEARCH"
_magics = [[b"PASSSTA", 3], [b"SYSINFO", 1],
[b"\x56\x00\x00\x0A\x0D", 13], [b"\x06", 1],
[b"\x56\x00\x10\x0A\x0D", 13], [b"\x06", 1],
[b"\x56\x00\x20\x0A\x0D", 13], [b"\x06", 1],
[b"\x56\x00\x00\x00\x0A", 11], [b"\x06", 1],
[b"\xFF\xFF\xFF\xFF\x0C\x55\x56\x31\x35\x39\x39\x39", 1],
[b"\02", 8], [b"\x06", 1]]
_fingerprint = b"\x06" + b"UV15999"

_tri_band = False
POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1.00),
chirp_common.PowerLevel("High", watts=5.00)]

LENGTH_NAME = 11
VALID_BANDS = [baofeng_uv17Pro.UV17Pro._vhf_range,
baofeng_uv17Pro.UV17Pro._uhf_range]
SCODE_LIST = LIST_SCODE

MEM_FORMAT = """
#seekto 0x0030;
struct {
lbcd rxfreq[4];
lbcd txfreq[4];
u8 unused1:8;
ul16 rxtone;
ul16 txtone;
u8 unknown1:1,
bcl:1,
pttid:2,
unknown2:1,
wide:1,
lowpower:1,
unknown:1;
u8 scode:4,
unknown3:3,
scan:1;
u8 unknown4:8;
} memory[1002];

#seekto 0x7000;
struct {
u8 bootscreen;
u8 unknown0[15];
char boottext1[10];
u8 unknown1[6];
char boottext2[10];
u8 unknown2[22];
u8 timeout;
u8 squelch;
u8 vox;
u8 powersave: 4,
unknown3:2,
language: 1,
voicealert: 1;
u8 backlight_timeout:8;
u8 beep:1,
autolock:1,
unknown4:1,
tail:1,
scanmode:2,
dtmfst:2;
u8 unknown5:1,
dualstandby:1,
roger:1,
unknown6:3,
fmenable:1,
unknown7:1;
u8 unknown8[9];
u8 unknown9:6,
chbdistype:1,
chadistype:1;
} settings;

struct vfo {
lbcd rxfreq[4];
lbcd txfreq[4];
u8 unused1:8;
ul16 rxtone;
ul16 txtone;
u8 unknown1:1,
bcl:1,
pttid:2,
unknown2:1,
wide:1,
lowpower:1,
unknown:1;
u8 scode:4,
unknown3:3,
scan:1;
u8 unknown4:8;
};

#seekto 0x0010;
struct {
struct vfo a;
struct vfo b;
} vfo;

#seekto 0x4000;
struct {
char name[11];
} names[999];

#seekto 0x8000;
struct {
u8 code[5];
} pttid[15];

struct {
u8 unknown[5];
u8 code[5];
} aniid;

"""

def sync_in(self):
"""Download from radio"""
try:
data = _download(self)
except errors.RadioError:
raise
except Exception:
LOG.exception('Unexpected error during download')
raise errors.RadioError('Unexpected error communicating '
'with the radio')
self._mmap = memmap.MemoryMapBytes(data)

self.process_mmap()

def sync_out(self):
"""Upload to radio"""
try:
_upload(self)
except errors.RadioError:
raise
except Exception:
LOG.exception('Unexpected error during upload')
raise errors.RadioError('Unexpected error communicating '
'with the radio')

def get_settings(self):
"""Translate the bit in the mem_struct into settings in the UI"""
_mem = self._memobj
basic = RadioSettingGroup("basic", "Basic Settings")
dtmfe = RadioSettingGroup("dtmfe", "DTMF Encode Settings")
top = RadioSettings(basic, dtmfe)
print(_mem.settings)

# Basic settings
if _mem.settings.squelch > 0x09:
val = 0x00
else:
val = _mem.settings.squelch
rs = RadioSetting("settings.squelch", "Squelch",
RadioSettingValueList(
LIST_OFF1TO9, LIST_OFF1TO9[val]))
basic.append(rs)

if _mem.settings.timeout > 0x27:
val = 0x03
else:
val = _mem.settings.timeout
rs = RadioSetting("settings.timeout", "Timeout Timer",
RadioSettingValueList(
LIST_TIMEOUT, LIST_TIMEOUT[val]))
basic.append(rs)

if _mem.settings.language > 0x02:
val = 0x01
else:
val = _mem.settings.language
rs = RadioSetting("settings.language", "Voice Prompt",
RadioSettingValueList(
LIST_VOICE, LIST_VOICE[val]))
basic.append(rs)

rs = RadioSetting("settings.voicealert", "Voice Alert",
RadioSettingValueBoolean(_mem.settings.voicealert))
basic.append(rs)

if _mem.settings.bootscreen > 0x02:
val = 0x00
else:
val = _mem.settings.bootscreen
rs = RadioSetting("settings.bootscreen", "Bootscreen",
RadioSettingValueList(
LIST_PONMSG, LIST_PONMSG[val]))
basic.append(rs)

def _filter(name):
filtered = ""
for char in str(name):
if char in chirp_common.CHARSET_ASCII:
filtered += char
else:
filtered += " "
return filtered

rs = RadioSetting("settings.boottext1", "Power-On Message 1",
RadioSettingValueString(
0, 10, _filter(self._memobj.settings.boottext1)))
basic.append(rs)

rs = RadioSetting("settings.boottext2", "Power-On Message 2",
RadioSettingValueString(
0, 10, _filter(self._memobj.settings.boottext2)))
basic.append(rs)

if _mem.settings.powersave > 0x04:
val = 0x00
else:
val = _mem.settings.powersave
rs = RadioSetting("settings.powersave", "Battery Saver",
RadioSettingValueList(
LIST_SAVE, LIST_SAVE[val]))
basic.append(rs)

if _mem.settings.backlight_timeout > 0x0A:
val = 0x00
else:
val = _mem.settings.backlight_timeout
rs = RadioSetting("settings.backlight_timeout", "Backlight Timeout",
RadioSettingValueList(
LIST_BCKLIGHT_TIMEOUT,
LIST_BCKLIGHT_TIMEOUT[val]))
basic.append(rs)

rs = RadioSetting("settings.beep", "Beep",
RadioSettingValueBoolean(_mem.settings.beep))
basic.append(rs)

rs = RadioSetting("settings.autolock", "Auto Lock",
RadioSettingValueBoolean(_mem.settings.autolock))
basic.append(rs)

rs = RadioSetting("settings.roger", "Roger",
RadioSettingValueBoolean(_mem.settings.roger))
basic.append(rs)

rs = RadioSetting("settings.scanmode", "Scan Mode",
RadioSettingValueList(
LIST_SCANMODE,
LIST_SCANMODE[_mem.settings.scanmode]))
basic.append(rs)

rs = RadioSetting("settings.dtmfst", "DTMF Sidetone",
RadioSettingValueList(LIST_DTMFST, LIST_DTMFST[
_mem.settings.dtmfst]))
basic.append(rs)

rs = RadioSetting("settings.dualstandby", "Dual Watch",
RadioSettingValueBoolean(_mem.settings.dualstandby))
basic.append(rs)

rs = RadioSetting("settings.fmenable", "Enable FM radio",
RadioSettingValueBoolean(_mem.settings.fmenable))
basic.append(rs)

rs = RadioSetting("settings.chadistype", "Channel A display type",
RadioSettingValueList(
LIST_MODE, LIST_MODE[_mem.settings.chadistype]))
basic.append(rs)

rs = RadioSetting("settings.chbdistype", "Channel B display type",
RadioSettingValueList(
LIST_MODE, LIST_MODE[_mem.settings.chbdistype]))
basic.append(rs)

# DTMF settings
def apply_code(setting, obj, length):
code = []
for j in range(0, length):
try:
code.append(DTMF_CHARS.index(str(setting.value)[j]))
except IndexError:
code.append(0xFF)
obj.code = code

for i in range(0, 15):
_codeobj = self._memobj.pttid[i].code
_code = "".join([
DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
val = RadioSettingValueString(0, 5, _code, False)
val.set_charset(DTMF_CHARS)
pttid = RadioSetting("pttid/%i.code" % i,
"Signal Code %i" % (i + 1), val)
pttid.set_apply_callback(apply_code, self._memobj.pttid[i], 5)
dtmfe.append(pttid)

_codeobj = self._memobj.aniid.code
_code = "".join([
DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
val = RadioSettingValueString(0, 5, _code, False)
val.set_charset(DTMF_CHARS)
aniid = RadioSetting("aniid.code",
"ANI ID", val)
aniid.set_apply_callback(apply_code, self._memobj.aniid, 5)
dtmfe.append(aniid)

return top

def get_features(self):
"""Get the radio's features"""

rf = chirp_common.RadioFeatures()
rf.has_settings = True
rf.has_bank = False
rf.has_tuning_step = False
rf.can_odd_split = True
rf.has_name = True
rf.has_offset = True
rf.has_mode = True
rf.has_dtcs = True
rf.has_rx_dtcs = True
rf.has_dtcs_polarity = True
rf.has_ctone = True
rf.has_cross = True
rf.valid_modes = self.MODES
rf.valid_characters = self.VALID_CHARS
rf.valid_name_length = self.LENGTH_NAME
if self._gmrs:
rf.valid_duplexes = ["", "+", "off"]
else:
rf.valid_duplexes = ["", "-", "+", "split", "off"]
rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
rf.valid_cross_modes = [
"Tone->Tone",
"DTCS->",
"->DTCS",
"Tone->DTCS",
"DTCS->Tone",
"->Tone",
"DTCS->DTCS"]
rf.valid_skips = self.SKIP_VALUES
rf.valid_dtcs_codes = self.DTCS_CODES
rf.memory_bounds = (0, 998)
rf.valid_power_levels = self.POWER_LEVELS
rf.valid_bands = self.VALID_BANDS
rf.valid_tuning_steps = STEPS

return rf

def decode_tone(self, val):
pol = "N"
mode = ""
if val in [0, 0xFFFF]:
xval = 0
elif (val & 0x8000) > 0:
mode = "DTCS"
xval = (val & 0x0f) + (val >> 4 & 0xf)\
* 10 + (val >> 8 & 0xf) * 100
if (val & 0xC000) == 0xC000:
pol = "R"
else:
mode = "Tone"
xval = int((val & 0x0f) + (val >> 4 & 0xf) * 10 +
(val >> 8 & 0xf) * 100 + (val >> 12 & 0xf)
* 1000) / 10.0

return mode, xval, pol

def get_memory(self, number):
offset = 0
# Skip 16 bytes at memory block boundary
# This is because these 16 bytes contain memory page numbers
if number >= 252:
offset += 1
if number >= 507:
offset += 1
if number >= 762:
offset += 1

_mem = self._memobj.memory[number + offset]
_nam = self._memobj.names[number]

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

if _mem.get_raw()[0] == 255:
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 baofeng_common._split(self.get_features(), mem.freq, int(
_mem.txfreq) * 10):
mem.duplex = "split"
mem.offset = int(_mem.txfreq) * 10
elif offset < 0:
mem.offset = abs(offset)
mem.duplex = "-"
elif offset > 0:
mem.offset = offset
mem.duplex = "+"
else:
mem.offset = 0

for char in _nam.name:
if (str(char) == "\xFF") | (str(char) == "\x00"):
char = " " # The OEM software may have 0xFF mid-name
mem.name += str(char)
mem.name = mem.name.rstrip()

txtone = self.decode_tone(_mem.txtone)
rxtone = self.decode_tone(_mem.rxtone)
chirp_common.split_tone_decode(mem, txtone, rxtone)

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

levels = self.POWER_LEVELS
try:
mem.power = levels[_mem.lowpower]
except IndexError:
LOG.error("Radio reported invalid power level %s (in %s)" %
(_mem.power, levels))
mem.power = levels[0]

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

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

rs = RadioSetting("bcl", "BCL",
RadioSettingValueBoolean(_mem.bcl))
mem.extra.append(rs)

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

rs = RadioSetting("scode", "S-CODE",
RadioSettingValueList(self.SCODE_LIST,
self.SCODE_LIST[
_mem.scode - 1]))
mem.extra.append(rs)

return mem

def encode_tone(self, memtone, mode, tone, pol):
if mode == "Tone":
xtone = str(int(tone * 10)).rjust(4, '0')
memtone.set_value((int(xtone[0]) << 12) + (int(xtone[1]) << 8) +
(int(xtone[2]) << 4) + int(xtone[3]))
elif mode == "TSQL":
xtone = str(int(tone * 10)).rjust(4, '0')
memtone.set_value((int(tone[0]) << 12) + (int(xtone[1]) << 8) +
(int(xtone[2]) << 4) + int(xtone[3]))
elif mode == "DTCS":
xtone = str(int(tone)).rjust(4, '0')
memtone.set_value((0x8000 + (int(xtone[0]) << 12) +
(int(xtone[1]) << 8) + (int(xtone[2]) << 4) +
int(xtone[3])))
else:
memtone.set_value(0)

if mode == "DTCS" and pol == "R":
memtone.set_value(memtone + 0x4000)

def set_memory(self, mem):
offset = 0
# skip 16 bytes at memory block boundary
if mem.number >= 252:
offset += 1
if mem.number >= 507:
offset += 1
if mem.number >= 762:
offset += 1
_mem = self._memobj.memory[mem.number + offset]
_nam = self._memobj.names[mem.number]

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

_mem.set_raw("\x00" * 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:
_nam.name[i] = mem.name[i]
except IndexError:
_nam.name[i] = "\xFF"

((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
chirp_common.split_tone_encode(mem)
self.encode_tone(_mem.txtone, txmode, txtone, txpol)
self.encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)

_mem.scan = mem.skip != "S"
_mem.wide = mem.mode == "FM"

if mem.power:
_mem.lowpower = self.POWER_LEVELS.index(mem.power)
else:
_mem.lowpower = 0

# extra settings
if len(mem.extra) > 0:
# there are setting, parse
for setting in mem.extra:
if setting.get_name() == "scode":
setattr(_mem, setting.get_name(), str(int(setting.value)
+ 1))
else:
setattr(_mem, setting.get_name(), setting.value)
else:
# there are no extra settings, load defaults
_mem.bcl = 0
_mem.pttid = 0
_mem.scode = 0
(3-3/3)