Project

General

Profile

Bug #4743 » anytone.py

Modified Anytone driver w/support for a dozen settings - Craig Jones, 03/13/2020 04:21 AM

 
1
# Copyright 2013 Dan Smith <dsmith@danplanet.com>
2
#
3
# This program is free software: you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation, either version 3 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15

    
16
import os
17
import struct
18
import time
19
import logging
20

    
21
from chirp import bitwise
22
from chirp import chirp_common
23
from chirp import directory
24
from chirp import errors
25
from chirp import memmap
26
from chirp import util
27
from chirp.settings import RadioSettingGroup, RadioSetting, RadioSettings, \
28
    RadioSettingValueList, RadioSettingValueString, RadioSettingValueBoolean, \
29
    RadioSettingValueInteger
30

    
31

    
32
LOG = logging.getLogger(__name__)
33

    
34
STEPS = [2.5, 5.0, 10.0, 12.5, 20.0, 25.0, 30.0, 50.0, 100.0]
35

    
36
_mem_format = """
37
#seekto 0x0100;
38
struct {
39
  u8 even_unknown:2,
40
     even_pskip:1,
41
     even_skip:1,
42
     odd_unknown:2,
43
     odd_pskip:1,
44
     odd_skip:1;
45
} flags[379];
46
"""
47

    
48
# NOTE: The "#seekto 0x0700;" below used to be 0x0280, but I had to change it to get the settings to work for the Powerwerx DB-750X.
49
# I don't know if it was just wrong before, or if 0x0280 is the correct location for the settings in the other make/model variants.
50
# I do know that the get_settings in the PowerwerxDB750XRadio class variant was overridden to nothing for some reason, which prevented the settings from being displayed/edited.
51
# // Craig K6NNL <craig@k6nnl.com>
52

    
53
mem_format = _mem_format + """
54
struct memory {
55
  bbcd freq[4];
56
  bbcd offset[4];
57
  u8 unknownA:4,
58
     tune_step:4;
59
  u8 rxdcsextra:1,
60
     txdcsextra:1,
61
     rxinv:1,
62
     txinv:1,
63
     channel_width:2,
64
     unknownB:2;
65
  u8 unknown8:3,
66
     is_am:1,
67
     power:2,
68
     duplex:2;
69
  u8 unknown4:4,
70
     rxtmode:2,
71
     txtmode:2;
72
  u8 unknown5:2,
73
     txtone:6;
74
  u8 unknown6:2,
75
     rxtone:6;
76
  u8 txcode;
77
  u8 rxcode;
78
  u8 unknown7[2];
79
  u8 unknown2[5];
80
  char name[7];
81
  u8 unknownZ[2];
82
};
83

    
84
#seekto 0x0030;
85
struct {
86
  char serial[16];
87
} serial_no;
88

    
89
#seekto 0x0050;
90
struct {
91
  char date[16];
92
} version;
93

    
94
#seekto 0x0700;
95
struct {
96
  u8 unknown1:6,
97
     display:2;
98
  u8 unknown2[5];
99
  u8 red;
100
  u8 green;
101
  u8 blue;
102
  u8 unknownAfterRBG[3];
103
  u8 unknown3:3,
104
     apo:5;
105
  u8 unknown4a[2];
106
  u8 unknown4b:6,
107
     mute:2;
108
  u8 unknownBeforeLocked:2,
109
     locked:1,
110
     unknownAfterLocked:5;
111
  u8 unknown5:5,  
112
     beep:1,
113
     unknown6:2;
114
  u8 unknown7[3];
115
  u8 keya;   
116
  u8 keyb;
117
  u8 keyc;
118
  u8 keyd;
119
  u8 unknown8[455];
120
  char welcome[8];  
121

    
122
} settings;
123

    
124

    
125

    
126
#seekto 0x0540;
127
struct memory memblk1[12];
128

    
129
#seekto 0x2000;
130
struct memory memory[758];
131

    
132
#seekto 0x7ec0;
133
struct memory memblk2[10];
134
"""
135

    
136

    
137
class FlagObj(object):
138
    def __init__(self, flagobj, which):
139
        self._flagobj = flagobj
140
        self._which = which
141

    
142
    def _get(self, flag):
143
        return getattr(self._flagobj, "%s_%s" % (self._which, flag))
144

    
145
    def _set(self, flag, value):
146
        return setattr(self._flagobj, "%s_%s" % (self._which, flag), value)
147

    
148
    def get_skip(self):
149
        return self._get("skip")
150

    
151
    def set_skip(self, value):
152
        self._set("skip", value)
153

    
154
    skip = property(get_skip, set_skip)
155

    
156
    def get_pskip(self):
157
        return self._get("pskip")
158

    
159
    def set_pskip(self, value):
160
        self._set("pskip", value)
161

    
162
    pskip = property(get_pskip, set_pskip)
163

    
164
    def set(self):
165
        self._set("unknown", 3)
166
        self._set("skip", 1)
167
        self._set("pskip", 1)
168

    
169
    def clear(self):
170
        self._set("unknown", 0)
171
        self._set("skip", 0)
172
        self._set("pskip", 0)
173

    
174
    def get(self):
175
        return (self._get("unknown") << 2 |
176
                self._get("skip") << 1 |
177
                self._get("pskip"))
178

    
179
    def __repr__(self):
180
        return repr(self._flagobj)
181

    
182

    
183
def _is_loc_used(memobj, loc):
184
    return memobj.flags[loc / 2].get_raw() != "\xFF"
185

    
186

    
187
def _addr_to_loc(addr):
188
    return (addr - 0x2000) / 32
189

    
190

    
191
def _should_send_addr(memobj, addr):
192
    if addr < 0x2000 or addr >= 0x7EC0:
193
        return True
194
    else:
195
        return _is_loc_used(memobj, _addr_to_loc(addr))
196

    
197

    
198
def _echo_write(radio, data):
199
    try:
200
        radio.pipe.write(data)
201
        radio.pipe.read(len(data))
202
    except Exception, e:
203
        LOG.error("Error writing to radio: %s" % e)
204
        raise errors.RadioError("Unable to write to radio")
205

    
206

    
207
def _read(radio, length):
208
    try:
209
        data = radio.pipe.read(length)
210
    except Exception, e:
211
        LOG.error("Error reading from radio: %s" % e)
212
        raise errors.RadioError("Unable to read from radio")
213

    
214
    if len(data) != length:
215
        LOG.error("Short read from radio (%i, expected %i)" %
216
                  (len(data), length))
217
        LOG.debug(util.hexprint(data))
218
        raise errors.RadioError("Short read from radio")
219
    return data
220

    
221
valid_model = ['QX588UV', 'HR-2040', 'DB-50M\x00', 'DB-750X']
222

    
223

    
224
def _ident(radio):
225
    radio.pipe.timeout = 1
226
    _echo_write(radio, "PROGRAM")
227
    response = radio.pipe.read(3)
228
    if response != "QX\x06":
229
        LOG.debug("Response was:\n%s" % util.hexprint(response))
230
        raise errors.RadioError("Unsupported model or bad connection")
231
    _echo_write(radio, "\x02")
232
    response = radio.pipe.read(16)
233
    LOG.debug(util.hexprint(response))
234
    if response[1:8] not in valid_model:
235
        LOG.debug("Response was:\n%s" % util.hexprint(response))
236
        raise errors.RadioError("Unsupported model")
237

    
238

    
239
def _finish(radio):
240
    endframe = "\x45\x4E\x44"
241
    _echo_write(radio, endframe)
242
    result = radio.pipe.read(1)
243
    if result != "\x06":
244
        LOG.debug("Got:\n%s" % util.hexprint(result))
245
        raise errors.RadioError("Radio did not finish cleanly")
246

    
247

    
248
def _checksum(data):
249
    cs = 0
250
    for byte in data:
251
        cs += ord(byte)
252
    return cs % 256
253

    
254

    
255
def _send(radio, cmd, addr, length, data=None):
256
    frame = struct.pack(">cHb", cmd, addr, length)
257
    if data:
258
        frame += data
259
        frame += chr(_checksum(frame[1:]))
260
        frame += "\x06"
261
    _echo_write(radio, frame)
262
    LOG.debug("Sent:\n%s" % util.hexprint(frame))
263
    if data:
264
        result = radio.pipe.read(1)
265
        if result != "\x06":
266
            LOG.debug("Ack was: %s" % repr(result))
267
            raise errors.RadioError(
268
                "Radio did not accept block at %04x" % addr)
269
        return
270
    result = _read(radio, length + 6)
271
    LOG.debug("Got:\n%s" % util.hexprint(result))
272
    header = result[0:4]
273
    data = result[4:-2]
274
    ack = result[-1]
275
    if ack != "\x06":
276
        LOG.debug("Ack was: %s" % repr(ack))
277
        raise errors.RadioError("Radio NAK'd block at %04x" % addr)
278
    _cmd, _addr, _length = struct.unpack(">cHb", header)
279
    if _addr != addr or _length != _length:
280
        LOG.debug("Expected/Received:")
281
        LOG.debug(" Length: %02x/%02x" % (length, _length))
282
        LOG.debug(" Addr: %04x/%04x" % (addr, _addr))
283
        raise errors.RadioError("Radio send unexpected block")
284
    cs = _checksum(result[1:-2])
285
    if cs != ord(result[-2]):
286
        LOG.debug("Calculated: %02x" % cs)
287
        LOG.debug("Actual:     %02x" % ord(result[-2]))
288
        raise errors.RadioError("Block at 0x%04x failed checksum" % addr)
289
    return data
290

    
291

    
292
def _download(radio):
293
    _ident(radio)
294

    
295
    memobj = None
296

    
297
    data = ""
298
    for start, end in radio._ranges:
299
        for addr in range(start, end, 0x10):
300
            if memobj is not None and not _should_send_addr(memobj, addr):
301
                block = "\xFF" * 0x10
302
            else:
303
                block = _send(radio, 'R', addr, 0x10)
304
            data += block
305

    
306
            status = chirp_common.Status()
307
            status.cur = len(data)
308
            status.max = end
309
            status.msg = "Cloning from radio"
310
            radio.status_fn(status)
311

    
312
            if addr == 0x19F0:
313
                memobj = bitwise.parse(_mem_format, data)
314

    
315
    _finish(radio)
316

    
317
    return memmap.MemoryMap(data)
318

    
319

    
320
def _upload(radio):
321
    _ident(radio)
322

    
323
    for start, end in radio._ranges:
324
        for addr in range(start, end, 0x10):
325
            if addr < 0x0100:
326
                continue
327
            if not _should_send_addr(radio._memobj, addr):
328
                continue
329
            block = radio._mmap[addr:addr + 0x10]
330
            _send(radio, 'W', addr, len(block), block)
331

    
332
            status = chirp_common.Status()
333
            status.cur = addr
334
            status.max = end
335
            status.msg = "Cloning to radio"
336
            radio.status_fn(status)
337

    
338
    _finish(radio)
339

    
340

    
341
TONES = [62.5] + list(chirp_common.TONES)
342
TMODES = ['', 'Tone', 'DTCS', '']
343
DUPLEXES = ['', '-', '+', '']
344
MODES = ["FM", "FM", "NFM"]
345
POWER_LEVELS = [chirp_common.PowerLevel("High", watts=50),
346
                chirp_common.PowerLevel("Mid1", watts=25),
347
                chirp_common.PowerLevel("Mid2", watts=10),
348
                chirp_common.PowerLevel("Low", watts=5)]
349

    
350

    
351
@directory.register
352
class AnyTone5888UVRadio(chirp_common.CloneModeRadio,
353
                         chirp_common.ExperimentalRadio):
354
    """AnyTone 5888UV"""
355
    VENDOR = "AnyTone"
356
    MODEL = "5888UV"
357
    BAUD_RATE = 9600
358
    _file_ident = "QX588UV"
359

    
360
    # May try to mirror the OEM behavior later
361
    _ranges = [
362
        (0x0000, 0x8000),
363
        ]
364

    
365
    @classmethod
366
    def get_prompts(cls):
367
        rp = chirp_common.RadioPrompts()
368
        rp.experimental = ("The Anytone driver is currently experimental. "
369
                           "There are no known issues with it, but you should "
370
                           "proceed with caution.")
371
        return rp
372

    
373
    def get_features(self):
374
        rf = chirp_common.RadioFeatures()
375
        rf.has_settings = True
376
        rf.has_bank = False
377
        rf.has_cross = True
378
        rf.has_tuning_step = False
379
        rf.valid_tuning_steps = STEPS
380
        rf.has_rx_dtcs = True
381
        rf.valid_skips = ["", "S", "P"]
382
        rf.valid_modes = ["FM", "NFM", "AM"]
383
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
384
        rf.valid_cross_modes = ['Tone->DTCS', 'DTCS->Tone',
385
                                '->Tone', '->DTCS', 'Tone->Tone']
386
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES
387
        rf.valid_bands = [(108000000, 500000000)]
388
        rf.valid_characters = chirp_common.CHARSET_UPPER_NUMERIC + "-"
389
        rf.valid_name_length = 7
390
        rf.valid_power_levels = POWER_LEVELS
391
        rf.memory_bounds = (1, 758)
392
        return rf
393

    
394
    def sync_in(self):
395
        self._mmap = _download(self)
396
        self.process_mmap()
397

    
398
    def sync_out(self):
399
        _upload(self)
400

    
401
    def process_mmap(self):
402
        self._memobj = bitwise.parse(mem_format, self._mmap)
403

    
404
    def _get_memobjs(self, number):
405
        number -= 1
406
        _mem = self._memobj.memory[number]
407
        _flg = FlagObj(self._memobj.flags[number / 2],
408
                       number % 2 and "even" or "odd")
409
        return _mem, _flg
410

    
411
    def _get_dcs_index(self, _mem, which):
412
        base = getattr(_mem, '%scode' % which)
413
        extra = getattr(_mem, '%sdcsextra' % which)
414
        return (int(extra) << 8) | int(base)
415

    
416
    def _set_dcs_index(self, _mem, which, index):
417
        base = getattr(_mem, '%scode' % which)
418
        extra = getattr(_mem, '%sdcsextra' % which)
419
        base.set_value(index & 0xFF)
420
        extra.set_value(index >> 8)
421

    
422
    def get_raw_memory(self, number):
423
        _mem, _flg = self._get_memobjs(number)
424
        return repr(_mem) + repr(_flg)
425

    
426
    def get_memory(self, number):
427
        _mem, _flg = self._get_memobjs(number)
428
        mem = chirp_common.Memory()
429
        mem.number = number
430

    
431
        if _flg.get() == 0x0F:
432
            mem.empty = True
433
            return mem
434

    
435
        mem.freq = int(_mem.freq) * 100
436
        mem.offset = int(_mem.offset) * 100
437
        mem.name = str(_mem.name).rstrip()
438
        mem.duplex = DUPLEXES[_mem.duplex]
439
        mem.mode = _mem.is_am and "AM" or MODES[_mem.channel_width]
440

    
441
        rxtone = txtone = None
442
        rxmode = TMODES[_mem.rxtmode]
443
        txmode = TMODES[_mem.txtmode]
444
        if txmode == "Tone":
445
            txtone = TONES[_mem.txtone]
446
        elif txmode == "DTCS":
447
            txtone = chirp_common.ALL_DTCS_CODES[self._get_dcs_index(_mem,
448
                                                                     'tx')]
449
        if rxmode == "Tone":
450
            rxtone = TONES[_mem.rxtone]
451
        elif rxmode == "DTCS":
452
            rxtone = chirp_common.ALL_DTCS_CODES[self._get_dcs_index(_mem,
453
                                                                     'rx')]
454

    
455
        rxpol = _mem.rxinv and "R" or "N"
456
        txpol = _mem.txinv and "R" or "N"
457

    
458
        chirp_common.split_tone_decode(mem,
459
                                       (txmode, txtone, txpol),
460
                                       (rxmode, rxtone, rxpol))
461

    
462
        mem.skip = _flg.get_skip() and "S" or _flg.get_pskip() and "P" or ""
463
        mem.power = POWER_LEVELS[_mem.power]
464

    
465
        return mem
466

    
467
    def set_memory(self, mem):
468
        _mem, _flg = self._get_memobjs(mem.number)
469
        if mem.empty:
470
            _flg.set()
471
            return
472
        _flg.clear()
473
        _mem.set_raw("\x00" * 32)
474

    
475
        _mem.freq = mem.freq / 100
476
        _mem.offset = mem.offset / 100
477
        _mem.name = mem.name.ljust(7)
478
        _mem.is_am = mem.mode == "AM"
479
        _mem.duplex = DUPLEXES.index(mem.duplex)
480

    
481
        try:
482
            _mem.channel_width = MODES.index(mem.mode)
483
        except ValueError:
484
            _mem.channel_width = 0
485

    
486
        ((txmode, txtone, txpol),
487
         (rxmode, rxtone, rxpol)) = chirp_common.split_tone_encode(mem)
488

    
489
        _mem.txtmode = TMODES.index(txmode)
490
        _mem.rxtmode = TMODES.index(rxmode)
491
        if txmode == "Tone":
492
            _mem.txtone = TONES.index(txtone)
493
        elif txmode == "DTCS":
494
            self._set_dcs_index(_mem, 'tx',
495
                                chirp_common.ALL_DTCS_CODES.index(txtone))
496
        if rxmode == "Tone":
497
            _mem.rxtone = TONES.index(rxtone)
498
        elif rxmode == "DTCS":
499
            self._set_dcs_index(_mem, 'rx',
500
                                chirp_common.ALL_DTCS_CODES.index(rxtone))
501

    
502
        _mem.txinv = txpol == "R"
503
        _mem.rxinv = rxpol == "R"
504

    
505
        _flg.set_skip(mem.skip == "S")
506
        _flg.set_pskip(mem.skip == "P")
507

    
508
        if mem.power:
509
            _mem.power = POWER_LEVELS.index(mem.power)
510
        else:
511
            _mem.power = 0
512

    
513
    def get_settings(self):
514
        _settings = self._memobj.settings
515
        basic_group = RadioSettingGroup("basic_group", "Basic Settings")
516
        audio_group = RadioSettingGroup("audio_group", "Audio Options")
517
        keys_group = RadioSettingGroup("keys_group", "Programmable Keys")
518
        display_group = RadioSettingGroup("display_group", "Display Options")
519
        settings = RadioSettings(basic_group, audio_group, keys_group, display_group)
520

    
521
        ############  Basic Group
522

    
523
        rs = RadioSetting("locked", "Keypad locked",
524
                          RadioSettingValueBoolean(_settings.locked))
525
        basic_group.append(rs)
526

    
527

    
528

    
529
        display = ["Frequency", "Channel", "Name"]
530
        rs = RadioSetting("display", "Memory Display",
531
                          RadioSettingValueList(display, display[_settings.display]))
532
        basic_group.append(rs)
533

    
534

    
535

    
536
        apo = ["Off"] + ['%.1f hour(s)' % (0.5 * x) for x in range(1, 25)]
537
        rs = RadioSetting("apo", "Automatic Power Off",
538
                          RadioSettingValueList(apo, apo[_settings.apo]))
539
        basic_group.append(rs)
540

    
541

    
542
        ############  Audio Group
543

    
544
        rs = RadioSetting("beep", "Beep Enabled",
545
                          RadioSettingValueBoolean(_settings.beep))
546
        audio_group.append(rs)
547

    
548
        mute = ["Off", "TX", "RX", "TX/RX"]
549
        rs = RadioSetting("mute", "Sub Band Mute",
550
                          RadioSettingValueList(mute, mute[_settings.mute]))
551
        audio_group.append(rs)
552

    
553

    
554
        ############  Keys Group
555

    
556
        progkey = ["Off", "RPTR offset direction", "PRI priority", "LOW power", "TONE", "MHZ", "REV", "HOME", "MAIN A/B", "VFO/MR", "SCAN", "SQLOFF/ON", "TBST tone burst", "CALLOUT", "COMP Compander on/off", "SCR scrambler on/off", "TONEDEC", "Wide/Nar", "TALK-around"] 
557
        rs = RadioSetting("keya", "Programmable Key A",
558
                          RadioSettingValueList(progkey, progkey[_settings.keya]))
559
        keys_group.append(rs)
560
        rs = RadioSetting("keyb", "Programmable Key B",
561
                          RadioSettingValueList(progkey, progkey[_settings.keyb]))
562
        keys_group.append(rs)
563
        rs = RadioSetting("keyc", "Programmable Key C",
564
                          RadioSettingValueList(progkey, progkey[_settings.keyc]))
565
        keys_group.append(rs)
566
        rs = RadioSetting("keyd", "Programmable Key D",
567
                          RadioSettingValueList(progkey, progkey[_settings.keyd]))
568
        keys_group.append(rs)
569

    
570
        ############  Display Group
571

    
572
        def filter(s):
573
            s_ = ""
574
            for i in range(0, 8):
575
                c = str(s[i])
576
                s_ += (c if c in chirp_common.CHARSET_ASCII else "")
577
            return s_
578
        rs = RadioSetting("welcome", "Welcome Message",
579
                          RadioSettingValueString(0, 8, filter(_settings.welcome)))
580
        display_group.append(rs)
581

    
582
        rs = RadioSetting("red", "Background Brightness: Red",
583
                          RadioSettingValueInteger(0,31,_settings.red))
584
        display_group.append(rs)
585
        rs = RadioSetting("green", "Background Brightness: Green",
586
                          RadioSettingValueInteger(0,31,_settings.green))
587
        display_group.append(rs)
588
        rs = RadioSetting("blue", "Background Brightness: Blue",
589
                          RadioSettingValueInteger(0,31,_settings.blue))
590
        display_group.append(rs)
591

    
592

    
593
        return settings
594

    
595
    def set_settings(self, settings):
596
        _settings = self._memobj.settings
597
        for element in settings:
598
            if not isinstance(element, RadioSetting):
599
                self.set_settings(element)
600
                continue
601
            name = element.get_name()
602
            setattr(_settings, name, element.value)
603

    
604
    @classmethod
605
    def match_model(cls, filedata, filename):
606
        return cls._file_ident in filedata[0x20:0x40]
607

    
608

    
609
@directory.register
610
class IntekHR2040Radio(AnyTone5888UVRadio):
611
    """Intek HR-2040"""
612
    VENDOR = "Intek"
613
    MODEL = "HR-2040"
614
    _file_ident = "HR-2040"
615

    
616

    
617
@directory.register
618
class PolmarDB50MRadio(AnyTone5888UVRadio):
619
    """Polmar DB-50M"""
620
    VENDOR = "Polmar"
621
    MODEL = "DB-50M"
622
    _file_ident = "DB-50M"
623

    
624

    
625
@directory.register
626
class PowerwerxDB750XRadio(AnyTone5888UVRadio):
627
    """Powerwerx DB-750X"""
628
    VENDOR = "Powerwerx"
629
    MODEL = "DB-750X"
630
    _file_ident = "DB-750X"
631

    
632
#    def get_settings(self):
633
#        return {}
(3-3/3)