Project

General

Profile

New Model #4145 » retevis_rt22_test.py

Jim Unroe, 11/22/2016 03:39 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

    
106
        ack = serial.read(1)
107

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

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

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

    
129
    if not ident.startswith("P32073"):
130
        _rt22_exit_programming_mode(radio)
131
        LOG.debug(util.hexprint(ident))
132
        raise errors.RadioError("Radio returned unknown identification string")
133

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

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

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

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

    
156

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

    
164

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

    
168
    time.sleep(0.05)
169

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

    
174
    try:
175
        for j in range(0, len(cmd)):
176
            time.sleep(0.005)
177
            serial.write(cmd[j])
178

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

    
184
        block_data = response[4:]
185

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

    
192
    if ack != CMD_ACK:
193
        _rt22_exit_programming_mode(radio)
194
        raise Exception("No ACK reading block %04x." % (block_addr))
195

    
196
    return block_data
197

    
198

    
199
def _rt22_write_block(radio, block_addr, block_size):
200
    serial = radio.pipe
201

    
202
    cmd = struct.pack(">cHb", 'W', block_addr, block_size)
203
    data = radio.get_mmap()[block_addr:block_addr + block_size]
204

    
205
    LOG.debug("Writing Data:")
206
    LOG.debug(util.hexprint(cmd + data))
207

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

    
222

    
223
def do_download(radio):
224
    LOG.debug("download")
225
    _rt22_enter_programming_mode(radio)
226

    
227
    data = ""
228

    
229
    status = chirp_common.Status()
230
    status.msg = "Cloning from radio"
231

    
232
    status.cur = 0
233
    status.max = radio._memsize
234

    
235
    for addr in range(0, radio._memsize, radio._block_size):
236
        status.cur = addr + radio._block_size
237
        radio.status_fn(status)
238

    
239
        block = _rt22_read_block(radio, addr, radio._block_size)
240
        data += block
241

    
242
        LOG.debug("Address: %04x" % addr)
243
        LOG.debug(util.hexprint(block))
244

    
245
    data += radio.MODEL.ljust(8)
246

    
247
    _rt22_exit_programming_mode(radio)
248

    
249
    return memmap.MemoryMap(data)
250

    
251

    
252
def do_upload(radio):
253
    status = chirp_common.Status()
254
    status.msg = "Uploading to radio"
255

    
256
    _rt22_enter_programming_mode(radio)
257

    
258
    status.cur = 0
259
    status.max = radio._memsize
260

    
261
    for start_addr, end_addr, block_size in radio._ranges:
262
        for addr in range(start_addr, end_addr, block_size):
263
            status.cur = addr + block_size
264
            radio.status_fn(status)
265
            _rt22_write_block(radio, addr, block_size)
266

    
267
    _rt22_exit_programming_mode(radio)
268

    
269

    
270
def model_match(cls, data):
271
    """Match the opened/downloaded image to the correct version"""
272

    
273
    if len(data) == 0x0408:
274
        rid = data[0x0400:0x0408]
275
        return rid.startswith(cls.MODEL)
276
    else:
277
        return False
278

    
279

    
280
@directory.register
281
class RT22Radio(chirp_common.CloneModeRadio):
282
    """Retevis RT22"""
283
    VENDOR = "Retevis"
284
    MODEL = "RT22"
285
    BAUD_RATE = 9600
286

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

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

    
316
        return rf
317

    
318
    def process_mmap(self):
319
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
320

    
321
    def sync_in(self):
322
        self._mmap = do_download(self)
323
        self.process_mmap()
324

    
325
    def sync_out(self):
326
        do_upload(self)
327

    
328
    def get_raw_memory(self, number):
329
        return repr(self._memobj.memory[number - 1])
330

    
331
    def _get_tone(self, _mem, mem):
332
        def _get_dcs(val):
333
            code = int("%03o" % (val & 0x07FF))
334
            pol = (val & 0x8000) and "R" or "N"
335
            return code, pol
336

    
337
        if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
338
            tcode, tpol = _get_dcs(_mem.tx_tone)
339
            mem.dtcs = tcode
340
            txmode = "DTCS"
341
        elif _mem.tx_tone != 0xFFFF:
342
            mem.rtone = _mem.tx_tone / 10.0
343
            txmode = "Tone"
344
        else:
345
            txmode = ""
346

    
347
        if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
348
            rcode, rpol = _get_dcs(_mem.rx_tone)
349
            mem.rx_dtcs = rcode
350
            rxmode = "DTCS"
351
        elif _mem.rx_tone != 0xFFFF:
352
            mem.ctone = _mem.rx_tone / 10.0
353
            rxmode = "Tone"
354
        else:
355
            rxmode = ""
356

    
357
        if txmode == "Tone" and not rxmode:
358
            mem.tmode = "Tone"
359
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
360
            mem.tmode = "TSQL"
361
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
362
            mem.tmode = "DTCS"
363
        elif rxmode or txmode:
364
            mem.tmode = "Cross"
365
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
366

    
367
        if mem.tmode == "DTCS":
368
            mem.dtcs_polarity = "%s%s" % (tpol, rpol)
369

    
370
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
371
                  (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
372

    
373
    def get_memory(self, number):
374
        bitpos = (1 << ((number - 1) % 8))
375
        bytepos = ((number - 1) / 8)
376
        LOG.debug("bitpos %s" % bitpos)
377
        LOG.debug("bytepos %s" % bytepos)
378

    
379
        _mem = self._memobj.memory[number - 1]
380
        _skp = self._memobj.skipflags[bytepos]
381

    
382
        mem = chirp_common.Memory()
383

    
384
        mem.number = number
385
        mem.freq = int(_mem.rxfreq) * 10
386

    
387
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
388
        if mem.freq == 0:
389
            mem.empty = True
390
            return mem
391

    
392
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
393
            mem.freq = 0
394
            mem.empty = True
395
            return mem
396

    
397
        if int(_mem.rxfreq) == int(_mem.txfreq):
398
            mem.duplex = ""
399
            mem.offset = 0
400
        else:
401
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
402
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
403

    
404
        mem.mode = _mem.wide and "FM" or "NFM"
405

    
406
        self._get_tone(_mem, mem)
407

    
408
        mem.power = RT22_POWER_LEVELS[_mem.highpower]
409

    
410
        mem.skip = "" if (_skp & bitpos) else "S"
411
        LOG.debug("mem.skip %s" % mem.skip)
412

    
413
        return mem
414

    
415
    def _set_tone(self, mem, _mem):
416
        def _set_dcs(code, pol):
417
            val = int("%i" % code, 8) + 0x2800
418
            if pol == "R":
419
                val += 0x8000
420
            return val
421

    
422
        if mem.tmode == "Cross":
423
            tx_mode, rx_mode = mem.cross_mode.split("->")
424
        elif mem.tmode == "Tone":
425
            tx_mode = mem.tmode
426
            rx_mode = None
427
        else:
428
            tx_mode = rx_mode = mem.tmode
429

    
430
        if tx_mode == "DTCS":
431
            _mem.tx_tone = mem.tmode != "DTCS" and \
432
                           _set_dcs(mem.dtcs, mem.dtcs_polarity[0]) or \
433
                           _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[0])
434
        elif tx_mode:
435
            _mem.tx_tone = tx_mode == "Tone" and \
436
                int(mem.rtone * 10) or int(mem.ctone * 10)
437
        else:
438
            _mem.tx_tone = 0xFFFF
439

    
440
        if rx_mode == "DTCS":
441
            _mem.rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
442
        elif rx_mode:
443
            _mem.rx_tone = int(mem.ctone * 10)
444
        else:
445
            _mem.rx_tone = 0xFFFF
446

    
447
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
448
                  (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
449

    
450
    def set_memory(self, mem):
451
        bitpos = (1 << ((mem.number - 1) % 8))
452
        bytepos = ((mem.number - 1) / 8)
453
        LOG.debug("bitpos %s" % bitpos)
454
        LOG.debug("bytepos %s" % bytepos)
455

    
456
        _mem = self._memobj.memory[mem.number - 1]
457
        _skp = self._memobj.skipflags[bytepos]
458

    
459
        if mem.empty:
460
            _mem.set_raw("\xFF" * (_mem.size() / 8))
461
            return
462

    
463
        _mem.rxfreq = mem.freq / 10
464

    
465
        if mem.duplex == "off":
466
            for i in range(0, 4):
467
                _mem.txfreq[i].set_raw("\xFF")
468
        elif mem.duplex == "split":
469
            _mem.txfreq = mem.offset / 10
470
        elif mem.duplex == "+":
471
            _mem.txfreq = (mem.freq + mem.offset) / 10
472
        elif mem.duplex == "-":
473
            _mem.txfreq = (mem.freq - mem.offset) / 10
474
        else:
475
            _mem.txfreq = mem.freq / 10
476

    
477
        _mem.wide = mem.mode == "FM"
478

    
479
        self._set_tone(mem, _mem)
480

    
481
        _mem.highpower = mem.power == RT22_POWER_LEVELS[1]
482

    
483
        if mem.skip != "S":
484
            _skp |= bitpos
485
        else:
486
            _skp &= ~bitpos
487
        LOG.debug("_skp %s" % _skp)
488

    
489
    def get_settings(self):
490
        _settings = self._memobj.settings
491
        _message = self._memobj.embedded_msg
492
        basic = RadioSettingGroup("basic", "Basic Settings")
493
        top = RadioSettings(basic)
494

    
495
        rs = RadioSetting("squelch", "Squelch Level",
496
                          RadioSettingValueInteger(0, 9, _settings.squelch))
497
        basic.append(rs)
498

    
499
        rs = RadioSetting("tot", "Time-out timer",
500
                          RadioSettingValueList(
501
                              TIMEOUTTIMER_LIST,
502
                              TIMEOUTTIMER_LIST[_settings.tot]))
503
        basic.append(rs)
504

    
505
        rs = RadioSetting("voice", "Voice Prompts",
506
                          RadioSettingValueList(
507
                              VOICE_LIST, VOICE_LIST[_settings.voice]))
508
        basic.append(rs)
509

    
510
        rs = RadioSetting("pf2key", "PF2 Key",
511
                          RadioSettingValueList(
512
                              PF2KEY_LIST, PF2KEY_LIST[_settings.pf2key]))
513
        basic.append(rs)
514

    
515
        rs = RadioSetting("vox", "Vox",
516
                          RadioSettingValueBoolean(_settings.vox))
517
        basic.append(rs)
518

    
519
        rs = RadioSetting("voxgain", "VOX Level",
520
                          RadioSettingValueList(
521
                              VOX_LIST, VOX_LIST[_settings.voxgain]))
522
        basic.append(rs)
523

    
524
        rs = RadioSetting("voxdelay", "VOX Delay Time",
525
                          RadioSettingValueList(
526
                              VOXDELAY_LIST,
527
                              VOXDELAY_LIST[_settings.voxdelay]))
528
        basic.append(rs)
529

    
530
        rs = RadioSetting("save", "Battery Save",
531
                          RadioSettingValueBoolean(_settings.save))
532
        basic.append(rs)
533

    
534
        rs = RadioSetting("beep", "Beep",
535
                          RadioSettingValueBoolean(_settings.beep))
536
        basic.append(rs)
537

    
538
        def _filter(name):
539
            filtered = ""
540
            for char in str(name):
541
                if char in VALID_CHARS:
542
                    filtered += char
543
                else:
544
                    filtered += " "
545
            return filtered
546

    
547
        rs = RadioSetting("embedded_msg.line1", "Embedded Message 1",
548
                          RadioSettingValueString(0, 32, _filter(
549
                              _message.line1)))
550
        basic.append(rs)
551

    
552
        rs = RadioSetting("embedded_msg.line2", "Embedded Message 2",
553
                          RadioSettingValueString(0, 32, _filter(
554
                              _message.line2)))
555
        basic.append(rs)
556

    
557
        return top
558

    
559
    def set_settings(self, settings):
560
        for element in settings:
561
            if not isinstance(element, RadioSetting):
562
                self.set_settings(element)
563
                continue
564
            else:
565
                try:
566
                    if "." in element.get_name():
567
                        bits = element.get_name().split(".")
568
                        obj = self._memobj
569
                        for bit in bits[:-1]:
570
                            obj = getattr(obj, bit)
571
                        setting = bits[-1]
572
                    else:
573
                        obj = self._memobj.settings
574
                        setting = element.get_name()
575

    
576
                    LOG.debug("Setting %s = %s" % (setting, element.value))
577
                    setattr(obj, setting, element.value)
578
                except Exception, e:
579
                    LOG.debug(element.get_name())
580
                    raise
581

    
582
    @classmethod
583
    def match_model(cls, filedata, filename):
584
        match_size = False
585
        match_model = False
586

    
587
        # testing the file data size
588
        if len(filedata) in [0x0408, ]:
589
            match_size = True
590
        
591
        # testing the model fingerprint
592
        match_model = model_match(cls, filedata)
593

    
594
        if match_size and match_model:
595
            return True
596
        else:
597
            return False
598

    
599
@directory.register
600
class KDC1(RT22Radio):
601
    """WLN KD-C1"""
602
    VENDOR = "WLN"
603
    MODEL = "KD-C1"
604

    
605
@directory.register
606
class ZTX6(RT22Radio):
607
    """Zastone ZT-X6"""
608
    VENDOR = "Zastone"
609
    MODEL = "ZT-X6"
(16-16/19)