Project

General

Profile

New Model #8803 » kguv8h.py

Latest dev-driver, removed vhf1 band and fixed some limits and other minor tweaks - Pavel Milanes, 05/04/2021 11:39 AM

 
1
# Copyright 2019 Pavel Milanes CO7WT <pavelmc@gmail.com>
2
#
3
# Based on the work of Krystian Struzik <toner_82@tlen.pl>
4
# who figured out the crypt used and made possible the
5
# Wuoxun KG-UV8D Plus driver, in which this work is based.
6
#
7
# This program is free software: you can redistribute it and/or modify
8
# it under the terms of the GNU General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# This program is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
# GNU General Public License for more details.
16
#
17
# You should have received a copy of the GNU General Public License
18
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
19

    
20
"""Wouxun KG-UV8H radio management module"""
21

    
22
import time
23
import os
24
import logging
25
from chirp import util, chirp_common, bitwise, memmap, errors, directory
26
from chirp.settings import RadioSetting, RadioSettingGroup, \
27
    RadioSettingValueBoolean, RadioSettingValueList, \
28
    RadioSettingValueInteger, RadioSettingValueString, \
29
    RadioSettings
30

    
31
LOG = logging.getLogger(__name__)
32

    
33
CMD_ID = 128    # \x80
34
CMD_END = 129   # \x81
35
CMD_RD = 130    # \82
36
CMD_WR = 131    # \83
37

    
38
MEM_VALID = 158
39

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

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

    
75
_MEM_FORMAT = """
76
    #seekto 0x0044;
77
    struct {
78
        u32    rx_start;
79
        u32    rx_stop;
80
        u32    tx_start;
81
        u32    tx_stop;
82
    } uhf_limits;
83

    
84
    #seekto 0x0054;
85
    struct {
86
        u32    rx_start;
87
        u32    rx_stop;
88
        u32    tx_start;
89
        u32    tx_stop;
90
    } vhf_limits;
91

    
92
    #seekto 0x0400;
93
    struct {
94
        u8     oem1[8];
95
        u8     unknown[2];
96
        u8     unknown2[10];
97
        u8     unknown3[10];
98
        u8     unknown4[8];
99
        u8     model[10];
100
        u8     version[6];
101
        u8     date[8];
102
        u8     unknown5[1];
103
        u8     oem2[8];
104
    } oem_info;
105

    
106
    #seekto 0x0480;
107
    struct {
108
        u16    lower;
109
        u16    upper;
110
    } scan_groups[10];
111

    
112
    #seekto 0x0500;
113
    struct {
114
        u8    call_code[6];
115
    } call_groups[20];
116

    
117
    #seekto 0x0580;
118
    struct {
119
        char    call_name[6];
120
    } call_group_name[20];
121

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

    
201
    #seekto 0x0880;
202
    struct {
203
        u32     rxfreq;
204
        u32     txoffset;
205
        u16     rxtone;
206
        u16     txtone;
207
        u8      scrambler:4,
208
                unknown1:2,
209
                power:1,
210
                unknown2:1;
211
        u8      unknown3:1,
212
                shift_dir:2
213
                unknown4:1,
214
                compander:1,
215
                mute_mode:2,
216
                iswide:1;
217
        u8      step;
218
        u8      squelch;
219
      } vfoa;
220

    
221
    #seekto 0x08c0;
222
    struct {
223
        u32     rxfreq;
224
        u32     txoffset;
225
        u16     rxtone;
226
        u16     txtone;
227
        u8      scrambler:4,
228
                unknown1:2,
229
                power:1,
230
                unknown2:1;
231
        u8      unknown3:1,
232
                shift_dir:2
233
                unknown4:1,
234
                compander:1,
235
                mute_mode:2,
236
                iswide:1;
237
        u8      step;
238
        u8      squelch;
239
    } vfob;
240

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

    
260
    #seekto 0x4780;
261
    struct {
262
        u8    name[8];
263
                u8    unknown[4];
264
    } names[1000];
265

    
266
    #seekto 0x7670;
267
    u8          valid[1000];
268
    """
269

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

    
289
class KGUV8TRadio(chirp_common.Alias):
290
    VENDOR = "Wuoxun"
291
    MODEL = "KG-UV8H"
292

    
293
@directory.register
294
class KGUV8HRadio(chirp_common.CloneModeRadio,
295
                  chirp_common.ExperimentalRadio):
296

    
297
    """Wouxun KG-UV8H"""
298
    VENDOR = "Wouxun"
299
    MODEL = "KG-UV8H"
300
    _model = "KG-UV8D-B"
301
    _file_ident = "UV8H"
302
    BAUD_RATE = 19200
303
    POWER_LEVELS = [chirp_common.PowerLevel("L", watts=1),
304
                    chirp_common.PowerLevel("H", watts=5)]
305
    _mmap = ""
306
    ALIASES = [KGUV8TRadio,]
307

    
308
    def _checksum(self, data):
309
        cs = 0
310
        for byte in data:
311
            cs += ord(byte)
312
        return chr(cs % 256)
313

    
314
    def _write_record(self, cmd, payload = None):
315
        # build the packet
316
        _header = '\x7c' + chr(cmd) + '\xff'
317

    
318
        _length = 0
319
        if payload:
320
            _length = len(payload)
321

    
322
        # update the length field
323
        _header += chr(_length)
324

    
325
        if payload:
326
            # calculate checksum then add it with the payload to the packet and encrypt
327
            crc = self._checksum(_header[1:] + payload)
328
            payload += crc
329
            _header += self.encrypt(payload)
330
        else:
331
            # calculate and add encrypted checksum to the packet
332
            crc = self._checksum(_header[1:])
333
            _header += self.strxor(crc, '\x57')
334

    
335
        try:
336
            self.pipe.write(_header)
337
        except Exception, e:
338
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
339

    
340
    def _read_record(self):
341
        # read 4 chars for the header
342
        _header = self.pipe.read(4)
343
        if len(_header) != 4:
344
            raise errors.RadioError('Radio did not respond')
345
        _length = ord(_header[3])
346
        _packet = self.pipe.read(_length)
347
        _rcs_xor = _packet[-1]
348
        _packet = self.decrypt(_packet)
349
        _cs = ord(self._checksum(_header[1:] + _packet))
350
        # read the checksum and decrypt it
351
        _rcs = ord(self.strxor(self.pipe.read(1), _rcs_xor))
352
        return (_rcs != _cs, _packet)
353

    
354
    def decrypt(self, data):
355
        result = ''
356
        for i in range(len(data)-1, 0, -1):
357
            result += self.strxor(data[i], data[i - 1])
358
        result += self.strxor(data[0], '\x57')
359
        return result[::-1]
360

    
361
    def encrypt(self, data):
362
        result = self.strxor('\x57', data[0])
363
        for i in range(1, len(data), 1):
364
            result += self.strxor(result[i - 1], data[i])
365
        return result
366

    
367
    def strxor (self, xora, xorb):
368
        return chr(ord(xora) ^ ord(xorb))
369

    
370
    # Identify the radio
371
    #
372
    # A Gotcha: the first identify packet returns a bad checksum, subsequent
373
    # attempts return the correct checksum... (well it does on my radio!)
374
    #
375
    # The ID record returned by the radio also includes the current frequency range
376
    # as 4 bytes big-endian in 10Hz increments
377
    #
378
    # Offset
379
    #  0:10     Model, zero padded (Looks for 'KG-UV8D-B')
380

    
381
    @classmethod
382
    def match_model(cls, filedata, filename):
383
        id = cls._file_ident 
384
        return cls._file_ident in filedata[0x426:0x430]
385

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

    
404
    def _finish(self):
405
        self._write_record(CMD_END)
406

    
407
    def process_mmap(self):
408
        self._memobj = bitwise.parse(_MEM_FORMAT, self._mmap)
409

    
410
    def sync_in(self):
411
        try:
412
            self._mmap = self._download()
413
        except errors.RadioError:
414
            raise
415
        except Exception, e:
416
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
417
        self.process_mmap()
418

    
419
    def sync_out(self):
420
        self._upload()
421

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

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

    
457
    def _upload(self):
458
        """Talk to a wouxun KG-UV8H and do a upload"""
459
        try:
460
            self._identify()
461
            self._do_upload(0, 32768, 64)
462
        except errors.RadioError:
463
            raise
464
        except Exception, e:
465
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
466
        return
467

    
468
    def _do_upload(self, start, end, blocksize):
469
        ptr = start
470
        for i in range(start, end, blocksize):
471
            req = chr(i / 256) + chr(i % 256)
472
            chunk = self.get_mmap()[ptr:ptr + blocksize]
473
            self._write_record(CMD_WR, req + chunk)
474
            LOG.debug(util.hexprint(req + chunk))
475
            cserr, ack = self._read_record()
476
            LOG.debug(util.hexprint(ack))
477
            j = ord(ack[0]) * 256 + ord(ack[1])
478
            if cserr or j != ptr:
479
                raise Exception("Radio did not ack block %i" % ptr)
480
            ptr += blocksize
481
            if self.status_fn:
482
                status = chirp_common.Status()
483
                status.cur = i
484
                status.max = end
485
                status.msg = "Cloning to radio"
486
                self.status_fn(status)
487
        self._finish()
488

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

    
520
    @classmethod
521
    def get_prompts(cls):
522
        rp = chirp_common.RadioPrompts()
523
        rp.experimental = \
524
            ('This driver is experimental.\n'
525
             '\n'
526
             'Please keep a copy of your memories with the original software '
527
             'if you treasure them, this driver is new and may contain'
528
             ' bugs.\n'
529
             '\n'
530
             )
531
        return rp
532

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

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

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

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

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

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

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

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

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

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

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

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

    
615
        self._get_tone(_mem, mem)
616

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

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

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

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

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

    
655
        _mem.rxtone = rxtone
656
        _mem.txtone = txtone
657

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

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

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

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

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

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

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

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

    
727
        #
728
        # Configuration Settings
729
        #
730
        rs = RadioSetting("channel_menu", "Menu available in channel mode",
731
                          RadioSettingValueBoolean(_settings.channel_menu))
732
        cfg_grp.append(rs)
733
        rs = RadioSetting("ponmsg", "Poweron message",
734
                          RadioSettingValueList(
735
                              PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
736
        cfg_grp.append(rs)
737
        rs = RadioSetting("voice", "Voice Guide",
738
                          RadioSettingValueBoolean(_settings.voice))
739
        cfg_grp.append(rs)
740
        rs = RadioSetting("language", "Language",
741
                          RadioSettingValueList(LANGUAGE_LIST,
742
                                                LANGUAGE_LIST[_settings.
743
                                                              language]))
744
        cfg_grp.append(rs)
745
        rs = RadioSetting("timeout", "Timeout Timer",
746
                          RadioSettingValueList(
747
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
748
        cfg_grp.append(rs)
749
        rs = RadioSetting("toalarm", "Timeout Alarm",
750
                          RadioSettingValueInteger(0, 10, _settings.toalarm))
751
        cfg_grp.append(rs)
752
        rs = RadioSetting("roger_beep", "Roger Beep",
753
                          RadioSettingValueList(ROGER_LIST,
754
                                                ROGER_LIST[_settings.roger_beep]))
755
        cfg_grp.append(rs)
756
        rs = RadioSetting("power_save", "Power save",
757
                          RadioSettingValueBoolean(_settings.power_save))
758
        cfg_grp.append(rs)
759
        rs = RadioSetting("autolock", "Autolock",
760
                          RadioSettingValueBoolean(_settings.autolock))
761
        cfg_grp.append(rs)
762
        rs = RadioSetting("keylock", "Keypad Lock",
763
                          RadioSettingValueBoolean(_settings.keylock))
764
        cfg_grp.append(rs)
765
        rs = RadioSetting("beep", "Keypad Beep",
766
                          RadioSettingValueBoolean(_settings.beep))
767
        cfg_grp.append(rs)
768
        rs = RadioSetting("stopwatch", "Stopwatch",
769
                          RadioSettingValueBoolean(_settings.stopwatch))
770
        cfg_grp.append(rs)
771
        rs = RadioSetting("backlight", "Backlight",
772
                          RadioSettingValueList(BACKLIGHT_LIST,
773
                                                BACKLIGHT_LIST[_settings.
774
                                                               backlight]))
775
        cfg_grp.append(rs)
776
        rs = RadioSetting("dtmf_st", "DTMF Sidetone",
777
                          RadioSettingValueList(DTMFST_LIST,
778
                                                DTMFST_LIST[_settings.
779
                                                            dtmf_st]))
780
        cfg_grp.append(rs)
781
        rs = RadioSetting("ani_sw", "ANI-ID Switch",
782
                          RadioSettingValueBoolean(_settings.ani_sw))
783
        cfg_grp.append(rs)
784
        rs = RadioSetting("ptt_id", "PTT-ID Delay",
785
                          RadioSettingValueList(PTTID_LIST,
786
                                                PTTID_LIST[_settings.ptt_id]))
787
        cfg_grp.append(rs)
788
        rs = RadioSetting("ring_time", "Ring Time",
789
                          RadioSettingValueList(LIST_10,
790
                                                LIST_10[_settings.ring_time]))
791
        cfg_grp.append(rs)
792
        rs = RadioSetting("scan_rev", "Scan Mode",
793
                          RadioSettingValueList(SCANMODE_LIST,
794
                                                SCANMODE_LIST[_settings.
795
                                                              scan_rev]))
796
        cfg_grp.append(rs)
797
        rs = RadioSetting("vox", "VOX",
798
                          RadioSettingValueList(LIST_10,
799
                                                LIST_10[_settings.vox]))
800
        cfg_grp.append(rs)
801
        rs = RadioSetting("prich_sw", "Priority Channel Switch",
802
                          RadioSettingValueBoolean(_settings.prich_sw))
803
        cfg_grp.append(rs)
804
        rs = RadioSetting("pri_ch", "Priority Channel",
805
                          RadioSettingValueInteger(1, 999, _settings.pri_ch))
806
        cfg_grp.append(rs)
807
        rs = RadioSetting("rpt_mode", "Radio Mode",
808
                          RadioSettingValueList(RPTMODE_LIST,
809
                                                RPTMODE_LIST[_settings.
810
                                                             rpt_mode]))
811
        cfg_grp.append(rs)
812
        rs = RadioSetting("rpt_set", "Repeater Setting",
813
                          RadioSettingValueList(RPTSET_LIST,
814
                                                RPTSET_LIST[_settings.
815
                                                            rpt_set]))
816
        cfg_grp.append(rs)
817
        rs = RadioSetting("rpt_spk", "Repeater Mode Speaker",
818
                          RadioSettingValueBoolean(_settings.rpt_spk))
819
        cfg_grp.append(rs)
820
        rs = RadioSetting("rpt_ptt", "Repeater PTT",
821
                          RadioSettingValueBoolean(_settings.rpt_ptt))
822
        cfg_grp.append(rs)
823
        rs = RadioSetting("dtmf_tx_time", "DTMF Tx Duration",
824
                          RadioSettingValueList(DTMF_TIMES,
825
                                                DTMF_TIMES[_settings.
826
                                                           dtmf_tx_time]))
827
        cfg_grp.append(rs)
828
        rs = RadioSetting("dtmf_interval", "DTMF Interval",
829
                          RadioSettingValueList(DTMF_TIMES,
830
                                                DTMF_TIMES[_settings.
831
                                                           dtmf_interval]))
832
        cfg_grp.append(rs)
833
        rs = RadioSetting("alert", "Alert Tone",
834
                          RadioSettingValueList(ALERTS_LIST,
835
                                                ALERTS_LIST[_settings.alert]))
836
        cfg_grp.append(rs)
837
        rs = RadioSetting("rpt_tone", "Repeater Tone",
838
                          RadioSettingValueBoolean(_settings.rpt_tone))
839
        cfg_grp.append(rs)
840
        rs = RadioSetting("rpt_hold", "Repeater Hold Time",
841
                          RadioSettingValueList(HOLD_TIMES,
842
                                                HOLD_TIMES[_settings.
843
                                                           rpt_hold]))
844
        cfg_grp.append(rs)
845
        rs = RadioSetting("scan_det", "Scan DET",
846
                          RadioSettingValueBoolean(_settings.scan_det))
847
        cfg_grp.append(rs)
848
        rs = RadioSetting("sc_qt", "SC-QT",
849
                          RadioSettingValueList(SCQT_LIST,
850
                                                SCQT_LIST[_settings.sc_qt]))
851
        cfg_grp.append(rs)
852
        rs = RadioSetting("smuteset", "SubFreq Mute",
853
                          RadioSettingValueList(SMUTESET_LIST,
854
                                                SMUTESET_LIST[_settings.
855
                                                              smuteset]))
856
        cfg_grp.append(rs)
857

    
858
                #
859
        # VFO A Settings
860
        #
861
        rs = RadioSetting("workmode_a", "VFO A Workmode",
862
                          RadioSettingValueList(WORKMODE_LIST, WORKMODE_LIST[_settings.workmode_a]))
863
        vfoa_grp.append(rs)
864
        rs = RadioSetting("work_cha", "VFO A Channel",
865
                          RadioSettingValueInteger(1, 999, _settings.work_cha))
866
        vfoa_grp.append(rs)
867
        rs = RadioSetting("vfoa.rxfreq", "VFO A Rx Frequency",
868
                          RadioSettingValueInteger(
869
                              134000000, 520000000, _vfoa.rxfreq * 10, 5000))
870
        vfoa_grp.append(rs)
871
        rs = RadioSetting("vfoa.txoffset", "VFO A Tx Offset",
872
                          RadioSettingValueInteger(
873
                              0, 520000000, _vfoa.txoffset * 10, 5000))
874
        vfoa_grp.append(rs)
875
        #   u16   rxtone;
876
        #   u16   txtone;
877
        rs = RadioSetting("vfoa.power", "VFO A Power",
878
                          RadioSettingValueList(
879
                              POWER_LIST, POWER_LIST[_vfoa.power]))
880
        vfoa_grp.append(rs)
881
        #         shift_dir:2
882
        rs = RadioSetting("vfoa.iswide", "VFO A NBFM",
883
                          RadioSettingValueList(
884
                              BANDWIDTH_LIST, BANDWIDTH_LIST[_vfoa.iswide]))
885
        vfoa_grp.append(rs)
886
        rs = RadioSetting("vfoa.mute_mode", "VFO A Mute",
887
                          RadioSettingValueList(
888
                              SPMUTE_LIST, SPMUTE_LIST[_vfoa.mute_mode]))
889
        vfoa_grp.append(rs)
890
        rs = RadioSetting("vfoa.step", "VFO A Step (kHz)",
891
                          RadioSettingValueList(
892
                              STEP_LIST, STEP_LIST[_vfoa.step]))
893
        vfoa_grp.append(rs)
894
        rs = RadioSetting("vfoa.squelch", "VFO A Squelch",
895
                          RadioSettingValueList(
896
                              LIST_10, LIST_10[_vfoa.squelch]))
897
        vfoa_grp.append(rs)
898
        rs = RadioSetting("bcl_a", "Busy Channel Lock-out A",
899
                          RadioSettingValueBoolean(_settings.bcl_a))
900
        vfoa_grp.append(rs)
901

    
902
                #
903
        # VFO B Settings
904
        #
905
        rs = RadioSetting("workmode_b", "VFO B Workmode",
906
                          RadioSettingValueList(WORKMODE_LIST, WORKMODE_LIST[_settings.workmode_b]))
907
        vfob_grp.append(rs)
908
        rs = RadioSetting("work_chb", "VFO B Channel",
909
                          RadioSettingValueInteger(1, 999, _settings.work_chb))
910
        vfob_grp.append(rs)
911
        rs = RadioSetting("vfob.rxfreq", "VFO B Rx Frequency",
912
                          RadioSettingValueInteger(
913
                              134000000, 520000000, _vfob.rxfreq * 10, 5000))
914
        vfob_grp.append(rs)
915
        rs = RadioSetting("vfob.txoffset", "VFO B Tx Offset",
916
                          RadioSettingValueInteger(
917
                              0, 520000000, _vfob.txoffset * 10, 5000))
918
        vfob_grp.append(rs)
919
        #   u16   rxtone;
920
        #   u16   txtone;
921
        rs = RadioSetting("vfob.power", "VFO B Power",
922
                          RadioSettingValueList(
923
                              POWER_LIST, POWER_LIST[_vfob.power]))
924
        vfob_grp.append(rs)
925
        #         shift_dir:2
926
        rs = RadioSetting("vfob.iswide", "VFO B NBFM",
927
                          RadioSettingValueList(
928
                              BANDWIDTH_LIST, BANDWIDTH_LIST[_vfob.iswide]))
929
        vfob_grp.append(rs)
930
        rs = RadioSetting("vfob.mute_mode", "VFO B Mute",
931
                          RadioSettingValueList(
932
                              SPMUTE_LIST, SPMUTE_LIST[_vfob.mute_mode]))
933
        vfob_grp.append(rs)
934
        rs = RadioSetting("vfob.step", "VFO B Step (kHz)",
935
                          RadioSettingValueList(
936
                              STEP_LIST, STEP_LIST[_vfob.step]))
937
        vfob_grp.append(rs)
938
        rs = RadioSetting("vfob.squelch", "VFO B Squelch",
939
                          RadioSettingValueList(
940
                              LIST_10, LIST_10[_vfob.squelch]))
941
        vfob_grp.append(rs)
942
        rs = RadioSetting("bcl_b", "Busy Channel Lock-out B",
943
                          RadioSettingValueBoolean(_settings.bcl_b))
944
        vfob_grp.append(rs)
945

    
946
                #
947
        # Key Settings
948
        #
949
        _msg = str(_settings.dispstr).split("\0")[0]
950
        val = RadioSettingValueString(0, 15, _msg)
951
        val.set_mutable(True)
952
        rs = RadioSetting("dispstr", "Display Message", val)
953
        key_grp.append(rs)
954

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

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

    
983
        #
984
        # Limits settings
985
        #
986
        rs = RadioSetting("vhf_limits.rx_start", "VHF RX Lower Limit",
987
                          RadioSettingValueInteger(
988
                              134000000, 174997500,
989
                              self._memobj.vhf_limits.rx_start * 10, 5000))
990
        vhf_lmt_grp.append(rs)
991
        rs = RadioSetting("vhf_limits.rx_stop", "VHF RX Upper Limit",
992
                          RadioSettingValueInteger(
993
                              134000000, 174997500,
994
                              self._memobj.vhf_limits.rx_stop * 10, 5000))
995
        vhf_lmt_grp.append(rs)
996
        rs = RadioSetting("vhf_limits.tx_start", "VHF TX Lower Limit",
997
                          RadioSettingValueInteger(
998
                              134000000, 174997500,
999
                              self._memobj.vhf_limits.tx_start * 10, 5000))
1000
        vhf_lmt_grp.append(rs)
1001
        rs = RadioSetting("vhf_limits.tx_stop", "VHF TX Upper Limit",
1002
                          RadioSettingValueInteger(
1003
                              134000000, 174997500,
1004
                              self._memobj.vhf_limits.tx_stop * 10, 5000))
1005
        vhf_lmt_grp.append(rs)
1006

    
1007
        rs = RadioSetting("uhf_limits.rx_start", "UHF RX Lower Limit",
1008
                          RadioSettingValueInteger(
1009
                              400000000, 520000000,
1010
                              self._memobj.uhf_limits.rx_start * 10, 5000))
1011
        uhf_lmt_grp.append(rs)
1012
        rs = RadioSetting("uhf_limits.rx_stop", "UHF RX Upper Limit",
1013
                          RadioSettingValueInteger(
1014
                              400000000, 520000000,
1015
                              self._memobj.uhf_limits.rx_stop * 10, 5000))
1016
        uhf_lmt_grp.append(rs)
1017
        rs = RadioSetting("uhf_limits.tx_start", "UHF TX Lower Limit",
1018
                          RadioSettingValueInteger(
1019
                              400000000, 520000000,
1020
                              self._memobj.uhf_limits.tx_start * 10, 5000))
1021
        uhf_lmt_grp.append(rs)
1022
        rs = RadioSetting("uhf_limits.tx_stop", "UHF TX Upper Limit",
1023
                          RadioSettingValueInteger(
1024
                              400000000, 520000000,
1025
                              self._memobj.uhf_limits.tx_stop * 10, 5000))
1026
        uhf_lmt_grp.append(rs)
1027

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

    
1036
        def do_nothing(setting, obj):
1037
            return
1038

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

    
1070
        return group
1071

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

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

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

    
1110
    def _is_freq(self, element):
1111
        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()
(19-19/37)