anytone778uv_keyassignment.py

Jim Unroe, 11/24/2020 07:07 pm

Download (53.8 kB)

 
1
# Copyright 2020 Joe Milbourn <joe@milbourn.org.uk>
2
# Copyright 2020 Jim Unroe <rock.unroe@gmail.com>
3
#
4
# This program is free software: you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation, either version 2 of the License, or
7
# (at your option) any later version.
8
#
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
# GNU General Public License for more details.
13
#
14
# You should have received a copy of the GNU General Public License
15
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
#
17
# TODO use the band field from ver_response
18
# TODO handle radio settings
19
#
20
# Supported features
21
# * Read and write memory access for 200 normal memories
22
# * CTCSS and DTCS for transmit and receive
23
# * Scan list
24
# * Tx off
25
# * Duplex (+ve, -ve, odd, and off splits)
26
# * Transmit power
27
# * Channel width (25kHz and 12.5kHz)
28
# * Retevis RT95, CRT Micron UV, and Midland DBR2500 radios
29
# * Full range of frequencies for tx and rx, supported band read from radio
30
#   during download, not verified on upload.  Radio will refuse to TX if out of
31
#   band.
32
#
33
# Unsupported features
34
# * VFO1, VFO2, and TRF memories
35
# * custom CTCSS tones
36
# * Any non-memory radio settings
37
# * Reverse, talkaround, scramble
38
# * busy channel lock out
39
# * probably other things too - like things encoded by the unknown bits in the
40
#   memory struct
41

    
42
from chirp import chirp_common, directory, memmap, errors, util
43
from chirp import bitwise
44
from chirp.settings import RadioSettingGroup, RadioSetting, \
45
    RadioSettingValueBoolean, RadioSettingValueList, \
46
    RadioSettingValueString, RadioSettingValueInteger, \
47
    RadioSettingValueFloat, RadioSettings, InvalidValueError
48

    
49
import struct
50
import time
51
import logging
52

    
53
LOG = logging.getLogger(__name__)
54

    
55
# Gross hack to handle missing future module on un-updatable
56
# platforms like MacOS. Just avoid registering these radio
57
# classes for now.
58
try:
59
    from builtins import bytes
60
    has_future = True
61
except ImportError:
62
    has_future = False
63
    LOG.warning('python-future package is not '
64
                'available; %s requires it' % __name__)
65

    
66

    
67
# Here is where we define the memory map for the radio. Since
68
# We often just know small bits of it, we can use #seekto to skip
69
# around as needed.
70

    
71
MEM_FORMAT = '''
72
#seekto 0x0000;
73
struct {
74
  bbcd freq[4];
75
  bbcd offset[4];
76
  u8 unknown1;
77
  u8 talkaround:1,
78
     scramble:1,
79
     unknown:2,
80
     txpower:2,
81
     duplex:2;
82
  u8 unknown_bits1:4,
83
     channel_width:2,
84
     reverse:1,
85
     tx_off:1;
86
  u8 unknown_bits2:4,
87
     dtcs_decode_en:1,
88
     ctcss_decode_en:1,
89
     dtcs_encode_en:1,
90
     ctcss_encode_en:1;
91
  u8 ctcss_dec_tone;
92
  u8 ctcss_enc_tone;
93
  u8 dtcs_decode_code;
94
  u8 unknown_bits6:6,
95
     dtcs_decode_invert:1,
96
     dtcs_decode_code_highbit:1;
97
  u8 dtcs_encode_code;
98
  u8 unknown_bits7:6,
99
     dtcs_encode_invert:1,
100
     dtcs_encode_code_highbit:1;
101
  u8 unknown_bits4:6,
102
     busy_channel_lockout:2;
103
  u8 unknown6;
104
  u8 unknown_bits5:7,
105
     tone_squelch_en:1;
106
  u8 unknown7;
107
  u8 unknown8;
108
  u8 unknown9;
109
  u8 unknown10;
110
  char name[5];
111
  ul16 customctcss;
112
} memory[200];
113
#seekto 0x1940;
114
struct {
115
  u8 occupied_bitfield[32];
116
  u8 scan_enabled_bitfield[32];
117
} memory_status;
118

    
119
#seekto 0x1980;
120
struct {
121
  char line[7];           // starting display
122
} starting_display;
123

    
124
#seekto 0x3200;
125
struct {
126
  u8 unk3200:5,           // 0x3200
127
     beepVolume:3;        //        beep volume
128
  u8 unk3201:4,           // 0x3201
129
     frequencyStep:4;     //        frequency step
130
  u8 unk3202:6,           // 0x3202
131
     displayMode:2;       // display mode
132
  u8 unk0x3203;
133
  u8 unk3204:4,           // 0x3204
134
     squelchLevelA:4;     //        squelch level a
135
  u8 unk3205:4,           // 0x3205
136
     squelchLevelB:4;     //        squelch level b
137
  u8 unk3206:2,           // 0x3206
138
     speakerVol:6;        //        speaker volume
139
  u8 unk3207:7,           // 0x3207
140
     powerOnPasswd:1;     //        power-on password
141
  u8 unk3208:6,           // 0x3208
142
     scanType:2;          //        scan type
143
  u8 unk3209:6,           // 0x3209
144
     scanRecoveryT:2;     //        scan recovery time
145
  u8 unk320a:7,           // 0x320A
146
     autoPowerOn:1;       //        auto power on
147
  u8 unk320b:7,           // 0x320B
148
     main:1;              //        main
149
  u8 unk320c:7,           // 0x320C
150
     dualWatch:1;         //        dual watch (rx way select)
151
  u8 unk320d:5,           // 0x320D
152
     backlightBr:3;       //        backlight brightness
153
  u8 unk320e:3,           // 0x320E
154
     timeOutTimer:5;      //        time out timer
155
  u8 unk320f:6,           // 0x320F
156
     autoPowerOff:2;      //        auto power off
157
  u8 unk3210:6,           // 0x3210
158
     tbstFrequency:2;     //        tbst frequency
159
  u8 unk3211:7,           // 0x3211
160
     screenDir:1;         //        screen direction
161
  u8 unk3212:2,           // 0x3212
162
     micKeyBrite:6;       //        hand mic key brightness
163
  u8 unk3213:6,           // 0x3213
164
     speakerSwitch:2;     //        speaker switch
165
  u8 keyPA;               // 0x3214 key pa
166
  u8 keyPB;               // 0x3215 key pb
167
  u8 keyPC;               // 0x3216 key pc
168
  u8 keyPD;               // 0x3217 key pd
169
  u8 unk3218:5,           // 0x3218
170
     steType:3;           //        ste type
171
  u8 unk3219:6,           // 0x3219
172
     steFrequency:2;      //        ste frequency
173
  u8 unk0x321A;
174
  u8 unk_bit7_6:2,        // 0x321B
175
     monKeyFunction:1,    //        mon key function
176
     channelLocked:1,     //        channel locked
177
     saveChParameter:1,   //        save channel parameter
178
     powerOnReset:1,      //        power on reset
179
     trfEnable:1,         //        trf enable
180
     knobMode:1;          //        knob mode
181
} settings;
182

    
183
#seekto 0x3240;
184
struct {
185
  char digits[6];         // password
186
} password;
187

    
188
#seekto 0x3250;
189
struct {
190
  u8 keyMode1P1;          // 0x3250 key mode 1 p1
191
  u8 keyMode1P2;          // 0x3251 key mode 1 p2
192
  u8 keyMode1P3;          // 0x3252 key mode 1 p3
193
  u8 keyMode1P4;          // 0x3253 key mode 1 p4
194
  u8 keyMode1P5;          // 0x3254 key mode 1 p5
195
  u8 keyMode1P6;          // 0x3255 key mode 1 p6
196
  u8 keyMode2P1;          // 0x3256 key mode 2 p1
197
  u8 keyMode2P2;          // 0x3257 key mode 2 p2
198
  u8 keyMode2P3;          // 0x3258 key mode 2 p3
199
  u8 keyMode2P4;          // 0x3259 key mode 2 p4
200
  u8 keyMode2P5;          // 0x325A key mode 2 p5
201
  u8 keyMode2P6;          // 0x325B key mode 2 p6
202
} pfkeys;
203

    
204
#seekto 0x3260;
205
struct {
206
  u8 mrChanA;             // 0x3260 mr channel a
207
  u8 unknown1_0:7,        // 0x3261
208
     vfomrA:1;            //        vfo/mr mode a
209
  u8 unknown2;
210
  u8 unknown3;
211
  u8 unknown4;
212
  u8 unknown5;
213
  u8 unknown6;
214
  u8 mrChanB;             // 0x3267 mr channel b
215
  u8 unknown8_0:4,        // 0x3268
216
     scan_active:1,
217
     unknown8_1:2,
218
     vfomrB:1;            //        vfo/mr mode b
219
  u8 unknown9;
220
  u8 unknowna;
221
  u8 unknownb;
222
  u8 unknownc;
223
  u8 bandlimit;           // 0x326D mode
224
  u8 unknownd;
225
  u8 unknowne;
226
  u8 unknownf;
227
} radio_settings;
228
'''
229

    
230
# Format for the version messages returned by the radio
231
VER_FORMAT = '''
232
u8 hdr;
233
char model[7];
234
u8 bandlimit;
235
char version[6];
236
u8 ack;
237
'''
238

    
239
TXPOWER_LOW = 0x00
240
TXPOWER_MED = 0x01
241
TXPOWER_HIGH = 0x02
242

    
243
DUPLEX_NOSPLIT = 0x00
244
DUPLEX_POSSPLIT = 0x01
245
DUPLEX_NEGSPLIT = 0x02
246
DUPLEX_ODDSPLIT = 0x03
247

    
248
CHANNEL_WIDTH_25kHz = 0x02
249
CHANNEL_WIDTH_20kHz = 0x01
250
CHANNEL_WIDTH_12d5kHz = 0x00
251

    
252
BUSY_CHANNEL_LOCKOUT_OFF = 0x00
253
BUSY_CHANNEL_LOCKOUT_REPEATER = 0x01
254
BUSY_CHANNEL_LOCKOUT_BUSY = 0x02
255

    
256
MEMORY_ADDRESS_RANGE = (0x0000, 0x3290)
257
MEMORY_RW_BLOCK_SIZE = 0x10
258
MEMORY_RW_BLOCK_CMD_SIZE = 0x16
259

    
260
POWER_LEVELS = [chirp_common.PowerLevel('Low', dBm=37),
261
                chirp_common.PowerLevel('Medium', dBm=40),
262
                chirp_common.PowerLevel('High', dBm=44)]
263

    
264
# CTCSS Tone definitions
265
TONE_CUSTOM_CTCSS = 0x33
266
TONE_MAP_VAL_TO_TONE = {0x00: 62.5, 0x01: 67.0, 0x02: 69.3,
267
                        0x03: 71.9, 0x04: 74.4, 0x05: 77.0,
268
                        0x06: 79.7, 0x07: 82.5, 0x08: 85.4,
269
                        0x09: 88.5, 0x0a: 91.5, 0x0b: 94.8,
270
                        0x0c: 97.4, 0x0d: 100.0, 0x0e: 103.5,
271
                        0x0f: 107.2, 0x10: 110.9, 0x11: 114.8,
272
                        0x12: 118.8, 0x13: 123.0, 0x14: 127.3,
273
                        0x15: 131.8, 0x16: 136.5, 0x17: 141.3,
274
                        0x18: 146.2, 0x19: 151.4, 0x1a: 156.7,
275
                        0x1b: 159.8, 0x1c: 162.2, 0x1d: 165.5,
276
                        0x1e: 167.9, 0x1f: 171.3, 0x20: 173.8,
277
                        0x21: 177.3, 0x22: 179.9, 0x23: 183.5,
278
                        0x24: 186.2, 0x25: 189.9, 0x26: 192.8,
279
                        0x27: 196.6, 0x28: 199.5, 0x29: 203.5,
280
                        0x2a: 206.5, 0x2b: 210.7, 0x2c: 218.1,
281
                        0x2d: 225.7, 0x2e: 229.1, 0x2f: 233.6,
282
                        0x30: 241.8, 0x31: 250.3, 0x32: 254.1}
283

    
284
TONE_MAP_TONE_TO_VAL = {TONE_MAP_VAL_TO_TONE[val]: val
285
                        for val in TONE_MAP_VAL_TO_TONE}
286

    
287
TONES_EN_TXTONE = (1 << 3)
288
TONES_EN_RXTONE = (1 << 2)
289
TONES_EN_TXCODE = (1 << 1)
290
TONES_EN_RXCODE = (1 << 0)
291
TONES_EN_NO_TONE = 0
292

    
293
# Radio supports upper case and symbols
294
CHARSET_ASCII_PLUS = chirp_common.CHARSET_UPPER_NUMERIC + '- '
295

    
296
# Band limits as defined by the band byte in ver_response, defined in Hz, for
297
# VHF and UHF, used for RX and TX.
298
BAND_LIMITS = {0x00: [(144000000, 148000000), (430000000, 440000000)],
299
               0x01: [(136000000, 174000000), (400000000, 490000000)],
300
               0x02: [(144000000, 146000000), (430000000, 440000000)]}
301

    
302

    
303
# Get band limits from a band limit value
304
def get_band_limits_Hz(limit_value):
305
    if limit_value not in BAND_LIMITS:
306
        limit_value = 0x01
307
        LOG.warning('Unknown band limit value 0x%02x, default to 0x01')
308
    bandlimitfrequencies = BAND_LIMITS[limit_value]
309
    return bandlimitfrequencies
310

    
311

    
312
# Calculate the checksum used in serial packets
313
def checksum(message_bytes):
314
    mask = 0xFF
315
    checksum = 0
316
    for b in message_bytes:
317
        checksum = (checksum + b) & mask
318
    return checksum
319

    
320

    
321
# Send a command to the radio, return any reply stripping the echo of the
322
# command (tx and rx share a single pin in this radio)
323
def send_serial_command(serial, command, expectedlen=None):
324
    ''' send a command to the radio, and return any response.
325
    set expectedlen to return as soon as that many bytes are read.
326
    '''
327
    serial.write(command)
328
    serial.flush()
329

    
330
    response = b''
331
    tout = time.time() + 0.5
332
    while time.time() < tout:
333
        if serial.inWaiting():
334
            response += serial.read()
335
        # remember everything gets echo'd back
336
        if len(response) - len(command) == expectedlen:
337
            break
338

    
339
    # cut off what got echo'd back, we don't need to see it again
340
    if response.startswith(command):
341
        response = response[len(command):]
342

    
343
    return response
344

    
345

    
346
# strip trailing 0x00 to convert a string returned by bitwise.parse into a
347
# python string
348
def cstring_to_py_string(cstring):
349
    return "".join(c for c in cstring if c != '\x00')
350

    
351

    
352
# Check the radio version reported to see if it's one we support,
353
# returns bool version supported, and the band index
354
def check_ver(ver_response, allowed_types):
355
    ''' Check the returned radio version is one we approve of '''
356

    
357
    LOG.debug('ver_response = ')
358
    LOG.debug(util.hexprint(ver_response))
359

    
360
    resp = bitwise.parse(VER_FORMAT, ver_response)
361
    verok = False
362

    
363
    if resp.hdr == 0x49 and resp.ack == 0x06:
364
        model, version = [cstring_to_py_string(bitwise.get_string(s)).strip()
365
                          for s in (resp.model, resp.version)]
366
        LOG.debug('radio model: \'%s\' version: \'%s\'' %
367
                  (model, version))
368
        LOG.debug('allowed_types = %s' % allowed_types)
369

    
370
        if model in allowed_types:
371
            LOG.debug('model in allowed_types')
372

    
373
            if version in allowed_types[model]:
374
                LOG.debug('version in allowed_types[model]')
375
                verok = True
376
    else:
377
        raise errors.RadioError('Failed to parse version response')
378

    
379
    return verok, int(resp.bandlimit)
380

    
381

    
382
# Put the radio in programming mode, sending the initial command and checking
383
# the response.  raise RadioError if there is no response (500ms timeout), and
384
# if the returned version isn't matched by check_ver
385
def enter_program_mode(radio):
386
    serial = radio.pipe
387
    # place the radio in program mode, and confirm
388
    program_response = send_serial_command(serial, b'PROGRAM')
389

    
390
    if program_response != b'QX\x06':
391
        raise errors.RadioError('No initial response from radio.')
392
    LOG.debug('entered program mode')
393

    
394
    # read the radio ID string, make sure it matches one we know about
395
    ver_response = send_serial_command(serial, b'\x02')
396

    
397
    verok, bandlimit = check_ver(ver_response, radio.ALLOWED_RADIO_TYPES)
398
    if not verok:
399
        exit_program_mode(radio)
400
        raise errors.RadioError(
401
            'Radio version not in allowed list for %s-%s: %s' %
402
            (radio.VENDOR, radio.MODEL, util.hexprint(ver_response)))
403

    
404
    return bandlimit
405

    
406

    
407
# Exit programming mode
408
def exit_program_mode(radio):
409
    send_serial_command(radio.pipe, b'END')
410

    
411

    
412
# Parse a packet from the radio returning the header (R/W, address, data, and
413
# checksum valid
414
def parse_read_response(resp):
415
    addr = resp[:4]
416
    data = bytes(resp[4:-2])
417
    cs = checksum(ord(d) for d in resp[1:-2])
418
    valid = cs == ord(resp[-2])
419
    if not valid:
420
        LOG.error('checksumfail: %02x, expected %02x' % (cs, ord(resp[-2])))
421
        LOG.error('msg data: %s' % util.hexprint(resp))
422
    return addr, data, valid
423

    
424

    
425
# Download data from the radio and populate the memory map
426
def do_download(radio):
427
    '''Download memories from the radio'''
428

    
429
    # Get the serial port connection
430
    serial = radio.pipe
431

    
432
    try:
433
        enter_program_mode(radio)
434

    
435
        memory_data = bytes()
436

    
437
        # status info for the UI
438
        status = chirp_common.Status()
439
        status.cur = 0
440
        status.max = (MEMORY_ADDRESS_RANGE[1] -
441
                      MEMORY_ADDRESS_RANGE[0])/MEMORY_RW_BLOCK_SIZE
442
        status.msg = 'Cloning from radio...'
443
        radio.status_fn(status)
444

    
445
        for addr in range(MEMORY_ADDRESS_RANGE[0],
446
                          MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
447
                          MEMORY_RW_BLOCK_SIZE):
448
            read_command = struct.pack('>BHB', 0x52, addr,
449
                                       MEMORY_RW_BLOCK_SIZE)
450
            read_response = send_serial_command(serial, read_command,
451
                                                MEMORY_RW_BLOCK_CMD_SIZE)
452
            # LOG.debug('read response:\n%s' % util.hexprint(read_response))
453

    
454
            address, data, valid = parse_read_response(read_response)
455
            memory_data += data
456

    
457
            # update UI
458
            status.cur = (addr - MEMORY_ADDRESS_RANGE[0])\
459
                / MEMORY_RW_BLOCK_SIZE
460
            radio.status_fn(status)
461

    
462
        exit_program_mode(radio)
463
    except errors.RadioError as e:
464
        raise e
465
    except Exception as e:
466
        raise errors.RadioError('Failed to download from radio: %s' % e)
467

    
468
    return memmap.MemoryMapBytes(memory_data)
469

    
470

    
471
# Build a write data command to send to the radio
472
def make_write_data_cmd(addr, data, datalen):
473
    cmd = struct.pack('>BHB', 0x57, addr, datalen)
474
    cmd += data
475
    cs = checksum(ord(c) for c in cmd[1:])
476
    cmd += struct.pack('>BB', cs, 0x06)
477
    return cmd
478

    
479

    
480
# Upload a memory map to the radio
481
def do_upload(radio):
482
    try:
483
        bandlimit = enter_program_mode(radio)
484

    
485
        if bandlimit != radio._memobj.radio_settings.bandlimit:
486
            LOG.warning('radio and image bandlimits differ'
487
                        ' some channels many not work'
488
                        ' (img:0x%02x radio:0x%02x)' %
489
                        (int(bandlimit),
490
                         int(radio._memobj.radio_settings.bandlimit)))
491
            LOG.warning('radio bands: %s' % get_band_limits_Hz(
492
                         int(radio._memobj.radio_settings.bandlimit)))
493
            LOG.warning('img bands: %s' % get_band_limits_Hz(bandlimit))
494

    
495
        serial = radio.pipe
496

    
497
        # send the initial message, radio responds with something that looks a
498
        # bit like a bitfield, but I don't know what it is yet.
499
        read_command = struct.pack('>BHB', 0x52, 0x3b10, MEMORY_RW_BLOCK_SIZE)
500
        read_response = send_serial_command(serial, read_command,
501
                                            MEMORY_RW_BLOCK_CMD_SIZE)
502
        address, data, valid = parse_read_response(read_response)
503
        LOG.debug('Got initial response from radio: %s' %
504
                  util.hexprint(read_response))
505

    
506
        bptr = 0
507

    
508
        memory_addrs = range(MEMORY_ADDRESS_RANGE[0],
509
                             MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
510
                             MEMORY_RW_BLOCK_SIZE)
511

    
512
        # status info for the UI
513
        status = chirp_common.Status()
514
        status.cur = 0
515
        status.max = len(memory_addrs)
516
        status.msg = 'Cloning to radio...'
517
        radio.status_fn(status)
518

    
519
        for idx, addr in enumerate(memory_addrs):
520
            write_command = make_write_data_cmd(
521
                addr, radio._mmap[bptr:bptr+MEMORY_RW_BLOCK_SIZE],
522
                MEMORY_RW_BLOCK_SIZE)
523
            # LOG.debug('write data:\n%s' % util.hexprint(write_command))
524
            write_response = send_serial_command(serial, write_command, 0x01)
525
            bptr += MEMORY_RW_BLOCK_SIZE
526

    
527
            if write_response == '\x0a':
528
                # NACK from radio, e.g. checksum wrongn
529
                LOG.debug('Radio returned 0x0a - NACK:')
530
                LOG.debug(' * write cmd:\n%s' % util.hexprint(write_command))
531
                LOG.debug(' * write response:\n%s' %
532
                          util.hexprint(write_response))
533
                exit_program_mode(radio)
534
                raise errors.RadioError('Radio NACK\'d write command')
535

    
536
            # update UI
537
            status.cur = idx
538
            radio.status_fn(status)
539
        exit_program_mode(radio)
540
    except errors.RadioError:
541
        raise
542
    except Exception as e:
543
        raise errors.RadioError('Failed to download from radio: %s' % e)
544

    
545

    
546
# Get the value of @bitfield @number of bits in from 0
547
def get_bitfield(bitfield, number):
548
    ''' Get the value of @bitfield @number of bits in '''
549
    byteidx = number//8
550
    bitidx = number - (byteidx * 8)
551
    return bitfield[byteidx] & (1 << bitidx)
552

    
553

    
554
# Set the @value of @bitfield @number of bits in from 0
555
def set_bitfield(bitfield, number, value):
556
    ''' Set the @value of @bitfield @number of bits in '''
557
    byteidx = number//8
558
    bitidx = number - (byteidx * 8)
559
    if value is True:
560
        bitfield[byteidx] |= (1 << bitidx)
561
    else:
562
        bitfield[byteidx] &= ~(1 << bitidx)
563
    return bitfield
564

    
565

    
566
# Translate the radio's version of a code as stored to a real code
567
def dtcs_code_bits_to_val(highbit, lowbyte):
568
    return chirp_common.ALL_DTCS_CODES[highbit*256 + lowbyte]
569

    
570

    
571
# Translate the radio's version of a tone as stored to a real tone
572
def ctcss_tone_bits_to_val(tone_byte):
573
    # TODO use the custom setting 0x33 and ref the custom ctcss
574
    # field
575
    tone_byte = int(tone_byte)
576
    if tone_byte in TONE_MAP_VAL_TO_TONE:
577
        return TONE_MAP_VAL_TO_TONE[tone_byte]
578
    elif tone_byte == TONE_CUSTOM_CTCSS:
579
        LOG.info('custom ctcss not implemented (yet?).')
580
    else:
581
        raise errors.UnsupportedToneError('unknown ctcss tone value: %02x' %
582
                                          tone_byte)
583

    
584

    
585
# Translate a real tone to the radio's version as stored
586
def ctcss_code_val_to_bits(tone_value):
587
    if tone_value in TONE_MAP_TONE_TO_VAL:
588
        return TONE_MAP_TONE_TO_VAL[tone_value]
589
    else:
590
        raise errors.UnsupportedToneError('Tone %f not supported' % tone_value)
591

    
592

    
593
# Translate a real code to the radio's version as stored
594
def dtcs_code_val_to_bits(code):
595
    val = chirp_common.ALL_DTCS_CODES.index(code)
596
    return (val & 0xFF), ((val >> 8) & 0x01)
597

    
598

    
599
class AnyTone778UVBase(chirp_common.CloneModeRadio,
600
                       chirp_common.ExperimentalRadio):
601
    '''AnyTone 778UV and probably Retivis RT95 and others'''
602
    BAUD_RATE = 9600
603
    NEEDS_COMPAT_SERIAL = False
604

    
605
    @classmethod
606
    def get_prompts(cls):
607
        rp = chirp_common.RadioPrompts()
608

    
609
        rp.experimental = \
610
            ('This is experimental support for the %s %s.  '
611
             'Please send in bug and enhancement requests!' %
612
             (cls.VENDOR, cls.MODEL))
613

    
614
        return rp
615

    
616
    # Return information about this radio's features, including
617
    # how many memories it has, what bands it supports, etc
618
    def get_features(self):
619
        rf = chirp_common.RadioFeatures()
620
        rf.has_bank = False
621
        rf.has_settings = True
622
        rf.can_odd_split = True
623
        rf.has_name = True
624
        rf.has_offset = True
625
        rf.valid_name_length = 5
626
        rf.valid_duplexes = ['', '+', '-', 'split', 'off']
627
        rf.valid_characters = CHARSET_ASCII_PLUS
628

    
629
        rf.has_dtcs = True
630
        rf.has_rx_dtcs = True
631
        rf.has_dtcs_polarity = True
632
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES
633
        rf.has_ctone = True
634
        rf.has_cross = True
635
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
636
        rf.valid_cross_modes = ['Tone->Tone',
637
                                'Tone->DTCS',
638
                                'DTCS->Tone',
639
                                'DTCS->DTCS',
640
                                'DTCS->',
641
                                '->DTCS',
642
                                '->Tone']
643

    
644
        rf.memory_bounds = (1, 200)  # This radio supports memories 1-200
645
        try:
646
            rf.valid_bands = get_band_limits_Hz(
647
                int(self._memobj.radio_settings.bandlimit))
648
        except TypeError as e:
649
            # If we're asked without memory loaded, assume the most permissive
650
            rf.valid_bands = get_band_limits_Hz(1)
651
        except Exception as e:
652
            LOG.error('Failed to get band limits for anytone778uv: %s' % e)
653
            rf.valid_bands = get_band_limits_Hz(1)
654
        rf.valid_modes = ['FM', 'NFM']
655
        rf.valid_power_levels = POWER_LEVELS
656
        rf.valid_tuning_steps = [2.5, 5, 6.25, 10, 12.5, 20, 25, 30, 50]
657
        rf.has_tuning_step = False
658
        return rf
659

    
660
    # Do a download of the radio from the serial port
661
    def sync_in(self):
662
        self._mmap = do_download(self)
663
        self.process_mmap()
664

    
665
    # Do an upload of the radio to the serial port
666
    def sync_out(self):
667
        do_upload(self)
668

    
669
    # Convert the raw byte array into a memory object structure
670
    def process_mmap(self):
671
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
672

    
673
    # Return a raw representation of the memory object, which
674
    # is very helpful for development
675
    def get_raw_memory(self, number):
676
        return repr(self._memobj.memory[number - 1])
677

    
678
    # Extract a high-level memory object from the low-level memory map
679
    # This is called to populate a memory in the UI
680
    def get_memory(self, number):
681
        number -= 1
682
        # Get a low-level memory object mapped to the image
683
        _mem = self._memobj.memory[number]
684
        _mem_status = self._memobj.memory_status
685

    
686
        # Create a high-level memory object to return to the UI
687
        mem = chirp_common.Memory()
688
        mem.number = number + 1           # Set the memory number
689

    
690
        # Check if this memory is present in the occupied list
691
        mem.empty = get_bitfield(_mem_status.occupied_bitfield, number) == 0
692

    
693
        if not mem.empty:
694
            # Check if this memory is in the scan enabled list
695
            mem.skip = ''
696
            if get_bitfield(_mem_status.scan_enabled_bitfield, number) == 0:
697
                mem.skip = 'S'
698

    
699
            # set the name
700
            mem.name = str(_mem.name).rstrip()  # Set the alpha tag
701

    
702
            # Convert your low-level frequency and offset to Hertz
703
            mem.freq = int(_mem.freq) * 10
704
            mem.offset = int(_mem.offset) * 10
705

    
706
            # Set the duplex flags
707
            if _mem.duplex == DUPLEX_POSSPLIT:
708
                mem.duplex = '+'
709
            elif _mem.duplex == DUPLEX_NEGSPLIT:
710
                mem.duplex = '-'
711
            elif _mem.duplex == DUPLEX_NOSPLIT:
712
                mem.duplex = ''
713
            elif _mem.duplex == DUPLEX_ODDSPLIT:
714
                mem.duplex = 'split'
715
            else:
716
                LOG.error('%s: get_mem: unhandled duplex: %02x' %
717
                          (mem.name, _mem.duplex))
718

    
719
            # handle tx off
720
            if _mem.tx_off:
721
                mem.duplex = 'off'
722

    
723
            # Set the channel width
724
            if _mem.channel_width == CHANNEL_WIDTH_25kHz:
725
                mem.mode = 'FM'
726
            elif _mem.channel_width == CHANNEL_WIDTH_20kHz:
727
                LOG.info(
728
                    '%s: get_mem: promoting 20kHz channel width to 25kHz' %
729
                    mem.name)
730
                mem.mode = 'FM'
731
            elif _mem.channel_width == CHANNEL_WIDTH_12d5kHz:
732
                mem.mode = 'NFM'
733
            else:
734
                LOG.error('%s: get_mem: unhandled channel width: 0x%02x' %
735
                          (mem.name, _mem.channel_width))
736

    
737
            # set the power level
738
            if _mem.txpower == TXPOWER_LOW:
739
                mem.power = POWER_LEVELS[0]
740
            elif _mem.txpower == TXPOWER_MED:
741
                mem.power = POWER_LEVELS[1]
742
            elif _mem.txpower == TXPOWER_HIGH:
743
                mem.power = POWER_LEVELS[2]
744
            else:
745
                LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
746
                          (mem.name, _mem.txpower))
747

    
748
            # CTCSS Tones
749
            # TODO support custom ctcss tones here
750
            txtone = None
751
            rxtone = None
752
            rxcode = None
753
            txcode = None
754

    
755
            # check if dtcs tx is enabled
756
            if _mem.dtcs_encode_en:
757
                txcode = dtcs_code_bits_to_val(_mem.dtcs_encode_code_highbit,
758
                                               _mem.dtcs_encode_code)
759

    
760
            # check if dtcs rx is enabled
761
            if _mem.dtcs_decode_en:
762
                rxcode = dtcs_code_bits_to_val(_mem.dtcs_decode_code_highbit,
763
                                               _mem.dtcs_decode_code)
764

    
765
            if txcode is not None:
766
                LOG.debug('%s: get_mem dtcs_enc: %d' % (mem.name, txcode))
767
            if rxcode is not None:
768
                LOG.debug('%s: get_mem dtcs_dec: %d' % (mem.name, rxcode))
769

    
770
            # tsql set if radio squelches on tone
771
            tsql = _mem.tone_squelch_en
772

    
773
            # check if ctcss tx is enabled
774
            if _mem.ctcss_encode_en:
775
                txtone = ctcss_tone_bits_to_val(_mem.ctcss_enc_tone)
776

    
777
            # check if ctcss rx is enabled
778
            if _mem.ctcss_decode_en:
779
                rxtone = ctcss_tone_bits_to_val(_mem.ctcss_dec_tone)
780

    
781
            # Define this here to allow a readable if-else tree enabling tone
782
            # options
783
            enabled = 0
784
            enabled |= (txtone is not None) * TONES_EN_TXTONE
785
            enabled |= (rxtone is not None) * TONES_EN_RXTONE
786
            enabled |= (txcode is not None) * TONES_EN_TXCODE
787
            enabled |= (rxcode is not None) * TONES_EN_RXCODE
788

    
789
            # Add some debugging output for the tone bitmap
790
            enstr = []
791
            if enabled & TONES_EN_TXTONE:
792
                enstr += ['TONES_EN_TXTONE']
793
            if enabled & TONES_EN_RXTONE:
794
                enstr += ['TONES_EN_RXTONE']
795
            if enabled & TONES_EN_TXCODE:
796
                enstr += ['TONES_EN_TXCODE']
797
            if enabled & TONES_EN_RXCODE:
798
                enstr += ['TONES_EN_RXCODE']
799
            if enabled == 0:
800
                enstr = ['TONES_EN_NOTONE']
801
            LOG.debug('%s: enabled = %s' % (
802
                mem.name, '|'.join(enstr)))
803

    
804
            mem.tmode = ''
805
            if enabled == TONES_EN_NO_TONE:
806
                mem.tmode = ''
807
            elif enabled == TONES_EN_TXTONE:
808
                mem.tmode = 'Tone'
809
                mem.rtone = txtone
810
            elif enabled == TONES_EN_RXTONE and tsql:
811
                mem.tmode = 'Cross'
812
                mem.cross_mode = '->Tone'
813
                mem.ctone = rxtone
814
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXTONE) and tsql:
815
                if txtone == rxtone:  # TSQL
816
                    mem.tmode = 'TSQL'
817
                    mem.ctone = txtone
818
                else:  # Tone->Tone
819
                    mem.tmode = 'Cross'
820
                    mem.cross_mode = 'Tone->Tone'
821
                    mem.ctone = rxtone
822
                    mem.rtone = txtone
823
            elif enabled == TONES_EN_TXCODE:
824
                mem.tmode = 'Cross'
825
                mem.cross_mode = 'DTCS->'
826
                mem.dtcs = txcode
827
            elif enabled == TONES_EN_RXCODE and tsql:
828
                mem.tmode = 'Cross'
829
                mem.cross_mode = '->DTCS'
830
                mem.rx_dtcs = rxcode
831
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXCODE) and tsql:
832
                if rxcode == txcode:
833
                    mem.tmode = 'DTCS'
834
                    mem.rx_dtcs = rxcode
835
                    # #8327 Not sure this is the correct interpretation of
836
                    # DevelopersToneModes, but it seems to make it work round
837
                    # tripping with the anytone software.  DTM implies that we
838
                    # might not need to set mem.dtcs, but if we do it only DTCS
839
                    # rx works (as if we were Cross:None->DTCS).
840
                    mem.dtcs = rxcode
841
                else:
842
                    mem.tmode = 'Cross'
843
                    mem.cross_mode = 'DTCS->DTCS'
844
                    mem.rx_dtcs = rxcode
845
                    mem.dtcs = txcode
846
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXTONE) and tsql:
847
                mem.tmode = 'Cross'
848
                mem.cross_mode = 'DTCS->Tone'
849
                mem.dtcs = txcode
850
                mem.ctone = rxtone
851
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXCODE) and tsql:
852
                mem.tmode = 'Cross'
853
                mem.cross_mode = 'Tone->DTCS'
854
                mem.rx_dtcs = rxcode
855
                mem.rtone = txtone
856
            else:
857
                LOG.error('%s: Unhandled tmode enabled = %d.' % (
858
                    mem.name, enabled))
859

    
860
                # Can get here if e.g. TONE_EN_RXCODE is set and tsql isn't
861
                # In that case should we perhaps store the tone and code values
862
                # if they're present and then setup tmode and cross_mode as
863
                # appropriate later?
864

    
865
            # set the dtcs polarity
866
            dtcs_pol_bit_to_str = {0: 'N', 1: 'R'}
867
            mem.dtcs_polarity = '%s%s' %\
868
                (dtcs_pol_bit_to_str[_mem.dtcs_encode_invert == 1],
869
                 dtcs_pol_bit_to_str[_mem.dtcs_decode_invert == 1])
870

    
871
        return mem
872

    
873
    # Store details about a high-level memory to the memory map
874
    # This is called when a user edits a memory in the UI
875
    def set_memory(self, mem):
876
        # Get a low-level memory object mapped to the image
877
        _mem = self._memobj.memory[mem.number - 1]
878
        _mem_status = self._memobj.memory_status
879

    
880
        # set the occupied bitfield
881
        _mem_status.occupied_bitfield = \
882
            set_bitfield(_mem_status.occupied_bitfield, mem.number - 1,
883
                         not mem.empty)
884

    
885
        # set the scan add bitfield
886
        _mem_status.scan_enabled_bitfield = \
887
            set_bitfield(_mem_status.scan_enabled_bitfield, mem.number - 1,
888
                         (not mem.empty) and (mem.skip != 'S'))
889

    
890
        if mem.empty:
891
            # Set the whole memory to 0xff
892
            _mem.set_raw('\xff' * (_mem.size() / 8))
893
        else:
894
            _mem.set_raw('\x00' * (_mem.size() / 8))
895

    
896
            _mem.freq = int(mem.freq / 10)
897
            _mem.offset = int(mem.offset / 10)
898

    
899
            _mem.name = mem.name.ljust(5)[:5]  # Store the alpha tag
900

    
901
            # TODO support busy channel lockout - disabled for now
902
            _mem.busy_channel_lockout = BUSY_CHANNEL_LOCKOUT_OFF
903

    
904
            # Set duplex bitfields
905
            if mem.duplex == '+':
906
                _mem.duplex = DUPLEX_POSSPLIT
907
            elif mem.duplex == '-':
908
                _mem.duplex = DUPLEX_NEGSPLIT
909
            elif mem.duplex == '':
910
                _mem.duplex = DUPLEX_NOSPLIT
911
            elif mem.duplex == 'split':
912
                # TODO: this is an unverified punt!
913
                _mem.duplex = DUPLEX_ODDSPLIT
914
            else:
915
                LOG.error('%s: set_mem: unhandled duplex: %s' %
916
                          (mem.name, mem.duplex))
917

    
918
            # handle tx off
919
            _mem.tx_off = 0
920
            if mem.duplex == 'off':
921
                _mem.tx_off = 1
922

    
923
            # Set the channel width - remember we promote 20kHz channels to FM
924
            # on import
925
            # , so don't handle them here
926
            if mem.mode == 'FM':
927
                _mem.channel_width = CHANNEL_WIDTH_25kHz
928
            elif mem.mode == 'NFM':
929
                _mem.channel_width = CHANNEL_WIDTH_12d5kHz
930
            else:
931
                LOG.error('%s: set_mem: unhandled mode: %s' % (
932
                    mem.name, mem.mode))
933

    
934
            # set the power level
935
            if mem.power == POWER_LEVELS[0]:
936
                _mem.txpower = TXPOWER_LOW
937
            elif mem.power == POWER_LEVELS[1]:
938
                _mem.txpower = TXPOWER_MED
939
            elif mem.power == POWER_LEVELS[2]:
940
                _mem.txpower = TXPOWER_HIGH
941
            else:
942
                LOG.error('%s: set_mem: unhandled power level: %s' %
943
                          (mem.name, mem.power))
944

    
945
            # TODO set the CTCSS values
946
            # TODO support custom ctcss tones here
947
            # Default - tones off, carrier sql
948
            _mem.ctcss_encode_en = 0
949
            _mem.ctcss_decode_en = 0
950
            _mem.tone_squelch_en = 0
951
            _mem.ctcss_enc_tone = 0x00
952
            _mem.ctcss_dec_tone = 0x00
953
            _mem.customctcss = 0x00
954
            _mem.dtcs_encode_en = 0
955
            _mem.dtcs_encode_code_highbit = 0
956
            _mem.dtcs_encode_code = 0
957
            _mem.dtcs_encode_invert = 0
958
            _mem.dtcs_decode_en = 0
959
            _mem.dtcs_decode_code_highbit = 0
960
            _mem.dtcs_decode_code = 0
961
            _mem.dtcs_decode_invert = 0
962

    
963
            dtcs_pol_str_to_bit = {'N': 0, 'R': 1}
964
            _mem.dtcs_encode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[0]]
965
            _mem.dtcs_decode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[1]]
966

    
967
            if mem.tmode == 'Tone':
968
                _mem.ctcss_encode_en = 1
969
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
970
            elif mem.tmode == 'TSQL':
971
                _mem.ctcss_encode_en = 1
972
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.ctone)
973
                _mem.ctcss_decode_en = 1
974
                _mem.tone_squelch_en = 1
975
                _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
976
            elif mem.tmode == 'DTCS':
977
                _mem.dtcs_encode_en = 1
978
                _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
979
                    dtcs_code_val_to_bits(mem.rx_dtcs)
980
                _mem.dtcs_decode_en = 1
981
                _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
982
                    dtcs_code_val_to_bits(mem.rx_dtcs)
983
                _mem.tone_squelch_en = 1
984
            elif mem.tmode == 'Cross':
985
                txmode, rxmode = mem.cross_mode.split('->')
986

    
987
                if txmode == 'Tone':
988
                    _mem.ctcss_encode_en = 1
989
                    _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
990
                elif txmode == '':
991
                    pass
992
                elif txmode == 'DTCS':
993
                    _mem.dtcs_encode_en = 1
994
                    _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
995
                        dtcs_code_val_to_bits(mem.dtcs)
996
                else:
997
                    LOG.error('%s: unhandled cross TX mode: %s' % (
998
                        mem.name, mem.cross_mode))
999

    
1000
                if rxmode == 'Tone':
1001
                    _mem.ctcss_decode_en = 1
1002
                    _mem.tone_squelch_en = 1
1003
                    _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
1004
                elif rxmode == '':
1005
                    pass
1006
                elif rxmode == 'DTCS':
1007
                    _mem.dtcs_decode_en = 1
1008
                    _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
1009
                        dtcs_code_val_to_bits(mem.rx_dtcs)
1010
                    _mem.tone_squelch_en = 1
1011
                else:
1012
                    LOG.error('%s: unhandled cross RX mode: %s' % (
1013
                        mem.name, mem.cross_mode))
1014
            else:
1015
                LOG.error('%s: Unhandled tmode/cross %s/%s.' %
1016
                          (mem.name, mem.tmode, mem.cross_mode))
1017
            LOG.debug('%s: tmode=%s, cross=%s, rtone=%f, ctone=%f' % (
1018
                mem.name, mem.tmode, mem.cross_mode, mem.rtone, mem.ctone))
1019
            LOG.debug('%s: CENC=%d, CDEC=%d, t(enc)=%02x, t(dec)=%02x' % (
1020
                mem.name,
1021
                _mem.ctcss_encode_en,
1022
                _mem.ctcss_decode_en,
1023
                ctcss_code_val_to_bits(mem.rtone),
1024
                ctcss_code_val_to_bits(mem.ctone)))
1025

    
1026
            # set unknown defaults, based on reading memory set by vendor tool
1027
            _mem.unknown1 = 0x00
1028
            _mem.unknown6 = 0x00
1029
            _mem.unknown7 = 0x00
1030
            _mem.unknown8 = 0x00
1031
            _mem.unknown9 = 0x00
1032
            _mem.unknown10 = 0x00
1033

    
1034
    def get_settings(self):
1035
        """Translate the MEM_FORMAT structs into setstuf in the UI"""
1036
        _pfkeys = self._memobj.pfkeys
1037
        _settings = self._memobj.settings
1038
        _radio_settings = self._memobj.radio_settings
1039
        _password = self._memobj.password
1040

    
1041
        # Function Setup
1042
        function = RadioSettingGroup("function", "Function Setup")
1043
        group = RadioSettings(function)
1044

    
1045
        # MODE SET
1046
        # Channel Locked
1047
        rs = RadioSettingValueBoolean(_settings.channelLocked)
1048
        rset = RadioSetting("settings.channelLocked", "Channel locked", rs)
1049
        function.append(rset)
1050

    
1051
        # Menu 3 - Display Mode
1052
        options = ["Frequency", "Channel", "Name"]
1053
        rs = RadioSettingValueList(options, options[_settings.displayMode])
1054
        rset = RadioSetting("settings.displayMode", "Display Mode", rs)
1055
        function.append(rset)
1056

    
1057
        # VFO/MR A
1058
        options = ["MR", "VFO"]
1059
        rs = RadioSettingValueList(options, options[_radio_settings.vfomrA])
1060
        rset = RadioSetting("radio_settings.vfomrA", "VFO/MR mode A", rs)
1061
        function.append(rset)
1062

    
1063
        # MR Channel A
1064
        options = ["%s" % x for x in range(1, 201)]
1065
        rs = RadioSettingValueList(options, options[_radio_settings.mrChanA])
1066
        rset = RadioSetting("radio_settings.mrChanA", "MR channel A", rs)
1067
        function.append(rset)
1068

    
1069
        # VFO/MR B
1070
        options = ["MR", "VFO"]
1071
        rs = RadioSettingValueList(options, options[_radio_settings.vfomrB])
1072
        rset = RadioSetting("radio_settings.vfomrB", "VFO/MR mode B", rs)
1073
        function.append(rset)
1074

    
1075
        # MR Channel B
1076
        options = ["%s" % x for x in range(1, 201)]
1077
        rs = RadioSettingValueList(options, options[_radio_settings.mrChanB])
1078
        rset = RadioSetting("radio_settings.mrChanB", "MR channel B", rs)
1079
        function.append(rset)
1080

    
1081
        # DISPLAY SET
1082
        # Starting Display
1083
        name = ""
1084
        for i in range(7):  # 0 - 7
1085
            name += chr(self._memobj.starting_display.line[i])
1086
        name = name.rstrip()  # remove trailing spaces
1087

    
1088
        rs = RadioSettingValueString(0, 7, name)
1089
        rset = RadioSetting("starting_display.line", "Starting display", rs)
1090
        function.append(rset)
1091

    
1092
        # Menu 11 - Backlight Brightness
1093
        options = ["%s" % x for x in range(1, 4)]
1094
        rs = RadioSettingValueList(options, options[_settings.backlightBr - 1])
1095
        rset = RadioSetting("settings.backlightBr", "Backlight brightness", rs)
1096
        function.append(rset)
1097

    
1098
        # Menu 15 - Screen Direction
1099
        options = ["Positive", "Inverted"]
1100
        rs = RadioSettingValueList(options, options[_settings.screenDir])
1101
        rset = RadioSetting("settings.screenDir", "Screen direction", rs)
1102
        function.append(rset)
1103

    
1104
        # Hand Mic Key Brightness
1105
        options = ["%s" % x for x in range(1, 32)]
1106
        rs = RadioSettingValueList(options, options[_settings.micKeyBrite - 1])
1107
        rset = RadioSetting("settings.micKeyBrite",
1108
                            "Hand mic key brightness", rs)
1109
        function.append(rset)
1110

    
1111
        # VOL SET
1112
        # Menu 1 - Beep Volume
1113
        options = ["OFF"] + ["%s" % x for x in range(1, 6)]
1114
        rs = RadioSettingValueList(options, options[_settings.beepVolume])
1115
        rset = RadioSetting("settings.beepVolume", "Beep volume", rs)
1116
        function.append(rset)
1117

    
1118
        # Menu 5 - Volume level Setup
1119
        options = ["%s" % x for x in range(1, 37)]
1120
        rs = RadioSettingValueList(options, options[_settings.speakerVol - 1])
1121
        rset = RadioSetting("settings.speakerVol", "Speaker volume", rs)
1122
        function.append(rset)
1123

    
1124
        # Menu 16 - Speaker Switch
1125
        options = ["Host on | Hand mic off", "Host on | Hand mic on",
1126
                   "Host off | Hand mic on"]
1127
        rs = RadioSettingValueList(options, options[_settings.speakerSwitch])
1128
        rset = RadioSetting("settings.speakerSwitch", "Speaker switch", rs)
1129
        function.append(rset)
1130

    
1131
        # STE SET
1132
        # STE Frequency
1133
        options = ["Off", "55.2 Hz", "259.2 Hz"]
1134
        rs = RadioSettingValueList(options, options[_settings.steFrequency])
1135
        rset = RadioSetting("settings.steFrequency", "STE frequency", rs)
1136
        function.append(rset)
1137

    
1138
        # STE Type
1139
        options = ["Off", "Silent", "120 degrees", "180 degrees",
1140
                   "240 degrees"]
1141
        rs = RadioSettingValueList(options, options[_settings.steType])
1142
        rset = RadioSetting("settings.steType", "STE type", rs)
1143
        function.append(rset)
1144

    
1145
        # ON/OFF SET
1146
        # Power-on Password
1147
        rs = RadioSettingValueBoolean(_settings.powerOnPasswd)
1148
        rset = RadioSetting("settings.powerOnPasswd", "Power-on Password", rs)
1149
        function.append(rset)
1150

    
1151
        # Password
1152
        def _char_to_str(chrx):
1153
            """ Remove ff pads from char array """
1154
            #  chrx is char array
1155
            str1 = ""
1156
            for sx in chrx:
1157
                if int(sx) > 31 and int(sx) < 127:
1158
                    str1 += chr(sx)
1159
            return str1
1160

    
1161
        def _pswd_vfy(setting, obj, atrb):
1162
            """ Verify password is 1-6 chars, numbers 1-5 """
1163
            str1 = str(setting.value).strip()   # initial
1164
            str2 = filter(lambda c: c in '0123456789', str1)    # valid chars
1165
            if str1 != str2:
1166
                # Two lines due to python 73 char limit
1167
                sx = "Bad characters in Password"
1168
                raise errors.RadioError(sx)
1169
            str2 = str1.ljust(6, chr(00))      # pad to 6 with 00's
1170
            setattr(obj, atrb, str2)
1171
            return
1172

    
1173
        sx = _char_to_str(_password.digits).strip()
1174
        rx = RadioSettingValueString(0, 6, sx)
1175
        sx = "Password (numerals 0-9)"
1176
        rset = RadioSetting("password.digits", sx, rx)
1177
        rset.set_apply_callback(_pswd_vfy, _password, "digits")
1178
        function.append(rset)
1179

    
1180
        # Menu 9 - Auto Power On
1181
        rs = RadioSettingValueBoolean(_settings.autoPowerOn)
1182
        rset = RadioSetting("settings.autoPowerOn", "Auto power on", rs)
1183
        function.append(rset)
1184

    
1185
        # Menu 13 - Auto Power Off
1186
        options = ["Off", "30 minutes", "60 minutes", "120 minutes"]
1187
        rs = RadioSettingValueList(options, options[_settings.autoPowerOff])
1188
        rset = RadioSetting("settings.autoPowerOff", "Auto power off", rs)
1189
        function.append(rset)
1190

    
1191
        # Power On Reset Enable
1192
        rs = RadioSettingValueBoolean(_settings.powerOnReset)
1193
        rset = RadioSetting("settings.powerOnReset", "Power on reset", rs)
1194
        function.append(rset)
1195

    
1196
        # FUNCTION SET
1197
        # Menu 4 - Squelch Level A
1198
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
1199
        rs = RadioSettingValueList(options, options[_settings.squelchLevelA])
1200
        rset = RadioSetting("settings.squelchLevelA", "Squelch level A", rs)
1201
        function.append(rset)
1202

    
1203
        # Squelch Level B
1204
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
1205
        rs = RadioSettingValueList(options, options[_settings.squelchLevelB])
1206
        rset = RadioSetting("settings.squelchLevelB", "Squelch level B", rs)
1207
        function.append(rset)
1208

    
1209
        # Menu 7 - Scan Type
1210
        options = ["Time operated (TO)", "Carrier operated (CO)",
1211
                   "Search (SE)"]
1212
        rs = RadioSettingValueList(options, options[_settings.scanType])
1213
        rset = RadioSetting("settings.scanType", "Scan mode", rs)
1214
        function.append(rset)
1215

    
1216
        # Menu 8 - Scan Recovery Time
1217
        options = ["%s seconds" % x for x in range(5, 20, 5)]
1218
        rs = RadioSettingValueList(options, options[_settings.scanRecoveryT])
1219
        rset = RadioSetting("settings.scanRecoveryT", "Scan recovery time", rs)
1220
        function.append(rset)
1221

    
1222
        # Main
1223
        options = ["A", "B"]
1224
        rs = RadioSettingValueList(options, options[_settings.main])
1225
        rset = RadioSetting("settings.main", "Main", rs)
1226
        function.append(rset)
1227

    
1228
        # Menu 10 - Dual Watch (RX Way Select)
1229
        rs = RadioSettingValueBoolean(_settings.dualWatch)
1230
        rset = RadioSetting("settings.dualWatch", "Dual watch", rs)
1231
        function.append(rset)
1232

    
1233
        # Menu 12 - Time Out Timer
1234
        options = ["OFF"] + ["%s minutes" % x for x in range(1, 31)]
1235
        rs = RadioSettingValueList(options, options[_settings.timeOutTimer])
1236
        rset = RadioSetting("settings.timeOutTimer", "Time out timer", rs)
1237
        function.append(rset)
1238

    
1239
        # TBST Frequency
1240
        options = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"]
1241
        rs = RadioSettingValueList(options, options[_settings.tbstFrequency])
1242
        rset = RadioSetting("settings.tbstFrequency", "TBST frequency", rs)
1243
        function.append(rset)
1244

    
1245
        # Save Channel Perameter
1246
        rs = RadioSettingValueBoolean(_settings.saveChParameter)
1247
        rset = RadioSetting("settings.saveChParameter",
1248
                            "Save channel parameter", rs)
1249
        function.append(rset)
1250

    
1251
        # MON Key Function
1252
        options = ["Squelch off momentary", "Squelch off"]
1253
        rs = RadioSettingValueList(options, options[_settings.monKeyFunction])
1254
        rset = RadioSetting("settings.monKeyFunction", "MON key function", rs)
1255
        function.append(rset)
1256

    
1257
        # Frequency Step
1258
        options = ["2.5 KHz", "5 KHz", "6.25 KHz", "10 KHz", "12.5 KHz",
1259
                   "20 KHz", "25 KHz", "30 KHz", "50 KHz"]
1260
        rs = RadioSettingValueList(options, options[_settings.frequencyStep])
1261
        rset = RadioSetting("settings.frequencyStep", "Frequency step", rs)
1262
        function.append(rset)
1263

    
1264
        # Knob Mode
1265
        options = ["Volume", "Channel"]
1266
        rs = RadioSettingValueList(options, options[_settings.knobMode])
1267
        rset = RadioSetting("settings.knobMode", "Knob mode", rs)
1268
        function.append(rset)
1269

    
1270
        # TRF Enable
1271
        rs = RadioSettingValueBoolean(_settings.trfEnable)
1272
        rset = RadioSetting("settings.trfEnable", "TRF enable", rs)
1273
        function.append(rset)
1274

    
1275
        # Key Assignment
1276
        pfkeys = RadioSettingGroup("pfkeys", "Key Assignment")
1277
        group.append(pfkeys)
1278

    
1279
        options = ["A/B", "V/M", "SQL", "VOL", "POW", "CDT", "REV", "SCN",
1280
                   "CAL", "TALK", "BND", "SFT", "MON", "DIR", "TRF", "RDW",
1281
                   "NULL"]
1282

    
1283
        # Key Mode 1
1284
        # P1
1285
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P1 - 1])
1286
        rset = RadioSetting("pfkeys.keyMode1P1",
1287
                            "Key mode 1 P1", rs)
1288
        pfkeys.append(rset)
1289

    
1290
        # P2
1291
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P2 - 1])
1292
        rset = RadioSetting("pfkeys.keyMode1P2",
1293
                            "Key mode 1 P2", rs)
1294
        pfkeys.append(rset)
1295

    
1296
        # P3
1297
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P3 - 1])
1298
        rset = RadioSetting("pfkeys.keyMode1P3",
1299
                            "Key mode 1 P3", rs)
1300
        pfkeys.append(rset)
1301

    
1302
        # P4
1303
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P4 - 1])
1304
        rset = RadioSetting("pfkeys.keyMode1P4",
1305
                            "Key mode 1 P4", rs)
1306
        pfkeys.append(rset)
1307

    
1308
        # P5
1309
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P5 - 1])
1310
        rset = RadioSetting("pfkeys.keyMode1P5",
1311
                            "Key mode 1 P5", rs)
1312
        pfkeys.append(rset)
1313

    
1314
        # P6
1315
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P6 - 1])
1316
        rset = RadioSetting("pfkeys.keyMode1P6",
1317
                            "Key mode 1 P6", rs)
1318
        pfkeys.append(rset)
1319

    
1320
        # Key Mode 2
1321
        # P1
1322
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P1 - 1])
1323
        rset = RadioSetting("pfkeys.keyMode2P1",
1324
                            "Key mode 2 P1", rs)
1325
        pfkeys.append(rset)
1326

    
1327
        # P2
1328
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P2 - 1])
1329
        rset = RadioSetting("pfkeys.keyMode2P2",
1330
                            "Key mode 2 P2", rs)
1331
        pfkeys.append(rset)
1332

    
1333
        # P3
1334
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P3 - 1])
1335
        rset = RadioSetting("pfkeys.keyMode2P3",
1336
                            "Key mode 2 P3", rs)
1337
        pfkeys.append(rset)
1338

    
1339
        # P4
1340
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P4 - 1])
1341
        rset = RadioSetting("pfkeys.keyMode2P4",
1342
                            "Key mode 2 P4", rs)
1343
        pfkeys.append(rset)
1344

    
1345
        # P5
1346
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P5 - 1])
1347
        rset = RadioSetting("pfkeys.keyMode2P5",
1348
                            "Key mode 2 P5", rs)
1349
        pfkeys.append(rset)
1350

    
1351
        # P6
1352
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P6 - 1])
1353
        rset = RadioSetting("pfkeys.keyMode2P6",
1354
                            "Key mode 2 P6", rs)
1355
        pfkeys.append(rset)
1356

    
1357
        options = ["V/M", "SQL", "VOL", "POW", "CDT", "REV", "SCN", "CAL",
1358
                   "TALK", "BND", "SFT", "MON", "DIR", "TRF", "RDW"]
1359

    
1360
        # PA
1361
        rs = RadioSettingValueList(options, options[_settings.keyPA - 2])
1362
        rset = RadioSetting("settings.keyPA",
1363
                            "Key PA", rs)
1364
        pfkeys.append(rset)
1365

    
1366
        # PB
1367
        rs = RadioSettingValueList(options, options[_settings.keyPB - 2])
1368
        rset = RadioSetting("settings.keyPB",
1369
                            "Key PB", rs)
1370
        pfkeys.append(rset)
1371

    
1372
        # PC
1373
        rs = RadioSettingValueList(options, options[_settings.keyPC - 2])
1374
        rset = RadioSetting("settings.keyPC",
1375
                            "Key PC", rs)
1376
        pfkeys.append(rset)
1377

    
1378
        # PD
1379
        rs = RadioSettingValueList(options, options[_settings.keyPD - 2])
1380
        rset = RadioSetting("settings.keyPD",
1381
                            "Key PD", rs)
1382
        pfkeys.append(rset)
1383

    
1384
        return group
1385

    
1386
    def set_settings(self, settings):
1387
        _settings = self._memobj.settings
1388
        _mem = self._memobj
1389
        for element in settings:
1390
            if not isinstance(element, RadioSetting):
1391
                self.set_settings(element)
1392
                continue
1393
            else:
1394
                try:
1395
                    name = element.get_name()
1396
                    if "." in name:
1397
                        bits = name.split(".")
1398
                        obj = self._memobj
1399
                        for bit in bits[:-1]:
1400
                            if "/" in bit:
1401
                                bit, index = bit.split("/", 1)
1402
                                index = int(index)
1403
                                obj = getattr(obj, bit)[index]
1404
                            else:
1405
                                obj = getattr(obj, bit)
1406
                        setting = bits[-1]
1407
                    else:
1408
                        obj = _settings
1409
                        setting = element.get_name()
1410

    
1411
                    if element.has_apply_callback():
1412
                        LOG.debug("Using apply callback")
1413
                        element.run_apply_callback()
1414
                    elif setting == "backlightBr":
1415
                        setattr(obj, setting, int(element.value) + 1)
1416
                    elif setting == "micKeyBrite":
1417
                        setattr(obj, setting, int(element.value) + 1)
1418
                    elif setting == "speakerVol":
1419
                        setattr(obj, setting, int(element.value) + 1)
1420
                    elif "keyMode" in setting:
1421
                        setattr(obj, setting, int(element.value) + 1)
1422
                    elif "keyP" in setting:
1423
                        setattr(obj, setting, int(element.value) + 2)
1424
                    elif element.value.get_mutable():
1425
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1426
                        setattr(obj, setting, element.value)
1427
                except Exception, e:
1428
                    LOG.debug(element.get_name())
1429
                    raise
1430

    
1431
if has_future:
1432
    @directory.register
1433
    class AnyTone778UV(AnyTone778UVBase):
1434
        VENDOR = "AnyTone"
1435
        MODEL = "778UV"
1436
        # Allowed radio types is a dict keyed by model of a list of version
1437
        # strings
1438
        ALLOWED_RADIO_TYPES = {'AT778UV': ['V100', 'V200']}
1439

    
1440
    @directory.register
1441
    class RetevisRT95(AnyTone778UVBase):
1442
        VENDOR = "Retevis"
1443
        MODEL = "RT95"
1444
        # Allowed radio types is a dict keyed by model of a list of version
1445
        # strings
1446
        ALLOWED_RADIO_TYPES = {'RT95': ['V100']}
1447

    
1448
    @directory.register
1449
    class CRTMicronUV(AnyTone778UVBase):
1450
        VENDOR = "CRT"
1451
        MODEL = "Micron UV"
1452
        # Allowed radio types is a dict keyed by model of a list of version
1453
        # strings
1454
        ALLOWED_RADIO_TYPES = {'MICRON': ['V100']}
1455

    
1456
    @directory.register
1457
    class MidlandDBR2500(AnyTone778UVBase):
1458
        VENDOR = "Midland"
1459
        MODEL = "DBR2500"
1460
        # Allowed radio types is a dict keyed by model of a list of version
1461
        # strings
1462
        ALLOWED_RADIO_TYPES = {'DBR2500': ['V100']}
1463

    
1464
    @directory.register
1465
    class YedroYCM04vus(AnyTone778UVBase):
1466
        VENDOR = "Yedro"
1467
        MODEL = "YC-M04VUS"
1468
        # Allowed radio types is a dict keyed by model of a list of version
1469
        # strings
1470
        ALLOWED_RADIO_TYPES = {'YCM04UV': ['V100']}