Project

General

Profile

New Model #8859 » anytone778uv_vox4.py

Jim Unroe, 03/12/2021 01:58 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
  char name[6];
112
  ul16 customctcss;
113
} memory[200];
114
#seekto 0x1940;
115
struct {
116
  u8 occupied_bitfield[32];
117
  u8 scan_enabled_bitfield[32];
118
} memory_status;
119

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

    
125
#seekto 0x1990;
126
struct {
127
  u8 code[16];            // DTMF Encode M1-M16
128
} pttid[16];
129

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
329

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

    
338

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

    
347

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

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

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

    
370
    return response
371

    
372

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

    
378

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

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

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

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

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

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

    
406
    return verok, int(resp.bandlimit)
407

    
408

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

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

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

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

    
431
    return bandlimit
432

    
433

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

    
438

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

    
451

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

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

    
459
    try:
460
        enter_program_mode(radio)
461

    
462
        memory_data = bytes()
463

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

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

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

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

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

    
495
    return memmap.MemoryMapBytes(memory_data)
496

    
497

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

    
506

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

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

    
522
        serial = radio.pipe
523

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

    
533
        bptr = 0
534

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

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

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

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

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

    
572

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

    
580

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

    
592

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

    
597

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

    
611

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

    
619

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

    
625

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

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

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

    
641
        return rp
642

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
898
        return mem
899

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

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

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

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

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

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

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

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

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

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

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

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

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

    
994
            if mem.tmode == 'Tone':
995
                _mem.ctcss_encode_en = 1
996
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
997
            elif mem.tmode == 'TSQL':
998
                _mem.ctcss_encode_en = 1
999
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.ctone)
1000
                _mem.ctcss_decode_en = 1
1001
                _mem.tone_squelch_en = 1
1002
                _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
1003
            elif mem.tmode == 'DTCS':
1004
                _mem.dtcs_encode_en = 1
1005
                _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
1006
                    dtcs_code_val_to_bits(mem.rx_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
            elif mem.tmode == 'Cross':
1012
                txmode, rxmode = mem.cross_mode.split('->')
1013

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1428
        # DTMF Self ID
1429

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1609
        return group
1610

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

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

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

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

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

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

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

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

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