Project

General

Profile

New Model #5109 ยป retevis_rt22(r1_test).py

Jim Unroe, 08/26/2017 07:12 PM

 
1
# Copyright 2016 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 chirp_common, directory, memmap
22
from chirp import bitwise, errors, util
23
from chirp.settings import RadioSetting, RadioSettingGroup, \
24
    RadioSettingValueInteger, RadioSettingValueList, \
25
    RadioSettingValueBoolean, RadioSettings, \
26
    RadioSettingValueString
27

    
28
LOG = logging.getLogger(__name__)
29

    
30
MEM_FORMAT = """
31
#seekto 0x0010;
32
struct {
33
  lbcd rxfreq[4];                
34
  lbcd txfreq[4];                
35
  ul16 rx_tone;                  
36
  ul16 tx_tone;                  
37
  u8 unknown1;                   
38
  u8 unknown3:2,                 
39
     highpower:1, // Power Level 
40
     wide:1,      // Bandwidth   
41
     unknown4:4;                 
42
  u8 unknown5[2];
43
} memory[16];
44

    
45
#seekto 0x012F;
46
struct {
47
  u8 voice;       // Voice Annunciation
48
  u8 tot;         // Time-out Timer                   
49
  u8 unknown1[3];
50
  u8 squelch;     // Squelch Level
51
  u8 save;        // Battery Saver                    
52
  u8 beep;        // Beep                             
53
  u8 unknown2[2];
54
  u8 vox;         // VOX
55
  u8 voxgain;     // VOX Gain
56
  u8 voxdelay;    // VOX Delay                        
57
  u8 unknown3[2];
58
  u8 pf2key;      // PF2 Key                          
59
} settings;
60

    
61
#seekto 0x017E;
62
u8 skipflags[2];  // SCAN_ADD
63

    
64
#seekto 0x0300;
65
struct {
66
  char line1[32];
67
  char line2[32];
68
} embedded_msg;
69
"""
70

    
71
CMD_ACK = "\x06"
72

    
73
RT22_POWER_LEVELS = [chirp_common.PowerLevel("Low",  watts=2.00),
74
                     chirp_common.PowerLevel("High", watts=5.00)]
75

    
76
RT22_DTCS = sorted(chirp_common.DTCS_CODES + [645])
77

    
78
PF2KEY_LIST = ["Scan", "Local Alarm", "Remote Alarm"]
79
TIMEOUTTIMER_LIST = [""] + ["%s seconds" % x for x in range(15, 615, 15)]
80
VOICE_LIST = ["Off", "Chinese", "English"]
81
VOX_LIST = ["OFF"] + ["%s" % x for x in range(1, 17)]
82
VOXDELAY_LIST = ["0.5", "1.0", "1.5", "2.0", "2.5", "3.0"]
83

    
84
SETTING_LISTS = {
85
    "pf2key": PF2KEY_LIST,
86
    "tot": TIMEOUTTIMER_LIST,
87
    "voice": VOICE_LIST,
88
    "vox": VOX_LIST,
89
    "voxdelay": VOXDELAY_LIST,
90
    }
91

    
92
VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
93
    "`{|}!\"#$%&'()*+,-./:;<=>?@[]^_"
94

    
95

    
96
def _rt22_enter_programming_mode(radio):
97
    serial = radio.pipe
98

    
99
    magic = "PROGRGS"
100
    exito = False
101
    for i in range(0, 5):
102
        for j in range(0, len(magic)):
103
            time.sleep(0.005)
104
            serial.write(magic[j])
105
        ack = serial.read(1)
106

    
107
        try:
108
            if ack == CMD_ACK:
109
                exito = True
110
                break
111
        except:
112
            LOG.debug("Attempt #%s, failed, trying again" % i)
113
            pass
114

    
115
    # check if we had EXITO
116
    if exito is False:
117
        msg = "The radio did not accept program mode after five tries.\n"
118
        msg += "Check you interface cable and power cycle your radio."
119
        raise errors.RadioError(msg)
120

    
121
    try:
122
        serial.write("\x02")
123
        ident = serial.read(8)
124
    except:
125
        _rt22_exit_programming_mode(radio)
126
        raise errors.RadioError("Error communicating with radio")
127

    
128
    if not ident.startswith("P32" + "\xB2" + "73"):
129
        _rt22_exit_programming_mode(radio)
130
        LOG.debug(util.hexprint(ident))
131
        raise errors.RadioError("Radio returned unknown identification string")
132

    
133
    try:
134
        serial.write(CMD_ACK)
135
        ack = serial.read(1)
136
    except:
137
        _rt22_exit_programming_mode(radio)
138
        raise errors.RadioError("Error communicating with radio")
139

    
140
    if ack != CMD_ACK:
141
        _rt22_exit_programming_mode(radio)
142
        raise errors.RadioError("Radio refused to enter programming mode")
143

    
144
    try:
145
        serial.write("\x07")
146
        ack = serial.read(1)
147
    except:
148
        _rt22_exit_programming_mode(radio)
149
        raise errors.RadioError("Error communicating with radio")
150

    
151
    if ack != "\x4E":
152
        _rt22_exit_programming_mode(radio)
153
        raise errors.RadioError("Radio refused to enter programming mode")
154

    
155

    
156
def _rt22_exit_programming_mode(radio):
157
    serial = radio.pipe
158
    try:
159
        serial.write("E")
160
    except:
161
        raise errors.RadioError("Radio refused to exit programming mode")
162

    
163

    
164
def _rt22_read_block(radio, block_addr, block_size):
165
    serial = radio.pipe
166

    
167
    cmd = struct.pack(">cHb", 'R', block_addr, block_size)
168
    expectedresponse = "W" + cmd[1:]
169
    LOG.debug("Reading block %04x..." % (block_addr))
170

    
171
    try:
172
        for j in range(0, len(cmd)):
173
            time.sleep(0.005)
174
            serial.write(cmd[j])
175

    
176
        response = serial.read(4 + block_size)
177
        if response[:4] != expectedresponse:
178
            _rt22_exit_programming_mode(radio)
179
            raise Exception("Error reading block %04x." % (block_addr))
180

    
181
        block_data = response[4:]
182

    
183
        serial.write(CMD_ACK)
184
        ack = serial.read(1)
185
    except:
186
        _rt22_exit_programming_mode(radio)
187
        raise errors.RadioError("Failed to read block at %04x" % block_addr)
188

    
189
    if ack != CMD_ACK:
190
        _rt22_exit_programming_mode(radio)
191
        raise Exception("No ACK reading block %04x." % (block_addr))
192

    
193
    return block_data
194

    
195

    
196
def _rt22_write_block(radio, block_addr, block_size):
197
    serial = radio.pipe
198

    
199
    cmd = struct.pack(">cHb", 'W', block_addr, block_size)
200
    data = radio.get_mmap()[block_addr:block_addr + block_size]
201

    
202
    LOG.debug("Writing Data:")
203
    LOG.debug(util.hexprint(cmd + data))
204

    
205
    try:
206
        for j in range(0, len(cmd)):
207
            time.sleep(0.005)
208
            serial.write(cmd[j])
209
        for j in range(0, len(data)):
210
            time.sleep(0.005)
211
            serial.write(data[j])
212
        if serial.read(1) != CMD_ACK:
213
            raise Exception("No ACK")
214
    except:
215
        _rt22_exit_programming_mode(radio)
216
        raise errors.RadioError("Failed to send block "
217
                                "to radio at %04x" % block_addr)
218

    
219

    
220
def do_download(radio):
221
    LOG.debug("download")
222
    _rt22_enter_programming_mode(radio)
223

    
224
    data = ""
225

    
226
    status = chirp_common.Status()
227
    status.msg = "Cloning from radio"
228

    
229
    status.cur = 0
230
    status.max = radio._memsize
231

    
232
    for addr in range(0, radio._memsize, radio._block_size):
233
        status.cur = addr + radio._block_size
234
        radio.status_fn(status)
235

    
236
        block = _rt22_read_block(radio, addr, radio._block_size)
237
        data += block
238

    
239
        LOG.debug("Address: %04x" % addr)
240
        LOG.debug(util.hexprint(block))
241

    
242
    data += radio.MODEL.ljust(8)
243

    
244
    _rt22_exit_programming_mode(radio)
245

    
246
    return memmap.MemoryMap(data)
247

    
248

    
249
def do_upload(radio):
250
    status = chirp_common.Status()
251
    status.msg = "Uploading to radio"
252

    
253
    _rt22_enter_programming_mode(radio)
254

    
255
    status.cur = 0
256
    status.max = radio._memsize
257

    
258
    for start_addr, end_addr, block_size in radio._ranges:
259
        for addr in range(start_addr, end_addr, block_size):
260
            status.cur = addr + block_size
261
            radio.status_fn(status)
262
            _rt22_write_block(radio, addr, block_size)
263

    
264
    _rt22_exit_programming_mode(radio)
265

    
266

    
267
def model_match(cls, data):
268
    """Match the opened/downloaded image to the correct version"""
269

    
270
    if len(data) == 0x0408:
271
        rid = data[0x0400:0x0408]
272
        return rid.startswith(cls.MODEL)
273
    else:
274
        return False
275

    
276

    
277
@directory.register
278
class RT22Radio(chirp_common.CloneModeRadio):
279
    """Retevis RT22"""
280
    VENDOR = "Retevis"
281
    MODEL = "RT22"
282
    BAUD_RATE = 9600
283

    
284
    _ranges = [
285
               (0x0000, 0x0180, 0x10),
286
               (0x01B8, 0x01F8, 0x10),
287
               (0x01F8, 0x0200, 0x08),
288
               (0x0200, 0x0340, 0x10),
289
              ]
290
    _memsize = 0x0400
291
    _block_size = 0x40
292

    
293
    def get_features(self):
294
        rf = chirp_common.RadioFeatures()
295
        rf.has_settings = True
296
        rf.has_bank = False
297
        rf.has_ctone = True
298
        rf.has_cross = True
299
        rf.has_rx_dtcs = True
300
        rf.has_tuning_step = False
301
        rf.can_odd_split = True
302
        rf.has_name = False
303
        rf.valid_skips = ["", "S"]
304
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
305
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
306
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
307
        rf.valid_power_levels = RT22_POWER_LEVELS
308
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
309
        rf.valid_modes = ["NFM", "FM"]  # 12.5 KHz, 25 kHz.
310
        rf.memory_bounds = (1, 16)
311
        rf.valid_bands = [(400000000, 520000000)]
312

    
313
        return rf
314

    
315
    def process_mmap(self):
316
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
317

    
318
    def sync_in(self):
319
        """Download from radio"""
320
        try:
321
            data = do_download(self)
322
        except errors.RadioError:
323
            # Pass through any real errors we raise
324
            raise
325
        except:
326
            # If anything unexpected happens, make sure we raise
327
            # a RadioError and log the problem
328
            LOG.exception('Unexpected error during download')
329
            raise errors.RadioError('Unexpected error communicating '
330
                                    'with the radio')
331
        self._mmap = data
332
        self.process_mmap()
333

    
334
    def sync_out(self):
335
        """Upload to radio"""
336
        try:
337
            do_upload(self)
338
        except:
339
            # If anything unexpected happens, make sure we raise
340
            # a RadioError and log the problem
341
            LOG.exception('Unexpected error during upload')
342
            raise errors.RadioError('Unexpected error communicating '
343
                                    'with the radio')
344

    
345
    def get_raw_memory(self, number):
346
        return repr(self._memobj.memory[number - 1])
347

    
348
    def _get_tone(self, _mem, mem):
349
        def _get_dcs(val):
350
            code = int("%03o" % (val & 0x07FF))
351
            pol = (val & 0x8000) and "R" or "N"
352
            return code, pol
353

    
354
        if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
355
            tcode, tpol = _get_dcs(_mem.tx_tone)
356
            mem.dtcs = tcode
357
            txmode = "DTCS"
358
        elif _mem.tx_tone != 0xFFFF:
359
            mem.rtone = _mem.tx_tone / 10.0
360
            txmode = "Tone"
361
        else:
362
            txmode = ""
363

    
364
        if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
365
            rcode, rpol = _get_dcs(_mem.rx_tone)
366
            mem.rx_dtcs = rcode
367
            rxmode = "DTCS"
368
        elif _mem.rx_tone != 0xFFFF:
369
            mem.ctone = _mem.rx_tone / 10.0
370
            rxmode = "Tone"
371
        else:
372
            rxmode = ""
373

    
374
        if txmode == "Tone" and not rxmode:
375
            mem.tmode = "Tone"
376
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
377
            mem.tmode = "TSQL"
378
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
379
            mem.tmode = "DTCS"
380
        elif rxmode or txmode:
381
            mem.tmode = "Cross"
382
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
383

    
384
        if mem.tmode == "DTCS":
385
            mem.dtcs_polarity = "%s%s" % (tpol, rpol)
386

    
387
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
388
                  (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
389

    
390
    def get_memory(self, number):
391
        bitpos = (1 << ((number - 1) % 8))
392
        bytepos = ((number - 1) / 8)
393
        LOG.debug("bitpos %s" % bitpos)
394
        LOG.debug("bytepos %s" % bytepos)
395

    
396
        _mem = self._memobj.memory[number - 1]
397
        _skp = self._memobj.skipflags[bytepos]
398

    
399
        mem = chirp_common.Memory()
400

    
401
        mem.number = number
402
        mem.freq = int(_mem.rxfreq) * 10
403

    
404
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
405
        if mem.freq == 0:
406
            mem.empty = True
407
            return mem
408

    
409
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
410
            mem.freq = 0
411
            mem.empty = True
412
            return mem
413

    
414
        if int(_mem.rxfreq) == int(_mem.txfreq):
415
            mem.duplex = ""
416
            mem.offset = 0
417
        else:
418
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
419
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
420

    
421
        mem.mode = _mem.wide and "FM" or "NFM"
422

    
423
        self._get_tone(_mem, mem)
424

    
425
        mem.power = RT22_POWER_LEVELS[_mem.highpower]
426

    
427
        mem.skip = "" if (_skp & bitpos) else "S"
428
        LOG.debug("mem.skip %s" % mem.skip)
429

    
430
        return mem
431

    
432
    def _set_tone(self, mem, _mem):
433
        def _set_dcs(code, pol):
434
            val = int("%i" % code, 8) + 0x2800
435
            if pol == "R":
436
                val += 0x8000
437
            return val
438

    
439
        rx_mode = tx_mode = None
440
        rx_tone = tx_tone = 0xFFFF
441

    
442
        if mem.tmode == "Tone":
443
            tx_mode = "Tone"
444
            rx_mode = None
445
            tx_tone = int(mem.rtone * 10)
446
        elif mem.tmode == "TSQL":
447
            rx_mode = tx_mode = "Tone"
448
            rx_tone = tx_tone = int(mem.ctone * 10)
449
        elif mem.tmode == "DTCS":
450
            tx_mode = rx_mode = "DTCS"
451
            tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
452
            rx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
453
        elif mem.tmode == "Cross":
454
            tx_mode, rx_mode = mem.cross_mode.split("->")
455
            if tx_mode == "DTCS":
456
                tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
457
            elif tx_mode == "Tone":
458
                tx_tone = int(mem.rtone * 10)
459
            if rx_mode == "DTCS":
460
                rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
461
            elif rx_mode == "Tone":
462
                rx_tone = int(mem.ctone * 10)
463

    
464
        _mem.rx_tone = rx_tone
465
        _mem.tx_tone = tx_tone
466

    
467
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
468
                  (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
469

    
470
    def set_memory(self, mem):
471
        bitpos = (1 << ((mem.number - 1) % 8))
472
        bytepos = ((mem.number - 1) / 8)
473
        LOG.debug("bitpos %s" % bitpos)
474
        LOG.debug("bytepos %s" % bytepos)
475

    
476
        _mem = self._memobj.memory[mem.number - 1]
477
        _skp = self._memobj.skipflags[bytepos]
478

    
479
        if mem.empty:
480
            _mem.set_raw("\xFF" * (_mem.size() / 8))
481
            return
482

    
483
        _mem.rxfreq = mem.freq / 10
484

    
485
        if mem.duplex == "off":
486
            for i in range(0, 4):
487
                _mem.txfreq[i].set_raw("\xFF")
488
        elif mem.duplex == "split":
489
            _mem.txfreq = mem.offset / 10
490
        elif mem.duplex == "+":
491
            _mem.txfreq = (mem.freq + mem.offset) / 10
492
        elif mem.duplex == "-":
493
            _mem.txfreq = (mem.freq - mem.offset) / 10
494
        else:
495
            _mem.txfreq = mem.freq / 10
496

    
497
        _mem.wide = mem.mode == "FM"
498

    
499
        self._set_tone(mem, _mem)
500

    
501
        _mem.highpower = mem.power == RT22_POWER_LEVELS[1]
502

    
503
        if mem.skip != "S":
504
            _skp |= bitpos
505
        else:
506
            _skp &= ~bitpos
507
        LOG.debug("_skp %s" % _skp)
508

    
509
    def get_settings(self):
510
        _settings = self._memobj.settings
511
        _message = self._memobj.embedded_msg
512
        basic = RadioSettingGroup("basic", "Basic Settings")
513
        top = RadioSettings(basic)
514

    
515
        rs = RadioSetting("squelch", "Squelch Level",
516
                          RadioSettingValueInteger(0, 9, _settings.squelch))
517
        basic.append(rs)
518

    
519
        rs = RadioSetting("tot", "Time-out timer",
520
                          RadioSettingValueList(
521
                              TIMEOUTTIMER_LIST,
522
                              TIMEOUTTIMER_LIST[_settings.tot]))
523
        basic.append(rs)
524

    
525
        rs = RadioSetting("voice", "Voice Prompts",
526
                          RadioSettingValueList(
527
                              VOICE_LIST, VOICE_LIST[_settings.voice]))
528
        basic.append(rs)
529

    
530
        rs = RadioSetting("pf2key", "PF2 Key",
531
                          RadioSettingValueList(
532
                              PF2KEY_LIST, PF2KEY_LIST[_settings.pf2key]))
533
        basic.append(rs)
534

    
535
        rs = RadioSetting("vox", "Vox",
536
                          RadioSettingValueBoolean(_settings.vox))
537
        basic.append(rs)
538

    
539
        rs = RadioSetting("voxgain", "VOX Level",
540
                          RadioSettingValueList(
541
                              VOX_LIST, VOX_LIST[_settings.voxgain]))
542
        basic.append(rs)
543

    
544
        rs = RadioSetting("voxdelay", "VOX Delay Time",
545
                          RadioSettingValueList(
546
                              VOXDELAY_LIST,
547
                              VOXDELAY_LIST[_settings.voxdelay]))
548
        basic.append(rs)
549

    
550
        rs = RadioSetting("save", "Battery Save",
551
                          RadioSettingValueBoolean(_settings.save))
552
        basic.append(rs)
553

    
554
        rs = RadioSetting("beep", "Beep",
555
                          RadioSettingValueBoolean(_settings.beep))
556
        basic.append(rs)
557

    
558
        def _filter(name):
559
            filtered = ""
560
            for char in str(name):
561
                if char in VALID_CHARS:
562
                    filtered += char
563
                else:
564
                    filtered += " "
565
            return filtered
566

    
567
        rs = RadioSetting("embedded_msg.line1", "Embedded Message 1",
568
                          RadioSettingValueString(0, 32, _filter(
569
                              _message.line1)))
570
        basic.append(rs)
571

    
572
        rs = RadioSetting("embedded_msg.line2", "Embedded Message 2",
573
                          RadioSettingValueString(0, 32, _filter(
574
                              _message.line2)))
575
        basic.append(rs)
576

    
577
        return top
578

    
579
    def set_settings(self, settings):
580
        for element in settings:
581
            if not isinstance(element, RadioSetting):
582
                self.set_settings(element)
583
                continue
584
            else:
585
                try:
586
                    if "." in element.get_name():
587
                        bits = element.get_name().split(".")
588
                        obj = self._memobj
589
                        for bit in bits[:-1]:
590
                            obj = getattr(obj, bit)
591
                        setting = bits[-1]
592
                    else:
593
                        obj = self._memobj.settings
594
                        setting = element.get_name()
595

    
596
                    LOG.debug("Setting %s = %s" % (setting, element.value))
597
                    setattr(obj, setting, element.value)
598
                except Exception, e:
599
                    LOG.debug(element.get_name())
600
                    raise
601

    
602
    @classmethod
603
    def match_model(cls, filedata, filename):
604
        match_size = False
605
        match_model = False
606

    
607
        # testing the file data size
608
        if len(filedata) in [0x0408, ]:
609
            match_size = True
610
        
611
        # testing the model fingerprint
612
        match_model = model_match(cls, filedata)
613

    
614
        if match_size and match_model:
615
            return True
616
        else:
617
            return False
618

    
619
@directory.register
620
class KDC1(RT22Radio):
621
    """WLN KD-C1"""
622
    VENDOR = "WLN"
623
    MODEL = "KD-C1"
624

    
625
@directory.register
626
class ZTX6(RT22Radio):
627
    """Zastone ZT-X6"""
628
    VENDOR = "Zastone"
629
    MODEL = "ZT-X6"
630

    
631
@directory.register
632
class LT316(RT22Radio):
633
    """Luiton LT-316"""
634
    VENDOR = "LUITON"
635
    MODEL = "LT-316"
636

    
637
@directory.register
638
class TDM8(RT22Radio):
639
    VENDOR = "TID"
640
    MODEL = "TD-M8"
    (1-1/1)