Project

General

Profile

New Model #6787 » 20200524_anytone778UV.py

Joe Milbourn, 05/24/2020 12:03 AM

 
1
# Copyright 2020 Joe Milbourn <joe@milbourn.org.uk>
2
#
3
# This program is free software: you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation, either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15

    
16
# TODONE change flags to use named bits, not bit type, u8 talkaround:1...
17
# TODONE replace reprdata with utils.hexprint
18
# TODONE read the whole image into memdata - need to re-arrange MEM_FORMAT to
19
#        suit, seeking around to put things in the right places, and set
20
#        default values
21
# TODONE Exception as e
22
# TODONE return memmap.MemoryMapBytes
23
# TODONE change experimental prompt wording
24
# TODONE add DTCS
25

    
26
from chirp import chirp_common, directory, memmap, errors, util
27
from chirp import bitwise
28

    
29
import struct
30
import time
31
import logging
32

    
33
LOG = logging.getLogger(__name__)
34

    
35
# Gross hack to handle missing future module on un-updatable
36
# platforms like MacOS. Just avoid registering these radio
37
# classes for now.
38
try:
39
    from builtins import bytes
40
    has_future = True
41
except ImportError:
42
    has_future = False
43
    LOG.warning('python-future package is not '
44
                'available; %s requires it' % __name__)
45

    
46

    
47
# Here is where we define the memory map for the radio. Since
48
# We often just know small bits of it, we can use #seekto to skip
49
# around as needed.
50

    
51
MEM_FORMAT = '''
52
#seekto 0x0000;
53
struct {
54
  bbcd freq[4];
55
  bbcd offset[4];
56
  u8 unknown1;
57
  u8 talkaround:1,
58
     scramble:1,
59
     unknown:2,
60
     txpower:2,
61
     duplex:2;
62
  u8 unknown_bits1:4,
63
     channel_width:2,
64
     reverse:1,
65
     tx_off:1;
66
  u8 unknown_bits2:4,
67
     dtcs_decode_en:1,
68
     ctcss_decode_en:1,
69
     dtcs_encode_en:1,
70
     ctcss_encode_en:1;
71
  u8 ctcss_dec_tone;
72
  u8 ctcss_enc_tone;
73
  u8 dtcs_decode_code;
74
  u8 unknown_bits6:6,
75
     dtcs_decode_invert:1,
76
     dtcs_decode_code_highbit:1;
77
  u8 dtcs_encode_code;
78
  u8 unknown_bits7:6,
79
     dtcs_encode_invert:1,
80
     dtcs_encode_code_highbit:1;
81
  u8 unknown_bits4:6,
82
     busy_channel_lockout:2;
83
  u8 unknown6;
84
  u8 unknown_bits5:7,
85
     tone_squelch_en:1;
86
  u8 unknown7;
87
  u8 unknown8;
88
  u8 unknown9;
89
  u8 unknown10;
90
  char name[5];
91
  ul16 customctcss;
92
} memory[200];
93
#seekto 0x1940;
94
struct {
95
  u8 occupied_bitfield[32];
96
  u8 scan_enabled_bitfield[32];
97
} memory_status;
98
'''
99

    
100
# Format for the version messages returned by the radio
101
VER_FORMAT = '''
102
u8 hdr;
103
char model[7];
104
u8 sep;
105
char version[6];
106
u8 ack;
107
'''
108

    
109
TXPOWER_LOW = 0x00
110
TXPOWER_MED = 0x01
111
TXPOWER_HIGH = 0x02
112

    
113
DUPLEX_NOSPLIT = 0x00
114
DUPLEX_POSSPLIT = 0x01
115
DUPLEX_NEGSPLIT = 0x02
116
DUPLEX_ODDSPLIT = 0x03
117

    
118
CHANNEL_WIDTH_25kHz = 0x02
119
CHANNEL_WIDTH_20kHz = 0x01
120
CHANNEL_WIDTH_12d5kHz = 0x00
121

    
122
BUSY_CHANNEL_LOCKOUT_OFF = 0x00
123
BUSY_CHANNEL_LOCKOUT_REPEATER = 0x01
124
BUSY_CHANNEL_LOCKOUT_BUSY = 0x02
125

    
126
MEMORY_ADDRESS_RANGE = (0x0000, 0x3290)
127
MEMORY_RW_BLOCK_SIZE = 0x10
128
MEMORY_RW_BLOCK_CMD_SIZE = 0x16
129

    
130
POWER_LEVELS = [chirp_common.PowerLevel('Low', dBm=37),
131
                chirp_common.PowerLevel('Medium', dBm=40),
132
                chirp_common.PowerLevel('High', dBm=44)]
133

    
134
# CTCSS Tone definitions
135
TONE_CUSTOM_CTCSS = 0x33
136
TONE_MAP_VAL_TO_TONE = {0x00: 62.5, 0x01: 67.0, 0x02: 69.3,
137
                        0x03: 71.9, 0x04: 74.4, 0x05: 77.0,
138
                        0x06: 79.7, 0x07: 82.5, 0x08: 85.4,
139
                        0x09: 88.5, 0x0a: 91.5, 0x0b: 94.8,
140
                        0x0c: 97.4, 0x0d: 100.0, 0x0e: 103.5,
141
                        0x0f: 107.2, 0x10: 110.9, 0x11: 114.8,
142
                        0x12: 118.8, 0x13: 123.0, 0x14: 127.3,
143
                        0x15: 131.8, 0x16: 136.5, 0x17: 141.3,
144
                        0x18: 146.2, 0x19: 151.4, 0x1a: 156.7,
145
                        0x1b: 159.8, 0x1c: 162.2, 0x1d: 165.5,
146
                        0x1e: 167.9, 0x1f: 171.3, 0x20: 173.8,
147
                        0x21: 177.3, 0x22: 179.9, 0x23: 183.5,
148
                        0x24: 186.2, 0x25: 189.9, 0x26: 192.8,
149
                        0x27: 196.6, 0x28: 199.5, 0x29: 203.5,
150
                        0x2a: 206.5, 0x2b: 210.7, 0x2c: 218.1,
151
                        0x2d: 225.7, 0x2e: 229.1, 0x2f: 233.6,
152
                        0x30: 241.8, 0x31: 250.3, 0x32: 254.1}
153

    
154
TONE_MAP_TONE_TO_VAL = {TONE_MAP_VAL_TO_TONE[val]: val
155
                        for val in TONE_MAP_VAL_TO_TONE}
156

    
157
TONES_EN_TXTONE = (1 << 3)
158
TONES_EN_RXTONE = (1 << 2)
159
TONES_EN_TXCODE = (1 << 1)
160
TONES_EN_RXCODE = (1 << 0)
161
TONES_EN_NO_TONE = 0
162

    
163

    
164
# Calculate the checksum used in serial packets
165
def checksum(message_bytes):
166
    mask = 0xFF
167
    checksum = 0
168
    for b in message_bytes:
169
        checksum = (checksum + b) & mask
170
    return checksum
171

    
172

    
173
# Send a command to the radio, return any reply stripping the echo of the
174
# command (tx and rx share a single pin in this radio)
175
def send_serial_command(serial, command, expectedlen=None):
176
    ''' send a command to the radio, and return any response.
177
    set expectedlen to return as soon as that many bytes are read.
178
    '''
179
    serial.write(command)
180
    serial.flush()
181

    
182
    response = b''
183
    tout = time.time() + 0.5
184
    while time.time() < tout:
185
        if serial.inWaiting():
186
            response += serial.read()
187
        # remember everything gets echo'd back
188
        if len(response) - len(command) == expectedlen:
189
            break
190

    
191
    # cut off what got echo'd back, we don't need to see it again
192
    if response.startswith(command):
193
        response = response[len(command):]
194

    
195
    return response
196

    
197

    
198
# return pretty printed hex and ascii representation of binary data
199
def reprdata(bindata):
200
    hexwidth = 60
201
    sepwidth = 4
202

    
203
    line = ''
204
    sepctr = 0
205
    for b in bytes(bindata):
206
        line += '%02x' % ord(b)
207
        sepctr += 1
208
        if sepctr == sepwidth:
209
            line += ' '
210
            sepctr = 0
211

    
212
    line += ' ' * (hexwidth - len(line))
213

    
214
    for b in bindata:
215
        if 0x21 <= ord(b) <= 0x7E:
216
            line += b
217
        else:
218
            line += '.'
219
    return line
220

    
221

    
222
# strip trailing 0x00 to convert a string returned by bitwise.parse into a
223
# python string
224
def cstring_to_py_string(cstring):
225
    return "".join(c for c in cstring if c != '\x00')
226

    
227

    
228
# Check the radio version reported to see if it's one we support
229
# TODO extend this list, as I suspect there are other very similar radios
230
# like the RT95
231
def check_ver(ver_response, allowed_types):
232
    ''' Check the returned radio version is one we approve of '''
233

    
234
    LOG.debug('ver_response = ')
235
    LOG.debug(util.hexprint(ver_response))
236

    
237
    resp = bitwise.parse(VER_FORMAT, ver_response)
238
    verok = False
239

    
240
    if resp.hdr == 0x49 and resp.ack == 0x06:
241
        model, version = [cstring_to_py_string(bitwise.get_string(s)).strip()
242
                          for s in (resp.model, resp.version)]
243
        LOG.debug('radio model: \'%s\' version: \'%s\'' %
244
                  (model, version))
245
        LOG.debug('allowed_types = %s' % allowed_types)
246

    
247
        if model in allowed_types:
248
            LOG.debug('model in allowed_types')
249

    
250
            if version in allowed_types[model]:
251
                LOG.debug('version in allowed_types[model]')
252
                verok = True
253
    else:
254
        raise errors.RadioError('Failed to parse version response')
255

    
256
    return verok
257

    
258
# Put the radio in programming mode, sending the initial command and checking
259
# the response.  raise RadioError if there is no response (500ms timeout), and
260
# if the returned version isn't matched by check_ver
261
def enter_program_mode(radio):
262
    serial = radio.pipe
263
    # place the radio in program mode, and confirm
264
    program_response = send_serial_command(serial, b'PROGRAM')
265

    
266
    if program_response != b'QX\x06':
267
        raise errors.RadioError('No initial response from radio.')
268
    LOG.debug('entered program mode')
269

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

    
273
    if not check_ver(ver_response, radio.ALLOWED_RADIO_TYPES):
274
        exit_program_mode(radio)
275
        raise errors.RadioError('Radio version not in allowed list for %s-%s: %s'
276
                                % (radio.VENDOR, radio.MODEL,
277
                                   util.hexprint(ver_response)))
278

    
279

    
280
# Exit programming mode
281
def exit_program_mode(radio):
282
    send_serial_command(radio.pipe, b'END')
283

    
284

    
285
# Parse a packet from the radio returning the header (R/W, address, data, and
286
# checksum valid
287
def parse_read_response(resp):
288
    addr = resp[:4]
289
    data = bytes(resp[4:-2])
290
    cs = checksum(ord(d) for d in resp[1:-2])
291
    valid = cs == ord(resp[-2])
292
    if not valid:
293
        LOG.error('checksumfail: %02x, expected %02x' % (cs, ord(resp[-2])))
294
        LOG.error('msg data: %s' % util.hexprint(resp))
295
    return addr, data, valid
296

    
297

    
298
# Download data from the radio and populate the memory map
299
def do_download(radio):
300
    '''Download memories from the radio'''
301

    
302
    # Get the serial port connection
303
    serial = radio.pipe
304

    
305
    try:
306
        enter_program_mode(radio)
307

    
308
        memory_data = bytes()
309

    
310
        # status info for the UI
311
        status = chirp_common.Status()
312
        status.cur = 0
313
        status.max = (MEMORY_ADDRESS_RANGE[1] -
314
                      MEMORY_ADDRESS_RANGE[0])/MEMORY_RW_BLOCK_SIZE
315
        status.msg = 'Cloning from radio...'
316
        radio.status_fn(status)
317

    
318
        for addr in range(MEMORY_ADDRESS_RANGE[0],
319
                          MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
320
                          MEMORY_RW_BLOCK_SIZE):
321
            read_command = struct.pack('>BHB', 0x52, addr,
322
                                       MEMORY_RW_BLOCK_SIZE)
323
            read_response = send_serial_command(serial, read_command,
324
                                                MEMORY_RW_BLOCK_CMD_SIZE)
325
            # LOG.debug('read response:\n%s' % util.hexprint(read_response))
326

    
327
            address, data, valid = parse_read_response(read_response)
328
            memory_data += data
329

    
330
            # update UI
331
            status.cur = (addr - MEMORY_ADDRESS_RANGE[0])\
332
                / MEMORY_RW_BLOCK_SIZE
333
            radio.status_fn(status)
334

    
335
        exit_program_mode(radio)
336
    except errors.RadioError as e:
337
        raise e
338
    except Exception as e:
339
        raise errors.RadioError('Failed to download from radio: %s' % e)
340

    
341
    return memmap.MemoryMapBytes(memory_data)
342

    
343

    
344
# Build a write data command to send to the radio
345
def make_write_data_cmd(addr, data, datalen):
346
    cmd = struct.pack('>BHB', 0x57, addr, datalen)
347
    cmd += data
348
    cs = checksum(ord(c) for c in cmd[1:])
349
    cmd += struct.pack('>BB', cs, 0x06)
350
    return cmd
351

    
352

    
353
# Upload a memory map to the radio
354
def do_upload(radio):
355
    try:
356
        enter_program_mode(radio)
357

    
358
        serial = radio.pipe
359

    
360
        # send the initial message, radio responds with something that looks a
361
        # bit like a bitfield, but I don't know what it is yet.
362
        read_command = struct.pack('>BHB', 0x52, 0x3b10, MEMORY_RW_BLOCK_SIZE)
363
        read_response = send_serial_command(serial, read_command,
364
                                            MEMORY_RW_BLOCK_CMD_SIZE)
365
        address, data, valid = parse_read_response(read_response)
366
        LOG.debug('Got initial response from radio: %s' %
367
                  util.hexprint(read_response))
368

    
369
        bptr = 0
370

    
371
        memory_addrs = range(MEMORY_ADDRESS_RANGE[0],
372
                             MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
373
                             MEMORY_RW_BLOCK_SIZE)
374

    
375
        # status info for the UI
376
        status = chirp_common.Status()
377
        status.cur = 0
378
        status.max = len(memory_addrs)
379
        status.msg = 'Cloning to radio...'
380
        radio.status_fn(status)
381

    
382
        for idx, addr in enumerate(memory_addrs):
383
            write_command = make_write_data_cmd(
384
                addr, radio._mmap[bptr:bptr+MEMORY_RW_BLOCK_SIZE],
385
                MEMORY_RW_BLOCK_SIZE)
386
            # LOG.debug('write data:\n%s' % util.hexprint(write_command))
387
            write_response = send_serial_command(serial, write_command, 0x01)
388
            bptr += MEMORY_RW_BLOCK_SIZE
389

    
390
            if write_response == '\x0a':
391
                # NACK from radio, e.g. checksum wrongn
392
                LOG.debug('Radio returned 0x0a - NACK:')
393
                LOG.debug(' * write cmd:\n%s' % util.hexprint(write_command))
394
                LOG.debug(' * write response:\n%s' %
395
                          util.hexprint(write_response))
396
                exit_program_mode(radio)
397
                raise errors.RadioError('Radio NACK\'d write command')
398

    
399
            # update UI
400
            status.cur = idx
401
            radio.status_fn(status)
402
        exit_program_mode(radio)
403
    except errors.RadioError:
404
        raise
405
    except Exception as e:
406
        raise errors.RadioError('Failed to download from radio: %s' % e)
407

    
408

    
409
# Get the value of @bitfield @number of bits in from 0
410
def get_bitfield(bitfield, number):
411
    ''' Get the value of @bitfield @number of bits in '''
412
    byteidx = number//8
413
    bitidx = number - (byteidx * 8)
414
    return bitfield[byteidx] & (1 << bitidx)
415

    
416

    
417
# Set the @value of @bitfield @number of bits in from 0
418
def set_bitfield(bitfield, number, value):
419
    ''' Set the @value of @bitfield @number of bits in '''
420
    byteidx = number//8
421
    bitidx = number - (byteidx * 8)
422
    if value is True:
423
        bitfield[byteidx] |= (1 << bitidx)
424
    else:
425
        bitfield[byteidx] &= ~(1 << bitidx)
426
    return bitfield
427

    
428

    
429
# Translate the radio's version of a code as stored to a real code
430
def dtcs_code_bits_to_val(highbit, lowbyte):
431
    return chirp_common.ALL_DTCS_CODES[highbit*256 + lowbyte]
432

    
433

    
434
# Translate the radio's version of a tone as stored to a real tone
435
def ctcss_tone_bits_to_val(tone_byte):
436
    # TODO use the custom setting 0x33 and ref the custom ctcss
437
    # field
438
    tone_byte = int(tone_byte)
439
    if tone_byte in TONE_MAP_VAL_TO_TONE:
440
        return TONE_MAP_VAL_TO_TONE[tone_byte]
441
    elif tone_byte == TONE_CUSTOM_CTCSS:
442
        LOG.info('custom ctcss not implemented (yet?).')
443
    else:
444
        raise errors.UnsupportedToneError('unknown ctcss tone value: %02x' %
445
                                          tone_byte)
446

    
447

    
448
# Translate a real tone to the radio's version as stored
449
def ctcss_code_val_to_bits(tone_value):
450
    if tone_value in TONE_MAP_TONE_TO_VAL:
451
        return TONE_MAP_TONE_TO_VAL[tone_value]
452
    else:
453
        raise errors.UnsupportedToneError('Tone %f not supported' % tone_value)
454

    
455

    
456
# Translate a real code to the radio's version as stored
457
def dtcs_code_val_to_bits(code):
458
    val = chirp_common.ALL_DTCS_CODES.index(code)
459
    return (val & 0xFF), ((val >> 8) & 0x01)
460

    
461

    
462
class AnyTone778UVBase(chirp_common.CloneModeRadio,
463
                       chirp_common.ExperimentalRadio):
464
    '''AnyTone 778UV and probably Retivis RT95 and others'''
465
    BAUD_RATE = 9600
466
    NEEDS_COMPAT_SERIAL = False
467

    
468
    @classmethod
469
    def get_prompts(cls):
470
        rp = chirp_common.RadioPrompts()
471

    
472
        rp.experimental = \
473
            ('This is experimental support for the %s %s.  '
474
             'Please send in bug and enhancement requests!' %
475
             (cls.VENDOR, cls.MODEL))
476

    
477
        return rp
478

    
479
    # Return information about this radio's features, including
480
    # how many memories it has, what bands it supports, etc
481
    def get_features(self):
482
        rf = chirp_common.RadioFeatures()
483
        rf.has_bank = False
484
        rf.has_settings = False
485
        rf.can_odd_split = True
486
        rf.has_name = True
487
        rf.has_offset = True
488
        rf.valid_name_length = 5
489
        rf.valid_duplexes = ['', '+', '-', 'split']
490

    
491
        rf.has_dtcs = True
492
        rf.has_rx_dtcs = True
493
        rf.has_dtcs_polarity = True
494
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES
495
        rf.has_ctone = True
496
        rf.has_cross = True
497
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
498
        rf.valid_cross_modes = ['Tone->Tone',
499
                                'Tone->DTCS',
500
                                'DTCS->Tone',
501
                                'DTCS->DTCS',
502
                                'DTCS->',
503
                                '->DTCS',
504
                                '->Tone']
505

    
506
        rf.memory_bounds = (0, 199)  # This radio supports memories 0-199
507
        rf.valid_bands = [(144000000, 148000000),  # Supports 2-meters
508
                          (430000000, 450000000),  # Supports 70-centimeters
509
                          ]
510
        rf.valid_modes = ['FM', 'NFM']
511
        rf.valid_power_levels = POWER_LEVELS
512
        rf.valid_tuning_steps = [2.5, 5, 6.25, 10, 12.5, 20, 25, 30, 50]
513
        return rf
514

    
515
    # Do a download of the radio from the serial port
516
    def sync_in(self):
517
        self._mmap = do_download(self)
518
        self.process_mmap()
519

    
520
    # Do an upload of the radio to the serial port
521
    def sync_out(self):
522
        do_upload(self)
523

    
524
    # Convert the raw byte array into a memory object structure
525
    def process_mmap(self):
526
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
527

    
528
    # Return a raw representation of the memory object, which
529
    # is very helpful for development
530
    def get_raw_memory(self, number):
531
        return repr(self._memobj.memory[number])
532

    
533
    # Extract a high-level memory object from the low-level memory map
534
    # This is called to populate a memory in the UI
535
    def get_memory(self, number):
536
        # Get a low-level memory object mapped to the image
537
        _mem = self._memobj.memory[number]
538
        _mem_status = self._memobj.memory_status
539

    
540
        # Create a high-level memory object to return to the UI
541
        mem = chirp_common.Memory()
542
        mem.number = number                 # Set the memory number
543

    
544
        # Check if this memory is present in the occupied list
545
        mem.empty = get_bitfield(_mem_status.occupied_bitfield, number) == 0
546

    
547
        if not mem.empty:
548
            # Check if this memory is in the scan enabled list
549
            mem.skip = ''
550
            if get_bitfield(_mem_status.scan_enabled_bitfield, number) == 0:
551
                mem.skip = 'S'
552

    
553
            # set the name
554
            mem.name = str(_mem.name).rstrip()  # Set the alpha tag
555

    
556
            # Convert your low-level frequency and offset to Hertz
557
            mem.freq = int(_mem.freq) * 10
558
            mem.offset = int(_mem.offset) * 10
559

    
560
            # Set the duplex flags
561
            if _mem.duplex == DUPLEX_POSSPLIT:
562
                mem.duplex = '+'
563
            elif _mem.duplex == DUPLEX_NEGSPLIT:
564
                mem.duplex = '-'
565
            elif _mem.duplex == DUPLEX_NOSPLIT:
566
                mem.duplex = ''
567
            elif _mem.duplex == DUPLEX_ODDSPLIT:
568
                mem.duplex = 'split'
569
            else:
570
                LOG.error('%s: get_mem: unhandled duplex: %02x' %
571
                          (mem.name, _mem.duplex))
572

    
573
            # Set the channel width
574
            if _mem.channel_width == CHANNEL_WIDTH_25kHz:
575
                mem.mode = 'FM'
576
            elif _mem.channel_width == CHANNEL_WIDTH_20kHz:
577
                LOG.info(
578
                    '%s: get_mem: promoting 20kHz channel width to 25kHz' %
579
                    mem.name)
580
                mem.mode = 'FM'
581
            elif _mem.channel_width == CHANNEL_WIDTH_12d5kHz:
582
                mem.mode = 'NFM'
583
            else:
584
                LOG.error('%s: get_mem: unhandled channel width: 0x%02x' %
585
                          (mem.name, _mem.channel_width))
586

    
587
            # set the power level
588
            if _mem.txpower == TXPOWER_LOW:
589
                mem.power = POWER_LEVELS[0]
590
            elif _mem.txpower == TXPOWER_MED:
591
                mem.power = POWER_LEVELS[1]
592
            elif _mem.txpower == TXPOWER_HIGH:
593
                mem.power = POWER_LEVELS[2]
594
            else:
595
                LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
596
                          (mem.name, _mem.txpower))
597

    
598
            # CTCSS Tones
599
            # TODO support custom ctcss tones here
600
            txtone = None
601
            rxtone = None
602
            rxcode = None
603
            txcode = None
604

    
605
            # check if dtcs tx is enabled
606
            if _mem.dtcs_encode_en:
607
                txcode = dtcs_code_bits_to_val(_mem.dtcs_encode_code_highbit,
608
                                     _mem.dtcs_encode_code)
609

    
610
            # check if dtcs rx is enabled
611
            if _mem.dtcs_decode_en:
612
                rxcode = dtcs_code_bits_to_val(_mem.dtcs_decode_code_highbit,
613
                                     _mem.dtcs_decode_code)
614

    
615
            if txcode is not None:
616
                LOG.debug('%s: get_mem dtcs_enc: %d' % (mem.name, txcode))
617
            if rxcode is not None:
618
                LOG.debug('%s: get_mem dtcs_dec: %d' % (mem.name, rxcode))
619

    
620
            # tsql set if radio squelches on tone
621
            tsql = _mem.tone_squelch_en
622

    
623
            # check if ctcss tx is enabled
624
            if _mem.ctcss_encode_en:
625
                txtone = ctcss_tone_bits_to_val(_mem.ctcss_enc_tone)
626

    
627
            # check if ctcss rx is enabled
628
            if _mem.ctcss_decode_en:
629
                rxtone = ctcss_tone_bits_to_val(_mem.ctcss_dec_tone)
630

    
631
            # Define this here to allow a readable if-else tree enabling tone
632
            # options
633
            enabled = 0
634
            enabled |= (txtone is not None) * TONES_EN_TXTONE
635
            enabled |= (rxtone is not None) * TONES_EN_RXTONE
636
            enabled |= (txcode is not None) * TONES_EN_TXCODE
637
            enabled |= (rxcode is not None) * TONES_EN_RXCODE
638

    
639
            # Add some debugging output for the tone bitmap
640
            enstr = []
641
            if enabled & TONES_EN_TXTONE:
642
                enstr += ['TONES_EN_TXTONE']
643
            if enabled & TONES_EN_RXTONE:
644
                enstr += ['TONES_EN_RXTONE']
645
            if enabled & TONES_EN_TXCODE:
646
                enstr += ['TONES_EN_TXCODE']
647
            if enabled & TONES_EN_RXCODE:
648
                enstr += ['TONES_EN_RXCODE']
649
            if enabled == 0:
650
                enstr = ['TONES_EN_NOTONE']
651
            LOG.debug('%s: enabled = %s' % (
652
                mem.name, '|'.join(enstr)))
653

    
654
            mem.tmode = ''
655
            if enabled == TONES_EN_NO_TONE:
656
                mem.tmode = ''
657
            elif enabled == TONES_EN_TXTONE:
658
                mem.tmode = 'Tone'
659
                mem.rtone = txtone
660
            elif enabled == TONES_EN_RXTONE and tsql:
661
                mem.tmode = 'Cross'
662
                mem.cross_mode = '->Tone'
663
                mem.ctone = rxtone
664
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXTONE) and tsql:
665
                if txtone == rxtone:  # TSQL
666
                    mem.tmode = 'TSQL'
667
                    mem.ctone = txtone
668
                else:  # Tone->Tone
669
                    mem.tmode = 'Cross'
670
                    mem.cross_mode = 'Tone->Tone'
671
                    mem.ctone = rxtone
672
                    mem.rtone = txtone
673
            elif enabled == TONES_EN_TXCODE:
674
                mem.tmode = 'Cross'
675
                mem.cross_mode = 'DTCS->'
676
                mem.dtcs = txcode
677
            elif enabled == TONES_EN_RXCODE and tsql:
678
                mem.tmode = 'Cross'
679
                mem.cross_mode = '->DTCS'
680
                mem.rx_dtcs = rxcode
681
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXCODE) and tsql:
682
                if rxcode == txcode:
683
                    mem.tmode = 'DTCS'
684
                    mem.rx_dtcs = rxcode
685
                else:
686
                    mem.tmode = 'Cross'
687
                    mem.cross_mode = 'DTCS->DTCS'
688
                    mem.rx_dtcs = rxcode
689
                    mem.dtcs = txcode
690
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXTONE) and tsql:
691
                mem.tmode = 'Cross'
692
                mem.cross_mode = 'DTCS->Tone'
693
                mem.dtcs = txcode
694
                mem.ctone = rxtone
695
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXCODE) and tsql:
696
                mem.tmode = 'Cross'
697
                mem.cross_mode = 'Tone->DTCS'
698
                mem.rx_dtcs = rxcode
699
                mem.rtone = txtone
700
            else:
701
                LOG.error('%s: Unhandled tmode enabled = %d.' % (
702
                    mem.name, enabled))
703

    
704
            # set the dtcs polarity
705
            dtcs_pol_bit_to_str = {0: 'N', 1: 'R'}
706
            mem.dtcs_polarity = '%s%s' %\
707
                (dtcs_pol_bit_to_str[_mem.dtcs_encode_invert == 1],
708
                 dtcs_pol_bit_to_str[_mem.dtcs_decode_invert == 1])
709

    
710
        return mem
711

    
712
    # Store details about a high-level memory to the memory map
713
    # This is called when a user edits a memory in the UI
714
    def set_memory(self, mem):
715
        # Get a low-level memory object mapped to the image
716
        _mem = self._memobj.memory[mem.number]
717
        _mem_status = self._memobj.memory_status
718

    
719
        # set the occupied bitfield
720
        _mem_status.occupied_bitfield = \
721
            set_bitfield(_mem_status.occupied_bitfield, mem.number,
722
                         not mem.empty)
723

    
724
        # set the scan add bitfield
725
        _mem_status.scan_enabled_bitfield = \
726
            set_bitfield(_mem_status.scan_enabled_bitfield, mem.number,
727
                         (not mem.empty) and (mem.skip != 'S'))
728

    
729
        if mem.empty:
730
            # Set the whole memory to 0xff
731
            _mem.set_raw('\xff' * (_mem.size() / 8))
732
        else:
733
            _mem.set_raw('\x00' * (_mem.size() / 8))
734

    
735
            _mem.freq = int(mem.freq / 10)
736
            _mem.offset = int(mem.offset / 10)
737

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

    
740
            # TODO support busy channel lockout - disabled for now
741
            _mem.busy_channel_lockout = BUSY_CHANNEL_LOCKOUT_OFF
742

    
743
            # Set duplex bitfields
744
            if mem.duplex == '+':
745
                _mem.duplex = DUPLEX_POSSPLIT
746
            elif mem.duplex == '-':
747
                _mem.duplex = DUPLEX_NEGSPLIT
748
            elif mem.duplex == '':
749
                _mem.duplex = DUPLEX_NOSPLIT
750
            elif mem.duplex == 'split':
751
                # TODO: this is an unverified punt!
752
                _mem.duplex = DUPLEX_ODDSPLIT
753
            else:
754
                LOG.error('%s: set_mem: unhandled duplex: %s' %
755
                          (mem.name, mem.duplex))
756

    
757
            # Set the channel width - remember we promote 20kHz channels to FM
758
            # on import, so don't handle them here
759
            if mem.mode == 'FM':
760
                _mem.channel_width = CHANNEL_WIDTH_25kHz
761
            elif mem.mode == 'NFM':
762
                _mem.channel_width = CHANNEL_WIDTH_12d5kHz
763
            else:
764
                LOG.error('%s: set_mem: unhandled mode: %s' % (
765
                    mem.name, mem.mode))
766

    
767
            # set the power level
768
            if mem.power == POWER_LEVELS[0]:
769
                _mem.txpower = TXPOWER_LOW
770
            elif mem.power == POWER_LEVELS[1]:
771
                _mem.txpower = TXPOWER_MED
772
            elif mem.power == POWER_LEVELS[2]:
773
                _mem.txpower = TXPOWER_LOW
774
            else:
775
                LOG.error('%s: set_mem: unhandled power level: %s' %
776
                          (mem.name, mem.power))
777

    
778
            # TODO set the CTCSS values
779
            # TODO support custom ctcss tones here
780
            # Default - tones off, carrier sql
781
            _mem.ctcss_encode_en = 0
782
            _mem.ctcss_decode_en = 0
783
            _mem.tone_squelch_en = 0
784
            _mem.ctcss_enc_tone = 0x00
785
            _mem.ctcss_dec_tone = 0x00
786
            _mem.customctcss = 0x00
787
            _mem.dtcs_encode_en = 0
788
            _mem.dtcs_encode_code_highbit = 0
789
            _mem.dtcs_encode_code = 0
790
            _mem.dtcs_encode_invert = 0
791
            _mem.dtcs_decode_en = 0
792
            _mem.dtcs_decode_code_highbit = 0
793
            _mem.dtcs_decode_code = 0
794
            _mem.dtcs_decode_invert = 0
795

    
796
            dtcs_pol_str_to_bit = {'N': 0, 'R': 1}
797
            _mem.dtcs_encode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[0]]
798
            _mem.dtcs_decode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[1]]
799

    
800
            if mem.tmode == 'Tone':
801
                _mem.ctcss_encode_en = 1
802
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
803
            elif mem.tmode == 'TSQL':
804
                _mem.ctcss_encode_en = 1
805
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.ctone)
806
                _mem.ctcss_decode_en = 1
807
                _mem.tone_squelch_en = 1
808
                _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
809
            elif mem.tmode == 'DTCS':
810
                _mem.dtcs_encode_en = 1
811
                _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
812
                    dtcs_code_val_to_bits(mem.rx_dtcs)
813
                _mem.dtcs_decode_en = 1
814
                _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
815
                    dtcs_code_val_to_bits(mem.rx_dtcs)
816
                _mem.tone_squelch_en = 1
817
            elif mem.tmode == 'Cross':
818
                txmode, rxmode = mem.cross_mode.split('->')
819

    
820
                if txmode == 'Tone':
821
                    _mem.ctcss_encode_en = 1
822
                    _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
823
                elif txmode == '':
824
                    pass
825
                elif txmode == 'DTCS':
826
                    _mem.dtcs_encode_en = 1
827
                    _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
828
                        dtcs_code_val_to_bits(mem.dtcs)
829
                else:
830
                    LOG.error('%s: unhandled cross TX mode: %s' % (
831
                        mem.name, mem.cross_mode))
832

    
833
                if rxmode == 'Tone':
834
                    _mem.ctcss_decode_en = 1
835
                    _mem.tone_squelch_en = 1
836
                    _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
837
                elif rxmode == '':
838
                    pass
839
                elif rxmode == 'DTCS':
840
                    _mem.dtcs_decode_en = 1
841
                    _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
842
                        dtcs_code_val_to_bits(mem.rx_dtcs)
843
                    _mem.tone_squelch_en = 1
844
                else:
845
                    LOG.error('%s: unhandled cross RX mode: %s' % (
846
                        mem.name, mem.cross_mode))
847
            else:
848
                LOG.error('%s: Unhandled tmode/cross %s/%s.' %
849
                          (mem.name, mem.tmode, mem.cross_mode))
850
            LOG.debug('%s: tmode=%s, cross=%s, rtone=%f, ctone=%f' % (
851
                mem.name, mem.tmode, mem.cross_mode, mem.rtone, mem.ctone))
852
            LOG.debug('%s: CENC=%d, CDEC=%d, t(enc)=%02x, t(dec)=%02x' % (
853
                mem.name,
854
                _mem.ctcss_encode_en,
855
                _mem.ctcss_decode_en,
856
                ctcss_code_val_to_bits(mem.rtone),
857
                ctcss_code_val_to_bits(mem.ctone)))
858

    
859
            # TODO set unknown defaults - hope that fixes Run time error 6,
860
            # overflow, from AT_778UV tool
861
            _mem.unknown1 = 0x00
862
            _mem.unknown6 = 0x00
863
            _mem.unknown7 = 0x00
864
            _mem.unknown8 = 0x00
865
            _mem.unknown9 = 0x00
866
            _mem.unknown10 = 0x00
867

    
868

    
869
if has_future:
870
    @directory.register
871
    class AnyTone778UV(AnyTone778UVBase):
872
        VENDOR = "AnyTone"
873
        MODEL = "778UV"
874
        # Allowed radio types is a dict keyed by model of a list of version
875
        # strings
876
        ALLOWED_RADIO_TYPES = {'AT778UV': ['V200']}
877

    
878
    @directory.register
879
    class RetevisRT95(AnyTone778UVBase):
880
        VENDOR = "Retevis"
881
        MODEL = "RT95"
882
        # Allowed radio types is a dict keyed by model of a list of version
883
        # strings
884
        ALLOWED_RADIO_TYPES = {'RT95': ['V100']}
885

    
886
    # This one is a guess based on a user supplied save file from the vendor
887
    # s/w
888
    @directory.register
889
    class CRTMicronUV(AnyTone778UVBase):
890
        VENDOR = "CRT"
891
        MODEL = "Micron UV"
892
        # Allowed radio types is a dict keyed by model of a list of version
893
        # strings
894
        ALLOWED_RADIO_TYPES = {'MICRON': ['V100']}
895

    
896
    # Don't know the radio ID string for this one yet, but suspect it's
897
    # similar, disabled for now.
898
    @directory.register
899
    class MidlandDBR2500(AnyTone778UVBase):
900
        VENDOR = "Midland"
901
        MODEL = "DBR2500"
902
        ALLOWED_RADIO_TYPES = {'DBR2500': ['V100']}
(3-3/10)