Project

General

Profile

New Model #8859 » anytone778uv_vox5.py

Jim Unroe, 03/15/2021 06:42 PM

 
1
# Copyright 2020 Joe Milbourn <joe@milbourn.org.uk>
2
# Copyright 2021 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
  u8 unk321c:7,           // 0x321C
209
     voxOnOff:1;          //        vox on/off
210
  u8 voxLevel;            // 0x321D vox level
211
  u8 voxDelay;            // 0x321E vox delay
212
} settings;
213

    
214
#seekto 0x3240;
215
struct {
216
  char digits[6];         // password
217
} password;
218

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

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

    
261
# Format for the version messages returned by the radio
262
VER_FORMAT = '''
263
u8 hdr;
264
char model[7];
265
u8 bandlimit;
266
char version[6];
267
u8 ack;
268
'''
269

    
270
TXPOWER_LOW = 0x00
271
TXPOWER_MED = 0x01
272
TXPOWER_HIGH = 0x02
273

    
274
DUPLEX_NOSPLIT = 0x00
275
DUPLEX_POSSPLIT = 0x01
276
DUPLEX_NEGSPLIT = 0x02
277
DUPLEX_ODDSPLIT = 0x03
278

    
279
CHANNEL_WIDTH_25kHz = 0x02
280
CHANNEL_WIDTH_20kHz = 0x01
281
CHANNEL_WIDTH_12d5kHz = 0x00
282

    
283
BUSY_CHANNEL_LOCKOUT_OFF = 0x00
284
BUSY_CHANNEL_LOCKOUT_REPEATER = 0x01
285
BUSY_CHANNEL_LOCKOUT_BUSY = 0x02
286

    
287
MEMORY_ADDRESS_RANGE = (0x0000, 0x3290)
288
MEMORY_RW_BLOCK_SIZE = 0x10
289
MEMORY_RW_BLOCK_CMD_SIZE = 0x16
290

    
291
POWER_LEVELS = [chirp_common.PowerLevel('Low', dBm=37),
292
                chirp_common.PowerLevel('Medium', dBm=40),
293
                chirp_common.PowerLevel('High', dBm=44)]
294

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

    
315
TONE_MAP_TONE_TO_VAL = {TONE_MAP_VAL_TO_TONE[val]: val
316
                        for val in TONE_MAP_VAL_TO_TONE}
317

    
318
TONES_EN_TXTONE = (1 << 3)
319
TONES_EN_RXTONE = (1 << 2)
320
TONES_EN_TXCODE = (1 << 1)
321
TONES_EN_RXCODE = (1 << 0)
322
TONES_EN_NO_TONE = 0
323

    
324
# Radio supports upper case and symbols
325
CHARSET_ASCII_PLUS = chirp_common.CHARSET_UPPER_NUMERIC + '- '
326

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

    
333

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

    
342

    
343
# Calculate the checksum used in serial packets
344
def checksum(message_bytes):
345
    mask = 0xFF
346
    checksum = 0
347
    for b in message_bytes:
348
        checksum = (checksum + b) & mask
349
    return checksum
350

    
351

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

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

    
370
    # cut off what got echo'd back, we don't need to see it again
371
    if response.startswith(command):
372
        response = response[len(command):]
373

    
374
    return response
375

    
376

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

    
382

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

    
388
    LOG.debug('ver_response = ')
389
    LOG.debug(util.hexprint(ver_response))
390

    
391
    resp = bitwise.parse(VER_FORMAT, ver_response)
392
    verok = False
393

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

    
401
        if model in allowed_types:
402
            LOG.debug('model in allowed_types')
403

    
404
            if version in allowed_types[model]:
405
                LOG.debug('version in allowed_types[model]')
406
                verok = True
407
    else:
408
        raise errors.RadioError('Failed to parse version response')
409

    
410
    return verok, int(resp.bandlimit)
411

    
412

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

    
421
    if program_response != b'QX\x06':
422
        raise errors.RadioError('No initial response from radio.')
423
    LOG.debug('entered program mode')
424

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

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

    
435
    return bandlimit
436

    
437

    
438
# Exit programming mode
439
def exit_program_mode(radio):
440
    send_serial_command(radio.pipe, b'END')
441

    
442

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

    
455

    
456
# Download data from the radio and populate the memory map
457
def do_download(radio):
458
    '''Download memories from the radio'''
459

    
460
    # Get the serial port connection
461
    serial = radio.pipe
462

    
463
    try:
464
        enter_program_mode(radio)
465

    
466
        memory_data = bytes()
467

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

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

    
485
            address, data, valid = parse_read_response(read_response)
486
            memory_data += data
487

    
488
            # update UI
489
            status.cur = (addr - MEMORY_ADDRESS_RANGE[0])\
490
                / MEMORY_RW_BLOCK_SIZE
491
            radio.status_fn(status)
492

    
493
        exit_program_mode(radio)
494
    except errors.RadioError as e:
495
        raise e
496
    except Exception as e:
497
        raise errors.RadioError('Failed to download from radio: %s' % e)
498

    
499
    return memmap.MemoryMapBytes(memory_data)
500

    
501

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

    
510

    
511
# Upload a memory map to the radio
512
def do_upload(radio):
513
    try:
514
        bandlimit = enter_program_mode(radio)
515

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

    
526
        serial = radio.pipe
527

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

    
537
        bptr = 0
538

    
539
        memory_addrs = range(MEMORY_ADDRESS_RANGE[0],
540
                             MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
541
                             MEMORY_RW_BLOCK_SIZE)
542

    
543
        # status info for the UI
544
        status = chirp_common.Status()
545
        status.cur = 0
546
        status.max = len(memory_addrs)
547
        status.msg = 'Cloning to radio...'
548
        radio.status_fn(status)
549

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

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

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

    
576

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

    
584

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

    
596

    
597
# Translate the radio's version of a code as stored to a real code
598
def dtcs_code_bits_to_val(highbit, lowbyte):
599
    return chirp_common.ALL_DTCS_CODES[highbit*256 + lowbyte]
600

    
601

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

    
615

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

    
623

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

    
629

    
630
class AnyTone778UVBase(chirp_common.CloneModeRadio,
631
                       chirp_common.ExperimentalRadio):
632
    '''AnyTone 778UV and probably Retivis RT95 and others'''
633
    BAUD_RATE = 9600
634
    NEEDS_COMPAT_SERIAL = False
635
    NAME_LENGTH = 5
636
    HAS_VOX = False
637

    
638
    @classmethod
639
    def get_prompts(cls):
640
        rp = chirp_common.RadioPrompts()
641

    
642
        rp.experimental = \
643
            ('This is experimental support for the %s %s.  '
644
             'Please send in bug and enhancement requests!' %
645
             (cls.VENDOR, cls.MODEL))
646

    
647
        return rp
648

    
649
    # Return information about this radio's features, including
650
    # how many memories it has, what bands it supports, etc
651
    def get_features(self):
652
        rf = chirp_common.RadioFeatures()
653
        rf.has_bank = False
654
        rf.has_settings = True
655
        rf.can_odd_split = True
656
        rf.has_name = True
657
        rf.has_offset = True
658
        rf.valid_name_length = self.NAME_LENGTH
659
        rf.valid_duplexes = ['', '+', '-', 'split', 'off']
660
        rf.valid_characters = CHARSET_ASCII_PLUS
661

    
662
        rf.has_dtcs = True
663
        rf.has_rx_dtcs = True
664
        rf.has_dtcs_polarity = True
665
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES
666
        rf.has_ctone = True
667
        rf.has_cross = True
668
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
669
        rf.valid_cross_modes = ['Tone->Tone',
670
                                'Tone->DTCS',
671
                                'DTCS->Tone',
672
                                'DTCS->DTCS',
673
                                'DTCS->',
674
                                '->DTCS',
675
                                '->Tone']
676

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

    
693
    # Do a download of the radio from the serial port
694
    def sync_in(self):
695
        self._mmap = do_download(self)
696
        self.process_mmap()
697

    
698
    # Do an upload of the radio to the serial port
699
    def sync_out(self):
700
        do_upload(self)
701

    
702
    # Convert the raw byte array into a memory object structure
703
    def process_mmap(self):
704
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
705

    
706
    # Return a raw representation of the memory object, which
707
    # is very helpful for development
708
    def get_raw_memory(self, number):
709
        return repr(self._memobj.memory[number - 1])
710

    
711
    # Extract a high-level memory object from the low-level memory map
712
    # This is called to populate a memory in the UI
713
    def get_memory(self, number):
714
        number -= 1
715
        # Get a low-level memory object mapped to the image
716
        _mem = self._memobj.memory[number]
717
        _mem_status = self._memobj.memory_status
718

    
719
        # Create a high-level memory object to return to the UI
720
        mem = chirp_common.Memory()
721
        mem.number = number + 1           # Set the memory number
722

    
723
        # Check if this memory is present in the occupied list
724
        mem.empty = get_bitfield(_mem_status.occupied_bitfield, number) == 0
725

    
726
        if not mem.empty:
727
            # Check if this memory is in the scan enabled list
728
            mem.skip = ''
729
            if get_bitfield(_mem_status.scan_enabled_bitfield, number) == 0:
730
                mem.skip = 'S'
731

    
732
            # set the name
733
            ## mem.name = str(_mem.name).rstrip()  # Set the alpha tag
734

    
735
            if self.NAME_LENGTH == 5:
736
                val = str(_mem.name)
737
                mem.name = str(val[1:6]).rstrip()  # Set the alpha tag
738
            else:
739
                mem.name = str(_mem.name).rstrip()  # Set the alpha tag
740

    
741
            # Convert your low-level frequency and offset to Hertz
742
            mem.freq = int(_mem.freq) * 10
743
            mem.offset = int(_mem.offset) * 10
744

    
745
            # Set the duplex flags
746
            if _mem.duplex == DUPLEX_POSSPLIT:
747
                mem.duplex = '+'
748
            elif _mem.duplex == DUPLEX_NEGSPLIT:
749
                mem.duplex = '-'
750
            elif _mem.duplex == DUPLEX_NOSPLIT:
751
                mem.duplex = ''
752
            elif _mem.duplex == DUPLEX_ODDSPLIT:
753
                mem.duplex = 'split'
754
            else:
755
                LOG.error('%s: get_mem: unhandled duplex: %02x' %
756
                          (mem.name, _mem.duplex))
757

    
758
            # handle tx off
759
            if _mem.tx_off:
760
                mem.duplex = 'off'
761

    
762
            # Set the channel width
763
            if _mem.channel_width == CHANNEL_WIDTH_25kHz:
764
                mem.mode = 'FM'
765
            elif _mem.channel_width == CHANNEL_WIDTH_20kHz:
766
                LOG.info(
767
                    '%s: get_mem: promoting 20kHz channel width to 25kHz' %
768
                    mem.name)
769
                mem.mode = 'FM'
770
            elif _mem.channel_width == CHANNEL_WIDTH_12d5kHz:
771
                mem.mode = 'NFM'
772
            else:
773
                LOG.error('%s: get_mem: unhandled channel width: 0x%02x' %
774
                          (mem.name, _mem.channel_width))
775

    
776
            # set the power level
777
            if _mem.txpower == TXPOWER_LOW:
778
                mem.power = POWER_LEVELS[0]
779
            elif _mem.txpower == TXPOWER_MED:
780
                mem.power = POWER_LEVELS[1]
781
            elif _mem.txpower == TXPOWER_HIGH:
782
                mem.power = POWER_LEVELS[2]
783
            else:
784
                LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
785
                          (mem.name, _mem.txpower))
786

    
787
            # CTCSS Tones
788
            # TODO support custom ctcss tones here
789
            txtone = None
790
            rxtone = None
791
            rxcode = None
792
            txcode = None
793

    
794
            # check if dtcs tx is enabled
795
            if _mem.dtcs_encode_en:
796
                txcode = dtcs_code_bits_to_val(_mem.dtcs_encode_code_highbit,
797
                                               _mem.dtcs_encode_code)
798

    
799
            # check if dtcs rx is enabled
800
            if _mem.dtcs_decode_en:
801
                rxcode = dtcs_code_bits_to_val(_mem.dtcs_decode_code_highbit,
802
                                               _mem.dtcs_decode_code)
803

    
804
            if txcode is not None:
805
                LOG.debug('%s: get_mem dtcs_enc: %d' % (mem.name, txcode))
806
            if rxcode is not None:
807
                LOG.debug('%s: get_mem dtcs_dec: %d' % (mem.name, rxcode))
808

    
809
            # tsql set if radio squelches on tone
810
            tsql = _mem.tone_squelch_en
811

    
812
            # check if ctcss tx is enabled
813
            if _mem.ctcss_encode_en:
814
                txtone = ctcss_tone_bits_to_val(_mem.ctcss_enc_tone)
815

    
816
            # check if ctcss rx is enabled
817
            if _mem.ctcss_decode_en:
818
                rxtone = ctcss_tone_bits_to_val(_mem.ctcss_dec_tone)
819

    
820
            # Define this here to allow a readable if-else tree enabling tone
821
            # options
822
            enabled = 0
823
            enabled |= (txtone is not None) * TONES_EN_TXTONE
824
            enabled |= (rxtone is not None) * TONES_EN_RXTONE
825
            enabled |= (txcode is not None) * TONES_EN_TXCODE
826
            enabled |= (rxcode is not None) * TONES_EN_RXCODE
827

    
828
            # Add some debugging output for the tone bitmap
829
            enstr = []
830
            if enabled & TONES_EN_TXTONE:
831
                enstr += ['TONES_EN_TXTONE']
832
            if enabled & TONES_EN_RXTONE:
833
                enstr += ['TONES_EN_RXTONE']
834
            if enabled & TONES_EN_TXCODE:
835
                enstr += ['TONES_EN_TXCODE']
836
            if enabled & TONES_EN_RXCODE:
837
                enstr += ['TONES_EN_RXCODE']
838
            if enabled == 0:
839
                enstr = ['TONES_EN_NOTONE']
840
            LOG.debug('%s: enabled = %s' % (
841
                mem.name, '|'.join(enstr)))
842

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

    
899
                # Can get here if e.g. TONE_EN_RXCODE is set and tsql isn't
900
                # In that case should we perhaps store the tone and code values
901
                # if they're present and then setup tmode and cross_mode as
902
                # appropriate later?
903

    
904
            # set the dtcs polarity
905
            dtcs_pol_bit_to_str = {0: 'N', 1: 'R'}
906
            mem.dtcs_polarity = '%s%s' %\
907
                (dtcs_pol_bit_to_str[_mem.dtcs_encode_invert == 1],
908
                 dtcs_pol_bit_to_str[_mem.dtcs_decode_invert == 1])
909

    
910
        return mem
911

    
912
    # Store details about a high-level memory to the memory map
913
    # This is called when a user edits a memory in the UI
914
    def set_memory(self, mem):
915
        # Get a low-level memory object mapped to the image
916
        _mem = self._memobj.memory[mem.number - 1]
917
        _mem_status = self._memobj.memory_status
918

    
919
        # set the occupied bitfield
920
        _mem_status.occupied_bitfield = \
921
            set_bitfield(_mem_status.occupied_bitfield, mem.number - 1,
922
                         not mem.empty)
923

    
924
        # set the scan add bitfield
925
        _mem_status.scan_enabled_bitfield = \
926
            set_bitfield(_mem_status.scan_enabled_bitfield, mem.number - 1,
927
                         (not mem.empty) and (mem.skip != 'S'))
928

    
929
        if mem.empty:
930
            # Set the whole memory to 0xff
931
            _mem.set_raw('\xff' * (_mem.size() / 8))
932
        else:
933
            _mem.set_raw('\x00' * (_mem.size() / 8))
934

    
935
            _mem.freq = int(mem.freq / 10)
936
            _mem.offset = int(mem.offset / 10)
937

    
938
            # Store the alpha tag
939
            ## _mem.name = mem.name.ljust(self.NAME_LENGTH)[:self.NAME_LENGTH]
940

    
941
            if self.NAME_LENGTH == 5:
942
                temp_name = mem.name.ljust(self.NAME_LENGTH)[:self.NAME_LENGTH]
943
                _mem.name = temp_name.rjust(6, chr(00))
944
            else:
945
                _mem.name = mem.name.ljust(self.NAME_LENGTH)[:self.NAME_LENGTH]
946

    
947
            ## str2 = str1.ljust(6, chr(00))      # pad to 6 with 00's
948

    
949

    
950
            # TODO support busy channel lockout - disabled for now
951
            _mem.busy_channel_lockout = BUSY_CHANNEL_LOCKOUT_OFF
952

    
953
            # Set duplex bitfields
954
            if mem.duplex == '+':
955
                _mem.duplex = DUPLEX_POSSPLIT
956
            elif mem.duplex == '-':
957
                _mem.duplex = DUPLEX_NEGSPLIT
958
            elif mem.duplex == '':
959
                _mem.duplex = DUPLEX_NOSPLIT
960
            elif mem.duplex == 'split':
961
                # TODO: this is an unverified punt!
962
                _mem.duplex = DUPLEX_ODDSPLIT
963
            else:
964
                LOG.error('%s: set_mem: unhandled duplex: %s' %
965
                          (mem.name, mem.duplex))
966

    
967
            # handle tx off
968
            _mem.tx_off = 0
969
            if mem.duplex == 'off':
970
                _mem.tx_off = 1
971

    
972
            # Set the channel width - remember we promote 20kHz channels to FM
973
            # on import
974
            # , so don't handle them here
975
            if mem.mode == 'FM':
976
                _mem.channel_width = CHANNEL_WIDTH_25kHz
977
            elif mem.mode == 'NFM':
978
                _mem.channel_width = CHANNEL_WIDTH_12d5kHz
979
            else:
980
                LOG.error('%s: set_mem: unhandled mode: %s' % (
981
                    mem.name, mem.mode))
982

    
983
            # set the power level
984
            if mem.power == POWER_LEVELS[0]:
985
                _mem.txpower = TXPOWER_LOW
986
            elif mem.power == POWER_LEVELS[1]:
987
                _mem.txpower = TXPOWER_MED
988
            elif mem.power == POWER_LEVELS[2]:
989
                _mem.txpower = TXPOWER_HIGH
990
            else:
991
                LOG.error('%s: set_mem: unhandled power level: %s' %
992
                          (mem.name, mem.power))
993

    
994
            # TODO set the CTCSS values
995
            # TODO support custom ctcss tones here
996
            # Default - tones off, carrier sql
997
            _mem.ctcss_encode_en = 0
998
            _mem.ctcss_decode_en = 0
999
            _mem.tone_squelch_en = 0
1000
            _mem.ctcss_enc_tone = 0x00
1001
            _mem.ctcss_dec_tone = 0x00
1002
            _mem.customctcss = 0x00
1003
            _mem.dtcs_encode_en = 0
1004
            _mem.dtcs_encode_code_highbit = 0
1005
            _mem.dtcs_encode_code = 0
1006
            _mem.dtcs_encode_invert = 0
1007
            _mem.dtcs_decode_en = 0
1008
            _mem.dtcs_decode_code_highbit = 0
1009
            _mem.dtcs_decode_code = 0
1010
            _mem.dtcs_decode_invert = 0
1011

    
1012
            dtcs_pol_str_to_bit = {'N': 0, 'R': 1}
1013
            _mem.dtcs_encode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[0]]
1014
            _mem.dtcs_decode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[1]]
1015

    
1016
            if mem.tmode == 'Tone':
1017
                _mem.ctcss_encode_en = 1
1018
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
1019
            elif mem.tmode == 'TSQL':
1020
                _mem.ctcss_encode_en = 1
1021
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.ctone)
1022
                _mem.ctcss_decode_en = 1
1023
                _mem.tone_squelch_en = 1
1024
                _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
1025
            elif mem.tmode == 'DTCS':
1026
                _mem.dtcs_encode_en = 1
1027
                _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
1028
                    dtcs_code_val_to_bits(mem.rx_dtcs)
1029
                _mem.dtcs_decode_en = 1
1030
                _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
1031
                    dtcs_code_val_to_bits(mem.rx_dtcs)
1032
                _mem.tone_squelch_en = 1
1033
            elif mem.tmode == 'Cross':
1034
                txmode, rxmode = mem.cross_mode.split('->')
1035

    
1036
                if txmode == 'Tone':
1037
                    _mem.ctcss_encode_en = 1
1038
                    _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
1039
                elif txmode == '':
1040
                    pass
1041
                elif txmode == 'DTCS':
1042
                    _mem.dtcs_encode_en = 1
1043
                    _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
1044
                        dtcs_code_val_to_bits(mem.dtcs)
1045
                else:
1046
                    LOG.error('%s: unhandled cross TX mode: %s' % (
1047
                        mem.name, mem.cross_mode))
1048

    
1049
                if rxmode == 'Tone':
1050
                    _mem.ctcss_decode_en = 1
1051
                    _mem.tone_squelch_en = 1
1052
                    _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
1053
                elif rxmode == '':
1054
                    pass
1055
                elif rxmode == 'DTCS':
1056
                    _mem.dtcs_decode_en = 1
1057
                    _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
1058
                        dtcs_code_val_to_bits(mem.rx_dtcs)
1059
                    _mem.tone_squelch_en = 1
1060
                else:
1061
                    LOG.error('%s: unhandled cross RX mode: %s' % (
1062
                        mem.name, mem.cross_mode))
1063
            else:
1064
                LOG.error('%s: Unhandled tmode/cross %s/%s.' %
1065
                          (mem.name, mem.tmode, mem.cross_mode))
1066
            LOG.debug('%s: tmode=%s, cross=%s, rtone=%f, ctone=%f' % (
1067
                mem.name, mem.tmode, mem.cross_mode, mem.rtone, mem.ctone))
1068
            LOG.debug('%s: CENC=%d, CDEC=%d, t(enc)=%02x, t(dec)=%02x' % (
1069
                mem.name,
1070
                _mem.ctcss_encode_en,
1071
                _mem.ctcss_decode_en,
1072
                ctcss_code_val_to_bits(mem.rtone),
1073
                ctcss_code_val_to_bits(mem.ctone)))
1074

    
1075
            # set unknown defaults, based on reading memory set by vendor tool
1076
            _mem.unknown1 = 0x00
1077
            _mem.unknown6 = 0x00
1078
            _mem.unknown7 = 0x00
1079
            _mem.unknown8 = 0x00
1080
            _mem.unknown9 = 0x00
1081
            ## if not self.HAS_VOX:
1082
            ##     _mem.unknown10 = 0x00
1083

    
1084
    def get_settings(self):
1085
        """Translate the MEM_FORMAT structs into setstuf in the UI"""
1086
        _settings = self._memobj.settings
1087
        _radio_settings = self._memobj.radio_settings
1088
        ## if not self.HAS_VOX:
1089
        ##     _password = self._memobj.password
1090
        _password = self._memobj.password
1091
        _pfkeys = self._memobj.pfkeys
1092
        _dtmf = self._memobj.dtmf
1093

    
1094
        # Function Setup
1095
        function = RadioSettingGroup("function", "Function Setup")
1096
        group = RadioSettings(function)
1097

    
1098
        # MODE SET
1099
        # Channel Locked
1100
        rs = RadioSettingValueBoolean(_settings.channelLocked)
1101
        rset = RadioSetting("settings.channelLocked", "Channel locked", rs)
1102
        function.append(rset)
1103

    
1104
        # Menu 3 - Display Mode
1105
        options = ["Frequency", "Channel", "Name"]
1106
        rs = RadioSettingValueList(options, options[_settings.displayMode])
1107
        rset = RadioSetting("settings.displayMode", "Display Mode", rs)
1108
        function.append(rset)
1109

    
1110
        # VFO/MR A
1111
        options = ["MR", "VFO"]
1112
        rs = RadioSettingValueList(options, options[_radio_settings.vfomrA])
1113
        rset = RadioSetting("radio_settings.vfomrA", "VFO/MR mode A", rs)
1114
        function.append(rset)
1115

    
1116
        # MR Channel A
1117
        options = ["%s" % x for x in range(1, 201)]
1118
        rs = RadioSettingValueList(options, options[_radio_settings.mrChanA])
1119
        rset = RadioSetting("radio_settings.mrChanA", "MR channel A", rs)
1120
        function.append(rset)
1121

    
1122
        # VFO/MR B
1123
        options = ["MR", "VFO"]
1124
        rs = RadioSettingValueList(options, options[_radio_settings.vfomrB])
1125
        rset = RadioSetting("radio_settings.vfomrB", "VFO/MR mode B", rs)
1126
        function.append(rset)
1127

    
1128
        # MR Channel B
1129
        options = ["%s" % x for x in range(1, 201)]
1130
        rs = RadioSettingValueList(options, options[_radio_settings.mrChanB])
1131
        rset = RadioSetting("radio_settings.mrChanB", "MR channel B", rs)
1132
        function.append(rset)
1133

    
1134
        # DISPLAY SET
1135
        # Starting Display
1136
        name = ""
1137
        for i in range(7):  # 0 - 7
1138
            name += chr(self._memobj.starting_display.line[i])
1139
        name = name.upper().rstrip()  # remove trailing spaces
1140

    
1141
        rs = RadioSettingValueString(0, 7, name)
1142
        rs.set_charset(chirp_common.CHARSET_ALPHANUMERIC)
1143
        rset = RadioSetting("starting_display.line", "Starting display", rs)
1144
        function.append(rset)
1145

    
1146
        # Menu 11 - Backlight Brightness
1147
        options = ["%s" % x for x in range(1, 4)]
1148
        rs = RadioSettingValueList(options, options[_settings.backlightBr - 1])
1149
        rset = RadioSetting("settings.backlightBr", "Backlight brightness", rs)
1150
        function.append(rset)
1151

    
1152
        # Menu 15 - Screen Direction
1153
        options = ["Positive", "Inverted"]
1154
        rs = RadioSettingValueList(options, options[_settings.screenDir])
1155
        rset = RadioSetting("settings.screenDir", "Screen direction", rs)
1156
        function.append(rset)
1157

    
1158
        # Hand Mic Key Brightness
1159
        options = ["%s" % x for x in range(1, 32)]
1160
        rs = RadioSettingValueList(options, options[_settings.micKeyBrite - 1])
1161
        rset = RadioSetting("settings.micKeyBrite",
1162
                            "Hand mic key brightness", rs)
1163
        function.append(rset)
1164

    
1165
        # VOL SET
1166
        # Menu 1 - Beep Volume
1167
        options = ["OFF"] + ["%s" % x for x in range(1, 6)]
1168
        rs = RadioSettingValueList(options, options[_settings.beepVolume])
1169
        rset = RadioSetting("settings.beepVolume", "Beep volume", rs)
1170
        function.append(rset)
1171

    
1172
        # Menu 5 - Volume level Setup
1173
        options = ["%s" % x for x in range(1, 37)]
1174
        rs = RadioSettingValueList(options, options[_settings.speakerVol - 1])
1175
        rset = RadioSetting("settings.speakerVol", "Speaker volume", rs)
1176
        function.append(rset)
1177

    
1178
        # Menu 16 - Speaker Switch
1179
        options = ["Host on | Hand mic off", "Host on | Hand mic on",
1180
                   "Host off | Hand mic on"]
1181
        rs = RadioSettingValueList(options, options[_settings.speakerSwitch])
1182
        rset = RadioSetting("settings.speakerSwitch", "Speaker switch", rs)
1183
        function.append(rset)
1184

    
1185
        # STE SET
1186
        # STE Frequency
1187
        options = ["Off", "55.2 Hz", "259.2 Hz"]
1188
        rs = RadioSettingValueList(options, options[_settings.steFrequency])
1189
        rset = RadioSetting("settings.steFrequency", "STE frequency", rs)
1190
        function.append(rset)
1191

    
1192
        # STE Type
1193
        options = ["Off", "Silent", "120 degrees", "180 degrees",
1194
                   "240 degrees"]
1195
        rs = RadioSettingValueList(options, options[_settings.steType])
1196
        rset = RadioSetting("settings.steType", "STE type", rs)
1197
        function.append(rset)
1198

    
1199
        # ON/OFF SET
1200
        # The Power-on Password Feature was removed from VOX capable models
1201
        if not self.HAS_VOX:
1202
            # Power-on Password
1203
            rs = RadioSettingValueBoolean(_settings.powerOnPasswd)
1204
            rset = RadioSetting("settings.powerOnPasswd", "Power-on Password", rs)
1205
            function.append(rset)
1206

    
1207
            # Password
1208
            def _char_to_str(chrx):
1209
                """ Remove ff pads from char array """
1210
                #  chrx is char array
1211
                str1 = ""
1212
                for sx in chrx:
1213
                    if int(sx) > 31 and int(sx) < 127:
1214
                        str1 += chr(sx)
1215
                return str1
1216

    
1217
            def _pswd_vfy(setting, obj, atrb):
1218
                """ Verify password is 1-6 chars, numbers 1-5 """
1219
                str1 = str(setting.value).strip()   # initial
1220
                str2 = filter(lambda c: c in '0123456789', str1)    # valid chars
1221
                if str1 != str2:
1222
                    # Two lines due to python 73 char limit
1223
                    sx = "Bad characters in Password"
1224
                    raise errors.RadioError(sx)
1225
                str2 = str1.ljust(6, chr(00))      # pad to 6 with 00's
1226
                setattr(obj, atrb, str2)
1227
                return
1228

    
1229
            sx = _char_to_str(_password.digits).strip()
1230
            rx = RadioSettingValueString(0, 6, sx)
1231
            sx = "Password (numerals 0-9)"
1232
            rset = RadioSetting("password.digits", sx, rx)
1233
            rset.set_apply_callback(_pswd_vfy, _password, "digits")
1234
            function.append(rset)
1235

    
1236
        # Menu 9 - Auto Power On
1237
        rs = RadioSettingValueBoolean(_settings.autoPowerOn)
1238
        rset = RadioSetting("settings.autoPowerOn", "Auto power on", rs)
1239
        function.append(rset)
1240

    
1241
        # Menu 13 - Auto Power Off
1242
        options = ["Off", "30 minutes", "60 minutes", "120 minutes"]
1243
        rs = RadioSettingValueList(options, options[_settings.autoPowerOff])
1244
        rset = RadioSetting("settings.autoPowerOff", "Auto power off", rs)
1245
        function.append(rset)
1246

    
1247
        # Power On Reset Enable
1248
        rs = RadioSettingValueBoolean(_settings.powerOnReset)
1249
        rset = RadioSetting("settings.powerOnReset", "Power on reset", rs)
1250
        function.append(rset)
1251

    
1252
        # FUNCTION SET
1253
        # Menu 4 - Squelch Level A
1254
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
1255
        rs = RadioSettingValueList(options, options[_settings.squelchLevelA])
1256
        rset = RadioSetting("settings.squelchLevelA", "Squelch level A", rs)
1257
        function.append(rset)
1258

    
1259
        # Squelch Level B
1260
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
1261
        rs = RadioSettingValueList(options, options[_settings.squelchLevelB])
1262
        rset = RadioSetting("settings.squelchLevelB", "Squelch level B", rs)
1263
        function.append(rset)
1264

    
1265
        # Menu 7 - Scan Type
1266
        options = ["Time operated (TO)", "Carrier operated (CO)",
1267
                   "Search (SE)"]
1268
        rs = RadioSettingValueList(options, options[_settings.scanType])
1269
        rset = RadioSetting("settings.scanType", "Scan mode", rs)
1270
        function.append(rset)
1271

    
1272
        # Menu 8 - Scan Recovery Time
1273
        options = ["%s seconds" % x for x in range(5, 20, 5)]
1274
        rs = RadioSettingValueList(options, options[_settings.scanRecoveryT])
1275
        rset = RadioSetting("settings.scanRecoveryT", "Scan recovery time", rs)
1276
        function.append(rset)
1277

    
1278
        # Main
1279
        options = ["A", "B"]
1280
        rs = RadioSettingValueList(options, options[_settings.main])
1281
        rset = RadioSetting("settings.main", "Main", rs)
1282
        function.append(rset)
1283

    
1284
        # Menu 10 - Dual Watch (RX Way Select)
1285
        rs = RadioSettingValueBoolean(_settings.dualWatch)
1286
        rset = RadioSetting("settings.dualWatch", "Dual watch", rs)
1287
        function.append(rset)
1288

    
1289
        # Menu 12 - Time Out Timer
1290
        options = ["OFF"] + ["%s minutes" % x for x in range(1, 31)]
1291
        rs = RadioSettingValueList(options, options[_settings.timeOutTimer])
1292
        rset = RadioSetting("settings.timeOutTimer", "Time out timer", rs)
1293
        function.append(rset)
1294

    
1295
        # TBST Frequency
1296
        options = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"]
1297
        rs = RadioSettingValueList(options, options[_settings.tbstFrequency])
1298
        rset = RadioSetting("settings.tbstFrequency", "TBST frequency", rs)
1299
        function.append(rset)
1300

    
1301
        # Save Channel Perameter
1302
        rs = RadioSettingValueBoolean(_settings.saveChParameter)
1303
        rset = RadioSetting("settings.saveChParameter",
1304
                            "Save channel parameter", rs)
1305
        function.append(rset)
1306

    
1307
        # MON Key Function
1308
        options = ["Squelch off momentary", "Squelch off"]
1309
        rs = RadioSettingValueList(options, options[_settings.monKeyFunction])
1310
        rset = RadioSetting("settings.monKeyFunction", "MON key function", rs)
1311
        function.append(rset)
1312

    
1313
        # Frequency Step
1314
        options = ["2.5 KHz", "5 KHz", "6.25 KHz", "10 KHz", "12.5 KHz",
1315
                   "20 KHz", "25 KHz", "30 KHz", "50 KHz"]
1316
        rs = RadioSettingValueList(options, options[_settings.frequencyStep])
1317
        rset = RadioSetting("settings.frequencyStep", "Frequency step", rs)
1318
        function.append(rset)
1319

    
1320
        # Knob Mode
1321
        options = ["Volume", "Channel"]
1322
        rs = RadioSettingValueList(options, options[_settings.knobMode])
1323
        rset = RadioSetting("settings.knobMode", "Knob mode", rs)
1324
        function.append(rset)
1325

    
1326
        # TRF Enable
1327
        rs = RadioSettingValueBoolean(_settings.trfEnable)
1328
        rset = RadioSetting("settings.trfEnable", "TRF enable", rs)
1329
        function.append(rset)
1330

    
1331
        if self.HAS_VOX:
1332
            # VOX On/Off
1333
            rs = RadioSettingValueBoolean(_settings.voxOnOff)
1334
            rset = RadioSetting("settings.voxOnOff",
1335
                                "VOX", rs)
1336
            function.append(rset)
1337

    
1338
            # VOX Delay
1339
            options = ["0.5 S", "1.0 S", "1.5 S", "2.0 S", "2.5 S",
1340
                       "3.0 S", "3.5 S", "4.0 S", "4.5 S"]
1341
            rs = RadioSettingValueList(options, options[_settings.voxDelay])
1342
            rset = RadioSetting("settings.voxDelay", "VOX delay", rs)
1343
            function.append(rset)
1344

    
1345
            # VOX Level
1346
            options = ["%s" % x for x in range(1, 10)]
1347
            rs = RadioSettingValueList(options, options[_settings.voxLevel])
1348
            rset = RadioSetting("settings.voxLevel", "VOX Level", rs)
1349
            function.append(rset)
1350

    
1351
        # Key Assignment
1352
        pfkeys = RadioSettingGroup("pfkeys", "Key Assignment")
1353
        group.append(pfkeys)
1354

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

    
1359
        if self.HAS_VOX:
1360
            options.insert(16, "VOX")
1361

    
1362
        # Key Mode 1
1363
        # P1
1364
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P1 - 1])
1365
        rset = RadioSetting("pfkeys.keyMode1P1",
1366
                            "Key mode 1 P1", rs)
1367
        pfkeys.append(rset)
1368

    
1369
        # P2
1370
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P2 - 1])
1371
        rset = RadioSetting("pfkeys.keyMode1P2",
1372
                            "Key mode 1 P2", rs)
1373
        pfkeys.append(rset)
1374

    
1375
        # P3
1376
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P3 - 1])
1377
        rset = RadioSetting("pfkeys.keyMode1P3",
1378
                            "Key mode 1 P3", rs)
1379
        pfkeys.append(rset)
1380

    
1381
        # P4
1382
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P4 - 1])
1383
        rset = RadioSetting("pfkeys.keyMode1P4",
1384
                            "Key mode 1 P4", rs)
1385
        pfkeys.append(rset)
1386

    
1387
        # P5
1388
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P5 - 1])
1389
        rset = RadioSetting("pfkeys.keyMode1P5",
1390
                            "Key mode 1 P5", rs)
1391
        pfkeys.append(rset)
1392

    
1393
        # P6
1394
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P6 - 1])
1395
        rset = RadioSetting("pfkeys.keyMode1P6",
1396
                            "Key mode 1 P6", rs)
1397
        pfkeys.append(rset)
1398

    
1399
        # Key Mode 2
1400
        # P1
1401
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P1 - 1])
1402
        rset = RadioSetting("pfkeys.keyMode2P1",
1403
                            "Key mode 2 P1", rs)
1404
        pfkeys.append(rset)
1405

    
1406
        # P2
1407
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P2 - 1])
1408
        rset = RadioSetting("pfkeys.keyMode2P2",
1409
                            "Key mode 2 P2", rs)
1410
        pfkeys.append(rset)
1411

    
1412
        # P3
1413
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P3 - 1])
1414
        rset = RadioSetting("pfkeys.keyMode2P3",
1415
                            "Key mode 2 P3", rs)
1416
        pfkeys.append(rset)
1417

    
1418
        # P4
1419
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P4 - 1])
1420
        rset = RadioSetting("pfkeys.keyMode2P4",
1421
                            "Key mode 2 P4", rs)
1422
        pfkeys.append(rset)
1423

    
1424
        # P5
1425
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P5 - 1])
1426
        rset = RadioSetting("pfkeys.keyMode2P5",
1427
                            "Key mode 2 P5", rs)
1428
        pfkeys.append(rset)
1429

    
1430
        # P6
1431
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P6 - 1])
1432
        rset = RadioSetting("pfkeys.keyMode2P6",
1433
                            "Key mode 2 P6", rs)
1434
        pfkeys.append(rset)
1435

    
1436
        options = ["V/M", "SQL", "VOL", "POW", "CDT", "REV", "SCN", "CAL",
1437
                   "TALK", "BND", "SFT", "MON", "DIR", "TRF", "RDW"]
1438

    
1439
        if self.HAS_VOX:
1440
            options.insert(15, "VOX")
1441

    
1442
        # PA
1443
        rs = RadioSettingValueList(options, options[_settings.keyPA - 2])
1444
        rset = RadioSetting("settings.keyPA",
1445
                            "Key PA", rs)
1446
        pfkeys.append(rset)
1447

    
1448
        # PB
1449
        rs = RadioSettingValueList(options, options[_settings.keyPB - 2])
1450
        rset = RadioSetting("settings.keyPB",
1451
                            "Key PB", rs)
1452
        pfkeys.append(rset)
1453

    
1454
        # PC
1455
        rs = RadioSettingValueList(options, options[_settings.keyPC - 2])
1456
        rset = RadioSetting("settings.keyPC",
1457
                            "Key PC", rs)
1458
        pfkeys.append(rset)
1459

    
1460
        # PD
1461
        rs = RadioSettingValueList(options, options[_settings.keyPD - 2])
1462
        rset = RadioSetting("settings.keyPD",
1463
                            "Key PD", rs)
1464
        pfkeys.append(rset)
1465

    
1466
        # DTMF
1467
        dtmf = RadioSettingGroup("dtmf", "DTMF")
1468
        group.append(dtmf)
1469

    
1470
        # DTMF Transmitting Time
1471
        options = ["50 milliseconds", "100 milliseconds", "200 milliseconds",
1472
                   "300 milliseconds", "500 milliseconds"]
1473
        rs = RadioSettingValueList(options, options[_settings.dtmfTxTime])
1474
        rset = RadioSetting("settings.dtmfTxTime",
1475
                            "DTMF transmitting time", rs)
1476
        dtmf.append(rset)
1477

    
1478
        # DTMF Self ID
1479

    
1480
        # DTMF Interval Character
1481
        IC_CHOICES = ["A", "B", "C", "D", "*", "#"]
1482
        IC_VALUES = [0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]
1483

    
1484
        def apply_ic_listvalue(setting, obj):
1485
            LOG.debug("Setting value: " + str(setting.value) + " from list")
1486
            val = str(setting.value)
1487
            index = IC_CHOICES.index(val)
1488
            val = IC_VALUES[index]
1489
            obj.set_value(val)
1490

    
1491
        if _dtmf.intervalChar in IC_VALUES:
1492
            idx = IC_VALUES.index(_dtmf.intervalChar)
1493
        else:
1494
            idx = IC_VALUES.index(0x0E)
1495
        rs = RadioSetting("dtmf.intervalChar", "DTMF interval character",
1496
                          RadioSettingValueList(IC_CHOICES,
1497
                                                IC_CHOICES[idx]))
1498
        rs.set_apply_callback(apply_ic_listvalue, _dtmf.intervalChar)
1499
        dtmf.append(rs)
1500

    
1501
        # Group Code
1502
        GC_CHOICES = ["Off", "A", "B", "C", "D", "*", "#"]
1503
        GC_VALUES = [0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]
1504

    
1505
        def apply_gc_listvalue(setting, obj):
1506
            LOG.debug("Setting value: " + str(setting.value) + " from list")
1507
            val = str(setting.value)
1508
            index = GC_CHOICES.index(val)
1509
            val = GC_VALUES[index]
1510
            obj.set_value(val)
1511

    
1512
        if _dtmf.groupCode in GC_VALUES:
1513
            idx = GC_VALUES.index(_dtmf.groupCode)
1514
        else:
1515
            idx = GC_VALUES.index(0x0A)
1516
        rs = RadioSetting("dtmf.groupCode", "DTMF interval character",
1517
                          RadioSettingValueList(GC_CHOICES,
1518
                                                GC_CHOICES[idx]))
1519
        rs.set_apply_callback(apply_gc_listvalue, _dtmf.groupCode)
1520
        dtmf.append(rs)
1521

    
1522
        # Decoding Response
1523
        options = ["None", "Beep tone", "Beep tone & respond"]
1524
        rs = RadioSettingValueList(options, options[_dtmf.decodingResponse])
1525
        rset = RadioSetting("dtmf.decodingResponse", "Decoding response", rs)
1526
        dtmf.append(rset)
1527

    
1528
        # First Digit Time
1529
        options = ["%s" % x for x in range(0, 2510, 10)]
1530
        rs = RadioSettingValueList(options, options[_dtmf.firstDigitTime])
1531
        rset = RadioSetting("dtmf.firstDigitTime", "First Digit Time(ms)", rs)
1532
        dtmf.append(rset)
1533

    
1534
        # First Digit Time
1535
        options = ["%s" % x for x in range(10, 2510, 10)]
1536
        rs = RadioSettingValueList(options, options[_dtmf.pretime - 1])
1537
        rset = RadioSetting("dtmf.pretime", "Pretime(ms)", rs)
1538
        dtmf.append(rset)
1539

    
1540
        # Auto Reset Time
1541
        options = ["%s" % x for x in range(0, 25100, 100)]
1542
        rs = RadioSettingValueList(options, options[_dtmf.autoResetTime])
1543
        rset = RadioSetting("dtmf.autoResetTime", "Auto Reset time(ms)", rs)
1544
        dtmf.append(rset)
1545

    
1546
        # Time-Lapse After Encode
1547
        options = ["%s" % x for x in range(10, 2510, 10)]
1548
        rs = RadioSettingValueList(options, options[_dtmf.timeLapse - 1])
1549
        rset = RadioSetting("dtmf.timeLapse",
1550
                            "Time-lapse after encode(ms)", rs)
1551
        dtmf.append(rset)
1552

    
1553
        # PTT ID Pause Time
1554
        options = ["Off", "-", "-", "-", "-"] + [
1555
                   "%s" % x for x in range(5, 76)]
1556
        rs = RadioSettingValueList(options, options[_dtmf.pauseTime])
1557
        rset = RadioSetting("dtmf.pauseTime", "PTT ID pause time(s)", rs)
1558
        dtmf.append(rset)
1559

    
1560
        # Side Tone
1561
        rs = RadioSettingValueBoolean(_dtmf.sideTone)
1562
        rset = RadioSetting("dtmf.sideTone", "Side tone", rs)
1563
        dtmf.append(rset)
1564

    
1565
        # PTT ID Starting
1566
        DTMF_CHARS = "0123456789ABCD*# "
1567
        _codeobj = _dtmf.pttIdStart
1568
        _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
1569
        val = RadioSettingValueString(0, 16, _code, False)
1570
        val.set_charset(DTMF_CHARS)
1571
        rs = RadioSetting("dtmf.pttIdStart", "PTT ID starting", val)
1572

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

    
1584
        # PTT ID Ending
1585
        _codeobj = _dtmf.pttIdEnd
1586
        _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
1587
        val = RadioSettingValueString(0, 16, _code, False)
1588
        val.set_charset(DTMF_CHARS)
1589
        rs = RadioSetting("dtmf.pttIdEnd", "PTT ID ending", val)
1590

    
1591
        def apply_code(setting, obj):
1592
            code = []
1593
            for j in range(0, 16):
1594
                try:
1595
                    code.append(DTMF_CHARS.index(str(setting.value)[j]))
1596
                except IndexError:
1597
                    code.append(0xFF)
1598
            obj.pttIdEnd = code
1599
        rs.set_apply_callback(apply_code, _dtmf)
1600
        dtmf.append(rs)
1601

    
1602
        # Remotely Kill
1603
        _codeobj = _dtmf.remoteKill
1604
        _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
1605
        val = RadioSettingValueString(0, 16, _code, False)
1606
        val.set_charset(DTMF_CHARS)
1607
        rs = RadioSetting("dtmf.remoteKill", "Remotely kill", val)
1608

    
1609
        def apply_code(setting, obj):
1610
            code = []
1611
            for j in range(0, 16):
1612
                try:
1613
                    code.append(DTMF_CHARS.index(str(setting.value)[j]))
1614
                except IndexError:
1615
                    code.append(0xFF)
1616
            obj.remoteKill = code
1617
        rs.set_apply_callback(apply_code, _dtmf)
1618
        dtmf.append(rs)
1619

    
1620
        # Remotely Stun
1621
        _codeobj = _dtmf.remoteStun
1622
        _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
1623
        val = RadioSettingValueString(0, 16, _code, False)
1624
        val.set_charset(DTMF_CHARS)
1625
        rs = RadioSetting("dtmf.remoteStun", "Remotely stun", val)
1626

    
1627
        def apply_code(setting, obj):
1628
            code = []
1629
            for j in range(0, 16):
1630
                try:
1631
                    code.append(DTMF_CHARS.index(str(setting.value)[j]))
1632
                except IndexError:
1633
                    code.append(0xFF)
1634
            obj.remoteStun = code
1635
        rs.set_apply_callback(apply_code, _dtmf)
1636
        dtmf.append(rs)
1637

    
1638
        # DTMF Encode
1639
        # M1 - M16
1640
        for i in range(0, 16):
1641
            _codeobj = self._memobj.pttid[i].code
1642
            _code = "".join([DTMF_CHARS[x] for x in _codeobj if int(x) < 0x1F])
1643
            val = RadioSettingValueString(0, 16, _code, False)
1644
            val.set_charset(DTMF_CHARS)
1645
            rs = RadioSetting("pttid/%i.code" % i,
1646
                              "DTMF encode M%i" % (i + 1), val)
1647

    
1648
            def apply_code(setting, obj):
1649
                code = []
1650
                for j in range(0, 16):
1651
                    try:
1652
                        code.append(DTMF_CHARS.index(str(setting.value)[j]))
1653
                    except IndexError:
1654
                        code.append(0xFF)
1655
                obj.code = code
1656
            rs.set_apply_callback(apply_code, self._memobj.pttid[i])
1657
            dtmf.append(rs)
1658

    
1659
        return group
1660

    
1661
    def set_settings(self, settings):
1662
        _settings = self._memobj.settings
1663
        _mem = self._memobj
1664
        for element in settings:
1665
            if not isinstance(element, RadioSetting):
1666
                self.set_settings(element)
1667
                continue
1668
            else:
1669
                try:
1670
                    name = element.get_name()
1671
                    if "." in name:
1672
                        bits = name.split(".")
1673
                        obj = self._memobj
1674
                        for bit in bits[:-1]:
1675
                            if "/" in bit:
1676
                                bit, index = bit.split("/", 1)
1677
                                index = int(index)
1678
                                obj = getattr(obj, bit)[index]
1679
                            else:
1680
                                obj = getattr(obj, bit)
1681
                        setting = bits[-1]
1682
                    else:
1683
                        obj = _settings
1684
                        setting = element.get_name()
1685

    
1686
                    if element.has_apply_callback():
1687
                        LOG.debug("Using apply callback")
1688
                        element.run_apply_callback()
1689
                    elif setting == "timeLapse":
1690
                        setattr(obj, setting, int(element.value) + 1)
1691
                    elif setting == "pretime":
1692
                        setattr(obj, setting, int(element.value) + 1)
1693
                    elif setting == "backlightBr":
1694
                        setattr(obj, setting, int(element.value) + 1)
1695
                    elif setting == "micKeyBrite":
1696
                        setattr(obj, setting, int(element.value) + 1)
1697
                    elif setting == "speakerVol":
1698
                        setattr(obj, setting, int(element.value) + 1)
1699
                    elif "keyMode" in setting:
1700
                        setattr(obj, setting, int(element.value) + 1)
1701
                    elif "keyP" in setting:
1702
                        setattr(obj, setting, int(element.value) + 2)
1703
                    elif element.value.get_mutable():
1704
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1705
                        setattr(obj, setting, element.value)
1706
                except Exception, e:
1707
                    LOG.debug(element.get_name())
1708
                    raise
1709

    
1710
# Original non-VOX models
1711
if has_future:
1712
    @directory.register
1713
    class AnyTone778UV(AnyTone778UVBase):
1714
        VENDOR = "AnyTone"
1715
        MODEL = "778UV"
1716
        # Allowed radio types is a dict keyed by model of a list of version
1717
        # strings
1718
        ALLOWED_RADIO_TYPES = {'AT778UV': ['V100', 'V200']}
1719

    
1720
    @directory.register
1721
    class RetevisRT95(AnyTone778UVBase):
1722
        VENDOR = "Retevis"
1723
        MODEL = "RT95"
1724
        # Allowed radio types is a dict keyed by model of a list of version
1725
        # strings
1726
        ALLOWED_RADIO_TYPES = {'RT95': ['V100']}
1727

    
1728
    @directory.register
1729
    class CRTMicronUV(AnyTone778UVBase):
1730
        VENDOR = "CRT"
1731
        MODEL = "Micron UV"
1732
        # Allowed radio types is a dict keyed by model of a list of version
1733
        # strings
1734
        ALLOWED_RADIO_TYPES = {'MICRON': ['V100']}
1735

    
1736
    @directory.register
1737
    class MidlandDBR2500(AnyTone778UVBase):
1738
        VENDOR = "Midland"
1739
        MODEL = "DBR2500"
1740
        # Allowed radio types is a dict keyed by model of a list of version
1741
        # strings
1742
        ALLOWED_RADIO_TYPES = {'DBR2500': ['V100']}
1743

    
1744
    @directory.register
1745
    class YedroYCM04vus(AnyTone778UVBase):
1746
        VENDOR = "Yedro"
1747
        MODEL = "YC-M04VUS"
1748
        # Allowed radio types is a dict keyed by model of a list of version
1749
        # strings
1750
        ALLOWED_RADIO_TYPES = {'YCM04UV': ['V100']}
1751

    
1752

    
1753
class AnyTone778UVvoxBase(AnyTone778UVBase):
1754
    '''AnyTone 778UV VOX, Retivis RT95 VOX and others'''
1755
    NAME_LENGTH = 6
1756
    HAS_VOX = True
1757

    
1758
# New VOX models
1759
if has_future:
1760
    @directory.register
1761
    class AnyTone778UVvox(AnyTone778UVvoxBase):
1762
        VENDOR = "AnyTone"
1763
        MODEL = "778UV VOX"
1764
        #MODEL = "778UV-P"
1765
        # Allowed radio types is a dict keyed by model of a list of version
1766
        # strings
1767
        ALLOWED_RADIO_TYPES = {'778UV-P': ['V100']}
1768

    
1769
    @directory.register
1770
    class RetevisRT95vox(AnyTone778UVvoxBase):
1771
        VENDOR = "Retevis"
1772
        MODEL = "RT95 VOX"
1773
        #MODEL = "RT95-P"
1774
        # Allowed radio types is a dict keyed by model of a list of version
1775
        # strings
1776
        ALLOWED_RADIO_TYPES = {'RT95-P': ['V100']}
(16-16/16)