Project

General

Profile

Bug #9982 » retevis_rb26_fix_b1.2.py

Jim Unroe, 08/19/2022 01:22 AM

 
1
# Copyright 2021 Jim Unroe <rock.unroe@gmail.com>
2
#
3
# This program is free software: you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation, either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15

    
16
import time
17
import os
18
import struct
19
import logging
20

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

    
39
LOG = logging.getLogger(__name__)
40

    
41
MEM_FORMAT = """
42
#seekto 0x0010;
43
struct {
44
  lbcd rxfreq[4];       // RX Frequency           0-3
45
  lbcd txfreq[4];       // TX Frequency           4-7
46
  ul16 rx_tone;         // PL/DPL Decode          8-9
47
  ul16 tx_tone;         // PL/DPL Encode          A-B
48
  u8 unknown1:3,        //                        C
49
     bcl:2,             // Busy Lock
50
     unknown2:3;
51
  u8 unknown3:2,        //                        D
52
     highpower:1,       // Power Level
53
     wide:1,            // Bandwidth
54
     unknown4:4;
55
  u8 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
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=2.50),
540
                    chirp_common.PowerLevel("Low", watts=1.00)]
541

    
542
    VALID_BANDS = [(400000000, 480000000)]
543

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

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

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

    
580
        return rf
581

    
582
    def process_mmap(self):
583
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
584

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

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

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

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

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

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

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

    
651
        if mem.tmode == "DTCS":
652
            mem.dtcs_polarity = "%s%s" % (tpol, rpol)
653

    
654
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
655
                  (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
656

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

    
665
        mem = chirp_common.Memory()
666

    
667
        mem.number = number
668

    
669
        if self.MODEL == "RB17A":
670
            if mem.number < 17:
671
                _mem = self._memobj.lomems[number - 1]
672
            else:
673
                _mem = self._memobj.himems[number - 17]
674
        else:
675
            _mem = self._memobj.memory[number - 1]
676

    
677
        if self._reserved:
678
            _rsvd = _mem.reserved.get_raw()
679

    
680
        mem.freq = int(_mem.rxfreq) * 10
681

    
682
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
683
        if mem.freq == 0:
684
            mem.empty = True
685
            return mem
686

    
687
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
688
            mem.freq = 0
689
            mem.empty = True
690
            return mem
691

    
692
        if int(_mem.rxfreq) == int(_mem.txfreq):
693
            mem.duplex = ""
694
            mem.offset = 0
695
        else:
696
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
697
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
698

    
699
        mem.mode = _mem.wide and "FM" or "NFM"
700

    
701
        self._get_tone(_mem, mem)
702

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

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

    
721
        mem.extra = RadioSettingGroup("Extra", "extra")
722

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

    
729
            rs = RadioSettingValueInteger(1, 8, _mem.scramble_type + 1)
730
            rset = RadioSetting("scramble_type", "Scramble Type", rs)
731
            mem.extra.append(rset)
732

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

    
738
            if self.MODEL == "RT29_UHF" or self.MODEL == "RT29_VHF":
739
                rs = RadioSettingValueList(CDCSS2_LIST,
740
                                           CDCSS2_LIST[_mem.cdcss])
741
                rset = RadioSetting("cdcss", "Cdcss Mode", rs)
742
                mem.extra.append(rset)
743

    
744
            if self.MODEL == "RB17A" or self.MODEL == "RT29_UHF" or \
745
                    self.MODEL == "RT29_VHF":
746
                rs = RadioSettingValueBoolean(_mem.compander)
747
                rset = RadioSetting("compander", "Compander", rs)
748
                mem.extra.append(rset)
749

    
750
        if self.MODEL == "RB26" or self.MODEL == "RT76":
751
            if self.MODEL == "RB26":
752
                rs = RadioSettingValueBoolean(_mem.bcl)
753
                rset = RadioSetting("bcl", "Busy Channel Lockout", rs)
754
                mem.extra.append(rset)
755

    
756
            rs = RadioSettingValueBoolean(_mem.compander)
757
            rset = RadioSetting("compander", "Compander", rs)
758
            mem.extra.append(rset)
759

    
760
        return mem
761

    
762
    def _set_tone(self, mem, _mem):
763
        def _set_dcs(code, pol):
764
            val = int("%i" % code, 8) + 0x2800
765
            if pol == "R":
766
                val += 0x8000
767
            return val
768

    
769
        rx_mode = tx_mode = None
770
        rx_tone = tx_tone = 0xFFFF
771

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

    
794
        _mem.rx_tone = rx_tone
795
        _mem.tx_tone = tx_tone
796

    
797
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
798
                  (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
799

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

    
808
        if self.MODEL == "RB17A":
809
            if mem.number < 17:
810
                _mem = self._memobj.lomems[mem.number - 1]
811
            else:
812
                _mem = self._memobj.himems[mem.number - 17]
813
        else:
814
            _mem = self._memobj.memory[mem.number - 1]
815

    
816
        if self._reserved:
817
            _rsvd = _mem.reserved.get_raw()
818

    
819
        if mem.empty:
820
            if self.MODEL == "RB26" or self.MODEL == "RT76":
821
                _mem.set_raw("\xFF" * 13 + _rsvd)
822
            else:
823
                _mem.set_raw("\xFF" * (_mem.size() / 8))
824

    
825
            return
826

    
827
        if self.MODEL == "RB17A":
828
            _mem.set_raw("\x00" * 14 + "\xFF\xFF")
829
        elif self.MODEL == "RB26" or self.MODEL == "RT76":
830
            _mem.set_raw("\x00" * 13 + _rsvd)
831
        else:
832
            _mem.set_raw("\x00" * 13 + "\x30\x8F\xF8")
833

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

    
848
        _mem.rxfreq = mem.freq / 10
849

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

    
862
        _mem.wide = mem.mode == "FM"
863

    
864
        self._set_tone(mem, _mem)
865

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

    
880
        if self.MODEL != "RT76":
881
            if mem.skip != "S":
882
                _skp |= bitpos
883
            else:
884
                _skp &= ~bitpos
885
            LOG.debug("_skp %s" % _skp)
886

    
887
        for setting in mem.extra:
888
            if setting.get_name() == "scramble_type":
889
                setattr(_mem, setting.get_name(), int(setting.value) - 1)
890
                if self.MODEL == "RT21":
891
                    setattr(_mem, "scramble_type2", int(setting.value) - 1)
892
            else:
893
                setattr(_mem, setting.get_name(), setting.value)
894

    
895
    def get_settings(self):
896
        _settings = self._memobj.settings
897
        basic = RadioSettingGroup("basic", "Basic Settings")
898
        top = RadioSettings(basic)
899

    
900
        if self.MODEL == "RT21" or self.MODEL == "RB17A" or \
901
                self.MODEL == "RT29_UHF" or self.MODEL == "RT29_VHF":
902
            _keys = self._memobj.keys
903

    
904
            rs = RadioSettingValueList(TIMEOUTTIMER_LIST,
905
                                       TIMEOUTTIMER_LIST[_settings.tot])
906
            rset = RadioSetting("tot", "Time-out timer", rs)
907
            basic.append(rset)
908

    
909
            rs = RadioSettingValueList(TOTALERT_LIST,
910
                                       TOTALERT_LIST[_settings.totalert])
911
            rset = RadioSetting("totalert", "TOT Pre-alert", rs)
912
            basic.append(rset)
913

    
914
            rs = RadioSettingValueInteger(0, 9, _settings.squelch)
915
            rset = RadioSetting("squelch", "Squelch Level", rs)
916
            basic.append(rset)
917

    
918
            rs = RadioSettingValueList(VOICE_LIST, VOICE_LIST[_settings.voice])
919
            rset = RadioSetting("voice", "Voice Annumciation", rs)
920
            basic.append(rset)
921

    
922
            if self.MODEL == "RB17A":
923
                rs = RadioSettingValueList(ALARM_LIST,
924
                                           ALARM_LIST[_settings.alarm])
925
                rset = RadioSetting("alarm", "Alarm Type", rs)
926
                basic.append(rset)
927

    
928
            rs = RadioSettingValueBoolean(_settings.save)
929
            rset = RadioSetting("save", "Battery Saver", rs)
930
            basic.append(rset)
931

    
932
            rs = RadioSettingValueBoolean(_settings.use_scramble)
933
            rset = RadioSetting("use_scramble", "Scramble", rs)
934
            basic.append(rset)
935

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

    
940
            rs = RadioSettingValueList(VOX_LIST, VOX_LIST[_settings.vox])
941
            rset = RadioSetting("vox", "VOX Gain", rs)
942
            basic.append(rset)
943

    
944
            if self.MODEL == "RT29_UHF" or self.MODEL == "RT29_VHF":
945
                rs = RadioSettingValueList(VOXD_LIST,
946
                                           VOXD_LIST[_settings.voxd])
947
                rset = RadioSetting("voxd", "Vox Delay", rs)
948
                basic.append(rset)
949

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

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

    
968
            def apply_pf1_17a_listvalue(setting, obj):
969
                LOG.debug("Setting value: " + str(
970
                          setting.value) + " from list")
971
                val = str(setting.value)
972
                index = PF1_17A_CHOICES.index(val)
973
                val = PF1_17A_VALUES[index]
974
                obj.set_value(val)
975

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

    
987
            def apply_topkey_listvalue(setting, obj):
988
                LOG.debug("Setting value: " + str(setting.value) +
989
                          " from list")
990
                val = str(setting.value)
991
                index = TOPKEY_CHOICES.index(val)
992
                val = TOPKEY_VALUES[index]
993
                obj.set_value(val)
994

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

    
1005
            def apply_pfkey_listvalue(setting, obj):
1006
                LOG.debug("Setting value: " + str(setting.value) +
1007
                          " from list")
1008
                val = str(setting.value)
1009
                index = PFKEY_CHOICES.index(val)
1010
                val = PFKEY_VALUES[index]
1011
                obj.set_value(val)
1012

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

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

    
1032
        if self.MODEL == "RB26" or self.MODEL == "RT76":
1033
            if self.MODEL == "RB26":
1034
                _settings2 = self._memobj.settings2
1035
                _settings3 = self._memobj.settings3
1036

    
1037
            rs = RadioSettingValueInteger(0, 9, _settings.squelch)
1038
            rset = RadioSetting("squelch", "Squelch Level", rs)
1039
            basic.append(rset)
1040

    
1041
            rs = RadioSettingValueList(TIMEOUTTIMER_LIST,
1042
                                       TIMEOUTTIMER_LIST[_settings.tot])
1043
            rset = RadioSetting("tot", "Time-out timer", rs)
1044
            basic.append(rset)
1045

    
1046
            if self.MODEL == "RT76":
1047
                rs = RadioSettingValueList(VOICE_LIST3,
1048
                                           VOICE_LIST3[_settings.voice])
1049
                rset = RadioSetting("voice", "Voice Annumciation", rs)
1050
                basic.append(rset)
1051

    
1052
            if self.MODEL == "RB26":
1053
                rs = RadioSettingValueList(VOICE_LIST2,
1054
                                           VOICE_LIST2[_settings.voice])
1055
                rset = RadioSetting("voice", "Voice Annumciation", rs)
1056
                basic.append(rset)
1057

    
1058
                rs = RadioSettingValueBoolean(not _settings.chnumberd)
1059
                rset = RadioSetting("chnumberd", "Channel Number Enable", rs)
1060
                basic.append(rset)
1061

    
1062
            rs = RadioSettingValueBoolean(_settings.save)
1063
            rset = RadioSetting("save", "Battery Save", rs)
1064
            basic.append(rset)
1065

    
1066
            rs = RadioSettingValueBoolean(_settings.beep)
1067
            rset = RadioSetting("beep", "Beep", rs)
1068
            basic.append(rset)
1069

    
1070
            if self.MODEL == "RB26":
1071
                rs = RadioSettingValueBoolean(not _settings.tail)
1072
                rset = RadioSetting("tail", "QT/DQT Tail", rs)
1073
                basic.append(rset)
1074

    
1075
            rs = RadioSettingValueList(SAVE_LIST, SAVE_LIST[_settings.savem])
1076
            rset = RadioSetting("savem", "Battery Save Mode", rs)
1077
            basic.append(rset)
1078

    
1079
            rs = RadioSettingValueList(GAIN_LIST, GAIN_LIST[_settings.gain])
1080
            rset = RadioSetting("gain", "MIC Gain", rs)
1081
            basic.append(rset)
1082

    
1083
            rs = RadioSettingValueList(WARN_LIST, WARN_LIST[_settings.warn])
1084
            rset = RadioSetting("warn", "Warn Mode", rs)
1085
            basic.append(rset)
1086

    
1087
            if self.MODEL == "RB26":
1088
                rs = RadioSettingValueBoolean(_settings3.vox)
1089
                rset = RadioSetting("settings3.vox", "Vox Function", rs)
1090
                basic.append(rset)
1091

    
1092
                rs = RadioSettingValueList(VOXL_LIST,
1093
                                           VOXL_LIST[_settings3.voxl])
1094
                rset = RadioSetting("settings3.voxl", "Vox Level", rs)
1095
                basic.append(rset)
1096

    
1097
                rs = RadioSettingValueList(VOXD_LIST,
1098
                                           VOXD_LIST[_settings3.voxd])
1099
                rset = RadioSetting("settings3.voxd", "Vox Delay", rs)
1100
                basic.append(rset)
1101

    
1102
                rs = RadioSettingValueList(PFKEY_LIST,
1103
                                           PFKEY_LIST[_settings.pf1])
1104
                rset = RadioSetting("pf1", "PF1 Key Set", rs)
1105
                basic.append(rset)
1106

    
1107
                rs = RadioSettingValueList(PFKEY_LIST,
1108
                                           PFKEY_LIST[_settings.pf2])
1109
                rset = RadioSetting("pf2", "PF2 Key Set", rs)
1110
                basic.append(rset)
1111

    
1112
                rs = RadioSettingValueInteger(1, 30, _settings2.chnumber + 1)
1113
                rset = RadioSetting("settings2.chnumber", "Channel Number", rs)
1114
                basic.append(rset)
1115

    
1116
            if self.MODEL == "RT76":
1117
                rs = RadioSettingValueBoolean(_settings.vox)
1118
                rset = RadioSetting("vox", "Vox Function", rs)
1119
                basic.append(rset)
1120

    
1121
                rs = RadioSettingValueList(VOXL_LIST,
1122
                                           VOXL_LIST[_settings.voxl])
1123
                rset = RadioSetting("voxl", "Vox Level", rs)
1124
                basic.append(rset)
1125

    
1126
                rs = RadioSettingValueList(VOXD_LIST,
1127
                                           VOXD_LIST[_settings.voxd])
1128
                rset = RadioSetting("voxd", "Vox Delay", rs)
1129
                basic.append(rset)
1130

    
1131
                rs = RadioSettingValueInteger(1, 30, _settings.chnumber + 1)
1132
                rset = RadioSetting("chnumber", "Channel Number", rs)
1133
                basic.append(rset)
1134

    
1135
        return top
1136

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

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

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

    
1179
            # testing the file data size
1180
            if len(filedata) in [0x0400, ]:
1181
                match_size = True
1182

    
1183
            # testing the model fingerprint
1184
            match_model = model_match(cls, filedata)
1185

    
1186
            if match_size and match_model:
1187
                return True
1188
            else:
1189
                return False
1190
        else:
1191
            # Radios that have always been post-metadata, so never do
1192
            # old-school detection
1193
            return False
1194

    
1195

    
1196
@directory.register
1197
class RB17ARadio(RT21Radio):
1198
    """RETEVIS RB17A"""
1199
    VENDOR = "Retevis"
1200
    MODEL = "RB17A"
1201
    BAUD_RATE = 9600
1202
    BLOCK_SIZE = 0x40
1203
    BLOCK_SIZE_UP = 0x10
1204

    
1205
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=5.00),
1206
                    chirp_common.PowerLevel("Low", watts=0.50)]
1207

    
1208
    _magic = "PROA8US"
1209
    _fingerprint = "P3217s\xF8\xFF"
1210
    _upper = 30
1211
    _skipflags = True
1212
    _reserved = False
1213
    _gmrs = True
1214

    
1215
    _ranges = [
1216
               (0x0000, 0x0300),
1217
              ]
1218
    _memsize = 0x0300
1219

    
1220
    def process_mmap(self):
1221
        self._memobj = bitwise.parse(MEM_FORMAT_RB17A, self._mmap)
1222

    
1223

    
1224
@directory.register
1225
class RB26Radio(RT21Radio):
1226
    """RETEVIS RB26"""
1227
    VENDOR = "Retevis"
1228
    MODEL = "RB26"
1229
    BAUD_RATE = 9600
1230
    BLOCK_SIZE = 0x20
1231
    BLOCK_SIZE_UP = 0x10
1232

    
1233
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=3.00),
1234
                    chirp_common.PowerLevel("Low", watts=0.50)]
1235

    
1236
    _magic = "PHOGR" + "\x01" + "0"
1237
    _fingerprint = "P32073" + "\x02\xFF"
1238
    _upper = 30
1239
    _skipflags = True
1240
    _reserved = True
1241
    _gmrs = True
1242

    
1243
    _ranges = [
1244
               (0x0000, 0x0320),
1245
              ]
1246
    _memsize = 0x0320
1247

    
1248
    def process_mmap(self):
1249
        self._memobj = bitwise.parse(MEM_FORMAT_RB26, self._mmap)
1250

    
1251

    
1252
@directory.register
1253
class RT76Radio(RT21Radio):
1254
    """RETEVIS RT76"""
1255
    VENDOR = "Retevis"
1256
    MODEL = "RT76"
1257
    BAUD_RATE = 9600
1258
    BLOCK_SIZE = 0x20
1259
    BLOCK_SIZE_UP = 0x10
1260

    
1261
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=5.00),
1262
                    chirp_common.PowerLevel("Low", watts=0.50)]
1263

    
1264
    _magic = "PHOGR\x14\xD4"
1265
    _fingerprint = "P32073" + "\x02\xFF"
1266
    _upper = 30
1267
    _skipflags = False
1268
    _reserved = True
1269
    _gmrs = True
1270

    
1271
    _ranges = [
1272
               (0x0000, 0x01E0),
1273
              ]
1274
    _memsize = 0x01E0
1275

    
1276
    def process_mmap(self):
1277
        self._memobj = bitwise.parse(MEM_FORMAT_RT76, self._mmap)
1278

    
1279

    
1280
@directory.register
1281
class RT29UHFRadio(RT21Radio):
1282
    """RETEVIS RT29UHF"""
1283
    VENDOR = "Retevis"
1284
    MODEL = "RT29_UHF"
1285
    BLOCK_SIZE = 0x40
1286
    BLOCK_SIZE_UP = 0x10
1287

    
1288
    TXPOWER_MED = 0x00
1289
    TXPOWER_HIGH = 0x01
1290
    TXPOWER_LOW = 0x02
1291

    
1292
    POWER_LEVELS = [chirp_common.PowerLevel("Mid", watts=5.00),
1293
                    chirp_common.PowerLevel("High", watts=10.00),
1294
                    chirp_common.PowerLevel("Low", watts=1.00)]
1295

    
1296
    _magic = "PROHRAM"
1297
    _fingerprint = "P3207" + "\x13\xF8\xFF"  # UHF model
1298
    _upper = 16
1299
    _skipflags = True
1300
    _reserved = False
1301

    
1302
    _ranges = [
1303
               (0x0000, 0x0300),
1304
              ]
1305
    _memsize = 0x0400
1306

    
1307
    def process_mmap(self):
1308
        self._memobj = bitwise.parse(MEM_FORMAT_RT29, self._mmap)
1309

    
1310

    
1311
@directory.register
1312
class RT29VHFRadio(RT29UHFRadio):
1313
    """RETEVIS RT29VHF"""
1314
    VENDOR = "Retevis"
1315
    MODEL = "RT29_VHF"
1316

    
1317
    TXPOWER_MED = 0x00
1318
    TXPOWER_HIGH = 0x01
1319
    TXPOWER_LOW = 0x02
1320

    
1321
    POWER_LEVELS = [chirp_common.PowerLevel("High", watts=10.00),
1322
                    chirp_common.PowerLevel("Mid", watts=5.00),
1323
                    chirp_common.PowerLevel("Low", watts=1.00)]
1324

    
1325
    VALID_BANDS = [(136000000, 174000000)]
1326

    
1327
    _magic = "PROHRAM"
1328
    _fingerprint = "P2207" + "\x01\xF8\xFF"  # VHF model
(6-6/6)