Project

General

Profile

New Model #5481 » kguv8dplus.py

This dev drivers is a merge of the KG-UV8D Plus & KG-UV8E, please test it and report back. - Pavel Milanes, 01/08/2018 08:01 AM

 
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
# Support for the KG-UV8E added by Pavel Milanes (CO7WT) <pavelmc@gmail.com>
14
# in January 2018 + refactoring of the library.
15
#
16
# This program is free software: you can redistribute it and/or modify
17
# it under the terms of the GNU General Public License as published by
18
# the Free Software Foundation, either version 3 of the License, or
19
# (at your option) any later version.
20
#
21
# This program is distributed in the hope that it will be useful,
22
# but WITHOUT ANY WARRANTY; without even the implied warranty of
23
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24
# GNU General Public License for more details.
25
#
26
# You should have received a copy of the GNU General Public License
27
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
28

    
29
"""Module for Wouxun KG-UV radios with cryptography in the serial comms"""
30

    
31
import time
32
import os
33
import logging
34
from chirp import util, chirp_common, bitwise, memmap, errors, directory
35
from chirp.settings import RadioSetting, RadioSettingGroup, \
36
    RadioSettingValueBoolean, RadioSettingValueList, \
37
    RadioSettingValueInteger, RadioSettingValueString, \
38
    RadioSettings
39

    
40
LOG = logging.getLogger(__name__)
41

    
42
CMD_ID = 128
43
CMD_END = 129
44
CMD_RD = 130
45
CMD_WR = 131
46

    
47
MEM_VALID = 158
48

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

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

    
84
# Support for the folowing Wouxun radios
85
#  * KG-UV8D Plus
86
#  * KG-UV8E
87
#  * KG-UV8T (untested)
88
# Serial coms are at 19200 baud
89
# The data is passed in variable length records
90
# Record structure:
91
#  Offset   Usage
92
#    0      start of record (\x7a)
93
#    1      Command (\x80 Identify \x81 End/Reboot \x82 Read \x83 Write)
94
#    2      direction (\xff PC-> Radio, \x00 Radio -> PC)
95
#    3      length of payload (excluding header/checksum) (n)
96
#    4      payload (n bytes)
97
#    4+n+1  checksum - byte sum (% 256) of bytes 1 -> 4+n
98
#
99
# Memory Read Records:
100
# the payload is 3 bytes, first 2 are offset (big endian),
101
# 3rd is number of bytes to read
102
# Memory Write Records:
103
# the maximum payload size (from the Wouxun software) seems to be 66 bytes
104
#  (2 bytes location + 64 bytes data).
105

    
106
_MEM_FORMAT = """
107
    #seekto 0x0030;
108
    struct {
109
        u32    rx_start;
110
        u32    rx_stop;
111
        u32    tx_start;
112
        u32    tx_stop;
113
    } vhf1_limits;
114

    
115
    #seekto 0x0044;
116
    struct {
117
        u32    rx_start;
118
        u32    rx_stop;
119
        u32    tx_start;
120
        u32    tx_stop;
121
    } uhf_limits;
122

    
123
    #seekto 0x0054;
124
    struct {
125
        u32    rx_start;
126
        u32    rx_stop;
127
        u32    tx_start;
128
        u32    tx_stop;
129
    } vhf_limits;
130

    
131
    #seekto 0x0400;
132
    struct {
133
        u8     oem1[8];
134
        u8     unknown[2];
135
        u8     unknown2[10];
136
        u8     unknown3[10];
137
        u8     unknown4[8];
138
        u8     model[10];
139
        u8     version[6];
140
        u8     date[8];
141
        u8     unknown5[1];
142
        u8     oem2[8];
143
    } oem_info;
144

    
145
    #seekto 0x0480;
146
    struct {
147
        u16    lower;
148
        u16    upper;
149
    } scan_groups[10];
150

    
151
    #seekto 0x0500;
152
    struct {
153
        u8    call_code[6];
154
    } call_groups[20];
155

    
156
    #seekto 0x0580;
157
    struct {
158
        char    call_name[6];
159
    } call_group_name[20];
160

    
161
    #seekto 0x0800;
162
    struct {
163
        u8      ponmsg;
164
        char    dispstr[15];
165
        u8 x0810;
166
        u8 x0811;
167
        u8 x0812;
168
        u8 x0813;
169
        u8 x0814;
170
        u8      voice;
171
        u8      timeout;
172
        u8      toalarm;
173
        u8      channel_menu;
174
        u8      power_save;
175
        u8      autolock;
176
        u8      keylock;
177
        u8      beep;
178
        u8      stopwatch;
179
        u8      vox;
180
        u8      scan_rev;
181
        u8      backlight;
182
        u8      roger_beep;
183
        u8 x0822[6];
184
        u8 x0823[6];
185
        u16     pri_ch;
186
        u8      ani_sw;
187
        u8      ptt_delay;
188
        u8      ani_code[6];
189
        u8      dtmf_st;
190
        u8      bcl_a;
191
        u8      bcl_b;
192
        u8      ptt_id;
193
        u8      prich_sw;
194
        u8      rpt_set;
195
        u8      rpt_spk;
196
        u8      rpt_ptt;
197
        u8      alert;
198
        u8      pf1_func;
199
        u8      pf3_func;
200
        u8 x0843;
201
        u8      workmode_a;
202
        u8      workmode_b;
203
        u8      dtmf_tx_time;
204
        u8      dtmf_interval;
205
        u8      main_ab;
206
        u16     work_cha;
207
        u16     work_chb;
208
        u8 x084d;
209
        u8 x084e;
210
        u8 x084f;
211
        u8 x0850;
212
        u8 x0851;
213
        u8 x0852;
214
        u8 x0853;
215
        u8 x0854;
216
        u8      rpt_mode;
217
        u8      language;
218
        u8 x0857;
219
        u8 x0858;
220
        u8 x0859;
221
        u8 x085a;
222
        u8 x085b;
223
        u8 x085c;
224
        u8 x085d;
225
        u8 x085e;
226
        u8      single_display;
227
        u8      ring_time;
228
        u8      scg_a;
229
        u8      scg_b;
230
        u8 x0863;
231
        u8      rpt_tone;
232
        u8      rpt_hold;
233
        u8      scan_det;
234
        u8      sc_qt;
235
        u8 x0868;
236
        u8      smuteset;
237
        u8      callcode;
238
    } settings;
239

    
240
    #seekto 0x0880;
241
    struct {
242
        u32     rxfreq;
243
        u32     txoffset;
244
        u16     rxtone;
245
        u16     txtone;
246
        u8      scrambler:4,
247
                unknown1:2,
248
                power:1,
249
                unknown2:1;
250
        u8      unknown3:1,
251
                shift_dir:2
252
                unknown4:1,
253
                compander:1,
254
                mute_mode:2,
255
                iswide:1;
256
        u8      step;
257
        u8      squelch;
258
      } vfoa;
259

    
260
    #seekto 0x08c0;
261
    struct {
262
        u32     rxfreq;
263
        u32     txoffset;
264
        u16     rxtone;
265
        u16     txtone;
266
        u8      scrambler:4,
267
                unknown1:2,
268
                power:1,
269
                unknown2:1;
270
        u8      unknown3:1,
271
                shift_dir:2
272
                unknown4:1,
273
                compander:1,
274
                mute_mode:2,
275
                iswide:1;
276
        u8      step;
277
        u8      squelch;
278
    } vfob;
279

    
280
    #seekto 0x0900;
281
    struct {
282
        u32     rxfreq;
283
        u32     txfreq;
284
        u16     rxtone;
285
        u16     txtone;
286
        u8      scrambler:4,
287
                unknown1:2,
288
                power:1,
289
                unknown2:1;
290
        u8      unknown3:2,
291
                scan_add:1,
292
                unknown4:1,
293
                compander:1,
294
                mute_mode:2,
295
                iswide:1;
296
        u16     padding;
297
    } memory[1000];
298

    
299
    #seekto 0x4780;
300
    struct {
301
        u8    name[8];
302
                u8    unknown[4];
303
    } names[1000];
304

    
305
    #seekto 0x7670;
306
    u8          valid[1000];
307
    """
308

    
309

    
310
class KGUV8crypt(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
311
    """Base class for Wouxun KG-UV radios with crypt serial communications"""
312
    VENDOR = "Wouxun"
313
    MODEL = ""
314
    _model = ""
315
    _file_ident = ""
316
    BAUD_RATE = 19200
317
    POWER_LEVELS = [chirp_common.PowerLevel("L", watts=1),
318
                    chirp_common.PowerLevel("H", watts=5)]
319
    _vhf_range = (134000000, 175000000) # supports 2m
320
    _uhf_range = (400000000, 520000000) # supports 70cm
321
    _mmap = ""
322
    _START_CMD = ''
323

    
324
    def _checksum(self, data):
325
        cs = 0
326
        for byte in data:
327
            cs += ord(byte)
328
        return chr(cs % 256)
329

    
330
    def _write_record(self, cmd, payload = None):
331
        # build the packet
332
        _header = self._START_CMD + chr(cmd) + '\xff'
333
        _length = 0
334
        if payload:
335
            _length = len(payload)
336
        # update the length field
337
        _header += chr(_length)
338
        if payload:
339
            # calculate checksum then add it with the payload to the packet and encrypt
340
            crc = self._checksum(_header[1:] + payload)
341
            payload += crc
342
            _header += self.encrypt(payload)
343
        else:
344
            # calculate and add encrypted checksum to the packet
345
            crc = self._checksum(_header[1:])
346
            _header += self.strxor(crc, '\x57')
347
        LOG.debug("Sent:\n%s" % util.hexprint(_header))
348
        self.pipe.write(_header)
349

    
350
    def _read_record(self):
351
        # read 4 chars for the header
352
        _header = self.pipe.read(4)
353
        if len(_header) != 4:
354
            raise errors.RadioError('Radio did not respond')
355
        _length = ord(_header[3])
356
        _packet = self.pipe.read(_length)
357
        _rcs_xor = _packet[-1]
358
        _packet = self.decrypt(_packet)
359
        _cs = ord(self._checksum(_header[1:] + _packet))
360
        # read the checksum and decrypt it
361
        _rcs = ord(self.strxor(self.pipe.read(1), _rcs_xor))
362
        LOG.debug("_cs =%x", _cs)
363
        LOG.debug("_rcs=%x", _rcs)
364
        return (_rcs != _cs, _packet)
365

    
366
    def decrypt(self, data):
367
        result = ''
368
        for i in range(len(data)-1, 0, -1):
369
            result += self.strxor(data[i], data[i - 1])
370
        result += self.strxor(data[0], '\x57')
371
        return result[::-1]
372

    
373
    def encrypt(self, data):
374
        result = self.strxor('\x57', data[0])
375
        for i in range(1, len(data), 1):
376
            result += self.strxor(result[i - 1], data[i])
377
        return result
378

    
379
    def strxor (self, xora, xorb):
380
        return chr(ord(xora) ^ ord(xorb))
381

    
382
    @classmethod
383
    def match_model(cls, filedata, filename):
384
        return cls._file_ident in 'kg' + filedata[0x0426:0x0430].\
385
            replace('(', '').replace(')', '').lower()
386

    
387
    # Identify the radio
388
    #
389
    # A Gotcha: the first identify packet returns a bad checksum, subsequent
390
    # attempts return the correct checksum... (well it does on my radio!)
391
    #
392
    # The ID record returned by the radio also includes the current frequency
393
    # range as 4 bytes big-endian in 10Hz increments
394
    #
395
    # Offset (All models)
396
    #  0:10     Model, zero padded, match self._model
397
    #
398
    # For the KG-UV8D Plus
399
    # ===================================================
400
    #  11:14    UHF rx lower limit (in units of 10Hz)
401
    #  15:18    UHF rx upper limit
402
    #  19:22    UHF tx lower limit
403
    #  23:26    UHF tx upper limit
404
    #  27:30    VHF rx lower limit
405
    #  31:34    VHF rx upper limit
406
    #  35:38    VHF tx lower limit
407
    #  39:42    VHF tx upper limit
408
    #
409
    # For the KG-UV8E this data seems like different positions
410

    
411
    def _identify(self):
412
        """Do the identification dance"""
413
        for _i in range(0, 10):
414
            self._write_record(CMD_ID)
415
            _chksum_err, _resp = self._read_record()
416
            LOG.debug("Got:\n%s" % util.hexprint(_resp))
417
            if _chksum_err:
418
                LOG.error("Checksum error: retrying ident...")
419
                time.sleep(0.100)
420
                continue
421
            read_model = _resp[0:len(self._model)]
422
            LOG.debug("Model %s" % util.hexprint(read_model))
423
            if read_model == self._model:
424
                return
425
            if len(_resp) == 0:
426
                raise Exception("Radio not responding")
427
            else:
428
                raise Exception("Unable to identify radio")
429

    
430
    def _finish(self):
431
        self._write_record(CMD_END)
432

    
433
    def process_mmap(self):
434
        self._memobj = bitwise.parse(_MEM_FORMAT, self._mmap)
435

    
436
    def sync_in(self):
437
        try:
438
            self._mmap = self._download()
439
        except errors.RadioError:
440
            raise
441
        except Exception, e:
442
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
443
        self.process_mmap()
444

    
445
    def sync_out(self):
446
        self._upload()
447

    
448
    # TODO: Load all memory.
449
    # It would be smarter to only load the active areas and none of
450
    # the padding/unused areas. Padding still need to be investigated.
451
    def _download(self):
452
        """Talk to a Wouxun KG-UV crypt radios and do a download"""
453
        try:
454
            self._identify()
455
            return self._do_download(0, 32768, 64)
456
        except errors.RadioError:
457
            raise
458
        except Exception, e:
459
            LOG.exception('Unknown error during download process')
460
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
461

    
462
    def _do_download(self, start, end, blocksize):
463
        # allocate & fill memory
464
        image = ""
465
        for i in range(start, end, blocksize):
466
            req = chr(i / 256) + chr(i % 256) + chr(blocksize)
467
            self._write_record(CMD_RD, req)
468
            cs_error, resp = self._read_record()
469
            if cs_error:
470
                LOG.debug(util.hexprint(resp))
471
                raise Exception("Checksum error on read")
472
            LOG.debug("Got:\n%s" % util.hexprint(resp))
473
            image += resp[2:]
474
            if self.status_fn:
475
                status = chirp_common.Status()
476
                status.cur = i
477
                status.max = end
478
                status.msg = "Cloning from radio"
479
                self.status_fn(status)
480
        self._finish()
481
        return memmap.MemoryMap(''.join(image))
482

    
483
    def _upload(self):
484
        """Talk to a Wouxun KG-UV crypt radios and do an upload"""
485
        try:
486
            self._identify()
487
            self._do_upload(0, 32768, 64)
488
        except errors.RadioError:
489
            raise
490
        except Exception, e:
491
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
492
        return
493

    
494
    def _do_upload(self, start, end, blocksize):
495
        ptr = start
496
        for i in range(start, end, blocksize):
497
            req = chr(i / 256) + chr(i % 256)
498
            chunk = self.get_mmap()[ptr:ptr + blocksize]
499
            self._write_record(CMD_WR, req + chunk)
500
            LOG.debug(util.hexprint(req + chunk))
501
            cserr, ack = self._read_record()
502
            LOG.debug(util.hexprint(ack))
503
            j = ord(ack[0]) * 256 + ord(ack[1])
504
            if cserr or j != ptr:
505
                raise Exception("Radio did not ack block %i" % ptr)
506
            ptr += blocksize
507
            if self.status_fn:
508
                status = chirp_common.Status()
509
                status.cur = i
510
                status.max = end
511
                status.msg = "Cloning to radio"
512
                self.status_fn(status)
513
        self._finish()
514

    
515
    def get_features(self):
516
        rf = chirp_common.RadioFeatures()
517
        rf.has_settings = True
518
        rf.has_ctone = True
519
        rf.has_rx_dtcs = True
520
        rf.has_cross = True
521
        rf.has_tuning_step = False
522
        rf.has_bank = False
523
        rf.can_odd_split = True
524
        rf.valid_skips = ["", "S"]
525
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
526
        rf.valid_cross_modes = [
527
            "Tone->Tone",
528
            "Tone->DTCS",
529
            "DTCS->Tone",
530
            "DTCS->",
531
            "->Tone",
532
            "->DTCS",
533
            "DTCS->DTCS",
534
        ]
535
        rf.valid_modes = ["FM", "NFM"]
536
        rf.valid_power_levels = self.POWER_LEVELS
537
        rf.valid_name_length = 8
538
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
539
        rf.valid_bands = [self._vhf_range, self._uhf_range]
540
        rf.valid_characters = chirp_common.CHARSET_ASCII
541
        rf.memory_bounds = (1, 999)  # 999 memories
542

    
543
        # KG-UV8E 1.25m band
544
        if (self.MODEL == "KG-UV8E"):
545
            rf.valid_bands.append(self._vhf1_range)
546

    
547
        return rf
548

    
549
    @classmethod
550
    def get_prompts(cls):
551
        rp = chirp_common.RadioPrompts()
552
        rp.experimental = ("This radio driver is currently under development. "
553
                           "There are no known issues with it, but you should "
554
                           "proceed with caution.")
555
        return rp
556

    
557
    def get_raw_memory(self, number):
558
        return repr(self._memobj.memory[number])
559

    
560
    def _get_tone(self, _mem, mem):
561
        def _get_dcs(val):
562
            code = int("%03o" % (val & 0x07FF))
563
            pol = (val & 0x8000) and "R" or "N"
564
            return code, pol
565

    
566
        tpol = False
567
        if _mem.txtone != 0xFFFF and (_mem.txtone & 0x2800) == 0x2800:
568
            tcode, tpol = _get_dcs(_mem.txtone)
569
            mem.dtcs = tcode
570
            txmode = "DTCS"
571
        elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
572
            mem.rtone = (_mem.txtone & 0x7fff) / 10.0
573
            txmode = "Tone"
574
        else:
575
            txmode = ""
576

    
577
        rpol = False
578
        if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x2800) == 0x2800:
579
            rcode, rpol = _get_dcs(_mem.rxtone)
580
            mem.rx_dtcs = rcode
581
            rxmode = "DTCS"
582
        elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
583
            mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
584
            rxmode = "Tone"
585
        else:
586
            rxmode = ""
587

    
588
        if txmode == "Tone" and not rxmode:
589
            mem.tmode = "Tone"
590
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
591
            mem.tmode = "TSQL"
592
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
593
            mem.tmode = "DTCS"
594
        elif rxmode or txmode:
595
            mem.tmode = "Cross"
596
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
597

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

    
601
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
602
                  (txmode, _mem.txtone, rxmode, _mem.rxtone))
603

    
604
    def get_memory(self, number):
605
        _mem = self._memobj.memory[number]
606
        _nam = self._memobj.names[number]
607

    
608
        mem = chirp_common.Memory()
609
        mem.number = number
610
        _valid = self._memobj.valid[mem.number]
611
        LOG.debug("CH %d %s", number, _valid == MEM_VALID)
612
        if _valid != MEM_VALID:
613
            mem.empty = True
614
            return mem
615
        else:
616
            mem.empty = False
617

    
618
        mem.freq = int(_mem.rxfreq) * 10
619

    
620
        if _mem.txfreq == 0xFFFFFFFF:
621
            # TX freq not set
622
            mem.duplex = "off"
623
            mem.offset = 0
624
        elif int(_mem.rxfreq) == int(_mem.txfreq):
625
            mem.duplex = ""
626
            mem.offset = 0
627
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
628
            mem.duplex = "split"
629
            mem.offset = int(_mem.txfreq) * 10
630
        else:
631
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
632
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
633

    
634
        for char in _nam.name:
635
            if char != 0:
636
                mem.name += chr(char)
637
        mem.name = mem.name.rstrip()
638

    
639
        self._get_tone(_mem, mem)
640

    
641
        mem.skip = "" if bool(_mem.scan_add) else "S"
642

    
643
        mem.power = self.POWER_LEVELS[_mem.power]
644
        mem.mode = _mem.iswide and "FM" or "NFM"
645
        return mem
646

    
647
    def _set_tone(self, mem, _mem):
648
        def _set_dcs(code, pol):
649
            val = int("%i" % code, 8) + 0x2800
650
            if pol == "R":
651
                val += 0x8000
652
            return val
653

    
654
        rx_mode = tx_mode = None
655
        rxtone = txtone = 0x0000
656

    
657
        if mem.tmode == "Tone":
658
            tx_mode = "Tone"
659
            rx_mode = None
660
            txtone = int(mem.rtone * 10) + 0x8000
661
        elif mem.tmode == "TSQL":
662
            rx_mode = tx_mode = "Tone"
663
            rxtone = txtone = int(mem.ctone * 10) + 0x8000
664
        elif mem.tmode == "DTCS":
665
            tx_mode = rx_mode = "DTCS"
666
            txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
667
            rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
668
        elif mem.tmode == "Cross":
669
            tx_mode, rx_mode = mem.cross_mode.split("->")
670
            if tx_mode == "DTCS":
671
                txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
672
            elif tx_mode == "Tone":
673
                txtone = int(mem.rtone * 10) + 0x8000
674
            if rx_mode == "DTCS":
675
                rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
676
            elif rx_mode == "Tone":
677
                rxtone = int(mem.ctone * 10) + 0x8000
678

    
679
        _mem.rxtone = rxtone
680
        _mem.txtone = txtone
681

    
682
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
683
                  (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
684

    
685
    def set_memory(self, mem):
686
        number = mem.number
687

    
688
        _mem = self._memobj.memory[number]
689
        _nam = self._memobj.names[number]
690

    
691
        if mem.empty:
692
            _mem.set_raw("\x00" * (_mem.size() / 8))
693
            self._memobj.valid[number] = 0
694
            self._memobj.names[number].set_raw("\x00" * (_nam.size() / 8))
695
            return
696

    
697
        _mem.rxfreq = int(mem.freq / 10)
698
        if mem.duplex == "off":
699
            _mem.txfreq = 0xFFFFFFFF
700
        elif mem.duplex == "split":
701
            _mem.txfreq = int(mem.offset / 10)
702
        elif mem.duplex == "off":
703
            for i in range(0, 4):
704
                _mem.txfreq[i].set_raw("\xFF")
705
        elif mem.duplex == "+":
706
            _mem.txfreq = int(mem.freq / 10) + int(mem.offset / 10)
707
        elif mem.duplex == "-":
708
            _mem.txfreq = int(mem.freq / 10) - int(mem.offset / 10)
709
        else:
710
            _mem.txfreq = int(mem.freq / 10)
711
        _mem.scan_add = int(mem.skip != "S")
712
        _mem.iswide = int(mem.mode == "FM")
713
        # set the tone
714
        self._set_tone(mem, _mem)
715
        # set the scrambler and compander to off by default
716
        _mem.scrambler = 0
717
        _mem.compander = 0
718
        # set the power
719
        if mem.power:
720
            _mem.power = self.POWER_LEVELS.index(mem.power)
721
        else:
722
            _mem.power = True
723
        # set to mute mode to QT (not QT+DTMF or QT*DTMF) by default
724
        _mem.mute_mode = 0
725

    
726
        for i in range(0, len(_nam.name)):
727
            if i < len(mem.name) and mem.name[i]:
728
                _nam.name[i] = ord(mem.name[i])
729
            else:
730
                _nam.name[i] = 0x0
731
        self._memobj.valid[mem.number] = MEM_VALID
732

    
733
    def _get_settings(self):
734
        _settings = self._memobj.settings
735
        _vfoa = self._memobj.vfoa
736
        _vfob = self._memobj.vfob
737
        cfg_grp = RadioSettingGroup("cfg_grp", "Configuration")
738
        vfoa_grp = RadioSettingGroup("vfoa_grp", "VFO A Settings")
739
        vfob_grp = RadioSettingGroup("vfob_grp", "VFO B Settings")
740
        key_grp = RadioSettingGroup("key_grp", "Key Settings")
741
        oem_grp = RadioSettingGroup("oem_grp", "OEM Info")
742
        lmt_grp = RadioSettingGroup("lmt_grp", "Frequency Limits")
743
        uhf_lmt_grp = RadioSettingGroup("uhf_lmt_grp", "UHF")
744
        vhf_lmt_grp = RadioSettingGroup("vhf_lmt_grp", "VHF")
745

    
746
        lmt_grp.append(uhf_lmt_grp);
747

    
748
        # KG-UV8E 1.25m band
749
        if (self.MODEL == "KG-UV8E"):
750
            vhf1_lmt_grp = RadioSettingGroup("vhf1_lmt_grp", "VHF1")
751
            lmt_grp.append(vhf1_lmt_grp);
752

    
753
        lmt_grp.append(vhf_lmt_grp);
754

    
755
        group = RadioSettings(cfg_grp, vfoa_grp, vfob_grp,
756
                              key_grp, lmt_grp, oem_grp)
757

    
758
        #
759
        # Configuration Settings
760
        #
761
        rs = RadioSetting("channel_menu", "Menu available in channel mode",
762
                          RadioSettingValueBoolean(_settings.channel_menu))
763
        cfg_grp.append(rs)
764
        rs = RadioSetting("ponmsg", "Poweron message",
765
                          RadioSettingValueList(
766
                              PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
767
        cfg_grp.append(rs)
768
        rs = RadioSetting("voice", "Voice Guide",
769
                          RadioSettingValueBoolean(_settings.voice))
770
        cfg_grp.append(rs)
771
        rs = RadioSetting("language", "Language",
772
                          RadioSettingValueList(LANGUAGE_LIST,
773
                                                LANGUAGE_LIST[_settings.
774
                                                              language]))
775
        cfg_grp.append(rs)
776
        rs = RadioSetting("timeout", "Timeout Timer",
777
                          RadioSettingValueList(
778
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
779
        cfg_grp.append(rs)
780
        rs = RadioSetting("toalarm", "Timeout Alarm",
781
                          RadioSettingValueInteger(0, 10, _settings.toalarm))
782
        cfg_grp.append(rs)
783
        rs = RadioSetting("roger_beep", "Roger Beep",
784
                          RadioSettingValueList(ROGER_LIST,
785
                                                ROGER_LIST[_settings.roger_beep]))
786
        cfg_grp.append(rs)
787
        rs = RadioSetting("power_save", "Power save",
788
                          RadioSettingValueBoolean(_settings.power_save))
789
        cfg_grp.append(rs)
790
        rs = RadioSetting("autolock", "Autolock",
791
                          RadioSettingValueBoolean(_settings.autolock))
792
        cfg_grp.append(rs)
793
        rs = RadioSetting("keylock", "Keypad Lock",
794
                          RadioSettingValueBoolean(_settings.keylock))
795
        cfg_grp.append(rs)
796
        rs = RadioSetting("beep", "Keypad Beep",
797
                          RadioSettingValueBoolean(_settings.beep))
798
        cfg_grp.append(rs)
799
        rs = RadioSetting("stopwatch", "Stopwatch",
800
                          RadioSettingValueBoolean(_settings.stopwatch))
801
        cfg_grp.append(rs)
802
        rs = RadioSetting("backlight", "Backlight",
803
                          RadioSettingValueList(BACKLIGHT_LIST,
804
                                                BACKLIGHT_LIST[_settings.
805
                                                               backlight]))
806
        cfg_grp.append(rs)
807
        rs = RadioSetting("dtmf_st", "DTMF Sidetone",
808
                          RadioSettingValueList(DTMFST_LIST,
809
                                                DTMFST_LIST[_settings.
810
                                                            dtmf_st]))
811
        cfg_grp.append(rs)
812
        rs = RadioSetting("ani_sw", "ANI-ID Switch",
813
                          RadioSettingValueBoolean(_settings.ani_sw))
814
        cfg_grp.append(rs)
815
        rs = RadioSetting("ptt_id", "PTT-ID Delay",
816
                          RadioSettingValueList(PTTID_LIST,
817
                                                PTTID_LIST[_settings.ptt_id]))
818
        cfg_grp.append(rs)
819
        rs = RadioSetting("ring_time", "Ring Time",
820
                          RadioSettingValueList(LIST_10,
821
                                                LIST_10[_settings.ring_time]))
822
        cfg_grp.append(rs)
823
        rs = RadioSetting("scan_rev", "Scan Mode",
824
                          RadioSettingValueList(SCANMODE_LIST,
825
                                                SCANMODE_LIST[_settings.
826
                                                              scan_rev]))
827
        cfg_grp.append(rs)
828
        rs = RadioSetting("vox", "VOX",
829
                          RadioSettingValueList(LIST_10,
830
                                                LIST_10[_settings.vox]))
831
        cfg_grp.append(rs)
832
        rs = RadioSetting("prich_sw", "Priority Channel Switch",
833
                          RadioSettingValueBoolean(_settings.prich_sw))
834
        cfg_grp.append(rs)
835
        rs = RadioSetting("pri_ch", "Priority Channel",
836
                          RadioSettingValueInteger(1, 999, _settings.pri_ch))
837
        cfg_grp.append(rs)
838
        rs = RadioSetting("rpt_mode", "Radio Mode",
839
                          RadioSettingValueList(RPTMODE_LIST,
840
                                                RPTMODE_LIST[_settings.
841
                                                             rpt_mode]))
842
        cfg_grp.append(rs)
843
        rs = RadioSetting("rpt_set", "Repeater Setting",
844
                          RadioSettingValueList(RPTSET_LIST,
845
                                                RPTSET_LIST[_settings.
846
                                                            rpt_set]))
847
        cfg_grp.append(rs)
848
        rs = RadioSetting("rpt_spk", "Repeater Mode Speaker",
849
                          RadioSettingValueBoolean(_settings.rpt_spk))
850
        cfg_grp.append(rs)
851
        rs = RadioSetting("rpt_ptt", "Repeater PTT",
852
                          RadioSettingValueBoolean(_settings.rpt_ptt))
853
        cfg_grp.append(rs)
854
        rs = RadioSetting("dtmf_tx_time", "DTMF Tx Duration",
855
                          RadioSettingValueList(DTMF_TIMES,
856
                                                DTMF_TIMES[_settings.
857
                                                           dtmf_tx_time]))
858
        cfg_grp.append(rs)
859
        rs = RadioSetting("dtmf_interval", "DTMF Interval",
860
                          RadioSettingValueList(DTMF_TIMES,
861
                                                DTMF_TIMES[_settings.
862
                                                           dtmf_interval]))
863
        cfg_grp.append(rs)
864
        rs = RadioSetting("alert", "Alert Tone",
865
                          RadioSettingValueList(ALERTS_LIST,
866
                                                ALERTS_LIST[_settings.alert]))
867
        cfg_grp.append(rs)
868
        rs = RadioSetting("rpt_tone", "Repeater Tone",
869
                          RadioSettingValueBoolean(_settings.rpt_tone))
870
        cfg_grp.append(rs)
871
        rs = RadioSetting("rpt_hold", "Repeater Hold Time",
872
                          RadioSettingValueList(HOLD_TIMES,
873
                                                HOLD_TIMES[_settings.
874
                                                           rpt_hold]))
875
        cfg_grp.append(rs)
876
        rs = RadioSetting("scan_det", "Scan DET",
877
                          RadioSettingValueBoolean(_settings.scan_det))
878
        cfg_grp.append(rs)
879
        rs = RadioSetting("sc_qt", "SC-QT",
880
                          RadioSettingValueList(SCQT_LIST,
881
                                                SCQT_LIST[_settings.sc_qt]))
882
        cfg_grp.append(rs)
883
        rs = RadioSetting("smuteset", "SubFreq Mute",
884
                          RadioSettingValueList(SMUTESET_LIST,
885
                                                SMUTESET_LIST[_settings.
886
                                                              smuteset]))
887
        cfg_grp.append(rs)
888

    
889
                #
890
        # VFO A Settings
891
        #
892
        rs = RadioSetting("workmode_a", "VFO A Workmode",
893
                          RadioSettingValueList(WORKMODE_LIST,
894
                            WORKMODE_LIST[_settings.workmode_a]))
895
        vfoa_grp.append(rs)
896
        rs = RadioSetting("work_cha", "VFO A Channel",
897
                          RadioSettingValueInteger(1, 999, _settings.work_cha))
898
        vfoa_grp.append(rs)
899
        rs = RadioSetting("vfoa.rxfreq", "VFO A Rx Frequency",
900
                          RadioSettingValueInteger(
901
                              self._vhf_range[0], self._uhf_range[1],
902
                                _vfoa.rxfreq * 10, 5000))
903
        vfoa_grp.append(rs)
904
        rs = RadioSetting("vfoa.txoffset", "VFO A Tx Offset",
905
                          RadioSettingValueInteger(
906
                              0,self._uhf_range[1], _vfoa.txoffset * 10, 5000))
907
        vfoa_grp.append(rs)
908
        #   u16   rxtone;
909
        #   u16   txtone;
910
        rs = RadioSetting("vfoa.power", "VFO A Power",
911
                          RadioSettingValueList(
912
                              POWER_LIST, POWER_LIST[_vfoa.power]))
913
        vfoa_grp.append(rs)
914
        #         shift_dir:2
915
        rs = RadioSetting("vfoa.iswide", "VFO A NBFM",
916
                          RadioSettingValueList(
917
                              BANDWIDTH_LIST, BANDWIDTH_LIST[_vfoa.iswide]))
918
        vfoa_grp.append(rs)
919
        rs = RadioSetting("vfoa.mute_mode", "VFO A Mute",
920
                          RadioSettingValueList(
921
                              SPMUTE_LIST, SPMUTE_LIST[_vfoa.mute_mode]))
922
        vfoa_grp.append(rs)
923
        rs = RadioSetting("vfoa.step", "VFO A Step (kHz)",
924
                          RadioSettingValueList(
925
                              STEP_LIST, STEP_LIST[_vfoa.step]))
926
        vfoa_grp.append(rs)
927
        rs = RadioSetting("vfoa.squelch", "VFO A Squelch",
928
                          RadioSettingValueList(
929
                              LIST_10, LIST_10[_vfoa.squelch]))
930
        vfoa_grp.append(rs)
931
        rs = RadioSetting("bcl_a", "Busy Channel Lock-out A",
932
                          RadioSettingValueBoolean(_settings.bcl_a))
933
        vfoa_grp.append(rs)
934

    
935
                #
936
        # VFO B Settings
937
        #
938
        rs = RadioSetting("workmode_b", "VFO B Workmode",
939
                          RadioSettingValueList(WORKMODE_LIST,
940
                            WORKMODE_LIST[_settings.workmode_b]))
941
        vfob_grp.append(rs)
942
        rs = RadioSetting("work_chb", "VFO B Channel",
943
                          RadioSettingValueInteger(1, 999, _settings.work_chb))
944
        vfob_grp.append(rs)
945
        rs = RadioSetting("vfob.rxfreq", "VFO B Rx Frequency",
946
                          RadioSettingValueInteger(
947
                              self._vhf_range[0], self._uhf_range[1],
948
                                _vfob.rxfreq * 10, 5000))
949
        vfob_grp.append(rs)
950
        rs = RadioSetting("vfob.txoffset", "VFO B Tx Offset",
951
                          RadioSettingValueInteger(
952
                              0, self._uhf_range[1], _vfob.txoffset * 10, 5000))
953
        vfob_grp.append(rs)
954
        #   u16   rxtone;
955
        #   u16   txtone;
956
        rs = RadioSetting("vfob.power", "VFO B Power",
957
                          RadioSettingValueList(
958
                              POWER_LIST, POWER_LIST[_vfob.power]))
959
        vfob_grp.append(rs)
960
        #         shift_dir:2
961
        rs = RadioSetting("vfob.iswide", "VFO B NBFM",
962
                          RadioSettingValueList(
963
                              BANDWIDTH_LIST, BANDWIDTH_LIST[_vfob.iswide]))
964
        vfob_grp.append(rs)
965
        rs = RadioSetting("vfob.mute_mode", "VFO B Mute",
966
                          RadioSettingValueList(
967
                              SPMUTE_LIST, SPMUTE_LIST[_vfob.mute_mode]))
968
        vfob_grp.append(rs)
969
        rs = RadioSetting("vfob.step", "VFO B Step (kHz)",
970
                          RadioSettingValueList(
971
                              STEP_LIST, STEP_LIST[_vfob.step]))
972
        vfob_grp.append(rs)
973
        rs = RadioSetting("vfob.squelch", "VFO B Squelch",
974
                          RadioSettingValueList(
975
                              LIST_10, LIST_10[_vfob.squelch]))
976
        vfob_grp.append(rs)
977
        rs = RadioSetting("bcl_b", "Busy Channel Lock-out B",
978
                          RadioSettingValueBoolean(_settings.bcl_b))
979
        vfob_grp.append(rs)
980

    
981
                #
982
        # Key Settings
983
        #
984
        _msg = str(_settings.dispstr).split("\0")[0]
985
        val = RadioSettingValueString(0, 15, _msg)
986
        val.set_mutable(True)
987
        rs = RadioSetting("dispstr", "Display Message", val)
988
        key_grp.append(rs)
989

    
990
        dtmfchars = "0123456789"
991
        _codeobj = _settings.ani_code
992
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x0A])
993
        val = RadioSettingValueString(3, 6, _code, False)
994
        val.set_charset(dtmfchars)
995
        rs = RadioSetting("ani_code", "ANI Code", val)
996
        def apply_ani_id(setting, obj):
997
            value = []
998
            for j in range(0, 6):
999
                try:
1000
                    value.append(dtmfchars.index(str(setting.value)[j]))
1001
                except IndexError:
1002
                    value.append(0xFF)
1003
            obj.ani_code = value
1004
        rs.set_apply_callback(apply_ani_id, _settings)
1005
        key_grp.append(rs)
1006

    
1007
        rs = RadioSetting("pf1_func", "PF1 Key function",
1008
                          RadioSettingValueList(
1009
                              PF1KEY_LIST,
1010
                              PF1KEY_LIST[_settings.pf1_func]))
1011
        key_grp.append(rs)
1012
        rs = RadioSetting("pf3_func", "PF3 Key function",
1013
                          RadioSettingValueList(
1014
                              PF3KEY_LIST,
1015
                              PF3KEY_LIST[_settings.pf3_func]))
1016
        key_grp.append(rs)
1017

    
1018
        #
1019
        # Limits settings
1020
        #
1021
        rs = RadioSetting("uhf_limits.rx_start", "UHF RX Lower Limit",
1022
                          RadioSettingValueInteger(
1023
                            self._uhf_range[0], self._uhf_range[1],
1024
                            self._memobj.uhf_limits.rx_start * 10, 5000))
1025
        uhf_lmt_grp.append(rs)
1026
        rs = RadioSetting("uhf_limits.rx_stop", "UHF RX Upper Limit",
1027
                          RadioSettingValueInteger(
1028
                            self._uhf_range[0], self._uhf_range[1],
1029
                            self._memobj.uhf_limits.rx_stop * 10, 5000))
1030
        uhf_lmt_grp.append(rs)
1031
        rs = RadioSetting("uhf_limits.tx_start", "UHF TX Lower Limit",
1032
                          RadioSettingValueInteger(
1033
                            self._uhf_range[0], self._uhf_range[1],
1034
                            self._memobj.uhf_limits.tx_start * 10, 5000))
1035
        uhf_lmt_grp.append(rs)
1036
        rs = RadioSetting("uhf_limits.tx_stop", "UHF TX Upper Limit",
1037
                          RadioSettingValueInteger(
1038
                            self._uhf_range[0], self._uhf_range[1],
1039
                            self._memobj.uhf_limits.tx_stop * 10, 5000))
1040
        uhf_lmt_grp.append(rs)
1041
        rs = RadioSetting("vhf_limits.rx_start", "VHF RX Lower Limit",
1042
                          RadioSettingValueInteger(
1043
                            self._vhf_range[0], self._vhf_range[1],
1044
                            self._memobj.vhf_limits.rx_start * 10, 5000))
1045
        vhf_lmt_grp.append(rs)
1046
        rs = RadioSetting("vhf_limits.rx_stop", "VHF RX Upper Limit",
1047
                          RadioSettingValueInteger(
1048
                            self._vhf_range[0], self._vhf_range[1],
1049
                            self._memobj.vhf_limits.rx_stop * 10, 5000))
1050
        vhf_lmt_grp.append(rs)
1051
        rs = RadioSetting("vhf_limits.tx_start", "VHF TX Lower Limit",
1052
                          RadioSettingValueInteger(
1053
                            self._vhf_range[0], self._vhf_range[1],
1054
                            self._memobj.vhf_limits.tx_start * 10, 5000))
1055
        vhf_lmt_grp.append(rs)
1056
        rs = RadioSetting("vhf_limits.tx_stop", "VHF TX Upper Limit",
1057
                          RadioSettingValueInteger(
1058
                            self._vhf_range[0], self._vhf_range[1],
1059
                            self._memobj.vhf_limits.tx_stop * 10, 5000))
1060
        vhf_lmt_grp.append(rs)
1061

    
1062
        # KG-UV8E 1.25m band
1063
        if (self.MODEL == "KG-UV8E"):
1064
            rs = RadioSetting("vhf1_limits.rx_start", "VHF1 RX Lower Limit",
1065
                              RadioSettingValueInteger(
1066
                                self._vhf1_range[0], self._vhf1_range[1],
1067
                                self._memobj.vhf1_limits.rx_start * 10, 5000))
1068
            vhf1_lmt_grp.append(rs)
1069
            rs = RadioSetting("vhf1_limits.rx_stop", "VHF1 RX Upper Limit",
1070
                              RadioSettingValueInteger(
1071
                                self._vhf1_range[0], self._vhf1_range[1],
1072
                                self._memobj.vhf1_limits.rx_stop * 10, 5000))
1073
            vhf1_lmt_grp.append(rs)
1074
            rs = RadioSetting("vhf1_limits.tx_start", "VHF1 TX Lower Limit",
1075
                              RadioSettingValueInteger(
1076
                                self._vhf1_range[0], self._vhf1_range[1],
1077
                                self._memobj.vhf1_limits.tx_start * 10, 5000))
1078
            vhf1_lmt_grp.append(rs)
1079
            rs = RadioSetting("vhf1_limits.tx_stop", "VHF1 TX Upper Limit",
1080
                              RadioSettingValueInteger(
1081
                                self._vhf1_range[0], self._vhf1_range[1],
1082
                                self._memobj.vhf1_limits.tx_stop * 10, 5000))
1083
            vhf1_lmt_grp.append(rs)
1084

    
1085

    
1086
        #
1087
        # OEM info
1088
        #
1089
        def _decode(lst):
1090
            _str = ''.join([chr(c) for c in lst
1091
                            if chr(c) in chirp_common.CHARSET_ASCII])
1092
            return _str
1093

    
1094
        def do_nothing(setting, obj):
1095
            return
1096

    
1097
        _str = _decode(self._memobj.oem_info.model)
1098
        val = RadioSettingValueString(0, 15, _str)
1099
        val.set_mutable(False)
1100
        rs = RadioSetting("oem_info.model", "Model", val)
1101
        rs.set_apply_callback(do_nothing, _settings)
1102
        oem_grp.append(rs)
1103
        _str = _decode(self._memobj.oem_info.oem1)
1104
        val = RadioSettingValueString(0, 15, _str)
1105
        val.set_mutable(False)
1106
        rs = RadioSetting("oem_info.oem1", "OEM String 1", val)
1107
        rs.set_apply_callback(do_nothing, _settings)
1108
        oem_grp.append(rs)
1109
        _str = _decode(self._memobj.oem_info.oem2)
1110
        val = RadioSettingValueString(0, 15, _str)
1111
        val.set_mutable(False)
1112
        rs = RadioSetting("oem_info.oem2", "OEM String 2", val)
1113
        rs.set_apply_callback(do_nothing, _settings)
1114
        oem_grp.append(rs)
1115
        _str = _decode(self._memobj.oem_info.version)
1116
        val = RadioSettingValueString(0, 15, _str)
1117
        val.set_mutable(False)
1118
        rs = RadioSetting("oem_info.version", "Software Version", val)
1119
        rs.set_apply_callback(do_nothing, _settings)
1120
        oem_grp.append(rs)
1121
        _str = _decode(self._memobj.oem_info.date)
1122
        val = RadioSettingValueString(0, 15, _str)
1123
        val.set_mutable(False)
1124
        rs = RadioSetting("oem_info.date", "OEM Date", val)
1125
        rs.set_apply_callback(do_nothing, _settings)
1126
        oem_grp.append(rs)
1127

    
1128
        return group
1129

    
1130
    def get_settings(self):
1131
        try:
1132
            return self._get_settings()
1133
        except:
1134
            import traceback
1135
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1136
            return None
1137

    
1138
    def set_settings(self, settings):
1139
        for element in settings:
1140
            if not isinstance(element, RadioSetting):
1141
                self.set_settings(element)
1142
                continue
1143
            else:
1144
                try:
1145
                    if "." in element.get_name():
1146
                        bits = element.get_name().split(".")
1147
                        obj = self._memobj
1148
                        for bit in bits[:-1]:
1149
                            obj = getattr(obj, bit)
1150
                        setting = bits[-1]
1151
                    else:
1152
                        obj = self._memobj.settings
1153
                        setting = element.get_name()
1154

    
1155
                    if element.has_apply_callback():
1156
                        LOG.debug("Using apply callback")
1157
                        element.run_apply_callback()
1158
                    else:
1159
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1160
                        if self._is_freq(element):
1161
                            setattr(obj, setting, int(element.value)/10)
1162
                        else:
1163
                            setattr(obj, setting, element.value)
1164
                except Exception, e:
1165
                    LOG.debug(element.get_name())
1166
                    raise
1167

    
1168
    def _is_freq(self, element):
1169
        return "rxfreq" in element.get_name() or "txoffset" in element.get_name() or "rx_start" in element.get_name() or "rx_stop" in element.get_name() or "tx_start" in element.get_name() or "tx_stop" in element.get_name()
1170

    
1171

    
1172
@directory.register
1173
class KGUV8DPlusRadio(KGUV8crypt):
1174
    """Wouxun KG-UV8D Plus"""
1175
    MODEL = "KG-UV8D Plus"
1176
    _model = "KG-UV8D"  # TODO need to use full 10 chars of the ident
1177
                        # string to distinct from the UV8E
1178
    _file_ident = "kguv8dplus"  # kg + "UV8D(Plus)"
1179
    _START_CMD = '\x7a'
1180

    
1181

    
1182
@directory.register
1183
class KGUV8E(KGUV8crypt):
1184
    """Wouxun KG-UV8E"""
1185
    MODEL = "KG-UV8E"
1186
    _model = "KG-UV8D-A\x00"    # full 10 chars
1187
    _file_ident = "kguv8e3txv"  # kg + "UV8E(3TX)V" actually the ending V is
1188
                                # from the Soft version but to KISS we
1189
                                # let it here
1190
    _START_CMD = '\x7b'
1191
    _vhf1_range = (220000000, 265000000)  # supports 1.25m
(1-1/12)