Project

General

Profile

New Model #10023 » th_uv88 - qrz_1_poc5.py

Jim Unroe, 09/28/2022 10:23 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
struct fm_chn {
190
  ul32 rxfreq;
191
};
192

    
193
#seekto 0x2180;
194
struct fm_chn fm_stations[24];
195

    
196
#seekto 0x021E0;
197
struct {
198
  u8  fmset[4];
199
} fmmap;
200

    
201
#seekto 0x21E4;
202
struct {
203
  ul32 fmcur;
204
} fmfrqs;
205

    
206
"""
207

    
208
MEM_SIZE = 0x22A0
209
BLOCK_SIZE = 0x20
210
STIMEOUT = 2
211
BAUDRATE = 57600
212

    
213
# Channel power: 3 levels
214
POWER_LEVELS = [chirp_common.PowerLevel("High", watts=5.00),
215
                chirp_common.PowerLevel("Mid", watts=2.50),
216
                chirp_common.PowerLevel("Low", watts=0.50)]
217

    
218
SCRAMBLE_LIST = ["OFF", "1", "2", "3", "4", "5", "6", "7", "8"]
219
B_LOCK_LIST = ["OFF", "Sub", "Carrier"]
220
OPTSIG_LIST = ["OFF", "DTMF", "2TONE", "5TONE"]
221
PTTID_LIST = ["Off", "BOT", "EOT", "Both"]
222
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0, 50.0, 100.0]
223
LIST_STEPS = [str(x) for x in STEPS]
224

    
225

    
226
def _clean_buffer(radio):
227
    radio.pipe.timeout = 0.005
228
    junk = radio.pipe.read(256)
229
    radio.pipe.timeout = STIMEOUT
230
    if junk:
231
        LOG.debug("Got %i bytes of junk before starting" % len(junk))
232

    
233

    
234
def _rawrecv(radio, amount):
235
    """Raw read from the radio device"""
236
    data = ""
237
    try:
238
        data = radio.pipe.read(amount)
239
    except Exception:
240
        _exit_program_mode(radio)
241
        msg = "Generic error reading data from radio; check your cable."
242
        raise errors.RadioError(msg)
243

    
244
    if len(data) != amount:
245
        _exit_program_mode(radio)
246
        msg = "Error reading from radio: not the amount of data we want."
247
        raise errors.RadioError(msg)
248

    
249
    return data
250

    
251

    
252
def _rawsend(radio, data):
253
    """Raw send to the radio device"""
254
    try:
255
        radio.pipe.write(data)
256
    except Exception:
257
        raise errors.RadioError("Error sending data to radio")
258

    
259

    
260
def _make_read_frame(addr, length):
261
    frame = "\xFE\xFE\xEE\xEF\xEB"
262
    """Pack the info in the header format"""
263
    frame += struct.pack(">ih", addr, length)
264

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

    
269

    
270
def _make_write_frame(addr, length, data=""):
271
    frame = "\xFE\xFE\xEE\xEF\xE4"
272

    
273
    """Pack the info in the header format"""
274
    output = struct.pack(">ih", addr, length)
275
    # Add the data if set
276
    if len(data) != 0:
277
        output += data
278

    
279
    frame += output
280
    frame += _calculate_checksum(output)
281

    
282
    frame += "\xFD"
283
    # Return the data
284
    return frame
285

    
286

    
287
def _calculate_checksum(data):
288
    num = 0
289
    for x in range(0, len(data)):
290
        num = (num + ord(data[x])) % 256
291

    
292
    if num == 0:
293
        return chr(0)
294

    
295
    return chr(256 - num)
296

    
297

    
298
def _recv(radio, addr, length):
299
    """Get data from the radio """
300

    
301
    data = _rawrecv(radio, length)
302

    
303
    # DEBUG
304
    LOG.info("Response:")
305
    LOG.debug(util.hexprint(data))
306

    
307
    return data
308

    
309

    
310
def _do_ident(radio):
311
    """Put the radio in PROGRAM mode & identify it"""
312
    radio.pipe.baudrate = BAUDRATE
313
    radio.pipe.parity = "N"
314
    radio.pipe.timeout = STIMEOUT
315

    
316
    # Flush input buffer
317
    _clean_buffer(radio)
318

    
319
    # Ident radio
320
    magic = radio._magic0
321
    _rawsend(radio, magic)
322
    ack = _rawrecv(radio, 36)
323

    
324
    if not ack.startswith(radio._fingerprint) or not ack.endswith("\xFD"):
325
        _exit_program_mode(radio)
326
        if ack:
327
            LOG.debug(repr(ack))
328
        raise errors.RadioError("Radio did not respond as expected (A)")
329

    
330
    return True
331

    
332

    
333
def _exit_program_mode(radio):
334
    # This may be the last part of a read
335
    magic = radio._magic5
336
    _rawsend(radio, magic)
337
    _clean_buffer(radio)
338

    
339

    
340
def _download(radio):
341
    """Get the memory map"""
342

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

    
346
    # Enter read mode
347
    magic = radio._magic2
348
    _rawsend(radio, magic)
349
    ack = _rawrecv(radio, 7)
350
    if ack != "\xFE\xFE\xEF\xEE\xE6\x00\xFD":
351
        _exit_program_mode(radio)
352
        if ack:
353
            LOG.debug(repr(ack))
354
        raise errors.RadioError("Radio did not respond to enter read mode")
355

    
356
    # UI progress
357
    status = chirp_common.Status()
358
    status.cur = 0
359
    status.max = MEM_SIZE / BLOCK_SIZE
360
    status.msg = "Cloning from radio..."
361
    radio.status_fn(status)
362

    
363
    data = ""
364
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
365
        frame = _make_read_frame(addr, BLOCK_SIZE)
366
        # DEBUG
367
        LOG.debug("Frame=" + util.hexprint(frame))
368

    
369
        # Sending the read request
370
        _rawsend(radio, frame)
371

    
372
        # Now we read data
373
        d = _recv(radio, addr, BLOCK_SIZE + 13)
374

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

    
377
        if not d.startswith("\xFE\xFE\xEF\xEE\xE4"):
378
            LOG.warning("Incorrect start")
379
        if not d.endswith("\xFD"):
380
            LOG.warning("Incorrect end")
381
        # could validate the block data
382

    
383
        # Aggregate the data
384
        data += d[11:-2]
385

    
386
        # UI Update
387
        status.cur = addr / BLOCK_SIZE
388
        status.msg = "Cloning from radio..."
389
        radio.status_fn(status)
390

    
391
    _exit_program_mode(radio)
392

    
393
    return data
394

    
395

    
396
def _upload(radio):
397
    """Upload procedure"""
398
    # Put radio in program mode and identify it
399
    _do_ident(radio)
400

    
401
    magic = radio._magic3
402
    _rawsend(radio, magic)
403
    ack = _rawrecv(radio, 7)
404
    if ack != "\xFE\xFE\xEF\xEE\xE6\x00\xFD":
405
        _exit_program_mode(radio)
406
        if ack:
407
            LOG.debug(repr(ack))
408
        raise errors.RadioError("Radio did not respond to enter write mode")
409

    
410
    # UI progress
411
    status = chirp_common.Status()
412
    status.cur = 0
413
    status.max = MEM_SIZE / BLOCK_SIZE
414
    status.msg = "Cloning to radio..."
415
    radio.status_fn(status)
416

    
417
    # The fun starts here
418
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
419
        # Official programmer skips writing these memory locations
420
        if addr >= 0x1680 and addr < 0x1940:
421
            continue
422

    
423
        # Sending the data
424
        data = radio.get_mmap()[addr:addr + BLOCK_SIZE]
425

    
426
        frame = _make_write_frame(addr, BLOCK_SIZE, data)
427
        LOG.warning("Frame:%s:" % util.hexprint(frame))
428
        _rawsend(radio, frame)
429

    
430
        ack = _rawrecv(radio, 7)
431
        LOG.debug("Response Data= " + util.hexprint(ack))
432

    
433
        if not ack.startswith("\xFE\xFE\xEF\xEE\xE6\x00\xFD"):
434
            LOG.warning("Unexpected response")
435
            _exit_program_mode(radio)
436
            msg = "Bad ack writing block 0x%04x" % addr
437
            raise errors.RadioError(msg)
438

    
439
        # UI Update
440
        status.cur = addr / BLOCK_SIZE
441
        status.msg = "Cloning to radio..."
442
        radio.status_fn(status)
443

    
444
    _exit_program_mode(radio)
445

    
446

    
447
def _do_map(chn, sclr, mary):
448
    """Set or Clear the chn (1-128) bit in mary[] word array map"""
449
    # chn is 1-based channel, sclr:1 = set, 0= = clear, 2= return state
450
    # mary[] is u8 array, but the map is by nibbles
451
    ndx = int(math.floor((chn - 1) / 8))
452
    bv = (chn - 1) % 8
453
    msk = 1 << bv
454
    mapbit = sclr
455
    if sclr == 1:    # Set the bit
456
        mary[ndx] = mary[ndx] | msk
457
    elif sclr == 0:  # clear
458
        mary[ndx] = mary[ndx] & (~ msk)     # ~ is complement
459
    else:       # return current bit state
460
        mapbit = 0
461
        if (mary[ndx] & msk) > 0:
462
            mapbit = 1
463
    return mapbit
464

    
465

    
466
@directory.register
467
class THUV88Radio(chirp_common.CloneModeRadio):
468
    """TYT UV88 Radio"""
469
    VENDOR = "TYT"
470
    MODEL = "TH-UV88"
471
    MODES = ['WFM', 'FM', 'NFM']
472
    TONES = chirp_common.TONES
473
    DTCS_CODES = chirp_common.DTCS_CODES
474
    NAME_LENGTH = 10
475
    DTMF_CHARS = list("0123456789ABCD*#")
476
    # 136-174, 400-480
477
    VALID_BANDS = [(136000000, 174000000), (400000000, 480000000)]
478

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

    
483
    _magic0 = "\xFE\xFE\xEE\xEF\xE0" + "UV88" + "\xFD"
484
    _magic2 = "\xFE\xFE\xEE\xEF\xE2" + "UV88" + "\xFD"
485
    _magic3 = "\xFE\xFE\xEE\xEF\xE3" + "UV88" + "\xFD"
486
    _magic5 = "\xFE\xFE\xEE\xEF\xE5" + "UV88" + "\xFD"
487
    _fingerprint = "\xFE\xFE\xEF\xEE\xE1" + "UV88"
488

    
489
    @classmethod
490
    def get_prompts(cls):
491
        rp = chirp_common.RadioPrompts()
492
        rp.info = \
493
            (cls.VENDOR + ' ' + cls.MODEL + '\n')
494

    
495
        rp.pre_download = _(dedent("""\
496
            This is an early stage beta driver
497
            """))
498
        rp.pre_upload = _(dedent("""\
499
            This is an early stage beta driver - upload at your own risk
500
            """))
501
        return rp
502

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

    
537
    def sync_in(self):
538
        """Download from radio"""
539
        try:
540
            data = _download(self)
541
        except errors.RadioError:
542
            # Pass through any real errors we raise
543
            raise
544
        except Exception:
545
            # If anything unexpected happens, make sure we raise
546
            # a RadioError and log the problem
547
            LOG.exception('Unexpected error during download')
548
            raise errors.RadioError('Unexpected error communicating '
549
                                    'with the radio')
550
        self._mmap = memmap.MemoryMap(data)
551
        self.process_mmap()
552

    
553
    def sync_out(self):
554
        """Upload to radio"""
555

    
556
        try:
557
            _upload(self)
558
        except Exception:
559
            # If anything unexpected happens, make sure we raise
560
            # a RadioError and log the problem
561
            LOG.exception('Unexpected error during upload')
562
            raise errors.RadioError('Unexpected error communicating '
563
                                    'with the radio')
564

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

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

    
572
    def set_memory(self, memory):
573
        """A value in a UI column for chan 'number' has been modified."""
574
        # update all raw channel memory values (_mem) from UI (mem)
575
        _mem = self._memobj.chan_mem[memory.number - 1]
576
        _name = self._memobj.chan_name[memory.number - 1]
577

    
578
        if memory.empty:
579
            _do_map(memory.number, 0, self._memobj.chan_avail.bitmap)
580
            return
581

    
582
        _do_map(memory.number, 1, self._memobj.chan_avail.bitmap)
583

    
584
        if memory.skip == "":
585
            _do_map(memory.number, 1, self._memobj.chan_skip.bitmap)
586
        else:
587
            _do_map(memory.number, 0, self._memobj.chan_skip.bitmap)
588

    
589
        return self._set_memory(memory, _mem, _name)
590

    
591
    def get_memory(self, number):
592
        # radio first channel is 1, mem map is base 0
593
        _mem = self._memobj.chan_mem[number - 1]
594
        _name = self._memobj.chan_name[number - 1]
595
        mem = chirp_common.Memory()
596
        mem.number = number
597

    
598
        # Determine if channel is empty
599

    
600
        if _do_map(number, 2, self._memobj.chan_avail.bitmap) == 0:
601
            mem.empty = True
602
            return mem
603

    
604
        if _do_map(mem.number, 2, self._memobj.chan_skip.bitmap) > 0:
605
            mem.skip = ""
606
        else:
607
            mem.skip = "S"
608

    
609
        return self._get_memory(mem, _mem, _name)
610

    
611
    def _get_memory(self, mem, _mem, _name):
612
        """Convert raw channel memory data into UI columns"""
613
        mem.extra = RadioSettingGroup("extra", "Extra")
614

    
615
        mem.empty = False
616
        # This function process both 'normal' and Freq up/down' entries
617
        mem.freq = int(_mem.rxfreq) * 10
618

    
619
        if _mem.txfreq == 0xFFFFFFFF:
620
            # TX freq not set
621
            mem.duplex = "off"
622
            mem.offset = 0
623
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 25000000:
624
            mem.duplex = "split"
625
            mem.offset = int(_mem.txfreq) * 10
626
        elif int(_mem.rxfreq) == int(_mem.txfreq):
627
            mem.duplex = ""
628
            mem.offset = 0
629
        else:
630
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) \
631
                and "-" or "+"
632
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
633

    
634
        mem.name = ""
635
        for i in range(6):   # 0 - 6
636
            mem.name += chr(_mem.name[i])
637
        for i in range(10):
638
            mem.name += chr(_name.extra_name[i])
639

    
640
        mem.name = mem.name.rstrip()    # remove trailing spaces
641

    
642
        # ########## TONE ##########
643

    
644
        if _mem.txtone > 2600:
645
            # All off
646
            txmode = ""
647
        elif _mem.txtone > 511:
648
            txmode = "Tone"
649
            mem.rtone = int(_mem.txtone) / 10.0
650
        else:
651
            # DTSC
652
            txmode = "DTCS"
653
            mem.dtcs = int(format(int(_mem.txtone), 'o'))
654

    
655
        if _mem.rxtone > 2600:
656
            rxmode = ""
657
        elif _mem.rxtone > 511:
658
            rxmode = "Tone"
659
            mem.ctone = int(_mem.rxtone) / 10.0
660
        else:
661
            rxmode = "DTCS"
662
            mem.rx_dtcs = int(format(int(_mem.rxtone), 'o'))
663

    
664
        mem.dtcs_polarity = ("N", "R")[_mem.encodeDSCI] + (
665
                             "N", "R")[_mem.decodeDSCI]
666

    
667
        mem.tmode = ""
668
        if txmode == "Tone" and not rxmode:
669
            mem.tmode = "Tone"
670
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
671
            mem.tmode = "TSQL"
672
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
673
            mem.tmode = "DTCS"
674
        elif rxmode or txmode:
675
            mem.tmode = "Cross"
676
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
677

    
678
        # ########## TONE ##########
679

    
680
        mem.mode = self.MODES[_mem.wide]
681
        mem.power = POWER_LEVELS[int(_mem.power)]
682

    
683
        b_lock = RadioSetting("b_lock", "B_Lock",
684
                              RadioSettingValueList(B_LOCK_LIST,
685
                                                    B_LOCK_LIST[_mem.b_lock]))
686
        mem.extra.append(b_lock)
687

    
688
        step = RadioSetting("step", "Step",
689
                            RadioSettingValueList(LIST_STEPS,
690
                                                  LIST_STEPS[_mem.step]))
691
        mem.extra.append(step)
692

    
693
        scramble_value = _mem.scramble
694
        if scramble_value >= 8:     # Looks like OFF is 0x0f ** CONFIRM
695
            scramble_value = 0
696
        scramble = RadioSetting("scramble", "Scramble",
697
                                RadioSettingValueList(SCRAMBLE_LIST,
698
                                                      SCRAMBLE_LIST[
699
                                                          scramble_value]))
700
        mem.extra.append(scramble)
701

    
702
        optsig = RadioSetting("signal", "Optional signaling",
703
                              RadioSettingValueList(
704
                                  OPTSIG_LIST,
705
                                  OPTSIG_LIST[_mem.signal]))
706
        mem.extra.append(optsig)
707

    
708
        rs = RadioSetting("pttid", "PTT ID",
709
                          RadioSettingValueList(PTTID_LIST,
710
                                                PTTID_LIST[_mem.pttid]))
711
        mem.extra.append(rs)
712

    
713
        return mem
714

    
715
    def _set_memory(self, mem, _mem, _name):
716
        # """Convert UI column data (mem) into MEM_FORMAT memory (_mem)."""
717

    
718
        _mem.rxfreq = mem.freq / 10
719
        if mem.duplex == "off":
720
            _mem.txfreq = 0xFFFFFFFF
721
        elif mem.duplex == "split":
722
            _mem.txfreq = mem.offset / 10
723
        elif mem.duplex == "+":
724
            _mem.txfreq = (mem.freq + mem.offset) / 10
725
        elif mem.duplex == "-":
726
            _mem.txfreq = (mem.freq - mem.offset) / 10
727
        else:
728
            _mem.txfreq = _mem.rxfreq
729

    
730
        out_name = mem.name.ljust(16)
731

    
732
        for i in range(6):   # 0 - 6
733
            _mem.name[i] = ord(out_name[i])
734
        for i in range(10):
735
            _name.extra_name[i] = ord(out_name[i+6])
736

    
737
        if mem.name != "":
738
            _mem.displayName = 1    # Name only displayed if this is set on
739
        else:
740
            _mem.displayName = 0
741

    
742
        rxmode = ""
743
        txmode = ""
744

    
745
        if mem.tmode == "Tone":
746
            txmode = "Tone"
747
        elif mem.tmode == "TSQL":
748
            rxmode = "Tone"
749
            txmode = "TSQL"
750
        elif mem.tmode == "DTCS":
751
            rxmode = "DTCSSQL"
752
            txmode = "DTCS"
753
        elif mem.tmode == "Cross":
754
            txmode, rxmode = mem.cross_mode.split("->", 1)
755

    
756
        if mem.dtcs_polarity[1] == "N":
757
            _mem.decodeDSCI = 0
758
        else:
759
            _mem.decodeDSCI = 1
760

    
761
        if rxmode == "":
762
            _mem.rxtone = 0xFFF
763
        elif rxmode == "Tone":
764
            _mem.rxtone = int(float(mem.ctone) * 10)
765
        elif rxmode == "DTCSSQL":
766
            _mem.rxtone = int(str(mem.dtcs), 8)
767
        elif rxmode == "DTCS":
768
            _mem.rxtone = int(str(mem.rx_dtcs), 8)
769

    
770
        if mem.dtcs_polarity[0] == "N":
771
            _mem.encodeDSCI = 0
772
        else:
773
            _mem.encodeDSCI = 1
774

    
775
        if txmode == "":
776
            _mem.txtone = 0xFFF
777
        elif txmode == "Tone":
778
            _mem.txtone = int(float(mem.rtone) * 10)
779
        elif txmode == "TSQL":
780
            _mem.txtone = int(float(mem.ctone) * 10)
781
        elif txmode == "DTCS":
782
            _mem.txtone = int(str(mem.dtcs), 8)
783

    
784
        _mem.wide = self.MODES.index(mem.mode)
785
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
786

    
787
        for element in mem.extra:
788
            setattr(_mem, element.get_name(), element.value)
789

    
790
        return
791

    
792
    def get_settings(self):
793
        """Translate the MEM_FORMAT structs into setstuf in the UI"""
794
        _settings = self._memobj.basicsettings
795
        _settings2 = self._memobj.settings2
796
        _workmode = self._memobj.workmodesettings
797

    
798
        basic = RadioSettingGroup("basic", "Basic Settings")
799
        group = RadioSettings(basic)
800

    
801
        # Menu 02 - TX Channel Select
802
        options = ["Last Channel", "Main Channel"]
803
        rx = RadioSettingValueList(options, options[_settings.txChSelect])
804
        rset = RadioSetting("basicsettings.txChSelect",
805
                            "Priority Transmit", rx)
806
        basic.append(rset)
807

    
808
        # Menu 03 - VOX Level
809
        rx = RadioSettingValueInteger(1, 7, _settings.voxLevel + 1)
810
        rset = RadioSetting("basicsettings.voxLevel", "Vox Level", rx)
811
        basic.append(rset)
812

    
813
        # Menu 05 - Squelch Level
814
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
815
        rx = RadioSettingValueList(options, options[_settings.sqlLevel])
816
        rset = RadioSetting("basicsettings.sqlLevel", "Squelch Level", rx)
817
        basic.append(rset)
818

    
819
        # Menu 06 - Dual Wait
820
        rx = RadioSettingValueBoolean(_settings.dualWait)
821
        rset = RadioSetting("basicsettings.dualWait", "Dual Wait/Standby", rx)
822
        basic.append(rset)
823

    
824
        # Menu 07 - LED Mode
825
        options = ["Off", "On", "Auto"]
826
        rx = RadioSettingValueList(options, options[_settings.ledMode])
827
        rset = RadioSetting("basicsettings.ledMode", "LED Display Mode", rx)
828
        basic.append(rset)
829

    
830
        # Menu 08 - Light
831
        options = ["%s" % x for x in range(1, 8)]
832
        rx = RadioSettingValueList(options, options[_settings.light])
833
        rset = RadioSetting("basicsettings.light",
834
                            "Background Light Color", rx)
835
        basic.append(rset)
836

    
837
        # Menu 09 - Beep
838
        rx = RadioSettingValueBoolean(_settings.beep)
839
        rset = RadioSetting("basicsettings.beep", "Keypad Beep", rx)
840
        basic.append(rset)
841

    
842
        # Menu 11 - TOT
843
        options = ["Off"] + ["%s seconds" % x for x in range(30, 300, 30)]
844
        rx = RadioSettingValueList(options, options[_settings.tot])
845
        rset = RadioSetting("basicsettings.tot",
846
                            "Transmission Time-out Timer", rx)
847
        basic.append(rset)
848

    
849
        # Menu 13 - VOX Switch
850
        rx = RadioSettingValueBoolean(_settings.voxSw)
851
        rset = RadioSetting("basicsettings.voxSw", "Vox Switch", rx)
852
        basic.append(rset)
853

    
854
        # Menu 14 - Roger
855
        rx = RadioSettingValueBoolean(_settings.roger)
856
        rset = RadioSetting("basicsettings.roger", "Roger Beep", rx)
857
        basic.append(rset)
858

    
859
        # Menu 16 - Save Mode
860
        options = ["Off", "1:1", "1:2", "1:4"]
861
        rx = RadioSettingValueList(options, options[_settings.saveMode])
862
        rset = RadioSetting("basicsettings.saveMode", "Battery Save Mode", rx)
863
        basic.append(rset)
864

    
865
        # Menu 17 - Scan Type
866
        if self.MODEL == "QRZ-1":
867
            options = ["Time", "Carrier", "Stop"]
868
        else:
869
            options = ["CO", "TO", "SE"]
870
        rx = RadioSettingValueList(options, options[_settings.scanType])
871
        rset = RadioSetting("basicsettings.scanType", "Scan Type", rx)
872
        basic.append(rset)
873

    
874
        # Menu 18 - Key Lock
875
        rx = RadioSettingValueBoolean(_settings.keylock)
876
        rset = RadioSetting("basicsettings.keylock", "Auto Key Lock", rx)
877
        basic.append(rset)
878

    
879
        if self.MODEL != "QRZ-1":
880
            # Menu 19 - SW Audio
881
            rx = RadioSettingValueBoolean(_settings.swAudio)
882
            rset = RadioSetting("basicsettings.swAudio", "Voice Prompts", rx)
883
            basic.append(rset)
884

    
885
        # Menu 20 - Intro Screen
886
        options = ["Off", "Voltage", "Character String"]
887
        rx = RadioSettingValueList(options, options[_settings.introScreen])
888
        rset = RadioSetting("basicsettings.introScreen", "Intro Screen", rx)
889
        basic.append(rset)
890

    
891
        # Menu 32 - Key Mode
892
        options = ["ALL", "PTT", "KEY", "Key & Side Key"]
893
        rx = RadioSettingValueList(options, options[_settings.keyMode])
894
        rset = RadioSetting("basicsettings.keyMode", "Key Lock Mode", rx)
895
        basic.append(rset)
896

    
897
        # Menu 33 - Display Mode
898
        options = ['Frequency', 'Channel #', 'Name']
899
        rx = RadioSettingValueList(options, options[_settings.disMode])
900
        rset = RadioSetting("basicsettings.disMode", "Display Mode", rx)
901
        basic.append(rset)
902

    
903
        # Menu 34 - FM Dual Wait
904
        rx = RadioSettingValueBoolean(_settings.radioMoni)
905
        rset = RadioSetting("basicsettings.radioMoni", "Radio Monitor", rx)
906
        basic.append(rset)
907

    
908
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
909
        group.append(advanced)
910

    
911
        # software only
912
        options = ['Off', 'Frequency']
913
        rx = RadioSettingValueList(options, options[_settings.endToneElim])
914
        rset = RadioSetting("basicsettings.endToneElim", "End Tone Elim", rx)
915
        advanced.append(rset)
916

    
917
        # software only
918
        name = ""
919
        for i in range(15):  # 0 - 15
920
            name += chr(self._memobj.openradioname.name1[i])
921
        name = name.rstrip()  # remove trailing spaces
922

    
923
        rx = RadioSettingValueString(0, 15, name)
924
        rset = RadioSetting("openradioname.name1", "Intro Line 1", rx)
925
        advanced.append(rset)
926

    
927
        # software only
928
        name = ""
929
        for i in range(15):  # 0 - 15
930
            name += chr(self._memobj.openradioname.name2[i])
931
        name = name.rstrip()  # remove trailing spaces
932

    
933
        rx = RadioSettingValueString(0, 15, name)
934
        rset = RadioSetting("openradioname.name2", "Intro Line 2", rx)
935
        advanced.append(rset)
936

    
937
        # software only
938
        options = ['0.5S', '1.0S', '1.5S', '2.0S', '2.5S', '3.0S', '3.5S',
939
                   '4.0S', '4.5S', '5.0S']
940
        rx = RadioSettingValueList(options, options[_settings.voxDelay])
941
        rset = RadioSetting("basicsettings.voxDelay", "VOX Delay", rx)
942
        advanced.append(rset)
943

    
944
        options = ['Unlocked', 'Unknown 1', 'Unknown 2', 'EU', 'US']
945
        # extend option list with unknown description for values 5 - 15.
946
        for ix in range(len(options), _settings2.region + 1):
947
            item_to_add = 'Unknown {region_code}'.format(region_code=ix)
948
            options.append(item_to_add)
949
        # log unknown region codes greater than 4
950
        if _settings2.region > 4:
951
            LOG.debug("Unknown region code: {value}".
952
                      format(value=_settings2.region))
953
        rx = RadioSettingValueList(options, options[_settings2.region])
954
        rx.set_mutable(False)
955
        rset = RadioSetting("settings2.region", "Region", rx)
956
        advanced.append(rset)
957

    
958
        workmode = RadioSettingGroup("workmode", "Work Mode Settings")
959
        group.append(workmode)
960

    
961
        # Toggle with [#] key
962
        options = ["Frequency", "Channel"]
963
        rx = RadioSettingValueList(options, options[_workmode.vfomrmode])
964
        rset = RadioSetting("workmodesettings.vfomrmode", "VFO/MR Mode", rx)
965
        workmode.append(rset)
966

    
967
        # Toggle with [#] key
968
        options = ["Frequency", "Channel"]
969
        rx = RadioSettingValueList(options, options[_workmode.vfomrmodeb])
970
        rset = RadioSetting("workmodesettings.vfomrmodeb",
971
                            "VFO/MR Mode B (BQ1.41+)", rx)
972
        workmode.append(rset)
973

    
974
        rx = RadioSettingValueInteger(1, 199, _workmode.mrAch + 1)
975
        rset = RadioSetting("workmodesettings.mrAch", "MR A Channel #", rx)
976
        workmode.append(rset)
977

    
978
        rx = RadioSettingValueInteger(1, 199, _workmode.mrBch + 1)
979
        rset = RadioSetting("workmodesettings.mrBch", "MR B Channel #", rx)
980
        workmode.append(rset)
981

    
982
        fmb = RadioSettingGroup("fmradioc", "FM Radio Settings")
983
        group.append(fmb)
984

    
985
        def myset_mask(setting, obj, atrb, nx):
986
            if bool(setting.value):     # Enabled = 1
987
                vx = 1
988
            else:
989
                vx = 0
990
            _do_map(nx + 1, vx, self._memobj.fmmap.fmset)
991
            return
992

    
993
        def myset_fmfrq(setting, obj, atrb, nx):
994
            """ Callback to set xx.x FM freq in memory as xx.x * 100000"""
995
            # in-valid even KHz freqs are allowed; to satisfy run_tests
996
            vx = float(str(setting.value))
997
            vx = int(vx * 100000)
998
            setattr(obj[nx], atrb, vx)
999
            return
1000

    
1001
        def myset_freq(setting, obj, atrb, mult):
1002
            """ Callback to set frequency by applying multiplier"""
1003
            value = int(float(str(setting.value)) * mult)
1004
            setattr(obj, atrb, value)
1005
            return
1006

    
1007
        _fmx = self._memobj.fmfrqs
1008

    
1009
        # FM Broadcast Manual Settings
1010
        val = _fmx.fmcur
1011
        val = val / 100000.0
1012
        if val < 64.0 or val > 108.0:
1013
            val = 100.7
1014
        rx = RadioSettingValueFloat(64.0, 108.0, val, 0.1, 1)
1015
        rset = RadioSetting("fmfrqs.fmcur", "Manual FM Freq (MHz)", rx)
1016
        rset.set_apply_callback(myset_freq, _fmx, "fmcur", 100000)
1017
        fmb.append(rset)
1018

    
1019
        _fmfrq = self._memobj.fm_stations
1020
        _fmap = self._memobj.fmmap
1021

    
1022
        # FM Broadcast Presets Settings
1023
        for j in range(0, 24):
1024
            val = _fmfrq[j].rxfreq
1025
            if val < 6400000 or val > 10800000:
1026
                val = 88.0
1027
                fmset = False
1028
            else:
1029
                val = (float(int(val)) / 100000)
1030
                # get fmmap bit value: 1 = enabled
1031
                ndx = int(math.floor((j) / 8))
1032
                bv = j % 8
1033
                msk = 1 << bv
1034
                vx = _fmap.fmset[ndx]
1035
                fmset = bool(vx & msk)
1036
            rx = RadioSettingValueBoolean(fmset)
1037
            rset = RadioSetting("fmmap.fmset/%d" % j,
1038
                                "FM Preset %02d" % (j + 1), rx)
1039
            rset.set_apply_callback(myset_mask, _fmap, "fmset", j)
1040
            fmb.append(rset)
1041

    
1042
            rx = RadioSettingValueFloat(64.0, 108.0, val, 0.1, 1)
1043
            rset = RadioSetting("fm_stations/%d.rxfreq" % j,
1044
                                "    Preset %02d Freq" % (j + 1), rx)
1045
            # This callback uses the array index
1046
            rset.set_apply_callback(myset_fmfrq, _fmfrq, "rxfreq", j)
1047
            fmb.append(rset)
1048

    
1049
        return group       # END get_settings()
1050

    
1051
    def set_settings(self, settings):
1052
        _settings = self._memobj.basicsettings
1053
        _mem = self._memobj
1054
        for element in settings:
1055
            if not isinstance(element, RadioSetting):
1056
                self.set_settings(element)
1057
                continue
1058
            else:
1059
                try:
1060
                    name = element.get_name()
1061
                    if "." in name:
1062
                        bits = name.split(".")
1063
                        obj = self._memobj
1064
                        for bit in bits[:-1]:
1065
                            if "/" in bit:
1066
                                bit, index = bit.split("/", 1)
1067
                                index = int(index)
1068
                                obj = getattr(obj, bit)[index]
1069
                            else:
1070
                                obj = getattr(obj, bit)
1071
                        setting = bits[-1]
1072
                    else:
1073
                        obj = _settings
1074
                        setting = element.get_name()
1075

    
1076
                    if element.has_apply_callback():
1077
                        LOG.debug("Using apply callback")
1078
                        element.run_apply_callback()
1079
                    elif setting == "mrAch" or setting == "mrBch":
1080
                        setattr(obj, setting, int(element.value) - 1)
1081
                    elif setting == "voxLevel":
1082
                        setattr(obj, setting, int(element.value) - 1)
1083
                    elif element.value.get_mutable():
1084
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1085
                        setattr(obj, setting, element.value)
1086
                except Exception, e:
1087
                    LOG.debug(element.get_name())
1088
                    raise
1089

    
1090

    
1091
@directory.register
1092
class RT85(THUV88Radio):
1093
    VENDOR = "Retevis"
1094
    MODEL = "RT85"
1095

    
1096

    
1097
@directory.register
1098
class QRZ1(THUV88Radio):
1099
    VENDOR = "Explorer"
1100
    MODEL = "QRZ-1"
1101

    
1102
    _magic0 = "\xFE\xFE\xEE\xEF\xE0" + "UV78" + "\xFD"
1103
    _magic2 = "\xFE\xFE\xEE\xEF\xE2" + "UV78" + "\xFD"
1104
    _magic3 = "\xFE\xFE\xEE\xEF\xE3" + "UV78" + "\xFD"
1105
    _magic5 = "\xFE\xFE\xEE\xEF\xE5" + "UV78" + "\xFD"
1106
    _fingerprint = "\xFE\xFE\xEF\xEE\xE1" + "UV78"
(56-56/57)