Project

General

Profile

New Model #4145 » retevis_rt22.py

Jim Unroe, 11/22/2016 02:02 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
    try:
101
        for j in range(0, len(magic)):
102
            time.sleep(0.01)
103
            serial.write(magic[j])
104
        ack = serial.read(1)
105
    except:
106
        _rt22_exit_programming_mode(radio)
107
        raise errors.RadioError("Error communicating with radio")
108

    
109
    if not ack:
110
        _rt22_exit_programming_mode(radio)
111
        raise errors.RadioError("No response from radio")
112
    elif ack != CMD_ACK:
113
        _rt22_exit_programming_mode(radio)
114
        raise errors.RadioError("Radio refused to enter programming mode")
115

    
116
    try:
117
        serial.write("\x02")
118
        ident = serial.read(8)
119
    except:
120
        _rt22_exit_programming_mode(radio)
121
        raise errors.RadioError("Error communicating with radio")
122

    
123
    if not ident.startswith("P32073"):
124
        _rt22_exit_programming_mode(radio)
125
        LOG.debug(util.hexprint(ident))
126
        raise errors.RadioError("Radio returned unknown identification string")
127

    
128
    try:
129
        serial.write(CMD_ACK)
130
        ack = serial.read(1)
131
    except:
132
        _rt22_exit_programming_mode(radio)
133
        raise errors.RadioError("Error communicating with radio")
134

    
135
    if ack != CMD_ACK:
136
        _rt22_exit_programming_mode(radio)
137
        raise errors.RadioError("Radio refused to enter programming mode")
138

    
139
    try:
140
        serial.write("\x07")
141
        ack = serial.read(1)
142
    except:
143
        _rt22_exit_programming_mode(radio)
144
        raise errors.RadioError("Error communicating with radio")
145

    
146
    if ack != "\x4E":
147
        _rt22_exit_programming_mode(radio)
148
        raise errors.RadioError("Radio refused to enter programming mode")
149

    
150

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

    
158

    
159
def _rt22_read_block(radio, block_addr, block_size):
160
    serial = radio.pipe
161

    
162
    cmd = struct.pack(">cHb", 'R', block_addr, block_size)
163
    expectedresponse = "W" + cmd[1:]
164
    LOG.debug("Reading block %04x..." % (block_addr))
165

    
166
    try:
167
        for j in range(0, len(cmd)):
168
            time.sleep(0.01)
169
            serial.write(cmd[j])
170

    
171
        response = serial.read(4 + block_size)
172
        if response[:4] != expectedresponse:
173
            _rt22_exit_programming_mode(radio)
174
            raise Exception("Error reading block %04x." % (block_addr))
175

    
176
        block_data = response[4:]
177

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

    
184
    if ack != CMD_ACK:
185
        _rt22_exit_programming_mode(radio)
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, block_size)
195
    data = radio.get_mmap()[block_addr:block_addr + 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.01)
203
            serial.write(cmd[j])
204
        for j in range(0, len(data)):
205
            time.sleep(0.01)
206
            serial.write(data[j])
207
        if serial.read(1) != CMD_ACK:
208
            raise Exception("No ACK")
209
    except:
210
        _rt22_exit_programming_mode(radio)
211
        raise errors.RadioError("Failed to send block "
212
                                "to radio at %04x" % block_addr)
213

    
214

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

    
219
    data = ""
220

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

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

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

    
231
        block = _rt22_read_block(radio, addr, radio._block_size)
232
        data += block
233

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

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

    
239
    _rt22_exit_programming_mode(radio)
240

    
241
    return memmap.MemoryMap(data)
242

    
243

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

    
248
    _rt22_enter_programming_mode(radio)
249

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

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

    
259
    _rt22_exit_programming_mode(radio)
260

    
261

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

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

    
271

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

    
279
    _ranges = [
280
               (0x0000, 0x0180, 0x10),
281
               (0x01B8, 0x01F8, 0x10),
282
               (0x01F8, 0x0200, 0x08),
283
               (0x0200, 0x0340, 0x10),
284
              ]
285
    _memsize = 0x0400
286
    _block_size = 0x40
287

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

    
308
        return rf
309

    
310
    def process_mmap(self):
311
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
312

    
313
    def sync_in(self):
314
        self._mmap = do_download(self)
315
        self.process_mmap()
316

    
317
    def sync_out(self):
318
        do_upload(self)
319

    
320
    def get_raw_memory(self, number):
321
        return repr(self._memobj.memory[number - 1])
322

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

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

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

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

    
359
        if mem.tmode == "DTCS":
360
            mem.dtcs_polarity = "%s%s" % (tpol, rpol)
361

    
362
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
363
                  (txmode, _mem.tx_tone, rxmode, _mem.rx_tone))
364

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

    
371
        _mem = self._memobj.memory[number - 1]
372
        _skp = self._memobj.skipflags[bytepos]
373

    
374
        mem = chirp_common.Memory()
375

    
376
        mem.number = number
377
        mem.freq = int(_mem.rxfreq) * 10
378

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

    
384
        if _mem.rxfreq.get_raw() == "\xFF\xFF\xFF\xFF":
385
            mem.freq = 0
386
            mem.empty = True
387
            return mem
388

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

    
396
        mem.mode = _mem.wide and "FM" or "NFM"
397

    
398
        self._get_tone(_mem, mem)
399

    
400
        mem.power = RT22_POWER_LEVELS[_mem.highpower]
401

    
402
        mem.skip = "" if (_skp & bitpos) else "S"
403
        LOG.debug("mem.skip %s" % mem.skip)
404

    
405
        return mem
406

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

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

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

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

    
439
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
440
                  (tx_mode, _mem.tx_tone, rx_mode, _mem.rx_tone))
441

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

    
448
        _mem = self._memobj.memory[mem.number - 1]
449
        _skp = self._memobj.skipflags[bytepos]
450

    
451
        if mem.empty:
452
            _mem.set_raw("\xFF" * (_mem.size() / 8))
453
            return
454

    
455
        _mem.rxfreq = mem.freq / 10
456

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

    
469
        _mem.wide = mem.mode == "FM"
470

    
471
        self._set_tone(mem, _mem)
472

    
473
        _mem.highpower = mem.power == RT22_POWER_LEVELS[1]
474

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

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

    
487
        rs = RadioSetting("squelch", "Squelch Level",
488
                          RadioSettingValueInteger(0, 9, _settings.squelch))
489
        basic.append(rs)
490

    
491
        rs = RadioSetting("tot", "Time-out timer",
492
                          RadioSettingValueList(
493
                              TIMEOUTTIMER_LIST,
494
                              TIMEOUTTIMER_LIST[_settings.tot]))
495
        basic.append(rs)
496

    
497
        rs = RadioSetting("voice", "Voice Prompts",
498
                          RadioSettingValueList(
499
                              VOICE_LIST, VOICE_LIST[_settings.voice]))
500
        basic.append(rs)
501

    
502
        rs = RadioSetting("pf2key", "PF2 Key",
503
                          RadioSettingValueList(
504
                              PF2KEY_LIST, PF2KEY_LIST[_settings.pf2key]))
505
        basic.append(rs)
506

    
507
        rs = RadioSetting("vox", "Vox",
508
                          RadioSettingValueBoolean(_settings.vox))
509
        basic.append(rs)
510

    
511
        rs = RadioSetting("voxgain", "VOX Level",
512
                          RadioSettingValueList(
513
                              VOX_LIST, VOX_LIST[_settings.voxgain]))
514
        basic.append(rs)
515

    
516
        rs = RadioSetting("voxdelay", "VOX Delay Time",
517
                          RadioSettingValueList(
518
                              VOXDELAY_LIST,
519
                              VOXDELAY_LIST[_settings.voxdelay]))
520
        basic.append(rs)
521

    
522
        rs = RadioSetting("save", "Battery Save",
523
                          RadioSettingValueBoolean(_settings.save))
524
        basic.append(rs)
525

    
526
        rs = RadioSetting("beep", "Beep",
527
                          RadioSettingValueBoolean(_settings.beep))
528
        basic.append(rs)
529

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

    
539
        rs = RadioSetting("embedded_msg.line1", "Embedded Message 1",
540
                          RadioSettingValueString(0, 32, _filter(
541
                              _message.line1)))
542
        basic.append(rs)
543

    
544
        rs = RadioSetting("embedded_msg.line2", "Embedded Message 2",
545
                          RadioSettingValueString(0, 32, _filter(
546
                              _message.line2)))
547
        basic.append(rs)
548

    
549
        return top
550

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

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

    
574
    @classmethod
575
    def match_model(cls, filedata, filename):
576
        match_size = False
577
        match_model = False
578

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

    
586
        if match_size and match_model:
587
            return True
588
        else:
589
            return False
590

    
591
@directory.register
592
class KDC1(RT22Radio):
593
    """WLN KD-C1"""
594
    VENDOR = "WLN"
595
    MODEL = "KD-C1"
596

    
597
@directory.register
598
class ZTX6(RT22Radio):
599
    """Zastone ZT-X6"""
600
    VENDOR = "Zastone"
601
    MODEL = "ZT-X6"
(13-13/19)