Project

General

Profile

New Model #10023 » th_uv88 - qrz_1_poc2.py

Jim Unroe, 09/22/2022 05:48 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
    ack = _rawrecv(radio, 7)
321
    if ack != "\xFE\xFE\xEF\xEE\xE6\x00\xFD":
322
        _exit_program_mode(radio)
323
        if ack:
324
            LOG.debug(repr(ack))
325
        raise errors.RadioError("Radio did not respond as expected (B)")
326

    
327

    
328
def _download(radio):
329
    """Get the memory map"""
330

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

    
334
    # Enter read mode
335
    magic = radio._magic2
336
    _rawsend(radio, magic)
337
    ack = _rawrecv(radio, 7)
338
    if ack != "\xFE\xFE\xEF\xEE\xE6\x00\xFD":
339
        _exit_program_mode(radio)
340
        if ack:
341
            LOG.debug(repr(ack))
342
        raise errors.RadioError("Radio did not respond to enter read mode")
343

    
344
    # UI progress
345
    status = chirp_common.Status()
346
    status.cur = 0
347
    status.max = MEM_SIZE / BLOCK_SIZE
348
    status.msg = "Cloning from radio..."
349
    radio.status_fn(status)
350

    
351
    data = ""
352
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
353
        frame = _make_read_frame(addr, BLOCK_SIZE)
354
        # DEBUG
355
        LOG.debug("Frame=" + util.hexprint(frame))
356

    
357
        # Sending the read request
358
        _rawsend(radio, frame)
359

    
360
        # Now we read data
361
        d = _recv(radio, addr, BLOCK_SIZE + 13)
362

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

    
365
        if not d.startswith("\xFE\xFE\xEF\xEE\xE4"):
366
            LOG.warning("Incorrect start")
367
        if not d.endswith("\xFD"):
368
            LOG.warning("Incorrect end")
369
        # could validate the block data
370

    
371
        # Aggregate the data
372
        data += d[11:-2]
373

    
374
        # UI Update
375
        status.cur = addr / BLOCK_SIZE
376
        status.msg = "Cloning from radio..."
377
        radio.status_fn(status)
378

    
379
    _exit_program_mode(radio)
380

    
381
    return data
382

    
383

    
384
def _upload(radio):
385
    """Upload procedure"""
386
    # Put radio in program mode and identify it
387
    _do_ident(radio)
388

    
389
    magic = radio._magic3
390
    _rawsend(radio, magic)
391
    ack = _rawrecv(radio, 7)
392
    if ack != "\xFE\xFE\xEF\xEE\xE6\x00\xFD":
393
        _exit_program_mode(radio)
394
        if ack:
395
            LOG.debug(repr(ack))
396
        raise errors.RadioError("Radio did not respond to enter write mode")
397

    
398
    # UI progress
399
    status = chirp_common.Status()
400
    status.cur = 0
401
    status.max = MEM_SIZE / BLOCK_SIZE
402
    status.msg = "Cloning to radio..."
403
    radio.status_fn(status)
404

    
405
    # The fun starts here
406
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
407
        # Official programmer skips writing these memory locations
408
        if addr >= 0x1680 and addr < 0x1940:
409
            continue
410

    
411
        # Sending the data
412
        data = radio.get_mmap()[addr:addr + BLOCK_SIZE]
413

    
414
        frame = _make_write_frame(addr, BLOCK_SIZE, data)
415
        LOG.warning("Frame:%s:" % util.hexprint(frame))
416
        _rawsend(radio, frame)
417

    
418
        ack = _rawrecv(radio, 7)
419
        LOG.debug("Response Data= " + util.hexprint(ack))
420

    
421
        if not ack.startswith("\xFE\xFE\xEF\xEE\xE6\x00\xFD"):
422
            LOG.warning("Unexpected response")
423
            _exit_program_mode(radio)
424
            msg = "Bad ack writing block 0x%04x" % addr
425
            raise errors.RadioError(msg)
426

    
427
        # UI Update
428
        status.cur = addr / BLOCK_SIZE
429
        status.msg = "Cloning to radio..."
430
        radio.status_fn(status)
431

    
432
    _exit_program_mode(radio)
433

    
434

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

    
453

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

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

    
471
    _magic0 = "\xFE\xFE\xEE\xEF\xE0" + "UV88" + "\xFD"
472
    _magic2 = "\xFE\xFE\xEE\xEF\xE2" + "UV88" + "\xFD"
473
    _magic3 = "\xFE\xFE\xEE\xEF\xE3" + "UV88" + "\xFD"
474
    _magic5 = "\xFE\xFE\xEE\xEF\xE5" + "UV88" + "\xFD"
475
    _fingerprint = "\xFE\xFE\xEF\xEE\xE1" + "UV88"
476

    
477

    
478
    @classmethod
479
    def get_prompts(cls):
480
        rp = chirp_common.RadioPrompts()
481
        rp.info = \
482
            (cls.VENDOR + ' ' + cls.MODEL + '\n')
483

    
484
        rp.pre_download = _(dedent("""\
485
            This is an early stage beta driver
486
            """))
487
        rp.pre_upload = _(dedent("""\
488
            This is an early stage beta driver - upload at your own risk
489
            """))
490
        return rp
491

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

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

    
542
    def sync_out(self):
543
        """Upload to radio"""
544

    
545
        try:
546
            _upload(self)
547
        except Exception:
548
            # If anything unexpected happens, make sure we raise
549
            # a RadioError and log the problem
550
            LOG.exception('Unexpected error during upload')
551
            raise errors.RadioError('Unexpected error communicating '
552
                                    'with the radio')
553

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

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

    
561
    def set_memory(self, memory):
562
        """A value in a UI column for chan 'number' has been modified."""
563
        # update all raw channel memory values (_mem) from UI (mem)
564
        _mem = self._memobj.chan_mem[memory.number - 1]
565
        _name = self._memobj.chan_name[memory.number - 1]
566

    
567
        if memory.empty:
568
            _do_map(memory.number, 0, self._memobj.chan_avail.bitmap)
569
            return
570

    
571
        _do_map(memory.number, 1, self._memobj.chan_avail.bitmap)
572

    
573
        if memory.skip == "":
574
            _do_map(memory.number, 1, self._memobj.chan_skip.bitmap)
575
        else:
576
            _do_map(memory.number, 0, self._memobj.chan_skip.bitmap)
577

    
578
        return self._set_memory(memory, _mem, _name)
579

    
580
    def get_memory(self, number):
581
        # radio first channel is 1, mem map is base 0
582
        _mem = self._memobj.chan_mem[number - 1]
583
        _name = self._memobj.chan_name[number - 1]
584
        mem = chirp_common.Memory()
585
        mem.number = number
586

    
587
        # Determine if channel is empty
588

    
589
        if _do_map(number, 2, self._memobj.chan_avail.bitmap) == 0:
590
            mem.empty = True
591
            return mem
592

    
593
        if _do_map(mem.number, 2, self._memobj.chan_skip.bitmap) > 0:
594
            mem.skip = ""
595
        else:
596
            mem.skip = "S"
597

    
598
        return self._get_memory(mem, _mem, _name)
599

    
600
    def _get_memory(self, mem, _mem, _name):
601
        """Convert raw channel memory data into UI columns"""
602
        mem.extra = RadioSettingGroup("extra", "Extra")
603

    
604
        mem.empty = False
605
        # This function process both 'normal' and Freq up/down' entries
606
        mem.freq = int(_mem.rxfreq) * 10
607

    
608
        if _mem.txfreq == 0xFFFFFFFF:
609
            # TX freq not set
610
            mem.duplex = "off"
611
            mem.offset = 0
612
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 25000000:
613
            mem.duplex = "split"
614
            mem.offset = int(_mem.txfreq) * 10
615
        elif int(_mem.rxfreq) == int(_mem.txfreq):
616
            mem.duplex = ""
617
            mem.offset = 0
618
        else:
619
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) \
620
                and "-" or "+"
621
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
622

    
623
        mem.name = ""
624
        for i in range(6):   # 0 - 6
625
            mem.name += chr(_mem.name[i])
626
        for i in range(10):
627
            mem.name += chr(_name.extra_name[i])
628

    
629
        mem.name = mem.name.rstrip()    # remove trailing spaces
630

    
631
        # ########## TONE ##########
632

    
633
        if _mem.txtone > 2600:
634
            # All off
635
            txmode = ""
636
        elif _mem.txtone > 511:
637
            txmode = "Tone"
638
            mem.rtone = int(_mem.txtone) / 10.0
639
        else:
640
            # DTSC
641
            txmode = "DTCS"
642
            mem.dtcs = int(format(int(_mem.txtone), 'o'))
643

    
644
        if _mem.rxtone > 2600:
645
            rxmode = ""
646
        elif _mem.rxtone > 511:
647
            rxmode = "Tone"
648
            mem.ctone = int(_mem.rxtone) / 10.0
649
        else:
650
            rxmode = "DTCS"
651
            mem.rx_dtcs = int(format(int(_mem.rxtone), 'o'))
652

    
653
        mem.dtcs_polarity = ("N", "R")[_mem.encodeDSCI] + (
654
                             "N", "R")[_mem.decodeDSCI]
655

    
656
        mem.tmode = ""
657
        if txmode == "Tone" and not rxmode:
658
            mem.tmode = "Tone"
659
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
660
            mem.tmode = "TSQL"
661
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
662
            mem.tmode = "DTCS"
663
        elif rxmode or txmode:
664
            mem.tmode = "Cross"
665
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
666

    
667
        # ########## TONE ##########
668

    
669
        mem.mode = self.MODES[_mem.wide]
670
        mem.power = POWER_LEVELS[int(_mem.power)]
671

    
672
        b_lock = RadioSetting("b_lock", "B_Lock",
673
                              RadioSettingValueList(B_LOCK_LIST,
674
                                                    B_LOCK_LIST[_mem.b_lock]))
675
        mem.extra.append(b_lock)
676

    
677
        b_lock = RadioSetting("step", "Step",
678
                              RadioSettingValueList(LIST_STEPS,
679
                                                    LIST_STEPS[_mem.step]))
680
        mem.extra.append(b_lock)
681

    
682
        scramble_value = _mem.scramble
683
        if scramble_value >= 8:     # Looks like OFF is 0x0f ** CONFIRM
684
            scramble_value = 0
685
        scramble = RadioSetting("scramble", "Scramble",
686
                                RadioSettingValueList(SCRAMBLE_LIST,
687
                                                      SCRAMBLE_LIST[
688
                                                          scramble_value]))
689
        mem.extra.append(scramble)
690

    
691
        optsig = RadioSetting("signal", "Optional signaling",
692
                              RadioSettingValueList(
693
                                  OPTSIG_LIST,
694
                                  OPTSIG_LIST[_mem.signal]))
695
        mem.extra.append(optsig)
696

    
697
        rs = RadioSetting("pttid", "PTT ID",
698
                          RadioSettingValueList(PTTID_LIST,
699
                                                PTTID_LIST[_mem.pttid]))
700
        mem.extra.append(rs)
701

    
702
        return mem
703

    
704
    def _set_memory(self, mem, _mem, _name):
705
        # """Convert UI column data (mem) into MEM_FORMAT memory (_mem)."""
706

    
707
        _mem.rxfreq = mem.freq / 10
708
        if mem.duplex == "off":
709
            _mem.txfreq = 0xFFFFFFFF
710
        elif mem.duplex == "split":
711
            _mem.txfreq = mem.offset / 10
712
        elif mem.duplex == "+":
713
            _mem.txfreq = (mem.freq + mem.offset) / 10
714
        elif mem.duplex == "-":
715
            _mem.txfreq = (mem.freq - mem.offset) / 10
716
        else:
717
            _mem.txfreq = _mem.rxfreq
718

    
719
        out_name = mem.name.ljust(16)
720

    
721
        for i in range(6):   # 0 - 6
722
            _mem.name[i] = ord(out_name[i])
723
        for i in range(10):
724
            _name.extra_name[i] = ord(out_name[i+6])
725

    
726
        if mem.name != "":
727
            _mem.displayName = 1    # Name only displayed if this is set on
728
        else:
729
            _mem.displayName = 0
730

    
731
        rxmode = ""
732
        txmode = ""
733

    
734
        if mem.tmode == "Tone":
735
            txmode = "Tone"
736
        elif mem.tmode == "TSQL":
737
            rxmode = "Tone"
738
            txmode = "TSQL"
739
        elif mem.tmode == "DTCS":
740
            rxmode = "DTCSSQL"
741
            txmode = "DTCS"
742
        elif mem.tmode == "Cross":
743
            txmode, rxmode = mem.cross_mode.split("->", 1)
744

    
745
        if mem.dtcs_polarity[1] == "N":
746
            _mem.decodeDSCI = 0
747
        else:
748
            _mem.decodeDSCI = 1
749

    
750
        if rxmode == "":
751
            _mem.rxtone = 0xFFF
752
        elif rxmode == "Tone":
753
            _mem.rxtone = int(float(mem.ctone) * 10)
754
        elif rxmode == "DTCSSQL":
755
            _mem.rxtone = int(str(mem.dtcs), 8)
756
        elif rxmode == "DTCS":
757
            _mem.rxtone = int(str(mem.rx_dtcs), 8)
758

    
759
        if mem.dtcs_polarity[0] == "N":
760
            _mem.encodeDSCI = 0
761
        else:
762
            _mem.encodeDSCI = 1
763

    
764
        if txmode == "":
765
            _mem.txtone = 0xFFF
766
        elif txmode == "Tone":
767
            _mem.txtone = int(float(mem.rtone) * 10)
768
        elif txmode == "TSQL":
769
            _mem.txtone = int(float(mem.ctone) * 10)
770
        elif txmode == "DTCS":
771
            _mem.txtone = int(str(mem.dtcs), 8)
772

    
773
        _mem.wide = self.MODES.index(mem.mode)
774
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
775

    
776
        for element in mem.extra:
777
            setattr(_mem, element.get_name(), element.value)
778

    
779
        return
780

    
781
    def get_settings(self):
782
        """Translate the MEM_FORMAT structs into setstuf in the UI"""
783
        _settings = self._memobj.basicsettings
784
        _settings2 = self._memobj.settings2
785
        _workmode = self._memobj.workmodesettings
786

    
787
        basic = RadioSettingGroup("basic", "Basic Settings")
788
        group = RadioSettings(basic)
789

    
790
        # Menu 02 - TX Channel Select
791
        options = ["Last Channel", "Main Channel"]
792
        rx = RadioSettingValueList(options, options[_settings.txChSelect])
793
        rset = RadioSetting("basicsettings.txChSelect",
794
                            "Priority Transmit", rx)
795
        basic.append(rset)
796

    
797
        # Menu 03 - VOX Level
798
        rx = RadioSettingValueInteger(1, 7, _settings.voxLevel + 1)
799
        rset = RadioSetting("basicsettings.voxLevel", "Vox Level", rx)
800
        basic.append(rset)
801

    
802
        # Menu 05 - Squelch Level
803
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
804
        rx = RadioSettingValueList(options, options[_settings.sqlLevel])
805
        rset = RadioSetting("basicsettings.sqlLevel", "Squelch Level", rx)
806
        basic.append(rset)
807

    
808
        # Menu 06 - Dual Wait
809
        rx = RadioSettingValueBoolean(_settings.dualWait)
810
        rset = RadioSetting("basicsettings.dualWait", "Dual Wait/Standby", rx)
811
        basic.append(rset)
812

    
813
        # Menu 07 - LED Mode
814
        options = ["Off", "On", "Auto"]
815
        rx = RadioSettingValueList(options, options[_settings.ledMode])
816
        rset = RadioSetting("basicsettings.ledMode", "LED Display Mode", rx)
817
        basic.append(rset)
818

    
819
        # Menu 08 - Light
820
        options = ["%s" % x for x in range(1, 8)]
821
        rx = RadioSettingValueList(options, options[_settings.light])
822
        rset = RadioSetting("basicsettings.light",
823
                            "Background Light Color", rx)
824
        basic.append(rset)
825

    
826
        # Menu 09 - Beep
827
        rx = RadioSettingValueBoolean(_settings.beep)
828
        rset = RadioSetting("basicsettings.beep", "Keypad Beep", rx)
829
        basic.append(rset)
830

    
831
        # Menu 11 - TOT
832
        options = ["Off"] + ["%s seconds" % x for x in range(30, 300, 30)]
833
        rx = RadioSettingValueList(options, options[_settings.tot])
834
        rset = RadioSetting("basicsettings.tot",
835
                            "Transmission Time-out Timer", rx)
836
        basic.append(rset)
837

    
838
        # Menu 13 - VOX Switch
839
        rx = RadioSettingValueBoolean(_settings.voxSw)
840
        rset = RadioSetting("basicsettings.voxSw", "Vox Switch", rx)
841
        basic.append(rset)
842

    
843
        # Menu 14 - Roger
844
        rx = RadioSettingValueBoolean(_settings.roger)
845
        rset = RadioSetting("basicsettings.roger", "Roger Beep", rx)
846
        basic.append(rset)
847

    
848
        # Menu 16 - Save Mode
849
        options = ["Off", "1:1", "1:2", "1:4"]
850
        rx = RadioSettingValueList(options, options[_settings.saveMode])
851
        rset = RadioSetting("basicsettings.saveMode", "Battery Save Mode", rx)
852
        basic.append(rset)
853

    
854
        # Menu 17 - Scan Type
855
        options = ["CO", "TO", "SE"]
856
        rx = RadioSettingValueList(options, options[_settings.scanType])
857
        rset = RadioSetting("basicsettings.scanType", "Scan Type", rx)
858
        basic.append(rset)
859

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

    
865
        # Menu 19 - SW Audio
866
        rx = RadioSettingValueBoolean(_settings.swAudio)
867
        rset = RadioSetting("basicsettings.swAudio", "Voice Prompts", rx)
868
        basic.append(rset)
869

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

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

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

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

    
893
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
894
        group.append(advanced)
895

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

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

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

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

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

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

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

    
943
        workmode = RadioSettingGroup("workmode", "Work Mode Settings")
944
        group.append(workmode)
945

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

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

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

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

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

    
973
        return group       # END get_settings()
974

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

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

    
1014

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

    
1020

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

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