Project

General

Profile

Bug #10208 » kguv8dplus.py

Prospective Converted KG-UV8DPlus - Dan Smith, 01/02/2023 05:58 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=None):
318
        # build the packet
319
        _length = 0
320
        if payload:
321
            _length = len(payload)
322
        _packet = struct.pack('BBBB', self._record_start, cmd, 0xFF, _length)
323
        if payload:
324
            # calculate and add the checksum to the packet
325
            checksum = bytes([self._checksum(_packet[1:] + payload)])
326
            # add the chars to the packet
327
            _packet += self.encrypt(payload + checksum)
328
        else:
329
            # calculate and add the checksum to the packet
330
            _packet += bytes([self._checksum(_packet[1:])])
331
        LOG.debug("Sent:\n%s" % util.hexprint(_packet))
332
        self.pipe.write(_packet)
333

    
334
    def _read_record(self):
335
        # read 4 chars for the header
336
        _header = self.pipe.read(4)
337
        if len(_header) != 4:
338
            raise errors.RadioError('Radio did not respond')
339
        _length = struct.unpack('xxxB', _header)[0]
340
        _packet = self.pipe.read(_length)
341
        _rcs_xor = _packet[-1]
342
        _packet = self.decrypt(_packet)
343
        _cs = self._checksum(_header[1:])
344
        _cs += self._checksum(_packet)
345
        _cs %= 256
346
        _rcs = self.strxor(self.pipe.read(1)[0], _rcs_xor)[0]
347
        LOG.debug("_cs =%x", _cs)
348
        LOG.debug("_rcs=%x", _rcs)
349
        return (_rcs != _cs, _packet)
350
 
351
    def decrypt(self, data):
352
        result = b''
353
        for i in range(len(data)-1, 0, -1):
354
            result += self.strxor(data[i], data[i - 1])
355
        result += self.strxor(data[0], 0x57)
356
        return result[::-1]
357

    
358
    def encrypt(self, data):
359
        result = self.strxor(0x57, data[0])
360
        for i in range(1, len(data), 1):
361
            result += self.strxor(result[i - 1], data[i])
362
        return result
363

    
364
    def strxor(self, xora, xorb):
365
        return bytes([xora ^ xorb])
366

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

    
390
    def _identify(self):
391
        """Do the identification dance"""
392
        for _i in range(0, 10):
393
            self._write_record(CMD_ID)
394
            _chksum_err, _resp = self._read_record()
395
            LOG.debug("Got:\n%s" % util.hexprint(_resp))
396
            if _chksum_err:
397
                LOG.error("Checksum error: retrying ident...")
398
                time.sleep(0.100)
399
                continue
400
            LOG.debug("Model %s" % util.hexprint(_resp[0:7]))
401
            if _resp[0:7] == self._model:
402
                return
403
            if len(_resp) == 0:
404
                raise Exception("Radio not responding")
405
            else:
406
                raise Exception("Unable to identify radio")
407

    
408
    def _finish(self):
409
        self._write_record(CMD_END)
410

    
411
    def process_mmap(self):
412
        self._memobj = bitwise.parse(_MEM_FORMAT, self._mmap)
413

    
414
    def sync_in(self):
415
        try:
416
            self._mmap = self._download()
417
        except errors.RadioError:
418
            raise
419
        except Exception as e:
420
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
421
        self.process_mmap()
422

    
423
    def sync_out(self):
424
        self._upload()
425

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

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

    
461
    def _upload(self):
462
        """Talk to a wouxun KG-UV8D Plus and do a upload"""
463
        try:
464
            self._identify()
465
            self._do_upload(0, 32768, 64)
466
        except errors.RadioError:
467
            raise
468
        except Exception as e:
469
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
470
        return
471

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

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

    
524
    @classmethod
525
    def get_prompts(cls):
526
        rp = chirp_common.RadioPrompts()
527
        rp.experimental = ("This radio driver is currently under development. "
528
                           "There are no known issues with it, but you should "
529
                           "proceed with caution.")
530
        return rp
531

    
532
    def get_raw_memory(self, number):
533
        return repr(self._memobj.memory[number])
534

    
535
    def _get_tone(self, _mem, mem):
536
        def _get_dcs(val):
537
            code = int("%03o" % (val & 0x07FF))
538
            pol = (val & 0x8000) and "R" or "N"
539
            return code, pol
540

    
541
        tpol = False
542
        if _mem.txtone != 0xFFFF and (_mem.txtone & 0x2800) == 0x2800:
543
            tcode, tpol = _get_dcs(_mem.txtone)
544
            mem.dtcs = tcode
545
            txmode = "DTCS"
546
        elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
547
            mem.rtone = (_mem.txtone & 0x7fff) / 10.0
548
            txmode = "Tone"
549
        else:
550
            txmode = ""
551

    
552
        rpol = False
553
        if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x2800) == 0x2800:
554
            rcode, rpol = _get_dcs(_mem.rxtone)
555
            mem.rx_dtcs = rcode
556
            rxmode = "DTCS"
557
        elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
558
            mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
559
            rxmode = "Tone"
560
        else:
561
            rxmode = ""
562

    
563
        if txmode == "Tone" and not rxmode:
564
            mem.tmode = "Tone"
565
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
566
            mem.tmode = "TSQL"
567
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
568
            mem.tmode = "DTCS"
569
        elif rxmode or txmode:
570
            mem.tmode = "Cross"
571
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
572

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

    
576
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
577
                  (txmode, _mem.txtone, rxmode, _mem.rxtone))
578

    
579
    def get_memory(self, number):
580
        _mem = self._memobj.memory[number]
581
        _nam = self._memobj.names[number]
582

    
583
        mem = chirp_common.Memory()
584
        mem.number = number
585
        _valid = self._memobj.valid[mem.number]
586
        LOG.debug("%d %s", number, _valid == MEM_VALID)
587
        if _valid != MEM_VALID:
588
            mem.empty = True
589
            return mem
590
        else:
591
            mem.empty = False
592

    
593
        mem.freq = int(_mem.rxfreq) * 10
594

    
595
        if _mem.txfreq == 0xFFFFFFFF:
596
            # TX freq not set
597
            mem.duplex = "off"
598
            mem.offset = 0
599
        elif int(_mem.rxfreq) == int(_mem.txfreq):
600
            mem.duplex = ""
601
            mem.offset = 0
602
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
603
            mem.duplex = "split"
604
            mem.offset = int(_mem.txfreq) * 10
605
        else:
606
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
607
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
608

    
609
        for char in _nam.name:
610
            if char != 0:
611
                mem.name += chr(char)
612
        mem.name = mem.name.rstrip()
613

    
614
        self._get_tone(_mem, mem)
615

    
616
        mem.skip = "" if bool(_mem.scan_add) else "S"
617

    
618
        mem.power = self.POWER_LEVELS[_mem.power]
619
        mem.mode = _mem.iswide and "FM" or "NFM"
620
        return mem
621

    
622
    def _set_tone(self, mem, _mem):
623
        def _set_dcs(code, pol):
624
            val = int("%i" % code, 8) + 0x2800
625
            if pol == "R":
626
                val += 0x8000
627
            return val
628

    
629
        rx_mode = tx_mode = None
630
        rxtone = txtone = 0x0000
631

    
632
        if mem.tmode == "Tone":
633
            tx_mode = "Tone"
634
            rx_mode = None
635
            txtone = int(mem.rtone * 10) + 0x8000
636
        elif mem.tmode == "TSQL":
637
            rx_mode = tx_mode = "Tone"
638
            rxtone = txtone = int(mem.ctone * 10) + 0x8000
639
        elif mem.tmode == "DTCS":
640
            tx_mode = rx_mode = "DTCS"
641
            txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
642
            rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
643
        elif mem.tmode == "Cross":
644
            tx_mode, rx_mode = mem.cross_mode.split("->")
645
            if tx_mode == "DTCS":
646
                txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
647
            elif tx_mode == "Tone":
648
                txtone = int(mem.rtone * 10) + 0x8000
649
            if rx_mode == "DTCS":
650
                rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
651
            elif rx_mode == "Tone":
652
                rxtone = int(mem.ctone * 10) + 0x8000
653

    
654
        _mem.rxtone = rxtone
655
        _mem.txtone = txtone
656

    
657
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
658
                  (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
659

    
660
    def set_memory(self, mem):
661
        number = mem.number
662

    
663
        _mem = self._memobj.memory[number]
664
        _nam = self._memobj.names[number]
665

    
666
        if mem.empty:
667
            _mem.set_raw("\x00" * (_mem.size() // 8))
668
            self._memobj.valid[number] = 0
669
            self._memobj.names[number].set_raw("\x00" * (_nam.size() // 8))
670
            return
671

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

    
701
        for i in range(0, len(_nam.name)):
702
            if i < len(mem.name) and mem.name[i]:
703
                _nam.name[i] = ord(mem.name[i])
704
            else:
705
                _nam.name[i] = 0x0
706
        self._memobj.valid[mem.number] = MEM_VALID
707

    
708
    def _get_settings(self):
709
        _settings = self._memobj.settings
710
        _vfoa = self._memobj.vfoa
711
        _vfob = self._memobj.vfob
712
        cfg_grp = RadioSettingGroup("cfg_grp", "Configuration")
713
        vfoa_grp = RadioSettingGroup("vfoa_grp", "VFO A Settings")
714
        vfob_grp = RadioSettingGroup("vfob_grp", "VFO B Settings")
715
        key_grp = RadioSettingGroup("key_grp", "Key Settings")
716
        lmt_grp = RadioSettingGroup("lmt_grp", "Frequency Limits")
717
        uhf_lmt_grp = RadioSettingGroup("uhf_lmt_grp", "UHF")
718
        vhf_lmt_grp = RadioSettingGroup("vhf_lmt_grp", "VHF")
719
        oem_grp = RadioSettingGroup("oem_grp", "OEM Info")
720

    
721
        lmt_grp.append(uhf_lmt_grp);
722
        lmt_grp.append(vhf_lmt_grp);
723
        group = RadioSettings(cfg_grp, vfoa_grp, vfob_grp,
724
                              key_grp, lmt_grp, oem_grp)
725

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

    
954
        dtmfchars = "0123456789"
955
        _codeobj = _settings.ani_code
956
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x0A])
957
        val = RadioSettingValueString(3, 6, _code, False)
958
        val.set_charset(dtmfchars)
959
        rs = RadioSetting("ani_code", "ANI Code", val)
960
        def apply_ani_id(setting, obj):
961
            value = []
962
            for j in range(0, 6):
963
                try:
964
                    value.append(dtmfchars.index(str(setting.value)[j]))
965
                except IndexError:
966
                    value.append(0xFF)
967
            obj.ani_code = value
968
        rs.set_apply_callback(apply_ani_id, _settings)
969
        key_grp.append(rs)
970

    
971
        rs = RadioSetting("pf1_func", "PF1 Key function",
972
                          RadioSettingValueList(
973
                              PF1KEY_LIST,
974
                              PF1KEY_LIST[_settings.pf1_func]))
975
        key_grp.append(rs)
976
        rs = RadioSetting("pf3_func", "PF3 Key function",
977
                          RadioSettingValueList(
978
                              PF3KEY_LIST,
979
                              PF3KEY_LIST[_settings.pf3_func]))
980
        key_grp.append(rs)
981

    
982
        #
983
        # Limits settings
984
        #
985
        rs = RadioSetting("uhf_limits.rx_start", "UHF RX Lower Limit",
986
                          RadioSettingValueInteger(
987
                              400000000, 520000000,
988
                              self._memobj.uhf_limits.rx_start * 10, 5000))
989
        uhf_lmt_grp.append(rs)
990
        rs = RadioSetting("uhf_limits.rx_stop", "UHF RX Upper Limit",
991
                          RadioSettingValueInteger(
992
                              400000000, 520000000,
993
                              self._memobj.uhf_limits.rx_stop * 10, 5000))
994
        uhf_lmt_grp.append(rs)
995
        rs = RadioSetting("uhf_limits.tx_start", "UHF TX Lower Limit",
996
                          RadioSettingValueInteger(
997
                              400000000, 520000000,
998
                              self._memobj.uhf_limits.tx_start * 10, 5000))
999
        uhf_lmt_grp.append(rs)
1000
        rs = RadioSetting("uhf_limits.tx_stop", "UHF TX Upper Limit",
1001
                          RadioSettingValueInteger(
1002
                              400000000, 520000000,
1003
                              self._memobj.uhf_limits.tx_stop * 10, 5000))
1004
        uhf_lmt_grp.append(rs)
1005
        rs = RadioSetting("vhf_limits.rx_start", "VHF RX Lower Limit",
1006
                          RadioSettingValueInteger(
1007
                              134000000, 174997500,
1008
                              self._memobj.vhf_limits.rx_start * 10, 5000))
1009
        vhf_lmt_grp.append(rs)
1010
        rs = RadioSetting("vhf_limits.rx_stop", "VHF RX Upper Limit",
1011
                          RadioSettingValueInteger(
1012
                              134000000, 174997500,
1013
                              self._memobj.vhf_limits.rx_stop * 10, 5000))
1014
        vhf_lmt_grp.append(rs)
1015
        rs = RadioSetting("vhf_limits.tx_start", "VHF TX Lower Limit",
1016
                          RadioSettingValueInteger(
1017
                              134000000, 174997500,
1018
                              self._memobj.vhf_limits.tx_start * 10, 5000))
1019
        vhf_lmt_grp.append(rs)
1020
        rs = RadioSetting("vhf_limits.tx_stop", "VHF TX Upper Limit",
1021
                          RadioSettingValueInteger(
1022
                              134000000, 174997500,
1023
                              self._memobj.vhf_limits.tx_stop * 10, 5000))
1024
        vhf_lmt_grp.append(rs)
1025

    
1026
        #
1027
        # OEM info
1028
        #
1029
        def _decode(lst):
1030
            _str = ''.join([chr(c) for c in lst
1031
                            if chr(c) in chirp_common.CHARSET_ASCII])
1032
            return _str
1033

    
1034
        def do_nothing(setting, obj):
1035
            return
1036

    
1037
        _str = _decode(self._memobj.oem_info.model)
1038
        val = RadioSettingValueString(0, 15, _str)
1039
        val.set_mutable(False)
1040
        rs = RadioSetting("oem_info.model", "Model", val)
1041
        rs.set_apply_callback(do_nothing, _settings)
1042
        oem_grp.append(rs)
1043
        _str = _decode(self._memobj.oem_info.oem1)
1044
        val = RadioSettingValueString(0, 15, _str)
1045
        val.set_mutable(False)
1046
        rs = RadioSetting("oem_info.oem1", "OEM String 1", val)
1047
        rs.set_apply_callback(do_nothing, _settings)
1048
        oem_grp.append(rs)
1049
        _str = _decode(self._memobj.oem_info.oem2)
1050
        val = RadioSettingValueString(0, 15, _str)
1051
        val.set_mutable(False)
1052
        rs = RadioSetting("oem_info.oem2", "OEM String 2", val)
1053
        rs.set_apply_callback(do_nothing, _settings)
1054
        oem_grp.append(rs)
1055
        _str = _decode(self._memobj.oem_info.version)
1056
        val = RadioSettingValueString(0, 15, _str)
1057
        val.set_mutable(False)
1058
        rs = RadioSetting("oem_info.version", "Software Version", val)
1059
        rs.set_apply_callback(do_nothing, _settings)
1060
        oem_grp.append(rs)
1061
        _str = _decode(self._memobj.oem_info.date)
1062
        val = RadioSettingValueString(0, 15, _str)
1063
        val.set_mutable(False)
1064
        rs = RadioSetting("oem_info.date", "OEM Date", val)
1065
        rs.set_apply_callback(do_nothing, _settings)
1066
        oem_grp.append(rs)
1067

    
1068
        return group
1069

    
1070
    def get_settings(self):
1071
        try:
1072
            return self._get_settings()
1073
        except:
1074
            import traceback
1075
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1076
            return None
1077

    
1078
    def set_settings(self, settings):
1079
        for element in settings:
1080
            if not isinstance(element, RadioSetting):
1081
                self.set_settings(element)
1082
                continue
1083
            else:
1084
                try:
1085
                    if "." in element.get_name():
1086
                        bits = element.get_name().split(".")
1087
                        obj = self._memobj
1088
                        for bit in bits[:-1]:
1089
                            obj = getattr(obj, bit)
1090
                        setting = bits[-1]
1091
                    else:
1092
                        obj = self._memobj.settings
1093
                        setting = element.get_name()
1094

    
1095
                    if element.has_apply_callback():
1096
                        LOG.debug("Using apply callback")
1097
                        element.run_apply_callback()
1098
                    else:
1099
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1100
                        if self._is_freq(element):
1101
                            setattr(obj, setting, int(element.value)/10)
1102
                        else:
1103
                            setattr(obj, setting, element.value)
1104
                except Exception as e:
1105
                    LOG.debug(element.get_name())
1106
                    raise
1107

    
1108
    def _is_freq(self, element):
1109
        return "rxfreq" in element.get_name() \
1110
                or "txoffset" in element.get_name() \
1111
                or "rx_start" in element.get_name() \
1112
                or "rx_stop" in element.get_name() \
1113
                or "tx_start" in element.get_name() \
1114
                or "tx_stop" in element.get_name()
1115

    
(5-5/9)