Project

General

Profile

New Model #10023 » th_uv88 - qrz_1_poc3.py

Jim Unroe, 09/25/2022 10:52 PM

 
1
# Version 1.0 for TYT-UV88
2
# Initial radio protocol decode, channels and memory layout
3
# by James Berry <james@coppermoth.com>, Summer 2020
4
# Additional configuration and help, Jim Unroe <rock.unroe@gmail.com>
5
#
6
# This program is free software: you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation, either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful,
12
# but WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
# GNU General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program.
18

    
19
import time
20
import struct
21
import logging
22
import re
23
import math
24
from chirp import chirp_common, directory, memmap
25
from chirp import bitwise, errors, util
26
from chirp.settings import RadioSettingGroup, RadioSetting, \
27
    RadioSettingValueBoolean, RadioSettingValueList, \
28
    RadioSettingValueString, RadioSettingValueInteger, \
29
    RadioSettingValueFloat, RadioSettings, InvalidValueError
30
from textwrap import dedent
31

    
32
LOG = logging.getLogger(__name__)
33

    
34
MEM_FORMAT = """
35
struct chns {
36
  ul32 rxfreq;
37
  ul32 txfreq;
38
  ul16 scramble:4
39
       rxtone:12; //decode:12
40
  ul16 decodeDSCI:1
41
       encodeDSCI:1
42
       unk1:1
43
       unk2:1
44
       txtone:12; //encode:12
45
  u8   power:2
46
       wide:2
47
       b_lock:2
48
       unk3:2;
49
  u8   unk4:3
50
       signal:2
51
       displayName:1
52
       unk5:2;
53
  u8   unk6:2
54
       pttid:2
55
       step:4;               // not required
56
  u8   name[6];
57
};
58

    
59
struct vfo {
60
  ul32 rxfreq;
61
  ul32 txfreq;  // displayed as an offset
62
  ul16 scramble:4
63
       rxtone:12; //decode:12
64
  ul16 decodeDSCI:1
65
       encodeDSCI:1
66
       unk1:1
67
       unk2:1
68
       txtone:12; //encode:12
69
  u8   power:2
70
       wide:2
71
       b_lock:2
72
       unk3:2;
73
  u8   unk4:3
74
       signal:2
75
       displayName:1
76
       unk5:2;
77
  u8   unk6:2
78
       pttid:2
79
       step:4;
80
  u8   name[6];
81
};
82

    
83
struct chname {
84
  u8  extra_name[10];
85
};
86

    
87
#seekto 0x0000;
88
struct chns chan_mem[199];
89

    
90
#seekto 0x1960;
91
struct chname chan_name[199];
92

    
93
#seekto 0x1180;
94
struct {
95
  u8 bitmap[26];    // one bit for each channel marked in use
96
} chan_avail;
97

    
98
#seekto 0x11A0;
99
struct {
100
  u8 bitmap[26];    // one bit for each channel skipped
101
} chan_skip;
102

    
103
#seekto 0x1140;
104
struct {
105
  u8 autoKeylock:1,       // 0x1140 [18] *OFF, On
106
     unk_bit6_5:1,        //
107
     vfomrmodeb:1,        //        *VFO B, MR B
108
     vfomrmode:1,         //        *VFO, MR
109
     unk_bit3_0:4;        //
110
  u8 mrAch;               // 0x1141 MR A Channel #
111
  u8 mrBch;               // 0x1142 MR B Channel #
112
  u8 unk_bit7_3:5,        //
113
     ab:1,                //        * A, B
114
     unk_bit1_0:2;        //
115
} workmodesettings;
116

    
117
#seekto 0x1160;
118
struct {
119
  u8 introScreen1[12];    // 0x1160 *Intro Screen Line 1(truncated to 12 alpha
120
                          //         text characters)
121
  u8 offFreqVoltage : 3,  // 0x116C unknown referred to in code but not on
122
                          //        screen
123
     unk_bit4 : 1,        //
124
     sqlLevel : 4;        //        [05] *OFF, 1-9
125
  u8 beep : 1             // 0x116D [09] *OFF, On
126
     callKind : 2,        //        code says 1750,2100,1000,1450 as options
127
                          //        not on screen
128
     introScreen: 2,      //        [20] *OFF, Voltage, Char String
129
     unkstr2: 2,          //
130
     txChSelect : 1;      //        [02] *Last CH, Main CH
131
  u8 autoPowOff : 3,      // 0x116E not on screen? OFF, 30Min, 1HR, 2HR
132
     unk : 1,             //
133
     tot : 4;             //        [11] *OFF, 30 Second, 60 Second, 90 Second,
134
                          //              ... , 270 Second
135
  u8 unk_bit7:1,          // 0x116F
136
     roger:1,             //        [14] *OFF, On
137
     dailDef:1,           //        Unknown - 'Volume, Frequency'
138
     language:1,          //        ?Chinese, English (English only FW BQ1.38+)
139
     unk_bit3:1,          //
140
     endToneElim:1,       //        *OFF, Frequency
141
     unkCheckBox1:1,      //
142
     unkCheckBox2:1;      //
143
  u8 scanResumeTime : 2,  // 0x1170 2S, 5S, 10S, 15S (not on screen)
144
     disMode : 2,         //        [33] *Frequency, Channel, Name
145
     scanType: 2,         //        [17] *To, Co, Se
146
     ledMode: 2;          //        [07] *Off, On, Auto
147
  u8 unky;                // 0x1171
148
  u8 str6;                // 0x1172 Has flags to do with logging - factory
149
                          // enabled (bits 16,64,128)
150
  u8 unk;                 // 0x1173
151
  u8 swAudio : 1,         // 0x1174 [19] *OFF, On
152
     radioMoni : 1,       //        [34] *OFF, On
153
     keylock : 1,         //        [18] *OFF, On
154
     dualWait : 1,        //        [06] *OFF, On
155
     unk_bit3 : 1,        //
156
     light : 3;           //        [08] *1, 2, 3, 4, 5, 6, 7
157
  u8 voxSw : 1,           // 0x1175 [13] *OFF, On
158
     voxDelay: 4,         //        *0.5S, 1.0S, 1.5S, 2.0S, 2.5S, 3.0S, 3.5S,
159
                          //         4.0S, 4.5S, 5.0S
160
     voxLevel : 3;        //        [03] *1, 2, 3, 4, 5, 6, 7
161
  u8 str9 : 4,            // 0x1176
162
     saveMode : 2,        //        [16] *OFF, 1:1, 1:2, 1:4
163
     keyMode : 2;         //        [32] *ALL, PTT, KEY, Key & Side Key
164
  u8 unk2;                // 0x1177
165
  u8 unk3;                // 0x1178
166
  u8 unk4;                // 0x1179
167
  u8 name2[6];            // 0x117A unused
168
} basicsettings;
169

    
170
#seekto 0x191E;
171
struct {
172
  u8 unknown191e:4,       //
173
     region:4;            // 0x191E Radio Region (read only)
174
                          // 0 = Unlocked  TX: 136-174 MHz / 400-480 MHz
175
                          // 2-3 = Unknown
176
                          // 3 = EU        TX: 144-146 MHz / 430-440 MHz
177
                          // 4 = US        TX: 144-148 MHz / 420-450 MHz
178
                          // 5-15 = Unknown
179
} settings2;
180

    
181
#seekto 0x1940;
182
struct {
183
  char name1[15];         // Intro Screen Line 1 (16 alpha text characters)
184
  u8 unk1;
185
  char name2[15];         // Intro Screen Line 2 (16 alpha text characters)
186
  u8 unk2;
187
} openradioname;
188

    
189
"""
190

    
191
MEM_SIZE = 0x22A0
192
BLOCK_SIZE = 0x20
193
STIMEOUT = 2
194
BAUDRATE = 57600
195

    
196
# Channel power: 3 levels
197
POWER_LEVELS = [chirp_common.PowerLevel("High", watts=5.00),
198
                chirp_common.PowerLevel("Mid", watts=2.50),
199
                chirp_common.PowerLevel("Low", watts=0.50)]
200

    
201
SCRAMBLE_LIST = ["OFF", "1", "2", "3", "4", "5", "6", "7", "8"]
202
B_LOCK_LIST = ["OFF", "Sub", "Carrier"]
203
OPTSIG_LIST = ["OFF", "DTMF", "2TONE", "5TONE"]
204
PTTID_LIST = ["Off", "BOT", "EOT", "Both"]
205
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0, 50.0, 100.0]
206
LIST_STEPS = [str(x) for x in STEPS]
207

    
208

    
209
def _clean_buffer(radio):
210
    radio.pipe.timeout = 0.005
211
    junk = radio.pipe.read(256)
212
    radio.pipe.timeout = STIMEOUT
213
    if junk:
214
        LOG.debug("Got %i bytes of junk before starting" % len(junk))
215

    
216

    
217
def _rawrecv(radio, amount):
218
    """Raw read from the radio device"""
219
    data = ""
220
    try:
221
        data = radio.pipe.read(amount)
222
    except Exception:
223
        _exit_program_mode(radio)
224
        msg = "Generic error reading data from radio; check your cable."
225
        raise errors.RadioError(msg)
226

    
227
    if len(data) != amount:
228
        _exit_program_mode(radio)
229
        msg = "Error reading from radio: not the amount of data we want."
230
        raise errors.RadioError(msg)
231

    
232
    return data
233

    
234

    
235
def _rawsend(radio, data):
236
    """Raw send to the radio device"""
237
    try:
238
        radio.pipe.write(data)
239
    except Exception:
240
        raise errors.RadioError("Error sending data to radio")
241

    
242

    
243
def _make_read_frame(addr, length):
244
    frame = "\xFE\xFE\xEE\xEF\xEB"
245
    """Pack the info in the header format"""
246
    frame += struct.pack(">ih", addr, length)
247

    
248
    frame += "\xFD"
249
    # Return the data
250
    return frame
251

    
252

    
253
def _make_write_frame(addr, length, data=""):
254
    frame = "\xFE\xFE\xEE\xEF\xE4"
255

    
256
    """Pack the info in the header format"""
257
    output = struct.pack(">ih", addr, length)
258
    # Add the data if set
259
    if len(data) != 0:
260
        output += data
261

    
262
    frame += output
263
    frame += _calculate_checksum(output)
264

    
265
    frame += "\xFD"
266
    # Return the data
267
    return frame
268

    
269

    
270
def _calculate_checksum(data):
271
    num = 0
272
    for x in range(0, len(data)):
273
        num = (num + ord(data[x])) % 256
274

    
275
    if num == 0:
276
        return chr(0)
277

    
278
    return chr(256 - num)
279

    
280

    
281
def _recv(radio, addr, length):
282
    """Get data from the radio """
283

    
284
    data = _rawrecv(radio, length)
285

    
286
    # DEBUG
287
    LOG.info("Response:")
288
    LOG.debug(util.hexprint(data))
289

    
290
    return data
291

    
292

    
293
def _do_ident(radio):
294
    """Put the radio in PROGRAM mode & identify it"""
295
    radio.pipe.baudrate = BAUDRATE
296
    radio.pipe.parity = "N"
297
    radio.pipe.timeout = STIMEOUT
298

    
299
    # Flush input buffer
300
    _clean_buffer(radio)
301

    
302
    # Ident radio
303
    magic = radio._magic0
304
    _rawsend(radio, magic)
305
    ack = _rawrecv(radio, 36)
306

    
307
    if not ack.startswith(radio._fingerprint) or not ack.endswith("\xFD"):
308
        _exit_program_mode(radio)
309
        if ack:
310
            LOG.debug(repr(ack))
311
        raise errors.RadioError("Radio did not respond as expected (A)")
312

    
313
    return True
314

    
315

    
316
def _exit_program_mode(radio):
317
    # This may be the last part of a read
318
    magic = radio._magic5
319
    _rawsend(radio, magic)
320
    _clean_buffer(radio)
321

    
322
def _download(radio):
323
    """Get the memory map"""
324

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

    
328
    # Enter read mode
329
    magic = radio._magic2
330
    _rawsend(radio, magic)
331
    ack = _rawrecv(radio, 7)
332
    if ack != "\xFE\xFE\xEF\xEE\xE6\x00\xFD":
333
        _exit_program_mode(radio)
334
        if ack:
335
            LOG.debug(repr(ack))
336
        raise errors.RadioError("Radio did not respond to enter read mode")
337

    
338
    # UI progress
339
    status = chirp_common.Status()
340
    status.cur = 0
341
    status.max = MEM_SIZE / BLOCK_SIZE
342
    status.msg = "Cloning from radio..."
343
    radio.status_fn(status)
344

    
345
    data = ""
346
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
347
        frame = _make_read_frame(addr, BLOCK_SIZE)
348
        # DEBUG
349
        LOG.debug("Frame=" + util.hexprint(frame))
350

    
351
        # Sending the read request
352
        _rawsend(radio, frame)
353

    
354
        # Now we read data
355
        d = _recv(radio, addr, BLOCK_SIZE + 13)
356

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

    
359
        if not d.startswith("\xFE\xFE\xEF\xEE\xE4"):
360
            LOG.warning("Incorrect start")
361
        if not d.endswith("\xFD"):
362
            LOG.warning("Incorrect end")
363
        # could validate the block data
364

    
365
        # Aggregate the data
366
        data += d[11:-2]
367

    
368
        # UI Update
369
        status.cur = addr / BLOCK_SIZE
370
        status.msg = "Cloning from radio..."
371
        radio.status_fn(status)
372

    
373
    _exit_program_mode(radio)
374

    
375
    return data
376

    
377

    
378
def _upload(radio):
379
    """Upload procedure"""
380
    # Put radio in program mode and identify it
381
    _do_ident(radio)
382

    
383
    magic = radio._magic3
384
    _rawsend(radio, magic)
385
    ack = _rawrecv(radio, 7)
386
    if ack != "\xFE\xFE\xEF\xEE\xE6\x00\xFD":
387
        _exit_program_mode(radio)
388
        if ack:
389
            LOG.debug(repr(ack))
390
        raise errors.RadioError("Radio did not respond to enter write mode")
391

    
392
    # UI progress
393
    status = chirp_common.Status()
394
    status.cur = 0
395
    status.max = MEM_SIZE / BLOCK_SIZE
396
    status.msg = "Cloning to radio..."
397
    radio.status_fn(status)
398

    
399
    # The fun starts here
400
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
401
        # Official programmer skips writing these memory locations
402
        if addr >= 0x1680 and addr < 0x1940:
403
            continue
404

    
405
        # Sending the data
406
        data = radio.get_mmap()[addr:addr + BLOCK_SIZE]
407

    
408
        frame = _make_write_frame(addr, BLOCK_SIZE, data)
409
        LOG.warning("Frame:%s:" % util.hexprint(frame))
410
        _rawsend(radio, frame)
411

    
412
        ack = _rawrecv(radio, 7)
413
        LOG.debug("Response Data= " + util.hexprint(ack))
414

    
415
        if not ack.startswith("\xFE\xFE\xEF\xEE\xE6\x00\xFD"):
416
            LOG.warning("Unexpected response")
417
            _exit_program_mode(radio)
418
            msg = "Bad ack writing block 0x%04x" % addr
419
            raise errors.RadioError(msg)
420

    
421
        # UI Update
422
        status.cur = addr / BLOCK_SIZE
423
        status.msg = "Cloning to radio..."
424
        radio.status_fn(status)
425

    
426
    _exit_program_mode(radio)
427

    
428

    
429
def _do_map(chn, sclr, mary):
430
    """Set or Clear the chn (1-128) bit in mary[] word array map"""
431
    # chn is 1-based channel, sclr:1 = set, 0= = clear, 2= return state
432
    # mary[] is u8 array, but the map is by nibbles
433
    ndx = int(math.floor((chn - 1) / 8))
434
    bv = (chn - 1) % 8
435
    msk = 1 << bv
436
    mapbit = sclr
437
    if sclr == 1:    # Set the bit
438
        mary[ndx] = mary[ndx] | msk
439
    elif sclr == 0:  # clear
440
        mary[ndx] = mary[ndx] & (~ msk)     # ~ is complement
441
    else:       # return current bit state
442
        mapbit = 0
443
        if (mary[ndx] & msk) > 0:
444
            mapbit = 1
445
    return mapbit
446

    
447

    
448
@directory.register
449
class THUV88Radio(chirp_common.CloneModeRadio):
450
    """TYT UV88 Radio"""
451
    VENDOR = "TYT"
452
    MODEL = "TH-UV88"
453
    MODES = ['WFM', 'FM', 'NFM']
454
    TONES = chirp_common.TONES
455
    DTCS_CODES = chirp_common.DTCS_CODES
456
    NAME_LENGTH = 10
457
    DTMF_CHARS = list("0123456789ABCD*#")
458
    # 136-174, 400-480
459
    VALID_BANDS = [(136000000, 174000000), (400000000, 480000000)]
460

    
461
    # Valid chars on the LCD
462
    VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
463
        "`!\"#$%&'()*+,-./:;<=>?@[]^_"
464

    
465
    _magic0 = "\xFE\xFE\xEE\xEF\xE0" + "UV88" + "\xFD"
466
    _magic2 = "\xFE\xFE\xEE\xEF\xE2" + "UV88" + "\xFD"
467
    _magic3 = "\xFE\xFE\xEE\xEF\xE3" + "UV88" + "\xFD"
468
    _magic5 = "\xFE\xFE\xEE\xEF\xE5" + "UV88" + "\xFD"
469
    _fingerprint = "\xFE\xFE\xEF\xEE\xE1" + "UV88"
470

    
471

    
472
    @classmethod
473
    def get_prompts(cls):
474
        rp = chirp_common.RadioPrompts()
475
        rp.info = \
476
            (cls.VENDOR + ' ' + cls.MODEL + '\n')
477

    
478
        rp.pre_download = _(dedent("""\
479
            This is an early stage beta driver
480
            """))
481
        rp.pre_upload = _(dedent("""\
482
            This is an early stage beta driver - upload at your own risk
483
            """))
484
        return rp
485

    
486
    def get_features(self):
487
        rf = chirp_common.RadioFeatures()
488
        rf.has_settings = True
489
        rf.has_bank = False
490
        rf.has_comment = False
491
        rf.has_tuning_step = False      # Not as chan feature
492
        rf.valid_tuning_steps = STEPS
493
        rf.can_odd_split = True
494
        rf.has_name = True
495
        rf.has_offset = True
496
        rf.has_mode = True
497
        rf.has_dtcs = True
498
        rf.has_rx_dtcs = True
499
        rf.has_dtcs_polarity = True
500
        rf.has_ctone = True
501
        rf.has_cross = True
502
        rf.has_sub_devices = False
503
        rf.valid_name_length = self.NAME_LENGTH
504
        rf.valid_modes = self.MODES
505
        rf.valid_characters = self.VALID_CHARS
506
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
507
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
508
        rf.valid_cross_modes = ["Tone->Tone", "DTCS->", "->DTCS",
509
                                "Tone->DTCS", "DTCS->Tone", "->Tone",
510
                                "DTCS->DTCS"]
511
        rf.valid_skips = []
512
        rf.valid_power_levels = POWER_LEVELS
513
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES  # this is just to
514
        # get it working, not sure this is right
515
        rf.valid_bands = self.VALID_BANDS
516
        rf.memory_bounds = (1, 199)
517
        rf.valid_skips = ["", "S"]
518
        return rf
519

    
520
    def sync_in(self):
521
        """Download from radio"""
522
        try:
523
            data = _download(self)
524
        except errors.RadioError:
525
            # Pass through any real errors we raise
526
            raise
527
        except Exception:
528
            # If anything unexpected happens, make sure we raise
529
            # a RadioError and log the problem
530
            LOG.exception('Unexpected error during download')
531
            raise errors.RadioError('Unexpected error communicating '
532
                                    'with the radio')
533
        self._mmap = memmap.MemoryMap(data)
534
        self.process_mmap()
535

    
536
    def sync_out(self):
537
        """Upload to radio"""
538

    
539
        try:
540
            _upload(self)
541
        except Exception:
542
            # If anything unexpected happens, make sure we raise
543
            # a RadioError and log the problem
544
            LOG.exception('Unexpected error during upload')
545
            raise errors.RadioError('Unexpected error communicating '
546
                                    'with the radio')
547

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

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

    
555
    def set_memory(self, memory):
556
        """A value in a UI column for chan 'number' has been modified."""
557
        # update all raw channel memory values (_mem) from UI (mem)
558
        _mem = self._memobj.chan_mem[memory.number - 1]
559
        _name = self._memobj.chan_name[memory.number - 1]
560

    
561
        if memory.empty:
562
            _do_map(memory.number, 0, self._memobj.chan_avail.bitmap)
563
            return
564

    
565
        _do_map(memory.number, 1, self._memobj.chan_avail.bitmap)
566

    
567
        if memory.skip == "":
568
            _do_map(memory.number, 1, self._memobj.chan_skip.bitmap)
569
        else:
570
            _do_map(memory.number, 0, self._memobj.chan_skip.bitmap)
571

    
572
        return self._set_memory(memory, _mem, _name)
573

    
574
    def get_memory(self, number):
575
        # radio first channel is 1, mem map is base 0
576
        _mem = self._memobj.chan_mem[number - 1]
577
        _name = self._memobj.chan_name[number - 1]
578
        mem = chirp_common.Memory()
579
        mem.number = number
580

    
581
        # Determine if channel is empty
582

    
583
        if _do_map(number, 2, self._memobj.chan_avail.bitmap) == 0:
584
            mem.empty = True
585
            return mem
586

    
587
        if _do_map(mem.number, 2, self._memobj.chan_skip.bitmap) > 0:
588
            mem.skip = ""
589
        else:
590
            mem.skip = "S"
591

    
592
        return self._get_memory(mem, _mem, _name)
593

    
594
    def _get_memory(self, mem, _mem, _name):
595
        """Convert raw channel memory data into UI columns"""
596
        mem.extra = RadioSettingGroup("extra", "Extra")
597

    
598
        mem.empty = False
599
        # This function process both 'normal' and Freq up/down' entries
600
        mem.freq = int(_mem.rxfreq) * 10
601

    
602
        if _mem.txfreq == 0xFFFFFFFF:
603
            # TX freq not set
604
            mem.duplex = "off"
605
            mem.offset = 0
606
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 25000000:
607
            mem.duplex = "split"
608
            mem.offset = int(_mem.txfreq) * 10
609
        elif int(_mem.rxfreq) == int(_mem.txfreq):
610
            mem.duplex = ""
611
            mem.offset = 0
612
        else:
613
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) \
614
                and "-" or "+"
615
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
616

    
617
        mem.name = ""
618
        for i in range(6):   # 0 - 6
619
            mem.name += chr(_mem.name[i])
620
        for i in range(10):
621
            mem.name += chr(_name.extra_name[i])
622

    
623
        mem.name = mem.name.rstrip()    # remove trailing spaces
624

    
625
        # ########## TONE ##########
626

    
627
        if _mem.txtone > 2600:
628
            # All off
629
            txmode = ""
630
        elif _mem.txtone > 511:
631
            txmode = "Tone"
632
            mem.rtone = int(_mem.txtone) / 10.0
633
        else:
634
            # DTSC
635
            txmode = "DTCS"
636
            mem.dtcs = int(format(int(_mem.txtone), 'o'))
637

    
638
        if _mem.rxtone > 2600:
639
            rxmode = ""
640
        elif _mem.rxtone > 511:
641
            rxmode = "Tone"
642
            mem.ctone = int(_mem.rxtone) / 10.0
643
        else:
644
            rxmode = "DTCS"
645
            mem.rx_dtcs = int(format(int(_mem.rxtone), 'o'))
646

    
647
        mem.dtcs_polarity = ("N", "R")[_mem.encodeDSCI] + (
648
                             "N", "R")[_mem.decodeDSCI]
649

    
650
        mem.tmode = ""
651
        if txmode == "Tone" and not rxmode:
652
            mem.tmode = "Tone"
653
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
654
            mem.tmode = "TSQL"
655
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
656
            mem.tmode = "DTCS"
657
        elif rxmode or txmode:
658
            mem.tmode = "Cross"
659
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
660

    
661
        # ########## TONE ##########
662

    
663
        mem.mode = self.MODES[_mem.wide]
664
        mem.power = POWER_LEVELS[int(_mem.power)]
665

    
666
        b_lock = RadioSetting("b_lock", "B_Lock",
667
                              RadioSettingValueList(B_LOCK_LIST,
668
                                                    B_LOCK_LIST[_mem.b_lock]))
669
        mem.extra.append(b_lock)
670

    
671
        b_lock = RadioSetting("step", "Step",
672
                              RadioSettingValueList(LIST_STEPS,
673
                                                    LIST_STEPS[_mem.step]))
674
        mem.extra.append(b_lock)
675

    
676
        scramble_value = _mem.scramble
677
        if scramble_value >= 8:     # Looks like OFF is 0x0f ** CONFIRM
678
            scramble_value = 0
679
        scramble = RadioSetting("scramble", "Scramble",
680
                                RadioSettingValueList(SCRAMBLE_LIST,
681
                                                      SCRAMBLE_LIST[
682
                                                          scramble_value]))
683
        mem.extra.append(scramble)
684

    
685
        optsig = RadioSetting("signal", "Optional signaling",
686
                              RadioSettingValueList(
687
                                  OPTSIG_LIST,
688
                                  OPTSIG_LIST[_mem.signal]))
689
        mem.extra.append(optsig)
690

    
691
        rs = RadioSetting("pttid", "PTT ID",
692
                          RadioSettingValueList(PTTID_LIST,
693
                                                PTTID_LIST[_mem.pttid]))
694
        mem.extra.append(rs)
695

    
696
        return mem
697

    
698
    def _set_memory(self, mem, _mem, _name):
699
        # """Convert UI column data (mem) into MEM_FORMAT memory (_mem)."""
700

    
701
        _mem.rxfreq = mem.freq / 10
702
        if mem.duplex == "off":
703
            _mem.txfreq = 0xFFFFFFFF
704
        elif mem.duplex == "split":
705
            _mem.txfreq = mem.offset / 10
706
        elif mem.duplex == "+":
707
            _mem.txfreq = (mem.freq + mem.offset) / 10
708
        elif mem.duplex == "-":
709
            _mem.txfreq = (mem.freq - mem.offset) / 10
710
        else:
711
            _mem.txfreq = _mem.rxfreq
712

    
713
        out_name = mem.name.ljust(16)
714

    
715
        for i in range(6):   # 0 - 6
716
            _mem.name[i] = ord(out_name[i])
717
        for i in range(10):
718
            _name.extra_name[i] = ord(out_name[i+6])
719

    
720
        if mem.name != "":
721
            _mem.displayName = 1    # Name only displayed if this is set on
722
        else:
723
            _mem.displayName = 0
724

    
725
        rxmode = ""
726
        txmode = ""
727

    
728
        if mem.tmode == "Tone":
729
            txmode = "Tone"
730
        elif mem.tmode == "TSQL":
731
            rxmode = "Tone"
732
            txmode = "TSQL"
733
        elif mem.tmode == "DTCS":
734
            rxmode = "DTCSSQL"
735
            txmode = "DTCS"
736
        elif mem.tmode == "Cross":
737
            txmode, rxmode = mem.cross_mode.split("->", 1)
738

    
739
        if mem.dtcs_polarity[1] == "N":
740
            _mem.decodeDSCI = 0
741
        else:
742
            _mem.decodeDSCI = 1
743

    
744
        if rxmode == "":
745
            _mem.rxtone = 0xFFF
746
        elif rxmode == "Tone":
747
            _mem.rxtone = int(float(mem.ctone) * 10)
748
        elif rxmode == "DTCSSQL":
749
            _mem.rxtone = int(str(mem.dtcs), 8)
750
        elif rxmode == "DTCS":
751
            _mem.rxtone = int(str(mem.rx_dtcs), 8)
752

    
753
        if mem.dtcs_polarity[0] == "N":
754
            _mem.encodeDSCI = 0
755
        else:
756
            _mem.encodeDSCI = 1
757

    
758
        if txmode == "":
759
            _mem.txtone = 0xFFF
760
        elif txmode == "Tone":
761
            _mem.txtone = int(float(mem.rtone) * 10)
762
        elif txmode == "TSQL":
763
            _mem.txtone = int(float(mem.ctone) * 10)
764
        elif txmode == "DTCS":
765
            _mem.txtone = int(str(mem.dtcs), 8)
766

    
767
        _mem.wide = self.MODES.index(mem.mode)
768
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
769

    
770
        for element in mem.extra:
771
            setattr(_mem, element.get_name(), element.value)
772

    
773
        return
774

    
775
    def get_settings(self):
776
        """Translate the MEM_FORMAT structs into setstuf in the UI"""
777
        _settings = self._memobj.basicsettings
778
        _settings2 = self._memobj.settings2
779
        _workmode = self._memobj.workmodesettings
780

    
781
        basic = RadioSettingGroup("basic", "Basic Settings")
782
        group = RadioSettings(basic)
783

    
784
        # Menu 02 - TX Channel Select
785
        options = ["Last Channel", "Main Channel"]
786
        rx = RadioSettingValueList(options, options[_settings.txChSelect])
787
        rset = RadioSetting("basicsettings.txChSelect",
788
                            "Priority Transmit", rx)
789
        basic.append(rset)
790

    
791
        # Menu 03 - VOX Level
792
        rx = RadioSettingValueInteger(1, 7, _settings.voxLevel + 1)
793
        rset = RadioSetting("basicsettings.voxLevel", "Vox Level", rx)
794
        basic.append(rset)
795

    
796
        # Menu 05 - Squelch Level
797
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
798
        rx = RadioSettingValueList(options, options[_settings.sqlLevel])
799
        rset = RadioSetting("basicsettings.sqlLevel", "Squelch Level", rx)
800
        basic.append(rset)
801

    
802
        # Menu 06 - Dual Wait
803
        rx = RadioSettingValueBoolean(_settings.dualWait)
804
        rset = RadioSetting("basicsettings.dualWait", "Dual Wait/Standby", rx)
805
        basic.append(rset)
806

    
807
        # Menu 07 - LED Mode
808
        options = ["Off", "On", "Auto"]
809
        rx = RadioSettingValueList(options, options[_settings.ledMode])
810
        rset = RadioSetting("basicsettings.ledMode", "LED Display Mode", rx)
811
        basic.append(rset)
812

    
813
        # Menu 08 - Light
814
        options = ["%s" % x for x in range(1, 8)]
815
        rx = RadioSettingValueList(options, options[_settings.light])
816
        rset = RadioSetting("basicsettings.light",
817
                            "Background Light Color", rx)
818
        basic.append(rset)
819

    
820
        # Menu 09 - Beep
821
        rx = RadioSettingValueBoolean(_settings.beep)
822
        rset = RadioSetting("basicsettings.beep", "Keypad Beep", rx)
823
        basic.append(rset)
824

    
825
        # Menu 11 - TOT
826
        options = ["Off"] + ["%s seconds" % x for x in range(30, 300, 30)]
827
        rx = RadioSettingValueList(options, options[_settings.tot])
828
        rset = RadioSetting("basicsettings.tot",
829
                            "Transmission Time-out Timer", rx)
830
        basic.append(rset)
831

    
832
        # Menu 13 - VOX Switch
833
        rx = RadioSettingValueBoolean(_settings.voxSw)
834
        rset = RadioSetting("basicsettings.voxSw", "Vox Switch", rx)
835
        basic.append(rset)
836

    
837
        # Menu 14 - Roger
838
        rx = RadioSettingValueBoolean(_settings.roger)
839
        rset = RadioSetting("basicsettings.roger", "Roger Beep", rx)
840
        basic.append(rset)
841

    
842
        # Menu 16 - Save Mode
843
        options = ["Off", "1:1", "1:2", "1:4"]
844
        rx = RadioSettingValueList(options, options[_settings.saveMode])
845
        rset = RadioSetting("basicsettings.saveMode", "Battery Save Mode", rx)
846
        basic.append(rset)
847

    
848
        # Menu 17 - Scan Type
849
        if self.MODEL == "QRZ-1":
850
            options = ["Time", "Carrier", "Stop"]
851
        else:
852
            options = ["CO", "TO", "SE"]
853
        rx = RadioSettingValueList(options, options[_settings.scanType])
854
        rset = RadioSetting("basicsettings.scanType", "Scan Type", rx)
855
        basic.append(rset)
856

    
857
        # Menu 18 - Key Lock
858
        rx = RadioSettingValueBoolean(_settings.keylock)
859
        rset = RadioSetting("basicsettings.keylock", "Auto Key Lock", rx)
860
        basic.append(rset)
861

    
862
        if self.MODEL != "QRZ-1":
863
            # Menu 19 - SW Audio
864
            rx = RadioSettingValueBoolean(_settings.swAudio)
865
            rset = RadioSetting("basicsettings.swAudio", "Voice Prompts", rx)
866
            basic.append(rset)
867

    
868
        # Menu 20 - Intro Screen
869
        options = ["Off", "Voltage", "Character String"]
870
        rx = RadioSettingValueList(options, options[_settings.introScreen])
871
        rset = RadioSetting("basicsettings.introScreen", "Intro Screen", rx)
872
        basic.append(rset)
873

    
874
        # Menu 32 - Key Mode
875
        options = ["ALL", "PTT", "KEY", "Key & Side Key"]
876
        rx = RadioSettingValueList(options, options[_settings.keyMode])
877
        rset = RadioSetting("basicsettings.keyMode", "Key Lock Mode", rx)
878
        basic.append(rset)
879

    
880
        # Menu 33 - Display Mode
881
        options = ['Frequency', 'Channel #', 'Name']
882
        rx = RadioSettingValueList(options, options[_settings.disMode])
883
        rset = RadioSetting("basicsettings.disMode", "Display Mode", rx)
884
        basic.append(rset)
885

    
886
        # Menu 34 - FM Dual Wait
887
        rx = RadioSettingValueBoolean(_settings.radioMoni)
888
        rset = RadioSetting("basicsettings.radioMoni", "Radio Monitor", rx)
889
        basic.append(rset)
890

    
891
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
892
        group.append(advanced)
893

    
894
        # software only
895
        options = ['Off', 'Frequency']
896
        rx = RadioSettingValueList(options, options[_settings.endToneElim])
897
        rset = RadioSetting("basicsettings.endToneElim", "End Tone Elim", rx)
898
        advanced.append(rset)
899

    
900
        # software only
901
        name = ""
902
        for i in range(15):  # 0 - 15
903
            name += chr(self._memobj.openradioname.name1[i])
904
        name = name.rstrip()  # remove trailing spaces
905

    
906
        rx = RadioSettingValueString(0, 15, name)
907
        rset = RadioSetting("openradioname.name1", "Intro Line 1", rx)
908
        advanced.append(rset)
909

    
910
        # software only
911
        name = ""
912
        for i in range(15):  # 0 - 15
913
            name += chr(self._memobj.openradioname.name2[i])
914
        name = name.rstrip()  # remove trailing spaces
915

    
916
        rx = RadioSettingValueString(0, 15, name)
917
        rset = RadioSetting("openradioname.name2", "Intro Line 2", rx)
918
        advanced.append(rset)
919

    
920
        # software only
921
        options = ['0.5S', '1.0S', '1.5S', '2.0S', '2.5S', '3.0S', '3.5S',
922
                   '4.0S', '4.5S', '5.0S']
923
        rx = RadioSettingValueList(options, options[_settings.voxDelay])
924
        rset = RadioSetting("basicsettings.voxDelay", "VOX Delay", rx)
925
        advanced.append(rset)
926

    
927
        options = ['Unlocked', 'Unknown 1', 'Unknown 2', 'EU', 'US']
928
        # extend option list with unknown description for values 5 - 15.
929
        for ix in range(len(options), _settings2.region + 1):
930
            item_to_add = 'Unknown {region_code}'.format(region_code=ix)
931
            options.append(item_to_add)
932
        # log unknown region codes greater than 4
933
        if _settings2.region > 4:
934
            LOG.debug("Unknown region code: {value}".
935
                      format(value=_settings2.region))
936
        rx = RadioSettingValueList(options, options[_settings2.region])
937
        rx.set_mutable(False)
938
        rset = RadioSetting("settings2.region", "Region", rx)
939
        advanced.append(rset)
940

    
941
        workmode = RadioSettingGroup("workmode", "Work Mode Settings")
942
        group.append(workmode)
943

    
944
        # Toggle with [#] key
945
        options = ["Frequency", "Channel"]
946
        rx = RadioSettingValueList(options, options[_workmode.vfomrmode])
947
        rset = RadioSetting("workmodesettings.vfomrmode", "VFO/MR Mode", rx)
948
        workmode.append(rset)
949

    
950
        # Toggle with [#] key
951
        options = ["Frequency", "Channel"]
952
        rx = RadioSettingValueList(options, options[_workmode.vfomrmodeb])
953
        rset = RadioSetting("workmodesettings.vfomrmodeb",
954
                            "VFO/MR Mode B (BQ1.41+)", rx)
955
        workmode.append(rset)
956

    
957
        # Toggle with [A/B] key
958
        options = ["B", "A"]
959
        rx = RadioSettingValueList(options, options[_workmode.ab])
960
        rset = RadioSetting("workmodesettings.ab", "A/B Select", rx)
961
        workmode.append(rset)
962

    
963
        rx = RadioSettingValueInteger(1, 199, _workmode.mrAch + 1)
964
        rset = RadioSetting("workmodesettings.mrAch", "MR A Channel #", rx)
965
        workmode.append(rset)
966

    
967
        rx = RadioSettingValueInteger(1, 199, _workmode.mrBch + 1)
968
        rset = RadioSetting("workmodesettings.mrBch", "MR B Channel #", rx)
969
        workmode.append(rset)
970

    
971
        return group       # END get_settings()
972

    
973
    def set_settings(self, settings):
974
        _settings = self._memobj.basicsettings
975
        _mem = self._memobj
976
        for element in settings:
977
            if not isinstance(element, RadioSetting):
978
                self.set_settings(element)
979
                continue
980
            else:
981
                try:
982
                    name = element.get_name()
983
                    if "." in name:
984
                        bits = name.split(".")
985
                        obj = self._memobj
986
                        for bit in bits[:-1]:
987
                            if "/" in bit:
988
                                bit, index = bit.split("/", 1)
989
                                index = int(index)
990
                                obj = getattr(obj, bit)[index]
991
                            else:
992
                                obj = getattr(obj, bit)
993
                        setting = bits[-1]
994
                    else:
995
                        obj = _settings
996
                        setting = element.get_name()
997

    
998
                    if element.has_apply_callback():
999
                        LOG.debug("Using apply callback")
1000
                        element.run_apply_callback()
1001
                    elif setting == "mrAch" or setting == "mrBch":
1002
                        setattr(obj, setting, int(element.value) - 1)
1003
                    elif setting == "voxLevel":
1004
                        setattr(obj, setting, int(element.value) - 1)
1005
                    elif element.value.get_mutable():
1006
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1007
                        setattr(obj, setting, element.value)
1008
                except Exception, e:
1009
                    LOG.debug(element.get_name())
1010
                    raise
1011

    
1012

    
1013
@directory.register
1014
class RT85(THUV88Radio):
1015
    VENDOR = "Retevis"
1016
    MODEL = "RT85"
1017

    
1018

    
1019
@directory.register
1020
class QRZ1(THUV88Radio):
1021
    VENDOR = "Explorer"
1022
    MODEL = "QRZ-1"
1023

    
1024
    _magic0 = "\xFE\xFE\xEE\xEF\xE0" + "UV78" + "\xFD"
1025
    _magic2 = "\xFE\xFE\xEE\xEF\xE2" + "UV78" + "\xFD"
1026
    _magic3 = "\xFE\xFE\xEE\xEF\xE3" + "UV78" + "\xFD"
1027
    _magic5 = "\xFE\xFE\xEE\xEF\xE5" + "UV78" + "\xFD"
1028
    _fingerprint = "\xFE\xFE\xEF\xEE\xE1" + "UV78"
(44-44/57)