Project

General

Profile

New Model #8859 » RetevisRT95-P.py

AJS QUIDZ, 03/07/2021 06:18 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
# TODO use the band field from ver_response
17
# TODO handle radio settings
18
#
19
# Supported features
20
# * Read and write memory access for 200 normal memories
21
# * CTCSS and DTCS for transmit and receive
22
# * Scan list
23
# * Tx off
24
# * Duplex (+ve, -ve, odd, and off splits)
25
# * Transmit power
26
# * Channel width (25kHz and 12.5kHz)
27
# * Retevis RT95, CRT Micron UV, and Midland DBR2500 radios
28
# * Full range of frequencies for tx and rx, supported band read from radio
29
#   during download, not verified on upload.  Radio will refuse to TX if out of
30
#   band.
31
#
32
# Unsupported features
33
# * VFO1, VFO2, and TRF memories
34
# * custom CTCSS tones
35
# * Any non-memory radio settings
36
# * Reverse, talkaround, scramble
37
# * busy channel lock out
38
# * probably other things too - like things encoded by the unknown bits in the
39
#   memory struct
40

    
41
from chirp import chirp_common, directory, memmap, errors, util
42
from chirp import bitwise
43

    
44
import struct
45
import time
46
import logging
47

    
48
LOG = logging.getLogger(__name__)
49

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

    
61

    
62
# Here is where we define the memory map for the radio. Since
63
# We often just know small bits of it, we can use #seekto to skip
64
# around as needed.
65

    
66
MEM_FORMAT = '''
67
#seekto 0x0000;
68
struct {
69
  bbcd freq[4];
70
  bbcd offset[4];
71
  u8 unknown1;
72
  u8 talkaround:1,
73
     scramble:1,
74
     unknown:2,
75
     txpower:2,
76
     duplex:2;
77
  u8 unknown_bits1:4,
78
     channel_width:2,
79
     reverse:1,
80
     tx_off:1;
81
  u8 unknown_bits2:4,
82
     dtcs_decode_en:1,
83
     ctcss_decode_en:1,
84
     dtcs_encode_en:1,
85
     ctcss_encode_en:1;
86
  u8 ctcss_dec_tone;
87
  u8 ctcss_enc_tone;
88
  u8 dtcs_decode_code;
89
  u8 unknown_bits6:6,
90
     dtcs_decode_invert:1,
91
     dtcs_decode_code_highbit:1;
92
  u8 dtcs_encode_code;
93
  u8 unknown_bits7:6,
94
     dtcs_encode_invert:1,
95
     dtcs_encode_code_highbit:1;
96
  u8 unknown_bits4:6,
97
     busy_channel_lockout:2;
98
  u8 unknown6;
99
  u8 unknown_bits5:7,
100
     tone_squelch_en:1;
101
  u8 unknown7;
102
  u8 unknown8;
103
  u8 unknown9;
104
  u8 unknown10;
105
  char name[5];
106
  ul16 customctcss;
107
} memory[200];
108
#seekto 0x1940;
109
struct {
110
  u8 occupied_bitfield[32];
111
  u8 scan_enabled_bitfield[32];
112
} memory_status;
113
#seekto 0x3260;
114
struct {
115
  u8 vfoa_current_channel; // 0
116
  u8 unknown1;
117
  u8 unknown2;
118
  u8 unknown3;
119
  u8 unknown4;
120
  u8 unknown5;
121
  u8 unknown6;
122
  u8 scan_channel;        // 7
123
  u8 unknown8_0:4,     // 8
124
     scan_active:1,
125
     unknown8_1:3;
126
  u8 unknown9;
127
  u8 unknowna;
128
  u8 unknownb;
129
  u8 unknownc;
130
  u8 bandlimit;       // d
131
  u8 unknownd;
132
  u8 unknowne;
133
  u8 unknownf;
134
} radio_settings;
135
'''
136

    
137
# Format for the version messages returned by the radio
138
VER_FORMAT = '''
139
u8 hdr;
140
char model[7];
141
u8 bandlimit;
142
char version[6];
143
u8 ack;
144
'''
145

    
146
TXPOWER_LOW = 0x00
147
TXPOWER_MED = 0x01
148
TXPOWER_HIGH = 0x02
149

    
150
DUPLEX_NOSPLIT = 0x00
151
DUPLEX_POSSPLIT = 0x01
152
DUPLEX_NEGSPLIT = 0x02
153
DUPLEX_ODDSPLIT = 0x03
154

    
155
CHANNEL_WIDTH_25kHz = 0x02
156
CHANNEL_WIDTH_20kHz = 0x01
157
CHANNEL_WIDTH_12d5kHz = 0x00
158

    
159
BUSY_CHANNEL_LOCKOUT_OFF = 0x00
160
BUSY_CHANNEL_LOCKOUT_REPEATER = 0x01
161
BUSY_CHANNEL_LOCKOUT_BUSY = 0x02
162

    
163
MEMORY_ADDRESS_RANGE = (0x0000, 0x3290)
164
MEMORY_RW_BLOCK_SIZE = 0x10
165
MEMORY_RW_BLOCK_CMD_SIZE = 0x16
166

    
167
POWER_LEVELS = [chirp_common.PowerLevel('Low', dBm=37),
168
                chirp_common.PowerLevel('Medium', dBm=40),
169
                chirp_common.PowerLevel('High', dBm=44)]
170

    
171
# CTCSS Tone definitions
172
TONE_CUSTOM_CTCSS = 0x33
173
TONE_MAP_VAL_TO_TONE = {0x00: 62.5, 0x01: 67.0, 0x02: 69.3,
174
                        0x03: 71.9, 0x04: 74.4, 0x05: 77.0,
175
                        0x06: 79.7, 0x07: 82.5, 0x08: 85.4,
176
                        0x09: 88.5, 0x0a: 91.5, 0x0b: 94.8,
177
                        0x0c: 97.4, 0x0d: 100.0, 0x0e: 103.5,
178
                        0x0f: 107.2, 0x10: 110.9, 0x11: 114.8,
179
                        0x12: 118.8, 0x13: 123.0, 0x14: 127.3,
180
                        0x15: 131.8, 0x16: 136.5, 0x17: 141.3,
181
                        0x18: 146.2, 0x19: 151.4, 0x1a: 156.7,
182
                        0x1b: 159.8, 0x1c: 162.2, 0x1d: 165.5,
183
                        0x1e: 167.9, 0x1f: 171.3, 0x20: 173.8,
184
                        0x21: 177.3, 0x22: 179.9, 0x23: 183.5,
185
                        0x24: 186.2, 0x25: 189.9, 0x26: 192.8,
186
                        0x27: 196.6, 0x28: 199.5, 0x29: 203.5,
187
                        0x2a: 206.5, 0x2b: 210.7, 0x2c: 218.1,
188
                        0x2d: 225.7, 0x2e: 229.1, 0x2f: 233.6,
189
                        0x30: 241.8, 0x31: 250.3, 0x32: 254.1}
190

    
191
TONE_MAP_TONE_TO_VAL = {TONE_MAP_VAL_TO_TONE[val]: val
192
                        for val in TONE_MAP_VAL_TO_TONE}
193

    
194
TONES_EN_TXTONE = (1 << 3)
195
TONES_EN_RXTONE = (1 << 2)
196
TONES_EN_TXCODE = (1 << 1)
197
TONES_EN_RXCODE = (1 << 0)
198
TONES_EN_NO_TONE = 0
199

    
200
# Radio supports upper case and symbols
201
CHARSET_ASCII_PLUS = chirp_common.CHARSET_UPPER_NUMERIC + '- '
202

    
203
# Band limits as defined by the band byte in ver_response, defined in Hz, for
204
# VHF and UHF, used for RX and TX.
205
BAND_LIMITS = {0x00: [(144000000, 148000000), (430000000, 440000000)],
206
               0x01: [(136000000, 174000000), (400000000, 490000000)],
207
               0x02: [(144000000, 146000000), (430000000, 440000000)]}
208

    
209

    
210
# Get band limits from a band limit value
211
def get_band_limits_Hz(limit_value):
212
    if limit_value not in BAND_LIMITS:
213
        limit_value = 0x01
214
        LOG.warning('Unknown band limit value 0x%02x, default to 0x01')
215
    bandlimitfrequencies = BAND_LIMITS[limit_value]
216
    return bandlimitfrequencies
217

    
218

    
219
# Calculate the checksum used in serial packets
220
def checksum(message_bytes):
221
    mask = 0xFF
222
    checksum = 0
223
    for b in message_bytes:
224
        checksum = (checksum + b) & mask
225
    return checksum
226

    
227

    
228
# Send a command to the radio, return any reply stripping the echo of the
229
# command (tx and rx share a single pin in this radio)
230
def send_serial_command(serial, command, expectedlen=None):
231
    ''' send a command to the radio, and return any response.
232
    set expectedlen to return as soon as that many bytes are read.
233
    '''
234
    serial.write(command)
235
    serial.flush()
236

    
237
    response = b''
238
    tout = time.time() + 0.5
239
    while time.time() < tout:
240
        if serial.inWaiting():
241
            response += serial.read()
242
        # remember everything gets echo'd back
243
        if len(response) - len(command) == expectedlen:
244
            break
245

    
246
    # cut off what got echo'd back, we don't need to see it again
247
    if response.startswith(command):
248
        response = response[len(command):]
249

    
250
    return response
251

    
252

    
253
# strip trailing 0x00 to convert a string returned by bitwise.parse into a
254
# python string
255
def cstring_to_py_string(cstring):
256
    return "".join(c for c in cstring if c != '\x00')
257

    
258

    
259
# Check the radio version reported to see if it's one we support,
260
# returns bool version supported, and the band index
261
def check_ver(ver_response, allowed_types):
262
    ''' Check the returned radio version is one we approve of '''
263

    
264
    LOG.debug('ver_response = ')
265
    LOG.debug(util.hexprint(ver_response))
266

    
267
    resp = bitwise.parse(VER_FORMAT, ver_response)
268
    verok = False
269

    
270
    if resp.hdr == 0x49 and resp.ack == 0x06:
271
        model, version = [cstring_to_py_string(bitwise.get_string(s)).strip()
272
                          for s in (resp.model, resp.version)]
273
        LOG.debug('radio model: \'%s\' version: \'%s\'' %
274
                  (model, version))
275
        LOG.debug('allowed_types = %s' % allowed_types)
276

    
277
        if model in allowed_types:
278
            LOG.debug('model in allowed_types')
279

    
280
            if version in allowed_types[model]:
281
                LOG.debug('version in allowed_types[model]')
282
                verok = True
283
    else:
284
        raise errors.RadioError('Failed to parse version response')
285

    
286
    return verok, int(resp.bandlimit)
287

    
288

    
289
# Put the radio in programming mode, sending the initial command and checking
290
# the response.  raise RadioError if there is no response (500ms timeout), and
291
# if the returned version isn't matched by check_ver
292
def enter_program_mode(radio):
293
    serial = radio.pipe
294
    # place the radio in program mode, and confirm
295
    program_response = send_serial_command(serial, b'PROGRAM')
296

    
297
    if program_response != b'QX\x06':
298
        raise errors.RadioError('No initial response from radio.')
299
    LOG.debug('entered program mode')
300

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

    
304
    verok, bandlimit = check_ver(ver_response, radio.ALLOWED_RADIO_TYPES)
305
    if not verok:
306
        exit_program_mode(radio)
307
        raise errors.RadioError(
308
            'Radio version not in allowed list for %s-%s: %s' %
309
            (radio.VENDOR, radio.MODEL, util.hexprint(ver_response)))
310

    
311
    return bandlimit
312

    
313

    
314
# Exit programming mode
315
def exit_program_mode(radio):
316
    send_serial_command(radio.pipe, b'END')
317

    
318

    
319
# Parse a packet from the radio returning the header (R/W, address, data, and
320
# checksum valid
321
def parse_read_response(resp):
322
    addr = resp[:4]
323
    data = bytes(resp[4:-2])
324
    cs = checksum(ord(d) for d in resp[1:-2])
325
    valid = cs == ord(resp[-2])
326
    if not valid:
327
        LOG.error('checksumfail: %02x, expected %02x' % (cs, ord(resp[-2])))
328
        LOG.error('msg data: %s' % util.hexprint(resp))
329
    return addr, data, valid
330

    
331

    
332
# Download data from the radio and populate the memory map
333
def do_download(radio):
334
    '''Download memories from the radio'''
335

    
336
    # Get the serial port connection
337
    serial = radio.pipe
338

    
339
    try:
340
        enter_program_mode(radio)
341

    
342
        memory_data = bytes()
343

    
344
        # status info for the UI
345
        status = chirp_common.Status()
346
        status.cur = 0
347
        status.max = (MEMORY_ADDRESS_RANGE[1] -
348
                      MEMORY_ADDRESS_RANGE[0])/MEMORY_RW_BLOCK_SIZE
349
        status.msg = 'Cloning from radio...'
350
        radio.status_fn(status)
351

    
352
        for addr in range(MEMORY_ADDRESS_RANGE[0],
353
                          MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
354
                          MEMORY_RW_BLOCK_SIZE):
355
            read_command = struct.pack('>BHB', 0x52, addr,
356
                                       MEMORY_RW_BLOCK_SIZE)
357
            read_response = send_serial_command(serial, read_command,
358
                                                MEMORY_RW_BLOCK_CMD_SIZE)
359
            # LOG.debug('read response:\n%s' % util.hexprint(read_response))
360

    
361
            address, data, valid = parse_read_response(read_response)
362
            memory_data += data
363

    
364
            # update UI
365
            status.cur = (addr - MEMORY_ADDRESS_RANGE[0])\
366
                / MEMORY_RW_BLOCK_SIZE
367
            radio.status_fn(status)
368

    
369
        exit_program_mode(radio)
370
    except errors.RadioError as e:
371
        raise e
372
    except Exception as e:
373
        raise errors.RadioError('Failed to download from radio: %s' % e)
374

    
375
    return memmap.MemoryMapBytes(memory_data)
376

    
377

    
378
# Build a write data command to send to the radio
379
def make_write_data_cmd(addr, data, datalen):
380
    cmd = struct.pack('>BHB', 0x57, addr, datalen)
381
    cmd += data
382
    cs = checksum(ord(c) for c in cmd[1:])
383
    cmd += struct.pack('>BB', cs, 0x06)
384
    return cmd
385

    
386

    
387
# Upload a memory map to the radio
388
def do_upload(radio):
389
    try:
390
        bandlimit = enter_program_mode(radio)
391

    
392
        if bandlimit != radio._memobj.radio_settings.bandlimit:
393
            LOG.warning('radio and image bandlimits differ'
394
                        ' some channels many not work'
395
                        ' (img:0x%02x radio:0x%02x)' %
396
                        (int(bandlimit),
397
                         int(radio._memobj.radio_settings.bandlimit)))
398
            LOG.warning('radio bands: %s' % get_band_limits_Hz(
399
                         int(radio._memobj.radio_settings.bandlimit)))
400
            LOG.warning('img bands: %s' % get_band_limits_Hz(bandlimit))
401

    
402
        serial = radio.pipe
403

    
404
        # send the initial message, radio responds with something that looks a
405
        # bit like a bitfield, but I don't know what it is yet.
406
        read_command = struct.pack('>BHB', 0x52, 0x3b10, MEMORY_RW_BLOCK_SIZE)
407
        read_response = send_serial_command(serial, read_command,
408
                                            MEMORY_RW_BLOCK_CMD_SIZE)
409
        address, data, valid = parse_read_response(read_response)
410
        LOG.debug('Got initial response from radio: %s' %
411
                  util.hexprint(read_response))
412

    
413
        bptr = 0
414

    
415
        memory_addrs = range(MEMORY_ADDRESS_RANGE[0],
416
                             MEMORY_ADDRESS_RANGE[1] + MEMORY_RW_BLOCK_SIZE,
417
                             MEMORY_RW_BLOCK_SIZE)
418

    
419
        # status info for the UI
420
        status = chirp_common.Status()
421
        status.cur = 0
422
        status.max = len(memory_addrs)
423
        status.msg = 'Cloning to radio...'
424
        radio.status_fn(status)
425

    
426
        for idx, addr in enumerate(memory_addrs):
427
            write_command = make_write_data_cmd(
428
                addr, radio._mmap[bptr:bptr+MEMORY_RW_BLOCK_SIZE],
429
                MEMORY_RW_BLOCK_SIZE)
430
            # LOG.debug('write data:\n%s' % util.hexprint(write_command))
431
            write_response = send_serial_command(serial, write_command, 0x01)
432
            bptr += MEMORY_RW_BLOCK_SIZE
433

    
434
            if write_response == '\x0a':
435
                # NACK from radio, e.g. checksum wrongn
436
                LOG.debug('Radio returned 0x0a - NACK:')
437
                LOG.debug(' * write cmd:\n%s' % util.hexprint(write_command))
438
                LOG.debug(' * write response:\n%s' %
439
                          util.hexprint(write_response))
440
                exit_program_mode(radio)
441
                raise errors.RadioError('Radio NACK\'d write command')
442

    
443
            # update UI
444
            status.cur = idx
445
            radio.status_fn(status)
446
        exit_program_mode(radio)
447
    except errors.RadioError:
448
        raise
449
    except Exception as e:
450
        raise errors.RadioError('Failed to download from radio: %s' % e)
451

    
452

    
453
# Get the value of @bitfield @number of bits in from 0
454
def get_bitfield(bitfield, number):
455
    ''' Get the value of @bitfield @number of bits in '''
456
    byteidx = number//8
457
    bitidx = number - (byteidx * 8)
458
    return bitfield[byteidx] & (1 << bitidx)
459

    
460

    
461
# Set the @value of @bitfield @number of bits in from 0
462
def set_bitfield(bitfield, number, value):
463
    ''' Set the @value of @bitfield @number of bits in '''
464
    byteidx = number//8
465
    bitidx = number - (byteidx * 8)
466
    if value is True:
467
        bitfield[byteidx] |= (1 << bitidx)
468
    else:
469
        bitfield[byteidx] &= ~(1 << bitidx)
470
    return bitfield
471

    
472

    
473
# Translate the radio's version of a code as stored to a real code
474
def dtcs_code_bits_to_val(highbit, lowbyte):
475
    return chirp_common.ALL_DTCS_CODES[highbit*256 + lowbyte]
476

    
477

    
478
# Translate the radio's version of a tone as stored to a real tone
479
def ctcss_tone_bits_to_val(tone_byte):
480
    # TODO use the custom setting 0x33 and ref the custom ctcss
481
    # field
482
    tone_byte = int(tone_byte)
483
    if tone_byte in TONE_MAP_VAL_TO_TONE:
484
        return TONE_MAP_VAL_TO_TONE[tone_byte]
485
    elif tone_byte == TONE_CUSTOM_CTCSS:
486
        LOG.info('custom ctcss not implemented (yet?).')
487
    else:
488
        raise errors.UnsupportedToneError('unknown ctcss tone value: %02x' %
489
                                          tone_byte)
490

    
491

    
492
# Translate a real tone to the radio's version as stored
493
def ctcss_code_val_to_bits(tone_value):
494
    if tone_value in TONE_MAP_TONE_TO_VAL:
495
        return TONE_MAP_TONE_TO_VAL[tone_value]
496
    else:
497
        raise errors.UnsupportedToneError('Tone %f not supported' % tone_value)
498

    
499

    
500
# Translate a real code to the radio's version as stored
501
def dtcs_code_val_to_bits(code):
502
    val = chirp_common.ALL_DTCS_CODES.index(code)
503
    return (val & 0xFF), ((val >> 8) & 0x01)
504

    
505

    
506
class AnyTone778UVBase(chirp_common.CloneModeRadio,
507
                       chirp_common.ExperimentalRadio):
508
    '''AnyTone 778UV and probably Retivis RT95 and others'''
509
    BAUD_RATE = 9600
510
    NEEDS_COMPAT_SERIAL = False
511

    
512
    @classmethod
513
    def get_prompts(cls):
514
        rp = chirp_common.RadioPrompts()
515

    
516
        rp.experimental = \
517
            ('This is experimental support for the %s %s.  '
518
             'Please send in bug and enhancement requests!' %
519
             (cls.VENDOR, cls.MODEL))
520

    
521
        return rp
522

    
523
    # Return information about this radio's features, including
524
    # how many memories it has, what bands it supports, etc
525
    def get_features(self):
526
        rf = chirp_common.RadioFeatures()
527
        rf.has_bank = False
528
        rf.has_settings = False
529
        rf.can_odd_split = True
530
        rf.has_name = True
531
        rf.has_offset = True
532
        rf.valid_name_length = 5
533
        rf.valid_duplexes = ['', '+', '-', 'split', 'off']
534
        rf.valid_characters = CHARSET_ASCII_PLUS
535

    
536
        rf.has_dtcs = True
537
        rf.has_rx_dtcs = True
538
        rf.has_dtcs_polarity = True
539
        rf.valid_dtcs_codes = chirp_common.ALL_DTCS_CODES
540
        rf.has_ctone = True
541
        rf.has_cross = True
542
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
543
        rf.valid_cross_modes = ['Tone->Tone',
544
                                'Tone->DTCS',
545
                                'DTCS->Tone',
546
                                'DTCS->DTCS',
547
                                'DTCS->',
548
                                '->DTCS',
549
                                '->Tone']
550

    
551
        rf.memory_bounds = (1, 200)  # This radio supports memories 1-200
552
        try:
553
            rf.valid_bands = get_band_limits_Hz(
554
                int(self._memobj.radio_settings.bandlimit))
555
        except TypeError as e:
556
            # If we're asked without memory loaded, assume the most permissive
557
            rf.valid_bands = get_band_limits_Hz(1)
558
        except Exception as e:
559
            LOG.error('Failed to get band limits for anytone778uv: %s' % e)
560
            rf.valid_bands = get_band_limits_Hz(1)
561
        rf.valid_modes = ['FM', 'NFM']
562
        rf.valid_power_levels = POWER_LEVELS
563
        rf.valid_tuning_steps = [2.5, 5, 6.25, 10, 12.5, 20, 25, 30, 50]
564
        rf.has_tuning_step = False
565
        return rf
566

    
567
    # Do a download of the radio from the serial port
568
    def sync_in(self):
569
        self._mmap = do_download(self)
570
        self.process_mmap()
571

    
572
    # Do an upload of the radio to the serial port
573
    def sync_out(self):
574
        do_upload(self)
575

    
576
    # Convert the raw byte array into a memory object structure
577
    def process_mmap(self):
578
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
579

    
580
    # Return a raw representation of the memory object, which
581
    # is very helpful for development
582
    def get_raw_memory(self, number):
583
        return repr(self._memobj.memory[number - 1])
584

    
585
    # Extract a high-level memory object from the low-level memory map
586
    # This is called to populate a memory in the UI
587
    def get_memory(self, number):
588
        number -= 1
589
        # Get a low-level memory object mapped to the image
590
        _mem = self._memobj.memory[number]
591
        _mem_status = self._memobj.memory_status
592

    
593
        # Create a high-level memory object to return to the UI
594
        mem = chirp_common.Memory()
595
        mem.number = number + 1           # Set the memory number
596

    
597
        # Check if this memory is present in the occupied list
598
        mem.empty = get_bitfield(_mem_status.occupied_bitfield, number) == 0
599

    
600
        if not mem.empty:
601
            # Check if this memory is in the scan enabled list
602
            mem.skip = ''
603
            if get_bitfield(_mem_status.scan_enabled_bitfield, number) == 0:
604
                mem.skip = 'S'
605

    
606
            # set the name
607
            mem.name = str(_mem.name).rstrip()  # Set the alpha tag
608

    
609
            # Convert your low-level frequency and offset to Hertz
610
            mem.freq = int(_mem.freq) * 10
611
            mem.offset = int(_mem.offset) * 10
612

    
613
            # Set the duplex flags
614
            if _mem.duplex == DUPLEX_POSSPLIT:
615
                mem.duplex = '+'
616
            elif _mem.duplex == DUPLEX_NEGSPLIT:
617
                mem.duplex = '-'
618
            elif _mem.duplex == DUPLEX_NOSPLIT:
619
                mem.duplex = ''
620
            elif _mem.duplex == DUPLEX_ODDSPLIT:
621
                mem.duplex = 'split'
622
            else:
623
                LOG.error('%s: get_mem: unhandled duplex: %02x' %
624
                          (mem.name, _mem.duplex))
625

    
626
            # handle tx off
627
            if _mem.tx_off:
628
                mem.duplex = 'off'
629

    
630
            # Set the channel width
631
            if _mem.channel_width == CHANNEL_WIDTH_25kHz:
632
                mem.mode = 'FM'
633
            elif _mem.channel_width == CHANNEL_WIDTH_20kHz:
634
                LOG.info(
635
                    '%s: get_mem: promoting 20kHz channel width to 25kHz' %
636
                    mem.name)
637
                mem.mode = 'FM'
638
            elif _mem.channel_width == CHANNEL_WIDTH_12d5kHz:
639
                mem.mode = 'NFM'
640
            else:
641
                LOG.error('%s: get_mem: unhandled channel width: 0x%02x' %
642
                          (mem.name, _mem.channel_width))
643

    
644
            # set the power level
645
            if _mem.txpower == TXPOWER_LOW:
646
                mem.power = POWER_LEVELS[0]
647
            elif _mem.txpower == TXPOWER_MED:
648
                mem.power = POWER_LEVELS[1]
649
            elif _mem.txpower == TXPOWER_HIGH:
650
                mem.power = POWER_LEVELS[2]
651
            else:
652
                LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
653
                          (mem.name, _mem.txpower))
654

    
655
            # CTCSS Tones
656
            # TODO support custom ctcss tones here
657
            txtone = None
658
            rxtone = None
659
            rxcode = None
660
            txcode = None
661

    
662
            # check if dtcs tx is enabled
663
            if _mem.dtcs_encode_en:
664
                txcode = dtcs_code_bits_to_val(_mem.dtcs_encode_code_highbit,
665
                                               _mem.dtcs_encode_code)
666

    
667
            # check if dtcs rx is enabled
668
            if _mem.dtcs_decode_en:
669
                rxcode = dtcs_code_bits_to_val(_mem.dtcs_decode_code_highbit,
670
                                               _mem.dtcs_decode_code)
671

    
672
            if txcode is not None:
673
                LOG.debug('%s: get_mem dtcs_enc: %d' % (mem.name, txcode))
674
            if rxcode is not None:
675
                LOG.debug('%s: get_mem dtcs_dec: %d' % (mem.name, rxcode))
676

    
677
            # tsql set if radio squelches on tone
678
            tsql = _mem.tone_squelch_en
679

    
680
            # check if ctcss tx is enabled
681
            if _mem.ctcss_encode_en:
682
                txtone = ctcss_tone_bits_to_val(_mem.ctcss_enc_tone)
683

    
684
            # check if ctcss rx is enabled
685
            if _mem.ctcss_decode_en:
686
                rxtone = ctcss_tone_bits_to_val(_mem.ctcss_dec_tone)
687

    
688
            # Define this here to allow a readable if-else tree enabling tone
689
            # options
690
            enabled = 0
691
            enabled |= (txtone is not None) * TONES_EN_TXTONE
692
            enabled |= (rxtone is not None) * TONES_EN_RXTONE
693
            enabled |= (txcode is not None) * TONES_EN_TXCODE
694
            enabled |= (rxcode is not None) * TONES_EN_RXCODE
695

    
696
            # Add some debugging output for the tone bitmap
697
            enstr = []
698
            if enabled & TONES_EN_TXTONE:
699
                enstr += ['TONES_EN_TXTONE']
700
            if enabled & TONES_EN_RXTONE:
701
                enstr += ['TONES_EN_RXTONE']
702
            if enabled & TONES_EN_TXCODE:
703
                enstr += ['TONES_EN_TXCODE']
704
            if enabled & TONES_EN_RXCODE:
705
                enstr += ['TONES_EN_RXCODE']
706
            if enabled == 0:
707
                enstr = ['TONES_EN_NOTONE']
708
            LOG.debug('%s: enabled = %s' % (
709
                mem.name, '|'.join(enstr)))
710

    
711
            mem.tmode = ''
712
            if enabled == TONES_EN_NO_TONE:
713
                mem.tmode = ''
714
            elif enabled == TONES_EN_TXTONE:
715
                mem.tmode = 'Tone'
716
                mem.rtone = txtone
717
            elif enabled == TONES_EN_RXTONE and tsql:
718
                mem.tmode = 'Cross'
719
                mem.cross_mode = '->Tone'
720
                mem.ctone = rxtone
721
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXTONE) and tsql:
722
                if txtone == rxtone:  # TSQL
723
                    mem.tmode = 'TSQL'
724
                    mem.ctone = txtone
725
                else:  # Tone->Tone
726
                    mem.tmode = 'Cross'
727
                    mem.cross_mode = 'Tone->Tone'
728
                    mem.ctone = rxtone
729
                    mem.rtone = txtone
730
            elif enabled == TONES_EN_TXCODE:
731
                mem.tmode = 'Cross'
732
                mem.cross_mode = 'DTCS->'
733
                mem.dtcs = txcode
734
            elif enabled == TONES_EN_RXCODE and tsql:
735
                mem.tmode = 'Cross'
736
                mem.cross_mode = '->DTCS'
737
                mem.rx_dtcs = rxcode
738
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXCODE) and tsql:
739
                if rxcode == txcode:
740
                    mem.tmode = 'DTCS'
741
                    mem.rx_dtcs = rxcode
742
                    # #8327 Not sure this is the correct interpretation of
743
                    # DevelopersToneModes, but it seems to make it work round
744
                    # tripping with the anytone software.  DTM implies that we
745
                    # might not need to set mem.dtcs, but if we do it only DTCS
746
                    # rx works (as if we were Cross:None->DTCS).
747
                    mem.dtcs = rxcode
748
                else:
749
                    mem.tmode = 'Cross'
750
                    mem.cross_mode = 'DTCS->DTCS'
751
                    mem.rx_dtcs = rxcode
752
                    mem.dtcs = txcode
753
            elif enabled == (TONES_EN_TXCODE | TONES_EN_RXTONE) and tsql:
754
                mem.tmode = 'Cross'
755
                mem.cross_mode = 'DTCS->Tone'
756
                mem.dtcs = txcode
757
                mem.ctone = rxtone
758
            elif enabled == (TONES_EN_TXTONE | TONES_EN_RXCODE) and tsql:
759
                mem.tmode = 'Cross'
760
                mem.cross_mode = 'Tone->DTCS'
761
                mem.rx_dtcs = rxcode
762
                mem.rtone = txtone
763
            else:
764
                LOG.error('%s: Unhandled tmode enabled = %d.' % (
765
                    mem.name, enabled))
766

    
767
                # Can get here if e.g. TONE_EN_RXCODE is set and tsql isn't
768
                # In that case should we perhaps store the tone and code values
769
                # if they're present and then setup tmode and cross_mode as
770
                # appropriate later?
771

    
772
            # set the dtcs polarity
773
            dtcs_pol_bit_to_str = {0: 'N', 1: 'R'}
774
            mem.dtcs_polarity = '%s%s' %\
775
                (dtcs_pol_bit_to_str[_mem.dtcs_encode_invert == 1],
776
                 dtcs_pol_bit_to_str[_mem.dtcs_decode_invert == 1])
777

    
778
        return mem
779

    
780
    # Store details about a high-level memory to the memory map
781
    # This is called when a user edits a memory in the UI
782
    def set_memory(self, mem):
783
        # Get a low-level memory object mapped to the image
784
        _mem = self._memobj.memory[mem.number - 1]
785
        _mem_status = self._memobj.memory_status
786

    
787
        # set the occupied bitfield
788
        _mem_status.occupied_bitfield = \
789
            set_bitfield(_mem_status.occupied_bitfield, mem.number - 1,
790
                         not mem.empty)
791

    
792
        # set the scan add bitfield
793
        _mem_status.scan_enabled_bitfield = \
794
            set_bitfield(_mem_status.scan_enabled_bitfield, mem.number - 1,
795
                         (not mem.empty) and (mem.skip != 'S'))
796

    
797
        if mem.empty:
798
            # Set the whole memory to 0xff
799
            _mem.set_raw('\xff' * (_mem.size() / 8))
800
        else:
801
            _mem.set_raw('\x00' * (_mem.size() / 8))
802

    
803
            _mem.freq = int(mem.freq / 10)
804
            _mem.offset = int(mem.offset / 10)
805

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

    
808
            # TODO support busy channel lockout - disabled for now
809
            _mem.busy_channel_lockout = BUSY_CHANNEL_LOCKOUT_OFF
810

    
811
            # Set duplex bitfields
812
            if mem.duplex == '+':
813
                _mem.duplex = DUPLEX_POSSPLIT
814
            elif mem.duplex == '-':
815
                _mem.duplex = DUPLEX_NEGSPLIT
816
            elif mem.duplex == '':
817
                _mem.duplex = DUPLEX_NOSPLIT
818
            elif mem.duplex == 'split':
819
                # TODO: this is an unverified punt!
820
                _mem.duplex = DUPLEX_ODDSPLIT
821
            else:
822
                LOG.error('%s: set_mem: unhandled duplex: %s' %
823
                          (mem.name, mem.duplex))
824

    
825
            # handle tx off
826
            _mem.tx_off = 0
827
            if mem.duplex == 'off':
828
                _mem.tx_off = 1
829

    
830
            # Set the channel width - remember we promote 20kHz channels to FM
831
            # on import
832
            # , so don't handle them here
833
            if mem.mode == 'FM':
834
                _mem.channel_width = CHANNEL_WIDTH_25kHz
835
            elif mem.mode == 'NFM':
836
                _mem.channel_width = CHANNEL_WIDTH_12d5kHz
837
            else:
838
                LOG.error('%s: set_mem: unhandled mode: %s' % (
839
                    mem.name, mem.mode))
840

    
841
            # set the power level
842
            if mem.power == POWER_LEVELS[0]:
843
                _mem.txpower = TXPOWER_LOW
844
            elif mem.power == POWER_LEVELS[1]:
845
                _mem.txpower = TXPOWER_MED
846
            elif mem.power == POWER_LEVELS[2]:
847
                _mem.txpower = TXPOWER_HIGH
848
            else:
849
                LOG.error('%s: set_mem: unhandled power level: %s' %
850
                          (mem.name, mem.power))
851

    
852
            # TODO set the CTCSS values
853
            # TODO support custom ctcss tones here
854
            # Default - tones off, carrier sql
855
            _mem.ctcss_encode_en = 0
856
            _mem.ctcss_decode_en = 0
857
            _mem.tone_squelch_en = 0
858
            _mem.ctcss_enc_tone = 0x00
859
            _mem.ctcss_dec_tone = 0x00
860
            _mem.customctcss = 0x00
861
            _mem.dtcs_encode_en = 0
862
            _mem.dtcs_encode_code_highbit = 0
863
            _mem.dtcs_encode_code = 0
864
            _mem.dtcs_encode_invert = 0
865
            _mem.dtcs_decode_en = 0
866
            _mem.dtcs_decode_code_highbit = 0
867
            _mem.dtcs_decode_code = 0
868
            _mem.dtcs_decode_invert = 0
869

    
870
            dtcs_pol_str_to_bit = {'N': 0, 'R': 1}
871
            _mem.dtcs_encode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[0]]
872
            _mem.dtcs_decode_invert = dtcs_pol_str_to_bit[mem.dtcs_polarity[1]]
873

    
874
            if mem.tmode == 'Tone':
875
                _mem.ctcss_encode_en = 1
876
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
877
            elif mem.tmode == 'TSQL':
878
                _mem.ctcss_encode_en = 1
879
                _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.ctone)
880
                _mem.ctcss_decode_en = 1
881
                _mem.tone_squelch_en = 1
882
                _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
883
            elif mem.tmode == 'DTCS':
884
                _mem.dtcs_encode_en = 1
885
                _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
886
                    dtcs_code_val_to_bits(mem.rx_dtcs)
887
                _mem.dtcs_decode_en = 1
888
                _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
889
                    dtcs_code_val_to_bits(mem.rx_dtcs)
890
                _mem.tone_squelch_en = 1
891
            elif mem.tmode == 'Cross':
892
                txmode, rxmode = mem.cross_mode.split('->')
893

    
894
                if txmode == 'Tone':
895
                    _mem.ctcss_encode_en = 1
896
                    _mem.ctcss_enc_tone = ctcss_code_val_to_bits(mem.rtone)
897
                elif txmode == '':
898
                    pass
899
                elif txmode == 'DTCS':
900
                    _mem.dtcs_encode_en = 1
901
                    _mem.dtcs_encode_code, _mem.dtcs_encode_code_highbit = \
902
                        dtcs_code_val_to_bits(mem.dtcs)
903
                else:
904
                    LOG.error('%s: unhandled cross TX mode: %s' % (
905
                        mem.name, mem.cross_mode))
906

    
907
                if rxmode == 'Tone':
908
                    _mem.ctcss_decode_en = 1
909
                    _mem.tone_squelch_en = 1
910
                    _mem.ctcss_dec_tone = ctcss_code_val_to_bits(mem.ctone)
911
                elif rxmode == '':
912
                    pass
913
                elif rxmode == 'DTCS':
914
                    _mem.dtcs_decode_en = 1
915
                    _mem.dtcs_decode_code, _mem.dtcs_decode_code_highbit = \
916
                        dtcs_code_val_to_bits(mem.rx_dtcs)
917
                    _mem.tone_squelch_en = 1
918
                else:
919
                    LOG.error('%s: unhandled cross RX mode: %s' % (
920
                        mem.name, mem.cross_mode))
921
            else:
922
                LOG.error('%s: Unhandled tmode/cross %s/%s.' %
923
                          (mem.name, mem.tmode, mem.cross_mode))
924
            LOG.debug('%s: tmode=%s, cross=%s, rtone=%f, ctone=%f' % (
925
                mem.name, mem.tmode, mem.cross_mode, mem.rtone, mem.ctone))
926
            LOG.debug('%s: CENC=%d, CDEC=%d, t(enc)=%02x, t(dec)=%02x' % (
927
                mem.name,
928
                _mem.ctcss_encode_en,
929
                _mem.ctcss_decode_en,
930
                ctcss_code_val_to_bits(mem.rtone),
931
                ctcss_code_val_to_bits(mem.ctone)))
932

    
933
            # set unknown defaults, based on reading memory set by vendor tool
934
            _mem.unknown1 = 0x00
935
            _mem.unknown6 = 0x00
936
            _mem.unknown7 = 0x00
937
            _mem.unknown8 = 0x00
938
            _mem.unknown9 = 0x00
939
            _mem.unknown10 = 0x00
940

    
941

    
942
if has_future:
943
    @directory.register
944
    class AnyTone778UV(AnyTone778UVBase):
945
        VENDOR = "AnyTone"
946
        MODEL = "778UV"
947
        # Allowed radio types is a dict keyed by model of a list of version
948
        # strings
949
        ALLOWED_RADIO_TYPES = {'AT778UV': ['V100', 'V200']}
950

    
951
    @directory.register
952
    class RetevisRT95(AnyTone778UVBase):
953
        VENDOR = "Retevis"
954
        MODEL = "RT95"
955
        # Allowed radio types is a dict keyed by model of a list of version
956
        # strings
957
        ALLOWED_RADIO_TYPES = {'RT95': ['V100']}
958

    
959
    @directory.register
960
    class CRTMicronUV(AnyTone778UVBase):
961
        VENDOR = "CRT"
962
        MODEL = "Micron UV"
963
        # Allowed radio types is a dict keyed by model of a list of version
964
        # strings
965
        ALLOWED_RADIO_TYPES = {'MICRON': ['V100']}
966

    
967
    @directory.register
968
    class MidlandDBR2500(AnyTone778UVBase):
969
        VENDOR = "Midland"
970
        MODEL = "DBR2500"
971
        # Allowed radio types is a dict keyed by model of a list of version
972
        # strings
973
        ALLOWED_RADIO_TYPES = {'DBR2500': ['V100']}
974

    
975
    @directory.register
976
    class YedroYCM04vus(AnyTone778UVBase):
977
        VENDOR = "Yedro"
978
        MODEL = "YC-M04VUS"
979
        # Allowed radio types is a dict keyed by model of a list of version
980
        # strings
981
        ALLOWED_RADIO_TYPES = {'YCM04UV': ['V100']}
982

    
983
    @directory.register
984
    class RetevisRT95P(AnyTone778UVBase):
985
        VENDOR = "Retevis"
986
        MODEL = "RT95-P"
987
        # Allowed radio types is a dict keyed by model of a list of version
988
        # strings
989
        ALLOWED_RADIO_TYPES = {'RT95-P': ['V100']}
990

    
(2-2/16)