retevis_rt21_rt21v_#2.py

Jim Unroe, 12/14/2021 01:36 pm

Download (41.6 kB)

 
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
MURS_FREQS = [151.820, 151.880, 151.940, 154.570, 154.600]
294

    
295

    
296
def _enter_programming_mode(radio):
297
    serial = radio.pipe
298

    
299
    exito = False
300
    for i in range(0, 5):
301
        serial.write(radio._magic)
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
    _murs = False
494

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

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

    
521
        return rf
522

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

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

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

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

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

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

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

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

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

    
570
        # MURS models
571
        if self._murs:
572
            # range of memories with values set by FCC rules
573
            if mem.freq != int(MURS_FREQS[mem.number - 1] * 1000000):
574
                # warn user can't change frequency
575
                msgs.append(chirp_common.ValidationError(_msg_freq))
576

    
577
            # channels 1 - 5 are simplex only
578
            if str(mem.duplex) != "":
579
                # warn user can't change duplex
580
                msgs.append(chirp_common.ValidationError(_msg_simplex))
581

    
582
            # channels 1 - 3 are NFM only
583
            if mem.number <= 3:
584
                if mem.mode != "NFM":
585
                    # warn user can't change mode
586
                    msgs.append(chirp_common.ValidationError(_msg_nfm))
587

    
588
        return msgs
589

    
590
    def sync_in(self):
591
        """Download from radio"""
592
        try:
593
            data = do_download(self)
594
        except errors.RadioError:
595
            # Pass through any real errors we raise
596
            raise
597
        except:
598
            # If anything unexpected happens, make sure we raise
599
            # a RadioError and log the problem
600
            LOG.exception('Unexpected error during download')
601
            raise errors.RadioError('Unexpected error communicating '
602
                                    'with the radio')
603
        self._mmap = data
604
        self.process_mmap()
605

    
606
    def sync_out(self):
607
        """Upload to radio"""
608
        try:
609
            do_upload(self)
610
        except:
611
            # If anything unexpected happens, make sure we raise
612
            # a RadioError and log the problem
613
            LOG.exception('Unexpected error during upload')
614
            raise errors.RadioError('Unexpected error communicating '
615
                                    'with the radio')
616

    
617
    def get_raw_memory(self, number):
618
        return repr(self._memobj.memory[number - 1])
619

    
620
    def _get_tone(self, _mem, mem):
621
        def _get_dcs(val):
622
            code = int("%03o" % (val & 0x07FF))
623
            pol = (val & 0x8000) and "R" or "N"
624
            return code, pol
625

    
626
        if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2000:
627
            tcode, tpol = _get_dcs(_mem.tx_tone)
628
            mem.dtcs = tcode
629
            txmode = "DTCS"
630
        elif _mem.tx_tone != 0xFFFF:
631
            mem.rtone = _mem.tx_tone / 10.0
632
            txmode = "Tone"
633
        else:
634
            txmode = ""
635

    
636
        if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2000:
637
            rcode, rpol = _get_dcs(_mem.rx_tone)
638
            mem.rx_dtcs = rcode
639
            rxmode = "DTCS"
640
        elif _mem.rx_tone != 0xFFFF:
641
            mem.ctone = _mem.rx_tone / 10.0
642
            rxmode = "Tone"
643
        else:
644
            rxmode = ""
645

    
646
        if txmode == "Tone" and not rxmode:
647
            mem.tmode = "Tone"
648
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
649
            mem.tmode = "TSQL"
650
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
651
            mem.tmode = "DTCS"
652
        elif rxmode or txmode:
653
            mem.tmode = "Cross"
654
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
655

    
656
        if mem.tmode == "DTCS":
657
            mem.dtcs_polarity = "%s%s" % (tpol, rpol)
658

    
659
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
660
                  (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
661

    
662
    def get_memory(self, number):
663
        if self._skipflags:
664
            bitpos = (1 << ((number - 1) % 8))
665
            bytepos = ((number - 1) / 8)
666
            LOG.debug("bitpos %s" % bitpos)
667
            LOG.debug("bytepos %s" % bytepos)
668
            _skp = self._memobj.skipflags[bytepos]
669

    
670
        mem = chirp_common.Memory()
671

    
672
        mem.number = number
673

    
674
        if self.MODEL == "RB17A":
675
            if mem.number < 17:
676
                _mem = self._memobj.lomems[number - 1]
677
            else:
678
                _mem = self._memobj.himems[number - 17]
679
        else:
680
            _mem = self._memobj.memory[number - 1]
681

    
682
        if self._reserved:
683
            _rsvd = _mem.reserved.get_raw()
684

    
685
        mem.freq = int(_mem.rxfreq) * 10
686

    
687
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
688
        if mem.freq == 0:
689
            mem.empty = True
690
            return mem
691

    
692
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
693
            mem.freq = 0
694
            mem.empty = True
695
            return mem
696

    
697
        if _mem.get_raw() == ("\xFF" * 16):
698
            LOG.debug("Initializing empty memory")
699
            if self.MODEL == "RB17A":
700
                _mem.set_raw("\x00" * 13 + "\x04\xFF\xFF")
701
            if self.MODEL == "RB26" or self.MODEL == "RT76":
702
                _mem.set_raw("\x00" * 13 + _rsvd)
703
            else:
704
                _mem.set_raw("\x00" * 13 + "\x30\x8F\xF8")
705

    
706
        if int(_mem.rxfreq) == int(_mem.txfreq):
707
            mem.duplex = ""
708
            mem.offset = 0
709
        else:
710
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
711
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
712

    
713
        mem.mode = _mem.wide and "FM" or "NFM"
714

    
715
        self._get_tone(_mem, mem)
716

    
717
        mem.power = self.POWER_LEVELS[_mem.highpower]
718

    
719
        if self.MODEL != "RT76":
720
            mem.skip = "" if (_skp & bitpos) else "S"
721
            LOG.debug("mem.skip %s" % mem.skip)
722

    
723
        mem.extra = RadioSettingGroup("Extra", "extra")
724

    
725
        if self.MODEL == "RT21" or self.MODEL == "RT21V" or self.MODEL == "RB17A":
726
            rs = RadioSettingValueList(BCL_LIST, BCL_LIST[_mem.bcl])
727
            rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
728
            mem.extra.append(rset)
729

    
730
            rs = RadioSettingValueList(SCRAMBLE_LIST,
731
                                       SCRAMBLE_LIST[_mem.scramble_type - 8])
732
            rset = RadioSetting("scramble_type", "Scramble Type", rs)
733
            mem.extra.append(rset)
734

    
735
            if self.MODEL == "RB17A":
736
                rs = RadioSettingValueList(CDCSS_LIST, CDCSS_LIST[_mem.cdcss])
737
                rset = RadioSetting("cdcss", "Cdcss Mode", rs)
738
                mem.extra.append(rset)
739

    
740
        if self.MODEL == "RB26" or self.MODEL == "RT76":
741
            if self.MODEL == "RB26":
742
                rs = RadioSettingValueBoolean(_mem.bcl)
743
                rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
744
                mem.extra.append(rset)
745

    
746
            rs = RadioSettingValueBoolean(_mem.compander)
747
            rset = RadioSetting("compander", "Compander", rs)
748
            mem.extra.append(rset)
749

    
750
        if self._gmrs:
751
            GMRS_IMMUTABLE = ["freq", "duplex", "offset"]
752
            if mem.number >= 8 and mem.number <= 14:
753
                mem.immutable = GMRS_IMMUTABLE + ["power", "mode"]
754
            else:
755
                mem.immutable = GMRS_IMMUTABLE
756

    
757
        if self._murs:
758
            MURS_IMMUTABLE = ["freq", "duplex", "offset"]
759
            if mem.number <= 3:
760
                mem.immutable = MURS_IMMUTABLE + ["mode"]
761
            else:
762
                mem.immutable = MURS_IMMUTABLE
763

    
764
        return mem
765

    
766
    def _set_tone(self, mem, _mem):
767
        def _set_dcs(code, pol):
768
            val = int("%i" % code, 8) + 0x2800
769
            if pol == "R":
770
                val += 0x8000
771
            return val
772

    
773
        rx_mode = tx_mode = None
774
        rx_tone = tx_tone = 0xFFFF
775

    
776
        if mem.tmode == "Tone":
777
            tx_mode = "Tone"
778
            rx_mode = None
779
            tx_tone = int(mem.rtone * 10)
780
        elif mem.tmode == "TSQL":
781
            rx_mode = tx_mode = "Tone"
782
            rx_tone = tx_tone = int(mem.ctone * 10)
783
        elif mem.tmode == "DTCS":
784
            tx_mode = rx_mode = "DTCS"
785
            tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
786
            rx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
787
        elif mem.tmode == "Cross":
788
            tx_mode, rx_mode = mem.cross_mode.split("->")
789
            if tx_mode == "DTCS":
790
                tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
791
            elif tx_mode == "Tone":
792
                tx_tone = int(mem.rtone * 10)
793
            if rx_mode == "DTCS":
794
                rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
795
            elif rx_mode == "Tone":
796
                rx_tone = int(mem.ctone * 10)
797

    
798
        _mem.rx_tone = rx_tone
799
        _mem.tx_tone = tx_tone
800

    
801
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
802
                  (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
803

    
804
    def set_memory(self, mem):
805
        if self._skipflags:
806
            bitpos = (1 << ((mem.number - 1) % 8))
807
            bytepos = ((mem.number - 1) / 8)
808
            LOG.debug("bitpos %s" % bitpos)
809
            LOG.debug("bytepos %s" % bytepos)
810
            _skp = self._memobj.skipflags[bytepos]
811

    
812
        if self.MODEL == "RB17A":
813
            if mem.number < 17:
814
                _mem = self._memobj.lomems[mem.number - 1]
815
            else:
816
                _mem = self._memobj.himems[mem.number - 17]
817
        else:
818
            _mem = self._memobj.memory[mem.number - 1]
819

    
820
        if self._reserved:
821
            _rsvd = _mem.reserved.get_raw()
822

    
823
        if mem.empty:
824
            if self.MODEL == "RB17A":
825
                _mem.set_raw("\xFF" * 12 + "\x00\x00\xFF\xFF")
826
            elif self.MODEL == "RB26" or self.MODEL == "RT76":
827
                _mem.set_raw("\xFF" * 13 + _rsvd)
828
            else:
829
                _mem.set_raw("\xFF" * (_mem.size() / 8))
830

    
831
            if self._gmrs:
832
                _mem.set_raw("\xFF" * 12 + "\x00\x00\xFF\xFF")
833
                GMRS_FREQ = int(GMRS_FREQS[mem.number - 1] * 100000)
834
                if mem.number > 22:
835
                    _mem.rxfreq = GMRS_FREQ
836
                    _mem.txfreq = int(_mem.rxfreq) + 500000
837
                    _mem.wide = True
838
                else:
839
                    _mem.rxfreq = _mem.txfreq = GMRS_FREQ
840
                if mem.number >= 8 and mem.number <= 14:
841
                    _mem.wide = False
842
                    _mem.highpower = False
843
                else:
844
                    _mem.wide = True
845
                    _mem.highpower = True
846

    
847
            if self._murs:
848
                _mem.set_raw("\xFF" * 12 + "\x00\x00\xFF\xFF")
849
                MURS_FREQ = int(MURS_FREQS[mem.number - 1] * 100000)
850
                _mem.rxfreq = _mem.txfreq = MURS_FREQ
851
                _mem.highpower = True
852
                if mem.number <= 3:
853
                    _mem.wide = False
854
                else:
855
                    _mem.wide = True
856

    
857
            return
858

    
859
        if self.MODEL == "RB17A":
860
            _mem.set_raw("\x00" * 13 + "\x00\xFF\xFF")
861
        elif self.MODEL == "RB26" or self.MODEL == "RT76":
862
            _mem.set_raw("\x00" * 13 + _rsvd)
863
        else:
864
            _mem.set_raw("\x00" * 13 + "\x30\x8F\xF8")
865

    
866
        _mem.rxfreq = mem.freq / 10
867

    
868
        if mem.duplex == "off":
869
            for i in range(0, 4):
870
                _mem.txfreq[i].set_raw("\xFF")
871
        elif mem.duplex == "split":
872
            _mem.txfreq = mem.offset / 10
873
        elif mem.duplex == "+":
874
            _mem.txfreq = (mem.freq + mem.offset) / 10
875
        elif mem.duplex == "-":
876
            _mem.txfreq = (mem.freq - mem.offset) / 10
877
        else:
878
            _mem.txfreq = mem.freq / 10
879

    
880
        _mem.wide = mem.mode == "FM"
881

    
882
        self._set_tone(mem, _mem)
883

    
884
        _mem.highpower = mem.power == self.POWER_LEVELS[1]
885

    
886
        if self.MODEL != "RT76":
887
            if mem.skip != "S":
888
                _skp |= bitpos
889
            else:
890
                _skp &= ~bitpos
891
            LOG.debug("_skp %s" % _skp)
892

    
893
        for setting in mem.extra:
894
            if setting.get_name() == "scramble_type":
895
                setattr(_mem, setting.get_name(), int(setting.value) + 8)
896
                setattr(_mem, "scramble_type2", int(setting.value) + 8)
897
            else:
898
                setattr(_mem, setting.get_name(), setting.value)
899

    
900
    def get_settings(self):
901
        _settings = self._memobj.settings
902
        basic = RadioSettingGroup("basic", "Basic Settings")
903
        top = RadioSettings(basic)
904

    
905
        if self.MODEL == "RT21" or self.MODEL == "RT21V"  or self.MODEL == "RB17A":
906
            _keys = self._memobj.keys
907

    
908
            rs = RadioSettingValueList(TIMEOUTTIMER_LIST,
909
                                       TIMEOUTTIMER_LIST[_settings.tot - 1])
910
            rset = RadioSetting("tot", "Time-out timer", rs)
911
            basic.append(rset)
912

    
913
            rs = RadioSettingValueList(TOTALERT_LIST,
914
                                       TOTALERT_LIST[_settings.totalert])
915
            rset = RadioSetting("totalert", "TOT Pre-alert", rs)
916
            basic.append(rset)
917

    
918
            rs = RadioSettingValueInteger(0, 9, _settings.squelch)
919
            rset = RadioSetting("squelch", "Squelch Level", rs)
920
            basic.append(rset)
921

    
922
            rs = RadioSettingValueList(VOICE_LIST, VOICE_LIST[_settings.voice])
923
            rset = RadioSetting("voice", "Voice Annumciation", rs)
924
            basic.append(rset)
925

    
926
            if self.MODEL == "RB17A":
927
                rs = RadioSettingValueList(ALARM_LIST,
928
                                           ALARM_LIST[_settings.alarm])
929
                rset = RadioSetting("alarm", "Alarm Type", rs)
930
                basic.append(rset)
931

    
932
            rs = RadioSettingValueBoolean(_settings.save)
933
            rset = RadioSetting("save", "Battery Saver", rs)
934
            basic.append(rset)
935

    
936
            rs = RadioSettingValueBoolean(_settings.use_scramble)
937
            rset = RadioSetting("use_scramble", "Scramble", rs)
938
            basic.append(rset)
939

    
940
            rs = RadioSettingValueBoolean(_settings.use_vox)
941
            rset = RadioSetting("use_vox", "VOX", rs)
942
            basic.append(rset)
943

    
944
            rs = RadioSettingValueList(VOX_LIST, VOX_LIST[_settings.vox])
945
            rset = RadioSetting("vox", "VOX Gain", rs)
946
            basic.append(rset)
947

    
948
            def apply_pf1_listvalue(setting, obj):
949
                LOG.debug("Setting value: " + str(
950
                          setting.value) + " from list")
951
                val = str(setting.value)
952
                index = PF1_CHOICES.index(val)
953
                val = PF1_VALUES[index]
954
                obj.set_value(val)
955

    
956
            if _keys.pf1 in PF1_VALUES:
957
                idx = PF1_VALUES.index(_keys.pf1)
958
            else:
959
                idx = LIST_DTMF_SPECIAL_VALUES.index(0x04)
960
            rs = RadioSettingValueList(PF1_CHOICES, PF1_CHOICES[idx])
961
            rset = RadioSetting("keys.pf1", "PF1 Key Function", rs)
962
            rset.set_apply_callback(apply_pf1_listvalue, _keys.pf1)
963
            basic.append(rset)
964

    
965
            def apply_topkey_listvalue(setting, obj):
966
                LOG.debug("Setting value: " + str(setting.value) +
967
                          " from list")
968
                val = str(setting.value)
969
                index = TOPKEY_CHOICES.index(val)
970
                val = TOPKEY_VALUES[index]
971
                obj.set_value(val)
972

    
973
            if self.MODEL == "RB17A":
974
                if _keys.topkey in TOPKEY_VALUES:
975
                    idx = TOPKEY_VALUES.index(_keys.topkey)
976
                else:
977
                    idx = TOPKEY_VALUES.index(0x0C)
978
                rs = RadioSettingValueList(TOPKEY_CHOICES, TOPKEY_CHOICES[idx])
979
                rset = RadioSetting("keys.topkey", "Top Key Function", rs)
980
                rset.set_apply_callback(apply_topkey_listvalue, _keys.topkey)
981
                basic.append(rset)
982

    
983
        if self.MODEL == "RB26" or self.MODEL == "RT76":
984
            if self.MODEL == "RB26":
985
                _settings2 = self._memobj.settings2
986
                _settings3 = self._memobj.settings3
987

    
988
            rs = RadioSettingValueInteger(0, 9, _settings.squelch)
989
            rset = RadioSetting("squelch", "Squelch Level", rs)
990
            basic.append(rset)
991

    
992
            rs = RadioSettingValueList(TIMEOUTTIMER_LIST,
993
                                       TIMEOUTTIMER_LIST[_settings.tot - 1])
994
            rset = RadioSetting("tot", "Time-out timer", rs)
995
            basic.append(rset)
996

    
997
            if self.MODEL == "RT76":
998
                rs = RadioSettingValueList(VOICE_LIST3,
999
                                           VOICE_LIST3[_settings.voice])
1000
                rset = RadioSetting("voice", "Voice Annumciation", rs)
1001
                basic.append(rset)
1002

    
1003
            if self.MODEL == "RB26":
1004
                rs = RadioSettingValueList(VOICE_LIST2,
1005
                                           VOICE_LIST2[_settings.voice])
1006
                rset = RadioSetting("voice", "Voice Annumciation", rs)
1007
                basic.append(rset)
1008

    
1009
                rs = RadioSettingValueBoolean(not _settings.chnumberd)
1010
                rset = RadioSetting("chnumberd", "Channel Number Enable", rs)
1011
                basic.append(rset)
1012

    
1013
            rs = RadioSettingValueBoolean(_settings.save)
1014
            rset = RadioSetting("save", "Battery Save", rs)
1015
            basic.append(rset)
1016

    
1017
            rs = RadioSettingValueBoolean(_settings.beep)
1018
            rset = RadioSetting("beep", "Beep", rs)
1019
            basic.append(rset)
1020

    
1021
            if self.MODEL == "RB26":
1022
                rs = RadioSettingValueBoolean(not _settings.tail)
1023
                rset = RadioSetting("tail", "QT/DQT Tail", rs)
1024
                basic.append(rset)
1025

    
1026
            rs = RadioSettingValueList(SAVE_LIST, SAVE_LIST[_settings.savem])
1027
            rset = RadioSetting("savem", "Battery Save Mode", rs)
1028
            basic.append(rset)
1029

    
1030
            rs = RadioSettingValueList(GAIN_LIST, GAIN_LIST[_settings.gain])
1031
            rset = RadioSetting("gain", "MIC Gain", rs)
1032
            basic.append(rset)
1033

    
1034
            rs = RadioSettingValueList(WARN_LIST, WARN_LIST[_settings.warn])
1035
            rset = RadioSetting("warn", "Warn Mode", rs)
1036
            basic.append(rset)
1037

    
1038
            if self.MODEL == "RB26":
1039
                rs = RadioSettingValueBoolean(_settings3.vox)
1040
                rset = RadioSetting("settings3.vox", "Vox Function", rs)
1041
                basic.append(rset)
1042

    
1043
                rs = RadioSettingValueList(VOXL_LIST,
1044
                                           VOXL_LIST[_settings3.voxl])
1045
                rset = RadioSetting("settings3.voxl", "Vox Level", rs)
1046
                basic.append(rset)
1047

    
1048
                rs = RadioSettingValueList(VOXD_LIST,
1049
                                           VOXD_LIST[_settings3.voxd])
1050
                rset = RadioSetting("settings3.voxd", "Vox Delay", rs)
1051
                basic.append(rset)
1052

    
1053
                rs = RadioSettingValueList(PFKEY_LIST,
1054
                                           PFKEY_LIST[_settings.pf1])
1055
                rset = RadioSetting("pf1", "PF1 Key Set", rs)
1056
                basic.append(rset)
1057

    
1058
                rs = RadioSettingValueList(PFKEY_LIST,
1059
                                           PFKEY_LIST[_settings.pf2])
1060
                rset = RadioSetting("pf2", "PF2 Key Set", rs)
1061
                basic.append(rset)
1062

    
1063
                rs = RadioSettingValueInteger(1, 30, _settings2.chnumber + 1)
1064
                rset = RadioSetting("settings2.chnumber", "Channel Number", rs)
1065
                basic.append(rset)
1066

    
1067
            if self.MODEL == "RT76":
1068
                rs = RadioSettingValueBoolean(_settings.vox)
1069
                rset = RadioSetting("vox", "Vox Function", rs)
1070
                basic.append(rset)
1071

    
1072
                rs = RadioSettingValueList(VOXL_LIST,
1073
                                           VOXL_LIST[_settings.voxl])
1074
                rset = RadioSetting("voxl", "Vox Level", rs)
1075
                basic.append(rset)
1076

    
1077
                rs = RadioSettingValueList(VOXD_LIST,
1078
                                           VOXD_LIST[_settings.voxd])
1079
                rset = RadioSetting("voxd", "Vox Delay", rs)
1080
                basic.append(rset)
1081

    
1082
                rs = RadioSettingValueInteger(1, 30, _settings.chnumber + 1)
1083
                rset = RadioSetting("chnumber", "Channel Number", rs)
1084
                basic.append(rset)
1085

    
1086
        return top
1087

    
1088
    def set_settings(self, settings):
1089
        for element in settings:
1090
            if not isinstance(element, RadioSetting):
1091
                self.set_settings(element)
1092
                continue
1093
            else:
1094
                try:
1095
                    if "." in element.get_name():
1096
                        bits = element.get_name().split(".")
1097
                        obj = self._memobj
1098
                        for bit in bits[:-1]:
1099
                            obj = getattr(obj, bit)
1100
                        setting = bits[-1]
1101
                    else:
1102
                        obj = self._memobj.settings
1103
                        setting = element.get_name()
1104

    
1105
                    if element.has_apply_callback():
1106
                        LOG.debug("Using apply callback")
1107
                        element.run_apply_callback()
1108
                    elif setting == "channel":
1109
                        setattr(obj, setting, int(element.value) - 1)
1110
                    elif setting == "chnumber":
1111
                        setattr(obj, setting, int(element.value) - 1)
1112
                    elif setting == "chnumberd":
1113
                        setattr(obj, setting, not int(element.value))
1114
                    elif setting == "tail":
1115
                        setattr(obj, setting, not int(element.value))
1116
                    elif setting == "tot":
1117
                        setattr(obj, setting, int(element.value) + 1)
1118
                    elif element.value.get_mutable():
1119
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1120
                        setattr(obj, setting, element.value)
1121
                except Exception, e:
1122
                    LOG.debug(element.get_name())
1123
                    raise
1124

    
1125
    @classmethod
1126
    def match_model(cls, filedata, filename):
1127
        if cls.MODEL == "RT21":
1128
            # The RT21 is pre-metadata, so do old-school detection
1129
            match_size = False
1130
            match_model = False
1131

    
1132
            # testing the file data size
1133
            if len(filedata) in [0x0400, ]:
1134
                match_size = True
1135

    
1136
            # testing the model fingerprint
1137
            match_model = model_match(cls, filedata)
1138

    
1139
            if match_size and match_model:
1140
                return True
1141
            else:
1142
                return False
1143
        else:
1144
            # Radios that have always been post-metadata, so never do
1145
            # old-school detection
1146
            return False
1147

    
1148

    
1149
@directory.register
1150
class RB17ARadio(RT21Radio):
1151
    """RETEVIS RB17A"""
1152
    VENDOR = "Retevis"
1153
    MODEL = "RB17A"
1154
    BAUD_RATE = 9600
1155
    BLOCK_SIZE = 0x40
1156
    BLOCK_SIZE_UP = 0x10
1157

    
1158
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
1159
                    chirp_common.PowerLevel("High", watts=5.00)]
1160

    
1161
    _magic = "PROA8US"
1162
    _fingerprint = "P3217s\xF8\xFF"
1163
    _upper = 30
1164
    _skipflags = True
1165
    _reserved = False
1166
    _gmrs = True
1167

    
1168
    _ranges = [
1169
               (0x0000, 0x0300),
1170
              ]
1171
    _memsize = 0x0300
1172

    
1173
    def process_mmap(self):
1174
        self._memobj = bitwise.parse(MEM_FORMAT_RB17A, self._mmap)
1175

    
1176

    
1177
@directory.register
1178
class RB26Radio(RT21Radio):
1179
    """RETEVIS RB26"""
1180
    VENDOR = "Retevis"
1181
    MODEL = "RB26"
1182
    BAUD_RATE = 9600
1183
    BLOCK_SIZE = 0x20
1184
    BLOCK_SIZE_UP = 0x10
1185

    
1186
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
1187
                    chirp_common.PowerLevel("High", watts=3.00)]
1188

    
1189
    _magic = "PHOGR" + "\x01" + "0"
1190
    _fingerprint = "P32073" + "\x02\xFF"
1191
    _upper = 30
1192
    _skipflags = True
1193
    _reserved = True
1194
    _gmrs = True
1195

    
1196
    _ranges = [
1197
               (0x0000, 0x0320),
1198
              ]
1199
    _memsize = 0x0320
1200

    
1201
    def process_mmap(self):
1202
        self._memobj = bitwise.parse(MEM_FORMAT_RB26, self._mmap)
1203

    
1204

    
1205
@directory.register
1206
class RT76Radio(RT21Radio):
1207
    """RETEVIS RT76"""
1208
    VENDOR = "Retevis"
1209
    MODEL = "RT76"
1210
    BAUD_RATE = 9600
1211
    BLOCK_SIZE = 0x20
1212
    BLOCK_SIZE_UP = 0x10
1213

    
1214
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
1215
                    chirp_common.PowerLevel("High", watts=5.00)]
1216

    
1217
    _magic = "PHOGR\x14\xD4"
1218
    _fingerprint = "P32073" + "\x02\xFF"
1219
    _upper = 30
1220
    _skipflags = False
1221
    _reserved = True
1222
    _gmrs = True
1223

    
1224
    _ranges = [
1225
               (0x0000, 0x01E0),
1226
              ]
1227
    _memsize = 0x01E0
1228

    
1229
    def process_mmap(self):
1230
        self._memobj = bitwise.parse(MEM_FORMAT_RT76, self._mmap)
1231

    
1232

    
1233
@directory.register
1234
class RT21VRadio(RT21Radio):
1235
    """RETEVIS RT21V"""
1236
    VENDOR = "Retevis"
1237
    MODEL = "RT21V"
1238

    
1239
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1.00),
1240
                    chirp_common.PowerLevel("High", watts=2.00)]
1241

    
1242
    _fingerprint = "P2207\x01\xF8\xFF"
1243
    _upper = 5
1244
    _murs = True
1245

    
1246
    def get_features(self):
1247
        rf = RT21Radio.get_features(self)
1248
        rf.valid_bands = [(136000000, 174000000)]
1249
        return rf