Project

General

Profile

Bug #9035 » retevis_rb26_draft_fix#1.py

Jim Unroe, 07/02/2021 10:38 AM

 
1
# Copyright 2021 Jim Unroe <rock.unroe@gmail.com>
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
import time
17
import os
18
import struct
19
import logging
20

    
21
from chirp import (
22
    bitwise,
23
    chirp_common,
24
    directory,
25
    errors,
26
    memmap,
27
    util,
28
)
29
from chirp.settings import (
30
    RadioSetting,
31
    RadioSettingGroup,
32
    RadioSettings,
33
    RadioSettingValueBoolean,
34
    RadioSettingValueInteger,
35
    RadioSettingValueList,
36
    RadioSettingValueString,
37
)
38

    
39
LOG = logging.getLogger(__name__)
40

    
41
MEM_FORMAT = """
42
#seekto 0x0010;
43
struct {
44
  lbcd rxfreq[4];       // RX Frequency           0-3
45
  lbcd txfreq[4];       // TX Frequency           4-7
46
  ul16 rx_tone;         // PL/DPL Decode          8-9
47
  ul16 tx_tone;         // PL/DPL Encode          A-B
48
  u8 unknown1:3,        //                        C
49
     bcl:2,             // Busy Lock
50
     unknown2:3;
51
  u8 unknown3:2,        //                        D
52
     highpower:1,       // Power Level
53
     wide:1,            // Bandwidth
54
     unknown4:4;
55
  u8 scramble_type:4,   // Scramble Type          E
56
     unknown5:4;
57
  u8 unknown6:4,
58
     scramble_type2:4;  // Scramble Type 2        F
59
} memory[16];
60

    
61
#seekto 0x011D;
62
struct {
63
  u8 unused:4,
64
     pf1:4;             // Programmable Function Key 1
65
} keys;
66

    
67
#seekto 0x012C;
68
struct {
69
  u8 use_scramble;      // Scramble Enable
70
  u8 unknown1[2];
71
  u8 voice;             // Voice Annunciation
72
  u8 tot;               // Time-out Timer
73
  u8 totalert;          // Time-out Timer Pre-alert
74
  u8 unknown2[2];
75
  u8 squelch;           // Squelch Level
76
  u8 save;              // Battery Saver
77
  u8 unknown3[3];
78
  u8 use_vox;           // VOX Enable
79
  u8 vox;               // VOX Gain
80
} settings;
81

    
82
#seekto 0x017E;
83
u8 skipflags[2];       // SCAN_ADD
84
"""
85

    
86
MEM_FORMAT_RB17A = """
87
struct memory {
88
  lbcd rxfreq[4];      // 0-3
89
  lbcd txfreq[4];      // 4-7
90
  ul16 rx_tone;        // 8-9
91
  ul16 tx_tone;        // A-B
92
  u8 unknown1:1,       // C
93
     compander:1,      // Compand
94
     bcl:2,            // Busy Channel Lock-out
95
     cdcss:1,          // Cdcss Mode
96
     scramble_type:3;  // Scramble Type
97
  u8 unknown2:4,       // D
98
     middlepower:1,    // Power Level-Middle
99
     unknown3:1,       //
100
     highpower:1,      // Power Level-High/Low
101
     wide:1;           // Bandwidth
102
  u8 unknown4;         // E
103
  u8 unknown5;         // F
104
};
105

    
106
#seekto 0x0010;
107
  struct memory lomems[16];
108

    
109
#seekto 0x0200;
110
  struct memory himems[14];
111

    
112
#seekto 0x011D;
113
struct {
114
  u8 pf1;              // 011D PF1 Key
115
  u8 topkey;           // 011E Top Key
116
} keys;
117

    
118
#seekto 0x012C;
119
struct {
120
  u8 use_scramble;     // 012C Scramble Enable
121
  u8 channel;          // 012D Channel Number
122
  u8 alarm;            // 012E Alarm Type
123
  u8 voice;            // 012F Voice Annunciation
124
  u8 tot;              // 0130 Time-out Timer
125
  u8 totalert;         // 0131 Time-out Timer Pre-alert
126
  u8 unknown2[2];
127
  u8 squelch;          // 0134 Squelch Level
128
  u8 save;             // 0135 Battery Saver
129
  u8 unknown3[3];
130
  u8 use_vox;          // 0139 VOX Enable
131
  u8 vox;              // 013A VOX Gain
132
} settings;
133

    
134
#seekto 0x017E;
135
u8 skipflags[4];       // Scan Add
136
"""
137

    
138
MEM_FORMAT_RB26 = """
139
#seekto 0x0000;
140
struct {
141
  lbcd rxfreq[4];      // RX Frequency           0-3
142
  lbcd txfreq[4];      // TX Frequency           4-7
143
  ul16 rx_tone;        // PL/DPL Decode          8-9
144
  ul16 tx_tone;        // PL/DPL Encode          A-B
145
  u8 compander:1,      // Compander              C
146
     unknown1:1,       //
147
     highpower:1,      // Power Level
148
     wide:1,           // Bandwidth
149
     bcl:1,            // Busy Lock  OFF=0 ON=1
150
     unknown2:3;       //
151
  u8 reserved[3];      // Reserved               D-F
152
} memory[30];
153

    
154
#seekto 0x002D;
155
struct {
156
  u8 unknown_1:1,      //                        002D
157
     chnumberd:1,      // Channel Number Disable
158
     gain:1,           // MIC Gain
159
     savem:1,          // Battery Save Mode
160
     save:1,           // Battery Save
161
     beep:1,           // Beep
162
     voice:1,          // Voice Prompts
163
     unknown_2:1;      //
164
  u8 squelch;          // Squelch                002E
165
  u8 tot;              // Time-out Timer         002F
166
  u8 channel_4[13];    //                        0030-003C
167
  u8 unknown_3[3];     //                        003D-003F
168
  u8 channel_5[13];    //                        0040-004C
169
  u8 unknown_4;        //                        004D
170
  u8 unknown_5[2];     //                        004E-004F
171
  u8 channel_6[13];    //                        0050-005C
172
  u8 unknown_6;        //                        005D
173
  u8 unknown_7[2];     //                        005E-005F
174
  u8 channel_7[13];    //                        0060-006C
175
  u8 warn;             // Warn Mode              006D
176
  u8 pf1;              // Key Set PF1            006E
177
  u8 pf2;              // Key Set PF2            006F
178
  u8 channel_8[13];    //                        0070-007C
179
  u8 unknown_8;        //                        007D
180
  u8 tail;             // QT/DQT Tail(inverted)  007E
181
} settings;
182

    
183
#seekto 0x01F0;
184
u8 skipflags[4];       // Scan Add
185

    
186
#seekto 0x029F;
187
struct {
188
  u8 chnumber;         // Channel Number         029F
189
} settings2;
190

    
191
#seekto 0x031D;
192
struct {
193
  u8 unused:7,         //                        031D
194
     vox:1;            // Vox
195
  u8 voxl;             // Vox Level              031E
196
  u8 voxd;             // Vox Delay              031F
197
} settings3;
198
"""
199

    
200
MEM_FORMAT_RT76 = """
201
#seekto 0x0000;
202
struct {
203
  lbcd rxfreq[4];      // RX Frequency           0-3
204
  lbcd txfreq[4];      // TX Frequency           4-7
205
  ul16 rx_tone;        // PL/DPL Decode          8-9
206
  ul16 tx_tone;        // PL/DPL Encode          A-B
207
  u8 compander:1,      // Compander              C
208
     unknown1:1,       //
209
     highpower:1,      // Power Level
210
     wide:1,           // Bandwidth
211
     unknown2:4;       //
212
  u8 reserved[3];      // Reserved               D-F
213
} memory[30];
214

    
215
#seekto 0x002D;
216
struct {
217
  u8 unknown_1:1,      //                        002D
218
     chnumberd:1,      // Channel Number Disable
219
     gain:1,           // MIC Gain                                 ---
220
     savem:1,          // Battery Save Mode                        ---
221
     save:1,           // Battery Save                             ---
222
     beep:1,           // Beep                                     ---
223
     voice:2;          // Voice Prompts                            ---
224
  u8 squelch;          // Squelch                002E              ---
225
  u8 tot;              // Time-out Timer         002F              ---
226
  u8 channel_4[13];    //                        0030-003C
227
  u8 unused:7,         //                        003D
228
     vox:1;            // Vox                                      ---
229
  u8 voxl;             // Vox Level              003E              ---
230
  u8 voxd;             // Vox Delay              003F              ---
231
  u8 channel_5[13];    //                        0040-004C
232
  u8 unknown_4;        //                        004D
233
  u8 unknown_5[2];     //                        004E-004F
234
  u8 channel_6[13];    //                        0050-005C
235
  u8 chnumber;         // Channel Number         005D              ---
236
  u8 unknown_7[2];     //                        005E-005F
237
  u8 channel_7[13];    //                        0060-006C
238
  u8 warn;             //                        006D              ---
239
} settings;
240
"""
241

    
242
CMD_ACK = "\x06"
243

    
244
ALARM_LIST = ["Local Alarm", "Remote Alarm"]
245
BCL_LIST = ["Off", "Carrier", "QT/DQT"]
246
CDCSS_LIST = ["Normal Code", "Special Code 2", "Special Code 1"]
247
GAIN_LIST = ["Standard", "Enhanced"]
248
PFKEY_LIST = ["None", "Monitor", "Lamp", "Warn", "VOX", "VOX Delay",
249
              "Key Lock", "Scan"]
250
SAVE_LIST = ["Standard", "Super"]
251
SCRAMBLE_LIST = ["%s" % x for x in range(1, 9)]
252
TIMEOUTTIMER_LIST = ["%s seconds" % x for x in range(15, 615, 15)]
253
TOTALERT_LIST = ["Off"] + ["%s seconds" % x for x in range(1, 11)]
254
VOICE_LIST = ["Off", "Chinese", "English"]
255
VOICE_LIST2 = ["Off", "English"]
256
VOICE_LIST3 = VOICE_LIST2 + ["Chinese"]
257
VOX_LIST = ["OFF"] + ["%s" % x for x in range(1, 17)]
258
VOXD_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0"]
259
VOXL_LIST = ["OFF"] + ["%s" % x for x in range(1, 9)]
260
WARN_LIST = ["OFF", "Native Warn", "Remote Warn"]
261
PF1_CHOICES = ["None", "Monitor", "Scan", "Scramble", "Alarm"]
262
PF1_VALUES = [0x0F, 0x04, 0x06, 0x08, 0x0C]
263
TOPKEY_CHOICES = ["None", "Alarming"]
264
TOPKEY_VALUES = [0xFF, 0x0C]
265

    
266
SETTING_LISTS = {
267
    "alarm": ALARM_LIST,
268
    "bcl": BCL_LIST,
269
    "cdcss": CDCSS_LIST,
270
    "gain": GAIN_LIST,
271
    "pfkey": PFKEY_LIST,
272
    "save": SAVE_LIST,
273
    "scramble": SCRAMBLE_LIST,
274
    "tot": TIMEOUTTIMER_LIST,
275
    "totalert": TOTALERT_LIST,
276
    "voice": VOICE_LIST,
277
    "voice": VOICE_LIST2,
278
    "voice": VOICE_LIST3,
279
    "vox": VOX_LIST,
280
    "voxd": VOXD_LIST,
281
    "voxl": VOXL_LIST,
282
    "warn": WARN_LIST,
283
    }
284

    
285
GMRS_FREQS1 = [462.5625, 462.5875, 462.6125, 462.6375, 462.6625,
286
               462.6875, 462.7125]
287
GMRS_FREQS2 = [467.5625, 467.5875, 467.6125, 467.6375, 467.6625,
288
               467.6875, 467.7125]
289
GMRS_FREQS3 = [462.5500, 462.5750, 462.6000, 462.6250, 462.6500,
290
               462.6750, 462.7000, 462.7250]
291
GMRS_FREQS = GMRS_FREQS1 + GMRS_FREQS2 + GMRS_FREQS3 * 2
292

    
293

    
294
def _enter_programming_mode(radio):
295
    serial = radio.pipe
296

    
297
    exito = False
298
    for i in range(0, 5):
299
        serial.write(radio._magic)
300
        #if radio.MODEL == "RB26" or radio.MODEL == "RT76":
301
        #    serial.read(1)
302
        ack = serial.read(1)
303
        if ack == "\x00":
304
            ack = serial.read(1)
305

    
306
        try:
307
            if ack == CMD_ACK:
308
                exito = True
309
                break
310
        except:
311
            LOG.debug("Attempt #%s, failed, trying again" % i)
312
            pass
313

    
314
    # check if we had EXITO
315
    if exito is False:
316
        msg = "The radio did not accept program mode after five tries.\n"
317
        msg += "Check you interface cable and power cycle your radio."
318
        raise errors.RadioError(msg)
319

    
320
    try:
321
        serial.write("\x02")
322
        ident = serial.read(8)
323
    except:
324
        raise errors.RadioError("Error communicating with radio")
325

    
326
    if not ident == radio._fingerprint:
327
        LOG.debug(util.hexprint(ident))
328
        raise errors.RadioError("Radio returned unknown identification string")
329

    
330
    try:
331
        serial.write(CMD_ACK)
332
        ack = serial.read(1)
333
    except:
334
        raise errors.RadioError("Error communicating with radio")
335

    
336
    if ack != CMD_ACK:
337
        raise errors.RadioError("Radio refused to enter programming mode")
338

    
339

    
340
def _exit_programming_mode(radio):
341
    serial = radio.pipe
342
    try:
343
        serial.write("E")
344
    except:
345
        raise errors.RadioError("Radio refused to exit programming mode")
346

    
347

    
348
def _read_block(radio, block_addr, block_size):
349
    serial = radio.pipe
350

    
351
    cmd = struct.pack(">cHb", 'R', block_addr, block_size)
352
    expectedresponse = "W" + cmd[1:]
353
    LOG.debug("Reading block %04x..." % (block_addr))
354

    
355
    try:
356
        serial.write(cmd)
357
        response = serial.read(4 + block_size)
358
        if response[:4] != expectedresponse:
359
            raise Exception("Error reading block %04x." % (block_addr))
360

    
361
        block_data = response[4:]
362

    
363
        serial.write(CMD_ACK)
364
        ack = serial.read(1)
365
    except:
366
        raise errors.RadioError("Failed to read block at %04x" % block_addr)
367

    
368
    if ack != CMD_ACK:
369
        raise Exception("No ACK reading block %04x." % (block_addr))
370

    
371
    return block_data
372

    
373

    
374
def _rb26_read_block(radio, block_addr, block_size):
375
    serial = radio.pipe
376

    
377
    cmd = struct.pack(">cHb", 'R', block_addr, block_size)
378
    expectedresponse = "W" + cmd[1:]
379
    LOG.debug("Reading block %04x..." % (block_addr))
380

    
381
    try:
382
        serial.write(cmd)
383
        response = serial.read(4 + block_size)
384
        if response[:4] != expectedresponse:
385
            raise Exception("Error reading block %04x." % (block_addr))
386

    
387
        block_data = response[4:]
388

    
389
        if block_addr != 0:
390
            serial.write(CMD_ACK)
391
            ack = serial.read(1)
392
    except:
393
        raise errors.RadioError("Failed to read block at %04x" % block_addr)
394

    
395
    if block_addr != 0:
396
        if ack != CMD_ACK:
397
            raise Exception("No ACK reading block %04x." % (block_addr))
398

    
399
    return block_data
400

    
401

    
402
def _write_block(radio, block_addr, block_size):
403
    serial = radio.pipe
404

    
405
    cmd = struct.pack(">cHb", 'W', block_addr, block_size)
406
    data = radio.get_mmap()[block_addr:block_addr + block_size]
407

    
408
    LOG.debug("Writing Data:")
409
    LOG.debug(util.hexprint(cmd + data))
410

    
411
    try:
412
        serial.write(cmd + data)
413
        if serial.read(1) != CMD_ACK:
414
            raise Exception("No ACK")
415
    except:
416
        raise errors.RadioError("Failed to send block "
417
                                "to radio at %04x" % block_addr)
418

    
419

    
420
def do_download(radio):
421
    LOG.debug("download")
422
    _enter_programming_mode(radio)
423

    
424
    data = ""
425

    
426
    status = chirp_common.Status()
427
    status.msg = "Cloning from radio"
428

    
429
    status.cur = 0
430
    status.max = radio._memsize
431

    
432
    for addr in range(0, radio._memsize, radio.BLOCK_SIZE):
433
        status.cur = addr + radio.BLOCK_SIZE
434
        radio.status_fn(status)
435

    
436
        if radio.MODEL == "RB26" or radio.MODEL == "RT76":
437
            block = _rb26_read_block(radio, addr, radio.BLOCK_SIZE)
438
        else:
439
            block = _read_block(radio, addr, radio.BLOCK_SIZE)
440
        data += block
441

    
442
        LOG.debug("Address: %04x" % addr)
443
        LOG.debug(util.hexprint(block))
444

    
445
    _exit_programming_mode(radio)
446

    
447
    return memmap.MemoryMap(data)
448

    
449

    
450
def do_upload(radio):
451
    status = chirp_common.Status()
452
    status.msg = "Uploading to radio"
453

    
454
    _enter_programming_mode(radio)
455

    
456
    status.cur = 0
457
    status.max = radio._memsize
458

    
459
    for start_addr, end_addr in radio._ranges:
460
        for addr in range(start_addr, end_addr, radio.BLOCK_SIZE_UP):
461
            status.cur = addr + radio.BLOCK_SIZE_UP
462
            radio.status_fn(status)
463
            _write_block(radio, addr, radio.BLOCK_SIZE_UP)
464

    
465
    _exit_programming_mode(radio)
466

    
467

    
468
def model_match(cls, data):
469
    """Match the opened/downloaded image to the correct version"""
470
    rid = data[0x01B8:0x01BE]
471

    
472
    return rid.startswith("P3207")
473

    
474

    
475
@directory.register
476
class RT21Radio(chirp_common.CloneModeRadio):
477
    """RETEVIS RT21"""
478
    VENDOR = "Retevis"
479
    MODEL = "RT21"
480
    BAUD_RATE = 9600
481
    BLOCK_SIZE = 0x10
482
    BLOCK_SIZE_UP = 0x10
483

    
484
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1.00),
485
                    chirp_common.PowerLevel("High", watts=2.50)]
486

    
487
    _magic = "PRMZUNE"
488
    _fingerprint = "P3207s\xF8\xFF"
489
    _upper = 16
490
    _skipflags = True
491
    _reserved = False
492
    _gmrs = False
493

    
494
    _ranges = [
495
               (0x0000, 0x0400),
496
              ]
497
    _memsize = 0x0400
498

    
499
    def get_features(self):
500
        rf = chirp_common.RadioFeatures()
501
        rf.has_settings = True
502
        rf.has_bank = False
503
        rf.has_ctone = True
504
        rf.has_cross = True
505
        rf.has_rx_dtcs = True
506
        rf.has_tuning_step = False
507
        rf.can_odd_split = True
508
        rf.has_name = False
509
        rf.valid_skips = ["", "S"]
510
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
511
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
512
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
513
        rf.valid_power_levels = self.POWER_LEVELS
514
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
515
        rf.valid_modes = ["NFM", "FM"]  # 12.5 KHz, 25 kHz.
516
        rf.memory_bounds = (1, self._upper)
517
        rf.valid_tuning_steps = [2.5, 5., 6.25, 10., 12.5, 25.]
518
        rf.valid_bands = [(400000000, 480000000)]
519

    
520
        return rf
521

    
522
    def process_mmap(self):
523
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
524

    
525
    def validate_memory(self, mem):
526
        msgs = ""
527
        msgs = chirp_common.CloneModeRadio.validate_memory(self, mem)
528

    
529
        _msg_freq = 'Memory location cannot change frequency'
530
        _msg_simplex = 'Memory location only supports Duplex:(None)'
531
        _msg_duplex = 'Memory location only supports Duplex: +'
532
        _msg_offset = 'Memory location only supports Offset: 5.000000'
533
        _msg_nfm = 'Memory location only supports Mode: NFM'
534
        _msg_txp = 'Memory location only supports Power: Low'
535

    
536
        # GMRS models
537
        if self._gmrs:
538
            # range of memories with values set by FCC rules
539
            if mem.freq != int(GMRS_FREQS[mem.number - 1] * 1000000):
540
                # warn user can't change frequency
541
                msgs.append(chirp_common.ValidationError(_msg_freq))
542

    
543
            # channels 1 - 22 are simplex only
544
            if mem.number <= 22:
545
                if str(mem.duplex) != "":
546
                    # warn user can't change duplex
547
                    msgs.append(chirp_common.ValidationError(_msg_simplex))
548

    
549
            # channels 23 - 30 are +5 MHz duplex only
550
            if mem.number >= 23:
551
                if str(mem.duplex) != "+":
552
                    # warn user can't change duplex
553
                    msgs.append(chirp_common.ValidationError(_msg_duplex))
554

    
555
                if str(mem.offset) != "5000000":
556
                    # warn user can't change offset
557
                    msgs.append(chirp_common.ValidationError(_msg_offset))
558

    
559
            # channels 8 - 14 are low power NFM only
560
            if mem.number >= 8 and mem.number <= 14:
561
                if mem.mode != "NFM":
562
                    # warn user can't change mode
563
                    msgs.append(chirp_common.ValidationError(_msg_nfm))
564

    
565
                if mem.power != "Low":
566
                    # warn user can't change power
567
                    msgs.append(chirp_common.ValidationError(_msg_txp))
568

    
569
        return msgs
570

    
571
    def sync_in(self):
572
        """Download from radio"""
573
        try:
574
            data = do_download(self)
575
        except errors.RadioError:
576
            # Pass through any real errors we raise
577
            raise
578
        except:
579
            # If anything unexpected happens, make sure we raise
580
            # a RadioError and log the problem
581
            LOG.exception('Unexpected error during download')
582
            raise errors.RadioError('Unexpected error communicating '
583
                                    'with the radio')
584
        self._mmap = data
585
        self.process_mmap()
586

    
587
    def sync_out(self):
588
        """Upload to radio"""
589
        try:
590
            do_upload(self)
591
        except:
592
            # If anything unexpected happens, make sure we raise
593
            # a RadioError and log the problem
594
            LOG.exception('Unexpected error during upload')
595
            raise errors.RadioError('Unexpected error communicating '
596
                                    'with the radio')
597

    
598
    def get_raw_memory(self, number):
599
        return repr(self._memobj.memory[number - 1])
600

    
601
    def _get_tone(self, _mem, mem):
602
        def _get_dcs(val):
603
            code = int("%03o" % (val & 0x07FF))
604
            pol = (val & 0x8000) and "R" or "N"
605
            return code, pol
606

    
607
        if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2000:
608
            tcode, tpol = _get_dcs(_mem.tx_tone)
609
            mem.dtcs = tcode
610
            txmode = "DTCS"
611
        elif _mem.tx_tone != 0xFFFF:
612
            mem.rtone = _mem.tx_tone / 10.0
613
            txmode = "Tone"
614
        else:
615
            txmode = ""
616

    
617
        if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2000:
618
            rcode, rpol = _get_dcs(_mem.rx_tone)
619
            mem.rx_dtcs = rcode
620
            rxmode = "DTCS"
621
        elif _mem.rx_tone != 0xFFFF:
622
            mem.ctone = _mem.rx_tone / 10.0
623
            rxmode = "Tone"
624
        else:
625
            rxmode = ""
626

    
627
        if txmode == "Tone" and not rxmode:
628
            mem.tmode = "Tone"
629
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
630
            mem.tmode = "TSQL"
631
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
632
            mem.tmode = "DTCS"
633
        elif rxmode or txmode:
634
            mem.tmode = "Cross"
635
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
636

    
637
        if mem.tmode == "DTCS":
638
            mem.dtcs_polarity = "%s%s" % (tpol, rpol)
639

    
640
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
641
                  (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
642

    
643
    def get_memory(self, number):
644
        if self._skipflags:
645
            bitpos = (1 << ((number - 1) % 8))
646
            bytepos = ((number - 1) / 8)
647
            LOG.debug("bitpos %s" % bitpos)
648
            LOG.debug("bytepos %s" % bytepos)
649
            _skp = self._memobj.skipflags[bytepos]
650

    
651
        mem = chirp_common.Memory()
652

    
653
        mem.number = number
654

    
655
        if self.MODEL == "RB17A":
656
            if mem.number < 17:
657
                _mem = self._memobj.lomems[number - 1]
658
            else:
659
                _mem = self._memobj.himems[number - 17]
660
        else:
661
            _mem = self._memobj.memory[number - 1]
662

    
663
        if self._reserved:
664
            _rsvd = _mem.reserved.get_raw()
665

    
666
        mem.freq = int(_mem.rxfreq) * 10
667

    
668
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
669
        if mem.freq == 0:
670
            mem.empty = True
671
            return mem
672

    
673
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
674
            mem.freq = 0
675
            mem.empty = True
676
            return mem
677

    
678
        if _mem.get_raw() == ("\xFF" * 16):
679
            LOG.debug("Initializing empty memory")
680
            if self.MODEL == "RB17A":
681
                _mem.set_raw("\x00" * 13 + "\x04\xFF\xFF")
682
            if self.MODEL == "RB26" or self.MODEL == "RT76":
683
                _mem.set_raw("\x00" * 13 + _rsvd)
684
            else:
685
                _mem.set_raw("\x00" * 13 + "\x30\x8F\xF8")
686

    
687
        if int(_mem.rxfreq) == int(_mem.txfreq):
688
            mem.duplex = ""
689
            mem.offset = 0
690
        else:
691
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
692
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
693

    
694
        mem.mode = _mem.wide and "FM" or "NFM"
695

    
696
        self._get_tone(_mem, mem)
697

    
698
        mem.power = self.POWER_LEVELS[_mem.highpower]
699

    
700
        if self.MODEL != "RT76":
701
            mem.skip = "" if (_skp & bitpos) else "S"
702
            LOG.debug("mem.skip %s" % mem.skip)
703

    
704
        mem.extra = RadioSettingGroup("Extra", "extra")
705

    
706
        if self.MODEL == "RT21" or self.MODEL == "RB17A":
707
            rs = RadioSettingValueList(BCL_LIST, BCL_LIST[_mem.bcl])
708
            rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
709
            mem.extra.append(rset)
710

    
711
            rs = RadioSettingValueList(SCRAMBLE_LIST,
712
                                       SCRAMBLE_LIST[_mem.scramble_type - 8])
713
            rset = RadioSetting("scramble_type", "Scramble Type", rs)
714
            mem.extra.append(rset)
715

    
716
            if self.MODEL == "RB17A":
717
                rs = RadioSettingValueList(CDCSS_LIST, CDCSS_LIST[_mem.cdcss])
718
                rset = RadioSetting("cdcss", "Cdcss Mode", rs)
719
                mem.extra.append(rset)
720

    
721
        if self.MODEL == "RB26" or self.MODEL == "RT76":
722
            if self.MODEL == "RB26":
723
                rs = RadioSettingValueBoolean(_mem.bcl)
724
                rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
725
                mem.extra.append(rset)
726

    
727
            rs = RadioSettingValueBoolean(_mem.compander)
728
            rset = RadioSetting("compander", "Compander", rs)
729
            mem.extra.append(rset)
730

    
731
        if self._gmrs:
732
            GMRS_IMMUTABLE = ["freq", "duplex", "offset"]
733
            if mem.number >= 8 and mem.number <= 14:
734
                mem.immutable = GMRS_IMMUTABLE + ["power", "mode"]
735
            else:
736
                mem.immutable = GMRS_IMMUTABLE
737

    
738
        return mem
739

    
740
    def _set_tone(self, mem, _mem):
741
        def _set_dcs(code, pol):
742
            val = int("%i" % code, 8) + 0x2800
743
            if pol == "R":
744
                val += 0x8000
745
            return val
746

    
747
        rx_mode = tx_mode = None
748
        rx_tone = tx_tone = 0xFFFF
749

    
750
        if mem.tmode == "Tone":
751
            tx_mode = "Tone"
752
            rx_mode = None
753
            tx_tone = int(mem.rtone * 10)
754
        elif mem.tmode == "TSQL":
755
            rx_mode = tx_mode = "Tone"
756
            rx_tone = tx_tone = int(mem.ctone * 10)
757
        elif mem.tmode == "DTCS":
758
            tx_mode = rx_mode = "DTCS"
759
            tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
760
            rx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
761
        elif mem.tmode == "Cross":
762
            tx_mode, rx_mode = mem.cross_mode.split("->")
763
            if tx_mode == "DTCS":
764
                tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
765
            elif tx_mode == "Tone":
766
                tx_tone = int(mem.rtone * 10)
767
            if rx_mode == "DTCS":
768
                rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
769
            elif rx_mode == "Tone":
770
                rx_tone = int(mem.ctone * 10)
771

    
772
        _mem.rx_tone = rx_tone
773
        _mem.tx_tone = tx_tone
774

    
775
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
776
                  (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
777

    
778
    def set_memory(self, mem):
779
        if self._skipflags:
780
            bitpos = (1 << ((mem.number - 1) % 8))
781
            bytepos = ((mem.number - 1) / 8)
782
            LOG.debug("bitpos %s" % bitpos)
783
            LOG.debug("bytepos %s" % bytepos)
784
            _skp = self._memobj.skipflags[bytepos]
785

    
786
        if self.MODEL == "RB17A":
787
            if mem.number < 17:
788
                _mem = self._memobj.lomems[mem.number - 1]
789
            else:
790
                _mem = self._memobj.himems[mem.number - 17]
791
        else:
792
            _mem = self._memobj.memory[mem.number - 1]
793

    
794
        if self._reserved:
795
            _rsvd = _mem.reserved.get_raw()
796

    
797
        if mem.empty:
798
            if self.MODEL == "RB17A":
799
                _mem.set_raw("\xFF" * 12 + "\x00\x00\xFF\xFF")
800
            elif self.MODEL == "RB26" or self.MODEL == "RT76":
801
                _mem.set_raw("\xFF" * 13 + _rsvd)
802
            else:
803
                _mem.set_raw("\xFF" * (_mem.size() / 8))
804

    
805
            if self._gmrs:
806
                GMRS_FREQ = int(GMRS_FREQS[mem.number - 1] * 100000)
807
                if mem.number > 22:
808
                    _mem.rxfreq = GMRS_FREQ
809
                    _mem.txfreq = int(_mem.rxfreq) + 500000
810
                    _mem.wide = True
811
                else:
812
                    _mem.rxfreq = _mem.txfreq = GMRS_FREQ
813
                if mem.number >= 8 and mem.number <= 14:
814
                    _mem.wide = False
815
                    _mem.highpower = False
816
                else:
817
                    _mem.wide = True
818
                    _mem.highpower = True
819

    
820
            return
821

    
822
        if self.MODEL == "RB17A":
823
            _mem.set_raw("\x00" * 13 + "\x00\xFF\xFF")
824
        elif self.MODEL == "RB26" or self.MODEL == "RT76":
825
            _mem.set_raw("\x00" * 13 + _rsvd)
826
        else:
827
            _mem.set_raw("\x00" * 13 + "\x30\x8F\xF8")
828

    
829
        _mem.rxfreq = mem.freq / 10
830

    
831
        if mem.duplex == "off":
832
            for i in range(0, 4):
833
                _mem.txfreq[i].set_raw("\xFF")
834
        elif mem.duplex == "split":
835
            _mem.txfreq = mem.offset / 10
836
        elif mem.duplex == "+":
837
            _mem.txfreq = (mem.freq + mem.offset) / 10
838
        elif mem.duplex == "-":
839
            _mem.txfreq = (mem.freq - mem.offset) / 10
840
        else:
841
            _mem.txfreq = mem.freq / 10
842

    
843
        _mem.wide = mem.mode == "FM"
844

    
845
        self._set_tone(mem, _mem)
846

    
847
        _mem.highpower = mem.power == self.POWER_LEVELS[1]
848

    
849
        if self.MODEL != "RT76":
850
            if mem.skip != "S":
851
                _skp |= bitpos
852
            else:
853
                _skp &= ~bitpos
854
            LOG.debug("_skp %s" % _skp)
855

    
856
        for setting in mem.extra:
857
            if setting.get_name() == "scramble_type":
858
                setattr(_mem, setting.get_name(), int(setting.value) + 8)
859
                setattr(_mem, "scramble_type2", int(setting.value) + 8)
860
            else:
861
                setattr(_mem, setting.get_name(), setting.value)
862

    
863
    def get_settings(self):
864
        _settings = self._memobj.settings
865
        basic = RadioSettingGroup("basic", "Basic Settings")
866
        top = RadioSettings(basic)
867

    
868
        if self.MODEL == "RT21" or self.MODEL == "RB17A":
869
            _keys = self._memobj.keys
870

    
871
            rs = RadioSettingValueList(TIMEOUTTIMER_LIST,
872
                                       TIMEOUTTIMER_LIST[_settings.tot - 1])
873
            rset = RadioSetting("tot", "Time-out timer", rs)
874
            basic.append(rset)
875

    
876
            rs = RadioSettingValueList(TOTALERT_LIST,
877
                                       TOTALERT_LIST[_settings.totalert])
878
            rset = RadioSetting("totalert", "TOT Pre-alert", rs)
879
            basic.append(rset)
880

    
881
            rs = RadioSettingValueInteger(0, 9, _settings.squelch)
882
            rset = RadioSetting("squelch", "Squelch Level", rs)
883
            basic.append(rset)
884

    
885
            rs = RadioSettingValueList(VOICE_LIST, VOICE_LIST[_settings.voice])
886
            rset = RadioSetting("voice", "Voice Annumciation", rs)
887
            basic.append(rset)
888

    
889
            if self.MODEL == "RB17A":
890
                rs = RadioSettingValueList(ALARM_LIST,
891
                                           ALARM_LIST[_settings.alarm])
892
                rset = RadioSetting("alarm", "Alarm Type", rs)
893
                basic.append(rset)
894

    
895
            rs = RadioSettingValueBoolean(_settings.save)
896
            rset = RadioSetting("save", "Battery Saver", rs)
897
            basic.append(rset)
898

    
899
            rs = RadioSettingValueBoolean(_settings.use_scramble)
900
            rset = RadioSetting("use_scramble", "Scramble", rs)
901
            basic.append(rset)
902

    
903
            rs = RadioSettingValueBoolean(_settings.use_vox)
904
            rset = RadioSetting("use_vox", "VOX", rs)
905
            basic.append(rset)
906

    
907
            rs = RadioSettingValueList(VOX_LIST, VOX_LIST[_settings.vox])
908
            rset = RadioSetting("vox", "VOX Gain", rs)
909
            basic.append(rset)
910

    
911
            def apply_pf1_listvalue(setting, obj):
912
                LOG.debug("Setting value: " + str(
913
                          setting.value) + " from list")
914
                val = str(setting.value)
915
                index = PF1_CHOICES.index(val)
916
                val = PF1_VALUES[index]
917
                obj.set_value(val)
918

    
919
            if _keys.pf1 in PF1_VALUES:
920
                idx = PF1_VALUES.index(_keys.pf1)
921
            else:
922
                idx = LIST_DTMF_SPECIAL_VALUES.index(0x04)
923
            rs = RadioSettingValueList(PF1_CHOICES, PF1_CHOICES[idx])
924
            rset = RadioSetting("keys.pf1", "PF1 Key Function", rs)
925
            rset.set_apply_callback(apply_pf1_listvalue, _keys.pf1)
926
            basic.append(rset)
927

    
928
            def apply_topkey_listvalue(setting, obj):
929
                LOG.debug("Setting value: " + str(setting.value) +
930
                          " from list")
931
                val = str(setting.value)
932
                index = TOPKEY_CHOICES.index(val)
933
                val = TOPKEY_VALUES[index]
934
                obj.set_value(val)
935

    
936
            if self.MODEL == "RB17A":
937
                if _keys.topkey in TOPKEY_VALUES:
938
                    idx = TOPKEY_VALUES.index(_keys.topkey)
939
                else:
940
                    idx = TOPKEY_VALUES.index(0x0C)
941
                rs = RadioSettingValueList(TOPKEY_CHOICES, TOPKEY_CHOICES[idx])
942
                rset = RadioSetting("keys.topkey", "Top Key Function", rs)
943
                rset.set_apply_callback(apply_topkey_listvalue, _keys.topkey)
944
                basic.append(rset)
945

    
946
        if self.MODEL == "RB26" or self.MODEL == "RT76":
947
            if self.MODEL == "RB26":
948
                _settings2 = self._memobj.settings2
949
                _settings3 = self._memobj.settings3
950

    
951
            rs = RadioSettingValueInteger(0, 9, _settings.squelch)
952
            rset = RadioSetting("squelch", "Squelch Level", rs)
953
            basic.append(rset)
954

    
955
            rs = RadioSettingValueList(TIMEOUTTIMER_LIST,
956
                                       TIMEOUTTIMER_LIST[_settings.tot - 1])
957
            rset = RadioSetting("tot", "Time-out timer", rs)
958
            basic.append(rset)
959

    
960
            if self.MODEL == "RT76":
961
                rs = RadioSettingValueList(VOICE_LIST3,
962
                                           VOICE_LIST3[_settings.voice])
963
                rset = RadioSetting("voice", "Voice Annumciation", rs)
964
                basic.append(rset)
965

    
966
            if self.MODEL == "RB26":
967
                rs = RadioSettingValueList(VOICE_LIST2,
968
                                           VOICE_LIST2[_settings.voice])
969
                rset = RadioSetting("voice", "Voice Annumciation", rs)
970
                basic.append(rset)
971

    
972
                rs = RadioSettingValueBoolean(not _settings.chnumberd)
973
                rset = RadioSetting("chnumberd", "Channel Number Enable", rs)
974
                basic.append(rset)
975

    
976
            rs = RadioSettingValueBoolean(_settings.save)
977
            rset = RadioSetting("save", "Battery Save", rs)
978
            basic.append(rset)
979

    
980
            rs = RadioSettingValueBoolean(_settings.beep)
981
            rset = RadioSetting("beep", "Beep", rs)
982
            basic.append(rset)
983

    
984
            if self.MODEL == "RB26":
985
                rs = RadioSettingValueBoolean(not _settings.tail)
986
                rset = RadioSetting("tail", "QT/DQT Tail", rs)
987
                basic.append(rset)
988

    
989
            rs = RadioSettingValueList(SAVE_LIST, SAVE_LIST[_settings.savem])
990
            rset = RadioSetting("savem", "Battery Save Mode", rs)
991
            basic.append(rset)
992

    
993
            rs = RadioSettingValueList(GAIN_LIST, GAIN_LIST[_settings.gain])
994
            rset = RadioSetting("gain", "MIC Gain", rs)
995
            basic.append(rset)
996

    
997
            rs = RadioSettingValueList(WARN_LIST, WARN_LIST[_settings.warn])
998
            rset = RadioSetting("warn", "Warn Mode", rs)
999
            basic.append(rset)
1000

    
1001
            if self.MODEL == "RB26":
1002
                rs = RadioSettingValueBoolean(_settings3.vox)
1003
                rset = RadioSetting("settings3.vox", "Vox Function", rs)
1004
                basic.append(rset)
1005

    
1006
                rs = RadioSettingValueList(VOXL_LIST,
1007
                                           VOXL_LIST[_settings3.voxl])
1008
                rset = RadioSetting("settings3.voxl", "Vox Level", rs)
1009
                basic.append(rset)
1010

    
1011
                rs = RadioSettingValueList(VOXD_LIST,
1012
                                           VOXD_LIST[_settings3.voxd])
1013
                rset = RadioSetting("settings3.voxd", "Vox Delay", rs)
1014
                basic.append(rset)
1015

    
1016
                rs = RadioSettingValueList(PFKEY_LIST,
1017
                                           PFKEY_LIST[_settings.pf1])
1018
                rset = RadioSetting("pf1", "PF1 Key Set", rs)
1019
                basic.append(rset)
1020

    
1021
                rs = RadioSettingValueList(PFKEY_LIST,
1022
                                           PFKEY_LIST[_settings.pf2])
1023
                rset = RadioSetting("pf2", "PF2 Key Set", rs)
1024
                basic.append(rset)
1025

    
1026
                rs = RadioSettingValueInteger(1, 30, _settings2.chnumber + 1)
1027
                rset = RadioSetting("settings2.chnumber", "Channel Number", rs)
1028
                basic.append(rset)
1029

    
1030
            if self.MODEL == "RT76":
1031
                rs = RadioSettingValueBoolean(_settings.vox)
1032
                rset = RadioSetting("vox", "Vox Function", rs)
1033
                basic.append(rset)
1034

    
1035
                rs = RadioSettingValueList(VOXL_LIST,
1036
                                           VOXL_LIST[_settings.voxl])
1037
                rset = RadioSetting("voxl", "Vox Level", rs)
1038
                basic.append(rset)
1039

    
1040
                rs = RadioSettingValueList(VOXD_LIST,
1041
                                           VOXD_LIST[_settings.voxd])
1042
                rset = RadioSetting("voxd", "Vox Delay", rs)
1043
                basic.append(rset)
1044

    
1045
                rs = RadioSettingValueInteger(1, 30, _settings.chnumber + 1)
1046
                rset = RadioSetting("chnumber", "Channel Number", rs)
1047
                basic.append(rset)
1048

    
1049
        return top
1050

    
1051
    def set_settings(self, settings):
1052
        for element in settings:
1053
            if not isinstance(element, RadioSetting):
1054
                self.set_settings(element)
1055
                continue
1056
            else:
1057
                try:
1058
                    if "." in element.get_name():
1059
                        bits = element.get_name().split(".")
1060
                        obj = self._memobj
1061
                        for bit in bits[:-1]:
1062
                            obj = getattr(obj, bit)
1063
                        setting = bits[-1]
1064
                    else:
1065
                        obj = self._memobj.settings
1066
                        setting = element.get_name()
1067

    
1068
                    if element.has_apply_callback():
1069
                        LOG.debug("Using apply callback")
1070
                        element.run_apply_callback()
1071
                    elif setting == "channel":
1072
                        setattr(obj, setting, int(element.value) - 1)
1073
                    elif setting == "chnumber":
1074
                        setattr(obj, setting, int(element.value) - 1)
1075
                    elif setting == "chnumberd":
1076
                        setattr(obj, setting, not int(element.value))
1077
                    elif setting == "tail":
1078
                        setattr(obj, setting, not int(element.value))
1079
                    elif setting == "tot":
1080
                        setattr(obj, setting, int(element.value) + 1)
1081
                    elif element.value.get_mutable():
1082
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1083
                        setattr(obj, setting, element.value)
1084
                except Exception, e:
1085
                    LOG.debug(element.get_name())
1086
                    raise
1087

    
1088
    @classmethod
1089
    def match_model(cls, filedata, filename):
1090
        if cls.MODEL == "RT21":
1091
            # The RT21 is pre-metadata, so do old-school detection
1092
            match_size = False
1093
            match_model = False
1094

    
1095
            # testing the file data size
1096
            if len(filedata) in [0x0400, ]:
1097
                match_size = True
1098

    
1099
            # testing the model fingerprint
1100
            match_model = model_match(cls, filedata)
1101

    
1102
            if match_size and match_model:
1103
                return True
1104
            else:
1105
                return False
1106
        else:
1107
            # Radios that have always been post-metadata, so never do
1108
            # old-school detection
1109
            return False
1110

    
1111

    
1112
@directory.register
1113
class RB17ARadio(RT21Radio):
1114
    """RETEVIS RB17A"""
1115
    VENDOR = "Retevis"
1116
    MODEL = "RB17A"
1117
    BAUD_RATE = 9600
1118
    BLOCK_SIZE = 0x40
1119
    BLOCK_SIZE_UP = 0x10
1120

    
1121
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
1122
                    chirp_common.PowerLevel("High", watts=5.00)]
1123

    
1124
    _magic = "PROA8US"
1125
    _fingerprint = "P3217s\xF8\xFF"
1126
    _upper = 30
1127
    _skipflags = True
1128
    _reserved = False
1129
    _gmrs = True
1130

    
1131
    _ranges = [
1132
               (0x0000, 0x0300),
1133
              ]
1134
    _memsize = 0x0300
1135

    
1136
    def process_mmap(self):
1137
        self._memobj = bitwise.parse(MEM_FORMAT_RB17A, self._mmap)
1138

    
1139

    
1140
@directory.register
1141
class RB26Radio(RT21Radio):
1142
    """RETEVIS RB26"""
1143
    VENDOR = "Retevis"
1144
    MODEL = "RB26"
1145
    BAUD_RATE = 9600
1146
    BLOCK_SIZE = 0x20
1147
    BLOCK_SIZE_UP = 0x10
1148

    
1149
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
1150
                    chirp_common.PowerLevel("High", watts=3.00)]
1151

    
1152
    _magic = "PHOGR" + "\x01" + "0"
1153
    _fingerprint = "P32073" + "\x02\xFF"
1154
    _upper = 30
1155
    _skipflags = True
1156
    _reserved = True
1157
    _gmrs = True
1158

    
1159
    _ranges = [
1160
               (0x0000, 0x0320),
1161
              ]
1162
    _memsize = 0x0320
1163

    
1164
    def process_mmap(self):
1165
        self._memobj = bitwise.parse(MEM_FORMAT_RB26, self._mmap)
1166

    
1167

    
1168
@directory.register
1169
class RT76Radio(RT21Radio):
1170
    """RETEVIS RT76"""
1171
    VENDOR = "Retevis"
1172
    MODEL = "RT76"
1173
    BAUD_RATE = 9600
1174
    BLOCK_SIZE = 0x20
1175
    BLOCK_SIZE_UP = 0x10
1176

    
1177
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
1178
                    chirp_common.PowerLevel("High", watts=5.00)]
1179

    
1180
    _magic = "PHOGR\x14\xD4"
1181
    _fingerprint = "P32073" + "\x02\xFF"
1182
    _upper = 30
1183
    _skipflags = False
1184
    _reserved = True
1185
    _gmrs = True
1186

    
1187
    _ranges = [
1188
               (0x0000, 0x01E0),
1189
              ]
1190
    _memsize = 0x01E0
1191

    
1192
    def process_mmap(self):
1193
        self._memobj = bitwise.parse(MEM_FORMAT_RT76, self._mmap)
(2-2/2)