Project

General

Profile

New Model #9579 » retevis_rt21v_dl_only.py

Jim Unroe, 12/05/2021 04:54 PM

 
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
        ack = serial.read(1)
301
        if ack == "\x00":
302
            ack = serial.read(1)
303

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

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

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

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

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

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

    
337

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

    
345

    
346
def _read_block(radio, block_addr, block_size):
347
    serial = radio.pipe
348

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

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

    
359
        block_data = response[4:]
360

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

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

    
369
    return block_data
370

    
371

    
372
def _rb26_read_block(radio, block_addr, block_size):
373
    serial = radio.pipe
374

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

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

    
385
        block_data = response[4:]
386

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

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

    
397
    return block_data
398

    
399

    
400
def _write_block(radio, block_addr, block_size):
401
    serial = radio.pipe
402

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

    
406
    LOG.debug("Writing Data:")
407
    LOG.debug(util.hexprint(cmd + data))
408

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

    
417

    
418
def do_download(radio):
419
    LOG.debug("download")
420
    _enter_programming_mode(radio)
421

    
422
    data = ""
423

    
424
    status = chirp_common.Status()
425
    status.msg = "Cloning from radio"
426

    
427
    status.cur = 0
428
    status.max = radio._memsize
429

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

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

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

    
443
    _exit_programming_mode(radio)
444

    
445
    return memmap.MemoryMap(data)
446

    
447

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

    
452
    _enter_programming_mode(radio)
453

    
454
    status.cur = 0
455
    status.max = radio._memsize
456

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

    
463
    _exit_programming_mode(radio)
464

    
465

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

    
470
    return rid.startswith("P3207")
471

    
472

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

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

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

    
492
    _ranges = [
493
               (0x0000, 0x0400),
494
              ]
495
    _memsize = 0x0400
496

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

    
518
        return rf
519

    
520
    def process_mmap(self):
521
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
522

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

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

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

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

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

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

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

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

    
567
        return msgs
568

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

    
585
    def sync_out(self):
586
        """Upload to radio"""
587
        try:
588
            do_not_do_upload(self)
589
        except:
590
            # If anything unexpected happens, make sure we raise
591
            # a RadioError and log the problem
592
            LOG.exception('Unexpected error during upload')
593
            raise errors.RadioError('For download testing only, '
594
                                    'uploading has been disabled.')
595

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

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

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

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

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

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

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

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

    
649
        mem = chirp_common.Memory()
650

    
651
        mem.number = number
652

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

    
661
        if self._reserved:
662
            _rsvd = _mem.reserved.get_raw()
663

    
664
        mem.freq = int(_mem.rxfreq) * 10
665

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

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

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

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

    
692
        mem.mode = _mem.wide and "FM" or "NFM"
693

    
694
        self._get_tone(_mem, mem)
695

    
696
        mem.power = self.POWER_LEVELS[_mem.highpower]
697

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

    
702
        mem.extra = RadioSettingGroup("Extra", "extra")
703

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

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

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

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

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

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

    
736
        return mem
737

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

    
745
        rx_mode = tx_mode = None
746
        rx_tone = tx_tone = 0xFFFF
747

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

    
770
        _mem.rx_tone = rx_tone
771
        _mem.tx_tone = tx_tone
772

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

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

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

    
792
        if self._reserved:
793
            _rsvd = _mem.reserved.get_raw()
794

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

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

    
818
            return
819

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

    
827
        _mem.rxfreq = mem.freq / 10
828

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

    
841
        _mem.wide = mem.mode == "FM"
842

    
843
        self._set_tone(mem, _mem)
844

    
845
        _mem.highpower = mem.power == self.POWER_LEVELS[1]
846

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

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

    
861

    
862
    def set_settings(self, settings):
863
        for element in settings:
864
            if not isinstance(element, RadioSetting):
865
                self.set_settings(element)
866
                continue
867
            else:
868
                try:
869
                    if "." in element.get_name():
870
                        bits = element.get_name().split(".")
871
                        obj = self._memobj
872
                        for bit in bits[:-1]:
873
                            obj = getattr(obj, bit)
874
                        setting = bits[-1]
875
                    else:
876
                        obj = self._memobj.settings
877
                        setting = element.get_name()
878

    
879
                    if element.has_apply_callback():
880
                        LOG.debug("Using apply callback")
881
                        element.run_apply_callback()
882
                    elif setting == "channel":
883
                        setattr(obj, setting, int(element.value) - 1)
884
                    elif setting == "chnumber":
885
                        setattr(obj, setting, int(element.value) - 1)
886
                    elif setting == "chnumberd":
887
                        setattr(obj, setting, not int(element.value))
888
                    elif setting == "tail":
889
                        setattr(obj, setting, not int(element.value))
890
                    elif setting == "tot":
891
                        setattr(obj, setting, int(element.value) + 1)
892
                    elif element.value.get_mutable():
893
                        LOG.debug("Setting %s = %s" % (setting, element.value))
894
                        setattr(obj, setting, element.value)
895
                except Exception, e:
896
                    LOG.debug(element.get_name())
897
                    raise
898

    
899
    @classmethod
900
    def match_model(cls, filedata, filename):
901
        if cls.MODEL == "RT21":
902
            # The RT21 is pre-metadata, so do old-school detection
903
            match_size = False
904
            match_model = False
905

    
906
            # testing the file data size
907
            if len(filedata) in [0x0400, ]:
908
                match_size = True
909

    
910
            # testing the model fingerprint
911
            match_model = model_match(cls, filedata)
912

    
913
            if match_size and match_model:
914
                return True
915
            else:
916
                return False
917
        else:
918
            # Radios that have always been post-metadata, so never do
919
            # old-school detection
920
            return False
921

    
922

    
923
@directory.register
924
class RB17ARadio(RT21Radio):
925
    """RETEVIS RB17A"""
926
    VENDOR = "Retevis"
927
    MODEL = "RB17A"
928
    BAUD_RATE = 9600
929
    BLOCK_SIZE = 0x40
930
    BLOCK_SIZE_UP = 0x10
931

    
932
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
933
                    chirp_common.PowerLevel("High", watts=5.00)]
934

    
935
    _magic = "PROA8US"
936
    _fingerprint = "P3217s\xF8\xFF"
937
    _upper = 30
938
    _skipflags = True
939
    _reserved = False
940
    _gmrs = True
941

    
942
    _ranges = [
943
               (0x0000, 0x0300),
944
              ]
945
    _memsize = 0x0300
946

    
947
    def process_mmap(self):
948
        self._memobj = bitwise.parse(MEM_FORMAT_RB17A, self._mmap)
949

    
950

    
951
@directory.register
952
class RB26Radio(RT21Radio):
953
    """RETEVIS RB26"""
954
    VENDOR = "Retevis"
955
    MODEL = "RB26"
956
    BAUD_RATE = 9600
957
    BLOCK_SIZE = 0x20
958
    BLOCK_SIZE_UP = 0x10
959

    
960
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
961
                    chirp_common.PowerLevel("High", watts=3.00)]
962

    
963
    _magic = "PHOGR" + "\x01" + "0"
964
    _fingerprint = "P32073" + "\x02\xFF"
965
    _upper = 30
966
    _skipflags = True
967
    _reserved = True
968
    _gmrs = True
969

    
970
    _ranges = [
971
               (0x0000, 0x0320),
972
              ]
973
    _memsize = 0x0320
974

    
975
    def process_mmap(self):
976
        self._memobj = bitwise.parse(MEM_FORMAT_RB26, self._mmap)
977

    
978

    
979
@directory.register
980
class RT76Radio(RT21Radio):
981
    """RETEVIS RT76"""
982
    VENDOR = "Retevis"
983
    MODEL = "RT76"
984
    BAUD_RATE = 9600
985
    BLOCK_SIZE = 0x20
986
    BLOCK_SIZE_UP = 0x10
987

    
988
    POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=0.50),
989
                    chirp_common.PowerLevel("High", watts=5.00)]
990

    
991
    _magic = "PHOGR\x14\xD4"
992
    _fingerprint = "P32073" + "\x02\xFF"
993
    _upper = 30
994
    _skipflags = False
995
    _reserved = True
996
    _gmrs = True
997

    
998
    _ranges = [
999
               (0x0000, 0x01E0),
1000
              ]
1001
    _memsize = 0x01E0
1002

    
1003
    def process_mmap(self):
1004
        self._memobj = bitwise.parse(MEM_FORMAT_RT76, self._mmap)
1005

    
1006

    
1007
@directory.register
1008
class RT21Radio(chirp_common.CloneModeRadio):
1009
    """RETEVIS RT21"""
1010
    VENDOR = "Retevis"
1011
    MODEL = "RT21V"
1012
    ##BAUD_RATE = 9600
1013
    ##BLOCK_SIZE = 0x10
1014
    ##BLOCK_SIZE_UP = 0x10
1015

    
1016
    ##POWER_LEVELS = [chirp_common.PowerLevel("Low", watts=1.00),
1017
    ##                chirp_common.PowerLevel("High", watts=2.50)]
1018

    
1019
    ##_magic = "PRMZUNE"
1020
    _fingerprint = "P2207\x01\xF8\xFF"
1021
    ##_upper = 16
1022
    ##_skipflags = True
1023
    ##_reserved = False
1024
    ##_gmrs = False
1025

    
1026
    ##_ranges = [
1027
    ##           (0x0000, 0x0400),
1028
    ##          ]
1029
    ##_memsize = 0x0400
(2-2/14)