Project

General

Profile

New Model #4145 » retevis_rt22.py

test driver module #2 - Jim Unroe, 11/12/2016 08:11 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];                 // confirmed
34
  lbcd txfreq[4];                 // confirmed
35
  ul16 rx_tone;                   // confirmed
36
  ul16 tx_tone;                   // confirmed
37
  u8 unknown1;
38
  u8 unknown3:2,
39
     highpower:1, // Power Level  // confirmed
40
     wide:1,      // Bandwidth    // confirmed
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
RECV_BLOCK_SIZE = 0x40
73
SEND_BLOCK_SIZE = 0x10
74

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

    
78
RT22_DTCS = sorted(chirp_common.DTCS_CODES + [645])
79

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

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

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

    
97

    
98
def _rt22_enter_programming_mode(radio):
99
    serial = radio.pipe
100
    serial.timeout = 2
101

    
102
    magic = "PROGRGS"
103
    exito = False
104
    for i in range(0, 5):
105
        for j in range(0, len(magic)):
106
            time.sleep(0.005)
107
            serial.write(magic[j])
108

    
109
        ack = serial.read(1)
110

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

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

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

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

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

    
141
    if ack != CMD_ACK:
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
        raise errors.RadioError("Error communicating with radio")
149

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

    
153

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

    
161

    
162
def _rt22_read_block(radio, block_addr, block_size):
163
    serial = radio.pipe
164

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

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

    
174
        response = serial.read(4 + RECV_BLOCK_SIZE)
175
        if response[:4] != expectedresponse:
176
            raise Exception("Error reading block %04x." % (block_addr))
177

    
178
        block_data = response[4:]
179

    
180
        serial.write(CMD_ACK)
181
        ack = serial.read(1)
182
    except:
183
        raise errors.RadioError("Failed to read block at %04x" % block_addr)
184

    
185
    if ack != CMD_ACK:
186
        raise Exception("No ACK reading block %04x." % (block_addr))
187

    
188
    return block_data
189

    
190

    
191
def _rt22_write_block(radio, block_addr, block_size):
192
    serial = radio.pipe
193

    
194
    cmd = struct.pack(">cHb", 'W', block_addr, SEND_BLOCK_SIZE)
195
    data = radio.get_mmap()[block_addr:block_addr + SEND_BLOCK_SIZE]
196

    
197
    LOG.debug("Writing Data:")
198
    LOG.debug(util.hexprint(cmd + data))
199

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

    
213

    
214
def do_download(radio):
215
    LOG.debug("download")
216
    _rt22_enter_programming_mode(radio)
217

    
218
    data = ""
219

    
220
    status = chirp_common.Status()
221
    status.msg = "Cloning from radio"
222

    
223
    status.cur = 0
224
    status.max = radio._memsize
225

    
226
    for addr in range(0, radio._memsize, RECV_BLOCK_SIZE):
227
        status.cur = addr + RECV_BLOCK_SIZE
228
        radio.status_fn(status)
229

    
230
        block = _rt22_read_block(radio, addr, RECV_BLOCK_SIZE)
231
        data += block
232

    
233
        LOG.debug("Address: %04x" % addr)
234
        LOG.debug(util.hexprint(block))
235

    
236
    data += radio.MODEL.ljust(8)
237

    
238
    _rt22_exit_programming_mode(radio)
239

    
240
    return memmap.MemoryMap(data)
241

    
242

    
243
def do_upload(radio):
244
    status = chirp_common.Status()
245
    status.msg = "Uploading to radio"
246

    
247
    _rt22_enter_programming_mode(radio)
248

    
249
    status.cur = 0
250
    status.max = radio._memsize
251

    
252
    for start_addr, end_addr in radio._ranges:
253
        for addr in range(start_addr, end_addr, SEND_BLOCK_SIZE):
254
            status.cur = addr + SEND_BLOCK_SIZE
255
            radio.status_fn(status)
256
            _rt22_write_block(radio, addr, SEND_BLOCK_SIZE)
257

    
258
    _rt22_exit_programming_mode(radio)
259

    
260

    
261
def model_match(cls, data):
262
    """Match the opened/downloaded image to the correct version"""
263

    
264
    if len(data) == 0x0408:
265
        rid = data[0x0400:0x0408]
266
        return rid.startswith(cls.MODEL)
267
    else:
268
        return False
269

    
270

    
271
@directory.register
272
class RT22Radio(chirp_common.CloneModeRadio):
273
    """Retevis RT22"""
274
    VENDOR = "Retevis"
275
    MODEL = "RT22"
276
    BAUD_RATE = 9600
277

    
278
    _ranges = [
279
               (0x0000, 0x0180),
280
               (0x01B0, 0x0200),
281
               (0x0200, 0x0340),
282
              ]
283
    _memsize = 0x0400
284

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

    
305
        return rf
306

    
307
    def process_mmap(self):
308
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
309

    
310
    def sync_in(self):
311
        self._mmap = do_download(self)
312
        self.process_mmap()
313

    
314
    def sync_out(self):
315
        do_upload(self)
316

    
317
    def get_raw_memory(self, number):
318
        return repr(self._memobj.memory[number - 1])
319

    
320
    def _get_tone(self, _mem, mem):
321
        def _get_dcs(val):
322
            code = int("%03o" % (val & 0x07FF))
323
            pol = (val & 0x8000) and "R" or "N"
324
            return code, pol
325

    
326
        if _mem.tx_tone != 0xFFFF and _mem.tx_tone > 0x2800:
327
            tcode, tpol = _get_dcs(_mem.tx_tone)
328
            mem.dtcs = tcode
329
            txmode = "DTCS"
330
        elif _mem.tx_tone != 0xFFFF:
331
            mem.rtone = _mem.tx_tone / 10.0
332
            txmode = "Tone"
333
        else:
334
            txmode = ""
335

    
336
        if _mem.rx_tone != 0xFFFF and _mem.rx_tone > 0x2800:
337
            rcode, rpol = _get_dcs(_mem.rx_tone)
338
            mem.rx_dtcs = rcode
339
            rxmode = "DTCS"
340
        elif _mem.rx_tone != 0xFFFF:
341
            mem.ctone = _mem.rx_tone / 10.0
342
            rxmode = "Tone"
343
        else:
344
            rxmode = ""
345

    
346
        if txmode == "Tone" and not rxmode:
347
            mem.tmode = "Tone"
348
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
349
            mem.tmode = "TSQL"
350
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
351
            mem.tmode = "DTCS"
352
        elif rxmode or txmode:
353
            mem.tmode = "Cross"
354
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
355

    
356
        if mem.tmode == "DTCS":
357
            mem.dtcs_polarity = "%s%s" % (tpol, rpol)
358

    
359
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
360
                  (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
361

    
362
    def get_memory(self, number):
363
        bitpos = (1 << ((number - 1) % 8))
364
        bytepos = ((number - 1) / 8)
365
        LOG.debug("bitpos %s" % bitpos)
366
        LOG.debug("bytepos %s" % bytepos)
367

    
368
        _mem = self._memobj.memory[number - 1]
369
        _skp = self._memobj.skipflags[bytepos]
370

    
371
        mem = chirp_common.Memory()
372

    
373
        mem.number = number
374
        mem.freq = int(_mem.rxfreq) * 10
375

    
376
        # We'll consider any blank (i.e. 0MHz frequency) to be empty
377
        if mem.freq == 0:
378
            mem.empty = True
379
            return mem
380

    
381
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
382
            mem.freq = 0
383
            mem.empty = True
384
            return mem
385

    
386
        if int(_mem.rxfreq) == int(_mem.txfreq):
387
            mem.duplex = ""
388
            mem.offset = 0
389
        else:
390
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
391
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
392

    
393
        mem.mode = _mem.wide and "FM" or "NFM"
394

    
395
        self._get_tone(_mem, mem)
396

    
397
        mem.power = RT22_POWER_LEVELS[_mem.highpower]
398

    
399
        mem.skip = "" if (_skp & bitpos) else "S"
400
        LOG.debug("mem.skip %s" % mem.skip)
401

    
402
        return mem
403

    
404
    def _set_tone(self, mem, _mem):
405
        def _set_dcs(code, pol):
406
            val = int("%i" % code, 8) + 0x2800
407
            if pol == "R":
408
                val += 0x8000
409
            return val
410

    
411
        if mem.tmode == "Cross":
412
            tx_mode, rx_mode = mem.cross_mode.split("->")
413
        elif mem.tmode == "Tone":
414
            tx_mode = mem.tmode
415
            rx_mode = None
416
        else:
417
            tx_mode = rx_mode = mem.tmode
418

    
419
        if tx_mode == "DTCS":
420
            _mem.tx_tone = mem.tmode != "DTCS" and \
421
                           _set_dcs(mem.dtcs, mem.dtcs_polarity[0]) or \
422
                           _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[0])
423
        elif tx_mode:
424
            _mem.tx_tone = tx_mode == "Tone" and \
425
                int(mem.rtone * 10) or int(mem.ctone * 10)
426
        else:
427
            _mem.tx_tone = 0xFFFF
428

    
429
        if rx_mode == "DTCS":
430
            _mem.rx_tone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
431
        elif rx_mode:
432
            _mem.rx_tone = int(mem.ctone * 10)
433
        else:
434
            _mem.rx_tone = 0xFFFF
435

    
436
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
437
                  (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
438

    
439
    def set_memory(self, mem):
440
        bitpos = (1 << ((mem.number - 1) % 8))
441
        bytepos = ((mem.number - 1) / 8)
442
        LOG.debug("bitpos %s" % bitpos)
443
        LOG.debug("bytepos %s" % bytepos)
444

    
445
        _mem = self._memobj.memory[mem.number - 1]
446
        _skp = self._memobj.skipflags[bytepos]
447

    
448
        if mem.empty:
449
            _mem.set_raw("\xFF" * (_mem.size() / 8))
450
            return
451

    
452
        _mem.rxfreq = mem.freq / 10
453

    
454
        if mem.duplex == "off":
455
            for i in range(0, 4):
456
                _mem.txfreq[i].set_raw("\xFF")
457
        elif mem.duplex == "split":
458
            _mem.txfreq = mem.offset / 10
459
        elif mem.duplex == "+":
460
            _mem.txfreq = (mem.freq + mem.offset) / 10
461
        elif mem.duplex == "-":
462
            _mem.txfreq = (mem.freq - mem.offset) / 10
463
        else:
464
            _mem.txfreq = mem.freq / 10
465

    
466
        _mem.wide = mem.mode == "FM"
467

    
468
        self._set_tone(mem, _mem)
469

    
470
        _mem.highpower = mem.power == RT22_POWER_LEVELS[1]
471

    
472
        if mem.skip != "S":
473
            _skp |= bitpos
474
        else:
475
            _skp &= ~bitpos
476
        LOG.debug("_skp %s" % _skp)
477

    
478
    def get_settings(self):
479
        _settings = self._memobj.settings
480
        _message = self._memobj.embedded_msg
481
        basic = RadioSettingGroup("basic", "Basic Settings")
482
        top = RadioSettings(basic)
483

    
484
        rs = RadioSetting("squelch", "Squelch Level",
485
                          RadioSettingValueInteger(0, 9, _settings.squelch))
486
        basic.append(rs)
487

    
488
        rs = RadioSetting("tot", "Time-out timer",
489
                          RadioSettingValueList(
490
                              TIMEOUTTIMER_LIST,
491
                              TIMEOUTTIMER_LIST[_settings.tot]))
492
        basic.append(rs)
493

    
494
        rs = RadioSetting("voice", "Voice Prompts",
495
                          RadioSettingValueList(
496
                              VOICE_LIST, VOICE_LIST[_settings.voice]))
497
        basic.append(rs)
498

    
499
        rs = RadioSetting("pf2key", "PF2 Key",
500
                          RadioSettingValueList(
501
                              PF2KEY_LIST, PF2KEY_LIST[_settings.pf2key]))
502
        basic.append(rs)
503

    
504
        rs = RadioSetting("vox", "Vox",
505
                          RadioSettingValueBoolean(_settings.vox))
506
        basic.append(rs)
507

    
508
        rs = RadioSetting("voxgain", "VOX Level",
509
                          RadioSettingValueList(
510
                              VOX_LIST, VOX_LIST[_settings.voxgain]))
511
        basic.append(rs)
512

    
513
        rs = RadioSetting("voxdelay", "VOX Delay Time",
514
                          RadioSettingValueList(
515
                              VOXDELAY_LIST,
516
                              VOXDELAY_LIST[_settings.voxdelay]))
517
        basic.append(rs)
518

    
519
        rs = RadioSetting("save", "Battery Save",
520
                          RadioSettingValueBoolean(_settings.save))
521
        basic.append(rs)
522

    
523
        rs = RadioSetting("beep", "Beep",
524
                          RadioSettingValueBoolean(_settings.beep))
525
        basic.append(rs)
526

    
527
        def _filter(name):
528
            filtered = ""
529
            for char in str(name):
530
                if char in VALID_CHARS:
531
                    filtered += char
532
                else:
533
                    filtered += " "
534
            return filtered
535

    
536
        rs = RadioSetting("embedded_msg.line1", "Embedded Message 1",
537
                          RadioSettingValueString(0, 32, _filter(
538
                              _message.line1)))
539
        basic.append(rs)
540

    
541
        rs = RadioSetting("embedded_msg.line2", "Embedded Message 2",
542
                          RadioSettingValueString(0, 32, _filter(
543
                              _message.line2)))
544
        basic.append(rs)
545

    
546
        return top
547

    
548
    def set_settings(self, settings):
549
        for element in settings:
550
            if not isinstance(element, RadioSetting):
551
                self.set_settings(element)
552
                continue
553
            else:
554
                try:
555
                    if "." in element.get_name():
556
                        bits = element.get_name().split(".")
557
                        obj = self._memobj
558
                        for bit in bits[:-1]:
559
                            obj = getattr(obj, bit)
560
                        setting = bits[-1]
561
                    else:
562
                        obj = self._memobj.settings
563
                        setting = element.get_name()
564

    
565
                    LOG.debug("Setting %s = %s" % (setting, element.value))
566
                    setattr(obj, setting, element.value)
567
                except Exception, e:
568
                    LOG.debug(element.get_name())
569
                    raise
570

    
571
    @classmethod
572
    def match_model(cls, filedata, filename):
573
        match_size = False
574
        match_model = False
575

    
576
        # testing the file data size
577
        if len(filedata) in [0x0408, ]:
578
            match_size = True
579
        
580
        # testing the firmware model fingerprint
581
        match_model = model_match(cls, filedata)
582

    
583
        if match_size and match_model:
584
            return True
585
        else:
586
            return False
587

    
588
@directory.register
589
class KDC1(RT22Radio):
590
    """WLN KD-C1"""
591
    VENDOR = "WLN"
592
    MODEL = "KD-C1"
593

    
594
@directory.register
595
class ZTX6(RT22Radio):
596
    """Zastone ZT-X6"""
597
    VENDOR = "Zastone"
598
    MODEL = "ZT-X6"
(8-8/19)