Project

General

Profile

Bug #6747 » retevis_rt22_butchered.py

Dan OLeary, 06/09/2020 09:14 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
    # check if ident is OK
129
    itis = False
130
    for fp in radio._fileid:
131
        if fp in ident:
132
            # got it!
133
            itis = True
134

    
135
            break
136

    
137
    if itis is False:
138
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
139
        raise errors.RadioError("Radio identification failed.")
140

    
141
    try:
142
        serial.write(CMD_ACK)
143
        ack = serial.read(1)
144
    except:
145
        _rt22_exit_programming_mode(radio)
146
        raise errors.RadioError("Error communicating with radio")
147

    
148
    if ack != CMD_ACK:
149
        _rt22_exit_programming_mode(radio)
150
        raise errors.RadioError("Radio refused to enter programming mode")
151

    
152
    try:
153
        serial.write("\x07")
154
        ack = serial.read(1)
155
    except:
156
        _rt22_exit_programming_mode(radio)
157
        raise errors.RadioError("Error communicating with radio")
158

    
159
    if ack != "\x4E":
160
        _rt22_exit_programming_mode(radio)
161
        raise errors.RadioError("Radio refused to enter programming mode")
162

    
163

    
164
def _rt22_exit_programming_mode(radio):
165
    serial = radio.pipe
166
    try:
167
        serial.write("E")
168
    except:
169
        raise errors.RadioError("Radio refused to exit programming mode")
170

    
171

    
172
def _rt22_read_block(radio, block_addr, block_size):
173
    serial = radio.pipe
174

    
175
    cmd = struct.pack(">cHb", 'R', block_addr, block_size)
176
    expectedresponse = "W" + cmd[1:]
177
    LOG.debug("Reading block %04x..." % (block_addr))
178

    
179
    try:
180
        for j in range(0, len(cmd)):
181
            time.sleep(0.005)
182
            serial.write(cmd[j])
183

    
184
        response = serial.read(4 + block_size)
185
        if response[:4] != expectedresponse:
186
            _rt22_exit_programming_mode(radio)
187
            raise Exception("Error reading block %04x." % (block_addr))
188

    
189
        block_data = response[4:]
190

    
191
        serial.write(CMD_ACK)
192
        ack = serial.read(1)
193
    except:
194
        _rt22_exit_programming_mode(radio)
195
        raise errors.RadioError("Failed to read block at %04x" % block_addr)
196

    
197
    if ack != CMD_ACK:
198
        _rt22_exit_programming_mode(radio)
199
        raise Exception("No ACK reading block %04x." % (block_addr))
200

    
201
    return block_data
202

    
203

    
204
def _rt22_write_block(radio, block_addr, block_size):
205
    serial = radio.pipe
206

    
207
    cmd = struct.pack(">cHb", 'W', block_addr, block_size)
208
    data = radio.get_mmap()[block_addr:block_addr + block_size]
209

    
210
    LOG.debug("Writing Data:")
211
    LOG.debug(util.hexprint(cmd + data))
212

    
213
    try:
214
        for j in range(0, len(cmd)):
215
            time.sleep(0.005)
216
            serial.write(cmd[j])
217
        for j in range(0, len(data)):
218
            time.sleep(0.005)
219
            serial.write(data[j])
220
        if serial.read(1) != CMD_ACK:
221
            raise Exception("No ACK")
222
    except:
223
        _rt22_exit_programming_mode(radio)
224
        raise errors.RadioError("Failed to send block "
225
                                "to radio at %04x" % block_addr)
226

    
227

    
228
def do_download(radio):
229
    LOG.debug("download")
230
    _rt22_enter_programming_mode(radio)
231

    
232
    data = ""
233

    
234
    status = chirp_common.Status()
235
    status.msg = "Cloning from radio"
236

    
237
    status.cur = 0
238
    status.max = radio._memsize
239

    
240
    for addr in range(0, radio._memsize, radio._block_size):
241
        status.cur = addr + radio._block_size
242
        radio.status_fn(status)
243

    
244
        block = _rt22_read_block(radio, addr, radio._block_size)
245
        data += block
246

    
247
        LOG.debug("Address: %04x" % addr)
248
        LOG.debug(util.hexprint(block))
249

    
250
    data += radio.MODEL.ljust(8)
251

    
252
    _rt22_exit_programming_mode(radio)
253

    
254
    return memmap.MemoryMap(data)
255

    
256

    
257
def do_upload(radio):
258
    status = chirp_common.Status()
259
    status.msg = "Uploading to radio"
260

    
261
    _rt22_enter_programming_mode(radio)
262

    
263
    status.cur = 0
264
    status.max = radio._memsize
265

    
266
    for start_addr, end_addr, block_size in radio._ranges:
267
        for addr in range(start_addr, end_addr, block_size):
268
            status.cur = addr + block_size
269
            radio.status_fn(status)
270
            _rt22_write_block(radio, addr, block_size)
271

    
272
    _rt22_exit_programming_mode(radio)
273

    
274

    
275
def model_match(cls, data):
276
    """Match the opened/downloaded image to the correct version"""
277

    
278
    if len(data) == 0x0408:
279
        rid = data[0x0400:0x0408]
280
        return rid.startswith(cls.MODEL)
281
    else:
282
        return False
283

    
284

    
285
@directory.register
286
class RT22Radio(chirp_common.CloneModeRadio):
287
    """Retevis RT22"""
288
    VENDOR = "Retevis"
289
    MODEL = "RT22"
290
    BAUD_RATE = 9600
291

    
292
    _ranges = [
293
               (0x0000, 0x0180, 0x10),
294
               (0x01B8, 0x01F8, 0x10),
295
               (0x01F8, 0x0200, 0x08),
296
               (0x0200, 0x0340, 0x10),
297
              ]
298
    _memsize = 0x0400
299
    _block_size = 0x40
300
    _fileid = ["P3207!", "P3" + "\x00\x00\x00" + "3"]
301

    
302
    def get_features(self):
303
        rf = chirp_common.RadioFeatures()
304
        rf.has_settings = True
305
        rf.has_bank = False
306
        rf.has_ctone = True
307
        rf.has_cross = True
308
        rf.has_rx_dtcs = True
309
        rf.has_tuning_step = False
310
        rf.can_odd_split = True
311
        rf.has_name = False
312
        rf.valid_skips = ["", "S"]
313
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
314
        rf.valid_cross_modes = ["Tone->Tone", "Tone->DTCS", "DTCS->Tone",
315
                                "->Tone", "->DTCS", "DTCS->", "DTCS->DTCS"]
316
        rf.valid_power_levels = RT22_POWER_LEVELS
317
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
318
        rf.valid_modes = ["NFM", "FM"]  # 12.5 KHz, 25 kHz.
319
        rf.memory_bounds = (1, 16)
320
        rf.valid_tuning_steps = [2.5, 5., 6.25, 10., 12.5, 25.]
321
        rf.valid_bands = [(400000000, 520000000)]
322

    
323
        return rf
324

    
325
    def process_mmap(self):
326
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
327

    
328
    def sync_in(self):
329
        """Download from radio"""
330
        try:
331
            data = do_download(self)
332
        except errors.RadioError:
333
            # Pass through any real errors we raise
334
            raise
335
        except:
336
            # If anything unexpected happens, make sure we raise
337
            # a RadioError and log the problem
338
            LOG.exception('Unexpected error during download')
339
            raise errors.RadioError('Unexpected error communicating '
340
                                    'with the radio')
341
        self._mmap = data
342
        self.process_mmap()
343

    
344
    def sync_out(self):
345
        """Upload to radio"""
346
        try:
347
            do_upload(self)
348
        except:
349
            # If anything unexpected happens, make sure we raise
350
            # a RadioError and log the problem
351
            LOG.exception('Unexpected error during upload')
352
            raise errors.RadioError('Unexpected error communicating '
353
                                    'with the radio')
354

    
355
    def get_raw_memory(self, number):
356
        return repr(self._memobj.memory[number - 1])
357

    
358
    def _get_tone(self, _mem, mem):
359
        def _get_dcs(val):
360
            code = int("%03o" % (val & 0x07FF))
361
            pol = (val & 0x8000) and "R" or "N"
362
            return code, pol
363

    
364
        if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
365
            tcode, tpol = _get_dcs(_mem.tx_tone)
366
            mem.dtcs = tcode
367
            txmode = "DTCS"
368
        elif _mem.tx_tone != 0xFFFF:
369
            mem.rtone = _mem.tx_tone / 10.0
370
            txmode = "Tone"
371
        else:
372
            txmode = ""
373

    
374
        if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
375
            rcode, rpol = _get_dcs(_mem.rx_tone)
376
            mem.rx_dtcs = rcode
377
            rxmode = "DTCS"
378
        elif _mem.rx_tone != 0xFFFF:
379
            mem.ctone = _mem.rx_tone / 10.0
380
            rxmode = "Tone"
381
        else:
382
            rxmode = ""
383

    
384
        if txmode == "Tone" and not rxmode:
385
            mem.tmode = "Tone"
386
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
387
            mem.tmode = "TSQL"
388
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
389
            mem.tmode = "DTCS"
390
        elif rxmode or txmode:
391
            mem.tmode = "Cross"
392
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
393

    
394
        if mem.tmode == "DTCS":
395
            mem.dtcs_polarity = "%s%s" % (tpol, rpol)
396

    
397
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
398
                  (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
399

    
400
    def get_memory(self, number):
401
        bitpos = (1 << ((number - 1) % 8))
402
        bytepos = ((number - 1) / 8)
403
        LOG.debug("bitpos %s" % bitpos)
404
        LOG.debug("bytepos %s" % bytepos)
405

    
406
        _mem = self._memobj.memory[number - 1]
407
        _skp = self._memobj.skipflags[bytepos]
408

    
409
        mem = chirp_common.Memory()
410

    
411
        mem.number = number
412
        mem.freq = int(_mem.rxfreq) * 10
413

    
414
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
415
        if mem.freq == 0:
416
            mem.empty = True
417
            return mem
418

    
419
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
420
            mem.freq = 0
421
            mem.empty = True
422
            return mem
423

    
424
        if int(_mem.rxfreq) == int(_mem.txfreq):
425
            mem.duplex = ""
426
            mem.offset = 0
427
        else:
428
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
429
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
430

    
431
        mem.mode = _mem.wide and "FM" or "NFM"
432

    
433
        self._get_tone(_mem, mem)
434

    
435
        mem.power = RT22_POWER_LEVELS[_mem.highpower]
436

    
437
        mem.skip = "" if (_skp & bitpos) else "S"
438
        LOG.debug("mem.skip %s" % mem.skip)
439

    
440
        return mem
441

    
442
    def _set_tone(self, mem, _mem):
443
        def _set_dcs(code, pol):
444
            val = int("%i" % code, 8) + 0x2800
445
            if pol == "R":
446
                val += 0x8000
447
            return val
448

    
449
        rx_mode = tx_mode = None
450
        rx_tone = tx_tone = 0xFFFF
451

    
452
        if mem.tmode == "Tone":
453
            tx_mode = "Tone"
454
            rx_mode = None
455
            tx_tone = int(mem.rtone * 10)
456
        elif mem.tmode == "TSQL":
457
            rx_mode = tx_mode = "Tone"
458
            rx_tone = tx_tone = int(mem.ctone * 10)
459
        elif mem.tmode == "DTCS":
460
            tx_mode = rx_mode = "DTCS"
461
            tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
462
            rx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
463
        elif mem.tmode == "Cross":
464
            tx_mode, rx_mode = mem.cross_mode.split("->")
465
            if tx_mode == "DTCS":
466
                tx_tone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
467
            elif tx_mode == "Tone":
468
                tx_tone = int(mem.rtone * 10)
469
            if rx_mode == "DTCS":
470
                rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
471
            elif rx_mode == "Tone":
472
                rx_tone = int(mem.ctone * 10)
473

    
474
        _mem.rx_tone = rx_tone
475
        _mem.tx_tone = tx_tone
476

    
477
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
478
                  (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
479

    
480
    def set_memory(self, mem):
481
        bitpos = (1 << ((mem.number - 1) % 8))
482
        bytepos = ((mem.number - 1) / 8)
483
        LOG.debug("bitpos %s" % bitpos)
484
        LOG.debug("bytepos %s" % bytepos)
485

    
486
        _mem = self._memobj.memory[mem.number - 1]
487
        _skp = self._memobj.skipflags[bytepos]
488

    
489
        if mem.empty:
490
            _mem.set_raw("\xFF" * (_mem.size() / 8))
491
            return
492

    
493
        _mem.rxfreq = mem.freq / 10
494

    
495
        if mem.duplex == "off":
496
            for i in range(0, 4):
497
                _mem.txfreq[i].set_raw("\xFF")
498
        elif mem.duplex == "split":
499
            _mem.txfreq = mem.offset / 10
500
        elif mem.duplex == "+":
501
            _mem.txfreq = (mem.freq + mem.offset) / 10
502
        elif mem.duplex == "-":
503
            _mem.txfreq = (mem.freq - mem.offset) / 10
504
        else:
505
            _mem.txfreq = mem.freq / 10
506

    
507
        _mem.wide = mem.mode == "FM"
508

    
509
        self._set_tone(mem, _mem)
510

    
511
        _mem.highpower = mem.power == RT22_POWER_LEVELS[1]
512

    
513
        if mem.skip != "S":
514
            _skp |= bitpos
515
        else:
516
            _skp &= ~bitpos
517
        LOG.debug("_skp %s" % _skp)
518

    
519
    def get_settings(self):
520
        _settings = self._memobj.settings
521
        _message = self._memobj.embedded_msg
522
        basic = RadioSettingGroup("basic", "Basic Settings")
523
        top = RadioSettings(basic)
524

    
525
        rs = RadioSetting("squelch", "Squelch Level",
526
                          RadioSettingValueInteger(0, 9, _settings.squelch))
527
        basic.append(rs)
528

    
529
        rs = RadioSetting("tot", "Time-out timer",
530
                          RadioSettingValueList(
531
                              TIMEOUTTIMER_LIST,
532
                              TIMEOUTTIMER_LIST[_settings.tot]))
533
        basic.append(rs)
534

    
535
        rs = RadioSetting("voice", "Voice Prompts",
536
                          RadioSettingValueList(
537
                              VOICE_LIST, VOICE_LIST[_settings.voice]))
538
        basic.append(rs)
539

    
540
        rs = RadioSetting("pf2key", "PF2 Key",
541
                          RadioSettingValueList(
542
                              PF2KEY_LIST, PF2KEY_LIST[_settings.pf2key]))
543
        basic.append(rs)
544

    
545
        rs = RadioSetting("vox", "Vox",
546
                          RadioSettingValueBoolean(_settings.vox))
547
        basic.append(rs)
548

    
549
        rs = RadioSetting("voxgain", "VOX Level",
550
                          RadioSettingValueList(
551
                              VOX_LIST, VOX_LIST[_settings.voxgain]))
552
        basic.append(rs)
553

    
554
        rs = RadioSetting("voxdelay", "VOX Delay Time",
555
                          RadioSettingValueList(
556
                              VOXDELAY_LIST,
557
                              VOXDELAY_LIST[_settings.voxdelay]))
558
        basic.append(rs)
559

    
560
        rs = RadioSetting("save", "Battery Save",
561
                          RadioSettingValueBoolean(_settings.save))
562
        basic.append(rs)
563

    
564
        rs = RadioSetting("beep", "Beep",
565
                          RadioSettingValueBoolean(_settings.beep))
566
        basic.append(rs)
567

    
568
        def _filter(name):
569
            filtered = ""
570
            for char in str(name):
571
                if char in VALID_CHARS:
572
                    filtered += char
573
                else:
574
                    filtered += " "
575
            return filtered
576

    
577
        rs = RadioSetting("embedded_msg.line1", "Embedded Message 1",
578
                          RadioSettingValueString(0, 32, _filter(
579
                              _message.line1)))
580
        basic.append(rs)
581

    
582
        rs = RadioSetting("embedded_msg.line2", "Embedded Message 2",
583
                          RadioSettingValueString(0, 32, _filter(
584
                              _message.line2)))
585
        basic.append(rs)
586

    
587
        return top
588

    
589
    def set_settings(self, settings):
590
        for element in settings:
591
            if not isinstance(element, RadioSetting):
592
                self.set_settings(element)
593
                continue
594
            else:
595
                try:
596
                    if "." in element.get_name():
597
                        bits = element.get_name().split(".")
598
                        obj = self._memobj
599
                        for bit in bits[:-1]:
600
                            obj = getattr(obj, bit)
601
                        setting = bits[-1]
602
                    else:
603
                        obj = self._memobj.settings
604
                        setting = element.get_name()
605

    
606
                    LOG.debug("Setting %s = %s" % (setting, element.value))
607
                    setattr(obj, setting, element.value)
608
                except Exception, e:
609
                    LOG.debug(element.get_name())
610
                    raise
611

    
612
    @classmethod
613
    def match_model(cls, filedata, filename):
614
        match_size = False
615
        match_model = False
616

    
617
        # testing the file data size
618
        if len(filedata) in [0x0408, ]:
619
            match_size = True
620
        
621
        # testing the model fingerprint
622
        match_model = model_match(cls, filedata)
623

    
624
        if match_size and match_model:
625
            return True
626
        else:
627
            return False
628

    
629
@directory.register
630
class KDC1(RT22Radio):
631
    """WLN KD-C1"""
632
    VENDOR = "WLN"
633
    MODEL = "KD-C1"
634

    
635
@directory.register
636
class ZTX6(RT22Radio):
637
    """Zastone ZT-X6"""
638
    VENDOR = "Zastone"
639
    MODEL = "ZT-X6"
640

    
641
@directory.register
642
class LT316(RT22Radio):
643
    """Luiton LT-316"""
644
    VENDOR = "LUITON"
645
    MODEL = "LT-316"
646

    
647
@directory.register
648
class TDM8(RT22Radio):
649
    VENDOR = "TID"
650
    MODEL = "TD-M8"
(5-5/14)