Project

General

Profile

Bug #10455 » kguv8dplus.py

8D Plus DCS decoding Read/Write + UHF lower Limit Change - Mel Terechenok, 06/05/2023 04:40 PM

 
1
# Copyright 2017 Krystian Struzik <toner_82@tlen.pl>
2
#                Based on Ron Wellsted driver for Wouxun KG-UV8D.
3
#                KG-UV8D Plus model has all serial data encrypted.
4
#                Figured out how the data is encrypted and implement
5
#                serial data encryption and decryption functions.
6
#                The algorithm of decryption works like this:
7
#                - the first byte of data stream is XOR by const 57h
8
#                - each next byte is encoded by previous byte using the XOR
9
#                  including the checksum (e.g data[i - 1] xor data[i])
10
#                I also changed the data structure to fit radio memory
11
#                and implement set_settings function.
12
#
13
# This program is free software: you can redistribute it and/or modify
14
# it under the terms of the GNU General Public License as published by
15
# the Free Software Foundation, either version 3 of the License, or
16
# (at your option) any later version.
17
#
18
# This program is distributed in the hope that it will be useful,
19
# but WITHOUT ANY WARRANTY; without even the implied warranty of
20
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21
# GNU General Public License for more details.
22
#
23
# You should have received a copy of the GNU General Public License
24
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
25

    
26
"""Wouxun KG-UV8D Plus radio management module"""
27

    
28
import struct
29
import time
30
import logging
31
from chirp import util, chirp_common, bitwise, memmap, errors, directory
32
from chirp.settings import RadioSetting, RadioSettingGroup, \
33
    RadioSettingValueBoolean, RadioSettingValueList, \
34
    RadioSettingValueInteger, RadioSettingValueString, \
35
    RadioSettings
36

    
37
LOG = logging.getLogger(__name__)
38

    
39
CMD_ID = 128
40
CMD_END = 129
41
CMD_RD = 130
42
CMD_WR = 131
43

    
44
MEM_VALID = 158
45

    
46
AB_LIST = ["A", "B"]
47
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0, 50.0, 100.0]
48
STEP_LIST = [str(x) for x in STEPS]
49
ROGER_LIST = ["Off", "Begin", "End", "Both"]
50
TIMEOUT_LIST = ["Off"] + [str(x) + "s" for x in range(15, 901, 15)]
51
VOX_LIST = ["Off"] + ["%s" % x for x in range(1, 10)]
52
BANDWIDTH_LIST = ["Narrow", "Wide"]
53
VOICE_LIST = ["Off", "On"]
54
LANGUAGE_LIST = ["Chinese", "English"]
55
SCANMODE_LIST = ["TO", "CO", "SE"]
56
PF1KEY_LIST = ["Call", "VFTX"]
57
PF3KEY_LIST = ["Disable", "Scan", "Lamp", "Tele Alarm", "SOS-CH", "Radio"]
58
WORKMODE_LIST = ["VFO", "Channel No.", "Ch. No.+Freq.", "Ch. No.+Name"]
59
BACKLIGHT_LIST = ["Always On"] + [str(x) + "s" for x in range(1, 21)] + \
60
    ["Always Off"]
61
OFFSET_LIST = ["+", "-"]
62
PONMSG_LIST = ["Bitmap", "Battery Volts"]
63
SPMUTE_LIST = ["QT", "QT+DTMF", "QT*DTMF"]
64
DTMFST_LIST = ["DT-ST", "ANI-ST", "DT-ANI", "Off"]
65
DTMF_TIMES = ["%s" % x for x in range(50, 501, 10)]
66
RPTSET_LIST = ["X-TWRPT", "X-DIRRPT"]
67
ALERTS = [1750, 2100, 1000, 1450]
68
ALERTS_LIST = [str(x) for x in ALERTS]
69
PTTID_LIST = ["Begin", "End", "Both"]
70
LIST_10 = ["Off"] + ["%s" % x for x in range(1, 11)]
71
SCANGRP_LIST = ["All"] + ["%s" % x for x in range(1, 11)]
72
SCQT_LIST = ["Decoder", "Encoder", "All"]
73
SMUTESET_LIST = ["Off", "Tx", "Rx", "Tx/Rx"]
74
POWER_LIST = ["Lo", "Hi"]
75
HOLD_TIMES = ["Off"] + ["%s" % x for x in range(100, 5001, 100)]
76
RPTMODE_LIST = ["Radio", "Repeater"]
77

    
78
# memory slot 0 is not used, start at 1 (so need 1000 slots, not 999)
79
# structure elements whose name starts with x are currently unidentified
80

    
81
_MEM_FORMAT = """
82
    #seekto 0x0044;
83
    struct {
84
        u32    rx_start;
85
        u32    rx_stop;
86
        u32    tx_start;
87
        u32    tx_stop;
88
    } uhf_limits;
89

    
90
    #seekto 0x0054;
91
    struct {
92
        u32    rx_start;
93
        u32    rx_stop;
94
        u32    tx_start;
95
        u32    tx_stop;
96
    } vhf_limits;
97

    
98
    #seekto 0x0400;
99
    struct {
100
        u8     oem1[8];
101
        u8     unknown[2];
102
        u8     unknown2[10];
103
        u8     unknown3[10];
104
        u8     unknown4[8];
105
        u8     model[10];
106
        u8     version[6];
107
        u8     date[8];
108
        u8     unknown5[1];
109
        u8     oem2[8];
110
    } oem_info;
111

    
112
    #seekto 0x0480;
113
    struct {
114
        u16    lower;
115
        u16    upper;
116
    } scan_groups[10];
117

    
118
    #seekto 0x0500;
119
    struct {
120
        u8    call_code[6];
121
    } call_groups[20];
122

    
123
    #seekto 0x0580;
124
    struct {
125
        char    call_name[6];
126
    } call_group_name[20];
127

    
128
    #seekto 0x0800;
129
    struct {
130
        u8      ponmsg;
131
        char    dispstr[15];
132
        u8 x0810;
133
        u8 x0811;
134
        u8 x0812;
135
        u8 x0813;
136
        u8 x0814;
137
        u8      voice;
138
        u8      timeout;
139
        u8      toalarm;
140
        u8      channel_menu;
141
        u8      power_save;
142
        u8      autolock;
143
        u8      keylock;
144
        u8      beep;
145
        u8      stopwatch;
146
        u8      vox;
147
        u8      scan_rev;
148
        u8      backlight;
149
        u8      roger_beep;
150
        u8 x0822[6];
151
        u8 x0823[6];
152
        u16     pri_ch;
153
        u8      ani_sw;
154
        u8      ptt_delay;
155
        u8      ani_code[6];
156
        u8      dtmf_st;
157
        u8      bcl_a;
158
        u8      bcl_b;
159
        u8      ptt_id;
160
        u8      prich_sw;
161
        u8      rpt_set;
162
        u8      rpt_spk;
163
        u8      rpt_ptt;
164
        u8      alert;
165
        u8      pf1_func;
166
        u8      pf3_func;
167
        u8 x0843;
168
        u8      workmode_a;
169
        u8      workmode_b;
170
        u8      dtmf_tx_time;
171
        u8      dtmf_interval;
172
        u8      main_ab;
173
        u16     work_cha;
174
        u16     work_chb;
175
        u8 x084d;
176
        u8 x084e;
177
        u8 x084f;
178
        u8 x0850;
179
        u8 x0851;
180
        u8 x0852;
181
        u8 x0853;
182
        u8 x0854;
183
        u8      rpt_mode;
184
        u8      language;
185
        u8 x0857;
186
        u8 x0858;
187
        u8 x0859;
188
        u8 x085a;
189
        u8 x085b;
190
        u8 x085c;
191
        u8 x085d;
192
        u8 x085e;
193
        u8      single_display;
194
        u8      ring_time;
195
        u8      scg_a;
196
        u8      scg_b;
197
        u8 x0863;
198
        u8      rpt_tone;
199
        u8      rpt_hold;
200
        u8      scan_det;
201
        u8      sc_qt;
202
        u8 x0868;
203
        u8      smuteset;
204
        u8      callcode;
205
    } settings;
206

    
207
    #seekto 0x0880;
208
    struct {
209
        u32     rxfreq;
210
        u32     txoffset;
211
        u16     rxtone;
212
        u16     txtone;
213
        u8      scrambler:4,
214
                unknown1:2,
215
                power:1,
216
                unknown2:1;
217
        u8      unknown3:1,
218
                shift_dir:2
219
                unknown4:1,
220
                compander:1,
221
                mute_mode:2,
222
                iswide:1;
223
        u8      step;
224
        u8      squelch;
225
      } vfoa;
226

    
227
    #seekto 0x08c0;
228
    struct {
229
        u32     rxfreq;
230
        u32     txoffset;
231
        u16     rxtone;
232
        u16     txtone;
233
        u8      scrambler:4,
234
                unknown1:2,
235
                power:1,
236
                unknown2:1;
237
        u8      unknown3:1,
238
                shift_dir:2
239
                unknown4:1,
240
                compander:1,
241
                mute_mode:2,
242
                iswide:1;
243
        u8      step;
244
        u8      squelch;
245
    } vfob;
246

    
247
    #seekto 0x0900;
248
    struct {
249
        u32     rxfreq;
250
        u32     txfreq;
251
        u16     rxtone;
252
        u16     txtone;
253
        u8      scrambler:4,
254
                unknown1:2,
255
                power:1,
256
                unknown2:1;
257
        u8      unknown3:2,
258
                scan_add:1,
259
                unknown4:1,
260
                compander:1,
261
                mute_mode:2,
262
                iswide:1;
263
        u16     padding;
264
    } memory[1000];
265

    
266
    #seekto 0x4780;
267
    struct {
268
        u8    name[8];
269
		u8    unknown[4];
270
    } names[1000];
271

    
272
    #seekto 0x7670;
273
    u8          valid[1000];
274
    """
275

    
276
# Support for the Wouxun KG-UV8D Plus radio
277
# Serial coms are at 19200 baud
278
# The data is passed in variable length records
279
# Record structure:
280
#  Offset   Usage
281
#    0      start of record (\x7a)
282
#    1      Command (\x80 Identify \x81 End/Reboot \x82 Read \x83 Write)
283
#    2      direction (\xff PC-> Radio, \x00 Radio -> PC)
284
#    3      length of payload (excluding header/checksum) (n)
285
#    4      payload (n bytes)
286
#    4+n+1  checksum - byte sum (% 256) of bytes 1 -> 4+n
287
#
288
# Memory Read Records:
289
# the payload is 3 bytes, first 2 are offset (big endian),
290
# 3rd is number of bytes to read
291
# Memory Write Records:
292
# the maximum payload size (from the Wouxun software) seems to be 66 bytes
293
#  (2 bytes location + 64 bytes data).
294

    
295
@directory.register
296
class KGUV8DPlusRadio(chirp_common.CloneModeRadio,
297
                  chirp_common.ExperimentalRadio):
298

    
299
    """Wouxun KG-UV8D Plus"""
300
    VENDOR = "Wouxun"
301
    MODEL = "KG-UV8D Plus"
302
    _model = b"KG-UV8D"
303
    _file_ident = b"kguv8dplus"
304
    BAUD_RATE = 19200
305
    POWER_LEVELS = [chirp_common.PowerLevel("L", watts=1),
306
                    chirp_common.PowerLevel("H", watts=5)]
307
    NEEDS_COMPAT_SERIAL = False
308
    _mmap = ""
309
    _record_start = 0x7A
310

    
311
    def _checksum(self, data):
312
        cs = 0
313
        for byte in data:
314
            cs += byte
315
        return cs % 256
316

    
317
    def _write_record(self, cmd, payload=b''):
318
        _packet = struct.pack('BBBB', self._record_start, cmd, 0xFF,
319
                              len(payload))
320
        checksum = bytes([self._checksum(_packet[1:] + payload)])
321
        _packet += self.encrypt(payload + checksum)
322
        LOG.debug("Sent:\n%s" % util.hexprint(_packet))
323
        self.pipe.write(_packet)
324

    
325
    def _read_record(self):
326
        # read 4 chars for the header
327
        _header = self.pipe.read(4)
328
        if len(_header) != 4:
329
            raise errors.RadioError('Radio did not respond')
330
        _length = struct.unpack('xxxB', _header)[0]
331
        _packet = self.pipe.read(_length)
332
        _rcs_xor = _packet[-1]
333
        _packet = self.decrypt(_packet)
334
        _cs = self._checksum(_header[1:])
335
        _cs += self._checksum(_packet)
336
        _cs %= 256
337
        _rcs = self.strxor(self.pipe.read(1)[0], _rcs_xor)[0]
338
        LOG.debug("_cs =%x", _cs)
339
        LOG.debug("_rcs=%x", _rcs)
340
        return (_rcs != _cs, _packet)
341

    
342
    def decrypt(self, data):
343
        result = b''
344
        for i in range(len(data)-1, 0, -1):
345
            result += self.strxor(data[i], data[i - 1])
346
        result += self.strxor(data[0], 0x57)
347
        return result[::-1]
348

    
349
    def encrypt(self, data):
350
        result = self.strxor(0x57, data[0])
351
        for i in range(1, len(data), 1):
352
            result += self.strxor(result[i - 1], data[i])
353
        return result
354

    
355
    def strxor(self, xora, xorb):
356
        return bytes([xora ^ xorb])
357

    
358
# Identify the radio
359
#
360
# A Gotcha: the first identify packet returns a bad checksum, subsequent
361
# attempts return the correct checksum... (well it does on my radio!)
362
#
363
# The ID record returned by the radio also includes the current frequency range
364
# as 4 bytes big-endian in 10Hz increments
365
#
366
# Offset
367
#  0:10     Model, zero padded (Use first 7 chars for 'KG-UV8D')
368
#  11:14    UHF rx lower limit (in units of 10Hz)
369
#  15:18    UHF rx upper limit
370
#  19:22    UHF tx lower limit
371
#  23:26    UHF tx upper limit
372
#  27:30    VHF rx lower limit
373
#  31:34    VHF rx upper limit
374
#  35:38    VHF tx lower limit
375
#  39:42    VHF tx upper limit
376
#
377
    @classmethod
378
    def match_model(cls, filedata, filename):
379
        return cls._file_ident in b'kg' + filedata[0x426:0x430].replace(b'(', b'').replace(b')', b'').lower()
380

    
381
    def _identify(self):
382
        """Do the identification dance"""
383
        for _i in range(0, 10):
384
            self._write_record(CMD_ID)
385
            _chksum_err, _resp = self._read_record()
386
            LOG.debug("Got:\n%s" % util.hexprint(_resp))
387
            if _chksum_err:
388
                LOG.error("Checksum error: retrying ident...")
389
                time.sleep(0.100)
390
                continue
391
            LOG.debug("Model %s" % util.hexprint(_resp[0:7]))
392
            if _resp[0:7] == self._model:
393
                return
394
            if len(_resp) == 0:
395
                raise Exception("Radio not responding")
396
            else:
397
                raise Exception("Unable to identify radio")
398

    
399
    def _finish(self):
400
        self._write_record(CMD_END)
401

    
402
    def process_mmap(self):
403
        self._memobj = bitwise.parse(_MEM_FORMAT, self._mmap)
404

    
405
    def sync_in(self):
406
        try:
407
            self._mmap = self._download()
408
        except errors.RadioError:
409
            raise
410
        except Exception as e:
411
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
412
        self.process_mmap()
413

    
414
    def sync_out(self):
415
        self._upload()
416

    
417
    # TODO: Load all memory.
418
    # It would be smarter to only load the active areas and none of
419
    # the padding/unused areas. Padding still need to be investigated.
420
    def _download(self):
421
        """Talk to a wouxun KG-UV8D Plus and do a download"""
422
        try:
423
            self._identify()
424
            return self._do_download(0, 32768, 64)
425
        except errors.RadioError:
426
            raise
427
        except Exception as e:
428
            LOG.exception('Unknown error during download process')
429
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
430

    
431
    def _do_download(self, start, end, blocksize):
432
        # allocate & fill memory
433
        image = b""
434
        for i in range(start, end, blocksize):
435
            req = struct.pack('>HB', i, blocksize)
436
            self._write_record(CMD_RD, req)
437
            cs_error, resp = self._read_record()
438
            if cs_error:
439
                LOG.debug(util.hexprint(resp))
440
                raise Exception("Checksum error on read")
441
            LOG.debug("Got:\n%s" % util.hexprint(resp))
442
            image += resp[2:]
443
            if self.status_fn:
444
                status = chirp_common.Status()
445
                status.cur = i
446
                status.max = end
447
                status.msg = "Cloning from radio"
448
                self.status_fn(status)
449
        self._finish()
450
        return memmap.MemoryMapBytes(image)
451

    
452
    def _upload(self):
453
        """Talk to a wouxun KG-UV8D Plus and do a upload"""
454
        try:
455
            self._identify()
456
            self._do_upload(0, 32768, 64)
457
        except errors.RadioError:
458
            raise
459
        except Exception as e:
460
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
461
        return
462

    
463
    def _do_upload(self, start, end, blocksize):
464
        ptr = start
465
        for i in range(start, end, blocksize):
466
            req = struct.pack('>H', i)
467
            chunk = self.get_mmap()[ptr:ptr + blocksize]
468
            self._write_record(CMD_WR, req + chunk)
469
            LOG.debug(util.hexprint(req + chunk))
470
            cserr, ack = self._read_record()
471
            LOG.debug(util.hexprint(ack))
472
            j = struct.unpack('>H', ack)[0]
473
            if cserr or j != ptr:
474
                raise Exception("Radio did not ack block %i" % ptr)
475
            ptr += blocksize
476
            if self.status_fn:
477
                status = chirp_common.Status()
478
                status.cur = i
479
                status.max = end
480
                status.msg = "Cloning to radio"
481
                self.status_fn(status)
482
        self._finish()
483

    
484
    def get_features(self):
485
        rf = chirp_common.RadioFeatures()
486
        rf.has_settings = True
487
        rf.has_ctone = True
488
        rf.has_rx_dtcs = True
489
        rf.has_cross = True
490
        rf.has_tuning_step = False
491
        rf.has_bank = False
492
        rf.can_odd_split = True
493
        rf.valid_skips = ["", "S"]
494
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
495
        rf.valid_cross_modes = [
496
            "Tone->Tone",
497
            "Tone->DTCS",
498
            "DTCS->Tone",
499
            "DTCS->",
500
            "->Tone",
501
            "->DTCS",
502
            "DTCS->DTCS",
503
        ]
504
        rf.valid_modes = ["FM", "NFM"]
505
        rf.valid_power_levels = self.POWER_LEVELS
506
        rf.valid_name_length = 8
507
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
508
        rf.valid_bands = [(134000000, 175000000),  # supports 2m
509
                          (400000000, 520000000)]  # supports 70cm
510
        rf.valid_characters = chirp_common.CHARSET_ASCII
511
        rf.valid_tuning_steps = STEPS
512
        rf.memory_bounds = (1, 999)  # 999 memories
513
        return rf
514

    
515
    @classmethod
516
    def get_prompts(cls):
517
        rp = chirp_common.RadioPrompts()
518
        rp.experimental = ("This radio driver is currently under development. "
519
                           "There are no known issues with it, but you should "
520
                           "proceed with caution.")
521
        return rp
522

    
523
    def get_raw_memory(self, number):
524
        return repr(self._memobj.memory[number])
525

    
526
    def _get_tone(self, _mem, mem):
527
        def _get_dcs(val):
528
            code = int("%03o" % (val & 0x07FF))
529
            pol = (val & 0x2000) and "R" or "N"
530
            return code, pol
531

    
532
        tpol = False
533
        if _mem.txtone != 0xFFFF and (_mem.txtone & 0x4000) == 0x4000:
534
            tcode, tpol = _get_dcs(_mem.txtone)
535
            mem.dtcs = tcode
536
            txmode = "DTCS"
537
        elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
538
            mem.rtone = (_mem.txtone & 0x7fff) / 10.0
539
            txmode = "Tone"
540
        else:
541
            txmode = ""
542

    
543
        rpol = False
544
        if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x4000) == 0x4000:
545
            rcode, rpol = _get_dcs(_mem.rxtone)
546
            mem.rx_dtcs = rcode
547
            rxmode = "DTCS"
548
        elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
549
            mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
550
            rxmode = "Tone"
551
        else:
552
            rxmode = ""
553

    
554
        if txmode == "Tone" and not rxmode:
555
            mem.tmode = "Tone"
556
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
557
            mem.tmode = "TSQL"
558
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
559
            mem.tmode = "DTCS"
560
        elif rxmode or txmode:
561
            mem.tmode = "Cross"
562
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
563

    
564
        # always set it even if no dtcs is used
565
        mem.dtcs_polarity = "%s%s" % (tpol or "N", rpol or "N")
566

    
567
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
568
                  (txmode, _mem.txtone, rxmode, _mem.rxtone))
569

    
570
    def get_memory(self, number):
571
        _mem = self._memobj.memory[number]
572
        _nam = self._memobj.names[number]
573

    
574
        mem = chirp_common.Memory()
575
        mem.number = number
576
        _valid = self._memobj.valid[mem.number]
577
        LOG.debug("%d %s", number, _valid == MEM_VALID)
578
        if _valid != MEM_VALID:
579
            mem.empty = True
580
            return mem
581
        else:
582
            mem.empty = False
583

    
584
        mem.freq = int(_mem.rxfreq) * 10
585

    
586
        if _mem.txfreq == 0xFFFFFFFF:
587
            # TX freq not set
588
            mem.duplex = "off"
589
            mem.offset = 0
590
        elif int(_mem.rxfreq) == int(_mem.txfreq):
591
            mem.duplex = ""
592
            mem.offset = 0
593
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
594
            mem.duplex = "split"
595
            mem.offset = int(_mem.txfreq) * 10
596
        else:
597
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
598
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
599

    
600
        for char in _nam.name:
601
            if char != 0:
602
                mem.name += chr(char)
603
        mem.name = mem.name.rstrip()
604

    
605
        self._get_tone(_mem, mem)
606

    
607
        mem.skip = "" if bool(_mem.scan_add) else "S"
608

    
609
        mem.power = self.POWER_LEVELS[_mem.power]
610
        mem.mode = _mem.iswide and "FM" or "NFM"
611
        return mem
612

    
613
    def _set_tone(self, mem, _mem):
614
        def _set_dcs(code, pol):
615
            val = int("%i" % code, 8) + 0x4000
616
            if pol == "R":
617
                val += 0x2000
618
            return val
619

    
620
        rx_mode = tx_mode = None
621
        rxtone = txtone = 0x0000
622

    
623
        if mem.tmode == "Tone":
624
            tx_mode = "Tone"
625
            rx_mode = None
626
            txtone = int(mem.rtone * 10) + 0x8000
627
        elif mem.tmode == "TSQL":
628
            rx_mode = tx_mode = "Tone"
629
            rxtone = txtone = int(mem.ctone * 10) + 0x8000
630
        elif mem.tmode == "DTCS":
631
            tx_mode = rx_mode = "DTCS"
632
            txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
633
            rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
634
        elif mem.tmode == "Cross":
635
            tx_mode, rx_mode = mem.cross_mode.split("->")
636
            if tx_mode == "DTCS":
637
                txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
638
            elif tx_mode == "Tone":
639
                txtone = int(mem.rtone * 10) + 0x8000
640
            if rx_mode == "DTCS":
641
                rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
642
            elif rx_mode == "Tone":
643
                rxtone = int(mem.ctone * 10) + 0x8000
644

    
645
        _mem.rxtone = rxtone
646
        _mem.txtone = txtone
647

    
648
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
649
                  (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
650

    
651
    def set_memory(self, mem):
652
        number = mem.number
653

    
654
        _mem = self._memobj.memory[number]
655
        _nam = self._memobj.names[number]
656

    
657
        if mem.empty:
658
            _mem.set_raw("\x00" * (_mem.size() // 8))
659
            self._memobj.valid[number] = 0
660
            self._memobj.names[number].set_raw("\x00" * (_nam.size() // 8))
661
            return
662

    
663
        _mem.rxfreq = int(mem.freq / 10)
664
        if mem.duplex == "off":
665
            _mem.txfreq = 0xFFFFFFFF
666
        elif mem.duplex == "split":
667
            _mem.txfreq = int(mem.offset / 10)
668
        elif mem.duplex == "off":
669
            for i in range(0, 4):
670
                _mem.txfreq[i].set_raw("\xFF")
671
        elif mem.duplex == "+":
672
            _mem.txfreq = int(mem.freq / 10) + int(mem.offset / 10)
673
        elif mem.duplex == "-":
674
            _mem.txfreq = int(mem.freq / 10) - int(mem.offset / 10)
675
        else:
676
            _mem.txfreq = int(mem.freq / 10)
677
        _mem.scan_add = int(mem.skip != "S")
678
        _mem.iswide = int(mem.mode == "FM")
679
        # set the tone
680
        self._set_tone(mem, _mem)
681
        # set the scrambler and compander to off by default
682
        _mem.scrambler = 0
683
        _mem.compander = 0
684
        # set the power
685
        if mem.power:
686
            _mem.power = self.POWER_LEVELS.index(mem.power)
687
        else:
688
            _mem.power = True
689
        # set to mute mode to QT (not QT+DTMF or QT*DTMF) by default
690
        _mem.mute_mode = 0
691

    
692
        for i in range(0, len(_nam.name)):
693
            if i < len(mem.name) and mem.name[i]:
694
                _nam.name[i] = ord(mem.name[i])
695
            else:
696
                _nam.name[i] = 0x0
697
        self._memobj.valid[mem.number] = MEM_VALID
698

    
699
    def _get_settings(self):
700
        _settings = self._memobj.settings
701
        _vfoa = self._memobj.vfoa
702
        _vfob = self._memobj.vfob
703
        cfg_grp = RadioSettingGroup("cfg_grp", "Configuration")
704
        vfoa_grp = RadioSettingGroup("vfoa_grp", "VFO A Settings")
705
        vfob_grp = RadioSettingGroup("vfob_grp", "VFO B Settings")
706
        key_grp = RadioSettingGroup("key_grp", "Key Settings")
707
        lmt_grp = RadioSettingGroup("lmt_grp", "Frequency Limits")
708
        uhf_lmt_grp = RadioSettingGroup("uhf_lmt_grp", "UHF")
709
        vhf_lmt_grp = RadioSettingGroup("vhf_lmt_grp", "VHF")
710
        oem_grp = RadioSettingGroup("oem_grp", "OEM Info")
711

    
712
        lmt_grp.append(uhf_lmt_grp)
713
        lmt_grp.append(vhf_lmt_grp)
714
        group = RadioSettings(cfg_grp, vfoa_grp, vfob_grp,
715
                              key_grp, lmt_grp, oem_grp)
716

    
717
        #
718
        # Configuration Settings
719
        #
720
        rs = RadioSetting("channel_menu", "Menu available in channel mode",
721
                          RadioSettingValueBoolean(_settings.channel_menu))
722
        cfg_grp.append(rs)
723
        rs = RadioSetting("ponmsg", "Poweron message",
724
                          RadioSettingValueList(
725
                              PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
726
        cfg_grp.append(rs)
727
        rs = RadioSetting("voice", "Voice Guide",
728
                          RadioSettingValueBoolean(_settings.voice))
729
        cfg_grp.append(rs)
730
        rs = RadioSetting("language", "Language",
731
                          RadioSettingValueList(LANGUAGE_LIST,
732
                                                LANGUAGE_LIST[_settings.
733
                                                              language]))
734
        cfg_grp.append(rs)
735
        rs = RadioSetting("timeout", "Timeout Timer",
736
                          RadioSettingValueList(
737
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
738
        cfg_grp.append(rs)
739
        rs = RadioSetting("toalarm", "Timeout Alarm",
740
                          RadioSettingValueInteger(0, 10, _settings.toalarm))
741
        cfg_grp.append(rs)
742
        rs = RadioSetting("roger_beep", "Roger Beep",
743
                          RadioSettingValueList(ROGER_LIST, 
744
                                                ROGER_LIST[_settings.roger_beep]))
745
        cfg_grp.append(rs)
746
        rs = RadioSetting("power_save", "Power save",
747
                          RadioSettingValueBoolean(_settings.power_save))
748
        cfg_grp.append(rs)
749
        rs = RadioSetting("autolock", "Autolock",
750
                          RadioSettingValueBoolean(_settings.autolock))
751
        cfg_grp.append(rs)
752
        rs = RadioSetting("keylock", "Keypad Lock",
753
                          RadioSettingValueBoolean(_settings.keylock))
754
        cfg_grp.append(rs)
755
        rs = RadioSetting("beep", "Keypad Beep",
756
                          RadioSettingValueBoolean(_settings.beep))
757
        cfg_grp.append(rs)
758
        rs = RadioSetting("stopwatch", "Stopwatch",
759
                          RadioSettingValueBoolean(_settings.stopwatch))
760
        cfg_grp.append(rs)
761
        rs = RadioSetting("backlight", "Backlight",
762
                          RadioSettingValueList(BACKLIGHT_LIST,
763
                                                BACKLIGHT_LIST[_settings.
764
                                                               backlight]))
765
        cfg_grp.append(rs)
766
        rs = RadioSetting("dtmf_st", "DTMF Sidetone",
767
                          RadioSettingValueList(DTMFST_LIST,
768
                                                DTMFST_LIST[_settings.
769
                                                            dtmf_st]))
770
        cfg_grp.append(rs)
771
        rs = RadioSetting("ani_sw", "ANI-ID Switch",
772
                          RadioSettingValueBoolean(_settings.ani_sw))
773
        cfg_grp.append(rs)
774
        rs = RadioSetting("ptt_id", "PTT-ID Delay",
775
                          RadioSettingValueList(PTTID_LIST,
776
                                                PTTID_LIST[_settings.ptt_id]))
777
        cfg_grp.append(rs)
778
        rs = RadioSetting("ring_time", "Ring Time",
779
                          RadioSettingValueList(LIST_10,
780
                                                LIST_10[_settings.ring_time]))
781
        cfg_grp.append(rs)
782
        rs = RadioSetting("scan_rev", "Scan Mode",
783
                          RadioSettingValueList(SCANMODE_LIST,
784
                                                SCANMODE_LIST[_settings.
785
                                                              scan_rev]))
786
        cfg_grp.append(rs)
787
        rs = RadioSetting("vox", "VOX",
788
                          RadioSettingValueList(LIST_10,
789
                                                LIST_10[_settings.vox]))
790
        cfg_grp.append(rs)
791
        rs = RadioSetting("prich_sw", "Priority Channel Switch",
792
                          RadioSettingValueBoolean(_settings.prich_sw))
793
        cfg_grp.append(rs)
794
        rs = RadioSetting("pri_ch", "Priority Channel",
795
                          RadioSettingValueInteger(1, 999, _settings.pri_ch))
796
        cfg_grp.append(rs)
797
        rs = RadioSetting("rpt_mode", "Radio Mode",
798
                          RadioSettingValueList(RPTMODE_LIST,
799
                                                RPTMODE_LIST[_settings.
800
                                                             rpt_mode]))
801
        cfg_grp.append(rs)
802
        rs = RadioSetting("rpt_set", "Repeater Setting",
803
                          RadioSettingValueList(RPTSET_LIST,
804
                                                RPTSET_LIST[_settings.
805
                                                            rpt_set]))
806
        cfg_grp.append(rs)
807
        rs = RadioSetting("rpt_spk", "Repeater Mode Speaker",
808
                          RadioSettingValueBoolean(_settings.rpt_spk))
809
        cfg_grp.append(rs)
810
        rs = RadioSetting("rpt_ptt", "Repeater PTT",
811
                          RadioSettingValueBoolean(_settings.rpt_ptt))
812
        cfg_grp.append(rs)
813
        rs = RadioSetting("dtmf_tx_time", "DTMF Tx Duration",
814
                          RadioSettingValueList(DTMF_TIMES,
815
                                                DTMF_TIMES[_settings.
816
                                                           dtmf_tx_time]))
817
        cfg_grp.append(rs)
818
        rs = RadioSetting("dtmf_interval", "DTMF Interval",
819
                          RadioSettingValueList(DTMF_TIMES,
820
                                                DTMF_TIMES[_settings.
821
                                                           dtmf_interval]))
822
        cfg_grp.append(rs)
823
        rs = RadioSetting("alert", "Alert Tone",
824
                          RadioSettingValueList(ALERTS_LIST,
825
                                                ALERTS_LIST[_settings.alert]))
826
        cfg_grp.append(rs)
827
        rs = RadioSetting("rpt_tone", "Repeater Tone",
828
                          RadioSettingValueBoolean(_settings.rpt_tone))
829
        cfg_grp.append(rs)
830
        rs = RadioSetting("rpt_hold", "Repeater Hold Time",
831
                          RadioSettingValueList(HOLD_TIMES,
832
                                                HOLD_TIMES[_settings.
833
                                                           rpt_hold]))
834
        cfg_grp.append(rs)
835
        rs = RadioSetting("scan_det", "Scan DET",
836
                          RadioSettingValueBoolean(_settings.scan_det))
837
        cfg_grp.append(rs)
838
        rs = RadioSetting("sc_qt", "SC-QT",
839
                          RadioSettingValueList(SCQT_LIST,
840
                                                SCQT_LIST[_settings.sc_qt]))
841
        cfg_grp.append(rs)
842
        rs = RadioSetting("smuteset", "SubFreq Mute",
843
                          RadioSettingValueList(SMUTESET_LIST,
844
                                                SMUTESET_LIST[_settings.
845
                                                              smuteset]))
846
        cfg_grp.append(rs)
847
        
848
		#
849
        # VFO A Settings
850
        #
851
        rs = RadioSetting("workmode_a", "VFO A Workmode",
852
                          RadioSettingValueList(WORKMODE_LIST, WORKMODE_LIST[_settings.workmode_a]))
853
        vfoa_grp.append(rs)
854
        rs = RadioSetting("work_cha", "VFO A Channel",
855
                          RadioSettingValueInteger(1, 999, _settings.work_cha))
856
        vfoa_grp.append(rs)
857
        rs = RadioSetting("vfoa.rxfreq", "VFO A Rx Frequency",
858
                          RadioSettingValueInteger(
859
                              134000000, 520000000, _vfoa.rxfreq * 10, 5000))
860
        vfoa_grp.append(rs)
861
        rs = RadioSetting("vfoa.txoffset", "VFO A Tx Offset",
862
                          RadioSettingValueInteger(
863
                              0, 520000000, _vfoa.txoffset * 10, 5000))
864
        vfoa_grp.append(rs)
865
        #   u16   rxtone;
866
        #   u16   txtone;
867
        rs = RadioSetting("vfoa.power", "VFO A Power",
868
                          RadioSettingValueList(
869
                              POWER_LIST, POWER_LIST[_vfoa.power]))
870
        vfoa_grp.append(rs)
871
        #         shift_dir:2
872
        rs = RadioSetting("vfoa.iswide", "VFO A NBFM",
873
                          RadioSettingValueList(
874
                              BANDWIDTH_LIST, BANDWIDTH_LIST[_vfoa.iswide]))
875
        vfoa_grp.append(rs)
876
        rs = RadioSetting("vfoa.mute_mode", "VFO A Mute",
877
                          RadioSettingValueList(
878
                              SPMUTE_LIST, SPMUTE_LIST[_vfoa.mute_mode]))
879
        vfoa_grp.append(rs)
880
        rs = RadioSetting("vfoa.step", "VFO A Step (kHz)",
881
                          RadioSettingValueList(
882
                              STEP_LIST, STEP_LIST[_vfoa.step]))
883
        vfoa_grp.append(rs)
884
        rs = RadioSetting("vfoa.squelch", "VFO A Squelch",
885
                          RadioSettingValueList(
886
                              LIST_10, LIST_10[_vfoa.squelch]))
887
        vfoa_grp.append(rs)
888
        rs = RadioSetting("bcl_a", "Busy Channel Lock-out A",
889
                          RadioSettingValueBoolean(_settings.bcl_a))
890
        vfoa_grp.append(rs)
891
        
892
		#
893
        # VFO B Settings
894
        #
895
        rs = RadioSetting("workmode_b", "VFO B Workmode",
896
                          RadioSettingValueList(WORKMODE_LIST, WORKMODE_LIST[_settings.workmode_b]))
897
        vfob_grp.append(rs)
898
        rs = RadioSetting("work_chb", "VFO B Channel",
899
                          RadioSettingValueInteger(1, 999, _settings.work_chb))
900
        vfob_grp.append(rs)
901
        rs = RadioSetting("vfob.rxfreq", "VFO B Rx Frequency",
902
                          RadioSettingValueInteger(
903
                              134000000, 520000000, _vfob.rxfreq * 10, 5000))
904
        vfob_grp.append(rs)
905
        rs = RadioSetting("vfob.txoffset", "VFO B Tx Offset",
906
                          RadioSettingValueInteger(
907
                              0, 520000000, _vfob.txoffset * 10, 5000))
908
        vfob_grp.append(rs)
909
        #   u16   rxtone;
910
        #   u16   txtone;
911
        rs = RadioSetting("vfob.power", "VFO B Power",
912
                          RadioSettingValueList(
913
                              POWER_LIST, POWER_LIST[_vfob.power]))
914
        vfob_grp.append(rs)
915
        #         shift_dir:2
916
        rs = RadioSetting("vfob.iswide", "VFO B NBFM",
917
                          RadioSettingValueList(
918
                              BANDWIDTH_LIST, BANDWIDTH_LIST[_vfob.iswide]))
919
        vfob_grp.append(rs)
920
        rs = RadioSetting("vfob.mute_mode", "VFO B Mute",
921
                          RadioSettingValueList(
922
                              SPMUTE_LIST, SPMUTE_LIST[_vfob.mute_mode]))
923
        vfob_grp.append(rs)
924
        rs = RadioSetting("vfob.step", "VFO B Step (kHz)",
925
                          RadioSettingValueList(
926
                              STEP_LIST, STEP_LIST[_vfob.step]))
927
        vfob_grp.append(rs)
928
        rs = RadioSetting("vfob.squelch", "VFO B Squelch",
929
                          RadioSettingValueList(
930
                              LIST_10, LIST_10[_vfob.squelch]))
931
        vfob_grp.append(rs)
932
        rs = RadioSetting("bcl_b", "Busy Channel Lock-out B",
933
                          RadioSettingValueBoolean(_settings.bcl_b))
934
        vfob_grp.append(rs)
935
        
936
		#
937
        # Key Settings
938
        #
939
        _msg = str(_settings.dispstr).split("\0")[0]
940
        val = RadioSettingValueString(0, 15, _msg)
941
        val.set_mutable(True)
942
        rs = RadioSetting("dispstr", "Display Message", val)
943
        key_grp.append(rs)
944

    
945
        dtmfchars = "0123456789"
946
        _codeobj = _settings.ani_code
947
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x0A])
948
        val = RadioSettingValueString(3, 6, _code, False)
949
        val.set_charset(dtmfchars)
950
        rs = RadioSetting("ani_code", "ANI Code", val)
951
        def apply_ani_id(setting, obj):
952
            value = []
953
            for j in range(0, 6):
954
                try:
955
                    value.append(dtmfchars.index(str(setting.value)[j]))
956
                except IndexError:
957
                    value.append(0xFF)
958
            obj.ani_code = value
959
        rs.set_apply_callback(apply_ani_id, _settings)
960
        key_grp.append(rs)
961

    
962
        rs = RadioSetting("pf1_func", "PF1 Key function",
963
                          RadioSettingValueList(
964
                              PF1KEY_LIST,
965
                              PF1KEY_LIST[_settings.pf1_func]))
966
        key_grp.append(rs)
967
        rs = RadioSetting("pf3_func", "PF3 Key function",
968
                          RadioSettingValueList(
969
                              PF3KEY_LIST,
970
                              PF3KEY_LIST[_settings.pf3_func]))
971
        key_grp.append(rs)
972

    
973
        #
974
        # Limits settings
975
        #
976
        rs = RadioSetting("uhf_limits.rx_start", "UHF RX Lower Limit",
977
                          RadioSettingValueInteger(
978
                              300000000, 520000000,
979
                              self._memobj.uhf_limits.rx_start * 10, 5000))
980
        uhf_lmt_grp.append(rs)
981
        rs = RadioSetting("uhf_limits.rx_stop", "UHF RX Upper Limit",
982
                          RadioSettingValueInteger(
983
                              400000000, 520000000,
984
                              self._memobj.uhf_limits.rx_stop * 10, 5000))
985
        uhf_lmt_grp.append(rs)
986
        rs = RadioSetting("uhf_limits.tx_start", "UHF TX Lower Limit",
987
                          RadioSettingValueInteger(
988
                              400000000, 520000000,
989
                              self._memobj.uhf_limits.tx_start * 10, 5000))
990
        uhf_lmt_grp.append(rs)
991
        rs = RadioSetting("uhf_limits.tx_stop", "UHF TX Upper Limit",
992
                          RadioSettingValueInteger(
993
                              400000000, 520000000,
994
                              self._memobj.uhf_limits.tx_stop * 10, 5000))
995
        uhf_lmt_grp.append(rs)
996
        rs = RadioSetting("vhf_limits.rx_start", "VHF RX Lower Limit",
997
                          RadioSettingValueInteger(
998
                              134000000, 174997500,
999
                              self._memobj.vhf_limits.rx_start * 10, 5000))
1000
        vhf_lmt_grp.append(rs)
1001
        rs = RadioSetting("vhf_limits.rx_stop", "VHF RX Upper Limit",
1002
                          RadioSettingValueInteger(
1003
                              134000000, 174997500,
1004
                              self._memobj.vhf_limits.rx_stop * 10, 5000))
1005
        vhf_lmt_grp.append(rs)
1006
        rs = RadioSetting("vhf_limits.tx_start", "VHF TX Lower Limit",
1007
                          RadioSettingValueInteger(
1008
                              134000000, 174997500,
1009
                              self._memobj.vhf_limits.tx_start * 10, 5000))
1010
        vhf_lmt_grp.append(rs)
1011
        rs = RadioSetting("vhf_limits.tx_stop", "VHF TX Upper Limit",
1012
                          RadioSettingValueInteger(
1013
                              134000000, 174997500,
1014
                              self._memobj.vhf_limits.tx_stop * 10, 5000))
1015
        vhf_lmt_grp.append(rs)
1016

    
1017
        #
1018
        # OEM info
1019
        #
1020
        def _decode(lst):
1021
            _str = ''.join([chr(c) for c in lst
1022
                            if chr(c) in chirp_common.CHARSET_ASCII])
1023
            return _str
1024

    
1025
        def do_nothing(setting, obj):
1026
            return
1027

    
1028
        _str = _decode(self._memobj.oem_info.model)
1029
        val = RadioSettingValueString(0, 15, _str)
1030
        val.set_mutable(False)
1031
        rs = RadioSetting("oem_info.model", "Model", val)
1032
        rs.set_apply_callback(do_nothing, _settings)
1033
        oem_grp.append(rs)
1034
        _str = _decode(self._memobj.oem_info.oem1)
1035
        val = RadioSettingValueString(0, 15, _str)
1036
        val.set_mutable(False)
1037
        rs = RadioSetting("oem_info.oem1", "OEM String 1", val)
1038
        rs.set_apply_callback(do_nothing, _settings)
1039
        oem_grp.append(rs)
1040
        _str = _decode(self._memobj.oem_info.oem2)
1041
        val = RadioSettingValueString(0, 15, _str)
1042
        val.set_mutable(False)
1043
        rs = RadioSetting("oem_info.oem2", "OEM String 2", val)
1044
        rs.set_apply_callback(do_nothing, _settings)
1045
        oem_grp.append(rs)
1046
        _str = _decode(self._memobj.oem_info.version)
1047
        val = RadioSettingValueString(0, 15, _str)
1048
        val.set_mutable(False)
1049
        rs = RadioSetting("oem_info.version", "Software Version", val)
1050
        rs.set_apply_callback(do_nothing, _settings)
1051
        oem_grp.append(rs)
1052
        _str = _decode(self._memobj.oem_info.date)
1053
        val = RadioSettingValueString(0, 15, _str)
1054
        val.set_mutable(False)
1055
        rs = RadioSetting("oem_info.date", "OEM Date", val)
1056
        rs.set_apply_callback(do_nothing, _settings)
1057
        oem_grp.append(rs)
1058

    
1059
        return group
1060

    
1061
    def get_settings(self):
1062
        try:
1063
            return self._get_settings()
1064
        except:
1065
            import traceback
1066
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1067
            return None
1068

    
1069
    def set_settings(self, settings):
1070
        for element in settings:
1071
            if not isinstance(element, RadioSetting):
1072
                self.set_settings(element)
1073
                continue
1074
            else:
1075
                try:
1076
                    if "." in element.get_name():
1077
                        bits = element.get_name().split(".")
1078
                        obj = self._memobj
1079
                        for bit in bits[:-1]:
1080
                            obj = getattr(obj, bit)
1081
                        setting = bits[-1]
1082
                    else:
1083
                        obj = self._memobj.settings
1084
                        setting = element.get_name()
1085

    
1086
                    if element.has_apply_callback():
1087
                        LOG.debug("Using apply callback")
1088
                        element.run_apply_callback()
1089
                    else:
1090
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1091
                        if self._is_freq(element):
1092
                            setattr(obj, setting, int(element.value)/10)
1093
                        else:
1094
                            setattr(obj, setting, element.value)
1095
                except Exception as e:
1096
                    LOG.debug(element.get_name())
1097
                    raise
1098

    
1099
    def _is_freq(self, element):
1100
        return "rxfreq" in element.get_name() \
1101
                or "txoffset" in element.get_name() \
1102
                or "rx_start" in element.get_name() \
1103
                or "rx_stop" in element.get_name() \
1104
                or "tx_start" in element.get_name() \
1105
                or "tx_stop" in element.get_name()
1106

    
(7-7/7)