Project

General

Profile

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

Mel Terechenok, 08/13/2022 12:00 AM

 
1
# MRT Beta 1.6 
2
#              - ADDED Current Call Group to Call Group settings
3
#              - ADDED VFOA/B rxtone and txtone to VFOA/B Settings
4
#              - ADDED VHF/UHF Tx Freq Limits back into Limit Settings
5
#                   - Radio does not use these values to extend transmit capability
6
#                   - However, the Wouxun CPS uses the Rx/Tx limit values to limit check entries so I added them back in to help maintain
7
#                   - compatibility between CHiRP and Wouxun CPS by allowing the range to be extended to make Wouxun CPS happy when necessary
8
#                   - I recommend keeping the Rx and Tx ranges the same unless all your non-GMRS channels have Tx set to OFF
9
#              - REMOVED PTT Delay option value of 0ms to match Wouxun CPS
10
#              - REMOVED option to select OFF for Active display brightness to match Wouxun CPS
11
#              - REMOVED DTMF transmit time and DTMF Interval time options below 50ms to match Wouxun CPS
12
#              - CORRECTED bug with Transmit Power Level settings to prevent Tx signal strength bar display corruption
13
#                and to ensure radio displays proper Power Level when accessing through radio MENU button after creating a new entry into a previously empty
14
#                Channel Memory location
15
#              - Update Channel Memory to force Unknown parameters to a default value to match what Wouxun CPS
16
#                uses when adding a new channel.
17
#              - CHANGED Memories tab freq limit checks to 30-999.999999 MHz to support ability to change VHF/UHF Rx Freq Limit settings- 
18
#                   - If value specified is outside of VHF/UHF Rx Freq Limit values, a default value will be used by radio
19
#              - general code cleanup 
20
#                   - utilize for loops on the call group settings
21
#                   - remove some outdated code and comments
22
#
23
# MRT Beta 1.5 - Corrected minor typos found in previous versions
24
#              - Made pri_ch,work_ch_a,work_ch_b U16 instead of U8 to fix errors when specifying channel values > 255
25
#              - Changed node_sw_pwd to mode_sw_pwd
26
#              - Added Compander to VFOA and VFOB settings
27
#              - Added Scan Group Upper/Lower to Scan Settings
28
#                    - changed group_x_lower and upper to group_lowerx to support for loop use
29
#              - Added Call Names to the Call Settings
30
#              - Added Mode SW Pwd and Reset Pwd to Config Settings
31
#              - Display FM Radio Presets in proper format / units (MHz)
32
#              - Display VFOA/VFOB/Rx Freq and RX Freq limits in units of MHz
33
#                   VHF freq Limit range is 30 - 299.999999 MHz
34
#                   UHF freq Limit range is 300 - 999.999999 MHz 
35
#                   VFOA/VFOB Freq Range is 30 - 999.999999 MHz
36
# 
37
#              - SETTINGS NOT YET IMPLEMENTED
38
#                   VFOA/VFOB RxTone and TxTone
39
#              - Note:  For channels shown on Memories tab 
40
#                   Compander, Descramble and SP Mute are not currently modifiable through the Memories tab.
41
#                   If any changes are made to a channel's settings, they are always defaulted to Off, Off, QT respectively. 
42
#                   
43

    
44
# MRT Beta 1.4 - updated User Interface to support settings modifications through the settings tab
45
# melvin.terechenok@gmail.com
46

    
47
# MRT 935G BETA1.3 - Update to handle 935G
48
# MRT Mapped most Wouxon CPS settings in Chirp
49
# MRT Upload to Radio and Download from Radio are working
50
# MRT Settings are available under the Browser tab in Hex/Dec/Bin format
51
# MRT No limits or error checking is done on values entered
52
# MRT Incorrect/Invalid values may cause radio malfunctions
53

    
54

    
55

    
56
# Copyright 2019 Pavel Milanes CO7WT <pavelmc@gmail.com>
57
#
58
# Based on the work of Krystian Struzik <toner_82@tlen.pl>
59
# who figured out the crypt used and made possible the
60
# Wuoxun KG-UV8D Plus driver, in which this work is based.
61
#
62
# This program is free software: you can redistribute it and/or modify
63
# it under the terms of the GNU General Public License as published by
64
# the Free Software Foundation, either version 3 of the License, or
65
# (at your option) any later version.
66
#
67
# This program is distributed in the hope that it will be useful,
68
# but WITHOUT ANY WARRANTY; without even the implied warranty of
69
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
70
# GNU General Public License for more details.
71
#
72
# You should have received a copy of the GNU General Public License
73
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
74

    
75
"""Wouxun KG-935G radio management module"""
76

    
77
import time
78
import os
79
import logging
80

    
81
from chirp import util, chirp_common, bitwise, memmap, errors, directory
82
from chirp.settings import RadioSetting, RadioSettingGroup, \
83
    RadioSettingValueBoolean, RadioSettingValueList, \
84
    RadioSettingValueInteger, RadioSettingValueString, \
85
    RadioSettingValueFloat, RadioSettingValueMap, RadioSettings
86

    
87

    
88
LOG = logging.getLogger(__name__)
89

    
90
CMD_ID = 128    # \x80
91
CMD_END = 129   # \x81
92
CMD_RD = 130    # \82
93
CMD_WR = 131    # \83
94

    
95
MEM_VALID = 158
96

    
97
AB_LIST = ["A", "B"]
98
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0, 50.0, 100.0]
99
STEP_LIST = [str(x) for x in STEPS]
100
ROGER_LIST = ["Off", "Begin", "End", "Both"]
101
TIMEOUT_LIST = ["Off"] + [str(x) + "s" for x in range(15, 901, 15)]
102
VOX_LIST = ["Off"] + ["%s" % x for x in range(1, 10)]
103
BANDWIDTH_LIST = ["Narrow", "Wide"]
104
VOICE_LIST = ["Off", "On"]
105
LANGUAGE_LIST = ["Chinese", "English"]
106
SCANMODE_LIST = ["TO", "CO", "SE"]
107
#MRT - EDIT FOR 935G
108
PFKEYLONG_LIST = ["undef", "FRQ2-PTT", "Selec Call", "Scan", "Flashlight", "Alarm", "SOS", "FM Radio", "Moni", "Strobe", "Weather", "Tlk A", "Reverse", "CTC Scan", "DCS Scan", "BRT"]
109
PFKEYSHORT_LIST = ["undef", "Scan", "Flashlight", "Alarm", "SOS", "FM Radio", "Moni", "Strobe", "Weather", "Tlk A", "Reverse", "CTC Scan", "DCS Scan", "BRT"]
110
#
111
WORKMODE_LIST = ["VFO", "Ch.Number.", "Ch.Freq.", "Ch.Name"]
112
BACKLIGHT_LIST = ["Always On"] + [str(x) + "s" for x in range(1, 21)] + \
113
    ["Always Off"]
114
OFFSET_LIST = ["+", "-"]
115
PONMSG_LIST = ["MSG - Bitmap", "Battery Volts"]
116
SPMUTE_LIST = ["QT", "QT+DTMF", "QT*DTMF"]
117
DTMFST_LIST = ["OFF", "DTMF", "ANI", "DTMF+ANI"]
118
# DTMF_TIMES = [str(x) + "ms" for x in range(0, 501, 10)]
119
DTMF_TIMES = [('%dms' % dtmf, (dtmf / 10)) for dtmf in range(50, 501, 10)]
120
RPTSET_LIST = ["", "X-DIRRPT", "X-TWRPT"] # TODO < what is index 0?
121
ALERTS = [1750, 2100, 1000, 1450]
122
ALERTS_LIST = [str(x) for x in ALERTS]
123
PTTID_LIST = ["BOT", "EOT", "Both"]
124
LIST_10 = ["Off"] + ["%s" % x for x in range(1, 11)]
125
SCANGRP_LIST = ["All"] + ["%s" % x for x in range(1, 11)]
126
SCQT_LIST = ["Decoder", "Encoder", "All"]
127
SMUTESET_LIST = ["Off", "Tx", "Rx", "Tx+Rx"]
128
POWER_LIST = ["Lo", "Mid", "Hi"]
129
HOLD_TIMES = ["Off"] + ["%s" % x for x in range(100, 5001, 100)]
130
RPTMODE_LIST = ["Radio", "Repeater"]
131
#MRT ADDED NEW LISTS
132
CALLGROUP_LIST = [str(x) for x in range(1,21)]
133
THEME_LIST = ["White-1", "White-2", "Black-1", "Black-2"]
134
DSPBRTSBY_LIST = ["OFF", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
135
DSPBRTACT_MAP = [ ("1",1), ("2",2), ("3",3), ("4",4), ("5",5), ("6",6) ,("7",7) ,("8",8) ,("9",9) ,("10",10)]
136
TONESCANSAVELIST= ["Rx", "Tx", "Tx/Rx"]
137
# PTTDELAY_LIST = [str(x) + "ms" for x in range(0, 3001, 100)]
138
PTTDELAY_TIMES = [('%dms' % pttdelay, (pttdelay / 100)) for pttdelay in range(100, 3001, 100)]
139
SCRAMBLE_LIST = ["OFF"] + [str(x) for x in range(1,9)]
140
ONOFF_LIST = ["OFF", "ON"]
141
# MRT - Map CTCSS Tones -  Value in mem is hex value of (ctcss tone * 10) + 0x8000
142
# MRT - 0x8000 is for CTCSS tones
143
# MRT - Map DCS Tones -  Value in mem is hex representation of DCS Tone# in Octal + either 0x4000 or 0x6000 for polarity
144
# MRT - 0x4000 is for DCS n tones
145
# MRT - 0x6000 is for DCS i tones
146
TONE_MAP = [('Off', 0x0000)] + \
147
           [('%.1f' % tone, int(0x8000 + tone * 10)) for tone in chirp_common.TONES] + \
148
           [('D%03dn' % tone, int(0x4000 + int(str(tone),8)))
149
               for tone in chirp_common.DTCS_CODES] + \
150
           [('D%03di' % tone, int(0x6000 + int(str(tone),8)))
151
               for tone in chirp_common.DTCS_CODES]
152

    
153

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

    
157
# MRT made Power = 4 bits to handle 935G's 3 power levels and to prevent display errors
158
# MRT beta 1.3 - updates to structure to match KG935G Custom programming SW configuration settings, FM Radio presets, Key Settings
159
# MRT beta 1.4 - modified some value names and merged FM Radio memories with other settings to resolve errors in UI implementation
160
_MEM_FORMAT = """
161
    #seekto 0x0044;
162
    struct {
163
        u32    rx_start;
164
        u32    rx_stop;
165
        u32    tx_start;
166
        u32    tx_stop;
167
    } uhf_limits;
168

    
169
    #seekto 0x0054;
170
    struct {
171
        u32    rx_start;
172
        u32    rx_stop;
173
        u32    tx_start;
174
        u32    tx_stop;
175
    } vhf_limits;
176

    
177
    #seekto 0x0400;
178
    struct {
179
        char     oem1[8];
180
        char     unknown[2];
181
        u8     unknown2[10];
182
        u8     unknown3[10];
183
        u8     unknown4[8];
184
        char     oem2[10];
185
        u8     version[6];
186
        char     date[8];
187
        u8     unknown5[2];
188
        char     model[8];     
189
    } oem_info;
190

    
191
    #seekto 0x0480;
192
    struct {
193
        u16    Group_lower1;
194
        u16    Group_upper1;
195
        u16    Group_lower2;
196
        u16    Group_upper2;
197
        u16    Group_lower3;
198
        u16    Group_upper3;
199
        u16    Group_lower4;
200
        u16    Group_upper4;
201
        u16    Group_lower5;
202
        u16    Group_upper5;
203
        u16    Group_lower6;
204
        u16    Group_upper6;
205
        u16    Group_lower7;
206
        u16    Group_upper7;
207
        u16    Group_lower8;
208
        u16    Group_upper8;
209
        u16    Group_lower9;
210
        u16    Group_upper9;
211
        u16    Group_lower10;
212
        u16    Group_upper10;
213
    } scan_groups;
214

    
215
    #seekto 0x0500;
216
    struct {
217
        u8    call_code_1[6];
218
        u8    call_code_2[6];
219
        u8    call_code_3[6];
220
        u8    call_code_4[6];
221
        u8    call_code_5[6];
222
        u8    call_code_6[6];
223
        u8    call_code_7[6];
224
        u8    call_code_8[6];
225
        u8    call_code_9[6];
226
        u8    call_code_10[6];
227
        u8    call_code_11[6];
228
        u8    call_code_12[6];
229
        u8    call_code_13[6];
230
        u8    call_code_14[6];
231
        u8    call_code_15[6];
232
        u8    call_code_16[6];
233
        u8    call_code_17[6];
234
        u8    call_code_18[6];
235
        u8    call_code_19[6];
236
        u8    call_code_20[6];
237
    } call_groups;
238

    
239
    #seekto 0x0580;
240
    struct {
241
        char    call_name1[6];
242
        char    call_name2[6];
243
        char    call_name3[6];
244
        char    call_name4[6];
245
        char    call_name5[6];
246
        char    call_name6[6];
247
        char    call_name7[6];
248
        char    call_name8[6];
249
        char    call_name9[6];
250
        char    call_name10[6];
251
        char    call_name11[6];
252
        char    call_name12[6];
253
        char    call_name13[6];
254
        char    call_name14[6];
255
        char    call_name15[6];
256
        char    call_name16[6];
257
        char    call_name17[6];
258
        char    call_name18[6];
259
        char    call_name19[6];
260
        char    call_name20[6];
261
    } call_names;
262

    
263

    
264
    #seekto 0x0600;
265
    struct {
266
        u16    FM_radio1;
267
        u16    FM_radio2;
268
        u16    FM_radio3;
269
        u16    FM_radio4;
270
        u16    FM_radio5;
271
        u16    FM_radio6;
272
        u16    FM_radio7;
273
        u16    FM_radio8;
274
        u16    FM_radio9;
275
        u16    FM_radio10;
276
        u16    FM_radio11;
277
        u16    FM_radio12;
278
        u16    FM_radio13;
279
        u16    FM_radio14;
280
        u16    FM_radio15;
281
        u16    FM_radio16;
282
        u16    FM_radio17;
283
        u16    FM_radio18;
284
        u16    FM_radio19;
285
        u16    FM_radio20;
286
        u16 unknown_pad_x0640[235];
287
        u8 unknown07fe;
288
        u8 unknown07ff;
289
        u8      ponmsg;
290
        char    dispstr[15];
291
        u8 unknown0810;
292
        u8 unknown0811;
293
        u8 unknown0812;
294
        u8 unknown0813;
295
        u8 unknown0814;
296
        u8      voice;
297
        u8      timeout;
298
        u8      toalarm;
299
        u8      channel_menu;
300
        u8      power_save;
301
        u8      autolock;
302
        u8      keylock;
303
        u8      beep;
304
        u8      stopwatch;
305
        u8      vox;
306
        u8      scan_rev;
307
        u8      backlight;
308
        u8      roger_beep;
309
        char      mode_sw_pwd[6];
310
        char      reset_pwd[6];
311
        u16     pri_ch;
312
        u8      ani_sw;
313
        u8      ptt_delay;
314
        u8      ani_code[6];
315
        u8      dtmf_st;
316
        u8      BCL_A;
317
        u8      BCL_B;
318
        u8      ptt_id;
319
        u8      prich_sw;
320
        u8 unknown083d;
321
        u8 unknown083e;
322
        u8 unknown083f;
323
        u8      alert;
324
        u8      pf1_shrt;
325
        u8      pf1_long;
326
        u8      pf2_shrt;
327
        u8      pf2_long;
328
        u8 unknown0845;
329
        u8      work_mode_a;
330
        u8      work_mode_b;
331
        u8      dtmf_tx_time;
332
        u8      dtmf_interval;
333
        u8      main_band;
334
        u16      work_ch_a;
335
        u16      work_ch_b;
336
        u8 unknown084f;
337
        u8 unknown0850;
338
        u8 unknown0851;
339
        u8 unknown0852;
340
        u8 unknown0853;
341
        u8 unknown0854;
342
        u8 unknown0855;
343
        u8 unknown0856;
344
        u8 unknown0857;
345
        u8 unknown0858;
346
        u8 unknown0859;
347
        u8 unknown085a;
348
        u8 unknown085b;
349
        u8 unknown085c;
350
        u8 unknown085d;
351
        u8 unknown085e;
352
        u8 unknown085f;
353
        u8 unknown0860;
354
        u8      TDR_single_mode;
355
        u8      ring_time;
356
        u8      ScnGrpA_Act;
357
        u8      ScnGrpB_Act;
358
        u8 unknown0865;
359
        u8      rpt_tone;
360
        u8 unknown0867;
361
        u8      scan_det;
362
        u8      ToneScnSave;
363
        u8 unknown086a;
364
        u8      smuteset;
365
        u8      current_call_group;
366
        u8      DspBrtAct;
367
        u8      DspBrtSby;
368
        u8 unknown086f;
369
        u8      theme;
370
        u8      wxalert;
371
        u8      VFO_repeater_a;
372
        u8      VFO_repeater_b;
373
        u8 unknown0874;
374
        u8 unknown0875;
375
        u8 unknown0876;
376
        u8 unknown0877;
377
        u8 unknown0878;
378
        u8 unknown0879;
379
        u8 unknown087a;
380
        u8 unknown087b;
381
        u8 unknown087c;
382
        u8 unknown087d;
383
        u8 unknown087e;
384
        u8 unknown087f;
385
    } settings;
386

    
387
    #seekto 0x0880;
388
    struct {
389
        u32     rxfreq;
390
        u32     unknown0;
391
        u16     rxtone;
392
        u16     txtone;
393
        u8      scrambler:4,
394
                power:4; 
395
        u8      unknown3:1,
396
                unknown5:2,
397
                unknown4:1,
398
                cmpndr:1,
399
                mute_mode:2,
400
                iswide:1;
401
        u8      step;
402
        u8      squelch;
403
      } vfoa;
404

    
405
    #seekto 0x08c0;
406
    struct {
407
        u32     rxfreq;
408
        u32     unknown0;
409
        u16     rxtone;
410
        u16     txtone;
411
        u8      scrambler:4,
412
                power:4; 
413
        u8      unknown3:1,
414
                unknown5:2,
415
                unknown4:1,
416
                cmpndr:1,
417
                mute_mode:2,
418
                iswide:1;
419
        u8      step;
420
        u8      squelch;
421
    } vfob;
422

    
423
    #seekto 0x0900;
424
    struct {
425
        u32     rxfreq;
426
        u32     txfreq;
427
        u16     rxtone;
428
        u16     txtone;
429
        u8      scrambler:4,
430
                power:4; 
431
        u8      unknown3:2,
432
                scan_add:1,
433
                unknown4:1,
434
                compander:1,
435
                mute_mode:2,
436
                iswide:1;
437
        u8      unknown5;
438
        u8      unknown6;
439
    } memory[1000];
440

    
441
    #seekto 0x4780;
442
    struct {
443
        u8    name[8];
444
                u8    unknown[4];
445
    } names[1000];
446

    
447
    #seekto 0x7670;
448
    u8          valid[1000];
449
    """
450

    
451
    # Support for the Wouxun KG-935G radio
452
    # Serial coms are at 19200 baud
453
    # The data is passed in variable length records
454
    # Record structure:
455
    #  Offset   Usage
456
    #    0      start of record (\x7c)
457
    #    1      Command (\x80 Identify \x81 End/Reboot \x82 Read \x83 Write)
458
    #    2      direction (\xff PC-> Radio, \x00 Radio -> PC)
459
    #    3      length of payload (excluding header/checksum) (n)
460
    #    4      payload (n bytes)
461
    #    4+n+1  checksum - byte sum (% 256) of bytes 1 -> 4+n
462
    #
463
    # Memory Read Records:
464
    # the payload is 3 bytes, first 2 are offset (big endian),
465
    # 3rd is number of bytes to read
466
    # Memory Write Records:
467
    # the maximum payload size (from the Wouxun software) seems to be 66 bytes
468
    #  (2 bytes location + 64 bytes data).
469

    
470
#MRT 1.2 correct spelling of Wouxon
471
class KGUV8TRadio(chirp_common.Alias):
472
    VENDOR = "Wouxun"
473
    MODEL = "KG-935G"
474

    
475
@directory.register
476
class KG935GRadio(chirp_common.CloneModeRadio,
477
                  chirp_common.ExperimentalRadio):
478

    
479
    """Wouxun KG-935G"""
480
    VENDOR = "Wouxun"
481
    MODEL = "KG-935G"
482
    _model = "KG-UV8D-B"
483
    _file_ident = "935G"
484
    BAUD_RATE = 19200
485
# MRT - Added Medium Power level for 935G support
486
    POWER_LEVELS = [chirp_common.PowerLevel("L", watts=0.5),
487
                    chirp_common.PowerLevel("M", watts=4.5),
488
                    chirp_common.PowerLevel("H", watts=5.5)]
489
    _mmap = ""
490
    ALIASES = [KGUV8TRadio,]
491

    
492
    def _checksum(self, data):
493
        cs = 0
494
        for byte in data:
495
            cs += ord(byte)
496
        return chr(cs % 256)
497

    
498
    def _write_record(self, cmd, payload = None):
499
        # build the packet
500
        _header = '\x7c' + chr(cmd) + '\xff'
501

    
502
        _length = 0
503
        if payload:
504
            _length = len(payload)
505

    
506
        # update the length field
507
        _header += chr(_length)
508

    
509
        if payload:
510
            # calculate checksum then add it with the payload to the packet and encrypt
511
            crc = self._checksum(_header[1:] + payload)
512
            payload += crc
513
            _header += self.encrypt(payload)
514
        else:
515
            # calculate and add encrypted checksum to the packet
516
            crc = self._checksum(_header[1:])
517
            _header += self.strxor(crc, '\x57')
518

    
519
        try:
520
            self.pipe.write(_header)
521
        except Exception, e:
522
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
523

    
524
    def _read_record(self):
525
        # read 4 chars for the header
526
        _header = self.pipe.read(4)
527
        if len(_header) != 4:
528
            raise errors.RadioError('Radio did not respond')
529
        _length = ord(_header[3])
530
        _packet = self.pipe.read(_length)
531
        _rcs_xor = _packet[-1]
532
        _packet = self.decrypt(_packet)
533
        _cs = ord(self._checksum(_header[1:] + _packet))
534
        # read the checksum and decrypt it
535
        _rcs = ord(self.strxor(self.pipe.read(1), _rcs_xor))
536
        return (_rcs != _cs, _packet)
537

    
538
    def decrypt(self, data):
539
        result = ''
540
        for i in range(len(data)-1, 0, -1):
541
            result += self.strxor(data[i], data[i - 1])
542
        result += self.strxor(data[0], '\x57')
543
        return result[::-1]
544

    
545
    def encrypt(self, data):
546
        result = self.strxor('\x57', data[0])
547
        for i in range(1, len(data), 1):
548
            result += self.strxor(result[i - 1], data[i])
549
        return result
550

    
551
    def strxor (self, xora, xorb):
552
        return chr(ord(xora) ^ ord(xorb))
553

    
554
    # Identify the radio
555
    #
556
    # A Gotcha: the first identify packet returns a bad checksum, subsequent
557
    # attempts return the correct checksum... (well it does on my radio!)
558
    #
559
    # The ID record returned by the radio also includes the current frequency range
560
    # as 4 bytes big-endian in 10Hz increments
561
    #
562
    # Offset
563
    #  0:10     Model, zero padded (Looks for 'KG-UV8D-B')
564

    
565
    @classmethod
566
    def match_model(cls, filedata, filename):
567
        id = cls._file_ident 
568
        return cls._file_ident in filedata[0x426:0x430]
569

    
570
    def _identify(self):
571
        """Do the identification dance"""
572
        for _i in range(0, 10):
573
            self._write_record(CMD_ID)
574
            _chksum_err, _resp = self._read_record()
575
            LOG.debug("Got:\n%s" % util.hexprint(_resp))
576
            if _chksum_err:
577
                LOG.error("Checksum error: retrying ident...")
578
                time.sleep(0.100)
579
                continue
580
            LOG.debug("Model %s" % util.hexprint(_resp[0:9]))
581
            if _resp[0:9] == self._model:
582
                return
583
            if len(_resp) == 0:
584
                raise Exception("Radio not responding")
585
            else:
586
                raise Exception("Unable to identify radio")
587

    
588
    def _finish(self):
589
        self._write_record(CMD_END)
590

    
591
    def process_mmap(self):
592
        self._memobj = bitwise.parse(_MEM_FORMAT, self._mmap)
593

    
594
    def sync_in(self):
595
        try:
596
            self._mmap = self._download()
597
        except errors.RadioError:
598
            raise
599
        except Exception, e:
600
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
601
        self.process_mmap()
602

    
603
    def sync_out(self):
604
        self._upload()
605

    
606
    # TODO: Load all memory.
607
    # It would be smarter to only load the active areas and none of
608
    # the padding/unused areas. Padding still need to be investigated.
609
    def _download(self):
610
        """Talk to a wouxun KG-935G and do a download"""
611
        try:
612
            self._identify()
613
            return self._do_download(0, 32768, 64)
614
        except errors.RadioError:
615
            raise
616
        except Exception, e:
617
            LOG.exception('Unknown error during download process')
618
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
619

    
620
    def _do_download(self, start, end, blocksize):
621
        # allocate & fill memory
622
        image = ""
623
        for i in range(start, end, blocksize):
624
            req = chr(i / 256) + chr(i % 256) + chr(blocksize)
625
            self._write_record(CMD_RD, req)
626
            cs_error, resp = self._read_record()
627
            if cs_error:
628
                LOG.debug(util.hexprint(resp))
629
                raise Exception("Checksum error on read")
630
            # LOG.debug("Got:\n%s" % util.hexprint(resp))
631
            image += resp[2:]
632
            if self.status_fn:
633
                status = chirp_common.Status()
634
                status.cur = i
635
                status.max = end
636
                status.msg = "Cloning from radio"
637
                self.status_fn(status)
638
        self._finish()
639
        return memmap.MemoryMap(''.join(image))
640

    
641
    def _upload(self):
642
        """Talk to a wouxun KG-935G and do a upload"""
643
        try:
644
            self._identify()
645
            self._do_upload(0, 32768, 64)
646
        except errors.RadioError:
647
            raise
648
        except Exception, e:
649
            raise errors.RadioError("Failed to communicate with radio: %s" % e)
650
        return
651

    
652
    def _do_upload(self, start, end, blocksize):
653
        ptr = start
654
        for i in range(start, end, blocksize):
655
            req = chr(i / 256) + chr(i % 256)
656
            chunk = self.get_mmap()[ptr:ptr + blocksize]
657
            self._write_record(CMD_WR, req + chunk)
658
            LOG.debug(util.hexprint(req + chunk))
659
            cserr, ack = self._read_record()
660
            LOG.debug(util.hexprint(ack))
661
            j = ord(ack[0]) * 256 + ord(ack[1])
662
            if cserr or j != ptr:
663
                raise Exception("Radio did not ack block %i" % ptr)
664
            ptr += blocksize
665
            if self.status_fn:
666
                status = chirp_common.Status()
667
                status.cur = i
668
                status.max = end
669
                status.msg = "Cloning to radio"
670
                self.status_fn(status)
671
        self._finish()
672

    
673
    def get_features(self):
674
        rf = chirp_common.RadioFeatures()
675
        rf.has_settings = True
676
        rf.has_ctone = True
677
        rf.has_rx_dtcs = True
678
        rf.has_cross = True
679
        rf.has_tuning_step = False
680
        rf.has_bank = False
681
        rf.can_odd_split = True
682
        rf.valid_skips = ["", "S"]
683
        rf.valid_tmodes = ["", "Tone", "TSQL", "DTCS", "Cross"]
684
        rf.valid_cross_modes = [
685
            "Tone->Tone",
686
            "Tone->DTCS",
687
            "DTCS->Tone",
688
            "DTCS->",
689
            "->Tone",
690
            "->DTCS",
691
            "DTCS->DTCS",
692
        ]
693
        rf.valid_modes = ["FM", "NFM"]
694
        rf.valid_power_levels = self.POWER_LEVELS
695
        rf.valid_name_length = 8
696
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
697
#   MRT - Open up channel memory freq range to support RxFreq limit expansion
698
        rf.valid_bands = [(30000000, 299999999),  # supports 2m
699
                          (300000000, 999999999)]  # supports 70cm
700
        # rf.valid_bands = [(self._memobj.vhf_limits.rx_start
701
        #                 , self._memobj.vhf_limits.rx_stop),  # supports 2m
702
        #                   (self._memobj.uhf_limits.rx_start
703
        #                 , self._memobj.uhf_limits.rx_stop)]  # supports 70cm
704

    
705
        rf.valid_characters = chirp_common.CHARSET_ASCII
706
        rf.memory_bounds = (1, 999)  # 999 memories
707
        rf.valid_tuning_steps = STEPS
708
        return rf
709

    
710
    @classmethod
711
    def get_prompts(cls):
712
        rp = chirp_common.RadioPrompts()
713
        rp.experimental = \
714
            ('This driver is experimental.\n'
715
             '\n'
716
             'Please keep a copy of your memories with the original Wouxon CPS software '
717
             'if you treasure them, this driver is new and may contain bugs.\n'
718
             '\n'
719
             ' Upload and Download to/from the Radio are working\n'
720
             ' '
721
             ' All of the settings from the Wouxon Custom Programming'
722
             ' Software (CSP) have been mapped\n in addition to some bonus settings that were'
723
             ' found.\n'
724
             ' Changing the VHF/UHF Rx limits does expand receive range - but radio performance\n'
725
             ' is not guaranteed-  and may void warranty or cause radio to malfunction.\n'
726
             ' You can also customize the bottom banner from the OEMINFO Model setting\n'
727
                          ' \n'
728
             ' There are no limits/error checking done on the settings when using the Browser tab.\n'
729
             ' \n'
730
             ' Incorrect/Illegal values for a setting may cause radio malfunctions\n'
731
             ' USE AT YOUR OWN RISK\n'
732
             '\n'
733
             )
734
        return rp
735

    
736
    def get_raw_memory(self, number):
737
        return repr(self._memobj.memory[number])
738
# MRT - corrected the Polarity decoding to match 935G implementation use 0x2000 bit mask for R
739
# MRT - 0x2000 appears to be the bit mask for Inverted DCS tones
740
# MRT - n DCS Tone will be 0x4xxx values - i DCS Tones will be 0x6xxx values.
741
# MRT - Chirp Uses N for n DCS Tones and R for i DCS Tones
742
    def _get_tone(self, _mem, mem):
743
        def _get_dcs(val):
744
            code = int("%03o" % (val & 0x07FF))
745
            pol = (val & 0x2000) and "R" or "N"
746
            return code, pol
747
# MRT - Modified the function below to bitwise AND with 0x4000 to check for 935G DCS Tone decoding
748
# MRT 0x4000 appears to be the bit mask for DCS tones
749
        tpol = False
750
# MRT Beta 1.1 - Fix the txtone compare to 0x4000 - was rxtone.
751
        if _mem.txtone != 0xFFFF and (_mem.txtone & 0x4000) == 0x4000:
752
            tcode, tpol = _get_dcs(_mem.txtone)
753
            mem.dtcs = tcode
754
            txmode = "DTCS"
755
        elif _mem.txtone != 0xFFFF and _mem.txtone != 0x0:
756
            mem.rtone = (_mem.txtone & 0x7fff) / 10.0
757
            txmode = "Tone"
758
        else:
759
            txmode = ""
760
# MRT - Modified the function below to bitwise AND with 0x4000 to check for 935G DCS Tone decoding
761
        rpol = False
762
        if _mem.rxtone != 0xFFFF and (_mem.rxtone & 0x4000) == 0x4000:
763
            rcode, rpol = _get_dcs(_mem.rxtone)
764
            mem.rx_dtcs = rcode
765
            rxmode = "DTCS"
766
        elif _mem.rxtone != 0xFFFF and _mem.rxtone != 0x0:
767
            mem.ctone = (_mem.rxtone & 0x7fff) / 10.0
768
            rxmode = "Tone"
769
        else:
770
            rxmode = ""
771

    
772
        if txmode == "Tone" and not rxmode:
773
            mem.tmode = "Tone"
774
        elif txmode == rxmode and txmode == "Tone" and mem.rtone == mem.ctone:
775
            mem.tmode = "TSQL"
776
        elif txmode == rxmode and txmode == "DTCS" and mem.dtcs == mem.rx_dtcs:
777
            mem.tmode = "DTCS"
778
        elif rxmode or txmode:
779
            mem.tmode = "Cross"
780
            mem.cross_mode = "%s->%s" % (txmode, rxmode)
781

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

    
785
        LOG.debug("Got TX %s (%i) RX %s (%i)" %
786
                  (txmode, _mem.txtone, rxmode, _mem.rxtone))
787

    
788
    def get_memory(self, number):
789
        _mem = self._memobj.memory[number]
790
        _nam = self._memobj.names[number]
791

    
792
        mem = chirp_common.Memory()
793
        mem.number = number
794
        _valid = self._memobj.valid[mem.number]
795
        LOG.debug("%d %s", number, _valid == MEM_VALID)
796
        if _valid != MEM_VALID:
797
            mem.empty = True
798
            return mem
799
        else:
800
            mem.empty = False
801

    
802
        mem.freq = int(_mem.rxfreq) * 10
803

    
804
        if _mem.txfreq == 0xFFFFFFFF:
805
            # TX freq not set
806
            mem.duplex = "off"
807
            mem.offset = 0
808
        elif int(_mem.rxfreq) == int(_mem.txfreq):
809
            mem.duplex = ""
810
            mem.offset = 0
811
        elif abs(int(_mem.rxfreq) * 10 - int(_mem.txfreq) * 10) > 70000000:
812
            mem.duplex = "split"
813
            mem.offset = int(_mem.txfreq) * 10
814
        else:
815
            mem.duplex = int(_mem.rxfreq) > int(_mem.txfreq) and "-" or "+"
816
            mem.offset = abs(int(_mem.rxfreq) - int(_mem.txfreq)) * 10
817

    
818
        for char in _nam.name:
819
            if char != 0:
820
                mem.name += chr(char)
821
        mem.name = mem.name.rstrip()
822

    
823
        self._get_tone(_mem, mem)
824

    
825
        mem.skip = "" if bool(_mem.scan_add) else "S"
826

    
827
        mem.power = self.POWER_LEVELS[_mem.power]
828
        mem.mode = _mem.iswide and "FM" or "NFM"
829
        return mem
830

    
831
    def _set_tone(self, mem, _mem):
832
        def _set_dcs(code, pol):
833
#MRT Change from + 0x2800 to bitwise OR with 0x4000 to set the bit for DCS
834
            val = int("%i" % code, 8) | 0x4000
835
            if pol == "R":
836
#MRT Change to 0x2000 from 0x8000 to set the bit for i/R polarity
837
               val += 0x2000
838
            return val
839

    
840
        rx_mode = tx_mode = None
841
        rxtone = txtone = 0x0000
842

    
843
        if mem.tmode == "Tone":
844
            tx_mode = "Tone"
845
            rx_mode = None
846
            txtone = int(mem.rtone * 10) + 0x8000
847
        elif mem.tmode == "TSQL":
848
            rx_mode = tx_mode = "Tone"
849
            rxtone = txtone = int(mem.ctone * 10) + 0x8000
850
        elif mem.tmode == "DTCS":
851
            tx_mode = rx_mode = "DTCS"
852
            txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
853
            rxtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[1])
854
        elif mem.tmode == "Cross":
855
            tx_mode, rx_mode = mem.cross_mode.split("->")
856
            if tx_mode == "DTCS":
857
                txtone = _set_dcs(mem.dtcs, mem.dtcs_polarity[0])
858
            elif tx_mode == "Tone":
859
                txtone = int(mem.rtone * 10) + 0x8000
860
            if rx_mode == "DTCS":
861
                rxtone = _set_dcs(mem.rx_dtcs, mem.dtcs_polarity[1])
862
            elif rx_mode == "Tone":
863
                rxtone = int(mem.ctone * 10) + 0x8000
864

    
865
        _mem.rxtone = rxtone
866
        _mem.txtone = txtone
867

    
868
        LOG.debug("Set TX %s (%i) RX %s (%i)" %
869
                  (tx_mode, _mem.txtone, rx_mode, _mem.rxtone))
870

    
871
    def set_memory(self, mem):
872
        number = mem.number
873

    
874
        _mem = self._memobj.memory[number]
875
        _nam = self._memobj.names[number]
876

    
877
        if mem.empty:
878
            _mem.set_raw("\x00" * (_mem.size() / 8))
879
            self._memobj.valid[number] = 0
880
            self._memobj.names[number].set_raw("\x00" * (_nam.size() / 8))
881
            return
882

    
883
        _mem.rxfreq = int(mem.freq / 10)
884
        if mem.duplex == "off":
885
            _mem.txfreq = 0xFFFFFFFF
886
        elif mem.duplex == "split":
887
            _mem.txfreq = int(mem.offset / 10)
888
        elif mem.duplex == "off":
889
            for i in range(0, 4):
890
                _mem.txfreq[i].set_raw("\xFF")
891
        elif mem.duplex == "+":
892
            _mem.txfreq = int(mem.freq / 10) + int(mem.offset / 10)
893
        elif mem.duplex == "-":
894
            _mem.txfreq = int(mem.freq / 10) - int(mem.offset / 10)
895
        else:
896
            _mem.txfreq = int(mem.freq / 10)
897
        _mem.scan_add = int(mem.skip != "S")
898
        _mem.iswide = int(mem.mode == "FM")
899
        # set the tone
900
        self._set_tone(mem, _mem)
901
        # MRT set the scrambler and compander to off by default
902
        # MRT This changes them in the channel memory 
903
        _mem.scrambler = 0
904
        _mem.compander = 0
905
        # set the power
906
        if mem.power:
907
            _mem.power = self.POWER_LEVELS.index(mem.power)
908
        else:
909
            _mem.power = True
910
        # MRT set to mute mode to QT (not QT+DTMF or QT*DTMF) by default
911
        # MRT This changes them in the channel memory
912
        _mem.mute_mode = 0
913

    
914
        # MRT it is unknown what impact these values have
915
        # MRT This changes them in the channel memory to match what Wouxun CPS shows when creating a channel
916
        # MRT It is likely that these are just left as is and not written to by CPS - bit remnants of 0xFF in the unused memory
917
        # _mem.unknown1 = 0
918
        # MRT Set to 3 to TO MATCH CPS VALUES 
919
        _mem.unknown3 = 3
920
        # MRT Set to 1 to TO MATCH CPS VALUES 
921
        _mem.unknown4 = 1
922
        # MRT set unknown5 to 1 and unknown6 to 0 
923
        _mem.unknown5 = 1
924
        _mem.unknown6 = 255
925

    
926

    
927
        for i in range(0, len(_nam.name)):
928
            if i < len(mem.name) and mem.name[i]:
929
                _nam.name[i] = ord(mem.name[i])
930
            else:
931
                _nam.name[i] = 0x0
932
        self._memobj.valid[mem.number] = MEM_VALID
933

    
934
    def _get_settings(self):
935
        _settings = self._memobj.settings
936
        _vfoa = self._memobj.vfoa
937
        _vfob = self._memobj.vfob
938
        _scan = self._memobj.scan_groups
939
        _call = self._memobj.call_groups
940
        _callname = self._memobj.call_names
941
        
942

    
943
        cfg_grp = RadioSettingGroup("cfg_grp", "Config Settings")
944
        vfoa_grp = RadioSettingGroup("vfoa_grp", "VFO A Settings")
945
        vfob_grp = RadioSettingGroup("vfob_grp", "VFO B Settings")
946
        key_grp = RadioSettingGroup("key_grp", "Key Settings")
947
        fmradio_grp = RadioSettingGroup("fmradio_grp", "FM Broadcast Memory")
948
        lmt_grp = RadioSettingGroup("lmt_grp", "Rx/Tx Frequency Limits")
949
        uhf_lmt_grp = RadioSettingGroup("uhf_lmt_grp", "UHF")
950
        vhf_lmt_grp = RadioSettingGroup("vhf_lmt_grp", "VHF")
951
        oem_grp = RadioSettingGroup("oem_grp", "OEM Info")
952
        scan_grp = RadioSettingGroup("scan_grp", "Scan Group")
953
        call_grp = RadioSettingGroup("call_grp", "Call Settings")
954
        extra_grp = RadioSettingGroup("extra_grp", "Extra Settings - NOT CHANGED BY RESET OR CPS")
955
        extra_grp.append(lmt_grp);
956
        extra_grp.append(oem_grp);
957
        group = RadioSettings(cfg_grp, vfoa_grp, vfob_grp,
958
                             fmradio_grp, key_grp, scan_grp, call_grp, extra_grp)
959

    
960

    
961
    # Call Settings
962
        rs = RadioSetting("current_call_group", "Current Call Group",
963
                          RadioSettingValueList(CALLGROUP_LIST,
964
                                                CALLGROUP_LIST[_settings.
965
                                                              current_call_group]))
966
        call_grp.append(rs)
967

    
968
        callchars = "0123456789"
969
        for i in range(1,21): 
970
            callnum = str(i)
971
            _msg = ""
972
            _msg1 = str(eval("_callname.call_name"+callnum)).split("\0")[0]
973
#MRT - Handle default factory values of 0xFF or non-ascii values in Call Name memory
974
            for char in _msg1:
975
                if char < chr(0x20) or char > chr(0x7E):
976
                    # _msg += chr(0x20)
977
                    _msg += ""
978
                else:
979
                    _msg += str(char)
980
            val = RadioSettingValueString(0, 6, _msg)
981
            val.set_mutable(True)
982
            rs = RadioSetting("call_names.call_name"+callnum, "Call Name "+callnum, val)
983
            call_grp.append(rs)
984

    
985
            _codeobj = eval("_call.call_code_"+callnum)
986
            _code = "".join([callchars[x] for x in _codeobj if int(x) < 0x0A])
987
            val = RadioSettingValueString(3, 6, _code, False)
988
            val.set_charset(callchars)
989
            rs = RadioSetting("call_code_"+callnum, "Call Code " + callnum, val)
990
            def apply_call_code(setting, obj):
991
                value = []
992
                for j in range(0, 6):
993
                    try:
994
                       value.append(callchars.index(str(setting.value)[j]))
995
                    except IndexError:
996
                        value.append(0xFF)
997
                obj.call_code = value
998
            rs.set_apply_callback(apply_call_code, eval("_call.call_code_"+callnum))
999
            call_grp.append(rs)
1000

    
1001

    
1002
        # Configuration Settings
1003
        #
1004
        rs = RadioSetting("DspBrtAct", "Display Brightness ACTIVE",
1005
                          RadioSettingValueMap(DSPBRTACT_MAP,
1006
                                                _settings.DspBrtAct))
1007
        cfg_grp.append(rs)
1008
        rs = RadioSetting("DspBrtSby", "Display Brightness STANDBY",
1009
                          RadioSettingValueList(DSPBRTSBY_LIST,
1010
                                                 DSPBRTSBY_LIST[_settings.DspBrtSby]))
1011
        cfg_grp.append(rs)
1012
        rs = RadioSetting("wxalert", "Weather Alert",
1013
                          RadioSettingValueBoolean(_settings.wxalert))
1014
        cfg_grp.append(rs)
1015
        rs = RadioSetting("power_save", "Battery Saver",
1016
                          RadioSettingValueBoolean(_settings.power_save))
1017
        cfg_grp.append(rs)
1018
        rs = RadioSetting("theme", "Theme",
1019
                          RadioSettingValueList(
1020
                              THEME_LIST, THEME_LIST[_settings.theme]))
1021
        cfg_grp.append(rs)
1022
        rs = RadioSetting("backlight", "Backlight Active Time",
1023
                          RadioSettingValueList(BACKLIGHT_LIST,
1024
                                                BACKLIGHT_LIST[_settings.
1025
                                                               backlight]))
1026
        cfg_grp.append(rs)
1027
        rs = RadioSetting("scan_rev", "Scan Mode",
1028
                          RadioSettingValueList(SCANMODE_LIST,
1029
                                                SCANMODE_LIST[_settings.
1030
                                                              scan_rev]))
1031
        cfg_grp.append(rs)
1032
        rs = RadioSetting("prich_sw", "Priority Channel Scan",
1033
                          RadioSettingValueBoolean(_settings.prich_sw))
1034
        cfg_grp.append(rs)
1035
        rs = RadioSetting("pri_ch", "Priority Channel - Can not be empty Channel",
1036
                          RadioSettingValueInteger(1, 999, _settings.pri_ch))
1037
        cfg_grp.append(rs)
1038
        rs = RadioSetting("scan_det", "Scan Mode Tone Detect",
1039
                          RadioSettingValueBoolean(_settings.scan_det))
1040
        cfg_grp.append(rs)
1041
        rs = RadioSetting("ToneScnSave", "Tone Scan Save",
1042
                          RadioSettingValueList(TONESCANSAVELIST,
1043
                                                TONESCANSAVELIST[_settings.ToneScnSave]))
1044
        cfg_grp.append(rs)
1045
        rs = RadioSetting("roger_beep", "Roger Beep",
1046
                          RadioSettingValueList(ROGER_LIST,
1047
                                                ROGER_LIST[_settings.roger_beep]))
1048
        cfg_grp.append(rs)
1049
        rs = RadioSetting("timeout", "Timeout Timer (TOT)",
1050
                          RadioSettingValueList(
1051
                              TIMEOUT_LIST, TIMEOUT_LIST[_settings.timeout]))
1052
        cfg_grp.append(rs)
1053
        rs = RadioSetting("toalarm", "Timeout Alarm (TOA)",
1054
                          RadioSettingValueInteger(0, 10, _settings.toalarm))
1055
        cfg_grp.append(rs)
1056
        rs = RadioSetting("vox", "VOX",
1057
                          RadioSettingValueList(LIST_10,
1058
                                                LIST_10[_settings.vox]))
1059
        cfg_grp.append(rs)
1060
        rs = RadioSetting("voice", "Voice Guide",
1061
                          RadioSettingValueBoolean(_settings.voice))
1062
        cfg_grp.append(rs)
1063
        rs = RadioSetting("beep", "Keypad Beep",
1064
                          RadioSettingValueBoolean(_settings.beep))
1065
        cfg_grp.append(rs)
1066
        rs = RadioSetting("BCL_B", "Busy Channel Lock-out A",
1067
                          RadioSettingValueBoolean(_settings.BCL_A))
1068
        cfg_grp.append(rs)
1069
        rs = RadioSetting("BCL_A", "Busy Channel Lock-out B",
1070
                          RadioSettingValueBoolean(_settings.BCL_B))
1071
        cfg_grp.append(rs)
1072
        rs = RadioSetting("smuteset", "Secondary Area Mute (SMUTESET)",
1073
                          RadioSettingValueList(SMUTESET_LIST,
1074
                                                SMUTESET_LIST[_settings.
1075
                                                              smuteset]))
1076
        cfg_grp.append(rs)
1077
        rs = RadioSetting("ani_sw", "ANI-ID Switch (ANI-SW)",
1078
                          RadioSettingValueBoolean(_settings.ani_sw))
1079
        cfg_grp.append(rs)
1080
        rs = RadioSetting("dtmf_st", "DTMF Sidetone (SIDETONE)",
1081
                          RadioSettingValueList(DTMFST_LIST,
1082
                                                DTMFST_LIST[_settings.
1083
                                                            dtmf_st]))
1084
        cfg_grp.append(rs)
1085
        rs = RadioSetting("alert", "Alert Tone",
1086
                          RadioSettingValueList(ALERTS_LIST,
1087
                                                ALERTS_LIST[_settings.alert]))
1088
        cfg_grp.append(rs)
1089
        rs = RadioSetting("ptt_delay", "PTT-DLY",
1090
                          RadioSettingValueMap(PTTDELAY_TIMES,
1091
                                                _settings.ptt_delay))
1092
        cfg_grp.append(rs)
1093
        rs = RadioSetting("ptt_id", "PTT-ID",
1094
                          RadioSettingValueList(PTTID_LIST,
1095
                                                PTTID_LIST[_settings.ptt_id]))
1096
        cfg_grp.append(rs)
1097
        rs = RadioSetting("ring_time", "Ring Time",
1098
                          RadioSettingValueList(LIST_10,
1099
                                                LIST_10[_settings.ring_time]))
1100
        cfg_grp.append(rs)
1101
        rs = RadioSetting("rpt_tone", "Repeater Tone",
1102
                          RadioSettingValueBoolean(_settings.rpt_tone))
1103
        cfg_grp.append(rs)
1104
        rs = RadioSetting("stopwatch", "Timer / Stopwatch",
1105
                          RadioSettingValueBoolean(_settings.stopwatch))
1106
        cfg_grp.append(rs)
1107
        rs = RadioSetting("autolock", "Autolock",
1108
                          RadioSettingValueBoolean(_settings.autolock))
1109
        cfg_grp.append(rs)
1110
        rs = RadioSetting("keylock", "Keypad Lock",
1111
                          RadioSettingValueBoolean(_settings.keylock))
1112
        cfg_grp.append(rs)
1113
        rs = RadioSetting("ponmsg", "Poweron message",
1114
                          RadioSettingValueList(
1115
                              PONMSG_LIST, PONMSG_LIST[_settings.ponmsg]))
1116
        cfg_grp.append(rs)
1117
        rs = RadioSetting("dtmf_tx_time", "DTMF Transmit Time",
1118
                          RadioSettingValueMap(DTMF_TIMES,
1119
                                                _settings.dtmf_tx_time))
1120
        cfg_grp.append(rs)
1121
        rs = RadioSetting("dtmf_interval", "DTMF Interval Time",
1122
                          RadioSettingValueMap(DTMF_TIMES,
1123
                                                _settings.dtmf_interval))
1124
        cfg_grp.append(rs)
1125
        rs = RadioSetting("channel_menu", "Menu available in channel mode",
1126
                          RadioSettingValueBoolean(_settings.channel_menu))
1127
        cfg_grp.append(rs)
1128

    
1129
        pswdchars = "0123456789"
1130
        _msg = str(_settings.mode_sw_pwd).split("\0")[0]
1131
        val = RadioSettingValueString(0, 6, _msg, False)
1132
        val.set_mutable(True)
1133
        val.set_charset(pswdchars)
1134
        rs = RadioSetting("mode_sw_pwd", "Mode SW Pwd", val)
1135
        cfg_grp.append(rs)
1136

    
1137
        _msg = str(_settings.reset_pwd).split("\0")[0]
1138
        val = RadioSettingValueString(0, 6, _msg, False)
1139
        val.set_charset(pswdchars)
1140
        val.set_mutable(True)
1141
        rs = RadioSetting("reset_pwd", "Reset Pwd", val)
1142
        cfg_grp.append(rs)
1143

    
1144
        # Key Settings
1145
        #
1146
        _msg = str(_settings.dispstr).split("\0")[0]
1147
        val = RadioSettingValueString(0, 15, _msg)
1148
        val.set_mutable(True)
1149
        rs = RadioSetting("dispstr", "Display Message - Interface Display Edit", val)
1150
        key_grp.append(rs)
1151

    
1152
        dtmfchars = "0123456789"
1153
        _codeobj = _settings.ani_code
1154
        _code = "".join([dtmfchars[x] for x in _codeobj if int(x) < 0x0A])
1155
        val = RadioSettingValueString(3, 6, _code, False)
1156
        val.set_charset(dtmfchars)
1157
        rs = RadioSetting("ani_code", "ANI Code", val)
1158
        def apply_ani_id(setting, obj):
1159
            value = []
1160
            for j in range(0, 6):
1161
                try:
1162
                    value.append(dtmfchars.index(str(setting.value)[j]))
1163
                except IndexError:
1164
                    value.append(0xFF)
1165
            obj.ani_code = value
1166
        rs.set_apply_callback(apply_ani_id, _settings)
1167
        key_grp.append(rs)
1168

    
1169
        rs = RadioSetting("pf1_shrt", "PF1 SHORT Key function",
1170
                          RadioSettingValueList(
1171
                              PFKEYSHORT_LIST,
1172
                              PFKEYSHORT_LIST[_settings.pf1_shrt]))
1173
        key_grp.append(rs)
1174
        rs = RadioSetting("pf1_long", "PF1 LONG Key function",
1175
                          RadioSettingValueList(
1176
                              PFKEYLONG_LIST,
1177
                              PFKEYLONG_LIST[_settings.pf1_long]))
1178
        key_grp.append(rs)
1179
        rs = RadioSetting("pf2_shrt", "PF2 SHORT Key function",
1180
                          RadioSettingValueList(
1181
                              PFKEYSHORT_LIST,
1182
                              PFKEYSHORT_LIST[_settings.pf2_shrt]))
1183
        key_grp.append(rs)
1184
        rs = RadioSetting("pf2_long", "PF2 LONG Key function",
1185
                          RadioSettingValueList(
1186
                              PFKEYLONG_LIST,
1187
                              PFKEYLONG_LIST[_settings.pf2_long]))
1188
        key_grp.append(rs)
1189

    
1190
#       SCAN GROUP settings
1191
        rs = RadioSetting("ScnGrpA_Act", "Scan Group A Active",
1192
                          RadioSettingValueList(SCANGRP_LIST, SCANGRP_LIST[_settings.ScnGrpA_Act]))
1193
        scan_grp.append(rs)
1194
        rs = RadioSetting("ScnGrpB_Act", "Scan Group B Active",
1195
                          RadioSettingValueList(SCANGRP_LIST, SCANGRP_LIST[_settings.ScnGrpB_Act]))
1196
        scan_grp.append(rs)
1197

    
1198
        for i in range(1, 11):
1199
            scgroup = str(i)
1200

    
1201
            rs = RadioSetting("scan_groups.Group_lower"+scgroup, "Scan Group "+scgroup+" Lower",
1202
                          RadioSettingValueInteger(1, 999, eval("self._memobj.scan_groups.Group_lower"+scgroup)))
1203
            scan_grp.append(rs)
1204

    
1205
            rs = RadioSetting("scan_groups.Group_upper"+scgroup, "Scan Group "+scgroup+" Upper",
1206
                          RadioSettingValueInteger(1, 999, eval("self._memobj.scan_groups.Group_upper"+scgroup)))
1207
            scan_grp.append(rs)
1208

    
1209
        # VFO A Settings
1210
        #
1211
        rs = RadioSetting("work_mode_a", "VFO A Workmode",
1212
                          RadioSettingValueList(WORKMODE_LIST, WORKMODE_LIST[_settings.work_mode_a]))
1213
        vfoa_grp.append(rs)
1214
        rs = RadioSetting("work_ch_a", "VFO A Work Channel",
1215
                          RadioSettingValueInteger(1, 999, _settings.work_ch_a))
1216
        vfoa_grp.append(rs)
1217
        rs = RadioSetting("vfoa.rxfreq", "VFO A Rx Frequency (MHz)",
1218
                          RadioSettingValueFloat(
1219
                              30.00000, 999.999999, (_vfoa.rxfreq / 100000.0), 0.000001, 6))
1220
        vfoa_grp.append(rs)
1221

    
1222
        rs = RadioSetting("vfoa.rxtone", "VFOA Rx tone",
1223
                          RadioSettingValueMap(
1224
                            TONE_MAP, _vfoa.rxtone))
1225
        vfoa_grp.append(rs)
1226
        rs = RadioSetting("vfoa.txtone", "VFOA Tx tone",
1227
                          RadioSettingValueMap(
1228
                            TONE_MAP, _vfoa.txtone))
1229
        vfoa_grp.append(rs)
1230

    
1231

    
1232
# MRT - AND power with 0x03 to display only the lower 2 bits for power level and to clear the upper bits
1233
# MRT - any bits set in the upper 2 bits will cause radio to show invalid values for power level and a display glitch
1234
# MRT - when PTT is pushed
1235
        _vfoa.power = _vfoa.power & 0x3
1236
        rs = RadioSetting("vfoa.power", "VFO A Power",
1237
                          RadioSettingValueList(
1238
                              POWER_LIST, POWER_LIST[_vfoa.power]))
1239
        vfoa_grp.append(rs)
1240
        rs = RadioSetting("vfoa.iswide", "VFO A Wide/Narrow",
1241
                          RadioSettingValueList(
1242
                              BANDWIDTH_LIST, BANDWIDTH_LIST[_vfoa.iswide]))
1243
        vfoa_grp.append(rs)
1244
        rs = RadioSetting("vfoa.mute_mode", "VFO A Mute (SP Mute)",
1245
                          RadioSettingValueList(
1246
                              SPMUTE_LIST, SPMUTE_LIST[_vfoa.mute_mode]))
1247
        vfoa_grp.append(rs)
1248
        rs = RadioSetting("VFO_repeater_a", "VFO A Repeater",
1249
                          RadioSettingValueBoolean(_settings.VFO_repeater_a))
1250
        vfoa_grp.append(rs)
1251

    
1252
        rs = RadioSetting("vfoa.scrambler", "VFO A Descramble",
1253
                          RadioSettingValueList(
1254
                              SCRAMBLE_LIST, SCRAMBLE_LIST[_vfoa.scrambler]))
1255
        vfoa_grp.append(rs)
1256

    
1257
        rs = RadioSetting("vfoa.cmpndr", "VFO A Compander",
1258
                         RadioSettingValueList(
1259
                             ONOFF_LIST, ONOFF_LIST[_vfoa.cmpndr]))
1260
        vfoa_grp.append(rs)
1261

    
1262
        rs = RadioSetting("vfoa.step", "VFO A Step (kHz)",
1263
                          RadioSettingValueList(
1264
                              STEP_LIST, STEP_LIST[_vfoa.step]))
1265
        vfoa_grp.append(rs)
1266
        rs = RadioSetting("vfoa.squelch", "VFO A Squelch",
1267
                          RadioSettingValueList(
1268
                              LIST_10, LIST_10[_vfoa.squelch]))
1269
        vfoa_grp.append(rs)
1270

    
1271

    
1272
        # VFO B Settings
1273
        #
1274
        rs = RadioSetting("work_mode_b", "VFO B Workmode",
1275
                          RadioSettingValueList(WORKMODE_LIST, WORKMODE_LIST[_settings.work_mode_b]))
1276
        vfob_grp.append(rs)
1277
        rs = RadioSetting("work_ch_b", "VFO B Work Channel",
1278
                          RadioSettingValueInteger(1, 999, _settings.work_ch_b))
1279
        vfob_grp.append(rs)
1280
        rs = RadioSetting("vfob.rxfreq", "VFO B Rx Frequency (MHz)",
1281
                          RadioSettingValueFloat(
1282
                              30.000000, 999.999999, (_vfob.rxfreq / 100000.0), 0.000001, 6))
1283
        vfob_grp.append(rs)
1284
        rs = RadioSetting("vfob.rxtone", "VFOB Rx tone",
1285
                          RadioSettingValueMap(
1286
                            TONE_MAP, _vfob.rxtone))
1287
        vfob_grp.append(rs)
1288
        rs = RadioSetting("vfob.txtone", "VFOB Tx tone",
1289
                          RadioSettingValueMap(
1290
                            TONE_MAP, _vfob.txtone))
1291
        vfob_grp.append(rs)
1292

    
1293
# MRT - AND power with 0x03 to display only the lower 2 bits for power level and to clear the upper bits
1294
# MRT - any bits set in the upper 2 bits will cause radio to show invalid values for power level and a display glitch
1295
# MRT - when PTT is pushed
1296
        _vfob.power = _vfob.power & 0x3
1297
        rs = RadioSetting("vfob.power", "VFO B Power",
1298
                          RadioSettingValueList(
1299
                              POWER_LIST, POWER_LIST[_vfob.power]))
1300
        vfob_grp.append(rs)
1301
        rs = RadioSetting("vfob.iswide", "VFO B Wide/Narrow",
1302
                          RadioSettingValueList(
1303
                              BANDWIDTH_LIST, BANDWIDTH_LIST[_vfob.iswide]))
1304
        vfob_grp.append(rs)
1305
        rs = RadioSetting("vfob.mute_mode", "VFO B Mute (SP Mute)",
1306
                          RadioSettingValueList(
1307
                              SPMUTE_LIST, SPMUTE_LIST[_vfob.mute_mode]))
1308
        vfob_grp.append(rs)
1309
        rs = RadioSetting("VFO_repeater_b", "VFO B Repeater",
1310
                          RadioSettingValueBoolean(_settings.VFO_repeater_b))
1311
        vfob_grp.append(rs)
1312

    
1313
        rs = RadioSetting("vfob.scrambler", "VFO B Descramble",
1314
                          RadioSettingValueList(
1315
                              SCRAMBLE_LIST, SCRAMBLE_LIST[_vfob.scrambler]))
1316
        vfob_grp.append(rs)
1317

    
1318
        rs = RadioSetting("vfob.cmpndr", "VFO B Compander",
1319
                         RadioSettingValueList(
1320
                             ONOFF_LIST, ONOFF_LIST[_vfob.cmpndr]))
1321
        vfob_grp.append(rs)
1322
        
1323
        rs = RadioSetting("vfob.step", "VFO B Step (kHz)",
1324
                          RadioSettingValueList(
1325
                              STEP_LIST, STEP_LIST[_vfob.step]))
1326
        vfob_grp.append(rs)
1327
        rs = RadioSetting("vfob.squelch", "VFO B Squelch",
1328
                          RadioSettingValueList(
1329
                              LIST_10, LIST_10[_vfob.squelch]))
1330
        vfob_grp.append(rs)
1331

    
1332
# FM RADIO PRESETS
1333

    
1334
        #memory stores raw integer value like 760
1335
        #radio will divide 760 by 10 and interpret correctly at 76.0Mhz
1336
        for i in range(1, 21):
1337
            chan = str(i)
1338
            rs = RadioSetting("FM_radio"+ chan, "FM Preset"+chan,
1339
                        RadioSettingValueFloat(76.0, 108.0, eval("_settings.FM_radio"+chan)/10.0,  0.1, 1))
1340
            fmradio_grp.append(rs)
1341

    
1342
# Freq Limits settings
1343
        #
1344
        rs = RadioSetting("vhf_limits.rx_start", "VHF RX Lower Limit (MHz)",
1345
                          RadioSettingValueFloat(
1346
                              30.000000, 299.999999, (self._memobj.vhf_limits.rx_start / 100000.0), 0.000001, 6))
1347

    
1348
        lmt_grp.append(rs)
1349
        rs = RadioSetting("vhf_limits.rx_stop", "VHF RX Upper Limit (MHz)",
1350
                          RadioSettingValueFloat(
1351
                              30.000000, 299.999999, (self._memobj.vhf_limits.rx_stop / 100000.0), 0.000001, 6))
1352
        lmt_grp.append(rs)
1353

    
1354
        rs = RadioSetting("vhf_limits.tx_start", "VHF TX Lower Limit (MHz)",
1355
                          RadioSettingValueFloat(
1356
                              30.000000, 299.999999, (self._memobj.vhf_limits.tx_start / 100000.0), 0.000001, 6))
1357

    
1358
        lmt_grp.append(rs)
1359
        rs = RadioSetting("vhf_limits.tx_stop", "VHF TX Upper Limit (MHz)",
1360
                          RadioSettingValueFloat(
1361
                              30.000000, 299.999999, (self._memobj.vhf_limits.tx_stop / 100000.0), 0.000001, 6))
1362
        lmt_grp.append(rs)
1363

    
1364
# MRT - TX Limits do not appear to change radio's ability to transmit on other freqs.  
1365
# MRT - Appears that the radio firmware prevent Tx on anything other than a valid GMRS Freq
1366

    
1367
        # rs = RadioSetting("vhf_limits.tx_start", "VHF TX Lower Limit",
1368
        #                   RadioSettingValueInteger(
1369
        #                       10000000, 299999999,
1370
        #                       self._memobj.vhf_limits.tx_start * 10, 5000))
1371
        # val.set_mutable(False)
1372
        # vhf_lmt_grp.append(rs)
1373
        # rs = RadioSetting("vhf_limits.tx_stop", "VHF TX Upper Limit",
1374
        #                   RadioSettingValueInteger(
1375
        #                       10000000, 299999999,
1376
        #                       self._memobj.vhf_limits.tx_stop * 10, 5000))
1377
        # val.set_mutable(False)
1378
        # vhf_lmt_grp.append(rs)
1379

    
1380
        rs = RadioSetting("uhf_limits.rx_start", "UHF RX Lower Limit (MHz)",
1381
                          RadioSettingValueFloat(
1382
                              300.000000, 999.999999, (self._memobj.uhf_limits.rx_start / 100000.0), 0.000001, 6))
1383
        lmt_grp.append(rs)
1384
        rs = RadioSetting("uhf_limits.rx_stop", "UHF RX Upper Limit (MHz)",
1385
                          RadioSettingValueFloat(
1386
                              300.000000, 999.999999, (self._memobj.uhf_limits.rx_stop / 100000.0), 0.000001, 6))
1387
        lmt_grp.append(rs)
1388

    
1389
        rs = RadioSetting("uhf_limits.tx_start", "UHF TX Lower Limit (MHz)",
1390
                          RadioSettingValueFloat(
1391
                              300.000000, 999.999999, (self._memobj.uhf_limits.tx_start / 100000.0), 0.000001, 6))
1392
        lmt_grp.append(rs)
1393
        rs = RadioSetting("uhf_limits.tx_stop", "UHF TX Upper Limit (MHz)",
1394
                          RadioSettingValueFloat(
1395
                              300.000000, 999.999999, (self._memobj.uhf_limits.tx_stop / 100000.0), 0.000001, 6))
1396
        lmt_grp.append(rs)
1397

    
1398
        # rs = RadioSetting("uhf_limits.tx_start", "UHF TX Lower Limit",
1399
        #                   RadioSettingValueInteger(
1400
        #                       300000000, 999999999,
1401
        #                       self._memobj.uhf_limits.tx_start * 10, 5000))
1402
        # uhf_lmt_grp.append(rs)
1403
        # rs = RadioSetting("uhf_limits.tx_stop", "UHF TX Upper Limit",
1404
        #                   RadioSettingValueInteger(
1405
        #                       300000000, 999999999,
1406
        #                       self._memobj.uhf_limits.tx_stop * 10, 5000))
1407
        # uhf_lmt_grp.append(rs)
1408

    
1409

    
1410
# OEM info
1411
        #
1412
        def _decode(lst):
1413
            _str = ''.join([chr(c) for c in lst
1414
                            if chr(c) in chirp_common.CHARSET_ASCII])
1415
            return _str
1416

    
1417
        def do_nothing(setting, obj):
1418
            return
1419

    
1420
        _str = _decode(self._memobj.oem_info.model)
1421
        val = RadioSettingValueString(0, 8, _str)
1422
        val.set_mutable(True)
1423
        rs = RadioSetting("oem_info.model", "Model / Bottom Banner", val)
1424
        oem_grp.append(rs)
1425
        _str = _decode(self._memobj.oem_info.oem1)
1426
        val = RadioSettingValueString(0, 15, _str)
1427
        val.set_mutable(False)
1428
        rs = RadioSetting("oem_info.oem1", "OEM String 1", val)
1429
        rs.set_apply_callback(do_nothing, _settings)
1430
        oem_grp.append(rs)
1431
        _str = _decode(self._memobj.oem_info.oem2)
1432
        val = RadioSettingValueString(0, 15, _str)
1433
        val.set_mutable(False)
1434
        rs = RadioSetting("oem_info.oem2", "Firmware Version ??", val)
1435
        rs.set_apply_callback(do_nothing, _settings)
1436
        oem_grp.append(rs)
1437
        # _str = _decode(self._memobj.oem_info.version)
1438
        # val = RadioSettingValueString(0, 15, _str)
1439
        # val.set_mutable(False)
1440
        # rs = RadioSetting("oem_info.version", "Software Version", val)
1441
        # rs.set_apply_callback(do_nothing, _settings)
1442
        # oem_grp.append(rs)
1443
        _str = _decode(self._memobj.oem_info.date)
1444
        val = RadioSettingValueString(0, 15, _str)
1445
        val.set_mutable(False)
1446
        rs = RadioSetting("oem_info.date", "OEM Date", val)
1447
        rs.set_apply_callback(do_nothing, _settings)
1448
        oem_grp.append(rs)
1449

    
1450
        return group
1451

    
1452

    
1453

    
1454

    
1455
        return group
1456

    
1457
    def get_settings(self):
1458
        try:
1459
            return self._get_settings()
1460
        except:
1461
            import traceback
1462
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
1463
            return None
1464

    
1465
    def set_settings(self, settings):
1466
        for element in settings:
1467
            if not isinstance(element, RadioSetting):
1468
                self.set_settings(element)
1469
                continue
1470
            else:
1471
                try:
1472
                    if "." in element.get_name():
1473
                        bits = element.get_name().split(".")
1474
                        obj = self._memobj
1475
                        for bit in bits[:-1]:
1476
                            obj = getattr(obj, bit)
1477
                        setting = bits[-1]
1478
                    else:
1479
                        obj = self._memobj.settings
1480
                        setting = element.get_name()
1481

    
1482
                    if element.has_apply_callback():
1483
                        LOG.debug("Using apply callback")
1484
                        element.run_apply_callback()
1485
                    else:
1486
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1487
                        if self._is_freq(element):
1488
                            # setattr(obj, setting, int(element.value / 10))
1489
                            # MRT rescale freq values to match radio expected values
1490
                            setattr(obj, setting, int(element.values()[0]._current *100000.0))
1491
                        elif self._is_fmradio(element):
1492
                            # MRT rescale FM Radio values to match radio expected values
1493
                            setattr(obj, setting, int(element.values()[0]._current *10.0))
1494
                        else:
1495
                            setattr(obj, setting, element.value)
1496
                except Exception, e:
1497
                    LOG.debug(element.get_name())
1498
                    raise
1499

    
1500
    def _is_freq(self, element):
1501
        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()
1502

    
1503
    def _is_fmradio(self, element):
1504
        return "FM_radio" in element.get_name()
1505
        
(17-17/18)