Project

General

Profile

Bug #6101 » program_defect_KD-C1.py

J A, 10/15/2018 04:26 AM

 
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("P3"):
129
        _rt22_exit_programming_mode(radio)
130
        LOG.debug(util.hexprint(ident))
131
        LOG.debug(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
    cmd = struct.pack(">cHb", 'R', block_addr, block_size)
169
    expectedresponse = "W" + cmd[1:]
170
    LOG.debug("Reading block %04x..." % (block_addr))
171

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

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

    
182
        block_data = response[4:]
183

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

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

    
194
    return block_data
195

    
196

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

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

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

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

    
220

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

    
225
    data = ""
226

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

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

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

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

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

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

    
245
    _rt22_exit_programming_mode(radio)
246

    
247
    return memmap.MemoryMap(data)
248

    
249

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

    
254
    _rt22_enter_programming_mode(radio)
255

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

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

    
265
    _rt22_exit_programming_mode(radio)
266

    
267

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

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

    
277

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

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

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

    
314
        return rf
315

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

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

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

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

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

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

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

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

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

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

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

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

    
400
        mem = chirp_common.Memory()
401

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

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

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

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

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

    
424
        self._get_tone(_mem, mem)
425

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

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

    
431
        return mem
432

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

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

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

    
465
        _mem.rx_tone = rx_tone
466
        _mem.tx_tone = tx_tone
467

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

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

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

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

    
484
        _mem.rxfreq = mem.freq / 10
485

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

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

    
500
        self._set_tone(mem, _mem)
501

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
578
        return top
579

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

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

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

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

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

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

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

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

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