Project

General

Profile

New Model #9489 » kg935g MRT test b1.3.py

KG935G Beta 1.3 driver - Mel Terechenok, 07/27/2022 10:43 PM

 
1
# MRT 935G BETA1.3 - Update to handle 935G
2
# MRT Mapped most Wouxon CPS settings in Chirp
3
# MRT Upload to Radio and Download from Radio are working
4
# MRT Settings are available under the Browser tab in Hex/Dec/Bin format
5
# MRT No limits or error checking is done on values entered
6
# MRT Incorrect/Invalid values may cause radio malfunctions
7
# MRT 
8

    
9

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

    
29
"""Wouxun KG-935G radio management module"""
30

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

    
40

    
41
LOG = logging.getLogger(__name__)
42

    
43
CMD_ID = 128    # \x80
44
CMD_END = 129   # \x81
45
CMD_RD = 130    # \82
46
CMD_WR = 131    # \83
47

    
48
MEM_VALID = 158
49

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

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

    
85
# MRT made Power = 2 bits to handle 935G's 3 power levels
86
# MRT beta 1.3 - updates to structure to match KG935G Custom programming SW configuration settings, FM Radio presets, Key Settings
87
_MEM_FORMAT = """
88
    #seekto 0x0044;
89
    struct {
90
        u32    rx_start;
91
        u32    rx_stop;
92
        u32    tx_start;
93
        u32    tx_stop;
94
    } uhf_limits;
95

    
96
    #seekto 0x0054;
97
    struct {
98
        u32    rx_start;
99
        u32    rx_stop;
100
        u32    tx_start;
101
        u32    tx_stop;
102
    } vhf_limits;
103

    
104
    #seekto 0x0400;
105
    struct {
106
        char     oem1[8];
107
        char     unknown[2];
108
        u8     unknown2[10];
109
        u8     unknown3[10];
110
        u8     unknown4[8];
111
        char     oem2[10];
112
        u8     version[6];
113
        char     date[8];
114
        u8     unknown5[2];
115
        char     model[8];     
116
    } oem_info;
117

    
118
    #seekto 0x0480;
119
    struct {
120
        u16    lower;
121
        u16    upper;
122
    } scan_groups[10];
123

    
124
    #seekto 0x0500;
125
    struct {
126
        u8    call_code[6];
127
    } call_groups[20];
128

    
129
    #seekto 0x0580;
130
    struct {
131
        u8    call_name[6];
132
    } call_group_name[20];
133

    
134
#seekto 0x0600;
135
    struct {
136
        u16    FM_radio1;
137
        u16    FM_radio2;
138
        u16    FM_radio3;
139
        u16    FM_radio4;
140
        u16    FM_radio5;
141
        u16    FM_radio6;
142
        u16    FM_radio7;
143
        u16    FM_radio8;
144
        u16    FM_radio9;
145
        u16    FM_radio10;
146
        u16    FM_radio11;
147
        u16    FM_radio12;
148
        u16    FM_radio13;
149
        u16    FM_radio14;
150
        u16    FM_radio15;
151
        u16    FM_radio16;
152
        u16    FM_radio17;
153
        u16    FM_radio18;
154
        u16    FM_radio19;
155
        u16    FM_radio20;
156
    } FM_radio_presets;
157

    
158
    #seekto 0x0800;
159
    struct {
160
        u8      ponmsg;
161
        char    dispstr[15];
162
        u8 unknown0810;
163
        u8 unknown0811;
164
        u8 unknown0812;
165
        u8 unknown0813;
166
        u8 unknown0814;
167
        u8      voice;
168
        u8      tot;
169
        u8      toa;
170
        u8      channel_menu;
171
        u8      bat_saver;
172
        u8      autolock;
173
        u8      keylock;
174
        u8      key_beep;
175
        u8      timer;
176
        u8      vox;
177
        u8      scan_mode;
178
        u8      bklt_act_time;
179
        u8      roger_beep;
180
        char      node_sw_pwd[6];
181
        char      reset_pwd[6];
182
        u8 unknown082e;
183
        u8      pri_ch;
184
        u8      ani_sw;
185
        u8      ptt_delay;
186
        u8      ani_code[6];
187
        u8      sidetone;
188
        u8      BCL_A;
189
        u8      BCL_B;
190
        u8      ptt_id;
191
        u8      pri_ch_scn;
192
        u8 unknown083d;
193
        u8 unknown083e;
194
        u8 unknown083f;
195
        u8      alert_tone;
196
        u8      pf1_shrt;
197
        u8      pf1_long;
198
        u8      pf2_shrt;
199
        u8      pf2_long;
200
        u8 unknown0845;
201
        u8      work_mode_a;
202
        u8      work_mode_b;
203
        u8      DTMF_Trans_time;
204
        u8      DTMF_Interval_time;
205
        u8      main_band;
206
        u8 unknown084b;
207
        u8      work_ch_a;
208
        u8 unknown084d;
209
        u8      work_ch_b;
210
        u8 unknown084f;
211
        u8 unknown0850;
212
        u8 unknown0851;
213
        u8 unknown0852;
214
        u8 unknown0853;
215
        u8 unknown0854;
216
        u8 unknown0855;
217
        u8 unknown0856;
218
        u8 unknown0857;
219
        u8 unknown0858;
220
        u8 unknown0859;
221
        u8 unknown085a;
222
        u8 unknown085b;
223
        u8 unknown085c;
224
        u8 unknown085d;
225
        u8 unknown085e;
226
        u8 unknown085f;
227
        u8 unknown0860;
228
        u8      TDR_single_mode;
229
        u8      ring;
230
        u8      ScnGrpA_Act;
231
        u8      ScnGrpB_Act;
232
        u8 unknown0865;
233
        u8      rpt_tone;
234
        u8 unknown0867;
235
        u8      ScnModeToneDet;
236
        u8      ToneScnSave;
237
        u8 unknown086a;
238
        u8      smuteset;
239
        u8 unknown086c;
240
        u8      DspBrtAct;
241
        u8      DspBrtSby;
242
        u8 unknown086f;
243
        u8      Theme;
244
        u8      Wx_Alert;
245
        u8      VFO_repeater_a;
246
        u8      VFO_repeater_b;
247
        u8 unknown0874;
248
        u8 unknown0875;
249
        u8 unknown0876;
250
        u8 unknown0877;
251
        u8 unknown0878;
252
        u8 unknown0879;
253
        u8 unknown087a;
254
        u8 unknown087b;
255
        u8 unknown087c;
256
        u8 unknown087d;
257
        u8 unknown087e;
258
        u8 unknown087f;
259
    } settings;
260

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

    
280
    #seekto 0x08c0;
281
    struct {
282
        u32     rxfreq;
283
        u32     unknown0;
284
        u16     rxtone;
285
        u16     txtone;
286
        u8      scrambler:4,
287
                unknown1:2,
288
                power:2; 
289
        u8      unknown3:1,
290
                unknown5:2
291
                unknown4:1,
292
                compander:1,
293
                mute_mode:2,
294
                iswide:1;
295
        u8      step;
296
        u8      squelch;
297
    } vfob;
298

    
299
    #seekto 0x0900;
300
    struct {
301
        u32     rxfreq;
302
        u32     txfreq;
303
        u16     rxtone;
304
        u16     txtone;
305
        u8      scrambler:4,
306
                unknown1:2,
307
                power:2; 
308
        u8      unknown3:2,
309
                scan_add:1,
310
                unknown4:1,
311
                compander:1,
312
                mute_mode:2,
313
                iswide:1;
314
        u16     padding;
315
    } memory[1000];
316

    
317
    #seekto 0x4780;
318
    struct {
319
        u8    name[8];
320
                u8    unknown[4];
321
    } names[1000];
322

    
323
    #seekto 0x7670;
324
    u8          valid[1000];
325
    """
326

    
327
    # Support for the Wouxun KG-935G radio
328
    # Serial coms are at 19200 baud
329
    # The data is passed in variable length records
330
    # Record structure:
331
    #  Offset   Usage
332
    #    0      start of record (\x7c)
333
    #    1      Command (\x80 Identify \x81 End/Reboot \x82 Read \x83 Write)
334
    #    2      direction (\xff PC-> Radio, \x00 Radio -> PC)
335
    #    3      length of payload (excluding header/checksum) (n)
336
    #    4      payload (n bytes)
337
    #    4+n+1  checksum - byte sum (% 256) of bytes 1 -> 4+n
338
    #
339
    # Memory Read Records:
340
    # the payload is 3 bytes, first 2 are offset (big endian),
341
    # 3rd is number of bytes to read
342
    # Memory Write Records:
343
    # the maximum payload size (from the Wouxun software) seems to be 66 bytes
344
    #  (2 bytes location + 64 bytes data).
345

    
346
#MRT 1.2 correct spelling of Wouxon
347
class KGUV8TRadio(chirp_common.Alias):
348
    VENDOR = "Wouxun"
349
    MODEL = "KG-935G"
350

    
351
@directory.register
352
class KG935GRadio(chirp_common.CloneModeRadio,
353
                  chirp_common.ExperimentalRadio):
354

    
355
    """Wouxun KG-935G"""
356
    VENDOR = "Wouxun"
357
    MODEL = "KG-935G"
358
    _model = "KG-UV8D-B"
359
    _file_ident = "935G"
360
    BAUD_RATE = 19200
361
# MRT - Added Medium Power level for 935G support
362
    POWER_LEVELS = [chirp_common.PowerLevel("L", watts=0.5),
363
                    chirp_common.PowerLevel("M", watts=4.5),
364
                    chirp_common.PowerLevel("H", watts=5.5)]
365
    _mmap = ""
366
    ALIASES = [KGUV8TRadio,]
367

    
368
    def _checksum(self, data):
369
        cs = 0
370
        for byte in data:
371
            cs += ord(byte)
372
        return chr(cs % 256)
373

    
374
    def _write_record(self, cmd, payload = None):
375
        # build the packet
376
        _header = '\x7c' + chr(cmd) + '\xff'
377

    
378
        _length = 0
379
        if payload:
380
            _length = len(payload)
381

    
382
        # update the length field
383
        _header += chr(_length)
384

    
385
        if payload:
386
            # calculate checksum then add it with the payload to the packet and encrypt
387
            crc = self._checksum(_header[1:] + payload)
388
            payload += crc
389
            _header += self.encrypt(payload)
390
        else:
391
            # calculate and add encrypted checksum to the packet
392
            crc = self._checksum(_header[1:])
393
            _header += self.strxor(crc, '\x57')
394

    
395
        try:
396
            self.pipe.write(_header)
397
        except Exception, e:
398
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
399

    
400
    def _read_record(self):
401
        # read 4 chars for the header
402
        _header = self.pipe.read(4)
403
        if len(_header) != 4:
404
            raise errors.RadioError('Radio did not respond')
405
        _length = ord(_header[3])
406
        _packet = self.pipe.read(_length)
407
        _rcs_xor = _packet[-1]
408
        _packet = self.decrypt(_packet)
409
        _cs = ord(self._checksum(_header[1:] + _packet))
410
        # read the checksum and decrypt it
411
        _rcs = ord(self.strxor(self.pipe.read(1), _rcs_xor))
412
        return (_rcs != _cs, _packet)
413

    
414
    def decrypt(self, data):
415
        result = ''
416
        for i in range(len(data)-1, 0, -1):
417
            result += self.strxor(data[i], data[i - 1])
418
        result += self.strxor(data[0], '\x57')
419
        return result[::-1]
420

    
421
    def encrypt(self, data):
422
        result = self.strxor('\x57', data[0])
423
        for i in range(1, len(data), 1):
424
            result += self.strxor(result[i - 1], data[i])
425
        return result
426

    
427
    def strxor (self, xora, xorb):
428
        return chr(ord(xora) ^ ord(xorb))
429

    
430
    # Identify the radio
431
    #
432
    # A Gotcha: the first identify packet returns a bad checksum, subsequent
433
    # attempts return the correct checksum... (well it does on my radio!)
434
    #
435
    # The ID record returned by the radio also includes the current frequency range
436
    # as 4 bytes big-endian in 10Hz increments
437
    #
438
    # Offset
439
    #  0:10     Model, zero padded (Looks for 'KG-UV8D-B')
440

    
441
    @classmethod
442
    def match_model(cls, filedata, filename):
443
        id = cls._file_ident 
444
        return cls._file_ident in filedata[0x426:0x430]
445

    
446
    def _identify(self):
447
        """Do the identification dance"""
448
        for _i in range(0, 10):
449
            self._write_record(CMD_ID)
450
            _chksum_err, _resp = self._read_record()
451
            LOG.debug("Got:\n%s" % util.hexprint(_resp))
452
            if _chksum_err:
453
                LOG.error("Checksum error: retrying ident...")
454
                time.sleep(0.100)
455
                continue
456
            LOG.debug("Model %s" % util.hexprint(_resp[0:9]))
457
            if _resp[0:9] == self._model:
458
                return
459
            if len(_resp) == 0:
460
                raise Exception("Radio not responding")
461
            else:
462
                raise Exception("Unable to identify radio")
463

    
464
    def _finish(self):
465
        self._write_record(CMD_END)
466

    
467
    def process_mmap(self):
468
        self._memobj = bitwise.parse(_MEM_FORMAT, self._mmap)
469

    
470
    def sync_in(self):
471
        try:
472
            self._mmap = self._download()
473
        except errors.RadioError:
474
            raise
475
        except Exception, e:
476
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
477
        self.process_mmap()
478

    
479
    def sync_out(self):
480
        self._upload()
481

    
482
    # TODO: Load all memory.
483
    # It would be smarter to only load the active areas and none of
484
    # the padding/unused areas. Padding still need to be investigated.
485
    def _download(self):
486
        """Talk to a wouxun KG-935G and do a download"""
487
        try:
488
            self._identify()
489
            return self._do_download(0, 32768, 64)
490
        except errors.RadioError:
491
            raise
492
        except Exception, e:
493
            LOG.exception('Unknown error during download process')
494
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
495

    
496
    def _do_download(self, start, end, blocksize):
497
        # allocate & fill memory
498
        image = ""
499
        for i in range(start, end, blocksize):
500
            req = chr(i / 256) + chr(i % 256) + chr(blocksize)
501
            self._write_record(CMD_RD, req)
502
            cs_error, resp = self._read_record()
503
            if cs_error:
504
                LOG.debug(util.hexprint(resp))
505
                raise Exception("Checksum error on read")
506
            # LOG.debug("Got:\n%s" % util.hexprint(resp))
507
            image += resp[2:]
508
            if self.status_fn:
509
                status = chirp_common.Status()
510
                status.cur = i
511
                status.max = end
512
                status.msg = "Cloning from radio"
513
                self.status_fn(status)
514
        self._finish()
515
        return memmap.MemoryMap(''.join(image))
516

    
517
    def _upload(self):
518
        """Talk to a wouxun KG-935G and do a upload"""
519
        try:
520
            self._identify()
521
            self._do_upload(0, 32768, 64)
522
        except errors.RadioError:
523
            raise
524
        except Exception, e:
525
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
526
        return
527

    
528
    def _do_upload(self, start, end, blocksize):
529
        ptr = start
530
        for i in range(start, end, blocksize):
531
            req = chr(i / 256) + chr(i % 256)
532
            chunk = self.get_mmap()[ptr:ptr + blocksize]
533
            self._write_record(CMD_WR, req + chunk)
534
            LOG.debug(util.hexprint(req + chunk))
535
            cserr, ack = self._read_record()
536
            LOG.debug(util.hexprint(ack))
537
            j = ord(ack[0]) * 256 + ord(ack[1])
538
            if cserr or j != ptr:
539
                raise Exception("Radio did not ack block %i" % ptr)
540
            ptr += blocksize
541
            if self.status_fn:
542
                status = chirp_common.Status()
543
                status.cur = i
544
                status.max = end
545
                status.msg = "Cloning to radio"
546
                self.status_fn(status)
547
        self._finish()
548

    
549
    def get_features(self):
550
        rf = chirp_common.RadioFeatures()
551
        rf.has_settings = True
552
        rf.has_ctone = True
553
        rf.has_rx_dtcs = True
554
        rf.has_cross = True
555
        rf.has_tuning_step = False
556
        rf.has_bank = False
557
        rf.can_odd_split = True
558
        rf.valid_skips = ["", "S"]
559
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
560
        rf.valid_cross_modes = [
561
            "Tone->Tone",
562
            "Tone->DTCS",
563
            "DTCS->Tone",
564
            "DTCS->",
565
            "->Tone",
566
            "->DTCS",
567
            "DTCS->DTCS",
568
        ]
569
        rf.valid_modes = ["FM", "NFM"]
570
        rf.valid_power_levels = self.POWER_LEVELS
571
        rf.valid_name_length = 8
572
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
573
        rf.valid_bands = [(137000000, 175000000),  # supports 2m
574
                          (400000000, 480000000)]  # supports 70cm
575
        rf.valid_characters = chirp_common.CHARSET_ASCII
576
        rf.memory_bounds = (1, 999)  # 999 memories
577
        rf.valid_tuning_steps = STEPS
578
        return rf
579

    
580
    @classmethod
581
    def get_prompts(cls):
582
        rp = chirp_common.RadioPrompts()
583
        rp.experimental = \
584
            ('This driver is experimental.\n'
585
             '\n'
586
             'Please keep a copy of your memories with the original Wouxon CPS software '
587
             'if you treasure them, this driver is new and may contain bugs.\n'
588
             '\n'
589
             ' Upload and Download from/to the Radio are working\n'
590
             ' This driver provides access to KG935G settings from the\n browser tab in Hex/Dec/Bin'
591
             ' format.\n Implementation of a better UI is still in development. \n Most of the settings from the Wouxon Custom Programming'
592
             ' software have been mapped\n in addition to some bonus settings that were'
593
             ' found.\n'
594
             ' Changing the VHF/UHF limits does appear to work - but radio performance\n'
595
             ' is not guaranteed-  and may void warranty or cause radio to malfunction.\n'
596
             ' You can also customize the bottom banner from the OEMINFO Model setting\n'
597
                          ' \n'
598
             ' There are no limits/error checking done on the settings.\n'
599
             ' \n'
600
             ' Incorrect/Illegal values for a setting may cause radio malfunctions\n'
601
             ' USE AT YOUR OWN RISK\n'
602
             '\n'
603
             )
604
        return rp
605

    
606
    def get_raw_memory(self, number):
607
        return repr(self._memobj.memory[number])
608
# MRT - corrected the Polarity decoding to match 935G implementation use 0x2000 bit mask for R
609
# MRT - 0x2000 appears to be the bit mask for Inverted DCS tones
610
# MRT - n DCS Tone will be 0x4xxx values - i DCS Tones will be 0x6xxx values.
611
# MRT - Chirp Uses N for n DCS Tones and R for i DCS Tones
612
    def _get_tone(self, _mem, mem):
613
        def _get_dcs(val):
614
            code = int("%03o" % (val & 0x07FF))
615
            pol = (val & 0x2000) and "R" or "N"
616
            return code, pol
617
# MRT - Modified the function below to bitwise AND with 0x4000 to check for 935G DCS Tone decoding
618
# MRT 0x4000 appears to be the bit mask for DCS tones
619
        tpol = False
620
# MRT Beta 1.1 - Fix the txtone compare to 0x4000 - was rxtone.
621
        if _mem.txtone != 0xFFFF and (_mem.txtone & 0x4000) == 0x4000:
622
            tcode, tpol = _get_dcs(_mem.txtone)
623
            mem.dtcs = tcode
624
            txmode = "DTCS"
625
        elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
626
            mem.rtone = (_mem.txtone & 0x7fff) / 10.0
627
            txmode = "Tone"
628
        else:
629
            txmode = ""
630
# MRT - Modified the function below to bitwise AND with 0x4000 to check for 935G DCS Tone decoding
631
        rpol = False
632
        if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x4000) == 0x4000:
633
            rcode, rpol = _get_dcs(_mem.rxtone)
634
            mem.rx_dtcs = rcode
635
            rxmode = "DTCS"
636
        elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
637
            mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
638
            rxmode = "Tone"
639
        else:
640
            rxmode = ""
641

    
642
        if txmode == "Tone" and not rxmode:
643
            mem.tmode = "Tone"
644
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
645
            mem.tmode = "TSQL"
646
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
647
            mem.tmode = "DTCS"
648
        elif rxmode or txmode:
649
            mem.tmode = "Cross"
650
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
651

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

    
655
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
656
                  (txmode, _mem.txtone, rxmode, _mem.rxtone))
657

    
658
    def get_memory(self, number):
659
        _mem = self._memobj.memory[number]
660
        _nam = self._memobj.names[number]
661

    
662
        mem = chirp_common.Memory()
663
        mem.number = number
664
        _valid = self._memobj.valid[mem.number]
665
        LOG.debug("%d %s", number, _valid == MEM_VALID)
666
        if _valid != MEM_VALID:
667
            mem.empty = True
668
            return mem
669
        else:
670
            mem.empty = False
671

    
672
        mem.freq = int(_mem.rxfreq) * 10
673

    
674
        if _mem.txfreq == 0xFFFFFFFF:
675
            # TX freq not set
676
            mem.duplex = "off"
677
            mem.offset = 0
678
        elif int(_mem.rxfreq) == int(_mem.txfreq):
679
            mem.duplex = ""
680
            mem.offset = 0
681
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
682
            mem.duplex = "split"
683
            mem.offset = int(_mem.txfreq) * 10
684
        else:
685
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
686
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
687

    
688
        for char in _nam.name:
689
            if char != 0:
690
                mem.name += chr(char)
691
        mem.name = mem.name.rstrip()
692

    
693
        self._get_tone(_mem, mem)
694

    
695
        mem.skip = "" if bool(_mem.scan_add) else "S"
696

    
697
        mem.power = self.POWER_LEVELS[_mem.power]
698
        mem.mode = _mem.iswide and "FM" or "NFM"
699
        return mem
700

    
701
    def _set_tone(self, mem, _mem):
702
        def _set_dcs(code, pol):
703
#MRT Change from + 0x2800 to bitwise OR with 0x4000 to set the bit for DCS
704
            val = int("%i" % code, 8) | 0x4000
705
            if pol == "R":
706
#MRT Change to 0x2000 from 0x8000 to set the bit for i/R polarity
707
               val += 0x2000
708
            return val
709

    
710
        rx_mode = tx_mode = None
711
        rxtone = txtone = 0x0000
712

    
713
        if mem.tmode == "Tone":
714
            tx_mode = "Tone"
715
            rx_mode = None
716
            txtone = int(mem.rtone * 10) + 0x8000
717
        elif mem.tmode == "TSQL":
718
            rx_mode = tx_mode = "Tone"
719
            rxtone = txtone = int(mem.ctone * 10) + 0x8000
720
        elif mem.tmode == "DTCS":
721
            tx_mode = rx_mode = "DTCS"
722
            txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
723
            rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
724
        elif mem.tmode == "Cross":
725
            tx_mode, rx_mode = mem.cross_mode.split("->")
726
            if tx_mode == "DTCS":
727
                txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
728
            elif tx_mode == "Tone":
729
                txtone = int(mem.rtone * 10) + 0x8000
730
            if rx_mode == "DTCS":
731
                rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
732
            elif rx_mode == "Tone":
733
                rxtone = int(mem.ctone * 10) + 0x8000
734

    
735
        _mem.rxtone = rxtone
736
        _mem.txtone = txtone
737

    
738
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
739
                  (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
740

    
741
    def set_memory(self, mem):
742
        number = mem.number
743

    
744
        _mem = self._memobj.memory[number]
745
        _nam = self._memobj.names[number]
746

    
747
        if mem.empty:
748
            _mem.set_raw("\x00" * (_mem.size() / 8))
749
            self._memobj.valid[number] = 0
750
            self._memobj.names[number].set_raw("\x00" * (_nam.size() / 8))
751
            return
752

    
753
        _mem.rxfreq = int(mem.freq / 10)
754
        if mem.duplex == "off":
755
            _mem.txfreq = 0xFFFFFFFF
756
        elif mem.duplex == "split":
757
            _mem.txfreq = int(mem.offset / 10)
758
        elif mem.duplex == "off":
759
            for i in range(0, 4):
760
                _mem.txfreq[i].set_raw("\xFF")
761
        elif mem.duplex == "+":
762
            _mem.txfreq = int(mem.freq / 10) + int(mem.offset / 10)
763
        elif mem.duplex == "-":
764
            _mem.txfreq = int(mem.freq / 10) - int(mem.offset / 10)
765
        else:
766
            _mem.txfreq = int(mem.freq / 10)
767
        _mem.scan_add = int(mem.skip != "S")
768
        _mem.iswide = int(mem.mode == "FM")
769
        # set the tone
770
        self._set_tone(mem, _mem)
771
        # set the scrambler and compander to off by default
772
        _mem.scrambler = 0
773
        _mem.compander = 0
774
        # set the power
775
        if mem.power:
776
            _mem.power = self.POWER_LEVELS.index(mem.power)
777
        else:
778
            _mem.power = True
779
        # set to mute mode to QT (not QT+DTMF or QT*DTMF) by default
780
        _mem.mute_mode = 0
781

    
782
        for i in range(0, len(_nam.name)):
783
            if i < len(mem.name) and mem.name[i]:
784
                _nam.name[i] = ord(mem.name[i])
785
            else:
786
                _nam.name[i] = 0x0
787
        self._memobj.valid[mem.number] = MEM_VALID
788

    
789
    def _get_settings(self):
790
        _settings = self._memobj.settings
791
        _vfoa = self._memobj.vfoa
792
        _vfob = self._memobj.vfob
793
        cfg_grp = RadioSettingGroup("cfg_grp", "Configuration")
794
        vfoa_grp = RadioSettingGroup("vfoa_grp", "VFO A Settings")
795
        vfob_grp = RadioSettingGroup("vfob_grp", "VFO B Settings")
796
        key_grp = RadioSettingGroup("key_grp", "Key Settings")
797
        lmt_grp = RadioSettingGroup("lmt_grp", "Frequency Limits")
798
        uhf_lmt_grp = RadioSettingGroup("uhf_lmt_grp", "UHF")
799
        vhf_lmt_grp = RadioSettingGroup("vhf_lmt_grp", "VHF")
800
        oem_grp = RadioSettingGroup("oem_grp", "OEM Info")
801

    
802
        lmt_grp.append(vhf_lmt_grp);
803
        lmt_grp.append(uhf_lmt_grp);
804
        group = RadioSettings(cfg_grp, vfoa_grp, vfob_grp,
805
                              key_grp, lmt_grp, oem_grp)
806

    
807
        #
808
        # Configuration Settings
809
        #
810
        rs = RadioSetting("channel_menu", "Menu available in channel mode",
811
                          RadioSettingValueBoolean(_settings.channel_menu))
812
        cfg_grp.append(rs)
813
        rs = RadioSetting("ponmsg", "Poweron message",
814
                          RadioSettingValueList(
815
                              PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
816
        cfg_grp.append(rs)
817
        rs = RadioSetting("voice", "Voice Guide",
818
                          RadioSettingValueBoolean(_settings.voice))
819
        cfg_grp.append(rs)
820
        rs = RadioSetting("language", "Language",
821
                         RadioSettingValueList(LANGUAGE_LIST,
822
                                                LANGUAGE_LIST[_settings.
823
                                                              language]))
824
        cfg_grp.append(rs)
825
        rs = RadioSetting("timeout", "Timeout Timer",
826
                          RadioSettingValueList(
827
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
828
        cfg_grp.append(rs)
829
        rs = RadioSetting("toalarm", "Timeout Alarm",
830
                          RadioSettingValueInteger(0, 10, _settings.toalarm))
831
        cfg_grp.append(rs)
832
        rs = RadioSetting("roger_beep", "Roger Beep",
833
                          RadioSettingValueList(ROGER_LIST,
834
                                                ROGER_LIST[_settings.roger_beep]))
835
        cfg_grp.append(rs)
836
        rs = RadioSetting("power_save", "Power save",
837
                          RadioSettingValueBoolean(_settings.power_save))
838
        cfg_grp.append(rs)
839
        rs = RadioSetting("autolock", "Autolock",
840
                          RadioSettingValueBoolean(_settings.autolock))
841
        cfg_grp.append(rs)
842
        rs = RadioSetting("keylock", "Keypad Lock",
843
                          RadioSettingValueBoolean(_settings.keylock))
844
        cfg_grp.append(rs)
845
        rs = RadioSetting("beep", "Keypad Beep",
846
                          RadioSettingValueBoolean(_settings.beep))
847
        cfg_grp.append(rs)
848
        rs = RadioSetting("stopwatch", "Stopwatch",
849
                          RadioSettingValueBoolean(_settings.stopwatch))
850
        cfg_grp.append(rs)
851
        rs = RadioSetting("backlight", "Backlight",
852
                          RadioSettingValueList(BACKLIGHT_LIST,
853
                                                BACKLIGHT_LIST[_settings.
854
                                                               backlight]))
855
        cfg_grp.append(rs)
856
        rs = RadioSetting("dtmf_st", "DTMF Sidetone",
857
                          RadioSettingValueList(DTMFST_LIST,
858
                                                DTMFST_LIST[_settings.
859
                                                            dtmf_st]))
860
        cfg_grp.append(rs)
861
        rs = RadioSetting("ani_sw", "ANI-ID Switch",
862
                          RadioSettingValueBoolean(_settings.ani_sw))
863
        cfg_grp.append(rs)
864
        rs = RadioSetting("ptt_id", "PTT-ID Delay",
865
                          RadioSettingValueList(PTTID_LIST,
866
                                                PTTID_LIST[_settings.ptt_id]))
867
        cfg_grp.append(rs)
868
        rs = RadioSetting("ring_time", "Ring Time",
869
                          RadioSettingValueList(LIST_10,
870
                                                LIST_10[_settings.ring_time]))
871
        cfg_grp.append(rs)
872
        rs = RadioSetting("scan_rev", "Scan Mode",
873
                          RadioSettingValueList(SCANMODE_LIST,
874
                                                SCANMODE_LIST[_settings.
875
                                                              scan_rev]))
876
        cfg_grp.append(rs)
877
        rs = RadioSetting("vox", "VOX",
878
                          RadioSettingValueList(LIST_10,
879
                                                LIST_10[_settings.vox]))
880
        cfg_grp.append(rs)
881
        rs = RadioSetting("prich_sw", "Priority Channel Switch",
882
                          RadioSettingValueBoolean(_settings.prich_sw))
883
        cfg_grp.append(rs)
884
        rs = RadioSetting("pri_ch", "Priority Channel",
885
                          RadioSettingValueInteger(1, 999, _settings.pri_ch))
886
        cfg_grp.append(rs)
887
        rs = RadioSetting("rpt_mode", "Radio Mode",
888
                          RadioSettingValueList(RPTMODE_LIST,
889
                                                RPTMODE_LIST[_settings.
890
                                                             rpt_mode]))
891
        cfg_grp.append(rs)
892
        rs = RadioSetting("rpt_set", "Repeater Setting",
893
                          RadioSettingValueList(RPTSET_LIST,
894
                                                RPTSET_LIST[_settings.
895
                                                            rpt_set]))
896
        cfg_grp.append(rs)
897
        rs = RadioSetting("rpt_spk", "Repeater Mode Speaker",
898
                          RadioSettingValueBoolean(_settings.rpt_spk))
899
        cfg_grp.append(rs)
900
        rs = RadioSetting("rpt_ptt", "Repeater PTT",
901
                          RadioSettingValueBoolean(_settings.rpt_ptt))
902
        cfg_grp.append(rs)
903
        rs = RadioSetting("dtmf_tx_time", "DTMF Tx Duration",
904
                          RadioSettingValueList(DTMF_TIMES,
905
                                                DTMF_TIMES[_settings.
906
                                                           dtmf_tx_time]))
907
        cfg_grp.append(rs)
908
        rs = RadioSetting("dtmf_interval", "DTMF Interval",
909
                          RadioSettingValueList(DTMF_TIMES,
910
                                                DTMF_TIMES[_settings.
911
                                                           dtmf_interval]))
912
        cfg_grp.append(rs)
913
        rs = RadioSetting("alert", "Alert Tone",
914
                          RadioSettingValueList(ALERTS_LIST,
915
                                                ALERTS_LIST[_settings.alert]))
916
        cfg_grp.append(rs)
917
        rs = RadioSetting("rpt_tone", "Repeater Tone",
918
                          RadioSettingValueBoolean(_settings.rpt_tone))
919
        cfg_grp.append(rs)
920
        rs = RadioSetting("rpt_hold", "Repeater Hold Time",
921
                          RadioSettingValueList(HOLD_TIMES,
922
                                                HOLD_TIMES[_settings.
923
                                                           rpt_hold]))
924
        cfg_grp.append(rs)
925
        rs = RadioSetting("scan_det", "Scan DET",
926
                          RadioSettingValueBoolean(_settings.scan_det))
927
        cfg_grp.append(rs)
928
        rs = RadioSetting("sc_qt", "SC-QT",
929
                          RadioSettingValueList(SCQT_LIST,
930
                                                SCQT_LIST[_settings.sc_qt]))
931
        cfg_grp.append(rs)
932
        rs = RadioSetting("smuteset", "SubFreq Mute",
933
                          RadioSettingValueList(SMUTESET_LIST,
934
                                                SMUTESET_LIST[_settings.
935
                                                              smuteset]))
936
        cfg_grp.append(rs)
937

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

    
982
                #
983
        # VFO B Settings
984
        #
985
        rs = RadioSetting("workmode_b", "VFO B Workmode",
986
                          RadioSettingValueList(WORKMODE_LIST, WORKMODE_LIST[_settings.workmode_b]))
987
        vfob_grp.append(rs)
988
        rs = RadioSetting("work_chb", "VFO B Channel",
989
                          RadioSettingValueInteger(1, 999, _settings.work_chb))
990
        vfob_grp.append(rs)
991
        rs = RadioSetting("vfob.rxfreq", "VFO B Rx Frequency",
992
                          RadioSettingValueInteger(
993
                              134000000, 520000000, _vfob.rxfreq * 10, 5000))
994
        vfob_grp.append(rs)
995
        rs = RadioSetting("vfob.txoffset", "VFO B Tx Offset",
996
                          RadioSettingValueInteger(
997
                              0, 520000000, _vfob.txoffset * 10, 5000))
998
        vfob_grp.append(rs)
999
        #   u16   rxtone;
1000
        #   u16   txtone;
1001
        rs = RadioSetting("vfob.power", "VFO B Power",
1002
                          RadioSettingValueList(
1003
                              POWER_LIST, POWER_LIST[_vfob.power]))
1004
        vfob_grp.append(rs)
1005
        #         shift_dir:2
1006
        rs = RadioSetting("vfob.iswide", "VFO B NBFM",
1007
                          RadioSettingValueList(
1008
                              BANDWIDTH_LIST, BANDWIDTH_LIST[_vfob.iswide]))
1009
        vfob_grp.append(rs)
1010
        rs = RadioSetting("vfob.mute_mode", "VFO B Mute",
1011
                          RadioSettingValueList(
1012
                              SPMUTE_LIST, SPMUTE_LIST[_vfob.mute_mode]))
1013
        vfob_grp.append(rs)
1014
        rs = RadioSetting("vfob.step", "VFO B Step (kHz)",
1015
                          RadioSettingValueList(
1016
                              STEP_LIST, STEP_LIST[_vfob.step]))
1017
        vfob_grp.append(rs)
1018
        rs = RadioSetting("vfob.squelch", "VFO B Squelch",
1019
                          RadioSettingValueList(
1020
                              LIST_10, LIST_10[_vfob.squelch]))
1021
        vfob_grp.append(rs)
1022
        rs = RadioSetting("bcl_b", "Busy Channel Lock-out B",
1023
                          RadioSettingValueBoolean(_settings.bcl_b))
1024
        vfob_grp.append(rs)
1025

    
1026
                #
1027
        # Key Settings
1028
        #
1029
        _msg = str(_settings.dispstr).split("\0")[0]
1030
        val = RadioSettingValueString(0, 15, _msg)
1031
        val.set_mutable(True)
1032
        rs = RadioSetting("dispstr", "Display Message", val)
1033
        key_grp.append(rs)
1034

    
1035
        dtmfchars = "0123456789"
1036
        _codeobj = _settings.ani_code
1037
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x0A])
1038
        val = RadioSettingValueString(3, 6, _code, False)
1039
        val.set_charset(dtmfchars)
1040
        rs = RadioSetting("ani_code", "ANI Code", val)
1041
        def apply_ani_id(setting, obj):
1042
            value = []
1043
            for j in range(0, 6):
1044
                try:
1045
                    value.append(dtmfchars.index(str(setting.value)[j]))
1046
                except IndexError:
1047
                    value.append(0xFF)
1048
            obj.ani_code = value
1049
        rs.set_apply_callback(apply_ani_id, _settings)
1050
        key_grp.append(rs)
1051

    
1052
        rs = RadioSetting("pf1_func", "PF1 Key function",
1053
                          RadioSettingValueList(
1054
                              PF1KEY_LIST,
1055
                              PF1KEY_LIST[_settings.pf1_func]))
1056
        key_grp.append(rs)
1057
        rs = RadioSetting("pf3_func", "PF3 Key function",
1058
                          RadioSettingValueList(
1059
                              PF3KEY_LIST,
1060
                              PF3KEY_LIST[_settings.pf3_func]))
1061
        key_grp.append(rs)
1062

    
1063
        #
1064
        # Limits settings
1065
        #
1066
        rs = RadioSetting("vhf_limits.rx_start", "VHF RX Lower Limit",
1067
                          RadioSettingValueInteger(
1068
                              134000000, 174997500,
1069
                              self._memobj.vhf_limits.rx_start * 10, 5000))
1070
        vhf_lmt_grp.append(rs)
1071
        rs = RadioSetting("vhf_limits.rx_stop", "VHF RX Upper Limit",
1072
                          RadioSettingValueInteger(
1073
                              134000000, 174997500,
1074
                              self._memobj.vhf_limits.rx_stop * 10, 5000))
1075
        vhf_lmt_grp.append(rs)
1076
        rs = RadioSetting("vhf_limits.tx_start", "VHF TX Lower Limit",
1077
                          RadioSettingValueInteger(
1078
                              134000000, 174997500,
1079
                              self._memobj.vhf_limits.tx_start * 10, 5000))
1080
        vhf_lmt_grp.append(rs)
1081
        rs = RadioSetting("vhf_limits.tx_stop", "VHF TX Upper Limit",
1082
                          RadioSettingValueInteger(
1083
                              134000000, 174997500,
1084
                              self._memobj.vhf_limits.tx_stop * 10, 5000))
1085
        vhf_lmt_grp.append(rs)
1086

    
1087
        rs = RadioSetting("uhf_limits.rx_start", "UHF RX Lower Limit",
1088
                          RadioSettingValueInteger(
1089
                              400000000, 520000000,
1090
                              self._memobj.uhf_limits.rx_start * 10, 5000))
1091
        uhf_lmt_grp.append(rs)
1092
        rs = RadioSetting("uhf_limits.rx_stop", "UHF RX Upper Limit",
1093
                          RadioSettingValueInteger(
1094
                              400000000, 520000000,
1095
                              self._memobj.uhf_limits.rx_stop * 10, 5000))
1096
        uhf_lmt_grp.append(rs)
1097
        rs = RadioSetting("uhf_limits.tx_start", "UHF TX Lower Limit",
1098
                          RadioSettingValueInteger(
1099
                              400000000, 520000000,
1100
                              self._memobj.uhf_limits.tx_start * 10, 5000))
1101
        uhf_lmt_grp.append(rs)
1102
        rs = RadioSetting("uhf_limits.tx_stop", "UHF TX Upper Limit",
1103
                          RadioSettingValueInteger(
1104
                              400000000, 520000000,
1105
                              self._memobj.uhf_limits.tx_stop * 10, 5000))
1106
        uhf_lmt_grp.append(rs)
1107

    
1108
        #
1109
        # OEM info
1110
        #
1111
        def _decode(lst):
1112
            _str = ''.join([chr(c) for c in lst
1113
                            if chr(c) in chirp_common.CHARSET_ASCII])
1114
            return _str
1115

    
1116
        def do_nothing(setting, obj):
1117
            return
1118

    
1119
        _str = _decode(self._memobj.oem_info.model)
1120
        val = RadioSettingValueString(0, 15, _str)
1121
        val.set_mutable(False)
1122
        rs = RadioSetting("oem_info.model", "Model", val)
1123
        rs.set_apply_callback(do_nothing, _settings)
1124
        oem_grp.append(rs)
1125
        _str = _decode(self._memobj.oem_info.oem1)
1126
        val = RadioSettingValueString(0, 15, _str)
1127
        val.set_mutable(False)
1128
        rs = RadioSetting("oem_info.oem1", "OEM String 1", val)
1129
        rs.set_apply_callback(do_nothing, _settings)
1130
        oem_grp.append(rs)
1131
        _str = _decode(self._memobj.oem_info.oem2)
1132
        val = RadioSettingValueString(0, 15, _str)
1133
        val.set_mutable(False)
1134
        rs = RadioSetting("oem_info.oem2", "OEM String 2", val)
1135
        rs.set_apply_callback(do_nothing, _settings)
1136
        oem_grp.append(rs)
1137
        _str = _decode(self._memobj.oem_info.version)
1138
        val = RadioSettingValueString(0, 15, _str)
1139
        val.set_mutable(False)
1140
        rs = RadioSetting("oem_info.version", "Software Version", val)
1141
        rs.set_apply_callback(do_nothing, _settings)
1142
        oem_grp.append(rs)
1143
        _str = _decode(self._memobj.oem_info.date)
1144
        val = RadioSettingValueString(0, 15, _str)
1145
        val.set_mutable(False)
1146
        rs = RadioSetting("oem_info.date", "OEM Date", val)
1147
        rs.set_apply_callback(do_nothing, _settings)
1148
        oem_grp.append(rs)
1149

    
1150
        return group
1151

    
1152
    def get_settings(self):
1153
        try:
1154
            return self._get_settings()
1155
        except:
1156
            import traceback
1157
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1158
            return None
1159

    
1160
    def set_settings(self, settings):
1161
        for element in settings:
1162
            if not isinstance(element, RadioSetting):
1163
                self.set_settings(element)
1164
                continue
1165
            else:
1166
                try:
1167
                    if "." in element.get_name():
1168
                        bits = element.get_name().split(".")
1169
                        obj = self._memobj
1170
                        for bit in bits[:-1]:
1171
                            obj = getattr(obj, bit)
1172
                        setting = bits[-1]
1173
                    else:
1174
                        obj = self._memobj.settings
1175
                        setting = element.get_name()
1176

    
1177
                    if element.has_apply_callback():
1178
                        LOG.debug("Using apply callback")
1179
                        element.run_apply_callback()
1180
                    else:
1181
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1182
                        if self._is_freq(element):
1183
                            setattr(obj, setting, int(element.value)/10)
1184
                        else:
1185
                            setattr(obj, setting, element.value)
1186
                except Exception, e:
1187
                    LOG.debug(element.get_name())
1188
                    raise
1189

    
1190
    def _is_freq(self, element):
1191
        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()
(3-3/18)