retevis_rt21_dtcs_fix_1.py

Jim Unroe, 08/29/2022 07:18 pm

Download (44.5 kB)

 
1
# Copyright 2021-2022 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 unknown7:1,        //                        E
56
     scramble_type:3,   // Scramble Type
57
     unknown5:4;
58
  u8 unknown6:5,
59
     scramble_type2:3;  // Scramble Type 2        F
60
} memory[16];
61

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
243
MEM_FORMAT_RT29 = """
244
#seekto 0x0010;
245
struct {
246
  lbcd rxfreq[4];       // RX Frequency           0-3
247
  lbcd txfreq[4];       // TX Frequency           4-7
248
  ul16 rx_tone;         // PL/DPL Decode          8-9
249
  ul16 tx_tone;         // PL/DPL Encode          A-B
250
  u8 unknown1:2,        //                        C
251
     compander:1,       // Compander
252
     bcl:2,             // Busy Lock
253
     unknown2:3;
254
  u8 unknown3:1,        //                        D
255
     txpower:2,         // Power Level
256
     wide:1,            // Bandwidth
257
     unknown4:3,
258
     cdcss:1;           // Cdcss Mode
259
  u8 unknown5;          //                        E
260
  u8 unknown6:5,
261
     scramble_type:3;   // Scramble Type          F
262
} memory[16];
263

    
264
#seekto 0x011D;
265
struct {
266
  u8 unused1:4,
267
     pf1:4;             // Programmable Function Key 1
268
  u8 unused2:4,
269
     pf2:4;             // Programmable Function Key 2
270
} keys;
271

    
272
#seekto 0x012C;
273
struct {
274
  u8 use_scramble;      // Scramble Enable
275
  u8 unknown1[2];
276
  u8 voice;             // Voice Annunciation
277
  u8 tot;               // Time-out Timer
278
  u8 totalert;          // Time-out Timer Pre-alert
279
  u8 unknown2[2];
280
  u8 squelch;           // Squelch Level
281
  u8 save;              // Battery Saver
282
  u8 unknown3[3];
283
  u8 use_vox;           // VOX Enable
284
  u8 vox;               // VOX Gain
285
  u8 voxd;              // Vox Delay
286
} settings;
287

    
288
#seekto 0x017E;
289
u8 skipflags[2];       // SCAN_ADD
290

    
291
#seekto 0x01B8;
292
u8 fingerprint[5];     // Fingerprint
293
"""
294

    
295
CMD_ACK = "\x06"
296

    
297
ALARM_LIST = ["Local Alarm", "Remote Alarm"]
298
BCL_LIST = ["Off", "Carrier", "QT/DQT"]
299
CDCSS_LIST = ["Normal Code", "Special Code 2", "Special Code 1"]
300
CDCSS2_LIST = ["Normal Code", "Special Code"]  # RT29 UHF and RT29 VHF
301
GAIN_LIST = ["Standard", "Enhanced"]
302
PFKEY_LIST = ["None", "Monitor", "Lamp", "Warn", "VOX", "VOX Delay",
303
              "Key Lock", "Scan"]
304
SAVE_LIST = ["Standard", "Super"]
305
TIMEOUTTIMER_LIST = ["Off"] + ["%s seconds" % x for x in range(15, 615, 15)]
306
TOTALERT_LIST = ["Off"] + ["%s seconds" % x for x in range(1, 11)]
307
VOICE_LIST = ["Off", "Chinese", "English"]
308
VOICE_LIST2 = ["Off", "English"]
309
VOICE_LIST3 = VOICE_LIST2 + ["Chinese"]
310
VOX_LIST = ["OFF"] + ["%s" % x for x in range(1, 17)]
311
VOXD_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0"]
312
VOXL_LIST = ["OFF"] + ["%s" % x for x in range(1, 9)]
313
WARN_LIST = ["OFF", "Native Warn", "Remote Warn"]
314
PF1_CHOICES = ["None", "Monitor", "Scan", "Scramble", "Alarm"]
315
PF1_VALUES = [0x0F, 0x04, 0x06, 0x08, 0x0C]
316
PF1_17A_CHOICES = ["None", "Monitor", "Scan", "Scramble"]
317
PF1_17A_VALUES = [0x0F, 0x04, 0x06, 0x08]
318
PFKEY_CHOICES = ["None", "Monitor", "Scan", "Scramble", "VOX", "Alarm"]
319
PFKEY_VALUES = [0x0F, 0x04, 0x06, 0x08, 0x09, 0x0A]
320
TOPKEY_CHOICES = ["None", "Alarming"]
321
TOPKEY_VALUES = [0xFF, 0x0C]
322

    
323
SETTING_LISTS = {
324
    "alarm": ALARM_LIST,
325
    "bcl": BCL_LIST,
326
    "cdcss": CDCSS_LIST,
327
    "cdcss": CDCSS2_LIST,
328
    "gain": GAIN_LIST,
329
    "pfkey": PFKEY_LIST,
330
    "save": SAVE_LIST,
331
    "tot": TIMEOUTTIMER_LIST,
332
    "totalert": TOTALERT_LIST,
333
    "voice": VOICE_LIST,
334
    "voice": VOICE_LIST2,
335
    "voice": VOICE_LIST3,
336
    "vox": VOX_LIST,
337
    "voxd": VOXD_LIST,
338
    "voxl": VOXL_LIST,
339
    "warn": WARN_LIST,
340
    }
341

    
342
GMRS_FREQS1 = [462.5625, 462.5875, 462.6125, 462.6375, 462.6625,
343
               462.6875, 462.7125]
344
GMRS_FREQS2 = [467.5625, 467.5875, 467.6125, 467.6375, 467.6625,
345
               467.6875, 467.7125]
346
GMRS_FREQS3 = [462.5500, 462.5750, 462.6000, 462.6250, 462.6500,
347
               462.6750, 462.7000, 462.7250]
348
GMRS_FREQS = GMRS_FREQS1 + GMRS_FREQS2 + GMRS_FREQS3 * 2
349

    
350

    
351
def _enter_programming_mode(radio):
352
    serial = radio.pipe
353

    
354
    exito = False
355
    for i in range(0, 5):
356
        serial.write(radio._magic)
357
        ack = serial.read(1)
358
        if ack == "\x00":
359
            ack = serial.read(1)
360

    
361
        try:
362
            if ack == CMD_ACK:
363
                exito = True
364
                break
365
        except:
366
            LOG.debug("Attempt #%s, failed, trying again" % i)
367
            pass
368

    
369
    # check if we had EXITO
370
    if exito is False:
371
        msg = "The radio did not accept program mode after five tries.\n"
372
        msg += "Check you interface cable and power cycle your radio."
373
        raise errors.RadioError(msg)
374

    
375
    try:
376
        serial.write("\x02")
377
        ident = serial.read(8)
378
    except:
379
        raise errors.RadioError("Error communicating with radio")
380

    
381
    if not ident == radio._fingerprint:
382
        LOG.debug(util.hexprint(ident))
383
        raise errors.RadioError("Radio returned unknown identification string")
384

    
385
    try:
386
        serial.write(CMD_ACK)
387
        ack = serial.read(1)
388
    except:
389
        raise errors.RadioError("Error communicating with radio")
390

    
391
    if ack != CMD_ACK:
392
        raise errors.RadioError("Radio refused to enter programming mode")
393

    
394

    
395
def _exit_programming_mode(radio):
396
    serial = radio.pipe
397
    try:
398
        serial.write("E")
399
    except:
400
        raise errors.RadioError("Radio refused to exit programming mode")
401

    
402

    
403
def _read_block(radio, block_addr, block_size):
404
    serial = radio.pipe
405

    
406
    cmd = struct.pack(">cHb", 'R', block_addr, block_size)
407
    expectedresponse = "W" + cmd[1:]
408
    LOG.debug("Reading block %04x..." % (block_addr))
409

    
410
    try:
411
        serial.write(cmd)
412
        response = serial.read(4 + block_size)
413
        if response[:4] != expectedresponse:
414
            raise Exception("Error reading block %04x." % (block_addr))
415

    
416
        block_data = response[4:]
417

    
418
        serial.write(CMD_ACK)
419
        ack = serial.read(1)
420
    except:
421
        raise errors.RadioError("Failed to read block at %04x" % block_addr)
422

    
423
    if ack != CMD_ACK:
424
        raise Exception("No ACK reading block %04x." % (block_addr))
425

    
426
    return block_data
427

    
428

    
429
def _rb26_read_block(radio, block_addr, block_size):
430
    serial = radio.pipe
431

    
432
    cmd = struct.pack(">cHb", 'R', block_addr, block_size)
433
    expectedresponse = "W" + cmd[1:]
434
    LOG.debug("Reading block %04x..." % (block_addr))
435

    
436
    try:
437
        serial.write(cmd)
438
        response = serial.read(4 + block_size)
439
        if response[:4] != expectedresponse:
440
            raise Exception("Error reading block %04x." % (block_addr))
441

    
442
        block_data = response[4:]
443

    
444
        if block_addr != 0:
445
            serial.write(CMD_ACK)
446
            ack = serial.read(1)
447
    except:
448
        raise errors.RadioError("Failed to read block at %04x" % block_addr)
449

    
450
    if block_addr != 0:
451
        if ack != CMD_ACK:
452
            raise Exception("No ACK reading block %04x." % (block_addr))
453

    
454
    return block_data
455

    
456

    
457
def _write_block(radio, block_addr, block_size):
458
    serial = radio.pipe
459

    
460
    cmd = struct.pack(">cHb", 'W', block_addr, block_size)
461
    data = radio.get_mmap()[block_addr:block_addr + block_size]
462

    
463
    LOG.debug("Writing Data:")
464
    LOG.debug(util.hexprint(cmd + data))
465

    
466
    try:
467
        serial.write(cmd + data)
468
        if serial.read(1) != CMD_ACK:
469
            raise Exception("No ACK")
470
    except:
471
        raise errors.RadioError("Failed to send block "
472
                                "to radio at %04x" % block_addr)
473

    
474

    
475
def do_download(radio):
476
    LOG.debug("download")
477
    _enter_programming_mode(radio)
478

    
479
    data = ""
480

    
481
    status = chirp_common.Status()
482
    status.msg = "Cloning from radio"
483

    
484
    status.cur = 0
485
    status.max = radio._memsize
486

    
487
    for addr in range(0, radio._memsize, radio.BLOCK_SIZE):
488
        status.cur = addr + radio.BLOCK_SIZE
489
        radio.status_fn(status)
490

    
491
        if radio.MODEL == "RB26" or radio.MODEL == "RT76":
492
            block = _rb26_read_block(radio, addr, radio.BLOCK_SIZE)
493
        else:
494
            block = _read_block(radio, addr, radio.BLOCK_SIZE)
495
        data += block
496

    
497
        LOG.debug("Address: %04x" % addr)
498
        LOG.debug(util.hexprint(block))
499

    
500
    _exit_programming_mode(radio)
501

    
502
    return memmap.MemoryMap(data)
503

    
504

    
505
def do_upload(radio):
506
    status = chirp_common.Status()
507
    status.msg = "Uploading to radio"
508

    
509
    _enter_programming_mode(radio)
510

    
511
    status.cur = 0
512
    status.max = radio._memsize
513

    
514
    for start_addr, end_addr in radio._ranges:
515
        for addr in range(start_addr, end_addr, radio.BLOCK_SIZE_UP):
516
            status.cur = addr + radio.BLOCK_SIZE_UP
517
            radio.status_fn(status)
518
            _write_block(radio, addr, radio.BLOCK_SIZE_UP)
519

    
520
    _exit_programming_mode(radio)
521

    
522

    
523
def model_match(cls, data):
524
    """Match the opened/downloaded image to the correct version"""
525
    rid = data[0x01B8:0x01BE]
526

    
527
    return rid.startswith("P3207")
528

    
529

    
530
@directory.register
531
class RT21Radio(chirp_common.CloneModeRadio):
532
    """RETEVIS RT21"""
533
    VENDOR = "Retevis"
534
    MODEL = "RT21"
535
    BAUD_RATE = 9600
536
    BLOCK_SIZE = 0x10
537
    BLOCK_SIZE_UP = 0x10
538

    
539
    DTCS_CODES = sorted(chirp_common.DTCS_CODES + [17, 50, 645])
540
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.50),
541
                    chirp_common.PowerLevel("Low", watts=1.00)]
542

    
543
    VALID_BANDS = [(400000000, 480000000)]
544

    
545
    _magic = "PRMZUNE"
546
    _fingerprint = "P3207s\xF8\xFF"
547
    _upper = 16
548
    _skipflags = True
549
    _reserved = False
550
    _gmrs = False
551

    
552
    _ranges = [
553
               (0x0000, 0x0400),
554
              ]
555
    _memsize = 0x0400
556

    
557
    def get_features(self):
558
        rf = chirp_common.RadioFeatures()
559
        rf.has_settings = True
560
        rf.has_bank = False
561
        rf.has_ctone = True
562
        rf.has_cross = True
563
        rf.has_rx_dtcs = True
564
        rf.has_tuning_step = False
565
        rf.can_odd_split = True
566
        rf.has_name = False
567
        if self.MODEL == "RT76":
568
            rf.valid_skips = []
569
        else:
570
            rf.valid_skips = ["", "S"]
571
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
572
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
573
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
574
        rf.valid_power_levels = self.POWER_LEVELS
575
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
576
        rf.valid_modes = ["FM", "NFM"]  # 25 KHz, 12.5 kHz.
577
        rf.valid_dtcs_codes = self.DTCS_CODES
578
        rf.memory_bounds = (1, self._upper)
579
        rf.valid_tuning_steps = [2.5, 5., 6.25, 10., 12.5, 25.]
580
        rf.valid_bands = self.VALID_BANDS
581

    
582
        return rf
583

    
584
    def process_mmap(self):
585
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
586

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

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

    
614
    def get_raw_memory(self, number):
615
        return repr(self._memobj.memory[number - 1])
616

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

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

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

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

    
655
        # always set it even if no dtcs is used
656
        mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")
657

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

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

    
669
        mem = chirp_common.Memory()
670

    
671
        mem.number = number
672

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

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

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

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

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

    
696
        if int(_mem.rxfreq) == int(_mem.txfreq):
697
            mem.duplex = ""
698
            mem.offset = 0
699
        else:
700
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
701
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
702

    
703
        mem.mode = _mem.wide and "FM" or "NFM"
704

    
705
        self._get_tone(_mem, mem)
706

    
707
        if self.MODEL == "RT29_UHF" or self.MODEL == "RT29_VHF":
708
            # set the power level
709
            if _mem.txpower == self.TXPOWER_LOW:
710
                mem.power = self.POWER_LEVELS[2]
711
            elif _mem.txpower == self.TXPOWER_MED:
712
                mem.power = self.POWER_LEVELS[1]
713
            elif _mem.txpower == self.TXPOWER_HIGH:
714
                mem.power = self.POWER_LEVELS[0]
715
            else:
716
                LOG.error('%s: get_mem: unhandled power level: 0x%02x' %
717
                          (mem.name, _mem.txpower))
718
        else:
719
            mem.power = self.POWER_LEVELS[1 - _mem.highpower]
720

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

    
725
        mem.extra = RadioSettingGroup("Extra", "extra")
726

    
727
        if self.MODEL == "RT21" or self.MODEL == "RB17A" or \
728
                self.MODEL == "RT29_UHF" or self.MODEL == "RT29_VHF":
729
            rs = RadioSettingValueList(BCL_LIST, BCL_LIST[_mem.bcl])
730
            rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
731
            mem.extra.append(rset)
732

    
733
            rs = RadioSettingValueInteger(1, 8, _mem.scramble_type + 1)
734
            rset = RadioSetting("scramble_type", "Scramble Type", rs)
735
            mem.extra.append(rset)
736

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

    
742
            if self.MODEL == "RT29_UHF" or self.MODEL == "RT29_VHF":
743
                rs = RadioSettingValueList(CDCSS2_LIST,
744
                                           CDCSS2_LIST[_mem.cdcss])
745
                rset = RadioSetting("cdcss", "Cdcss Mode", rs)
746
                mem.extra.append(rset)
747

    
748
            if self.MODEL == "RB17A" or self.MODEL == "RT29_UHF" or \
749
                    self.MODEL == "RT29_VHF":
750
                rs = RadioSettingValueBoolean(_mem.compander)
751
                rset = RadioSetting("compander", "Compander", rs)
752
                mem.extra.append(rset)
753

    
754
        if self.MODEL == "RB26" or self.MODEL == "RT76":
755
            if self.MODEL == "RB26":
756
                rs = RadioSettingValueBoolean(_mem.bcl)
757
                rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
758
                mem.extra.append(rset)
759

    
760
            rs = RadioSettingValueBoolean(_mem.compander)
761
            rset = RadioSetting("compander", "Compander", rs)
762
            mem.extra.append(rset)
763

    
764
        return mem
765

    
766
    def _set_tone(self, mem, _mem):
767
        def _set_dcs(code, pol):
768
            val = int("%i" % code, 8) + 0x2000
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 == "RB26" or self.MODEL == "RT76":
825
                _mem.set_raw("\xFF" * 13 + _rsvd)
826
            else:
827
                _mem.set_raw("\xFF" * (_mem.size() / 8))
828

    
829
            return
830

    
831
        if self.MODEL == "RB17A":
832
            _mem.set_raw("\x00" * 14 + "\xFF\xFF")
833
        elif self.MODEL == "RB26" or self.MODEL == "RT76":
834
            _mem.set_raw("\x00" * 13 + _rsvd)
835
        else:
836
            _mem.set_raw("\x00" * 13 + "\x30\x8F\xF8")
837

    
838
        if self._gmrs:
839
            if mem.number >= 1 and mem.number <= 30:
840
                GMRS_FREQ = int(GMRS_FREQS[mem.number - 1] * 1000000)
841
                mem.freq = GMRS_FREQ
842
                if mem.number <= 22:
843
                    mem.duplex = ''
844
                    mem.offset = 0
845
                    if mem.number >= 8 and mem.number <= 14:
846
                        mem.mode = "NFM"
847
                        mem.power = self.POWER_LEVELS[1]
848
                if mem.number > 22:
849
                    mem.duplex = '+'
850
                    mem.offset = 5000000
851

    
852
        _mem.rxfreq = mem.freq / 10
853

    
854
        if mem.duplex == "off":
855
            for i in range(0, 4):
856
                _mem.txfreq[i].set_raw("\xFF")
857
        elif mem.duplex == "split":
858
            _mem.txfreq = mem.offset / 10
859
        elif mem.duplex == "+":
860
            _mem.txfreq = (mem.freq + mem.offset) / 10
861
        elif mem.duplex == "-":
862
            _mem.txfreq = (mem.freq - mem.offset) / 10
863
        else:
864
            _mem.txfreq = mem.freq / 10
865

    
866
        _mem.wide = mem.mode == "FM"
867

    
868
        self._set_tone(mem, _mem)
869

    
870
        if self.MODEL == "RT29_UHF" or self.MODEL == "RT29_VHF":
871
            # set the power level
872
            if mem.power == self.POWER_LEVELS[2]:
873
                _mem.txpower = self.TXPOWER_LOW
874
            elif mem.power == self.POWER_LEVELS[1]:
875
                _mem.txpower = self.TXPOWER_MED
876
            elif mem.power == self.POWER_LEVELS[0]:
877
                _mem.txpower = self.TXPOWER_HIGH
878
            else:
879
                LOG.error('%s: set_mem: unhandled power level: %s' %
880
                          (mem.name, mem.power))
881
        else:
882
            _mem.highpower = mem.power == self.POWER_LEVELS[0]
883

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

    
891
        for setting in mem.extra:
892
            if setting.get_name() == "scramble_type":
893
                setattr(_mem, setting.get_name(), int(setting.value) - 1)
894
                if self.MODEL == "RT21":
895
                    setattr(_mem, "scramble_type2", int(setting.value) - 1)
896
            else:
897
                setattr(_mem, setting.get_name(), setting.value)
898

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

    
904
        if self.MODEL == "RT21" or self.MODEL == "RB17A" or \
905
                self.MODEL == "RT29_UHF" or self.MODEL == "RT29_VHF":
906
            _keys = self._memobj.keys
907

    
908
            rs = RadioSettingValueList(TIMEOUTTIMER_LIST,
909
                                       TIMEOUTTIMER_LIST[_settings.tot])
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
            if self.MODEL == "RT29_UHF" or self.MODEL == "RT29_VHF":
949
                rs = RadioSettingValueList(VOXD_LIST,
950
                                           VOXD_LIST[_settings.voxd])
951
                rset = RadioSetting("voxd", "Vox Delay", rs)
952
                basic.append(rset)
953

    
954
            def apply_pf1_listvalue(setting, obj):
955
                LOG.debug("Setting value: " + str(
956
                          setting.value) + " from list")
957
                val = str(setting.value)
958
                index = PF1_CHOICES.index(val)
959
                val = PF1_VALUES[index]
960
                obj.set_value(val)
961

    
962
            if self.MODEL == "RT21":
963
                if _keys.pf1 in PF1_VALUES:
964
                    idx = PF1_VALUES.index(_keys.pf1)
965
                else:
966
                    idx = LIST_DTMF_SPECIAL_VALUES.index(0x04)
967
                rs = RadioSettingValueList(PF1_CHOICES, PF1_CHOICES[idx])
968
                rset = RadioSetting("keys.pf1", "PF1 Key Function", rs)
969
                rset.set_apply_callback(apply_pf1_listvalue, _keys.pf1)
970
                basic.append(rset)
971

    
972
            def apply_pf1_17a_listvalue(setting, obj):
973
                LOG.debug("Setting value: " + str(
974
                          setting.value) + " from list")
975
                val = str(setting.value)
976
                index = PF1_17A_CHOICES.index(val)
977
                val = PF1_17A_VALUES[index]
978
                obj.set_value(val)
979

    
980
            if self.MODEL == "RB17A":
981
                if _keys.pf1 in PF1_17A_VALUES:
982
                    idx = PF1_17A_VALUES.index(_keys.pf1)
983
                else:
984
                    idx = LIST_DTMF_SPECIAL_VALUES.index(0x04)
985
                rs = RadioSettingValueList(PF1_17A_CHOICES,
986
                                           PF1_17A_CHOICES[idx])
987
                rset = RadioSetting("keys.pf1", "PF1 Key Function", rs)
988
                rset.set_apply_callback(apply_pf1_17a_listvalue, _keys.pf1)
989
                basic.append(rset)
990

    
991
            def apply_topkey_listvalue(setting, obj):
992
                LOG.debug("Setting value: " + str(setting.value) +
993
                          " from list")
994
                val = str(setting.value)
995
                index = TOPKEY_CHOICES.index(val)
996
                val = TOPKEY_VALUES[index]
997
                obj.set_value(val)
998

    
999
            if self.MODEL == "RB17A":
1000
                if _keys.topkey in TOPKEY_VALUES:
1001
                    idx = TOPKEY_VALUES.index(_keys.topkey)
1002
                else:
1003
                    idx = TOPKEY_VALUES.index(0x0C)
1004
                rs = RadioSettingValueList(TOPKEY_CHOICES, TOPKEY_CHOICES[idx])
1005
                rset = RadioSetting("keys.topkey", "Top Key Function", rs)
1006
                rset.set_apply_callback(apply_topkey_listvalue, _keys.topkey)
1007
                basic.append(rset)
1008

    
1009
            def apply_pfkey_listvalue(setting, obj):
1010
                LOG.debug("Setting value: " + str(setting.value) +
1011
                          " from list")
1012
                val = str(setting.value)
1013
                index = PFKEY_CHOICES.index(val)
1014
                val = PFKEY_VALUES[index]
1015
                obj.set_value(val)
1016

    
1017
            if self.MODEL == "RT29_UHF" or self.MODEL == "RT29_VHF":
1018
                if _keys.pf1 in PFKEY_VALUES:
1019
                    idx = PFKEY_VALUES.index(_keys.pf1)
1020
                else:
1021
                    idx = PFKEY_VALUES.index(0x04)
1022
                rs = RadioSettingValueList(PFKEY_CHOICES, PFKEY_CHOICES[idx])
1023
                rset = RadioSetting("keys.pf1", "PF1 Key Function", rs)
1024
                rset.set_apply_callback(apply_pfkey_listvalue, _keys.pf1)
1025
                basic.append(rset)
1026

    
1027
                if _keys.pf2 in PFKEY_VALUES:
1028
                    idx = PFKEY_VALUES.index(_keys.pf2)
1029
                else:
1030
                    idx = PFKEY_VALUES.index(0x0A)
1031
                rs = RadioSettingValueList(PFKEY_CHOICES, PFKEY_CHOICES[idx])
1032
                rset = RadioSetting("keys.pf2", "PF2 Key Function", rs)
1033
                rset.set_apply_callback(apply_pfkey_listvalue, _keys.pf2)
1034
                basic.append(rset)
1035

    
1036
        if self.MODEL == "RB26" or self.MODEL == "RT76":
1037
            if self.MODEL == "RB26":
1038
                _settings2 = self._memobj.settings2
1039
                _settings3 = self._memobj.settings3
1040

    
1041
            rs = RadioSettingValueInteger(0, 9, _settings.squelch)
1042
            rset = RadioSetting("squelch", "Squelch Level", rs)
1043
            basic.append(rset)
1044

    
1045
            rs = RadioSettingValueList(TIMEOUTTIMER_LIST,
1046
                                       TIMEOUTTIMER_LIST[_settings.tot])
1047
            rset = RadioSetting("tot", "Time-out timer", rs)
1048
            basic.append(rset)
1049

    
1050
            if self.MODEL == "RT76":
1051
                rs = RadioSettingValueList(VOICE_LIST3,
1052
                                           VOICE_LIST3[_settings.voice])
1053
                rset = RadioSetting("voice", "Voice Annumciation", rs)
1054
                basic.append(rset)
1055

    
1056
            if self.MODEL == "RB26":
1057
                rs = RadioSettingValueList(VOICE_LIST2,
1058
                                           VOICE_LIST2[_settings.voice])
1059
                rset = RadioSetting("voice", "Voice Annumciation", rs)
1060
                basic.append(rset)
1061

    
1062
                rs = RadioSettingValueBoolean(not _settings.chnumberd)
1063
                rset = RadioSetting("chnumberd", "Channel Number Enable", rs)
1064
                basic.append(rset)
1065

    
1066
            rs = RadioSettingValueBoolean(_settings.save)
1067
            rset = RadioSetting("save", "Battery Save", rs)
1068
            basic.append(rset)
1069

    
1070
            rs = RadioSettingValueBoolean(_settings.beep)
1071
            rset = RadioSetting("beep", "Beep", rs)
1072
            basic.append(rset)
1073

    
1074
            if self.MODEL == "RB26":
1075
                rs = RadioSettingValueBoolean(not _settings.tail)
1076
                rset = RadioSetting("tail", "QT/DQT Tail", rs)
1077
                basic.append(rset)
1078

    
1079
            rs = RadioSettingValueList(SAVE_LIST, SAVE_LIST[_settings.savem])
1080
            rset = RadioSetting("savem", "Battery Save Mode", rs)
1081
            basic.append(rset)
1082

    
1083
            rs = RadioSettingValueList(GAIN_LIST, GAIN_LIST[_settings.gain])
1084
            rset = RadioSetting("gain", "MIC Gain", rs)
1085
            basic.append(rset)
1086

    
1087
            rs = RadioSettingValueList(WARN_LIST, WARN_LIST[_settings.warn])
1088
            rset = RadioSetting("warn", "Warn Mode", rs)
1089
            basic.append(rset)
1090

    
1091
            if self.MODEL == "RB26":
1092
                rs = RadioSettingValueBoolean(_settings3.vox)
1093
                rset = RadioSetting("settings3.vox", "Vox Function", rs)
1094
                basic.append(rset)
1095

    
1096
                rs = RadioSettingValueList(VOXL_LIST,
1097
                                           VOXL_LIST[_settings3.voxl])
1098
                rset = RadioSetting("settings3.voxl", "Vox Level", rs)
1099
                basic.append(rset)
1100

    
1101
                rs = RadioSettingValueList(VOXD_LIST,
1102
                                           VOXD_LIST[_settings3.voxd])
1103
                rset = RadioSetting("settings3.voxd", "Vox Delay", rs)
1104
                basic.append(rset)
1105

    
1106
                rs = RadioSettingValueList(PFKEY_LIST,
1107
                                           PFKEY_LIST[_settings.pf1])
1108
                rset = RadioSetting("pf1", "PF1 Key Set", rs)
1109
                basic.append(rset)
1110

    
1111
                rs = RadioSettingValueList(PFKEY_LIST,
1112
                                           PFKEY_LIST[_settings.pf2])
1113
                rset = RadioSetting("pf2", "PF2 Key Set", rs)
1114
                basic.append(rset)
1115

    
1116
                rs = RadioSettingValueInteger(1, 30, _settings2.chnumber + 1)
1117
                rset = RadioSetting("settings2.chnumber", "Channel Number", rs)
1118
                basic.append(rset)
1119

    
1120
            if self.MODEL == "RT76":
1121
                rs = RadioSettingValueBoolean(_settings.vox)
1122
                rset = RadioSetting("vox", "Vox Function", rs)
1123
                basic.append(rset)
1124

    
1125
                rs = RadioSettingValueList(VOXL_LIST,
1126
                                           VOXL_LIST[_settings.voxl])
1127
                rset = RadioSetting("voxl", "Vox Level", rs)
1128
                basic.append(rset)
1129

    
1130
                rs = RadioSettingValueList(VOXD_LIST,
1131
                                           VOXD_LIST[_settings.voxd])
1132
                rset = RadioSetting("voxd", "Vox Delay", rs)
1133
                basic.append(rset)
1134

    
1135
                rs = RadioSettingValueInteger(1, 30, _settings.chnumber + 1)
1136
                rset = RadioSetting("chnumber", "Channel Number", rs)
1137
                basic.append(rset)
1138

    
1139
        return top
1140

    
1141
    def set_settings(self, settings):
1142
        for element in settings:
1143
            if not isinstance(element, RadioSetting):
1144
                self.set_settings(element)
1145
                continue
1146
            else:
1147
                try:
1148
                    if "." in element.get_name():
1149
                        bits = element.get_name().split(".")
1150
                        obj = self._memobj
1151
                        for bit in bits[:-1]:
1152
                            obj = getattr(obj, bit)
1153
                        setting = bits[-1]
1154
                    else:
1155
                        obj = self._memobj.settings
1156
                        setting = element.get_name()
1157

    
1158
                    if element.has_apply_callback():
1159
                        LOG.debug("Using apply callback")
1160
                        element.run_apply_callback()
1161
                    elif setting == "channel":
1162
                        setattr(obj, setting, int(element.value) - 1)
1163
                    elif setting == "chnumber":
1164
                        setattr(obj, setting, int(element.value) - 1)
1165
                    elif setting == "chnumberd":
1166
                        setattr(obj, setting, not int(element.value))
1167
                    elif setting == "tail":
1168
                        setattr(obj, setting, not int(element.value))
1169
                    elif element.value.get_mutable():
1170
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1171
                        setattr(obj, setting, element.value)
1172
                except Exception, e:
1173
                    LOG.debug(element.get_name())
1174
                    raise
1175

    
1176
    @classmethod
1177
    def match_model(cls, filedata, filename):
1178
        if cls.MODEL == "RT21":
1179
            # The RT21 is pre-metadata, so do old-school detection
1180
            match_size = False
1181
            match_model = False
1182

    
1183
            # testing the file data size
1184
            if len(filedata) in [0x0400, ]:
1185
                match_size = True
1186

    
1187
            # testing the model fingerprint
1188
            match_model = model_match(cls, filedata)
1189

    
1190
            if match_size and match_model:
1191
                return True
1192
            else:
1193
                return False
1194
        else:
1195
            # Radios that have always been post-metadata, so never do
1196
            # old-school detection
1197
            return False
1198

    
1199

    
1200
@directory.register
1201
class RB17ARadio(RT21Radio):
1202
    """RETEVIS RB17A"""
1203
    VENDOR = "Retevis"
1204
    MODEL = "RB17A"
1205
    BAUD_RATE = 9600
1206
    BLOCK_SIZE = 0x40
1207
    BLOCK_SIZE_UP = 0x10
1208

    
1209
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=5.00),
1210
                    chirp_common.PowerLevel("Low", watts=0.50)]
1211

    
1212
    _magic = "PROA8US"
1213
    _fingerprint = "P3217s\xF8\xFF"
1214
    _upper = 30
1215
    _skipflags = True
1216
    _reserved = False
1217
    _gmrs = True
1218

    
1219
    _ranges = [
1220
               (0x0000, 0x0300),
1221
              ]
1222
    _memsize = 0x0300
1223

    
1224
    def process_mmap(self):
1225
        self._memobj = bitwise.parse(MEM_FORMAT_RB17A, self._mmap)
1226

    
1227

    
1228
@directory.register
1229
class RB26Radio(RT21Radio):
1230
    """RETEVIS RB26"""
1231
    VENDOR = "Retevis"
1232
    MODEL = "RB26"
1233
    BAUD_RATE = 9600
1234
    BLOCK_SIZE = 0x20
1235
    BLOCK_SIZE_UP = 0x10
1236

    
1237
    DTCS_CODES = sorted(chirp_common.DTCS_CODES + [645])
1238
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=3.00),
1239
                    chirp_common.PowerLevel("Low", watts=0.50)]
1240

    
1241
    _magic = "PHOGR" + "\x01" + "0"
1242
    _fingerprint = "P32073" + "\x02\xFF"
1243
    _upper = 30
1244
    _skipflags = True
1245
    _reserved = True
1246
    _gmrs = True
1247

    
1248
    _ranges = [
1249
               (0x0000, 0x0320),
1250
              ]
1251
    _memsize = 0x0320
1252

    
1253
    def process_mmap(self):
1254
        self._memobj = bitwise.parse(MEM_FORMAT_RB26, self._mmap)
1255

    
1256

    
1257
@directory.register
1258
class RT76Radio(RT21Radio):
1259
    """RETEVIS RT76"""
1260
    VENDOR = "Retevis"
1261
    MODEL = "RT76"
1262
    BAUD_RATE = 9600
1263
    BLOCK_SIZE = 0x20
1264
    BLOCK_SIZE_UP = 0x10
1265

    
1266
    DTCS_CODES = sorted(chirp_common.DTCS_CODES + [645])
1267
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=5.00),
1268
                    chirp_common.PowerLevel("Low", watts=0.50)]
1269

    
1270
    _magic = "PHOGR\x14\xD4"
1271
    _fingerprint = "P32073" + "\x02\xFF"
1272
    _upper = 30
1273
    _skipflags = False
1274
    _reserved = True
1275
    _gmrs = True
1276

    
1277
    _ranges = [
1278
               (0x0000, 0x01E0),
1279
              ]
1280
    _memsize = 0x01E0
1281

    
1282
    def process_mmap(self):
1283
        self._memobj = bitwise.parse(MEM_FORMAT_RT76, self._mmap)
1284

    
1285

    
1286
@directory.register
1287
class RT29UHFRadio(RT21Radio):
1288
    """RETEVIS RT29UHF"""
1289
    VENDOR = "Retevis"
1290
    MODEL = "RT29_UHF"
1291
    BLOCK_SIZE = 0x40
1292
    BLOCK_SIZE_UP = 0x10
1293

    
1294
    TXPOWER_MED = 0x00
1295
    TXPOWER_HIGH = 0x01
1296
    TXPOWER_LOW = 0x02
1297

    
1298
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=10.00),
1299
                    chirp_common.PowerLevel("Mid", watts=5.00),
1300
                    chirp_common.PowerLevel("Low", watts=1.00)]
1301

    
1302
    _magic = "PROHRAM"
1303
    _fingerprint = "P3207" + "\x13\xF8\xFF"  # UHF model
1304
    _upper = 16
1305
    _skipflags = True
1306
    _reserved = False
1307

    
1308
    _ranges = [
1309
               (0x0000, 0x0300),
1310
              ]
1311
    _memsize = 0x0400
1312

    
1313
    def process_mmap(self):
1314
        self._memobj = bitwise.parse(MEM_FORMAT_RT29, self._mmap)
1315

    
1316

    
1317
@directory.register
1318
class RT29VHFRadio(RT29UHFRadio):
1319
    """RETEVIS RT29VHF"""
1320
    VENDOR = "Retevis"
1321
    MODEL = "RT29_VHF"
1322

    
1323
    TXPOWER_MED = 0x00
1324
    TXPOWER_HIGH = 0x01
1325
    TXPOWER_LOW = 0x02
1326

    
1327
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=10.00),
1328
                    chirp_common.PowerLevel("Mid", watts=5.00),
1329
                    chirp_common.PowerLevel("Low", watts=1.00)]
1330

    
1331
    VALID_BANDS = [(136000000, 174000000)]
1332

    
1333
    _magic = "PROHRAM"
1334
    _fingerprint = "P2207" + "\x01\xF8\xFF"  # VHF model