Project

General

Profile

New Model #9185 » anytone778uv(crt_micronuv_v2).py

Jim Unroe, 07/05/2021 04:42 AM

 
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
  char name[6];           // the VOX models have 6-character names
110
                          // the original models only have 5-character names
111
                          // the 1st byte is not used and will always be 0x00
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
            if self.NAME_LENGTH == 5:
734
                # original models with 5-character name length
735
                temp_name = str(_mem.name)
736
                # Strip the first character and set the alpha tag
737
                mem.name = str(temp_name[1:6]).rstrip()
738
            else:
739
                # new VOX models with 6-character name length
740
                mem.name = str(_mem.name).rstrip()  # Set the alpha tag
741

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
911
        return mem
912

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

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

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

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

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

    
939
            # Store the alpha tag
940
            if self.NAME_LENGTH == 5:
941
                # original models with 5-character name length
942
                temp_name = mem.name.ljust(self.NAME_LENGTH)[:self.NAME_LENGTH]
943
                # prefix the 5-character name with 0x00 to fit structure
944
                _mem.name = temp_name.rjust(6, chr(00))
945
            else:
946
                # new VOX models with 6-character name length
947
                _mem.name = mem.name.ljust(self.NAME_LENGTH)[:self.NAME_LENGTH]
948

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

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

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

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

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

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

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

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

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

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

    
1074
            # set unknown defaults, based on reading memory set by vendor tool
1075
            _mem.unknown1 = 0x00
1076
            _mem.unknown6 = 0x00
1077
            _mem.unknown7 = 0x00
1078
            _mem.unknown8 = 0x00
1079
            _mem.unknown9 = 0x00
1080

    
1081
    def get_settings(self):
1082
        """Translate the MEM_FORMAT structs into setstuf in the UI"""
1083
        _settings = self._memobj.settings
1084
        _radio_settings = self._memobj.radio_settings
1085
        _password = self._memobj.password
1086
        _pfkeys = self._memobj.pfkeys
1087
        _dtmf = self._memobj.dtmf
1088

    
1089
        # Function Setup
1090
        function = RadioSettingGroup("function", "Function Setup")
1091
        group = RadioSettings(function)
1092

    
1093
        # MODE SET
1094
        # Channel Locked
1095
        rs = RadioSettingValueBoolean(_settings.channelLocked)
1096
        rset = RadioSetting("settings.channelLocked", "Channel locked", rs)
1097
        function.append(rset)
1098

    
1099
        # Menu 3 - Display Mode
1100
        options = ["Frequency", "Channel", "Name"]
1101
        rs = RadioSettingValueList(options, options[_settings.displayMode])
1102
        rset = RadioSetting("settings.displayMode", "Display Mode", rs)
1103
        function.append(rset)
1104

    
1105
        # VFO/MR A
1106
        options = ["MR", "VFO"]
1107
        rs = RadioSettingValueList(options, options[_radio_settings.vfomrA])
1108
        rset = RadioSetting("radio_settings.vfomrA", "VFO/MR mode A", rs)
1109
        function.append(rset)
1110

    
1111
        # MR Channel A
1112
        options = ["%s" % x for x in range(1, 201)]
1113
        rs = RadioSettingValueList(options, options[_radio_settings.mrChanA])
1114
        rset = RadioSetting("radio_settings.mrChanA", "MR channel A", rs)
1115
        function.append(rset)
1116

    
1117
        # VFO/MR B
1118
        options = ["MR", "VFO"]
1119
        rs = RadioSettingValueList(options, options[_radio_settings.vfomrB])
1120
        rset = RadioSetting("radio_settings.vfomrB", "VFO/MR mode B", rs)
1121
        function.append(rset)
1122

    
1123
        # MR Channel B
1124
        options = ["%s" % x for x in range(1, 201)]
1125
        rs = RadioSettingValueList(options, options[_radio_settings.mrChanB])
1126
        rset = RadioSetting("radio_settings.mrChanB", "MR channel B", rs)
1127
        function.append(rset)
1128

    
1129
        # DISPLAY SET
1130
        # Starting Display
1131
        name = ""
1132
        for i in range(7):  # 0 - 7
1133
            name += chr(self._memobj.starting_display.line[i])
1134
        name = name.upper().rstrip()  # remove trailing spaces
1135

    
1136
        rs = RadioSettingValueString(0, 7, name)
1137
        rs.set_charset(chirp_common.CHARSET_ALPHANUMERIC)
1138
        rset = RadioSetting("starting_display.line", "Starting display", rs)
1139
        function.append(rset)
1140

    
1141
        # Menu 11 - Backlight Brightness
1142
        options = ["%s" % x for x in range(1, 4)]
1143
        rs = RadioSettingValueList(options, options[_settings.backlightBr - 1])
1144
        rset = RadioSetting("settings.backlightBr", "Backlight brightness", rs)
1145
        function.append(rset)
1146

    
1147
        # Menu 15 - Screen Direction
1148
        options = ["Positive", "Inverted"]
1149
        rs = RadioSettingValueList(options, options[_settings.screenDir])
1150
        rset = RadioSetting("settings.screenDir", "Screen direction", rs)
1151
        function.append(rset)
1152

    
1153
        # Hand Mic Key Brightness
1154
        options = ["%s" % x for x in range(1, 32)]
1155
        rs = RadioSettingValueList(options, options[_settings.micKeyBrite - 1])
1156
        rset = RadioSetting("settings.micKeyBrite",
1157
                            "Hand mic key brightness", rs)
1158
        function.append(rset)
1159

    
1160
        # VOL SET
1161
        # Menu 1 - Beep Volume
1162
        options = ["OFF"] + ["%s" % x for x in range(1, 6)]
1163
        rs = RadioSettingValueList(options, options[_settings.beepVolume])
1164
        rset = RadioSetting("settings.beepVolume", "Beep volume", rs)
1165
        function.append(rset)
1166

    
1167
        # Menu 5 - Volume level Setup
1168
        options = ["%s" % x for x in range(1, 37)]
1169
        rs = RadioSettingValueList(options, options[_settings.speakerVol - 1])
1170
        rset = RadioSetting("settings.speakerVol", "Speaker volume", rs)
1171
        function.append(rset)
1172

    
1173
        # Menu 16 - Speaker Switch
1174
        options = ["Host on | Hand mic off", "Host on | Hand mic on",
1175
                   "Host off | Hand mic on"]
1176
        rs = RadioSettingValueList(options, options[_settings.speakerSwitch])
1177
        rset = RadioSetting("settings.speakerSwitch", "Speaker switch", rs)
1178
        function.append(rset)
1179

    
1180
        # STE SET
1181
        # STE Frequency
1182
        options = ["Off", "55.2 Hz", "259.2 Hz"]
1183
        rs = RadioSettingValueList(options, options[_settings.steFrequency])
1184
        rset = RadioSetting("settings.steFrequency", "STE frequency", rs)
1185
        function.append(rset)
1186

    
1187
        # STE Type
1188
        options = ["Off", "Silent", "120 degrees", "180 degrees",
1189
                   "240 degrees"]
1190
        rs = RadioSettingValueList(options, options[_settings.steType])
1191
        rset = RadioSetting("settings.steType", "STE type", rs)
1192
        function.append(rset)
1193

    
1194
        # ON/OFF SET
1195
        # The Power-on Password feature is not available on models with VOX
1196
        if not self.HAS_VOX:
1197
            # Power-on Password
1198
            rs = RadioSettingValueBoolean(_settings.powerOnPasswd)
1199
            rset = RadioSetting("settings.powerOnPasswd", "Power-on Password",
1200
                                rs)
1201
            function.append(rset)
1202

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

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

    
1225
            sx = _char_to_str(_password.digits).strip()
1226
            rx = RadioSettingValueString(0, 6, sx)
1227
            sx = "Password (numerals 0-9)"
1228
            rset = RadioSetting("password.digits", sx, rx)
1229
            rset.set_apply_callback(_pswd_vfy, _password, "digits")
1230
            function.append(rset)
1231

    
1232
        # Menu 9 - Auto Power On
1233
        rs = RadioSettingValueBoolean(_settings.autoPowerOn)
1234
        rset = RadioSetting("settings.autoPowerOn", "Auto power on", rs)
1235
        function.append(rset)
1236

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

    
1243
        # Power On Reset Enable
1244
        rs = RadioSettingValueBoolean(_settings.powerOnReset)
1245
        rset = RadioSetting("settings.powerOnReset", "Power on reset", rs)
1246
        function.append(rset)
1247

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

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

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

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

    
1274
        # Main
1275
        options = ["A", "B"]
1276
        rs = RadioSettingValueList(options, options[_settings.main])
1277
        rset = RadioSetting("settings.main", "Main", rs)
1278
        function.append(rset)
1279

    
1280
        # Menu 10 - Dual Watch (RX Way Select)
1281
        rs = RadioSettingValueBoolean(_settings.dualWatch)
1282
        rset = RadioSetting("settings.dualWatch", "Dual watch", rs)
1283
        function.append(rset)
1284

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

    
1291
        # TBST Frequency
1292
        options = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"]
1293
        rs = RadioSettingValueList(options, options[_settings.tbstFrequency])
1294
        rset = RadioSetting("settings.tbstFrequency", "TBST frequency", rs)
1295
        function.append(rset)
1296

    
1297
        # Save Channel Perameter
1298
        rs = RadioSettingValueBoolean(_settings.saveChParameter)
1299
        rset = RadioSetting("settings.saveChParameter",
1300
                            "Save channel parameter", rs)
1301
        function.append(rset)
1302

    
1303
        # MON Key Function
1304
        options = ["Squelch off momentary", "Squelch off"]
1305
        rs = RadioSettingValueList(options, options[_settings.monKeyFunction])
1306
        rset = RadioSetting("settings.monKeyFunction", "MON key function", rs)
1307
        function.append(rset)
1308

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

    
1316
        # Knob Mode
1317
        options = ["Volume", "Channel"]
1318
        rs = RadioSettingValueList(options, options[_settings.knobMode])
1319
        rset = RadioSetting("settings.knobMode", "Knob mode", rs)
1320
        function.append(rset)
1321

    
1322
        # TRF Enable
1323
        rs = RadioSettingValueBoolean(_settings.trfEnable)
1324
        rset = RadioSetting("settings.trfEnable", "TRF enable", rs)
1325
        function.append(rset)
1326

    
1327
        if self.HAS_VOX:
1328
            # VOX On/Off
1329
            rs = RadioSettingValueBoolean(_settings.voxOnOff)
1330
            rset = RadioSetting("settings.voxOnOff",
1331
                                "VOX", rs)
1332
            function.append(rset)
1333

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

    
1341
            # VOX Level
1342
            options = ["%s" % x for x in range(1, 10)]
1343
            rs = RadioSettingValueList(options, options[_settings.voxLevel])
1344
            rset = RadioSetting("settings.voxLevel", "VOX Level", rs)
1345
            function.append(rset)
1346

    
1347
        # Key Assignment
1348
        pfkeys = RadioSettingGroup("pfkeys", "Key Assignment")
1349
        group.append(pfkeys)
1350

    
1351
        options = ["A/B", "V/M", "SQL", "VOL", "POW", "CDT", "REV", "SCN",
1352
                   "CAL", "TALK", "BND", "SFT", "MON", "DIR", "TRF", "RDW",
1353
                   "NULL"]
1354

    
1355
        if self.HAS_VOX:
1356
            options.insert(16, "VOX")
1357

    
1358
        # Key Mode 1
1359
        # P1
1360
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P1 - 1])
1361
        rset = RadioSetting("pfkeys.keyMode1P1",
1362
                            "Key mode 1 P1", rs)
1363
        pfkeys.append(rset)
1364

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

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

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

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

    
1389
        # P6
1390
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode1P6 - 1])
1391
        rset = RadioSetting("pfkeys.keyMode1P6",
1392
                            "Key mode 1 P6", rs)
1393
        pfkeys.append(rset)
1394

    
1395
        # Key Mode 2
1396
        # P1
1397
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P1 - 1])
1398
        rset = RadioSetting("pfkeys.keyMode2P1",
1399
                            "Key mode 2 P1", rs)
1400
        pfkeys.append(rset)
1401

    
1402
        # P2
1403
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P2 - 1])
1404
        rset = RadioSetting("pfkeys.keyMode2P2",
1405
                            "Key mode 2 P2", rs)
1406
        pfkeys.append(rset)
1407

    
1408
        # P3
1409
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P3 - 1])
1410
        rset = RadioSetting("pfkeys.keyMode2P3",
1411
                            "Key mode 2 P3", rs)
1412
        pfkeys.append(rset)
1413

    
1414
        # P4
1415
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P4 - 1])
1416
        rset = RadioSetting("pfkeys.keyMode2P4",
1417
                            "Key mode 2 P4", rs)
1418
        pfkeys.append(rset)
1419

    
1420
        # P5
1421
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P5 - 1])
1422
        rset = RadioSetting("pfkeys.keyMode2P5",
1423
                            "Key mode 2 P5", rs)
1424
        pfkeys.append(rset)
1425

    
1426
        # P6
1427
        rs = RadioSettingValueList(options, options[_pfkeys.keyMode2P6 - 1])
1428
        rset = RadioSetting("pfkeys.keyMode2P6",
1429
                            "Key mode 2 P6", rs)
1430
        pfkeys.append(rset)
1431

    
1432
        options = ["V/M", "SQL", "VOL", "POW", "CDT", "REV", "SCN", "CAL",
1433
                   "TALK", "BND", "SFT", "MON", "DIR", "TRF", "RDW"]
1434

    
1435
        if self.HAS_VOX:
1436
            options.insert(15, "VOX")
1437

    
1438
        # PA
1439
        rs = RadioSettingValueList(options, options[_settings.keyPA - 2])
1440
        rset = RadioSetting("settings.keyPA",
1441
                            "Key PA", rs)
1442
        pfkeys.append(rset)
1443

    
1444
        # PB
1445
        rs = RadioSettingValueList(options, options[_settings.keyPB - 2])
1446
        rset = RadioSetting("settings.keyPB",
1447
                            "Key PB", rs)
1448
        pfkeys.append(rset)
1449

    
1450
        # PC
1451
        rs = RadioSettingValueList(options, options[_settings.keyPC - 2])
1452
        rset = RadioSetting("settings.keyPC",
1453
                            "Key PC", rs)
1454
        pfkeys.append(rset)
1455

    
1456
        # PD
1457
        rs = RadioSettingValueList(options, options[_settings.keyPD - 2])
1458
        rset = RadioSetting("settings.keyPD",
1459
                            "Key PD", rs)
1460
        pfkeys.append(rset)
1461

    
1462
        # DTMF
1463
        dtmf = RadioSettingGroup("dtmf", "DTMF")
1464
        group.append(dtmf)
1465

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

    
1474
        # DTMF Self ID
1475

    
1476
        # DTMF Interval Character
1477
        IC_CHOICES = ["A", "B", "C", "D", "*", "#"]
1478
        IC_VALUES = [0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]
1479

    
1480
        def apply_ic_listvalue(setting, obj):
1481
            LOG.debug("Setting value: " + str(setting.value) + " from list")
1482
            val = str(setting.value)
1483
            index = IC_CHOICES.index(val)
1484
            val = IC_VALUES[index]
1485
            obj.set_value(val)
1486

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

    
1497
        # Group Code
1498
        GC_CHOICES = ["Off", "A", "B", "C", "D", "*", "#"]
1499
        GC_VALUES = [0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]
1500

    
1501
        def apply_gc_listvalue(setting, obj):
1502
            LOG.debug("Setting value: " + str(setting.value) + " from list")
1503
            val = str(setting.value)
1504
            index = GC_CHOICES.index(val)
1505
            val = GC_VALUES[index]
1506
            obj.set_value(val)
1507

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

    
1518
        # Decoding Response
1519
        options = ["None", "Beep tone", "Beep tone & respond"]
1520
        rs = RadioSettingValueList(options, options[_dtmf.decodingResponse])
1521
        rset = RadioSetting("dtmf.decodingResponse", "Decoding response", rs)
1522
        dtmf.append(rset)
1523

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

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

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

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

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

    
1556
        # Side Tone
1557
        rs = RadioSettingValueBoolean(_dtmf.sideTone)
1558
        rset = RadioSetting("dtmf.sideTone", "Side tone", rs)
1559
        dtmf.append(rset)
1560

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

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

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

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

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

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

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

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

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

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

    
1655
        return group
1656

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

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

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

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

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

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

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

    
1748

    
1749
class AnyTone778UVvoxBase(AnyTone778UVBase):
1750
    '''AnyTone 778UV VOX, Retivis RT95 VOX and others'''
1751
    NAME_LENGTH = 6
1752
    HAS_VOX = True
1753

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

    
1764
    @directory.register
1765
    class RetevisRT95vox(AnyTone778UVvoxBase):
1766
        VENDOR = "Retevis"
1767
        MODEL = "RT95 VOX"
1768
        # Allowed radio types is a dict keyed by model of a list of version
1769
        # strings
1770
        ALLOWED_RADIO_TYPES = {'RT95-P': ['V100']}
1771

    
1772
    @directory.register
1773
    class CRTMicronUVvox(AnyTone778UVvoxBase):
1774
        VENDOR = "CRT"
1775
        MODEL = "Micron UV V2"
1776
        # Allowed radio types is a dict keyed by model of a list of version
1777
        # strings
1778
        ALLOWED_RADIO_TYPES = {'MICRONP': ['V100']}
(2-2/2)