Project

General

Profile

New Model #9489 » kg935g test.py

Mel Terechenok, 04/15/2022 12:43 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-935G 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", "Med", "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
# MRT made Power = 2 bits to handle 935G's 3 power levels
76
_MEM_FORMAT = """
77
    #seekto 0x0044;
78
    struct {
79
        u32    rx_start;
80
        u32    rx_stop;
81
        u32    tx_start;
82
        u32    tx_stop;
83
    } uhf_limits;
84

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

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

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

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

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

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

    
202
    #seekto 0x0880;
203
    struct {
204
        u32     rxfreq;
205
        u32     txoffset;
206
        u16     rxtone;
207
        u16     txtone;
208
        u8      scrambler:4,
209
                unknown1:2,
210
                power:2; 
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:2; 
230
        u8      unknown3:1,
231
                shift_dir:2
232
                unknown4:1,
233
                compander:1,
234
                mute_mode:2,
235
                iswide:1;
236
        u8      step;
237
        u8      squelch;
238
    } vfob;
239

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

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

    
264
    #seekto 0x7670;
265
    u8          valid[1000];
266
    """
267

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

    
287
class KGUV8TRadio(chirp_common.Alias):
288
    VENDOR = "Wuoxun"
289
    MODEL = "KG-935G"
290

    
291
@directory.register
292
class KG935GRadio(chirp_common.CloneModeRadio,
293
                  chirp_common.ExperimentalRadio):
294

    
295
    """Wouxun KG-935G"""
296
    VENDOR = "Wouxun"
297
    MODEL = "KG-935G"
298
    _model = "KG-UV8D-B"
299
    _file_ident = "935G"
300
    BAUD_RATE = 19200
301
# MRT - Added Medium Power level for 935G support
302
    POWER_LEVELS = [chirp_common.PowerLevel("L", watts=0.5),
303
                    chirp_common.PowerLevel("M", watts=4.5),
304
                    chirp_common.PowerLevel("H", watts=5.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-935G 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-935G 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
             ' USE FOR DOWNLOAD FROM RADIO ONLY - \n'
531
             ' DO NOT UPLOAD AS THIS HAS NOT BEEN TESTED\n'
532
             ' USE AT YOUR OWN RISK\n'
533
             '\n'
534
             )
535
        return rp
536

    
537
    def get_raw_memory(self, number):
538
        return repr(self._memobj.memory[number])
539
# MRT - corrected the Polarity decoding to match 935G implementation use 0x2000 bit mask for R
540
# MRT - 0x2000 appears to be the bit mask for Inverted DCS tones
541
# MRT - n DCS Tone will be 0x4xxx values - i DCS Tones will be 0x6xxx values.
542
# MRT - Chirp Uses N for n DCS Tones and R for i DCS Tones
543
    def _get_tone(self, _mem, mem):
544
        def _get_dcs(val):
545
            code = int("%03o" % (val & 0x07FF))
546
            pol = (val & 0x2000) and "R" or "N"
547
            return code, pol
548
# MRT - Modified the function below to bitwise AND with 0x4000 to check for 935G DCS Tone decoding
549
# MRT 0x4000 appears to be the bit mask for DCS tones
550
        tpol = False
551
        if _mem.txtone != 0xFFFF and (_mem.rxtone & 0x4000) == 0x4000:
552
            tcode, tpol = _get_dcs(_mem.txtone)
553
            mem.dtcs = tcode
554
            txmode = "DTCS"
555
        elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
556
            mem.rtone = (_mem.txtone & 0x7fff) / 10.0
557
            txmode = "Tone"
558
        else:
559
            txmode = ""
560
# MRT - Modified the function below to bitwise AND with 0x4000 to check for 935G DCS Tone decoding
561
        rpol = False
562
        if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x4000) == 0x4000:
563
            rcode, rpol = _get_dcs(_mem.rxtone)
564
            mem.rx_dtcs = rcode
565
            rxmode = "DTCS"
566
        elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
567
            mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
568
            rxmode = "Tone"
569
        else:
570
            rxmode = ""
571

    
572
        if txmode == "Tone" and not rxmode:
573
            mem.tmode = "Tone"
574
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
575
            mem.tmode = "TSQL"
576
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
577
            mem.tmode = "DTCS"
578
        elif rxmode or txmode:
579
            mem.tmode = "Cross"
580
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
581

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

    
585
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
586
                  (txmode, _mem.txtone, rxmode, _mem.rxtone))
587

    
588
    def get_memory(self, number):
589
        _mem = self._memobj.memory[number]
590
        _nam = self._memobj.names[number]
591

    
592
        mem = chirp_common.Memory()
593
        mem.number = number
594
        _valid = self._memobj.valid[mem.number]
595
        LOG.debug("%d %s", number, _valid == MEM_VALID)
596
        if _valid != MEM_VALID:
597
            mem.empty = True
598
            return mem
599
        else:
600
            mem.empty = False
601

    
602
        mem.freq = int(_mem.rxfreq) * 10
603

    
604
        if _mem.txfreq == 0xFFFFFFFF:
605
            # TX freq not set
606
            mem.duplex = "off"
607
            mem.offset = 0
608
        elif int(_mem.rxfreq) == int(_mem.txfreq):
609
            mem.duplex = ""
610
            mem.offset = 0
611
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
612
            mem.duplex = "split"
613
            mem.offset = int(_mem.txfreq) * 10
614
        else:
615
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
616
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
617

    
618
        for char in _nam.name:
619
            if char != 0:
620
                mem.name += chr(char)
621
        mem.name = mem.name.rstrip()
622

    
623
        self._get_tone(_mem, mem)
624

    
625
        mem.skip = "" if bool(_mem.scan_add) else "S"
626

    
627
        mem.power = self.POWER_LEVELS[_mem.power]
628
        mem.mode = _mem.iswide and "FM" or "NFM"
629
        return mem
630

    
631
    def _set_tone(self, mem, _mem):
632
        def _set_dcs(code, pol):
633
#MRT Change from + 0x2800 to bitwise OR with 0x4000 to set the bit for DCS
634
            val = int("%i" % code, 8) | 0x4000
635
            if pol == "R":
636
#MRT Change to 0x2000 from 0x8000 to set the bit for i/R polarity
637
               val += 0x2000
638
            return val
639

    
640
        rx_mode = tx_mode = None
641
        rxtone = txtone = 0x0000
642

    
643
        if mem.tmode == "Tone":
644
            tx_mode = "Tone"
645
            rx_mode = None
646
            txtone = int(mem.rtone * 10) + 0x8000
647
        elif mem.tmode == "TSQL":
648
            rx_mode = tx_mode = "Tone"
649
            rxtone = txtone = int(mem.ctone * 10) + 0x8000
650
        elif mem.tmode == "DTCS":
651
            tx_mode = rx_mode = "DTCS"
652
            txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
653
            rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
654
        elif mem.tmode == "Cross":
655
            tx_mode, rx_mode = mem.cross_mode.split("->")
656
            if tx_mode == "DTCS":
657
                txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
658
            elif tx_mode == "Tone":
659
                txtone = int(mem.rtone * 10) + 0x8000
660
            if rx_mode == "DTCS":
661
                rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
662
            elif rx_mode == "Tone":
663
                rxtone = int(mem.ctone * 10) + 0x8000
664

    
665
        _mem.rxtone = rxtone
666
        _mem.txtone = txtone
667

    
668
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
669
                  (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
670

    
671
    def set_memory(self, mem):
672
        number = mem.number
673

    
674
        _mem = self._memobj.memory[number]
675
        _nam = self._memobj.names[number]
676

    
677
        if mem.empty:
678
            _mem.set_raw("\x00" * (_mem.size() / 8))
679
            self._memobj.valid[number] = 0
680
            self._memobj.names[number].set_raw("\x00" * (_nam.size() / 8))
681
            return
682

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

    
712
        for i in range(0, len(_nam.name)):
713
            if i < len(mem.name) and mem.name[i]:
714
                _nam.name[i] = ord(mem.name[i])
715
            else:
716
                _nam.name[i] = 0x0
717
        self._memobj.valid[mem.number] = MEM_VALID
718

    
719
    def _get_settings(self):
720
        _settings = self._memobj.settings
721
        _vfoa = self._memobj.vfoa
722
        _vfob = self._memobj.vfob
723
        cfg_grp = RadioSettingGroup("cfg_grp", "Configuration")
724
        vfoa_grp = RadioSettingGroup("vfoa_grp", "VFO A Settings")
725
        vfob_grp = RadioSettingGroup("vfob_grp", "VFO B Settings")
726
        key_grp = RadioSettingGroup("key_grp", "Key Settings")
727
        lmt_grp = RadioSettingGroup("lmt_grp", "Frequency Limits")
728
        uhf_lmt_grp = RadioSettingGroup("uhf_lmt_grp", "UHF")
729
        vhf_lmt_grp = RadioSettingGroup("vhf_lmt_grp", "VHF")
730
        oem_grp = RadioSettingGroup("oem_grp", "OEM Info")
731

    
732
        lmt_grp.append(vhf_lmt_grp);
733
        lmt_grp.append(uhf_lmt_grp);
734
        group = RadioSettings(cfg_grp, vfoa_grp, vfob_grp,
735
                              key_grp, lmt_grp, oem_grp)
736

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

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

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

    
956
                #
957
        # Key Settings
958
        #
959
        _msg = str(_settings.dispstr).split("\0")[0]
960
        val = RadioSettingValueString(0, 15, _msg)
961
        val.set_mutable(True)
962
        rs = RadioSetting("dispstr", "Display Message", val)
963
        key_grp.append(rs)
964

    
965
        dtmfchars = "0123456789"
966
        _codeobj = _settings.ani_code
967
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x0A])
968
        val = RadioSettingValueString(3, 6, _code, False)
969
        val.set_charset(dtmfchars)
970
        rs = RadioSetting("ani_code", "ANI Code", val)
971
        def apply_ani_id(setting, obj):
972
            value = []
973
            for j in range(0, 6):
974
                try:
975
                    value.append(dtmfchars.index(str(setting.value)[j]))
976
                except IndexError:
977
                    value.append(0xFF)
978
            obj.ani_code = value
979
        rs.set_apply_callback(apply_ani_id, _settings)
980
        key_grp.append(rs)
981

    
982
        rs = RadioSetting("pf1_func", "PF1 Key function",
983
                          RadioSettingValueList(
984
                              PF1KEY_LIST,
985
                              PF1KEY_LIST[_settings.pf1_func]))
986
        key_grp.append(rs)
987
        rs = RadioSetting("pf3_func", "PF3 Key function",
988
                          RadioSettingValueList(
989
                              PF3KEY_LIST,
990
                              PF3KEY_LIST[_settings.pf3_func]))
991
        key_grp.append(rs)
992

    
993
        #
994
        # Limits settings
995
        #
996
        rs = RadioSetting("vhf_limits.rx_start", "VHF RX Lower Limit",
997
                          RadioSettingValueInteger(
998
                              134000000, 174997500,
999
                              self._memobj.vhf_limits.rx_start * 10, 5000))
1000
        vhf_lmt_grp.append(rs)
1001
        rs = RadioSetting("vhf_limits.rx_stop", "VHF RX Upper Limit",
1002
                          RadioSettingValueInteger(
1003
                              134000000, 174997500,
1004
                              self._memobj.vhf_limits.rx_stop * 10, 5000))
1005
        vhf_lmt_grp.append(rs)
1006
        rs = RadioSetting("vhf_limits.tx_start", "VHF TX Lower Limit",
1007
                          RadioSettingValueInteger(
1008
                              134000000, 174997500,
1009
                              self._memobj.vhf_limits.tx_start * 10, 5000))
1010
        vhf_lmt_grp.append(rs)
1011
        rs = RadioSetting("vhf_limits.tx_stop", "VHF TX Upper Limit",
1012
                          RadioSettingValueInteger(
1013
                              134000000, 174997500,
1014
                              self._memobj.vhf_limits.tx_stop * 10, 5000))
1015
        vhf_lmt_grp.append(rs)
1016

    
1017
        rs = RadioSetting("uhf_limits.rx_start", "UHF RX Lower Limit",
1018
                          RadioSettingValueInteger(
1019
                              400000000, 520000000,
1020
                              self._memobj.uhf_limits.rx_start * 10, 5000))
1021
        uhf_lmt_grp.append(rs)
1022
        rs = RadioSetting("uhf_limits.rx_stop", "UHF RX Upper Limit",
1023
                          RadioSettingValueInteger(
1024
                              400000000, 520000000,
1025
                              self._memobj.uhf_limits.rx_stop * 10, 5000))
1026
        uhf_lmt_grp.append(rs)
1027
        rs = RadioSetting("uhf_limits.tx_start", "UHF TX Lower Limit",
1028
                          RadioSettingValueInteger(
1029
                              400000000, 520000000,
1030
                              self._memobj.uhf_limits.tx_start * 10, 5000))
1031
        uhf_lmt_grp.append(rs)
1032
        rs = RadioSetting("uhf_limits.tx_stop", "UHF TX Upper Limit",
1033
                          RadioSettingValueInteger(
1034
                              400000000, 520000000,
1035
                              self._memobj.uhf_limits.tx_stop * 10, 5000))
1036
        uhf_lmt_grp.append(rs)
1037

    
1038
        #
1039
        # OEM info
1040
        #
1041
        def _decode(lst):
1042
            _str = ''.join([chr(c) for c in lst
1043
                            if chr(c) in chirp_common.CHARSET_ASCII])
1044
            return _str
1045

    
1046
        def do_nothing(setting, obj):
1047
            return
1048

    
1049
        _str = _decode(self._memobj.oem_info.model)
1050
        val = RadioSettingValueString(0, 15, _str)
1051
        val.set_mutable(False)
1052
        rs = RadioSetting("oem_info.model", "Model", val)
1053
        rs.set_apply_callback(do_nothing, _settings)
1054
        oem_grp.append(rs)
1055
        _str = _decode(self._memobj.oem_info.oem1)
1056
        val = RadioSettingValueString(0, 15, _str)
1057
        val.set_mutable(False)
1058
        rs = RadioSetting("oem_info.oem1", "OEM String 1", val)
1059
        rs.set_apply_callback(do_nothing, _settings)
1060
        oem_grp.append(rs)
1061
        _str = _decode(self._memobj.oem_info.oem2)
1062
        val = RadioSettingValueString(0, 15, _str)
1063
        val.set_mutable(False)
1064
        rs = RadioSetting("oem_info.oem2", "OEM String 2", val)
1065
        rs.set_apply_callback(do_nothing, _settings)
1066
        oem_grp.append(rs)
1067
        _str = _decode(self._memobj.oem_info.version)
1068
        val = RadioSettingValueString(0, 15, _str)
1069
        val.set_mutable(False)
1070
        rs = RadioSetting("oem_info.version", "Software Version", val)
1071
        rs.set_apply_callback(do_nothing, _settings)
1072
        oem_grp.append(rs)
1073
        _str = _decode(self._memobj.oem_info.date)
1074
        val = RadioSettingValueString(0, 15, _str)
1075
        val.set_mutable(False)
1076
        rs = RadioSetting("oem_info.date", "OEM Date", val)
1077
        rs.set_apply_callback(do_nothing, _settings)
1078
        oem_grp.append(rs)
1079

    
1080
        return group
1081

    
1082
    def get_settings(self):
1083
        try:
1084
            return self._get_settings()
1085
        except:
1086
            import traceback
1087
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1088
            return None
1089

    
1090
    def set_settings(self, settings):
1091
        for element in settings:
1092
            if not isinstance(element, RadioSetting):
1093
                self.set_settings(element)
1094
                continue
1095
            else:
1096
                try:
1097
                    if "." in element.get_name():
1098
                        bits = element.get_name().split(".")
1099
                        obj = self._memobj
1100
                        for bit in bits[:-1]:
1101
                            obj = getattr(obj, bit)
1102
                        setting = bits[-1]
1103
                    else:
1104
                        obj = self._memobj.settings
1105
                        setting = element.get_name()
1106

    
1107
                    if element.has_apply_callback():
1108
                        LOG.debug("Using apply callback")
1109
                        element.run_apply_callback()
1110
                    else:
1111
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1112
                        if self._is_freq(element):
1113
                            setattr(obj, setting, int(element.value)/10)
1114
                        else:
1115
                            setattr(obj, setting, element.value)
1116
                except Exception, e:
1117
                    LOG.debug(element.get_name())
1118
                    raise
1119

    
1120
    def _is_freq(self, element):
1121
        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()
(1-1/18)