Project

General

Profile

New Model #8859 » anytone778uv_vox3.py

Jim Unroe, 03/08/2021 08:01 PM

 
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 0x1990;
125
struct {
126
  u8 code[16];            // DTMF Encode M1-M16
127
} pttid[16];
128

    
129
#seekto 0x1A90;
130
struct {
131
  u8 pttIdStart[16];      // 0x1A90 ptt id starting
132
  u8 pttIdEnd[16];        // 0x1AA0 ptt id ending
133
  u8 remoteStun[16];      // 0x1AB0 remotely stun
134
  u8 remoteKill[16];      // 0x1AC0 remotely kill
135
  u8 intervalChar;        // 0x1AD0 dtmf interval character
136
  u8 groupCode;           // 0x1AD1 group code
137
  u8 unk1ad2:6,           // 0x1AD2
138
     decodingResponse:2;  //        decoding response
139
  u8 pretime;             // 0x1AD3 pretime
140
  u8 firstDigitTime;      // 0x1AD4 first digit time
141
  u8 autoResetTime;       // 0x1AD5 auto reset time
142
  u8 selfID[3];           // 0x1AD6 dtmf self id
143
  u8 unk1ad9:7,           // 0x1AD9
144
     sideTone:1;          //        side tone
145
  u8 timeLapse;           // 0x1ADA time-lapse after encode
146
  u8 pauseTime;           // 0x1ADB ptt id pause time
147
} dtmf;
148

    
149
#seekto 0x3200;
150
struct {
151
  u8 unk3200:5,           // 0x3200
152
     beepVolume:3;        //        beep volume
153
  u8 unk3201:4,           // 0x3201
154
     frequencyStep:4;     //        frequency step
155
  u8 unk3202:6,           // 0x3202
156
     displayMode:2;       // display mode
157
  u8 unk0x3203;
158
  u8 unk3204:4,           // 0x3204
159
     squelchLevelA:4;     //        squelch level a
160
  u8 unk3205:4,           // 0x3205
161
     squelchLevelB:4;     //        squelch level b
162
  u8 unk3206:2,           // 0x3206
163
     speakerVol:6;        //        speaker volume
164
  u8 unk3207:7,           // 0x3207
165
     powerOnPasswd:1;     //        power-on password
166
  u8 unk3208:6,           // 0x3208
167
     scanType:2;          //        scan type
168
  u8 unk3209:6,           // 0x3209
169
     scanRecoveryT:2;     //        scan recovery time
170
  u8 unk320a:7,           // 0x320A
171
     autoPowerOn:1;       //        auto power on
172
  u8 unk320b:7,           // 0x320B
173
     main:1;              //        main
174
  u8 unk320c:7,           // 0x320C
175
     dualWatch:1;         //        dual watch (rx way select)
176
  u8 unk320d:5,           // 0x320D
177
     backlightBr:3;       //        backlight brightness
178
  u8 unk320e:3,           // 0x320E
179
     timeOutTimer:5;      //        time out timer
180
  u8 unk320f:6,           // 0x320F
181
     autoPowerOff:2;      //        auto power off
182
  u8 unk3210:6,           // 0x3210
183
     tbstFrequency:2;     //        tbst frequency
184
  u8 unk3211:7,           // 0x3211
185
     screenDir:1;         //        screen direction
186
  u8 unk3212:2,           // 0x3212
187
     micKeyBrite:6;       //        hand mic key brightness
188
  u8 unk3213:6,           // 0x3213
189
     speakerSwitch:2;     //        speaker switch
190
  u8 keyPA;               // 0x3214 key pa
191
  u8 keyPB;               // 0x3215 key pb
192
  u8 keyPC;               // 0x3216 key pc
193
  u8 keyPD;               // 0x3217 key pd
194
  u8 unk3218:5,           // 0x3218
195
     steType:3;           //        ste type
196
  u8 unk3219:6,           // 0x3219
197
     steFrequency:2;      //        ste frequency
198
  u8 unk321a:5,           // 0x321A
199
     dtmfTxTime:3;        //        dtmf transmitting time
200
  u8 unk_bit7_6:2,        // 0x321B
201
     monKeyFunction:1,    //        mon key function
202
     channelLocked:1,     //        channel locked
203
     saveChParameter:1,   //        save channel parameter
204
     powerOnReset:1,      //        power on reset
205
     trfEnable:1,         //        trf enable
206
     knobMode:1;          //        knob mode
207
} settings;
208

    
209
#seekto 0x3240;
210
struct {
211
  char digits[6];         // password
212
} password;
213

    
214
#seekto 0x3250;
215
struct {
216
  u8 keyMode1P1;          // 0x3250 key mode 1 p1
217
  u8 keyMode1P2;          // 0x3251 key mode 1 p2
218
  u8 keyMode1P3;          // 0x3252 key mode 1 p3
219
  u8 keyMode1P4;          // 0x3253 key mode 1 p4
220
  u8 keyMode1P5;          // 0x3254 key mode 1 p5
221
  u8 keyMode1P6;          // 0x3255 key mode 1 p6
222
  u8 keyMode2P1;          // 0x3256 key mode 2 p1
223
  u8 keyMode2P2;          // 0x3257 key mode 2 p2
224
  u8 keyMode2P3;          // 0x3258 key mode 2 p3
225
  u8 keyMode2P4;          // 0x3259 key mode 2 p4
226
  u8 keyMode2P5;          // 0x325A key mode 2 p5
227
  u8 keyMode2P6;          // 0x325B key mode 2 p6
228
} pfkeys;
229

    
230
#seekto 0x3260;
231
struct {
232
  u8 mrChanA;             // 0x3260 mr channel a
233
  u8 unknown1_0:7,        // 0x3261
234
     vfomrA:1;            //        vfo/mr mode a
235
  u8 unknown2;
236
  u8 unknown3;
237
  u8 unknown4;
238
  u8 unknown5;
239
  u8 unknown6;
240
  u8 mrChanB;             // 0x3267 mr channel b
241
  u8 unknown8_0:4,        // 0x3268
242
     scan_active:1,
243
     unknown8_1:2,
244
     vfomrB:1;            //        vfo/mr mode b
245
  u8 unknown9;
246
  u8 unknowna;
247
  u8 unknownb;
248
  u8 unknownc;
249
  u8 bandlimit;           // 0x326D mode
250
  u8 unknownd;
251
  u8 unknowne;
252
  u8 unknownf;
253
} radio_settings;
254
'''
255

    
256
# Format for the version messages returned by the radio
257
VER_FORMAT = '''
258
u8 hdr;
259
char model[7];
260
u8 bandlimit;
261
char version[6];
262
u8 ack;
263
'''
264

    
265
TXPOWER_LOW = 0x00
266
TXPOWER_MED = 0x01
267
TXPOWER_HIGH = 0x02
268

    
269
DUPLEX_NOSPLIT = 0x00
270
DUPLEX_POSSPLIT = 0x01
271
DUPLEX_NEGSPLIT = 0x02
272
DUPLEX_ODDSPLIT = 0x03
273

    
274
CHANNEL_WIDTH_25kHz = 0x02
275
CHANNEL_WIDTH_20kHz = 0x01
276
CHANNEL_WIDTH_12d5kHz = 0x00
277

    
278
BUSY_CHANNEL_LOCKOUT_OFF = 0x00
279
BUSY_CHANNEL_LOCKOUT_REPEATER = 0x01
280
BUSY_CHANNEL_LOCKOUT_BUSY = 0x02
281

    
282
MEMORY_ADDRESS_RANGE = (0x0000, 0x3290)
283
MEMORY_RW_BLOCK_SIZE = 0x10
284
MEMORY_RW_BLOCK_CMD_SIZE = 0x16
285

    
286
POWER_LEVELS = [chirp_common.PowerLevel('Low', dBm=37),
287
                chirp_common.PowerLevel('Medium', dBm=40),
288
                chirp_common.PowerLevel('High', dBm=44)]
289

    
290
# CTCSS Tone definitions
291
TONE_CUSTOM_CTCSS = 0x33
292
TONE_MAP_VAL_TO_TONE = {0x00: 62.5, 0x01: 67.0, 0x02: 69.3,
293
                        0x03: 71.9, 0x04: 74.4, 0x05: 77.0,
294
                        0x06: 79.7, 0x07: 82.5, 0x08: 85.4,
295
                        0x09: 88.5, 0x0a: 91.5, 0x0b: 94.8,
296
                        0x0c: 97.4, 0x0d: 100.0, 0x0e: 103.5,
297
                        0x0f: 107.2, 0x10: 110.9, 0x11: 114.8,
298
                        0x12: 118.8, 0x13: 123.0, 0x14: 127.3,
299
                        0x15: 131.8, 0x16: 136.5, 0x17: 141.3,
300
                        0x18: 146.2, 0x19: 151.4, 0x1a: 156.7,
301
                        0x1b: 159.8, 0x1c: 162.2, 0x1d: 165.5,
302
                        0x1e: 167.9, 0x1f: 171.3, 0x20: 173.8,
303
                        0x21: 177.3, 0x22: 179.9, 0x23: 183.5,
304
                        0x24: 186.2, 0x25: 189.9, 0x26: 192.8,
305
                        0x27: 196.6, 0x28: 199.5, 0x29: 203.5,
306
                        0x2a: 206.5, 0x2b: 210.7, 0x2c: 218.1,
307
                        0x2d: 225.7, 0x2e: 229.1, 0x2f: 233.6,
308
                        0x30: 241.8, 0x31: 250.3, 0x32: 254.1}
309

    
310
TONE_MAP_TONE_TO_VAL = {TONE_MAP_VAL_TO_TONE[val]: val
311
                        for val in TONE_MAP_VAL_TO_TONE}
312

    
313
TONES_EN_TXTONE = (1 << 3)
314
TONES_EN_RXTONE = (1 << 2)
315
TONES_EN_TXCODE = (1 << 1)
316
TONES_EN_RXCODE = (1 << 0)
317
TONES_EN_NO_TONE = 0
318

    
319
# Radio supports upper case and symbols
320
CHARSET_ASCII_PLUS = chirp_common.CHARSET_UPPER_NUMERIC + '- '
321

    
322
# Band limits as defined by the band byte in ver_response, defined in Hz, for
323
# VHF and UHF, used for RX and TX.
324
BAND_LIMITS = {0x00: [(144000000, 148000000), (430000000, 440000000)],
325
               0x01: [(136000000, 174000000), (400000000, 490000000)],
326
               0x02: [(144000000, 146000000), (430000000, 440000000)]}
327

    
328

    
329
# Get band limits from a band limit value
330
def get_band_limits_Hz(limit_value):
331
    if limit_value not in BAND_LIMITS:
332
        limit_value = 0x01
333
        LOG.warning('Unknown band limit value 0x%02x, default to 0x01')
334
    bandlimitfrequencies = BAND_LIMITS[limit_value]
335
    return bandlimitfrequencies
336

    
337

    
338
# Calculate the checksum used in serial packets
339
def checksum(message_bytes):
340
    mask = 0xFF
341
    checksum = 0
342
    for b in message_bytes:
343
        checksum = (checksum + b) & mask
344
    return checksum
345

    
346

    
347
# Send a command to the radio, return any reply stripping the echo of the
348
# command (tx and rx share a single pin in this radio)
349
def send_serial_command(serial, command, expectedlen=None):
350
    ''' send a command to the radio, and return any response.
351
    set expectedlen to return as soon as that many bytes are read.
352
    '''
353
    serial.write(command)
354
    serial.flush()
355

    
356
    response = b''
357
    tout = time.time() + 0.5
358
    while time.time() < tout:
359
        if serial.inWaiting():
360
            response += serial.read()
361
        # remember everything gets echo'd back
362
        if len(response) - len(command) == expectedlen:
363
            break
364

    
365
    # cut off what got echo'd back, we don't need to see it again
366
    if response.startswith(command):
367
        response = response[len(command):]
368

    
369
    return response
370

    
371

    
372
# strip trailing 0x00 to convert a string returned by bitwise.parse into a
373
# python string
374
def cstring_to_py_string(cstring):
375
    return "".join(c for c in cstring if c != '\x00')
376

    
377

    
378
# Check the radio version reported to see if it's one we support,
379
# returns bool version supported, and the band index
380
def check_ver(ver_response, allowed_types):
381
    ''' Check the returned radio version is one we approve of '''
382

    
383
    LOG.debug('ver_response = ')
384
    LOG.debug(util.hexprint(ver_response))
385

    
386
    resp = bitwise.parse(VER_FORMAT, ver_response)
387
    verok = False
388

    
389
    if resp.hdr == 0x49 and resp.ack == 0x06:
390
        model, version = [cstring_to_py_string(bitwise.get_string(s)).strip()
391
                          for s in (resp.model, resp.version)]
392
        LOG.debug('radio model: \'%s\' version: \'%s\'' %
393
                  (model, version))
394
        LOG.debug('allowed_types = %s' % allowed_types)
395

    
396
        if model in allowed_types:
397
            LOG.debug('model in allowed_types')
398

    
399
            if version in allowed_types[model]:
400
                LOG.debug('version in allowed_types[model]')
401
                verok = True
402
    else:
403
        raise errors.RadioError('Failed to parse version response')
404

    
405
    return verok, int(resp.bandlimit)
406

    
407

    
408
# Put the radio in programming mode, sending the initial command and checking
409
# the response.  raise RadioError if there is no response (500ms timeout), and
410
# if the returned version isn't matched by check_ver
411
def enter_program_mode(radio):
412
    serial = radio.pipe
413
    # place the radio in program mode, and confirm
414
    program_response = send_serial_command(serial, b'PROGRAM')
415

    
416
    if program_response != b'QX\x06':
417
        raise errors.RadioError('No initial response from radio.')
418
    LOG.debug('entered program mode')
419

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

    
423
    verok, bandlimit = check_ver(ver_response, radio.ALLOWED_RADIO_TYPES)
424
    if not verok:
425
        exit_program_mode(radio)
426
        raise errors.RadioError(
427
            'Radio version not in allowed list for %s-%s: %s' %
428
            (radio.VENDOR, radio.MODEL, util.hexprint(ver_response)))
429

    
430
    return bandlimit
431

    
432

    
433
# Exit programming mode
434
def exit_program_mode(radio):
435
    send_serial_command(radio.pipe, b'END')
436

    
437

    
438
# Parse a packet from the radio returning the header (R/W, address, data, and
439
# checksum valid
440
def parse_read_response(resp):
441
    addr = resp[:4]
442
    data = bytes(resp[4:-2])
443
    cs = checksum(ord(d) for d in resp[1:-2])
444
    valid = cs == ord(resp[-2])
445
    if not valid:
446
        LOG.error('checksumfail: %02x, expected %02x' % (cs, ord(resp[-2])))
447
        LOG.error('msg data: %s' % util.hexprint(resp))
448
    return addr, data, valid
449

    
450

    
451
# Download data from the radio and populate the memory map
452
def do_download(radio):
453
    '''Download memories from the radio'''
454

    
455
    # Get the serial port connection
456
    serial = radio.pipe
457

    
458
    try:
459
        enter_program_mode(radio)
460

    
461
        memory_data = bytes()
462

    
463
        # status info for the UI
464
        status = chirp_common.Status()
465
        status.cur = 0
466
        status.max = (MEMORY_ADDRESS_RANGE[1] -
467
                      MEMORY_ADDRESS_RANGE[0])/MEMORY_RW_BLOCK_SIZE
468
        status.msg = 'Cloning from radio...'
469
        radio.status_fn(status)
470

    
471
        for addr in range(MEMORY_ADDRESS_RANGE[0],
472
                          MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
473
                          MEMORY_RW_BLOCK_SIZE):
474
            read_command = struct.pack('>BHB', 0x52, addr,
475
                                       MEMORY_RW_BLOCK_SIZE)
476
            read_response = send_serial_command(serial, read_command,
477
                                                MEMORY_RW_BLOCK_CMD_SIZE)
478
            # LOG.debug('read response:\n%s' % util.hexprint(read_response))
479

    
480
            address, data, valid = parse_read_response(read_response)
481
            memory_data += data
482

    
483
            # update UI
484
            status.cur = (addr - MEMORY_ADDRESS_RANGE[0])\
485
                / MEMORY_RW_BLOCK_SIZE
486
            radio.status_fn(status)
487

    
488
        exit_program_mode(radio)
489
    except errors.RadioError as e:
490
        raise e
491
    except Exception as e:
492
        raise errors.RadioError('Failed to download from radio: %s' % e)
493

    
494
    return memmap.MemoryMapBytes(memory_data)
495

    
496

    
497
# Build a write data command to send to the radio
498
def make_write_data_cmd(addr, data, datalen):
499
    cmd = struct.pack('>BHB', 0x57, addr, datalen)
500
    cmd += data
501
    cs = checksum(ord(c) for c in cmd[1:])
502
    cmd += struct.pack('>BB', cs, 0x06)
503
    return cmd
504

    
505

    
506
# Upload a memory map to the radio
507
def do_upload(radio):
508
    try:
509
        bandlimit = enter_program_mode(radio)
510

    
511
        if bandlimit != radio._memobj.radio_settings.bandlimit:
512
            LOG.warning('radio and image bandlimits differ'
513
                        ' some channels many not work'
514
                        ' (img:0x%02x radio:0x%02x)' %
515
                        (int(bandlimit),
516
                         int(radio._memobj.radio_settings.bandlimit)))
517
            LOG.warning('radio bands: %s' % get_band_limits_Hz(
518
                         int(radio._memobj.radio_settings.bandlimit)))
519
            LOG.warning('img bands: %s' % get_band_limits_Hz(bandlimit))
520

    
521
        serial = radio.pipe
522

    
523
        # send the initial message, radio responds with something that looks a
524
        # bit like a bitfield, but I don't know what it is yet.
525
        read_command = struct.pack('>BHB', 0x52, 0x3b10, MEMORY_RW_BLOCK_SIZE)
526
        read_response = send_serial_command(serial, read_command,
527
                                            MEMORY_RW_BLOCK_CMD_SIZE)
528
        address, data, valid = parse_read_response(read_response)
529
        LOG.debug('Got initial response from radio: %s' %
530
                  util.hexprint(read_response))
531

    
532
        bptr = 0
533

    
534
        memory_addrs = range(MEMORY_ADDRESS_RANGE[0],
535
                             MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
536
                             MEMORY_RW_BLOCK_SIZE)
537

    
538
        # status info for the UI
539
        status = chirp_common.Status()
540
        status.cur = 0
541
        status.max = len(memory_addrs)
542
        status.msg = 'Cloning to radio...'
543
        radio.status_fn(status)
544

    
545
        for idx, addr in enumerate(memory_addrs):
546
            write_command = make_write_data_cmd(
547
                addr, radio._mmap[bptr:bptr+MEMORY_RW_BLOCK_SIZE],
548
                MEMORY_RW_BLOCK_SIZE)
549
            # LOG.debug('write data:\n%s' % util.hexprint(write_command))
550
            write_response = send_serial_command(serial, write_command, 0x01)
551
            bptr += MEMORY_RW_BLOCK_SIZE
552

    
553
            if write_response == '\x0a':
554
                # NACK from radio, e.g. checksum wrongn
555
                LOG.debug('Radio returned 0x0a - NACK:')
556
                LOG.debug(' * write cmd:\n%s' % util.hexprint(write_command))
557
                LOG.debug(' * write response:\n%s' %
558
                          util.hexprint(write_response))
559
                exit_program_mode(radio)
560
                raise errors.RadioError('Radio NACK\'d write command')
561

    
562
            # update UI
563
            status.cur = idx
564
            radio.status_fn(status)
565
        exit_program_mode(radio)
566
    except errors.RadioError:
567
        raise
568
    except Exception as e:
569
        raise errors.RadioError('Failed to download from radio: %s' % e)
570

    
571

    
572
# Get the value of @bitfield @number of bits in from 0
573
def get_bitfield(bitfield, number):
574
    ''' Get the value of @bitfield @number of bits in '''
575
    byteidx = number//8
576
    bitidx = number - (byteidx * 8)
577
    return bitfield[byteidx] & (1 << bitidx)
578

    
579

    
580
# Set the @value of @bitfield @number of bits in from 0
581
def set_bitfield(bitfield, number, value):
582
    ''' Set the @value of @bitfield @number of bits in '''
583
    byteidx = number//8
584
    bitidx = number - (byteidx * 8)
585
    if value is True:
586
        bitfield[byteidx] |= (1 << bitidx)
587
    else:
588
        bitfield[byteidx] &= ~(1 << bitidx)
589
    return bitfield
590

    
591

    
592
# Translate the radio's version of a code as stored to a real code
593
def dtcs_code_bits_to_val(highbit, lowbyte):
594
    return chirp_common.ALL_DTCS_CODES[highbit*256 + lowbyte]
595

    
596

    
597
# Translate the radio's version of a tone as stored to a real tone
598
def ctcss_tone_bits_to_val(tone_byte):
599
    # TODO use the custom setting 0x33 and ref the custom ctcss
600
    # field
601
    tone_byte = int(tone_byte)
602
    if tone_byte in TONE_MAP_VAL_TO_TONE:
603
        return TONE_MAP_VAL_TO_TONE[tone_byte]
604
    elif tone_byte == TONE_CUSTOM_CTCSS:
605
        LOG.info('custom ctcss not implemented (yet?).')
606
    else:
607
        raise errors.UnsupportedToneError('unknown ctcss tone value: %02x' %
608
                                          tone_byte)
609

    
610

    
611
# Translate a real tone to the radio's version as stored
612
def ctcss_code_val_to_bits(tone_value):
613
    if tone_value in TONE_MAP_TONE_TO_VAL:
614
        return TONE_MAP_TONE_TO_VAL[tone_value]
615
    else:
616
        raise errors.UnsupportedToneError('Tone %f not supported' % tone_value)
617

    
618

    
619
# Translate a real code to the radio's version as stored
620
def dtcs_code_val_to_bits(code):
621
    val = chirp_common.ALL_DTCS_CODES.index(code)
622
    return (val & 0xFF), ((val >> 8) & 0x01)
623

    
624

    
625
class AnyTone778UVBase(chirp_common.CloneModeRadio,
626
                       chirp_common.ExperimentalRadio):
627
    '''AnyTone 778UV and probably Retivis RT95 and others'''
628
    BAUD_RATE = 9600
629
    NEEDS_COMPAT_SERIAL = False
630

    
631
    @classmethod
632
    def get_prompts(cls):
633
        rp = chirp_common.RadioPrompts()
634

    
635
        rp.experimental = \
636
            ('This is experimental support for the %s %s.  '
637
             'Please send in bug and enhancement requests!' %
638
             (cls.VENDOR, cls.MODEL))
639

    
640
        return rp
641

    
642
    # Return information about this radio's features, including
643
    # how many memories it has, what bands it supports, etc
644
    def get_features(self):
645
        rf = chirp_common.RadioFeatures()
646
        rf.has_bank = False
647
        rf.has_settings = True
648
        rf.can_odd_split = True
649
        rf.has_name = True
650
        rf.has_offset = True
651
        rf.valid_name_length = 5
652
        rf.valid_duplexes = ['', '+', '-', 'split', 'off']
653
        rf.valid_characters = CHARSET_ASCII_PLUS
654

    
655
        rf.has_dtcs = True
656
        rf.has_rx_dtcs = True
657
        rf.has_dtcs_polarity = True
658
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES
659
        rf.has_ctone = True
660
        rf.has_cross = True
661
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
662
        rf.valid_cross_modes = ['Tone->Tone',
663
                                'Tone->DTCS',
664
                                'DTCS->Tone',
665
                                'DTCS->DTCS',
666
                                'DTCS->',
667
                                '->DTCS',
668
                                '->Tone']
669

    
670
        rf.memory_bounds = (1, 200)  # This radio supports memories 1-200
671
        try:
672
            rf.valid_bands = get_band_limits_Hz(
673
                int(self._memobj.radio_settings.bandlimit))
674
        except TypeError as e:
675
            # If we're asked without memory loaded, assume the most permissive
676
            rf.valid_bands = get_band_limits_Hz(1)
677
        except Exception as e:
678
            LOG.error('Failed to get band limits for anytone778uv: %s' % e)
679
            rf.valid_bands = get_band_limits_Hz(1)
680
        rf.valid_modes = ['FM', 'NFM']
681
        rf.valid_power_levels = POWER_LEVELS
682
        rf.valid_tuning_steps = [2.5, 5, 6.25, 10, 12.5, 20, 25, 30, 50]
683
        rf.has_tuning_step = False
684
        return rf
685

    
686
    # Do a download of the radio from the serial port
687
    def sync_in(self):
688
        self._mmap = do_download(self)
689
        self.process_mmap()
690

    
691
    # Do an upload of the radio to the serial port
692
    def sync_out(self):
693
        do_upload(self)
694

    
695
    # Convert the raw byte array into a memory object structure
696
    def process_mmap(self):
697
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
698

    
699
    # Return a raw representation of the memory object, which
700
    # is very helpful for development
701
    def get_raw_memory(self, number):
702
        return repr(self._memobj.memory[number - 1])
703

    
704
    # Extract a high-level memory object from the low-level memory map
705
    # This is called to populate a memory in the UI
706
    def get_memory(self, number):
707
        number -= 1
708
        # Get a low-level memory object mapped to the image
709
        _mem = self._memobj.memory[number]
710
        _mem_status = self._memobj.memory_status
711

    
712
        # Create a high-level memory object to return to the UI
713
        mem = chirp_common.Memory()
714
        mem.number = number + 1           # Set the memory number
715

    
716
        # Check if this memory is present in the occupied list
717
        mem.empty = get_bitfield(_mem_status.occupied_bitfield, number) == 0
718

    
719
        if not mem.empty:
720
            # Check if this memory is in the scan enabled list
721
            mem.skip = ''
722
            if get_bitfield(_mem_status.scan_enabled_bitfield, number) == 0:
723
                mem.skip = 'S'
724

    
725
            # set the name
726
            mem.name = str(_mem.name).rstrip()  # Set the alpha tag
727

    
728
            # Convert your low-level frequency and offset to Hertz
729
            mem.freq = int(_mem.freq) * 10
730
            mem.offset = int(_mem.offset) * 10
731

    
732
            # Set the duplex flags
733
            if _mem.duplex == DUPLEX_POSSPLIT:
734
                mem.duplex = '+'
735
            elif _mem.duplex == DUPLEX_NEGSPLIT:
736
                mem.duplex = '-'
737
            elif _mem.duplex == DUPLEX_NOSPLIT:
738
                mem.duplex = ''
739
            elif _mem.duplex == DUPLEX_ODDSPLIT:
740
                mem.duplex = 'split'
741
            else:
742
                LOG.error('%s: get_mem: unhandled duplex: %02x' %
743
                          (mem.name, _mem.duplex))
744

    
745
            # handle tx off
746
            if _mem.tx_off:
747
                mem.duplex = 'off'
748

    
749
            # Set the channel width
750
            if _mem.channel_width == CHANNEL_WIDTH_25kHz:
751
                mem.mode = 'FM'
752
            elif _mem.channel_width == CHANNEL_WIDTH_20kHz:
753
                LOG.info(
754
                    '%s: get_mem: promoting 20kHz channel width to 25kHz' %
755
                    mem.name)
756
                mem.mode = 'FM'
757
            elif _mem.channel_width == CHANNEL_WIDTH_12d5kHz:
758
                mem.mode = 'NFM'
759
            else:
760
                LOG.error('%s: get_mem: unhandled channel width: 0x%02x' %
761
                          (mem.name, _mem.channel_width))
762

    
763
            # set the power level
764
            if _mem.txpower == TXPOWER_LOW:
765
                mem.power = POWER_LEVELS[0]
766
            elif _mem.txpower == TXPOWER_MED:
767
                mem.power = POWER_LEVELS[1]
768
            elif _mem.txpower == TXPOWER_HIGH:
769
                mem.power = POWER_LEVELS[2]
770
            else:
771
                LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
772
                          (mem.name, _mem.txpower))
773

    
774
            # CTCSS Tones
775
            # TODO support custom ctcss tones here
776
            txtone = None
777
            rxtone = None
778
            rxcode = None
779
            txcode = None
780

    
781
            # check if dtcs tx is enabled
782
            if _mem.dtcs_encode_en:
783
                txcode = dtcs_code_bits_to_val(_mem.dtcs_encode_code_highbit,
784
                                               _mem.dtcs_encode_code)
785

    
786
            # check if dtcs rx is enabled
787
            if _mem.dtcs_decode_en:
788
                rxcode = dtcs_code_bits_to_val(_mem.dtcs_decode_code_highbit,
789
                                               _mem.dtcs_decode_code)
790

    
791
            if txcode is not None:
792
                LOG.debug('%s: get_mem dtcs_enc: %d' % (mem.name, txcode))
793
            if rxcode is not None:
794
                LOG.debug('%s: get_mem dtcs_dec: %d' % (mem.name, rxcode))
795

    
796
            # tsql set if radio squelches on tone
797
            tsql = _mem.tone_squelch_en
798

    
799
            # check if ctcss tx is enabled
800
            if _mem.ctcss_encode_en:
801
                txtone = ctcss_tone_bits_to_val(_mem.ctcss_enc_tone)
802

    
803
            # check if ctcss rx is enabled
804
            if _mem.ctcss_decode_en:
805
                rxtone = ctcss_tone_bits_to_val(_mem.ctcss_dec_tone)
806

    
807
            # Define this here to allow a readable if-else tree enabling tone
808
            # options
809
            enabled = 0
810
            enabled |= (txtone is not None) * TONES_EN_TXTONE
811
            enabled |= (rxtone is not None) * TONES_EN_RXTONE
812
            enabled |= (txcode is not None) * TONES_EN_TXCODE
813
            enabled |= (rxcode is not None) * TONES_EN_RXCODE
814

    
815
            # Add some debugging output for the tone bitmap
816
            enstr = []
817
            if enabled & TONES_EN_TXTONE:
818
                enstr += ['TONES_EN_TXTONE']
819
            if enabled & TONES_EN_RXTONE:
820
                enstr += ['TONES_EN_RXTONE']
821
            if enabled & TONES_EN_TXCODE:
822
                enstr += ['TONES_EN_TXCODE']
823
            if enabled & TONES_EN_RXCODE:
824
                enstr += ['TONES_EN_RXCODE']
825
            if enabled == 0:
826
                enstr = ['TONES_EN_NOTONE']
827
            LOG.debug('%s: enabled = %s' % (
828
                mem.name, '|'.join(enstr)))
829

    
830
            mem.tmode = ''
831
            if enabled == TONES_EN_NO_TONE:
832
                mem.tmode = ''
833
            elif enabled == TONES_EN_TXTONE:
834
                mem.tmode = 'Tone'
835
                mem.rtone = txtone
836
            elif enabled == TONES_EN_RXTONE and tsql:
837
                mem.tmode = 'Cross'
838
                mem.cross_mode = '->Tone'
839
                mem.ctone = rxtone
840
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXTONE) and tsql:
841
                if txtone == rxtone:  # TSQL
842
                    mem.tmode = 'TSQL'
843
                    mem.ctone = txtone
844
                else:  # Tone->Tone
845
                    mem.tmode = 'Cross'
846
                    mem.cross_mode = 'Tone->Tone'
847
                    mem.ctone = rxtone
848
                    mem.rtone = txtone
849
            elif enabled == TONES_EN_TXCODE:
850
                mem.tmode = 'Cross'
851
                mem.cross_mode = 'DTCS->'
852
                mem.dtcs = txcode
853
            elif enabled == TONES_EN_RXCODE and tsql:
854
                mem.tmode = 'Cross'
855
                mem.cross_mode = '->DTCS'
856
                mem.rx_dtcs = rxcode
857
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXCODE) and tsql:
858
                if rxcode == txcode:
859
                    mem.tmode = 'DTCS'
860
                    mem.rx_dtcs = rxcode
861
                    # #8327 Not sure this is the correct interpretation of
862
                    # DevelopersToneModes, but it seems to make it work round
863
                    # tripping with the anytone software.  DTM implies that we
864
                    # might not need to set mem.dtcs, but if we do it only DTCS
865
                    # rx works (as if we were Cross:None->DTCS).
866
                    mem.dtcs = rxcode
867
                else:
868
                    mem.tmode = 'Cross'
869
                    mem.cross_mode = 'DTCS->DTCS'
870
                    mem.rx_dtcs = rxcode
871
                    mem.dtcs = txcode
872
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXTONE) and tsql:
873
                mem.tmode = 'Cross'
874
                mem.cross_mode = 'DTCS->Tone'
875
                mem.dtcs = txcode
876
                mem.ctone = rxtone
877
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXCODE) and tsql:
878
                mem.tmode = 'Cross'
879
                mem.cross_mode = 'Tone->DTCS'
880
                mem.rx_dtcs = rxcode
881
                mem.rtone = txtone
882
            else:
883
                LOG.error('%s: Unhandled tmode enabled = %d.' % (
884
                    mem.name, enabled))
885

    
886
                # Can get here if e.g. TONE_EN_RXCODE is set and tsql isn't
887
                # In that case should we perhaps store the tone and code values
888
                # if they're present and then setup tmode and cross_mode as
889
                # appropriate later?
890

    
891
            # set the dtcs polarity
892
            dtcs_pol_bit_to_str = {0: 'N', 1: 'R'}
893
            mem.dtcs_polarity = '%s%s' %\
894
                (dtcs_pol_bit_to_str[_mem.dtcs_encode_invert == 1],
895
                 dtcs_pol_bit_to_str[_mem.dtcs_decode_invert == 1])
896

    
897
        return mem
898

    
899
    # Store details about a high-level memory to the memory map
900
    # This is called when a user edits a memory in the UI
901
    def set_memory(self, mem):
902
        # Get a low-level memory object mapped to the image
903
        _mem = self._memobj.memory[mem.number - 1]
904
        _mem_status = self._memobj.memory_status
905

    
906
        # set the occupied bitfield
907
        _mem_status.occupied_bitfield = \
908
            set_bitfield(_mem_status.occupied_bitfield, mem.number - 1,
909
                         not mem.empty)
910

    
911
        # set the scan add bitfield
912
        _mem_status.scan_enabled_bitfield = \
913
            set_bitfield(_mem_status.scan_enabled_bitfield, mem.number - 1,
914
                         (not mem.empty) and (mem.skip != 'S'))
915

    
916
        if mem.empty:
917
            # Set the whole memory to 0xff
918
            _mem.set_raw('\xff' * (_mem.size() / 8))
919
        else:
920
            _mem.set_raw('\x00' * (_mem.size() / 8))
921

    
922
            _mem.freq = int(mem.freq / 10)
923
            _mem.offset = int(mem.offset / 10)
924

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

    
927
            # TODO support busy channel lockout - disabled for now
928
            _mem.busy_channel_lockout = BUSY_CHANNEL_LOCKOUT_OFF
929

    
930
            # Set duplex bitfields
931
            if mem.duplex == '+':
932
                _mem.duplex = DUPLEX_POSSPLIT
933
            elif mem.duplex == '-':
934
                _mem.duplex = DUPLEX_NEGSPLIT
935
            elif mem.duplex == '':
936
                _mem.duplex = DUPLEX_NOSPLIT
937
            elif mem.duplex == 'split':
938
                # TODO: this is an unverified punt!
939
                _mem.duplex = DUPLEX_ODDSPLIT
940
            else:
941
                LOG.error('%s: set_mem: unhandled duplex: %s' %
942
                          (mem.name, mem.duplex))
943

    
944
            # handle tx off
945
            _mem.tx_off = 0
946
            if mem.duplex == 'off':
947
                _mem.tx_off = 1
948

    
949
            # Set the channel width - remember we promote 20kHz channels to FM
950
            # on import
951
            # , so don't handle them here
952
            if mem.mode == 'FM':
953
                _mem.channel_width = CHANNEL_WIDTH_25kHz
954
            elif mem.mode == 'NFM':
955
                _mem.channel_width = CHANNEL_WIDTH_12d5kHz
956
            else:
957
                LOG.error('%s: set_mem: unhandled mode: %s' % (
958
                    mem.name, mem.mode))
959

    
960
            # set the power level
961
            if mem.power == POWER_LEVELS[0]:
962
                _mem.txpower = TXPOWER_LOW
963
            elif mem.power == POWER_LEVELS[1]:
964
                _mem.txpower = TXPOWER_MED
965
            elif mem.power == POWER_LEVELS[2]:
966
                _mem.txpower = TXPOWER_HIGH
967
            else:
968
                LOG.error('%s: set_mem: unhandled power level: %s' %
969
                          (mem.name, mem.power))
970

    
971
            # TODO set the CTCSS values
972
            # TODO support custom ctcss tones here
973
            # Default - tones off, carrier sql
974
            _mem.ctcss_encode_en = 0
975
            _mem.ctcss_decode_en = 0
976
            _mem.tone_squelch_en = 0
977
            _mem.ctcss_enc_tone = 0x00
978
            _mem.ctcss_dec_tone = 0x00
979
            _mem.customctcss = 0x00
980
            _mem.dtcs_encode_en = 0
981
            _mem.dtcs_encode_code_highbit = 0
982
            _mem.dtcs_encode_code = 0
983
            _mem.dtcs_encode_invert = 0
984
            _mem.dtcs_decode_en = 0
985
            _mem.dtcs_decode_code_highbit = 0
986
            _mem.dtcs_decode_code = 0
987
            _mem.dtcs_decode_invert = 0
988

    
989
            dtcs_pol_str_to_bit = {'N': 0, 'R': 1}
990
            _mem.dtcs_encode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[0]]
991
            _mem.dtcs_decode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[1]]
992

    
993
            if mem.tmode == 'Tone':
994
                _mem.ctcss_encode_en = 1
995
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
996
            elif mem.tmode == 'TSQL':
997
                _mem.ctcss_encode_en = 1
998
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.ctone)
999
                _mem.ctcss_decode_en = 1
1000
                _mem.tone_squelch_en = 1
1001
                _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
1002
            elif mem.tmode == 'DTCS':
1003
                _mem.dtcs_encode_en = 1
1004
                _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
1005
                    dtcs_code_val_to_bits(mem.rx_dtcs)
1006
                _mem.dtcs_decode_en = 1
1007
                _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
1008
                    dtcs_code_val_to_bits(mem.rx_dtcs)
1009
                _mem.tone_squelch_en = 1
1010
            elif mem.tmode == 'Cross':
1011
                txmode, rxmode = mem.cross_mode.split('->')
1012

    
1013
                if txmode == 'Tone':
1014
                    _mem.ctcss_encode_en = 1
1015
                    _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
1016
                elif txmode == '':
1017
                    pass
1018
                elif txmode == 'DTCS':
1019
                    _mem.dtcs_encode_en = 1
1020
                    _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
1021
                        dtcs_code_val_to_bits(mem.dtcs)
1022
                else:
1023
                    LOG.error('%s: unhandled cross TX mode: %s' % (
1024
                        mem.name, mem.cross_mode))
1025

    
1026
                if rxmode == 'Tone':
1027
                    _mem.ctcss_decode_en = 1
1028
                    _mem.tone_squelch_en = 1
1029
                    _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
1030
                elif rxmode == '':
1031
                    pass
1032
                elif rxmode == 'DTCS':
1033
                    _mem.dtcs_decode_en = 1
1034
                    _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
1035
                        dtcs_code_val_to_bits(mem.rx_dtcs)
1036
                    _mem.tone_squelch_en = 1
1037
                else:
1038
                    LOG.error('%s: unhandled cross RX mode: %s' % (
1039
                        mem.name, mem.cross_mode))
1040
            else:
1041
                LOG.error('%s: Unhandled tmode/cross %s/%s.' %
1042
                          (mem.name, mem.tmode, mem.cross_mode))
1043
            LOG.debug('%s: tmode=%s, cross=%s, rtone=%f, ctone=%f' % (
1044
                mem.name, mem.tmode, mem.cross_mode, mem.rtone, mem.ctone))
1045
            LOG.debug('%s: CENC=%d, CDEC=%d, t(enc)=%02x, t(dec)=%02x' % (
1046
                mem.name,
1047
                _mem.ctcss_encode_en,
1048
                _mem.ctcss_decode_en,
1049
                ctcss_code_val_to_bits(mem.rtone),
1050
                ctcss_code_val_to_bits(mem.ctone)))
1051

    
1052
            # set unknown defaults, based on reading memory set by vendor tool
1053
            _mem.unknown1 = 0x00
1054
            _mem.unknown6 = 0x00
1055
            _mem.unknown7 = 0x00
1056
            _mem.unknown8 = 0x00
1057
            _mem.unknown9 = 0x00
1058
            _mem.unknown10 = 0x00
1059

    
1060
    def get_settings(self):
1061
        """Translate the MEM_FORMAT structs into setstuf in the UI"""
1062
        _settings = self._memobj.settings
1063
        _radio_settings = self._memobj.radio_settings
1064
        _password = self._memobj.password
1065
        _pfkeys = self._memobj.pfkeys
1066
        _dtmf = self._memobj.dtmf
1067

    
1068
        # Function Setup
1069
        function = RadioSettingGroup("function", "Function Setup")
1070
        group = RadioSettings(function)
1071

    
1072
        # MODE SET
1073
        # Channel Locked
1074
        rs = RadioSettingValueBoolean(_settings.channelLocked)
1075
        rset = RadioSetting("settings.channelLocked", "Channel locked", rs)
1076
        function.append(rset)
1077

    
1078
        # Menu 3 - Display Mode
1079
        options = ["Frequency", "Channel", "Name"]
1080
        rs = RadioSettingValueList(options, options[_settings.displayMode])
1081
        rset = RadioSetting("settings.displayMode", "Display Mode", rs)
1082
        function.append(rset)
1083

    
1084
        # VFO/MR A
1085
        options = ["MR", "VFO"]
1086
        rs = RadioSettingValueList(options, options[_radio_settings.vfomrA])
1087
        rset = RadioSetting("radio_settings.vfomrA", "VFO/MR mode A", rs)
1088
        function.append(rset)
1089

    
1090
        # MR Channel A
1091
        options = ["%s" % x for x in range(1, 201)]
1092
        rs = RadioSettingValueList(options, options[_radio_settings.mrChanA])
1093
        rset = RadioSetting("radio_settings.mrChanA", "MR channel A", rs)
1094
        function.append(rset)
1095

    
1096
        # VFO/MR B
1097
        options = ["MR", "VFO"]
1098
        rs = RadioSettingValueList(options, options[_radio_settings.vfomrB])
1099
        rset = RadioSetting("radio_settings.vfomrB", "VFO/MR mode B", rs)
1100
        function.append(rset)
1101

    
1102
        # MR Channel B
1103
        options = ["%s" % x for x in range(1, 201)]
1104
        rs = RadioSettingValueList(options, options[_radio_settings.mrChanB])
1105
        rset = RadioSetting("radio_settings.mrChanB", "MR channel B", rs)
1106
        function.append(rset)
1107

    
1108
        # DISPLAY SET
1109
        # Starting Display
1110
        name = ""
1111
        for i in range(7):  # 0 - 7
1112
            name += chr(self._memobj.starting_display.line[i])
1113
        name = name.upper().rstrip()  # remove trailing spaces
1114

    
1115
        rs = RadioSettingValueString(0, 7, name)
1116
        rs.set_charset(chirp_common.CHARSET_ALPHANUMERIC)
1117
        rset = RadioSetting("starting_display.line", "Starting display", rs)
1118
        function.append(rset)
1119

    
1120
        # Menu 11 - Backlight Brightness
1121
        options = ["%s" % x for x in range(1, 4)]
1122
        rs = RadioSettingValueList(options, options[_settings.backlightBr - 1])
1123
        rset = RadioSetting("settings.backlightBr", "Backlight brightness", rs)
1124
        function.append(rset)
1125

    
1126
        # Menu 15 - Screen Direction
1127
        options = ["Positive", "Inverted"]
1128
        rs = RadioSettingValueList(options, options[_settings.screenDir])
1129
        rset = RadioSetting("settings.screenDir", "Screen direction", rs)
1130
        function.append(rset)
1131

    
1132
        # Hand Mic Key Brightness
1133
        options = ["%s" % x for x in range(1, 32)]
1134
        rs = RadioSettingValueList(options, options[_settings.micKeyBrite - 1])
1135
        rset = RadioSetting("settings.micKeyBrite",
1136
                            "Hand mic key brightness", rs)
1137
        function.append(rset)
1138

    
1139
        # VOL SET
1140
        # Menu 1 - Beep Volume
1141
        options = ["OFF"] + ["%s" % x for x in range(1, 6)]
1142
        rs = RadioSettingValueList(options, options[_settings.beepVolume])
1143
        rset = RadioSetting("settings.beepVolume", "Beep volume", rs)
1144
        function.append(rset)
1145

    
1146
        # Menu 5 - Volume level Setup
1147
        options = ["%s" % x for x in range(1, 37)]
1148
        rs = RadioSettingValueList(options, options[_settings.speakerVol - 1])
1149
        rset = RadioSetting("settings.speakerVol", "Speaker volume", rs)
1150
        function.append(rset)
1151

    
1152
        # Menu 16 - Speaker Switch
1153
        options = ["Host on | Hand mic off", "Host on | Hand mic on",
1154
                   "Host off | Hand mic on"]
1155
        rs = RadioSettingValueList(options, options[_settings.speakerSwitch])
1156
        rset = RadioSetting("settings.speakerSwitch", "Speaker switch", rs)
1157
        function.append(rset)
1158

    
1159
        # STE SET
1160
        # STE Frequency
1161
        options = ["Off", "55.2 Hz", "259.2 Hz"]
1162
        rs = RadioSettingValueList(options, options[_settings.steFrequency])
1163
        rset = RadioSetting("settings.steFrequency", "STE frequency", rs)
1164
        function.append(rset)
1165

    
1166
        # STE Type
1167
        options = ["Off", "Silent", "120 degrees", "180 degrees",
1168
                   "240 degrees"]
1169
        rs = RadioSettingValueList(options, options[_settings.steType])
1170
        rset = RadioSetting("settings.steType", "STE type", rs)
1171
        function.append(rset)
1172

    
1173
        # ON/OFF SET
1174
        # Power-on Password
1175
        rs = RadioSettingValueBoolean(_settings.powerOnPasswd)
1176
        rset = RadioSetting("settings.powerOnPasswd", "Power-on Password", rs)
1177
        function.append(rset)
1178

    
1179
        # Password
1180
        def _char_to_str(chrx):
1181
            """ Remove ff pads from char array """
1182
            #  chrx is char array
1183
            str1 = ""
1184
            for sx in chrx:
1185
                if int(sx) > 31 and int(sx) < 127:
1186
                    str1 += chr(sx)
1187
            return str1
1188

    
1189
        def _pswd_vfy(setting, obj, atrb):
1190
            """ Verify password is 1-6 chars, numbers 1-5 """
1191
            str1 = str(setting.value).strip()   # initial
1192
            str2 = filter(lambda c: c in '0123456789', str1)    # valid chars
1193
            if str1 != str2:
1194
                # Two lines due to python 73 char limit
1195
                sx = "Bad characters in Password"
1196
                raise errors.RadioError(sx)
1197
            str2 = str1.ljust(6, chr(00))      # pad to 6 with 00's
1198
            setattr(obj, atrb, str2)
1199
            return
1200

    
1201
        sx = _char_to_str(_password.digits).strip()
1202
        rx = RadioSettingValueString(0, 6, sx)
1203
        sx = "Password (numerals 0-9)"
1204
        rset = RadioSetting("password.digits", sx, rx)
1205
        rset.set_apply_callback(_pswd_vfy, _password, "digits")
1206
        function.append(rset)
1207

    
1208
        # Menu 9 - Auto Power On
1209
        rs = RadioSettingValueBoolean(_settings.autoPowerOn)
1210
        rset = RadioSetting("settings.autoPowerOn", "Auto power on", rs)
1211
        function.append(rset)
1212

    
1213
        # Menu 13 - Auto Power Off
1214
        options = ["Off", "30 minutes", "60 minutes", "120 minutes"]
1215
        rs = RadioSettingValueList(options, options[_settings.autoPowerOff])
1216
        rset = RadioSetting("settings.autoPowerOff", "Auto power off", rs)
1217
        function.append(rset)
1218

    
1219
        # Power On Reset Enable
1220
        rs = RadioSettingValueBoolean(_settings.powerOnReset)
1221
        rset = RadioSetting("settings.powerOnReset", "Power on reset", rs)
1222
        function.append(rset)
1223

    
1224
        # FUNCTION SET
1225
        # Menu 4 - Squelch Level A
1226
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
1227
        rs = RadioSettingValueList(options, options[_settings.squelchLevelA])
1228
        rset = RadioSetting("settings.squelchLevelA", "Squelch level A", rs)
1229
        function.append(rset)
1230

    
1231
        # Squelch Level B
1232
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
1233
        rs = RadioSettingValueList(options, options[_settings.squelchLevelB])
1234
        rset = RadioSetting("settings.squelchLevelB", "Squelch level B", rs)
1235
        function.append(rset)
1236

    
1237
        # Menu 7 - Scan Type
1238
        options = ["Time operated (TO)", "Carrier operated (CO)",
1239
                   "Search (SE)"]
1240
        rs = RadioSettingValueList(options, options[_settings.scanType])
1241
        rset = RadioSetting("settings.scanType", "Scan mode", rs)
1242
        function.append(rset)
1243

    
1244
        # Menu 8 - Scan Recovery Time
1245
        options = ["%s seconds" % x for x in range(5, 20, 5)]
1246
        rs = RadioSettingValueList(options, options[_settings.scanRecoveryT])
1247
        rset = RadioSetting("settings.scanRecoveryT", "Scan recovery time", rs)
1248
        function.append(rset)
1249

    
1250
        # Main
1251
        options = ["A", "B"]
1252
        rs = RadioSettingValueList(options, options[_settings.main])
1253
        rset = RadioSetting("settings.main", "Main", rs)
1254
        function.append(rset)
1255

    
1256
        # Menu 10 - Dual Watch (RX Way Select)
1257
        rs = RadioSettingValueBoolean(_settings.dualWatch)
1258
        rset = RadioSetting("settings.dualWatch", "Dual watch", rs)
1259
        function.append(rset)
1260

    
1261
        # Menu 12 - Time Out Timer
1262
        options = ["OFF"] + ["%s minutes" % x for x in range(1, 31)]
1263
        rs = RadioSettingValueList(options, options[_settings.timeOutTimer])
1264
        rset = RadioSetting("settings.timeOutTimer", "Time out timer", rs)
1265
        function.append(rset)
1266

    
1267
        # TBST Frequency
1268
        options = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"]
1269
        rs = RadioSettingValueList(options, options[_settings.tbstFrequency])
1270
        rset = RadioSetting("settings.tbstFrequency", "TBST frequency", rs)
1271
        function.append(rset)
1272

    
1273
        # Save Channel Perameter
1274
        rs = RadioSettingValueBoolean(_settings.saveChParameter)
1275
        rset = RadioSetting("settings.saveChParameter",
1276
                            "Save channel parameter", rs)
1277
        function.append(rset)
1278

    
1279
        # MON Key Function
1280
        options = ["Squelch off momentary", "Squelch off"]
1281
        rs = RadioSettingValueList(options, options[_settings.monKeyFunction])
1282
        rset = RadioSetting("settings.monKeyFunction", "MON key function", rs)
1283
        function.append(rset)
1284

    
1285
        # Frequency Step
1286
        options = ["2.5 KHz", "5 KHz", "6.25 KHz", "10 KHz", "12.5 KHz",
1287
                   "20 KHz", "25 KHz", "30 KHz", "50 KHz"]
1288
        rs = RadioSettingValueList(options, options[_settings.frequencyStep])
1289
        rset = RadioSetting("settings.frequencyStep", "Frequency step", rs)
1290
        function.append(rset)
1291

    
1292
        # Knob Mode
1293
        options = ["Volume", "Channel"]
1294
        rs = RadioSettingValueList(options, options[_settings.knobMode])
1295
        rset = RadioSetting("settings.knobMode", "Knob mode", rs)
1296
        function.append(rset)
1297

    
1298
        # TRF Enable
1299
        rs = RadioSettingValueBoolean(_settings.trfEnable)
1300
        rset = RadioSetting("settings.trfEnable", "TRF enable", rs)
1301
        function.append(rset)
1302

    
1303
        # Key Assignment
1304
        pfkeys = RadioSettingGroup("pfkeys", "Key Assignment")
1305
        group.append(pfkeys)
1306

    
1307
        options = ["A/B", "V/M", "SQL", "VOL", "POW", "CDT", "REV", "SCN",
1308
                   "CAL", "TALK", "BND", "SFT", "MON", "DIR", "TRF", "RDW",
1309
                   "NULL"]
1310
                   
1311
        if self._has_vox:
1312
            options.insert(16, "VOX")
1313

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

    
1321
        # P2
1322
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P2 - 1])
1323
        rset = RadioSetting("pfkeys.keyMode1P2",
1324
                            "Key mode 1 P2", rs)
1325
        pfkeys.append(rset)
1326

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

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

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

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

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

    
1358
        # P2
1359
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P2 - 1])
1360
        rset = RadioSetting("pfkeys.keyMode2P2",
1361
                            "Key mode 2 P2", rs)
1362
        pfkeys.append(rset)
1363

    
1364
        # P3
1365
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P3 - 1])
1366
        rset = RadioSetting("pfkeys.keyMode2P3",
1367
                            "Key mode 2 P3", rs)
1368
        pfkeys.append(rset)
1369

    
1370
        # P4
1371
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P4 - 1])
1372
        rset = RadioSetting("pfkeys.keyMode2P4",
1373
                            "Key mode 2 P4", rs)
1374
        pfkeys.append(rset)
1375

    
1376
        # P5
1377
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P5 - 1])
1378
        rset = RadioSetting("pfkeys.keyMode2P5",
1379
                            "Key mode 2 P5", rs)
1380
        pfkeys.append(rset)
1381

    
1382
        # P6
1383
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P6 - 1])
1384
        rset = RadioSetting("pfkeys.keyMode2P6",
1385
                            "Key mode 2 P6", rs)
1386
        pfkeys.append(rset)
1387

    
1388
        options = ["V/M", "SQL", "VOL", "POW", "CDT", "REV", "SCN", "CAL",
1389
                   "TALK", "BND", "SFT", "MON", "DIR", "TRF", "RDW"]
1390

    
1391
        # PA
1392
        rs = RadioSettingValueList(options, options[_settings.keyPA - 2])
1393
        rset = RadioSetting("settings.keyPA",
1394
                            "Key PA", rs)
1395
        pfkeys.append(rset)
1396

    
1397
        # PB
1398
        rs = RadioSettingValueList(options, options[_settings.keyPB - 2])
1399
        rset = RadioSetting("settings.keyPB",
1400
                            "Key PB", rs)
1401
        pfkeys.append(rset)
1402

    
1403
        # PC
1404
        rs = RadioSettingValueList(options, options[_settings.keyPC - 2])
1405
        rset = RadioSetting("settings.keyPC",
1406
                            "Key PC", rs)
1407
        pfkeys.append(rset)
1408

    
1409
        # PD
1410
        rs = RadioSettingValueList(options, options[_settings.keyPD - 2])
1411
        rset = RadioSetting("settings.keyPD",
1412
                            "Key PD", rs)
1413
        pfkeys.append(rset)
1414

    
1415
        # DTMF
1416
        dtmf = RadioSettingGroup("dtmf", "DTMF")
1417
        group.append(dtmf)
1418

    
1419
        # DTMF Transmitting Time
1420
        options = ["50 milliseconds", "100 milliseconds", "200 milliseconds",
1421
                   "300 milliseconds", "500 milliseconds"]
1422
        rs = RadioSettingValueList(options, options[_settings.dtmfTxTime])
1423
        rset = RadioSetting("settings.dtmfTxTime",
1424
                            "DTMF transmitting time", rs)
1425
        dtmf.append(rset)
1426

    
1427
        # DTMF Self ID
1428

    
1429
        # DTMF Interval Character
1430
        IC_CHOICES = ["A", "B", "C", "D", "*", "#"]
1431
        IC_VALUES = [0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]
1432

    
1433
        def apply_ic_listvalue(setting, obj):
1434
            LOG.debug("Setting value: " + str(setting.value) + " from list")
1435
            val = str(setting.value)
1436
            index = IC_CHOICES.index(val)
1437
            val = IC_VALUES[index]
1438
            obj.set_value(val)
1439

    
1440
        if _dtmf.intervalChar in IC_VALUES:
1441
            idx = IC_VALUES.index(_dtmf.intervalChar)
1442
        else:
1443
            idx = IC_VALUES.index(0x0E)
1444
        rs = RadioSetting("dtmf.intervalChar", "DTMF interval character",
1445
                          RadioSettingValueList(IC_CHOICES,
1446
                                                IC_CHOICES[idx]))
1447
        rs.set_apply_callback(apply_ic_listvalue, _dtmf.intervalChar)
1448
        dtmf.append(rs)
1449

    
1450
        # Group Code
1451
        GC_CHOICES = ["Off", "A", "B", "C", "D", "*", "#"]
1452
        GC_VALUES = [0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]
1453

    
1454
        def apply_gc_listvalue(setting, obj):
1455
            LOG.debug("Setting value: " + str(setting.value) + " from list")
1456
            val = str(setting.value)
1457
            index = GC_CHOICES.index(val)
1458
            val = GC_VALUES[index]
1459
            obj.set_value(val)
1460

    
1461
        if _dtmf.groupCode in GC_VALUES:
1462
            idx = GC_VALUES.index(_dtmf.groupCode)
1463
        else:
1464
            idx = GC_VALUES.index(0x0A)
1465
        rs = RadioSetting("dtmf.groupCode", "DTMF interval character",
1466
                          RadioSettingValueList(GC_CHOICES,
1467
                                                GC_CHOICES[idx]))
1468
        rs.set_apply_callback(apply_gc_listvalue, _dtmf.groupCode)
1469
        dtmf.append(rs)
1470

    
1471
        # Decoding Response
1472
        options = ["None", "Beep tone", "Beep tone & respond"]
1473
        rs = RadioSettingValueList(options, options[_dtmf.decodingResponse])
1474
        rset = RadioSetting("dtmf.decodingResponse", "Decoding response", rs)
1475
        dtmf.append(rset)
1476

    
1477
        # First Digit Time
1478
        options = ["%s" % x for x in range(0, 2510, 10)]
1479
        rs = RadioSettingValueList(options, options[_dtmf.firstDigitTime])
1480
        rset = RadioSetting("dtmf.firstDigitTime", "First Digit Time(ms)", rs)
1481
        dtmf.append(rset)
1482

    
1483
        # First Digit Time
1484
        options = ["%s" % x for x in range(10, 2510, 10)]
1485
        rs = RadioSettingValueList(options, options[_dtmf.pretime - 1])
1486
        rset = RadioSetting("dtmf.pretime", "Pretime(ms)", rs)
1487
        dtmf.append(rset)
1488

    
1489
        # Auto Reset Time
1490
        options = ["%s" % x for x in range(0, 25100, 100)]
1491
        rs = RadioSettingValueList(options, options[_dtmf.autoResetTime])
1492
        rset = RadioSetting("dtmf.autoResetTime", "Auto Reset time(ms)", rs)
1493
        dtmf.append(rset)
1494

    
1495
        # Time-Lapse After Encode
1496
        options = ["%s" % x for x in range(10, 2510, 10)]
1497
        rs = RadioSettingValueList(options, options[_dtmf.timeLapse - 1])
1498
        rset = RadioSetting("dtmf.timeLapse",
1499
                            "Time-lapse after encode(ms)", rs)
1500
        dtmf.append(rset)
1501

    
1502
        # PTT ID Pause Time
1503
        options = ["Off", "-", "-", "-", "-"] + [
1504
                   "%s" % x for x in range(5, 76)]
1505
        rs = RadioSettingValueList(options, options[_dtmf.pauseTime])
1506
        rset = RadioSetting("dtmf.pauseTime", "PTT ID pause time(s)", rs)
1507
        dtmf.append(rset)
1508

    
1509
        # Side Tone
1510
        rs = RadioSettingValueBoolean(_dtmf.sideTone)
1511
        rset = RadioSetting("dtmf.sideTone", "Side tone", rs)
1512
        dtmf.append(rset)
1513

    
1514
        # PTT ID Starting
1515
        DTMF_CHARS = "0123456789ABCD*# "
1516
        _codeobj = _dtmf.pttIdStart
1517
        _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
1518
        val = RadioSettingValueString(0, 16, _code, False)
1519
        val.set_charset(DTMF_CHARS)
1520
        rs = RadioSetting("dtmf.pttIdStart", "PTT ID starting", val)
1521

    
1522
        def apply_code(setting, obj):
1523
            code = []
1524
            for j in range(0, 16):
1525
                try:
1526
                    code.append(DTMF_CHARS.index(str(setting.value)[j]))
1527
                except IndexError:
1528
                    code.append(0xFF)
1529
            obj.pttIdStart = code
1530
        rs.set_apply_callback(apply_code, _dtmf)
1531
        dtmf.append(rs)
1532

    
1533
        # PTT ID Ending
1534
        _codeobj = _dtmf.pttIdEnd
1535
        _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
1536
        val = RadioSettingValueString(0, 16, _code, False)
1537
        val.set_charset(DTMF_CHARS)
1538
        rs = RadioSetting("dtmf.pttIdEnd", "PTT ID ending", val)
1539

    
1540
        def apply_code(setting, obj):
1541
            code = []
1542
            for j in range(0, 16):
1543
                try:
1544
                    code.append(DTMF_CHARS.index(str(setting.value)[j]))
1545
                except IndexError:
1546
                    code.append(0xFF)
1547
            obj.pttIdEnd = code
1548
        rs.set_apply_callback(apply_code, _dtmf)
1549
        dtmf.append(rs)
1550

    
1551
        # Remotely Kill
1552
        _codeobj = _dtmf.remoteKill
1553
        _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
1554
        val = RadioSettingValueString(0, 16, _code, False)
1555
        val.set_charset(DTMF_CHARS)
1556
        rs = RadioSetting("dtmf.remoteKill", "Remotely kill", val)
1557

    
1558
        def apply_code(setting, obj):
1559
            code = []
1560
            for j in range(0, 16):
1561
                try:
1562
                    code.append(DTMF_CHARS.index(str(setting.value)[j]))
1563
                except IndexError:
1564
                    code.append(0xFF)
1565
            obj.remoteKill = code
1566
        rs.set_apply_callback(apply_code, _dtmf)
1567
        dtmf.append(rs)
1568

    
1569
        # Remotely Stun
1570
        _codeobj = _dtmf.remoteStun
1571
        _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
1572
        val = RadioSettingValueString(0, 16, _code, False)
1573
        val.set_charset(DTMF_CHARS)
1574
        rs = RadioSetting("dtmf.remoteStun", "Remotely stun", val)
1575

    
1576
        def apply_code(setting, obj):
1577
            code = []
1578
            for j in range(0, 16):
1579
                try:
1580
                    code.append(DTMF_CHARS.index(str(setting.value)[j]))
1581
                except IndexError:
1582
                    code.append(0xFF)
1583
            obj.remoteStun = code
1584
        rs.set_apply_callback(apply_code, _dtmf)
1585
        dtmf.append(rs)
1586

    
1587
        # DTMF Encode
1588
        # M1 - M16
1589
        for i in range(0, 16):
1590
            _codeobj = self._memobj.pttid[i].code
1591
            _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
1592
            val = RadioSettingValueString(0, 16, _code, False)
1593
            val.set_charset(DTMF_CHARS)
1594
            rs = RadioSetting("pttid/%i.code" % i,
1595
                              "DTMF encode M%i" % (i + 1), val)
1596

    
1597
            def apply_code(setting, obj):
1598
                code = []
1599
                for j in range(0, 16):
1600
                    try:
1601
                        code.append(DTMF_CHARS.index(str(setting.value)[j]))
1602
                    except IndexError:
1603
                        code.append(0xFF)
1604
                obj.code = code
1605
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1606
            dtmf.append(rs)
1607

    
1608
        return group
1609

    
1610
    def set_settings(self, settings):
1611
        _settings = self._memobj.settings
1612
        _mem = self._memobj
1613
        for element in settings:
1614
            if not isinstance(element, RadioSetting):
1615
                self.set_settings(element)
1616
                continue
1617
            else:
1618
                try:
1619
                    name = element.get_name()
1620
                    if "." in name:
1621
                        bits = name.split(".")
1622
                        obj = self._memobj
1623
                        for bit in bits[:-1]:
1624
                            if "/" in bit:
1625
                                bit, index = bit.split("/", 1)
1626
                                index = int(index)
1627
                                obj = getattr(obj, bit)[index]
1628
                            else:
1629
                                obj = getattr(obj, bit)
1630
                        setting = bits[-1]
1631
                    else:
1632
                        obj = _settings
1633
                        setting = element.get_name()
1634

    
1635
                    if element.has_apply_callback():
1636
                        LOG.debug("Using apply callback")
1637
                        element.run_apply_callback()
1638
                    elif setting == "timeLapse":
1639
                        setattr(obj, setting, int(element.value) + 1)
1640
                    elif setting == "pretime":
1641
                        setattr(obj, setting, int(element.value) + 1)
1642
                    elif setting == "backlightBr":
1643
                        setattr(obj, setting, int(element.value) + 1)
1644
                    elif setting == "micKeyBrite":
1645
                        setattr(obj, setting, int(element.value) + 1)
1646
                    elif setting == "speakerVol":
1647
                        setattr(obj, setting, int(element.value) + 1)
1648
                    elif "keyMode" in setting:
1649
                        setattr(obj, setting, int(element.value) + 1)
1650
                    elif "keyP" in setting:
1651
                        setattr(obj, setting, int(element.value) + 2)
1652
                    elif element.value.get_mutable():
1653
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1654
                        setattr(obj, setting, element.value)
1655
                except Exception, e:
1656
                    LOG.debug(element.get_name())
1657
                    raise
1658

    
1659
if has_future:
1660
    @directory.register
1661
    class AnyTone778UV(AnyTone778UVBase):
1662
        VENDOR = "AnyTone"
1663
        MODEL = "778UV"
1664
        # Allowed radio types is a dict keyed by model of a list of version
1665
        # strings
1666
        ALLOWED_RADIO_TYPES = {'AT778UV': ['V100', 'V200']}
1667
        _has_vox = False
1668

    
1669
    @directory.register
1670
    class RetevisRT95(AnyTone778UVBase):
1671
        VENDOR = "Retevis"
1672
        MODEL = "RT95"
1673
        # Allowed radio types is a dict keyed by model of a list of version
1674
        # strings
1675
        ALLOWED_RADIO_TYPES = {'RT95': ['V100']}
1676
        _has_vox = False
1677

    
1678
    @directory.register
1679
    class CRTMicronUV(AnyTone778UVBase):
1680
        VENDOR = "CRT"
1681
        MODEL = "Micron UV"
1682
        # Allowed radio types is a dict keyed by model of a list of version
1683
        # strings
1684
        ALLOWED_RADIO_TYPES = {'MICRON': ['V100']}
1685
        _has_vox = False
1686

    
1687
    @directory.register
1688
    class MidlandDBR2500(AnyTone778UVBase):
1689
        VENDOR = "Midland"
1690
        MODEL = "DBR2500"
1691
        # Allowed radio types is a dict keyed by model of a list of version
1692
        # strings
1693
        ALLOWED_RADIO_TYPES = {'DBR2500': ['V100']}
1694
        _has_vox = False
1695

    
1696
    @directory.register
1697
    class YedroYCM04vus(AnyTone778UVBase):
1698
        VENDOR = "Yedro"
1699
        MODEL = "YC-M04VUS"
1700
        # Allowed radio types is a dict keyed by model of a list of version
1701
        # strings
1702
        ALLOWED_RADIO_TYPES = {'YCM04UV': ['V100']}
1703
        _has_vox = False
1704

    
1705
    @directory.register
1706
    class RetevisRT95P(AnyTone778UVBase):
1707
        VENDOR = "Retevis"
1708
        MODEL = "RT95-P"
1709
        # Allowed radio types is a dict keyed by model of a list of version
1710
        # strings
1711
        ALLOWED_RADIO_TYPES = {'RT95-P': ['V100']}
1712
        _has_vox = True
1713

    
1714
    @directory.register
1715
    class AnyTone778UVP(AnyTone778UVBase):
1716
        VENDOR = "AnyTone"
1717
        MODEL = "778UV-P"
1718
        # Allowed radio types is a dict keyed by model of a list of version
1719
        # strings
1720
        ALLOWED_RADIO_TYPES = {'778UV-P': ['V100']}
1721
        _has_vox = True
(11-11/16)