Project

General

Profile

New Model #6425 » 20200522_anytone778uv.py

Joe Milbourn, 05/22/2020 02:40 PM

 
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
TXPOWER_LOW = 0x00
101
TXPOWER_MED = 0x01
102
TXPOWER_HIGH = 0x02
103

    
104
DUPLEX_NOSPLIT = 0x00
105
DUPLEX_POSSPLIT = 0x01
106
DUPLEX_NEGSPLIT = 0x02
107
DUPLEX_ODDSPLIT = 0x03
108

    
109
CHANNEL_WIDTH_25kHz = 0x02
110
CHANNEL_WIDTH_20kHz = 0x01
111
CHANNEL_WIDTH_12d5kHz = 0x00
112

    
113
BUSY_CHANNEL_LOCKOUT_OFF = 0x00
114
BUSY_CHANNEL_LOCKOUT_REPEATER = 0x01
115
BUSY_CHANNEL_LOCKOUT_BUSY = 0x02
116

    
117
#ALLOWED_RADIO_TYPES = ['AT778UV\x01V200']
118

    
119
MEMORY_ADDRESS_RANGE = (0x0000, 0x3290)
120
MEMORY_RW_BLOCK_SIZE = 0x10
121
MEMORY_RW_BLOCK_CMD_SIZE = 0x16
122

    
123
POWER_LEVELS = [chirp_common.PowerLevel('Low', dBm=37),
124
                chirp_common.PowerLevel('Medium', dBm=40),
125
                chirp_common.PowerLevel('High', dBm=44)]
126

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

    
147
TONE_MAP_TONE_TO_VAL = {TONE_MAP_VAL_TO_TONE[val]: val
148
                        for val in TONE_MAP_VAL_TO_TONE}
149

    
150
TONES_EN_TXTONE = (1 << 3)
151
TONES_EN_RXTONE = (1 << 2)
152
TONES_EN_TXCODE = (1 << 1)
153
TONES_EN_RXCODE = (1 << 0)
154
TONES_EN_NO_TONE = 0
155

    
156

    
157
# Calculate the checksum used in serial packets
158
def checksum(message_bytes):
159
    mask = 0xFF
160
    checksum = 0
161
    for b in message_bytes:
162
        checksum = (checksum + b) & mask
163
    return checksum
164

    
165

    
166
# Send a command to the radio, return any reply stripping the echo of the
167
# command (tx and rx share a single pin in this radio)
168
def send_serial_command(serial, command, expectedlen=None):
169
    ''' send a command to the radio, and return any response.
170
    set expectedlen to return as soon as that many bytes are read.
171
    '''
172
    serial.write(command)
173
    serial.flush()
174

    
175
    response = b''
176
    tout = time.time() + 0.5
177
    while time.time() < tout:
178
        if serial.inWaiting():
179
            response += serial.read()
180
        # remember everything gets echo'd back
181
        if len(response) - len(command) == expectedlen:
182
            break
183

    
184
    # cut off what got echo'd back, we don't need to see it again
185
    if response.startswith(command):
186
        response = response[len(command):]
187

    
188
    return response
189

    
190

    
191
# return pretty printed hex and ascii representation of binary data
192
def reprdata(bindata):
193
    hexwidth = 60
194
    sepwidth = 4
195

    
196
    line = ''
197
    sepctr = 0
198
    for b in bytes(bindata):
199
        line += '%02x' % ord(b)
200
        sepctr += 1
201
        if sepctr == sepwidth:
202
            line += ' '
203
            sepctr = 0
204

    
205
    line += ' ' * (hexwidth - len(line))
206

    
207
    for b in bindata:
208
        if 0x21 <= ord(b) <= 0x7E:
209
            line += b
210
        else:
211
            line += '.'
212
    return line
213

    
214

    
215
# Check the radio version reported to see if it's one we support
216
# TODO extend this list, as I suspect there are other very similar radios
217
# like the RT95
218
def check_ver(ver_response, allowed_types):
219
    ''' Check the returned radio version is one we approve of '''
220
    ver = ver_response[1:-3]
221
    LOG.debug("ver_response = " + util.hexprint(ver_response))
222
    LOG.debug('radio version: %s' % ver)
223
    return ver in allowed_types
224

    
225

    
226
# Put the radio in programming mode, sending the initial command and checking
227
# the response.  raise RadioError if there is no response (500ms timeout), and
228
# if the returned version isn't matched by check_ver
229
def enter_program_mode(radio):
230
    serial = radio.pipe
231
    # place the radio in program mode, and confirm
232
    program_response = send_serial_command(serial, b'PROGRAM')
233

    
234
    if program_response != b'QX\x06':
235
        raise errors.RadioError('No initial response from radio.')
236
    LOG.debug('entered program mode')
237

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

    
241
    if not check_ver(ver_response, radio.ALLOWED_RADIO_TYPES):
242
        exit_program_mode(radio)
243
        raise errors.RadioError('Radio version not in allowed list: %s'
244
                                % util.hexprint(ver_response))
245

    
246

    
247
# Exit programming mode
248
def exit_program_mode(radio):
249
    send_serial_command(radio.pipe, b'END')
250

    
251

    
252
# Parse a packet from the radio returning the header (R/W, address, data, and
253
# checksum valid
254
def parse_read_response(resp):
255
    addr = resp[:4]
256
    data = bytes(resp[4:-2])
257
    cs = checksum(ord(d) for d in resp[1:-2])
258
    valid = cs == ord(resp[-2])
259
    if not valid:
260
        LOG.error('checksumfail: %02x, expected %02x' % (cs, ord(resp[-2])))
261
        LOG.error('msg data: %s' % util.hexprint(resp))
262
    return addr, data, valid
263

    
264

    
265
# Download data from the radio and populate the memory map
266
def do_download(radio):
267
    '''Download memories from the radio'''
268

    
269
    # Get the serial port connection
270
    serial = radio.pipe
271

    
272
    try:
273
        enter_program_mode(radio)
274

    
275
        memory_data = bytes()
276

    
277
        # status info for the UI
278
        status = chirp_common.Status()
279
        status.cur = 0
280
        status.max = (MEMORY_ADDRESS_RANGE[1] -
281
                      MEMORY_ADDRESS_RANGE[0])/MEMORY_RW_BLOCK_SIZE
282
        status.msg = 'Cloning from radio...'
283
        radio.status_fn(status)
284

    
285
        for addr in range(MEMORY_ADDRESS_RANGE[0],
286
                          MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
287
                          MEMORY_RW_BLOCK_SIZE):
288
            read_command = struct.pack('>BHB', 0x52, addr,
289
                                       MEMORY_RW_BLOCK_SIZE)
290
            read_response = send_serial_command(serial, read_command,
291
                                                MEMORY_RW_BLOCK_CMD_SIZE)
292
            # LOG.debug('read response:\n%s' % util.hexprint(read_response))
293

    
294
            address, data, valid = parse_read_response(read_response)
295
            memory_data += data
296

    
297
            # update UI
298
            status.cur = (addr - MEMORY_ADDRESS_RANGE[0])\
299
                / MEMORY_RW_BLOCK_SIZE
300
            radio.status_fn(status)
301

    
302
        exit_program_mode(radio)
303
    except errors.RadioError as e:
304
        raise e
305
    except Exception as e:
306
        raise errors.RadioError('Failed to download from radio: %s' % e)
307

    
308
    return memmap.MemoryMapBytes(memory_data)
309

    
310

    
311
# Build a write data command to send to the radio
312
def make_write_data_cmd(addr, data, datalen):
313
    cmd = struct.pack('>BHB', 0x57, addr, datalen)
314
    cmd += data
315
    cs = checksum(ord(c) for c in cmd[1:])
316
    cmd += struct.pack('>BB', cs, 0x06)
317
    return cmd
318

    
319

    
320
# Upload a memory map to the radio
321
def do_upload(radio):
322
    try:
323
        enter_program_mode(radio)
324

    
325
        serial = radio.pipe
326

    
327
        # send the initial message, radio responds with something that looks a
328
        # bit like a bitfield, but I don't know what it is yet.
329
        read_command = struct.pack('>BHB', 0x52, 0x3b10, MEMORY_RW_BLOCK_SIZE)
330
        read_response = send_serial_command(serial, read_command,
331
                                            MEMORY_RW_BLOCK_CMD_SIZE)
332
        address, data, valid = parse_read_response(read_response)
333
        LOG.debug('Got initial response from radio: %s' %
334
                  util.hexprint(read_response))
335

    
336
        bptr = 0
337

    
338
        memory_addrs = range(MEMORY_ADDRESS_RANGE[0],
339
                             MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
340
                             MEMORY_RW_BLOCK_SIZE)
341

    
342
        # status info for the UI
343
        status = chirp_common.Status()
344
        status.cur = 0
345
        status.max = len(memory_addrs)
346
        status.msg = 'Cloning to radio...'
347
        radio.status_fn(status)
348

    
349
        for idx, addr in enumerate(memory_addrs):
350
            write_command = make_write_data_cmd(
351
                addr, radio._mmap[bptr:bptr+MEMORY_RW_BLOCK_SIZE],
352
                MEMORY_RW_BLOCK_SIZE)
353
            # LOG.debug('write data:\n%s' % util.hexprint(write_command))
354
            write_response = send_serial_command(serial, write_command, 0x01)
355
            bptr += MEMORY_RW_BLOCK_SIZE
356

    
357
            if write_response == '\x0a':
358
                # NACK from radio, e.g. checksum wrongn
359
                LOG.debug('Radio returned 0x0a - NACK:')
360
                LOG.debug(' * write cmd:\n%s' % util.hexprint(write_command))
361
                LOG.debug(' * write response:\n%s' %
362
                          util.hexprint(write_response))
363
                exit_program_mode(radio)
364
                raise errors.RadioError('Radio NACK\'d write command')
365

    
366
            # update UI
367
            status.cur = idx
368
            radio.status_fn(status)
369
        exit_program_mode(radio)
370
    except errors.RadioError:
371
        raise
372
    except Exception as e:
373
        raise errors.RadioError('Failed to download from radio: %s' % e)
374

    
375

    
376
# Get the value of @bitfield @number of bits in from 0
377
def get_bitfield(bitfield, number):
378
    ''' Get the value of @bitfield @number of bits in '''
379
    byteidx = number//8
380
    bitidx = number - (byteidx * 8)
381
    return bitfield[byteidx] & (1 << bitidx)
382

    
383

    
384
# Set the @value of @bitfield @number of bits in from 0
385
def set_bitfield(bitfield, number, value):
386
    ''' Set the @value of @bitfield @number of bits in '''
387
    byteidx = number//8
388
    bitidx = number - (byteidx * 8)
389
    if value is True:
390
        bitfield[byteidx] |= (1 << bitidx)
391
    else:
392
        bitfield[byteidx] &= ~(1 << bitidx)
393
    return bitfield
394

    
395

    
396
# Translate the radio's version of a code as stored to a real code
397
def dtcs_code_bits_to_val(highbit, lowbyte):
398
    return chirp_common.ALL_DTCS_CODES[highbit*256 + lowbyte]
399

    
400

    
401
# Translate the radio's version of a tone as stored to a real tone
402
def ctcss_tone_bits_to_val(tone_byte):
403
    # TODO use the custom setting 0x33 and ref the custom ctcss
404
    # field
405
    tone_byte = int(tone_byte)
406
    if tone_byte in TONE_MAP_VAL_TO_TONE:
407
        return TONE_MAP_VAL_TO_TONE[tone_byte]
408
    elif tone_byte == TONE_CUSTOM_CTCSS:
409
        LOG.info('custom ctcss not implemented (yet?).')
410
    else:
411
        raise errors.UnsupportedToneError('unknown ctcss tone value: %02x' %
412
                                          tone_byte)
413

    
414

    
415
# Translate a real tone to the radio's version as stored
416
def ctcss_code_val_to_bits(tone_value):
417
    if tone_value in TONE_MAP_TONE_TO_VAL:
418
        return TONE_MAP_TONE_TO_VAL[tone_value]
419
    else:
420
        raise errors.UnsupportedToneError('Tone %f not supported' % tone_value)
421

    
422

    
423
# Translate a real code to the radio's version as stored
424
def dtcs_code_val_to_bits(code):
425
    val = chirp_common.ALL_DTCS_CODES.index(code)
426
    return (val & 0xFF), ((val >> 8) & 0x01)
427

    
428

    
429
class AnyTone778UVBase(chirp_common.CloneModeRadio,
430
                       chirp_common.ExperimentalRadio):
431
    '''AnyTone 778UV and probably Retivis RT95 and others'''
432
    BAUD_RATE = 9600    # Replace this with your baud rate
433

    
434
    @classmethod
435
    def get_prompts(cls):
436
        rp = chirp_common.RadioPrompts()
437

    
438
        rp.experimental = \
439
            ('This is experimental support for the %s %s.  '
440
             'Please send in bug and enhancement requests!' %
441
             (cls.VENDOR, cls.MODEL))
442

    
443
        return rp
444

    
445
    # Return information about this radio's features, including
446
    # how many memories it has, what bands it supports, etc
447
    def get_features(self):
448
        rf = chirp_common.RadioFeatures()
449
        rf.has_bank = False
450
        rf.has_settings = False
451
        rf.can_odd_split = True
452
        rf.has_name = True
453
        rf.has_offset = True
454
        rf.valid_name_length = 5
455
        rf.valid_duplexes = ['', '+', '-', 'split']
456

    
457
        rf.has_dtcs = True
458
        rf.has_rx_dtcs = True
459
        rf.has_dtcs_polarity = True
460
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES
461
        rf.has_ctone = True
462
        rf.has_cross = True
463
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
464
        rf.valid_cross_modes = ['Tone->Tone',
465
                                'Tone->DTCS',
466
                                'DTCS->Tone',
467
                                'DTCS->DTCS',
468
                                'DTCS->',
469
                                '->DTCS',
470
                                '->Tone']
471

    
472
        rf.memory_bounds = (0, 199)  # This radio supports memories 0-199
473
        rf.valid_bands = [(144000000, 148000000),  # Supports 2-meters
474
                          (430000000, 450000000),  # Supports 70-centimeters
475
                          ]
476
        rf.valid_modes = ['FM', 'NFM']
477
        rf.valid_power_levels = POWER_LEVELS
478
        rf.valid_tuning_steps = [2.5, 5, 6.25, 10, 12.5, 20, 25, 30, 50]
479
        return rf
480

    
481
    # Do a download of the radio from the serial port
482
    def sync_in(self):
483
        self._mmap = do_download(self)
484
        self.process_mmap()
485

    
486
    # Do an upload of the radio to the serial port
487
    def sync_out(self):
488
        do_upload(self)
489

    
490
    # Convert the raw byte array into a memory object structure
491
    def process_mmap(self):
492
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
493

    
494
    # Return a raw representation of the memory object, which
495
    # is very helpful for development
496
    def get_raw_memory(self, number):
497
        return repr(self._memobj.memory[number])
498

    
499
    # Extract a high-level memory object from the low-level memory map
500
    # This is called to populate a memory in the UI
501
    def get_memory(self, number):
502
        # Get a low-level memory object mapped to the image
503
        _mem = self._memobj.memory[number]
504
        _mem_status = self._memobj.memory_status
505

    
506
        # Create a high-level memory object to return to the UI
507
        mem = chirp_common.Memory()
508
        mem.number = number                 # Set the memory number
509

    
510
        # Check if this memory is present in the occupied list
511
        mem.empty = get_bitfield(_mem_status.occupied_bitfield, number) == 0
512

    
513
        if not mem.empty:
514
            # Check if this memory is in the scan enabled list
515
            mem.skip = ''
516
            if get_bitfield(_mem_status.scan_enabled_bitfield, number) == 0:
517
                mem.skip = 'S'
518

    
519
            # set the name
520
            mem.name = str(_mem.name).rstrip()  # Set the alpha tag
521

    
522
            # Convert your low-level frequency and offset to Hertz
523
            mem.freq = int(_mem.freq) * 10
524
            mem.offset = int(_mem.offset) * 10
525

    
526
            # Set the duplex flags
527
            if _mem.duplex == DUPLEX_POSSPLIT:
528
                mem.duplex = '+'
529
            elif _mem.duplex == DUPLEX_NEGSPLIT:
530
                mem.duplex = '-'
531
            elif _mem.duplex == DUPLEX_NOSPLIT:
532
                mem.duplex = ''
533
            elif _mem.duplex == DUPLEX_ODDSPLIT:
534
                mem.duplex = 'split'
535
            else:
536
                LOG.error('%s: get_mem: unhandled duplex: %02x' %
537
                          (mem.name, _mem.duplex))
538

    
539
            # Set the channel width
540
            if _mem.channel_width == CHANNEL_WIDTH_25kHz:
541
                mem.mode = 'FM'
542
            elif _mem.channel_width == CHANNEL_WIDTH_20kHz:
543
                LOG.info(
544
                    '%s: get_mem: promoting 20kHz channel width to 25kHz' %
545
                    mem.name)
546
                mem.mode = 'FM'
547
            elif _mem.channel_width == CHANNEL_WIDTH_12d5kHz:
548
                mem.mode = 'NFM'
549
            else:
550
                LOG.error('%s: get_mem: unhandled channel width: 0x%02x' %
551
                          (mem.name, _mem.channel_width))
552

    
553
            # set the power level
554
            if _mem.txpower == TXPOWER_LOW:
555
                mem.power = POWER_LEVELS[0]
556
            elif _mem.txpower == TXPOWER_MED:
557
                mem.power = POWER_LEVELS[1]
558
            elif _mem.txpower == TXPOWER_HIGH:
559
                mem.power = POWER_LEVELS[2]
560
            else:
561
                LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
562
                          (mem.name, _mem.txpower))
563

    
564
            # CTCSS Tones
565
            # TODO support custom ctcss tones here
566
            txtone = None
567
            rxtone = None
568
            rxcode = None
569
            txcode = None
570

    
571
            # check if dtcs tx is enabled
572
            if _mem.dtcs_encode_en:
573
                txcode = dtcs_code_bits_to_val(_mem.dtcs_encode_code_highbit,
574
                                     _mem.dtcs_encode_code)
575

    
576
            # check if dtcs rx is enabled
577
            if _mem.dtcs_decode_en:
578
                rxcode = dtcs_code_bits_to_val(_mem.dtcs_decode_code_highbit,
579
                                     _mem.dtcs_decode_code)
580

    
581
            if txcode is not None:
582
                LOG.debug('%s: get_mem dtcs_enc: %d' % (mem.name, txcode))
583
            if rxcode is not None:
584
                LOG.debug('%s: get_mem dtcs_dec: %d' % (mem.name, rxcode))
585

    
586
            # tsql set if radio squelches on tone
587
            tsql = _mem.tone_squelch_en
588

    
589
            # check if ctcss tx is enabled
590
            if _mem.ctcss_encode_en:
591
                txtone = ctcss_tone_bits_to_val(_mem.ctcss_enc_tone)
592

    
593
            # check if ctcss rx is enabled
594
            if _mem.ctcss_decode_en:
595
                rxtone = ctcss_tone_bits_to_val(_mem.ctcss_dec_tone)
596

    
597
            # Define this here to allow a readable if-else tree enabling tone
598
            # options
599
            enabled = 0
600
            enabled |= (txtone is not None) * TONES_EN_TXTONE
601
            enabled |= (rxtone is not None) * TONES_EN_RXTONE
602
            enabled |= (txcode is not None) * TONES_EN_TXCODE
603
            enabled |= (rxcode is not None) * TONES_EN_RXCODE
604

    
605
            # Add some debugging output for the tone bitmap
606
            enstr = []
607
            if enabled & TONES_EN_TXTONE:
608
                enstr += ['TONES_EN_TXTONE']
609
            if enabled & TONES_EN_RXTONE:
610
                enstr += ['TONES_EN_RXTONE']
611
            if enabled & TONES_EN_TXCODE:
612
                enstr += ['TONES_EN_TXCODE']
613
            if enabled & TONES_EN_RXCODE:
614
                enstr += ['TONES_EN_RXCODE']
615
            if enabled == 0:
616
                enstr = ['TONES_EN_NOTONE']
617
            LOG.debug('%s: enabled = %s' % (
618
                mem.name, '|'.join(enstr)))
619

    
620
            mem.tmode = ''
621
            if enabled == TONES_EN_NO_TONE:
622
                mem.tmode = ''
623
            elif enabled == TONES_EN_TXTONE:
624
                mem.tmode = 'Tone'
625
                mem.rtone = txtone
626
            elif enabled == TONES_EN_RXTONE and tsql:
627
                mem.tmode = 'Cross'
628
                mem.cross_mode = '->Tone'
629
                mem.ctone = rxtone
630
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXTONE) and tsql:
631
                if txtone == rxtone:  # TSQL
632
                    mem.tmode = 'TSQL'
633
                    mem.ctone = txtone
634
                else:  # Tone->Tone
635
                    mem.tmode = 'Cross'
636
                    mem.cross_mode = 'Tone->Tone'
637
                    mem.ctone = rxtone
638
                    mem.rtone = txtone
639
            elif enabled == TONES_EN_TXCODE:
640
                mem.tmode = 'Cross'
641
                mem.cross_mode = 'DTCS->'
642
                mem.dtcs = txcode
643
            elif enabled == TONES_EN_RXCODE and tsql:
644
                mem.tmode = 'Cross'
645
                mem.cross_mode = '->DTCS'
646
                mem.rx_dtcs = rxcode
647
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXCODE) and tsql:
648
                if rxcode == txcode:
649
                    mem.tmode = 'DTCS'
650
                    mem.rx_dtcs = rxcode
651
                else:
652
                    mem.tmode = 'Cross'
653
                    mem.cross_mode = 'DTCS->DTCS'
654
                    mem.rx_dtcs = rxcode
655
                    mem.dtcs = txcode
656
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXTONE) and tsql:
657
                mem.tmode = 'Cross'
658
                mem.cross_mode = 'DTCS->Tone'
659
                mem.dtcs = txcode
660
                mem.ctone = rxtone
661
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXCODE) and tsql:
662
                mem.tmode = 'Cross'
663
                mem.cross_mode = 'Tone->DTCS'
664
                mem.rx_dtcs = rxcode
665
                mem.rtone = txtone
666
            else:
667
                LOG.error('%s: Unhandled tmode enabled = %d.' % (
668
                    mem.name, enabled))
669

    
670
            # set the dtcs polarity
671
            dtcs_pol_bit_to_str = {0: 'N', 1: 'R'}
672
            mem.dtcs_polarity = '%s%s' %\
673
                (dtcs_pol_bit_to_str[_mem.dtcs_encode_invert == 1],
674
                 dtcs_pol_bit_to_str[_mem.dtcs_decode_invert == 1])
675

    
676
        return mem
677

    
678
    # Store details about a high-level memory to the memory map
679
    # This is called when a user edits a memory in the UI
680
    def set_memory(self, mem):
681
        # Get a low-level memory object mapped to the image
682
        _mem = self._memobj.memory[mem.number]
683
        _mem_status = self._memobj.memory_status
684

    
685
        # set the occupied bitfield
686
        _mem_status.occupied_bitfield = \
687
            set_bitfield(_mem_status.occupied_bitfield, mem.number,
688
                         not mem.empty)
689

    
690
        # set the scan add bitfield
691
        _mem_status.scan_enabled_bitfield = \
692
            set_bitfield(_mem_status.scan_enabled_bitfield, mem.number,
693
                         (not mem.empty) and (mem.skip != 'S'))
694

    
695
        if mem.empty:
696
            # Set the whole memory to 0xff
697
            _mem.set_raw('\xff' * (_mem.size() / 8))
698
        else:
699
            _mem.set_raw('\x00' * (_mem.size() / 8))
700

    
701
            _mem.freq = int(mem.freq / 10)
702
            _mem.offset = int(mem.offset / 10)
703

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

    
706
            # TODO support busy channel lockout - disabled for now
707
            _mem.busy_channel_lockout = BUSY_CHANNEL_LOCKOUT_OFF
708

    
709
            # Set duplex bitfields
710
            if mem.duplex == '+':
711
                _mem.duplex = DUPLEX_POSSPLIT
712
            elif mem.duplex == '-':
713
                _mem.duplex = DUPLEX_NEGSPLIT
714
            elif mem.duplex == '':
715
                _mem.duplex = DUPLEX_NOSPLIT
716
            elif mem.duplex == 'split':
717
                # TODO: this is an unverified punt!
718
                _mem.duplex = DUPLEX_ODDSPLIT
719
            else:
720
                LOG.error('%s: set_mem: unhandled duplex: %s' %
721
                          (mem.name, mem.duplex))
722

    
723
            # Set the channel width - remember we promote 20kHz channels to FM
724
            # on import, so don't handle them here
725
            if mem.mode == 'FM':
726
                _mem.channel_width = CHANNEL_WIDTH_25kHz
727
            elif mem.mode == 'NFM':
728
                _mem.channel_width = CHANNEL_WIDTH_12d5kHz
729
            else:
730
                LOG.error('%s: set_mem: unhandled mode: %s' % (
731
                    mem.name, mem.mode))
732

    
733
            # set the power level
734
            if mem.power == POWER_LEVELS[0]:
735
                _mem.txpower = TXPOWER_LOW
736
            elif mem.power == POWER_LEVELS[1]:
737
                _mem.txpower = TXPOWER_MED
738
            elif mem.power == POWER_LEVELS[2]:
739
                _mem.txpower = TXPOWER_LOW
740
            else:
741
                LOG.error('%s: set_mem: unhandled power level: %s' %
742
                          (mem.name, mem.power))
743

    
744
            # TODO set the CTCSS values
745
            # TODO support custom ctcss tones here
746
            # Default - tones off, carrier sql
747
            _mem.ctcss_encode_en = 0
748
            _mem.ctcss_decode_en = 0
749
            _mem.tone_squelch_en = 0
750
            _mem.ctcss_enc_tone = 0x00
751
            _mem.ctcss_dec_tone = 0x00
752
            _mem.customctcss = 0x00
753
            _mem.dtcs_encode_en = 0
754
            _mem.dtcs_encode_code_highbit = 0
755
            _mem.dtcs_encode_code = 0
756
            _mem.dtcs_encode_invert = 0
757
            _mem.dtcs_decode_en = 0
758
            _mem.dtcs_decode_code_highbit = 0
759
            _mem.dtcs_decode_code = 0
760
            _mem.dtcs_decode_invert = 0
761

    
762
            dtcs_pol_str_to_bit = {'N': 0, 'R': 1}
763
            _mem.dtcs_encode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[0]]
764
            _mem.dtcs_decode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[1]]
765

    
766
            if mem.tmode == 'Tone':
767
                _mem.ctcss_encode_en = 1
768
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
769
            elif mem.tmode == 'TSQL':
770
                _mem.ctcss_encode_en = 1
771
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.ctone)
772
                _mem.ctcss_decode_en = 1
773
                _mem.tone_squelch_en = 1
774
                _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
775
            elif mem.tmode == 'DTCS':
776
                _mem.dtcs_encode_en = 1
777
                _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
778
                    dtcs_code_val_to_bits(mem.rx_dtcs)
779
                _mem.dtcs_decode_en = 1
780
                _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
781
                    dtcs_code_val_to_bits(mem.rx_dtcs)
782
                _mem.tone_squelch_en = 1
783
            elif mem.tmode == 'Cross':
784
                txmode, rxmode = mem.cross_mode.split('->')
785

    
786
                if txmode == 'Tone':
787
                    _mem.ctcss_encode_en = 1
788
                    _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
789
                elif txmode == '':
790
                    pass
791
                elif txmode == 'DTCS':
792
                    _mem.dtcs_encode_en = 1
793
                    _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
794
                        dtcs_code_val_to_bits(mem.dtcs)
795
                else:
796
                    LOG.error('%s: unhandled cross TX mode: %s' % (
797
                        mem.name, mem.cross_mode))
798

    
799
                if rxmode == 'Tone':
800
                    _mem.ctcss_decode_en = 1
801
                    _mem.tone_squelch_en = 1
802
                    _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
803
                elif rxmode == '':
804
                    pass
805
                elif rxmode == 'DTCS':
806
                    _mem.dtcs_decode_en = 1
807
                    _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
808
                        dtcs_code_val_to_bits(mem.rx_dtcs)
809
                    _mem.tone_squelch_en = 1
810
                else:
811
                    LOG.error('%s: unhandled cross RX mode: %s' % (
812
                        mem.name, mem.cross_mode))
813
            else:
814
                LOG.error('%s: Unhandled tmode/cross %s/%s.' %
815
                          (mem.name, mem.tmode, mem.cross_mode))
816
            LOG.debug('%s: tmode=%s, cross=%s, rtone=%f, ctone=%f' % (
817
                mem.name, mem.tmode, mem.cross_mode, mem.rtone, mem.ctone))
818
            LOG.debug('%s: CENC=%d, CDEC=%d, t(enc)=%02x, t(dec)=%02x' % (
819
                mem.name,
820
                _mem.ctcss_encode_en,
821
                _mem.ctcss_decode_en,
822
                ctcss_code_val_to_bits(mem.rtone),
823
                ctcss_code_val_to_bits(mem.ctone)))
824

    
825
            # TODO set unknown defaults - hope that fixes Run time error 6,
826
            # overflow, from AT_778UV tool
827
            _mem.unknown1 = 0x00
828
            _mem.unknown6 = 0x00
829
            _mem.unknown7 = 0x00
830
            _mem.unknown8 = 0x00
831
            _mem.unknown9 = 0x00
832
            _mem.unknown10 = 0x00
833

    
834

    
835
if has_future:
836
    @directory.register
837
    class AnyTone778UV(AnyTone778UVBase):
838
        VENDOR = "AnyTone"
839
        MODEL = "778UV"
840
        ALLOWED_RADIO_TYPES = ['AT778UV\x01V200']
841

    
842
    @directory.register
843
    class RetevisRT95(AnyTone778UVBase):
844
        VENDOR = "Retevis"
845
        MODEL = "RT95"
846
        ALLOWED_RADIO_TYPES = [b'RT95\x00\x00\x00\x01V100']
847

    
848
    @directory.register
849
    class CRTMicronUV(AnyTone778UVBase):
850
        VENDOR = "CRT"
851
        MODEL = "Micron UV"
852
        ALLOWED_RADIO_TYPES = [b'MICRON\x00\x01V100']
(3-3/6)