anytone778uv_function2.py

Jim Unroe, 11/24/2020 05:56 pm

Download (49 kB)

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

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

    
49
import struct
50
import time
51
import logging
52

    
53
LOG = logging.getLogger(__name__)
54

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

    
66

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

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

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

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

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

    
188
#seekto 0x3260;
189
struct {
190
  u8 mrChanA;             // 0x3260 mr channel a
191
  u8 unknown1_0:7,        // 0x3261
192
     vfomrA:1;            //        vfo/mr mode a
193
  u8 unknown2;
194
  u8 unknown3;
195
  u8 unknown4;
196
  u8 unknown5;
197
  u8 unknown6;
198
  u8 mrChanB;             // 0x3267 mr channel b
199
  u8 unknown8_0:4,        // 0x3268
200
     scan_active:1,
201
     unknown8_1:2,
202
     vfomrB:1;            //        vfo/mr mode b
203
  u8 unknown9;
204
  u8 unknowna;
205
  u8 unknownb;
206
  u8 unknownc;
207
  u8 bandlimit;           // 0x326D mode
208
  u8 unknownd;
209
  u8 unknowne;
210
  u8 unknownf;
211
} radio_settings;
212
'''
213

    
214
# Format for the version messages returned by the radio
215
VER_FORMAT = '''
216
u8 hdr;
217
char model[7];
218
u8 bandlimit;
219
char version[6];
220
u8 ack;
221
'''
222

    
223
TXPOWER_LOW = 0x00
224
TXPOWER_MED = 0x01
225
TXPOWER_HIGH = 0x02
226

    
227
DUPLEX_NOSPLIT = 0x00
228
DUPLEX_POSSPLIT = 0x01
229
DUPLEX_NEGSPLIT = 0x02
230
DUPLEX_ODDSPLIT = 0x03
231

    
232
CHANNEL_WIDTH_25kHz = 0x02
233
CHANNEL_WIDTH_20kHz = 0x01
234
CHANNEL_WIDTH_12d5kHz = 0x00
235

    
236
BUSY_CHANNEL_LOCKOUT_OFF = 0x00
237
BUSY_CHANNEL_LOCKOUT_REPEATER = 0x01
238
BUSY_CHANNEL_LOCKOUT_BUSY = 0x02
239

    
240
MEMORY_ADDRESS_RANGE = (0x0000, 0x3290)
241
MEMORY_RW_BLOCK_SIZE = 0x10
242
MEMORY_RW_BLOCK_CMD_SIZE = 0x16
243

    
244
POWER_LEVELS = [chirp_common.PowerLevel('Low', dBm=37),
245
                chirp_common.PowerLevel('Medium', dBm=40),
246
                chirp_common.PowerLevel('High', dBm=44)]
247

    
248
# CTCSS Tone definitions
249
TONE_CUSTOM_CTCSS = 0x33
250
TONE_MAP_VAL_TO_TONE = {0x00: 62.5, 0x01: 67.0, 0x02: 69.3,
251
                        0x03: 71.9, 0x04: 74.4, 0x05: 77.0,
252
                        0x06: 79.7, 0x07: 82.5, 0x08: 85.4,
253
                        0x09: 88.5, 0x0a: 91.5, 0x0b: 94.8,
254
                        0x0c: 97.4, 0x0d: 100.0, 0x0e: 103.5,
255
                        0x0f: 107.2, 0x10: 110.9, 0x11: 114.8,
256
                        0x12: 118.8, 0x13: 123.0, 0x14: 127.3,
257
                        0x15: 131.8, 0x16: 136.5, 0x17: 141.3,
258
                        0x18: 146.2, 0x19: 151.4, 0x1a: 156.7,
259
                        0x1b: 159.8, 0x1c: 162.2, 0x1d: 165.5,
260
                        0x1e: 167.9, 0x1f: 171.3, 0x20: 173.8,
261
                        0x21: 177.3, 0x22: 179.9, 0x23: 183.5,
262
                        0x24: 186.2, 0x25: 189.9, 0x26: 192.8,
263
                        0x27: 196.6, 0x28: 199.5, 0x29: 203.5,
264
                        0x2a: 206.5, 0x2b: 210.7, 0x2c: 218.1,
265
                        0x2d: 225.7, 0x2e: 229.1, 0x2f: 233.6,
266
                        0x30: 241.8, 0x31: 250.3, 0x32: 254.1}
267

    
268
TONE_MAP_TONE_TO_VAL = {TONE_MAP_VAL_TO_TONE[val]: val
269
                        for val in TONE_MAP_VAL_TO_TONE}
270

    
271
TONES_EN_TXTONE = (1 << 3)
272
TONES_EN_RXTONE = (1 << 2)
273
TONES_EN_TXCODE = (1 << 1)
274
TONES_EN_RXCODE = (1 << 0)
275
TONES_EN_NO_TONE = 0
276

    
277
# Radio supports upper case and symbols
278
CHARSET_ASCII_PLUS = chirp_common.CHARSET_UPPER_NUMERIC + '- '
279

    
280
# Band limits as defined by the band byte in ver_response, defined in Hz, for
281
# VHF and UHF, used for RX and TX.
282
BAND_LIMITS = {0x00: [(144000000, 148000000), (430000000, 440000000)],
283
               0x01: [(136000000, 174000000), (400000000, 490000000)],
284
               0x02: [(144000000, 146000000), (430000000, 440000000)]}
285

    
286

    
287
# Get band limits from a band limit value
288
def get_band_limits_Hz(limit_value):
289
    if limit_value not in BAND_LIMITS:
290
        limit_value = 0x01
291
        LOG.warning('Unknown band limit value 0x%02x, default to 0x01')
292
    bandlimitfrequencies = BAND_LIMITS[limit_value]
293
    return bandlimitfrequencies
294

    
295

    
296
# Calculate the checksum used in serial packets
297
def checksum(message_bytes):
298
    mask = 0xFF
299
    checksum = 0
300
    for b in message_bytes:
301
        checksum = (checksum + b) & mask
302
    return checksum
303

    
304

    
305
# Send a command to the radio, return any reply stripping the echo of the
306
# command (tx and rx share a single pin in this radio)
307
def send_serial_command(serial, command, expectedlen=None):
308
    ''' send a command to the radio, and return any response.
309
    set expectedlen to return as soon as that many bytes are read.
310
    '''
311
    serial.write(command)
312
    serial.flush()
313

    
314
    response = b''
315
    tout = time.time() + 0.5
316
    while time.time() < tout:
317
        if serial.inWaiting():
318
            response += serial.read()
319
        # remember everything gets echo'd back
320
        if len(response) - len(command) == expectedlen:
321
            break
322

    
323
    # cut off what got echo'd back, we don't need to see it again
324
    if response.startswith(command):
325
        response = response[len(command):]
326

    
327
    return response
328

    
329

    
330
# strip trailing 0x00 to convert a string returned by bitwise.parse into a
331
# python string
332
def cstring_to_py_string(cstring):
333
    return "".join(c for c in cstring if c != '\x00')
334

    
335

    
336
# Check the radio version reported to see if it's one we support,
337
# returns bool version supported, and the band index
338
def check_ver(ver_response, allowed_types):
339
    ''' Check the returned radio version is one we approve of '''
340

    
341
    LOG.debug('ver_response = ')
342
    LOG.debug(util.hexprint(ver_response))
343

    
344
    resp = bitwise.parse(VER_FORMAT, ver_response)
345
    verok = False
346

    
347
    if resp.hdr == 0x49 and resp.ack == 0x06:
348
        model, version = [cstring_to_py_string(bitwise.get_string(s)).strip()
349
                          for s in (resp.model, resp.version)]
350
        LOG.debug('radio model: \'%s\' version: \'%s\'' %
351
                  (model, version))
352
        LOG.debug('allowed_types = %s' % allowed_types)
353

    
354
        if model in allowed_types:
355
            LOG.debug('model in allowed_types')
356

    
357
            if version in allowed_types[model]:
358
                LOG.debug('version in allowed_types[model]')
359
                verok = True
360
    else:
361
        raise errors.RadioError('Failed to parse version response')
362

    
363
    return verok, int(resp.bandlimit)
364

    
365

    
366
# Put the radio in programming mode, sending the initial command and checking
367
# the response.  raise RadioError if there is no response (500ms timeout), and
368
# if the returned version isn't matched by check_ver
369
def enter_program_mode(radio):
370
    serial = radio.pipe
371
    # place the radio in program mode, and confirm
372
    program_response = send_serial_command(serial, b'PROGRAM')
373

    
374
    if program_response != b'QX\x06':
375
        raise errors.RadioError('No initial response from radio.')
376
    LOG.debug('entered program mode')
377

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

    
381
    verok, bandlimit = check_ver(ver_response, radio.ALLOWED_RADIO_TYPES)
382
    if not verok:
383
        exit_program_mode(radio)
384
        raise errors.RadioError(
385
            'Radio version not in allowed list for %s-%s: %s' %
386
            (radio.VENDOR, radio.MODEL, util.hexprint(ver_response)))
387

    
388
    return bandlimit
389

    
390

    
391
# Exit programming mode
392
def exit_program_mode(radio):
393
    send_serial_command(radio.pipe, b'END')
394

    
395

    
396
# Parse a packet from the radio returning the header (R/W, address, data, and
397
# checksum valid
398
def parse_read_response(resp):
399
    addr = resp[:4]
400
    data = bytes(resp[4:-2])
401
    cs = checksum(ord(d) for d in resp[1:-2])
402
    valid = cs == ord(resp[-2])
403
    if not valid:
404
        LOG.error('checksumfail: %02x, expected %02x' % (cs, ord(resp[-2])))
405
        LOG.error('msg data: %s' % util.hexprint(resp))
406
    return addr, data, valid
407

    
408

    
409
# Download data from the radio and populate the memory map
410
def do_download(radio):
411
    '''Download memories from the radio'''
412

    
413
    # Get the serial port connection
414
    serial = radio.pipe
415

    
416
    try:
417
        enter_program_mode(radio)
418

    
419
        memory_data = bytes()
420

    
421
        # status info for the UI
422
        status = chirp_common.Status()
423
        status.cur = 0
424
        status.max = (MEMORY_ADDRESS_RANGE[1] -
425
                      MEMORY_ADDRESS_RANGE[0])/MEMORY_RW_BLOCK_SIZE
426
        status.msg = 'Cloning from radio...'
427
        radio.status_fn(status)
428

    
429
        for addr in range(MEMORY_ADDRESS_RANGE[0],
430
                          MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
431
                          MEMORY_RW_BLOCK_SIZE):
432
            read_command = struct.pack('>BHB', 0x52, addr,
433
                                       MEMORY_RW_BLOCK_SIZE)
434
            read_response = send_serial_command(serial, read_command,
435
                                                MEMORY_RW_BLOCK_CMD_SIZE)
436
            # LOG.debug('read response:\n%s' % util.hexprint(read_response))
437

    
438
            address, data, valid = parse_read_response(read_response)
439
            memory_data += data
440

    
441
            # update UI
442
            status.cur = (addr - MEMORY_ADDRESS_RANGE[0])\
443
                / MEMORY_RW_BLOCK_SIZE
444
            radio.status_fn(status)
445

    
446
        exit_program_mode(radio)
447
    except errors.RadioError as e:
448
        raise e
449
    except Exception as e:
450
        raise errors.RadioError('Failed to download from radio: %s' % e)
451

    
452
    return memmap.MemoryMapBytes(memory_data)
453

    
454

    
455
# Build a write data command to send to the radio
456
def make_write_data_cmd(addr, data, datalen):
457
    cmd = struct.pack('>BHB', 0x57, addr, datalen)
458
    cmd += data
459
    cs = checksum(ord(c) for c in cmd[1:])
460
    cmd += struct.pack('>BB', cs, 0x06)
461
    return cmd
462

    
463

    
464
# Upload a memory map to the radio
465
def do_upload(radio):
466
    try:
467
        bandlimit = enter_program_mode(radio)
468

    
469
        if bandlimit != radio._memobj.radio_settings.bandlimit:
470
            LOG.warning('radio and image bandlimits differ'
471
                        ' some channels many not work'
472
                        ' (img:0x%02x radio:0x%02x)' %
473
                        (int(bandlimit),
474
                         int(radio._memobj.radio_settings.bandlimit)))
475
            LOG.warning('radio bands: %s' % get_band_limits_Hz(
476
                         int(radio._memobj.radio_settings.bandlimit)))
477
            LOG.warning('img bands: %s' % get_band_limits_Hz(bandlimit))
478

    
479
        serial = radio.pipe
480

    
481
        # send the initial message, radio responds with something that looks a
482
        # bit like a bitfield, but I don't know what it is yet.
483
        read_command = struct.pack('>BHB', 0x52, 0x3b10, MEMORY_RW_BLOCK_SIZE)
484
        read_response = send_serial_command(serial, read_command,
485
                                            MEMORY_RW_BLOCK_CMD_SIZE)
486
        address, data, valid = parse_read_response(read_response)
487
        LOG.debug('Got initial response from radio: %s' %
488
                  util.hexprint(read_response))
489

    
490
        bptr = 0
491

    
492
        memory_addrs = range(MEMORY_ADDRESS_RANGE[0],
493
                             MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
494
                             MEMORY_RW_BLOCK_SIZE)
495

    
496
        # status info for the UI
497
        status = chirp_common.Status()
498
        status.cur = 0
499
        status.max = len(memory_addrs)
500
        status.msg = 'Cloning to radio...'
501
        radio.status_fn(status)
502

    
503
        for idx, addr in enumerate(memory_addrs):
504
            write_command = make_write_data_cmd(
505
                addr, radio._mmap[bptr:bptr+MEMORY_RW_BLOCK_SIZE],
506
                MEMORY_RW_BLOCK_SIZE)
507
            # LOG.debug('write data:\n%s' % util.hexprint(write_command))
508
            write_response = send_serial_command(serial, write_command, 0x01)
509
            bptr += MEMORY_RW_BLOCK_SIZE
510

    
511
            if write_response == '\x0a':
512
                # NACK from radio, e.g. checksum wrongn
513
                LOG.debug('Radio returned 0x0a - NACK:')
514
                LOG.debug(' * write cmd:\n%s' % util.hexprint(write_command))
515
                LOG.debug(' * write response:\n%s' %
516
                          util.hexprint(write_response))
517
                exit_program_mode(radio)
518
                raise errors.RadioError('Radio NACK\'d write command')
519

    
520
            # update UI
521
            status.cur = idx
522
            radio.status_fn(status)
523
        exit_program_mode(radio)
524
    except errors.RadioError:
525
        raise
526
    except Exception as e:
527
        raise errors.RadioError('Failed to download from radio: %s' % e)
528

    
529

    
530
# Get the value of @bitfield @number of bits in from 0
531
def get_bitfield(bitfield, number):
532
    ''' Get the value of @bitfield @number of bits in '''
533
    byteidx = number//8
534
    bitidx = number - (byteidx * 8)
535
    return bitfield[byteidx] & (1 << bitidx)
536

    
537

    
538
# Set the @value of @bitfield @number of bits in from 0
539
def set_bitfield(bitfield, number, value):
540
    ''' Set the @value of @bitfield @number of bits in '''
541
    byteidx = number//8
542
    bitidx = number - (byteidx * 8)
543
    if value is True:
544
        bitfield[byteidx] |= (1 << bitidx)
545
    else:
546
        bitfield[byteidx] &= ~(1 << bitidx)
547
    return bitfield
548

    
549

    
550
# Translate the radio's version of a code as stored to a real code
551
def dtcs_code_bits_to_val(highbit, lowbyte):
552
    return chirp_common.ALL_DTCS_CODES[highbit*256 + lowbyte]
553

    
554

    
555
# Translate the radio's version of a tone as stored to a real tone
556
def ctcss_tone_bits_to_val(tone_byte):
557
    # TODO use the custom setting 0x33 and ref the custom ctcss
558
    # field
559
    tone_byte = int(tone_byte)
560
    if tone_byte in TONE_MAP_VAL_TO_TONE:
561
        return TONE_MAP_VAL_TO_TONE[tone_byte]
562
    elif tone_byte == TONE_CUSTOM_CTCSS:
563
        LOG.info('custom ctcss not implemented (yet?).')
564
    else:
565
        raise errors.UnsupportedToneError('unknown ctcss tone value: %02x' %
566
                                          tone_byte)
567

    
568

    
569
# Translate a real tone to the radio's version as stored
570
def ctcss_code_val_to_bits(tone_value):
571
    if tone_value in TONE_MAP_TONE_TO_VAL:
572
        return TONE_MAP_TONE_TO_VAL[tone_value]
573
    else:
574
        raise errors.UnsupportedToneError('Tone %f not supported' % tone_value)
575

    
576

    
577
# Translate a real code to the radio's version as stored
578
def dtcs_code_val_to_bits(code):
579
    val = chirp_common.ALL_DTCS_CODES.index(code)
580
    return (val & 0xFF), ((val >> 8) & 0x01)
581

    
582

    
583
class AnyTone778UVBase(chirp_common.CloneModeRadio,
584
                       chirp_common.ExperimentalRadio):
585
    '''AnyTone 778UV and probably Retivis RT95 and others'''
586
    BAUD_RATE = 9600
587
    NEEDS_COMPAT_SERIAL = False
588

    
589
    @classmethod
590
    def get_prompts(cls):
591
        rp = chirp_common.RadioPrompts()
592

    
593
        rp.experimental = \
594
            ('This is experimental support for the %s %s.  '
595
             'Please send in bug and enhancement requests!' %
596
             (cls.VENDOR, cls.MODEL))
597

    
598
        return rp
599

    
600
    # Return information about this radio's features, including
601
    # how many memories it has, what bands it supports, etc
602
    def get_features(self):
603
        rf = chirp_common.RadioFeatures()
604
        rf.has_bank = False
605
        rf.has_settings = True
606
        rf.can_odd_split = True
607
        rf.has_name = True
608
        rf.has_offset = True
609
        rf.valid_name_length = 5
610
        rf.valid_duplexes = ['', '+', '-', 'split', 'off']
611
        rf.valid_characters = CHARSET_ASCII_PLUS
612

    
613
        rf.has_dtcs = True
614
        rf.has_rx_dtcs = True
615
        rf.has_dtcs_polarity = True
616
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES
617
        rf.has_ctone = True
618
        rf.has_cross = True
619
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
620
        rf.valid_cross_modes = ['Tone->Tone',
621
                                'Tone->DTCS',
622
                                'DTCS->Tone',
623
                                'DTCS->DTCS',
624
                                'DTCS->',
625
                                '->DTCS',
626
                                '->Tone']
627

    
628
        rf.memory_bounds = (1, 200)  # This radio supports memories 1-200
629
        try:
630
            rf.valid_bands = get_band_limits_Hz(
631
                int(self._memobj.radio_settings.bandlimit))
632
        except TypeError as e:
633
            # If we're asked without memory loaded, assume the most permissive
634
            rf.valid_bands = get_band_limits_Hz(1)
635
        except Exception as e:
636
            LOG.error('Failed to get band limits for anytone778uv: %s' % e)
637
            rf.valid_bands = get_band_limits_Hz(1)
638
        rf.valid_modes = ['FM', 'NFM']
639
        rf.valid_power_levels = POWER_LEVELS
640
        rf.valid_tuning_steps = [2.5, 5, 6.25, 10, 12.5, 20, 25, 30, 50]
641
        rf.has_tuning_step = False
642
        return rf
643

    
644
    # Do a download of the radio from the serial port
645
    def sync_in(self):
646
        self._mmap = do_download(self)
647
        self.process_mmap()
648

    
649
    # Do an upload of the radio to the serial port
650
    def sync_out(self):
651
        do_upload(self)
652

    
653
    # Convert the raw byte array into a memory object structure
654
    def process_mmap(self):
655
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
656

    
657
    # Return a raw representation of the memory object, which
658
    # is very helpful for development
659
    def get_raw_memory(self, number):
660
        return repr(self._memobj.memory[number - 1])
661

    
662
    # Extract a high-level memory object from the low-level memory map
663
    # This is called to populate a memory in the UI
664
    def get_memory(self, number):
665
        number -= 1
666
        # Get a low-level memory object mapped to the image
667
        _mem = self._memobj.memory[number]
668
        _mem_status = self._memobj.memory_status
669

    
670
        # Create a high-level memory object to return to the UI
671
        mem = chirp_common.Memory()
672
        mem.number = number + 1           # Set the memory number
673

    
674
        # Check if this memory is present in the occupied list
675
        mem.empty = get_bitfield(_mem_status.occupied_bitfield, number) == 0
676

    
677
        if not mem.empty:
678
            # Check if this memory is in the scan enabled list
679
            mem.skip = ''
680
            if get_bitfield(_mem_status.scan_enabled_bitfield, number) == 0:
681
                mem.skip = 'S'
682

    
683
            # set the name
684
            mem.name = str(_mem.name).rstrip()  # Set the alpha tag
685

    
686
            # Convert your low-level frequency and offset to Hertz
687
            mem.freq = int(_mem.freq) * 10
688
            mem.offset = int(_mem.offset) * 10
689

    
690
            # Set the duplex flags
691
            if _mem.duplex == DUPLEX_POSSPLIT:
692
                mem.duplex = '+'
693
            elif _mem.duplex == DUPLEX_NEGSPLIT:
694
                mem.duplex = '-'
695
            elif _mem.duplex == DUPLEX_NOSPLIT:
696
                mem.duplex = ''
697
            elif _mem.duplex == DUPLEX_ODDSPLIT:
698
                mem.duplex = 'split'
699
            else:
700
                LOG.error('%s: get_mem: unhandled duplex: %02x' %
701
                          (mem.name, _mem.duplex))
702

    
703
            # handle tx off
704
            if _mem.tx_off:
705
                mem.duplex = 'off'
706

    
707
            # Set the channel width
708
            if _mem.channel_width == CHANNEL_WIDTH_25kHz:
709
                mem.mode = 'FM'
710
            elif _mem.channel_width == CHANNEL_WIDTH_20kHz:
711
                LOG.info(
712
                    '%s: get_mem: promoting 20kHz channel width to 25kHz' %
713
                    mem.name)
714
                mem.mode = 'FM'
715
            elif _mem.channel_width == CHANNEL_WIDTH_12d5kHz:
716
                mem.mode = 'NFM'
717
            else:
718
                LOG.error('%s: get_mem: unhandled channel width: 0x%02x' %
719
                          (mem.name, _mem.channel_width))
720

    
721
            # set the power level
722
            if _mem.txpower == TXPOWER_LOW:
723
                mem.power = POWER_LEVELS[0]
724
            elif _mem.txpower == TXPOWER_MED:
725
                mem.power = POWER_LEVELS[1]
726
            elif _mem.txpower == TXPOWER_HIGH:
727
                mem.power = POWER_LEVELS[2]
728
            else:
729
                LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
730
                          (mem.name, _mem.txpower))
731

    
732
            # CTCSS Tones
733
            # TODO support custom ctcss tones here
734
            txtone = None
735
            rxtone = None
736
            rxcode = None
737
            txcode = None
738

    
739
            # check if dtcs tx is enabled
740
            if _mem.dtcs_encode_en:
741
                txcode = dtcs_code_bits_to_val(_mem.dtcs_encode_code_highbit,
742
                                               _mem.dtcs_encode_code)
743

    
744
            # check if dtcs rx is enabled
745
            if _mem.dtcs_decode_en:
746
                rxcode = dtcs_code_bits_to_val(_mem.dtcs_decode_code_highbit,
747
                                               _mem.dtcs_decode_code)
748

    
749
            if txcode is not None:
750
                LOG.debug('%s: get_mem dtcs_enc: %d' % (mem.name, txcode))
751
            if rxcode is not None:
752
                LOG.debug('%s: get_mem dtcs_dec: %d' % (mem.name, rxcode))
753

    
754
            # tsql set if radio squelches on tone
755
            tsql = _mem.tone_squelch_en
756

    
757
            # check if ctcss tx is enabled
758
            if _mem.ctcss_encode_en:
759
                txtone = ctcss_tone_bits_to_val(_mem.ctcss_enc_tone)
760

    
761
            # check if ctcss rx is enabled
762
            if _mem.ctcss_decode_en:
763
                rxtone = ctcss_tone_bits_to_val(_mem.ctcss_dec_tone)
764

    
765
            # Define this here to allow a readable if-else tree enabling tone
766
            # options
767
            enabled = 0
768
            enabled |= (txtone is not None) * TONES_EN_TXTONE
769
            enabled |= (rxtone is not None) * TONES_EN_RXTONE
770
            enabled |= (txcode is not None) * TONES_EN_TXCODE
771
            enabled |= (rxcode is not None) * TONES_EN_RXCODE
772

    
773
            # Add some debugging output for the tone bitmap
774
            enstr = []
775
            if enabled & TONES_EN_TXTONE:
776
                enstr += ['TONES_EN_TXTONE']
777
            if enabled & TONES_EN_RXTONE:
778
                enstr += ['TONES_EN_RXTONE']
779
            if enabled & TONES_EN_TXCODE:
780
                enstr += ['TONES_EN_TXCODE']
781
            if enabled & TONES_EN_RXCODE:
782
                enstr += ['TONES_EN_RXCODE']
783
            if enabled == 0:
784
                enstr = ['TONES_EN_NOTONE']
785
            LOG.debug('%s: enabled = %s' % (
786
                mem.name, '|'.join(enstr)))
787

    
788
            mem.tmode = ''
789
            if enabled == TONES_EN_NO_TONE:
790
                mem.tmode = ''
791
            elif enabled == TONES_EN_TXTONE:
792
                mem.tmode = 'Tone'
793
                mem.rtone = txtone
794
            elif enabled == TONES_EN_RXTONE and tsql:
795
                mem.tmode = 'Cross'
796
                mem.cross_mode = '->Tone'
797
                mem.ctone = rxtone
798
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXTONE) and tsql:
799
                if txtone == rxtone:  # TSQL
800
                    mem.tmode = 'TSQL'
801
                    mem.ctone = txtone
802
                else:  # Tone->Tone
803
                    mem.tmode = 'Cross'
804
                    mem.cross_mode = 'Tone->Tone'
805
                    mem.ctone = rxtone
806
                    mem.rtone = txtone
807
            elif enabled == TONES_EN_TXCODE:
808
                mem.tmode = 'Cross'
809
                mem.cross_mode = 'DTCS->'
810
                mem.dtcs = txcode
811
            elif enabled == TONES_EN_RXCODE and tsql:
812
                mem.tmode = 'Cross'
813
                mem.cross_mode = '->DTCS'
814
                mem.rx_dtcs = rxcode
815
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXCODE) and tsql:
816
                if rxcode == txcode:
817
                    mem.tmode = 'DTCS'
818
                    mem.rx_dtcs = rxcode
819
                    # #8327 Not sure this is the correct interpretation of
820
                    # DevelopersToneModes, but it seems to make it work round
821
                    # tripping with the anytone software.  DTM implies that we
822
                    # might not need to set mem.dtcs, but if we do it only DTCS
823
                    # rx works (as if we were Cross:None->DTCS).
824
                    mem.dtcs = rxcode
825
                else:
826
                    mem.tmode = 'Cross'
827
                    mem.cross_mode = 'DTCS->DTCS'
828
                    mem.rx_dtcs = rxcode
829
                    mem.dtcs = txcode
830
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXTONE) and tsql:
831
                mem.tmode = 'Cross'
832
                mem.cross_mode = 'DTCS->Tone'
833
                mem.dtcs = txcode
834
                mem.ctone = rxtone
835
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXCODE) and tsql:
836
                mem.tmode = 'Cross'
837
                mem.cross_mode = 'Tone->DTCS'
838
                mem.rx_dtcs = rxcode
839
                mem.rtone = txtone
840
            else:
841
                LOG.error('%s: Unhandled tmode enabled = %d.' % (
842
                    mem.name, enabled))
843

    
844
                # Can get here if e.g. TONE_EN_RXCODE is set and tsql isn't
845
                # In that case should we perhaps store the tone and code values
846
                # if they're present and then setup tmode and cross_mode as
847
                # appropriate later?
848

    
849
            # set the dtcs polarity
850
            dtcs_pol_bit_to_str = {0: 'N', 1: 'R'}
851
            mem.dtcs_polarity = '%s%s' %\
852
                (dtcs_pol_bit_to_str[_mem.dtcs_encode_invert == 1],
853
                 dtcs_pol_bit_to_str[_mem.dtcs_decode_invert == 1])
854

    
855
        return mem
856

    
857
    # Store details about a high-level memory to the memory map
858
    # This is called when a user edits a memory in the UI
859
    def set_memory(self, mem):
860
        # Get a low-level memory object mapped to the image
861
        _mem = self._memobj.memory[mem.number - 1]
862
        _mem_status = self._memobj.memory_status
863

    
864
        # set the occupied bitfield
865
        _mem_status.occupied_bitfield = \
866
            set_bitfield(_mem_status.occupied_bitfield, mem.number - 1,
867
                         not mem.empty)
868

    
869
        # set the scan add bitfield
870
        _mem_status.scan_enabled_bitfield = \
871
            set_bitfield(_mem_status.scan_enabled_bitfield, mem.number - 1,
872
                         (not mem.empty) and (mem.skip != 'S'))
873

    
874
        if mem.empty:
875
            # Set the whole memory to 0xff
876
            _mem.set_raw('\xff' * (_mem.size() / 8))
877
        else:
878
            _mem.set_raw('\x00' * (_mem.size() / 8))
879

    
880
            _mem.freq = int(mem.freq / 10)
881
            _mem.offset = int(mem.offset / 10)
882

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

    
885
            # TODO support busy channel lockout - disabled for now
886
            _mem.busy_channel_lockout = BUSY_CHANNEL_LOCKOUT_OFF
887

    
888
            # Set duplex bitfields
889
            if mem.duplex == '+':
890
                _mem.duplex = DUPLEX_POSSPLIT
891
            elif mem.duplex == '-':
892
                _mem.duplex = DUPLEX_NEGSPLIT
893
            elif mem.duplex == '':
894
                _mem.duplex = DUPLEX_NOSPLIT
895
            elif mem.duplex == 'split':
896
                # TODO: this is an unverified punt!
897
                _mem.duplex = DUPLEX_ODDSPLIT
898
            else:
899
                LOG.error('%s: set_mem: unhandled duplex: %s' %
900
                          (mem.name, mem.duplex))
901

    
902
            # handle tx off
903
            _mem.tx_off = 0
904
            if mem.duplex == 'off':
905
                _mem.tx_off = 1
906

    
907
            # Set the channel width - remember we promote 20kHz channels to FM
908
            # on import
909
            # , so don't handle them here
910
            if mem.mode == 'FM':
911
                _mem.channel_width = CHANNEL_WIDTH_25kHz
912
            elif mem.mode == 'NFM':
913
                _mem.channel_width = CHANNEL_WIDTH_12d5kHz
914
            else:
915
                LOG.error('%s: set_mem: unhandled mode: %s' % (
916
                    mem.name, mem.mode))
917

    
918
            # set the power level
919
            if mem.power == POWER_LEVELS[0]:
920
                _mem.txpower = TXPOWER_LOW
921
            elif mem.power == POWER_LEVELS[1]:
922
                _mem.txpower = TXPOWER_MED
923
            elif mem.power == POWER_LEVELS[2]:
924
                _mem.txpower = TXPOWER_HIGH
925
            else:
926
                LOG.error('%s: set_mem: unhandled power level: %s' %
927
                          (mem.name, mem.power))
928

    
929
            # TODO set the CTCSS values
930
            # TODO support custom ctcss tones here
931
            # Default - tones off, carrier sql
932
            _mem.ctcss_encode_en = 0
933
            _mem.ctcss_decode_en = 0
934
            _mem.tone_squelch_en = 0
935
            _mem.ctcss_enc_tone = 0x00
936
            _mem.ctcss_dec_tone = 0x00
937
            _mem.customctcss = 0x00
938
            _mem.dtcs_encode_en = 0
939
            _mem.dtcs_encode_code_highbit = 0
940
            _mem.dtcs_encode_code = 0
941
            _mem.dtcs_encode_invert = 0
942
            _mem.dtcs_decode_en = 0
943
            _mem.dtcs_decode_code_highbit = 0
944
            _mem.dtcs_decode_code = 0
945
            _mem.dtcs_decode_invert = 0
946

    
947
            dtcs_pol_str_to_bit = {'N': 0, 'R': 1}
948
            _mem.dtcs_encode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[0]]
949
            _mem.dtcs_decode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[1]]
950

    
951
            if mem.tmode == 'Tone':
952
                _mem.ctcss_encode_en = 1
953
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
954
            elif mem.tmode == 'TSQL':
955
                _mem.ctcss_encode_en = 1
956
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.ctone)
957
                _mem.ctcss_decode_en = 1
958
                _mem.tone_squelch_en = 1
959
                _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
960
            elif mem.tmode == 'DTCS':
961
                _mem.dtcs_encode_en = 1
962
                _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
963
                    dtcs_code_val_to_bits(mem.rx_dtcs)
964
                _mem.dtcs_decode_en = 1
965
                _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
966
                    dtcs_code_val_to_bits(mem.rx_dtcs)
967
                _mem.tone_squelch_en = 1
968
            elif mem.tmode == 'Cross':
969
                txmode, rxmode = mem.cross_mode.split('->')
970

    
971
                if txmode == 'Tone':
972
                    _mem.ctcss_encode_en = 1
973
                    _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
974
                elif txmode == '':
975
                    pass
976
                elif txmode == 'DTCS':
977
                    _mem.dtcs_encode_en = 1
978
                    _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
979
                        dtcs_code_val_to_bits(mem.dtcs)
980
                else:
981
                    LOG.error('%s: unhandled cross TX mode: %s' % (
982
                        mem.name, mem.cross_mode))
983

    
984
                if rxmode == 'Tone':
985
                    _mem.ctcss_decode_en = 1
986
                    _mem.tone_squelch_en = 1
987
                    _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
988
                elif rxmode == '':
989
                    pass
990
                elif rxmode == 'DTCS':
991
                    _mem.dtcs_decode_en = 1
992
                    _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
993
                        dtcs_code_val_to_bits(mem.rx_dtcs)
994
                    _mem.tone_squelch_en = 1
995
                else:
996
                    LOG.error('%s: unhandled cross RX mode: %s' % (
997
                        mem.name, mem.cross_mode))
998
            else:
999
                LOG.error('%s: Unhandled tmode/cross %s/%s.' %
1000
                          (mem.name, mem.tmode, mem.cross_mode))
1001
            LOG.debug('%s: tmode=%s, cross=%s, rtone=%f, ctone=%f' % (
1002
                mem.name, mem.tmode, mem.cross_mode, mem.rtone, mem.ctone))
1003
            LOG.debug('%s: CENC=%d, CDEC=%d, t(enc)=%02x, t(dec)=%02x' % (
1004
                mem.name,
1005
                _mem.ctcss_encode_en,
1006
                _mem.ctcss_decode_en,
1007
                ctcss_code_val_to_bits(mem.rtone),
1008
                ctcss_code_val_to_bits(mem.ctone)))
1009

    
1010
            # set unknown defaults, based on reading memory set by vendor tool
1011
            _mem.unknown1 = 0x00
1012
            _mem.unknown6 = 0x00
1013
            _mem.unknown7 = 0x00
1014
            _mem.unknown8 = 0x00
1015
            _mem.unknown9 = 0x00
1016
            _mem.unknown10 = 0x00
1017

    
1018
    def get_settings(self):
1019
        """Translate the MEM_FORMAT structs into setstuf in the UI"""
1020
        _settings = self._memobj.settings
1021
        _radio_settings = self._memobj.radio_settings
1022
        _password = self._memobj.password
1023

    
1024
        function = RadioSettingGroup("function", "Function Setup")
1025
        group = RadioSettings(function)
1026

    
1027
        # MODE SET
1028
        # Channel Locked
1029
        rs = RadioSettingValueBoolean(_settings.channelLocked)
1030
        rset = RadioSetting("settings.channelLocked", "Channel locked", rs)
1031
        function.append(rset)
1032

    
1033
        # Menu 3 - Display Mode
1034
        options = ["Frequency", "Channel", "Name"]
1035
        rs = RadioSettingValueList(options, options[_settings.displayMode])
1036
        rset = RadioSetting("settings.displayMode", "Display Mode", rs)
1037
        function.append(rset)
1038

    
1039
        # VFO/MR A
1040
        options = ["MR", "VFO"]
1041
        rs = RadioSettingValueList(options, options[_radio_settings.vfomrA])
1042
        rset = RadioSetting("radio_settings.vfomrA", "VFO/MR mode A", rs)
1043
        function.append(rset)
1044

    
1045
        # MR Channel A
1046
        options = ["%s" % x for x in range(1, 201)]
1047
        rs = RadioSettingValueList(options, options[_radio_settings.mrChanA])
1048
        rset = RadioSetting("radio_settings.mrChanA", "MR channel A", rs)
1049
        function.append(rset)
1050

    
1051
        # VFO/MR B
1052
        options = ["MR", "VFO"]
1053
        rs = RadioSettingValueList(options, options[_radio_settings.vfomrB])
1054
        rset = RadioSetting("radio_settings.vfomrB", "VFO/MR mode B", rs)
1055
        function.append(rset)
1056

    
1057
        # MR Channel B
1058
        options = ["%s" % x for x in range(1, 201)]
1059
        rs = RadioSettingValueList(options, options[_radio_settings.mrChanB])
1060
        rset = RadioSetting("radio_settings.mrChanB", "MR channel B", rs)
1061
        function.append(rset)
1062

    
1063
        # DISPLAY SET
1064
        # Starting Display
1065
        name = ""
1066
        for i in range(7):  # 0 - 7
1067
            name += chr(self._memobj.starting_display.line[i])
1068
        name = name.rstrip()  # remove trailing spaces
1069

    
1070
        rs = RadioSettingValueString(0, 7, name)
1071
        rset = RadioSetting("starting_display.line", "Starting display", rs)
1072
        function.append(rset)
1073

    
1074
        # Menu 11 - Backlight Brightness
1075
        options = ["%s" % x for x in range(1, 4)]
1076
        rs = RadioSettingValueList(options, options[_settings.backlightBr - 1])
1077
        rset = RadioSetting("settings.backlightBr", "Backlight brightness", rs)
1078
        function.append(rset)
1079

    
1080
        # Menu 15 - Screen Direction
1081
        options = ["Positive", "Inverted"]
1082
        rs = RadioSettingValueList(options, options[_settings.screenDir])
1083
        rset = RadioSetting("settings.screenDir", "Screen direction", rs)
1084
        function.append(rset)
1085

    
1086
        # Hand Mic Key Brightness
1087
        options = ["%s" % x for x in range(1, 32)]
1088
        rs = RadioSettingValueList(options, options[_settings.micKeyBrite - 1])
1089
        rset = RadioSetting("settings.micKeyBrite",
1090
                            "Hand mic key brightness", rs)
1091
        function.append(rset)
1092

    
1093
        # VOL SET
1094
        # Menu 1 - Beep Volume
1095
        options = ["OFF"] + ["%s" % x for x in range(1, 6)]
1096
        rs = RadioSettingValueList(options, options[_settings.beepVolume])
1097
        rset = RadioSetting("settings.beepVolume", "Beep volume", rs)
1098
        function.append(rset)
1099

    
1100
        # Menu 5 - Volume level Setup
1101
        options = ["%s" % x for x in range(1, 37)]
1102
        rs = RadioSettingValueList(options, options[_settings.speakerVol - 1])
1103
        rset = RadioSetting("settings.speakerVol", "Speaker volume", rs)
1104
        function.append(rset)
1105

    
1106
        # Menu 16 - Speaker Switch
1107
        options = ["Host on | Hand mic off", "Host on | Hand mic on",
1108
                   "Host off | Hand mic on"]
1109
        rs = RadioSettingValueList(options, options[_settings.speakerSwitch])
1110
        rset = RadioSetting("settings.speakerSwitch", "Speaker switch", rs)
1111
        function.append(rset)
1112

    
1113
        # STE SET
1114
        # STE Frequency
1115
        options = ["Off", "55.2 Hz", "259.2 Hz"]
1116
        rs = RadioSettingValueList(options, options[_settings.steFrequency])
1117
        rset = RadioSetting("settings.steFrequency", "STE frequency", rs)
1118
        function.append(rset)
1119

    
1120
        # STE Type
1121
        options = ["Off", "Silent", "120 degrees", "180 degrees",
1122
                   "240 degrees"]
1123
        rs = RadioSettingValueList(options, options[_settings.steType])
1124
        rset = RadioSetting("settings.steType", "STE type", rs)
1125
        function.append(rset)
1126

    
1127
        # ON/OFF SET
1128
        # Power-on Password
1129
        rs = RadioSettingValueBoolean(_settings.powerOnPasswd)
1130
        rset = RadioSetting("settings.powerOnPasswd", "Power-on Password", rs)
1131
        function.append(rset)
1132

    
1133
        # Password
1134
        def _char_to_str(chrx):
1135
            """ Remove ff pads from char array """
1136
            #  chrx is char array
1137
            str1 = ""
1138
            for sx in chrx:
1139
                if int(sx) > 31 and int(sx) < 127:
1140
                    str1 += chr(sx)
1141
            return str1
1142

    
1143
        def _pswd_vfy(setting, obj, atrb):
1144
            """ Verify password is 1-6 chars, numbers 1-5 """
1145
            str1 = str(setting.value).strip()   # initial
1146
            str2 = filter(lambda c: c in '0123456789', str1)    # valid chars
1147
            if str1 != str2:
1148
                # Two lines due to python 73 char limit
1149
                sx = "Bad characters in Password"
1150
                raise errors.RadioError(sx)
1151
            str2 = str1.ljust(6, chr(00))      # pad to 6 with 00's
1152
            setattr(obj, atrb, str2)
1153
            return
1154

    
1155
        sx = _char_to_str(_password.digits).strip()
1156
        rx = RadioSettingValueString(0, 6, sx)
1157
        sx = "Password (numerals 0-9)"
1158
        rset = RadioSetting("password.digits", sx, rx)
1159
        rset.set_apply_callback(_pswd_vfy, _password, "digits")
1160
        function.append(rset)
1161

    
1162
        # Menu 9 - Auto Power On
1163
        rs = RadioSettingValueBoolean(_settings.autoPowerOn)
1164
        rset = RadioSetting("settings.autoPowerOn", "Auto power on", rs)
1165
        function.append(rset)
1166

    
1167
        # Menu 13 - Auto Power Off
1168
        options = ["Off", "30 minutes", "60 minutes", "120 minutes"]
1169
        rs = RadioSettingValueList(options, options[_settings.autoPowerOff])
1170
        rset = RadioSetting("settings.autoPowerOff", "Auto power off", rs)
1171
        function.append(rset)
1172

    
1173
        # Power On Reset Enable
1174
        rs = RadioSettingValueBoolean(_settings.powerOnReset)
1175
        rset = RadioSetting("settings.powerOnReset", "Power on reset", rs)
1176
        function.append(rset)
1177

    
1178
        # FUNCTION SET
1179
        # Menu 4 - Squelch Level A
1180
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
1181
        rs = RadioSettingValueList(options, options[_settings.squelchLevelA])
1182
        rset = RadioSetting("settings.squelchLevelA", "Squelch level A", rs)
1183
        function.append(rset)
1184

    
1185
        # Squelch Level B
1186
        options = ["OFF"] + ["%s" % x for x in range(1, 10)]
1187
        rs = RadioSettingValueList(options, options[_settings.squelchLevelB])
1188
        rset = RadioSetting("settings.squelchLevelB", "Squelch level B", rs)
1189
        function.append(rset)
1190

    
1191
        # Menu 7 - Scan Type
1192
        options = ["Time operated (TO)", "Carrier operated (CO)",
1193
                   "Search (SE)"]
1194
        rs = RadioSettingValueList(options, options[_settings.scanType])
1195
        rset = RadioSetting("settings.scanType", "Scan mode", rs)
1196
        function.append(rset)
1197

    
1198
        # Menu 8 - Scan Recovery Time
1199
        options = ["%s seconds" % x for x in range(5, 20, 5)]
1200
        rs = RadioSettingValueList(options, options[_settings.scanRecoveryT])
1201
        rset = RadioSetting("settings.scanRecoveryT", "Scan recovery time", rs)
1202
        function.append(rset)
1203

    
1204
        # Main
1205
        options = ["A", "B"]
1206
        rs = RadioSettingValueList(options, options[_settings.main])
1207
        rset = RadioSetting("settings.main", "Main", rs)
1208
        function.append(rset)
1209

    
1210
        # Menu 10 - Dual Watch (RX Way Select)
1211
        rs = RadioSettingValueBoolean(_settings.dualWatch)
1212
        rset = RadioSetting("settings.dualWatch", "Dual watch", rs)
1213
        function.append(rset)
1214

    
1215
        # Menu 12 - Time Out Timer
1216
        options = ["OFF"] + ["%s minutes" % x for x in range(1, 31)]
1217
        rs = RadioSettingValueList(options, options[_settings.timeOutTimer])
1218
        rset = RadioSetting("settings.timeOutTimer", "Time out timer", rs)
1219
        function.append(rset)
1220

    
1221
        # TBST Frequency
1222
        options = ["1000 Hz", "1450 Hz", "1750 Hz", "2100 Hz"]
1223
        rs = RadioSettingValueList(options, options[_settings.tbstFrequency])
1224
        rset = RadioSetting("settings.tbstFrequency", "TBST frequency", rs)
1225
        function.append(rset)
1226

    
1227
        # Save Channel Perameter
1228
        rs = RadioSettingValueBoolean(_settings.saveChParameter)
1229
        rset = RadioSetting("settings.saveChParameter",
1230
                            "Save channel parameter", rs)
1231
        function.append(rset)
1232

    
1233
        # MON Key Function
1234
        options = ["Squelch off momentary", "Squelch off"]
1235
        rs = RadioSettingValueList(options, options[_settings.monKeyFunction])
1236
        rset = RadioSetting("settings.monKeyFunction", "MON key function", rs)
1237
        function.append(rset)
1238

    
1239
        # Frequency Step
1240
        options = ["2.5 KHz", "5 KHz", "6.25 KHz", "10 KHz", "12.5 KHz",
1241
                   "20 KHz", "25 KHz", "30 KHz", "50 KHz"]
1242
        rs = RadioSettingValueList(options, options[_settings.frequencyStep])
1243
        rset = RadioSetting("settings.frequencyStep", "Frequency step", rs)
1244
        function.append(rset)
1245

    
1246
        # Knob Mode
1247
        options = ["Volume", "Channel"]
1248
        rs = RadioSettingValueList(options, options[_settings.knobMode])
1249
        rset = RadioSetting("settings.knobMode", "Knob mode", rs)
1250
        function.append(rset)
1251

    
1252
        # TRF Enable
1253
        rs = RadioSettingValueBoolean(_settings.trfEnable)
1254
        rset = RadioSetting("settings.trfEnable", "TRF enable", rs)
1255
        function.append(rset)
1256

    
1257
        return group
1258

    
1259
    def set_settings(self, settings):
1260
        _settings = self._memobj.settings
1261
        _mem = self._memobj
1262
        for element in settings:
1263
            if not isinstance(element, RadioSetting):
1264
                self.set_settings(element)
1265
                continue
1266
            else:
1267
                try:
1268
                    name = element.get_name()
1269
                    if "." in name:
1270
                        bits = name.split(".")
1271
                        obj = self._memobj
1272
                        for bit in bits[:-1]:
1273
                            if "/" in bit:
1274
                                bit, index = bit.split("/", 1)
1275
                                index = int(index)
1276
                                obj = getattr(obj, bit)[index]
1277
                            else:
1278
                                obj = getattr(obj, bit)
1279
                        setting = bits[-1]
1280
                    else:
1281
                        obj = _settings
1282
                        setting = element.get_name()
1283

    
1284
                    if element.has_apply_callback():
1285
                        LOG.debug("Using apply callback")
1286
                        element.run_apply_callback()
1287
                    elif setting == "backlightBr":
1288
                        setattr(obj, setting, int(element.value) + 1)
1289
                    elif setting == "micKeyBrite":
1290
                        setattr(obj, setting, int(element.value) + 1)
1291
                    elif setting == "speakerVol":
1292
                        setattr(obj, setting, int(element.value) + 1)
1293
                    elif element.value.get_mutable():
1294
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1295
                        setattr(obj, setting, element.value)
1296
                except Exception, e:
1297
                    LOG.debug(element.get_name())
1298
                    raise
1299

    
1300
if has_future:
1301
    @directory.register
1302
    class AnyTone778UV(AnyTone778UVBase):
1303
        VENDOR = "AnyTone"
1304
        MODEL = "778UV"
1305
        # Allowed radio types is a dict keyed by model of a list of version
1306
        # strings
1307
        ALLOWED_RADIO_TYPES = {'AT778UV': ['V100', 'V200']}
1308

    
1309
    @directory.register
1310
    class RetevisRT95(AnyTone778UVBase):
1311
        VENDOR = "Retevis"
1312
        MODEL = "RT95"
1313
        # Allowed radio types is a dict keyed by model of a list of version
1314
        # strings
1315
        ALLOWED_RADIO_TYPES = {'RT95': ['V100']}
1316

    
1317
    @directory.register
1318
    class CRTMicronUV(AnyTone778UVBase):
1319
        VENDOR = "CRT"
1320
        MODEL = "Micron UV"
1321
        # Allowed radio types is a dict keyed by model of a list of version
1322
        # strings
1323
        ALLOWED_RADIO_TYPES = {'MICRON': ['V100']}
1324

    
1325
    @directory.register
1326
    class MidlandDBR2500(AnyTone778UVBase):
1327
        VENDOR = "Midland"
1328
        MODEL = "DBR2500"
1329
        # Allowed radio types is a dict keyed by model of a list of version
1330
        # strings
1331
        ALLOWED_RADIO_TYPES = {'DBR2500': ['V100']}
1332

    
1333
    @directory.register
1334
    class YedroYCM04vus(AnyTone778UVBase):
1335
        VENDOR = "Yedro"
1336
        MODEL = "YC-M04VUS"
1337
        # Allowed radio types is a dict keyed by model of a list of version
1338
        # strings
1339
        ALLOWED_RADIO_TYPES = {'YCM04UV': ['V100']}