Project

General

Profile

New Model #10023 » th_uv88 - qrz_1_poc1.py

Jim Unroe, 09/22/2022 03:17 AM

 
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 = "\xFE\xFE\xEE\xEF\xE0\x55\x56\x38\x38\xFD"
304
    magic = "\xFE\xFE\xEE\xEF\xE0\x55\x56\x37\x38\xFD"
305
    _rawsend(radio, magic)
306
    ack = _rawrecv(radio, 36)
307

    
308
    ##if not ack.startswith("\xFE\xFE\xEF\xEE\xE1\x55\x56\x38\x38"
309
    if not ack.startswith("\xFE\xFE\xEF\xEE\xE1\x55\x56\x37\x38"
310
                          ) or not ack.endswith("\xFD"):
311
        _exit_program_mode(radio)
312
        if ack:
313
            LOG.debug(repr(ack))
314
        raise errors.RadioError("Radio did not respond as expected (A)")
315

    
316
    return True
317

    
318

    
319
def _exit_program_mode(radio):
320
    # This may be the last part of a read
321
    ##magic = "\xFE\xFE\xEE\xEF\xE5\x55\x56\x38\x38\xFD"
322
    magic = "\xFE\xFE\xEE\xEF\xE5\x55\x56\x37\x38\xFD"
323
    _rawsend(radio, magic)
324
    ack = _rawrecv(radio, 7)
325
    if ack != "\xFE\xFE\xEF\xEE\xE6\x00\xFD":
326
        _exit_program_mode(radio)
327
        if ack:
328
            LOG.debug(repr(ack))
329
        raise errors.RadioError("Radio did not respond as expected (B)")
330

    
331

    
332
def _download(radio):
333
    """Get the memory map"""
334

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

    
338
    # Enter read mode
339
    magic = "\xFE\xFE\xEE\xEF\xE2\x55\x56\x38\x38\xFD"
340
    _rawsend(radio, magic)
341
    ack = _rawrecv(radio, 7)
342
    if ack != "\xFE\xFE\xEF\xEE\xE6\x00\xFD":
343
        _exit_program_mode(radio)
344
        if ack:
345
            LOG.debug(repr(ack))
346
        raise errors.RadioError("Radio did not respond to enter read mode")
347

    
348
    # UI progress
349
    status = chirp_common.Status()
350
    status.cur = 0
351
    status.max = MEM_SIZE / BLOCK_SIZE
352
    status.msg = "Cloning from radio..."
353
    radio.status_fn(status)
354

    
355
    data = ""
356
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
357
        frame = _make_read_frame(addr, BLOCK_SIZE)
358
        # DEBUG
359
        LOG.debug("Frame=" + util.hexprint(frame))
360

    
361
        # Sending the read request
362
        _rawsend(radio, frame)
363

    
364
        # Now we read data
365
        d = _recv(radio, addr, BLOCK_SIZE + 13)
366

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

    
369
        if not d.startswith("\xFE\xFE\xEF\xEE\xE4"):
370
            LOG.warning("Incorrect start")
371
        if not d.endswith("\xFD"):
372
            LOG.warning("Incorrect end")
373
        # could validate the block data
374

    
375
        # Aggregate the data
376
        data += d[11:-2]
377

    
378
        # UI Update
379
        status.cur = addr / BLOCK_SIZE
380
        status.msg = "Cloning from radio..."
381
        radio.status_fn(status)
382

    
383
    _exit_program_mode(radio)
384

    
385
    return data
386

    
387

    
388
def _upload(radio):
389
    """Upload procedure"""
390
    # Put radio in program mode and identify it
391
    _do_ident(radio)
392

    
393
    magic = "\xFE\xFE\xEE\xEF\xE3\x55\x56\x38\x38\xFD"
394
    _rawsend(radio, magic)
395
    ack = _rawrecv(radio, 7)
396
    if ack != "\xFE\xFE\xEF\xEE\xE6\x00\xFD":
397
        _exit_program_mode(radio)
398
        if ack:
399
            LOG.debug(repr(ack))
400
        raise errors.RadioError("Radio did not respond to enter write mode")
401

    
402
    # UI progress
403
    status = chirp_common.Status()
404
    status.cur = 0
405
    status.max = MEM_SIZE / BLOCK_SIZE
406
    status.msg = "Cloning to radio..."
407
    radio.status_fn(status)
408

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

    
415
        # Sending the data
416
        data = radio.get_mmap()[addr:addr + BLOCK_SIZE]
417

    
418
        frame = _make_write_frame(addr, BLOCK_SIZE, data)
419
        LOG.warning("Frame:%s:" % util.hexprint(frame))
420
        _rawsend(radio, frame)
421

    
422
        ack = _rawrecv(radio, 7)
423
        LOG.debug("Response Data= " + util.hexprint(ack))
424

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

    
431
        # UI Update
432
        status.cur = addr / BLOCK_SIZE
433
        status.msg = "Cloning to radio..."
434
        radio.status_fn(status)
435

    
436
    _exit_program_mode(radio)
437

    
438

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

    
457

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

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

    
475
    @classmethod
476
    def get_prompts(cls):
477
        rp = chirp_common.RadioPrompts()
478
        rp.info = \
479
            (cls.VENDOR + ' ' + cls.MODEL + '\n')
480

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

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

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

    
539
    def sync_out(self):
540
        """Upload to radio"""
541

    
542
        try:
543
            _upload(self)
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 upload')
548
            raise errors.RadioError('Unexpected error communicating '
549
                                    'with the radio')
550

    
551
    def process_mmap(self):
552
        """Process the mem map into the mem object"""
553
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
554

    
555
    def get_raw_memory(self, number):
556
        return repr(self._memobj.memory[number - 1])
557

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

    
564
        if memory.empty:
565
            _do_map(memory.number, 0, self._memobj.chan_avail.bitmap)
566
            return
567

    
568
        _do_map(memory.number, 1, self._memobj.chan_avail.bitmap)
569

    
570
        if memory.skip == "":
571
            _do_map(memory.number, 1, self._memobj.chan_skip.bitmap)
572
        else:
573
            _do_map(memory.number, 0, self._memobj.chan_skip.bitmap)
574

    
575
        return self._set_memory(memory, _mem, _name)
576

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

    
584
        # Determine if channel is empty
585

    
586
        if _do_map(number, 2, self._memobj.chan_avail.bitmap) == 0:
587
            mem.empty = True
588
            return mem
589

    
590
        if _do_map(mem.number, 2, self._memobj.chan_skip.bitmap) > 0:
591
            mem.skip = ""
592
        else:
593
            mem.skip = "S"
594

    
595
        return self._get_memory(mem, _mem, _name)
596

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

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

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

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

    
626
        mem.name = mem.name.rstrip()    # remove trailing spaces
627

    
628
        # ########## TONE ##########
629

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

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

    
650
        mem.dtcs_polarity = ("N", "R")[_mem.encodeDSCI] + (
651
                             "N", "R")[_mem.decodeDSCI]
652

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

    
664
        # ########## TONE ##########
665

    
666
        mem.mode = self.MODES[_mem.wide]
667
        mem.power = POWER_LEVELS[int(_mem.power)]
668

    
669
        b_lock = RadioSetting("b_lock", "B_Lock",
670
                              RadioSettingValueList(B_LOCK_LIST,
671
                                                    B_LOCK_LIST[_mem.b_lock]))
672
        mem.extra.append(b_lock)
673

    
674
        b_lock = RadioSetting("step", "Step",
675
                              RadioSettingValueList(LIST_STEPS,
676
                                                    LIST_STEPS[_mem.step]))
677
        mem.extra.append(b_lock)
678

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

    
688
        optsig = RadioSetting("signal", "Optional signaling",
689
                              RadioSettingValueList(
690
                                  OPTSIG_LIST,
691
                                  OPTSIG_LIST[_mem.signal]))
692
        mem.extra.append(optsig)
693

    
694
        rs = RadioSetting("pttid", "PTT ID",
695
                          RadioSettingValueList(PTTID_LIST,
696
                                                PTTID_LIST[_mem.pttid]))
697
        mem.extra.append(rs)
698

    
699
        return mem
700

    
701
    def _set_memory(self, mem, _mem, _name):
702
        # """Convert UI column data (mem) into MEM_FORMAT memory (_mem)."""
703

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

    
716
        out_name = mem.name.ljust(16)
717

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

    
723
        if mem.name != "":
724
            _mem.displayName = 1    # Name only displayed if this is set on
725
        else:
726
            _mem.displayName = 0
727

    
728
        rxmode = ""
729
        txmode = ""
730

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

    
742
        if mem.dtcs_polarity[1] == "N":
743
            _mem.decodeDSCI = 0
744
        else:
745
            _mem.decodeDSCI = 1
746

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

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

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

    
770
        _mem.wide = self.MODES.index(mem.mode)
771
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
772

    
773
        for element in mem.extra:
774
            setattr(_mem, element.get_name(), element.value)
775

    
776
        return
777

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

    
784
        basic = RadioSettingGroup("basic", "Basic Settings")
785
        group = RadioSettings(basic)
786

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

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

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

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

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

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

    
823
        # Menu 09 - Beep
824
        rx = RadioSettingValueBoolean(_settings.beep)
825
        rset = RadioSetting("basicsettings.beep", "Keypad Beep", rx)
826
        basic.append(rset)
827

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

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

    
840
        # Menu 14 - Roger
841
        rx = RadioSettingValueBoolean(_settings.roger)
842
        rset = RadioSetting("basicsettings.roger", "Roger Beep", rx)
843
        basic.append(rset)
844

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

    
851
        # Menu 17 - Scan Type
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
        # Menu 19 - SW Audio
863
        rx = RadioSettingValueBoolean(_settings.swAudio)
864
        rset = RadioSetting("basicsettings.swAudio", "Voice Prompts", rx)
865
        basic.append(rset)
866

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
970
        return group       # END get_settings()
971

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

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

    
1011

    
1012
@directory.register
1013
class RT85(THUV88Radio):
1014
    VENDOR = "Retevis"
1015
    MODEL = "RT85"
(21-21/57)