leixen_dualbank.py

Brian Dickman, 03/10/2018 04:01 pm

Download (36.5 kB)

 
1
# Copyright 2014 Tom Hayward <tom@tomh.us>
2
#
3
# This program is free software: you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation, either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
15

    
16
import struct
17
import os
18
import logging
19

    
20
from chirp import chirp_common, directory, memmap, errors, util
21
from chirp import bitwise
22
from chirp.settings import RadioSetting, RadioSettingGroup, \
23
    RadioSettingValueInteger, RadioSettingValueList, \
24
    RadioSettingValueBoolean, RadioSettingValueString, \
25
    RadioSettingValueFloat, InvalidValueError, RadioSettings
26
from textwrap import dedent
27

    
28
LOG = logging.getLogger(__name__)
29

    
30
MEM_FORMAT = """
31
#seekto 0x0184;
32
struct {
33
  u8 unknown:4,
34
     sql:4;              // squelch level
35
  u8 unknown0x0185;
36
  u8 obeep:1,            // open beep
37
     dw_off:1,           // dual watch (inverted)
38
     kbeep:1,            // key beep
39
     rbeep:1,            // roger beep
40
     unknown:2,
41
     ctdcsb:1,           // ct/dcs busy lock
42
     unknown:1;
43
  u8 alarm:1,            // alarm key
44
     unknown1:1,
45
     aliasen_off:1,      // alias enable (inverted)
46
     save:1,             // battery save
47
     unknown2:1,
48
     keypad_enable:1,    // microphone keypad enable
49
     mrcha:1,            // mr/cha
50
     vfomr:1;            // vfo/mr
51
  u8 keylock_off:1,      // key lock (inverted)
52
     txstop_off:1,       // tx stop (inverted)
53
     scanm:1,            // scan key/mode
54
     vir:1,              // vox inhibit on receive
55
     keylockm:2,         // key lock mode
56
     lamp:2;             // backlight
57
  u8 opendis:2,          // open display
58
     fmen_off:1,         // fm enable (inverted)
59
     unknown1:1,
60
     fmscan_off:1,       // fm scan (inverted)
61
     fmdw:1,             // fm dual watch
62
     unknown2:2;
63
  u8 step:4,             // step
64
     vol:4;              // volume
65
  u8 apo:4,              // auto power off
66
     tot:4;              // time out timer
67
  u8 unknown0x018C;
68
  u8 voxdt:4,            // vox delay time
69
     voxgain:4;          // vox gain
70
  u8 unknown0x018E;
71
  u8 unknown0x018F;
72
  u8 unknown:3,
73
     lptime:5;           // long press time
74
  u8 keyp2long:4,        // p2 key long press
75
     keyp2short:4;       // p2 key short press
76
  u8 keyp1long:4,        // p1 key long press
77
     keyp1short:4;       // p1 key short press
78
  u8 keyp3long:4,        // p3 key long press
79
     keyp3short:4;       // p3 key short press
80
  u8 unknown0x0194;
81
  u8 menuen:1,           // menu enable
82
     absel:1,            // a/b select
83
     unknown:2
84
     keymshort:4;        // m key short press
85
  u8 unknown:4,
86
     dtmfst:1,           // dtmf sidetone
87
     ackdecode:1,        // ack decode
88
     monitor:2;          // monitor
89
  u8 unknown1:3,
90
     reset:1,            // reset enable
91
     unknown2:1,
92
     keypadmic_off:1,    // keypad mic (inverted)
93
     unknown3:2;
94
  u8 unknown0x0198;
95
  u8 unknown1:3,
96
     dtmftime:5;         // dtmf digit time
97
  u8 unknown1:3,
98
     dtmfspace:5;        // dtmf digit space time
99
  u8 unknown1:2,
100
     dtmfdelay:6;        // dtmf first digit delay
101
  u8 unknown1:1,
102
     dtmfpretime:7;      // dtmf pretime
103
  u8 unknown1:2,
104
     dtmfdelay2:6;       // dtmf * and # digit delay
105
  u8 unknown1:3,
106
     smfont_off:1,       // small font (inverted)
107
     unknown:4;
108
} settings;
109

    
110
#seekto 0x01cd;
111
struct {
112
  u8 rssi136;            // squelch base level (vhf)
113
  u8 unknown0x01ce;
114
  u8 rssi400;            // squelch base level (uhf)
115
} service;
116

    
117
#seekto 0x0900;
118
struct {
119
  char user1[7];         // user message 1
120
  char unknown0x0907;
121
  char unknown0x0908[8];
122
  char unknown0x0910[8];
123
  char system[7];        // system message
124
  char unknown0x091F;
125
  char user2[7];         // user message 2
126
  char unknown0x0927;
127
} messages;
128

    
129
struct channel {
130
  bbcd rx_freq[4];
131
  bbcd tx_freq[4];
132
  u8 rx_tone;
133
  u8 rx_tmode_extra:6,
134
     rx_tmode:2;
135
  u8 tx_tone;
136
  u8 tx_tmode_extra:6,
137
     tx_tmode:2;
138
  u8 unknown5;
139
  u8 pttidoff:1,
140
     dtmfoff:1,
141
     %(unknownormode)s,
142
     tailcut:1,
143
     aliasop:1,
144
     talkaroundoff:1,
145
     voxoff:1,
146
     skip:1;
147
  u8 %(modeorpower)s,
148
     reverseoff:1,
149
     blckoff:1,
150
     unknown7:1,
151
     apro:3;
152
  u8 unknown8;
153
};
154

    
155
struct name {
156
    char name[7];
157
    u8 pad;
158
};
159

    
160
#seekto 0x%(chanstart)x;
161
struct channel default[%(defaults)i];
162
struct channel memory[199];
163

    
164
#seekto 0x%(namestart)x;
165
struct name defaultname[%(defaults)i];
166
struct name name[199];
167
"""
168

    
169

    
170
APO_LIST = ["OFF", "10M", "20M", "30M", "40M", "50M", "60M", "90M",
171
            "2H", "4H", "6H", "8H", "10H", "12H", "14H", "16H"]
172
SQL_LIST = ["%s" % x for x in range(0, 10)]
173
SCANM_LIST = ["CO", "TO"]
174
TOT_LIST = ["OFF"] + ["%s seconds" % x for x in range(10, 130, 10)]
175
STEP_LIST = ["2.5 KHz", "5 KHz", "6.25 KHz", "10 KHz", "12.5 KHz", "25 KHz"]
176
MONITOR_LIST = ["CTC/DCS", "DTMF", "CTC/DCS and DTMF", "CTC/DCS or DTMF"]
177
VFOMR_LIST = ["MR", "VFO"]
178
MRCHA_LIST = ["MR CHA", "Freq. MR"]
179
VOL_LIST = ["OFF"] + ["%s" % x for x in range(1, 16)]
180
OPENDIS_LIST = ["All", "Lease Time", "User-defined", "Leixen"]
181
LAMP_LIST = ["OFF", "KEY", "CONT"]
182
KEYLOCKM_LIST = ["K+S", "PTT", "KEY", "ALL"]
183
ABSEL_LIST = ["B Channel",  "A Channel"]
184
VOXGAIN_LIST = ["%s" % x for x in range(1, 9)]
185
VOXDT_LIST = ["%s seconds" % x for x in range(1, 5)]
186
DTMFTIME_LIST = ["%i milliseconds" % x for x in range(50, 210, 10)]
187
DTMFDELAY_LIST = ["%i milliseconds" % x for x in range(0, 550, 50)]
188
DTMFPRETIME_LIST = ["%i milliseconds" % x for x in range(100, 1100, 100)]
189
DTMFDELAY2_LIST = ["%i milliseconds" % x for x in range(0, 450, 50)]
190

    
191
LPTIME_LIST = ["%i milliseconds" % x for x in range(500, 2600, 100)]
192
PFKEYLONG_LIST = ["OFF",
193
                  "FM",
194
                  "Monitor Momentary",
195
                  "Monitor Lock",
196
                  "SQ Off Momentary",
197
                  "Mute",
198
                  "SCAN",
199
                  "TX Power",
200
                  "EMG",
201
                  "VFO/MR",
202
                  "DTMF",
203
                  "CALL",
204
                  "Transmit 1750Hz",
205
                  "A/B",
206
                  "Talk Around",
207
                  "Reverse"
208
                  ]
209

    
210
PFKEYSHORT_LIST = ["OFF",
211
                   "FM",
212
                   "BandChange",
213
                   "Time",
214
                   "Monitor Lock",
215
                   "Mute",
216
                   "SCAN",
217
                   "TX Power",
218
                   "EMG",
219
                   "VFO/MR",
220
                   "DTMF",
221
                   "CALL",
222
                   "Transmit 1750Hz",
223
                   "A/B",
224
                   "Talk Around",
225
                   "Reverse"
226
                   ]
227

    
228
MODES = ["NFM", "FM"]
229
WTFTONES = map(float, xrange(56, 64))
230
TONES = WTFTONES + chirp_common.TONES
231
DTCS_CODES = [17, 50, 645] + chirp_common.DTCS_CODES
232
DTCS_CODES.sort()
233
TMODES = ["", "Tone", "DTCS", "DTCS"]
234

    
235

    
236
def _image_ident_from_data(data):
237
    return data[0x168:0x178]
238

    
239

    
240
def _image_ident_from_image(radio):
241
    return _image_ident_from_data(radio.get_mmap())
242

    
243

    
244
def checksum(frame):
245
    x = 0
246
    for b in frame:
247
        x ^= ord(b)
248
    return chr(x)
249

    
250

    
251
def make_frame(cmd, addr, data=""):
252
    payload = struct.pack(">H", addr) + data
253
    header = struct.pack(">BB", ord(cmd), len(payload))
254
    frame = header + payload
255
    return frame + checksum(frame)
256

    
257

    
258
def send(radio, frame):
259
    # LOG.debug("%04i P>R: %s" %
260
    #           (len(frame),
261
    #            util.hexprint(frame).replace("\n", "\n          ")))
262
    try:
263
        radio.pipe.write(frame)
264
    except Exception, e:
265
        raise errors.RadioError("Failed to communicate with radio: %s" % e)
266

    
267

    
268
def recv(radio, readdata=True):
269
    hdr = radio.pipe.read(4)
270
    # LOG.debug("%04i P<R: %s" %
271
    #           (len(hdr), util.hexprint(hdr).replace("\n", "\n          ")))
272
    if hdr == "\x09\x00\x09":
273
        raise errors.RadioError("Radio rejected command.")
274
    cmd, length, addr = struct.unpack(">BBH", hdr)
275
    length -= 2
276
    if readdata:
277
        data = radio.pipe.read(length)
278
        # LOG.debug("     P<R: %s" %
279
        #           util.hexprint(hdr + data).replace("\n", "\n          "))
280
        if len(data) != length:
281
            raise errors.RadioError("Radio sent %i bytes (expected %i)" % (
282
                len(data), length))
283
        chk = radio.pipe.read(1)
284
    else:
285
        data = ""
286
    return addr, data
287

    
288

    
289
def do_ident(radio):
290
    send(radio, "\x02\x06LEIXEN\x17")
291
    ident = radio.pipe.read(9)
292
    LOG.debug("     P<R: %s" %
293
              util.hexprint(ident).replace("\n", "\n          "))
294
    if ident != "\x06\x06leixen\x13":
295
        raise errors.RadioError("Radio refused program mode")
296
    radio.pipe.write("\x06\x00\x06")
297
    ack = radio.pipe.read(3)
298
    if ack != "\x06\x00\x06":
299
        raise errors.RadioError("Radio did not ack.")
300

    
301

    
302
def do_download(radio):
303
    do_ident(radio)
304

    
305
    data = ""
306
    data += "\xFF" * (0 - len(data))
307
    for addr in range(0, radio._memsize, 0x10):
308
        send(radio, make_frame("R", addr, chr(0x10)))
309
        _addr, _data = recv(radio)
310
        if _addr != addr:
311
            raise errors.RadioError("Radio sent unexpected address")
312
        data += _data
313

    
314
        status = chirp_common.Status()
315
        status.cur = addr
316
        status.max = radio._memsize
317
        status.msg = "Cloning from radio"
318
        radio.status_fn(status)
319

    
320
    finish(radio)
321

    
322
    return memmap.MemoryMap(data)
323

    
324

    
325
def do_upload(radio):
326
    _ranges = [(0x0d00, 0x2000)]
327

    
328
    image_ident = _image_ident_from_image(radio)
329
    if image_ident.startswith(radio._file_ident) and \
330
       radio._model_ident in image_ident:
331
        _ranges = radio._ranges
332

    
333
    do_ident(radio)
334

    
335
    for start, end in _ranges:
336
        LOG.debug('Uploading range 0x%04X - 0x%04X' % (start, end))
337
        for addr in range(start, end, 0x10):
338
            frame = make_frame("W", addr, radio._mmap[addr:addr + 0x10])
339
            send(radio, frame)
340
            # LOG.debug("     P<R: %s" %
341
            #           util.hexprint(frame).replace("\n", "\n          "))
342
            radio.pipe.write("\x06\x00\x06")
343
            ack = radio.pipe.read(3)
344
            if ack != "\x06\x00\x06":
345
                raise errors.RadioError("Radio refused block at %04x" % addr)
346

    
347
            status = chirp_common.Status()
348
            status.cur = addr
349
            status.max = radio._memsize
350
            status.msg = "Cloning to radio"
351
            radio.status_fn(status)
352

    
353
    finish(radio)
354

    
355

    
356
def finish(radio):
357
    send(radio, "\x64\x01\x6F\x0A")
358
    ack = radio.pipe.read(8)
359

    
360

    
361
# Declaring Aliases
362
class LT898UV(chirp_common.Alias):
363
    VENDOR = "LUITON"
364
    MODEL = "LT-898UV"
365

    
366

    
367
@directory.register
368
class LeixenVV898Radio(chirp_common.CloneModeRadio):
369

    
370
    """Leixen VV-898"""
371
    VENDOR = "Leixen"
372
    MODEL = "VV-898"
373
    ALIASES = [LT898UV, ]
374
    BAUD_RATE = 9600
375

    
376
    _file_ident = "Leixen"
377
    _model_ident = 'LX-\x89\x85\x63'
378

    
379
    _memsize = 0x2000
380
    _ranges = [
381
        (0x0000, 0x013f),
382
        (0x0148, 0x0167),
383
        (0x0184, 0x018f),
384
        (0x0190, 0x01cf),
385
        (0x0900, 0x090f),
386
        (0x0920, 0x0927),
387
        (0x0d00, 0x2000),
388
    ]
389

    
390
    _mem_formatter = {'unknownormode': 'unknown6:1',
391
                      'modeorpower': 'mode:1, power:1',
392
                      'chanstart': 0x0D00,
393
                      'namestart': 0x19B0,
394
                      'defaults': 3}
395
    _power_levels = [chirp_common.PowerLevel("Low", watts=4),
396
                     chirp_common.PowerLevel("High", watts=10)]
397

    
398
    def get_features(self):
399
        rf = chirp_common.RadioFeatures()
400
        rf.has_settings = True
401
        rf.has_cross = True
402
        rf.has_bank = False
403
        rf.has_tuning_step = False
404
        rf.can_odd_split = True
405
        rf.has_rx_dtcs = True
406
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
407
        rf.valid_modes = MODES
408
        rf.valid_cross_modes = [
409
            "Tone->Tone",
410
            "DTCS->",
411
            "->DTCS",
412
            "Tone->DTCS",
413
            "DTCS->Tone",
414
            "->Tone",
415
            "DTCS->DTCS"]
416
        rf.valid_characters = chirp_common.CHARSET_ASCII
417
        rf.valid_name_length = 7
418
        rf.valid_power_levels = self._power_levels
419
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
420
        rf.valid_skips = ["", "S"]
421
        rf.valid_bands = [(136000000, 174000000),
422
                          (400000000, 470000000)]
423
        rf.memory_bounds = (1, 199)
424
        return rf
425

    
426
    def sync_in(self):
427
        try:
428
            self._mmap = do_download(self)
429
        except Exception, e:
430
            finish(self)
431
            raise errors.RadioError("Failed to download from radio: %s" % e)
432
        self.process_mmap()
433

    
434
    def process_mmap(self):
435
        self._memobj = bitwise.parse(
436
            MEM_FORMAT % self._mem_formatter, self._mmap)
437

    
438
    def sync_out(self):
439
        try:
440
            do_upload(self)
441
        except errors.RadioError:
442
            finish(self)
443
            raise
444
        except Exception, e:
445
            raise errors.RadioError("Failed to upload to radio: %s" % e)
446

    
447
    def get_raw_memory(self, number):
448
        name, mem = self._get_memobjs(number)
449
        return repr(name) + repr(mem)
450

    
451
    def _get_tone(self, mem, _mem):
452
        rx_tone = tx_tone = None
453

    
454
        tx_tmode = TMODES[_mem.tx_tmode]
455
        rx_tmode = TMODES[_mem.rx_tmode]
456

    
457
        if tx_tmode == "Tone":
458
            tx_tone = TONES[_mem.tx_tone - 1]
459
        elif tx_tmode == "DTCS":
460
            tx_tone = DTCS_CODES[_mem.tx_tone - 1]
461

    
462
        if rx_tmode == "Tone":
463
            rx_tone = TONES[_mem.rx_tone - 1]
464
        elif rx_tmode == "DTCS":
465
            rx_tone = DTCS_CODES[_mem.rx_tone - 1]
466

    
467
        tx_pol = _mem.tx_tmode == 0x03 and "R" or "N"
468
        rx_pol = _mem.rx_tmode == 0x03 and "R" or "N"
469

    
470
        chirp_common.split_tone_decode(mem, (tx_tmode, tx_tone, tx_pol),
471
                                       (rx_tmode, rx_tone, rx_pol))
472

    
473
    def _is_txinh(self, _mem):
474
        raw_tx = ""
475
        for i in range(0, 4):
476
            raw_tx += _mem.tx_freq[i].get_raw()
477
        return raw_tx == "\xFF\xFF\xFF\xFF"
478

    
479
    def _get_memobjs(self, number):
480
        _mem = self._memobj.memory[number - 1]
481
        _name = self._memobj.name[number - 1]
482
        return _mem, _name
483

    
484
    def get_memory(self, number):
485
        _mem, _name = self._get_memobjs(number)
486

    
487
        mem = chirp_common.Memory()
488
        mem.number = number
489

    
490
        if _mem.get_raw()[:4] == "\xFF\xFF\xFF\xFF":
491
            mem.empty = True
492
            return mem
493

    
494
        mem.freq = int(_mem.rx_freq) * 10
495

    
496
        if self._is_txinh(_mem):
497
            mem.duplex = "off"
498
            mem.offset = 0
499
        elif int(_mem.rx_freq) == int(_mem.tx_freq):
500
            mem.duplex = ""
501
            mem.offset = 0
502
        elif abs(int(_mem.rx_freq) * 10 - int(_mem.tx_freq) * 10) > 70000000:
503
            mem.duplex = "split"
504
            mem.offset = int(_mem.tx_freq) * 10
505
        else:
506
            mem.duplex = int(_mem.rx_freq) > int(_mem.tx_freq) and "-" or "+"
507
            mem.offset = abs(int(_mem.rx_freq) - int(_mem.tx_freq)) * 10
508

    
509
        mem.name = str(_name.name).rstrip()
510

    
511
        self._get_tone(mem, _mem)
512
        mem.mode = MODES[_mem.mode]
513
        powerindex = _mem.power if _mem.power < len(self._power_levels) else -1
514
        mem.power = self._power_levels[powerindex]
515
        mem.skip = _mem.skip and "S" or ""
516

    
517
        mem.extra = RadioSettingGroup("Extra", "extra")
518

    
519
        opts = ["On", "Off"]
520
        rs = RadioSetting("blckoff", "Busy Channel Lockout",
521
                          RadioSettingValueList(
522
                              opts, opts[_mem.blckoff]))
523
        mem.extra.append(rs)
524
        opts = ["Off", "On"]
525
        rs = RadioSetting("tailcut", "Squelch Tail Elimination",
526
                          RadioSettingValueList(
527
                              opts, opts[_mem.tailcut]))
528
        mem.extra.append(rs)
529
        apro = _mem.apro if _mem.apro < 0x5 else 0
530
        opts = ["Off", "Compander", "Scrambler", "TX Scrambler",
531
                "RX Scrambler"]
532
        rs = RadioSetting("apro", "Audio Processing",
533
                          RadioSettingValueList(
534
                              opts, opts[apro]))
535
        mem.extra.append(rs)
536
        opts = ["On", "Off"]
537
        rs = RadioSetting("voxoff", "VOX",
538
                          RadioSettingValueList(
539
                              opts, opts[_mem.voxoff]))
540
        mem.extra.append(rs)
541
        opts = ["On", "Off"]
542
        rs = RadioSetting("pttidoff", "PTT ID",
543
                          RadioSettingValueList(
544
                              opts, opts[_mem.pttidoff]))
545
        mem.extra.append(rs)
546
        opts = ["On", "Off"]
547
        rs = RadioSetting("dtmfoff", "DTMF",
548
                          RadioSettingValueList(
549
                              opts, opts[_mem.dtmfoff]))
550
        mem.extra.append(rs)
551
        opts = ["Name", "Frequency"]
552
        aliasop = RadioSetting("aliasop", "Display",
553
                               RadioSettingValueList(
554
                                   opts, opts[_mem.aliasop]))
555
        mem.extra.append(aliasop)
556
        opts = ["On", "Off"]
557
        rs = RadioSetting("reverseoff", "Reverse Frequency",
558
                          RadioSettingValueList(
559
                              opts, opts[_mem.reverseoff]))
560
        mem.extra.append(rs)
561
        opts = ["On", "Off"]
562
        rs = RadioSetting("talkaroundoff", "Talk Around",
563
                          RadioSettingValueList(
564
                              opts, opts[_mem.talkaroundoff]))
565
        mem.extra.append(rs)
566

    
567
        return mem
568

    
569
    def _set_tone(self, mem, _mem):
570
        ((txmode, txtone, txpol),
571
         (rxmode, rxtone, rxpol)) = chirp_common.split_tone_encode(mem)
572

    
573
        _mem.tx_tmode = TMODES.index(txmode)
574
        _mem.rx_tmode = TMODES.index(rxmode)
575
        if txmode == "Tone":
576
            _mem.tx_tone = TONES.index(txtone) + 1
577
        elif txmode == "DTCS":
578
            _mem.tx_tmode = txpol == "R" and 0x03 or 0x02
579
            _mem.tx_tone = DTCS_CODES.index(txtone) + 1
580
        if rxmode == "Tone":
581
            _mem.rx_tone = TONES.index(rxtone) + 1
582
        elif rxmode == "DTCS":
583
            _mem.rx_tmode = rxpol == "R" and 0x03 or 0x02
584
            _mem.rx_tone = DTCS_CODES.index(rxtone) + 1
585

    
586
    def set_memory(self, mem):
587
        _mem, _name = self._get_memobjs(mem.number)
588

    
589
        if mem.empty:
590
            _mem.set_raw("\xFF" * 16)
591
            return
592
        elif _mem.get_raw() == ("\xFF" * 16):
593
            _mem.set_raw("\xFF" * 8 + "\xFF\x00\xFF\x00\xFF\xFE\xF0\xFC")
594

    
595
        _mem.rx_freq = mem.freq / 10
596

    
597
        if mem.duplex == "off":
598
            for i in range(0, 4):
599
                _mem.tx_freq[i].set_raw("\xFF")
600
        elif mem.duplex == "split":
601
            _mem.tx_freq = mem.offset / 10
602
        elif mem.duplex == "+":
603
            _mem.tx_freq = (mem.freq + mem.offset) / 10
604
        elif mem.duplex == "-":
605
            _mem.tx_freq = (mem.freq - mem.offset) / 10
606
        else:
607
            _mem.tx_freq = mem.freq / 10
608

    
609
        self._set_tone(mem, _mem)
610

    
611
        _mem.power = mem.power and self._power_levels.index(mem.power) or 0
612
        _mem.mode = MODES.index(mem.mode)
613
        _mem.skip = mem.skip == "S"
614
        _name.name = mem.name.ljust(7)
615

    
616
        # autoset display to name if filled, else show frequency
617
        if mem.extra:
618
            # mem.extra only seems to be populated when called from edit panel
619
            aliasop = mem.extra["aliasop"]
620
        else:
621
            aliasop = None
622
        if mem.name:
623
            _mem.aliasop = False
624
            if aliasop and not aliasop.changed():
625
                aliasop.value = "Name"
626
        else:
627
            _mem.aliasop = True
628
            if aliasop and not aliasop.changed():
629
                aliasop.value = "Frequency"
630

    
631
        for setting in mem.extra:
632
            setattr(_mem, setting.get_name(), setting.value)
633

    
634
    def _get_settings(self):
635
        _settings = self._memobj.settings
636
        _service = self._memobj.service
637
        _msg = self._memobj.messages
638
        cfg_grp = RadioSettingGroup("cfg_grp", "Basic Settings")
639
        adv_grp = RadioSettingGroup("adv_grp", "Advanced Settings")
640
        key_grp = RadioSettingGroup("key_grp", "Key Assignment")
641
        group = RadioSettings(cfg_grp, adv_grp, key_grp)
642

    
643
        #
644
        # Basic Settings
645
        #
646
        rs = RadioSetting("apo", "Auto Power Off",
647
                          RadioSettingValueList(
648
                              APO_LIST, APO_LIST[_settings.apo]))
649
        cfg_grp.append(rs)
650
        rs = RadioSetting("sql", "Squelch Level",
651
                          RadioSettingValueList(
652
                              SQL_LIST, SQL_LIST[_settings.sql]))
653
        cfg_grp.append(rs)
654
        rs = RadioSetting("scanm", "Scan Mode",
655
                          RadioSettingValueList(
656
                              SCANM_LIST, SCANM_LIST[_settings.scanm]))
657
        cfg_grp.append(rs)
658
        rs = RadioSetting("tot", "Time Out Timer",
659
                          RadioSettingValueList(
660
                              TOT_LIST, TOT_LIST[_settings.tot]))
661
        cfg_grp.append(rs)
662
        rs = RadioSetting("step", "Step",
663
                          RadioSettingValueList(
664
                              STEP_LIST, STEP_LIST[_settings.step]))
665
        cfg_grp.append(rs)
666
        rs = RadioSetting("monitor", "Monitor",
667
                          RadioSettingValueList(
668
                              MONITOR_LIST, MONITOR_LIST[_settings.monitor]))
669
        cfg_grp.append(rs)
670
        rs = RadioSetting("vfomr", "VFO/MR",
671
                          RadioSettingValueList(
672
                              VFOMR_LIST, VFOMR_LIST[_settings.vfomr]))
673
        cfg_grp.append(rs)
674
        rs = RadioSetting("mrcha", "MR/CHA",
675
                          RadioSettingValueList(
676
                              MRCHA_LIST, MRCHA_LIST[_settings.mrcha]))
677
        cfg_grp.append(rs)
678
        rs = RadioSetting("vol", "Volume",
679
                          RadioSettingValueList(
680
                              VOL_LIST, VOL_LIST[_settings.vol]))
681
        cfg_grp.append(rs)
682
        rs = RadioSetting("opendis", "Open Display",
683
                          RadioSettingValueList(
684
                              OPENDIS_LIST, OPENDIS_LIST[_settings.opendis]))
685
        cfg_grp.append(rs)
686

    
687
        def _filter(name):
688
            filtered = ""
689
            for char in str(name):
690
                if char in chirp_common.CHARSET_ASCII:
691
                    filtered += char
692
                else:
693
                    filtered += " "
694
            LOG.debug("Filtered: %s" % filtered)
695
            return filtered
696

    
697
        rs = RadioSetting("messages.user1", "User-defined Message 1",
698
                          RadioSettingValueString(0, 7, _filter(_msg.user1)))
699
        cfg_grp.append(rs)
700
        rs = RadioSetting("messages.user2", "User-defined Message 2",
701
                          RadioSettingValueString(0, 7, _filter(_msg.user2)))
702
        cfg_grp.append(rs)
703

    
704
        val = RadioSettingValueString(0, 7, _filter(_msg.system))
705
        val.set_mutable(False)
706
        rs = RadioSetting("messages.system", "System Message", val)
707
        cfg_grp.append(rs)
708

    
709
        rs = RadioSetting("lamp", "Backlight",
710
                          RadioSettingValueList(
711
                              LAMP_LIST, LAMP_LIST[_settings.lamp]))
712
        cfg_grp.append(rs)
713
        rs = RadioSetting("keylockm", "Key Lock Mode",
714
                          RadioSettingValueList(
715
                              KEYLOCKM_LIST,
716
                              KEYLOCKM_LIST[_settings.keylockm]))
717
        cfg_grp.append(rs)
718
        rs = RadioSetting("absel", "A/B Select",
719
                          RadioSettingValueList(ABSEL_LIST,
720
                                                ABSEL_LIST[_settings.absel]))
721
        cfg_grp.append(rs)
722

    
723
        rs = RadioSetting("obeep", "Open Beep",
724
                          RadioSettingValueBoolean(_settings.obeep))
725
        cfg_grp.append(rs)
726
        rs = RadioSetting("rbeep", "Roger Beep",
727
                          RadioSettingValueBoolean(_settings.rbeep))
728
        cfg_grp.append(rs)
729
        rs = RadioSetting("keylock_off", "Key Lock",
730
                          RadioSettingValueBoolean(not _settings.keylock_off))
731
        cfg_grp.append(rs)
732
        rs = RadioSetting("ctdcsb", "CT/DCS Busy Lock",
733
                          RadioSettingValueBoolean(_settings.ctdcsb))
734
        cfg_grp.append(rs)
735
        rs = RadioSetting("alarm", "Alarm Key",
736
                          RadioSettingValueBoolean(_settings.alarm))
737
        cfg_grp.append(rs)
738
        rs = RadioSetting("save", "Battery Save",
739
                          RadioSettingValueBoolean(_settings.save))
740
        cfg_grp.append(rs)
741
        rs = RadioSetting("kbeep", "Key Beep",
742
                          RadioSettingValueBoolean(_settings.kbeep))
743
        cfg_grp.append(rs)
744
        rs = RadioSetting("reset", "Reset Enable",
745
                          RadioSettingValueBoolean(_settings.reset))
746
        cfg_grp.append(rs)
747
        rs = RadioSetting("smfont_off", "Small Font",
748
                          RadioSettingValueBoolean(not _settings.smfont_off))
749
        cfg_grp.append(rs)
750
        rs = RadioSetting("aliasen_off", "Alias Enable",
751
                          RadioSettingValueBoolean(not _settings.aliasen_off))
752
        cfg_grp.append(rs)
753
        rs = RadioSetting("txstop_off", "TX Stop",
754
                          RadioSettingValueBoolean(not _settings.txstop_off))
755
        cfg_grp.append(rs)
756
        rs = RadioSetting("dw_off", "Dual Watch",
757
                          RadioSettingValueBoolean(not _settings.dw_off))
758
        cfg_grp.append(rs)
759
        rs = RadioSetting("fmen_off", "FM Enable",
760
                          RadioSettingValueBoolean(not _settings.fmen_off))
761
        cfg_grp.append(rs)
762
        rs = RadioSetting("fmdw", "FM Dual Watch",
763
                          RadioSettingValueBoolean(_settings.fmdw))
764
        cfg_grp.append(rs)
765
        rs = RadioSetting("fmscan_off", "FM Scan",
766
                          RadioSettingValueBoolean(
767
                              not _settings.fmscan_off))
768
        cfg_grp.append(rs)
769
        rs = RadioSetting("keypadmic_off", "Keypad MIC",
770
                          RadioSettingValueBoolean(
771
                              not _settings.keypadmic_off))
772
        cfg_grp.append(rs)
773
        rs = RadioSetting("voxgain", "VOX Gain",
774
                          RadioSettingValueList(
775
                              VOXGAIN_LIST, VOXGAIN_LIST[_settings.voxgain]))
776
        cfg_grp.append(rs)
777
        rs = RadioSetting("voxdt", "VOX Delay Time",
778
                          RadioSettingValueList(
779
                              VOXDT_LIST, VOXDT_LIST[_settings.voxdt]))
780
        cfg_grp.append(rs)
781
        rs = RadioSetting("vir", "VOX Inhibit on Receive",
782
                          RadioSettingValueBoolean(_settings.vir))
783
        cfg_grp.append(rs)
784

    
785
        #
786
        # Advanced Settings
787
        #
788
        val = (_settings.dtmftime) - 5
789
        rs = RadioSetting("dtmftime", "DTMF Digit Time",
790
                          RadioSettingValueList(
791
                              DTMFTIME_LIST, DTMFTIME_LIST[val]))
792
        adv_grp.append(rs)
793
        val = (_settings.dtmfspace) - 5
794
        rs = RadioSetting("dtmfspace", "DTMF Digit Space Time",
795
                          RadioSettingValueList(
796
                              DTMFTIME_LIST, DTMFTIME_LIST[val]))
797
        adv_grp.append(rs)
798
        val = (_settings.dtmfdelay) / 5
799
        rs = RadioSetting("dtmfdelay", "DTMF 1st Digit Delay",
800
                          RadioSettingValueList(
801
                              DTMFDELAY_LIST, DTMFDELAY_LIST[val]))
802
        adv_grp.append(rs)
803
        val = (_settings.dtmfpretime) / 10 - 1
804
        rs = RadioSetting("dtmfpretime", "DTMF Pretime",
805
                          RadioSettingValueList(
806
                              DTMFPRETIME_LIST, DTMFPRETIME_LIST[val]))
807
        adv_grp.append(rs)
808
        val = (_settings.dtmfdelay2) / 5
809
        rs = RadioSetting("dtmfdelay2", "DTMF * and # Digit Delay",
810
                          RadioSettingValueList(
811
                              DTMFDELAY2_LIST, DTMFDELAY2_LIST[val]))
812
        adv_grp.append(rs)
813
        rs = RadioSetting("ackdecode", "ACK Decode",
814
                          RadioSettingValueBoolean(_settings.ackdecode))
815
        adv_grp.append(rs)
816
        rs = RadioSetting("dtmfst", "DTMF Sidetone",
817
                          RadioSettingValueBoolean(_settings.dtmfst))
818
        adv_grp.append(rs)
819

    
820
        rs = RadioSetting("service.rssi400", "Squelch Base Level (UHF)",
821
                          RadioSettingValueInteger(0, 255, _service.rssi400))
822
        adv_grp.append(rs)
823
        rs = RadioSetting("service.rssi136", "Squelch Base Level (VHF)",
824
                          RadioSettingValueInteger(0, 255, _service.rssi136))
825
        adv_grp.append(rs)
826

    
827
        #
828
        # Key Settings
829
        #
830
        val = (_settings.lptime) - 5
831
        rs = RadioSetting("lptime", "Long Press Time",
832
                          RadioSettingValueList(
833
                              LPTIME_LIST, LPTIME_LIST[val]))
834
        key_grp.append(rs)
835
        rs = RadioSetting("keyp1long", "P1 Long Key",
836
                          RadioSettingValueList(
837
                              PFKEYLONG_LIST,
838
                              PFKEYLONG_LIST[_settings.keyp1long]))
839
        key_grp.append(rs)
840
        rs = RadioSetting("keyp1short", "P1 Short Key",
841
                          RadioSettingValueList(
842
                              PFKEYSHORT_LIST,
843
                              PFKEYSHORT_LIST[_settings.keyp1short]))
844
        key_grp.append(rs)
845
        rs = RadioSetting("keyp2long", "P2 Long Key",
846
                          RadioSettingValueList(
847
                              PFKEYLONG_LIST,
848
                              PFKEYLONG_LIST[_settings.keyp2long]))
849
        key_grp.append(rs)
850
        rs = RadioSetting("keyp2short", "P2 Short Key",
851
                          RadioSettingValueList(
852
                              PFKEYSHORT_LIST,
853
                              PFKEYSHORT_LIST[_settings.keyp2short]))
854
        key_grp.append(rs)
855
        rs = RadioSetting("keyp3long", "P3 Long Key",
856
                          RadioSettingValueList(
857
                              PFKEYLONG_LIST,
858
                              PFKEYLONG_LIST[_settings.keyp3long]))
859
        key_grp.append(rs)
860
        rs = RadioSetting("keyp3short", "P3 Short Key",
861
                          RadioSettingValueList(
862
                              PFKEYSHORT_LIST,
863
                              PFKEYSHORT_LIST[_settings.keyp3short]))
864
        key_grp.append(rs)
865

    
866
        val = RadioSettingValueList(PFKEYSHORT_LIST,
867
                                    PFKEYSHORT_LIST[_settings.keymshort])
868
        val.set_mutable(_settings.menuen == 0)
869
        rs = RadioSetting("keymshort", "M Short Key", val)
870
        key_grp.append(rs)
871
        val = RadioSettingValueBoolean(_settings.menuen)
872
        rs = RadioSetting("menuen", "Menu Enable", val)
873
        key_grp.append(rs)
874

    
875
        return group
876

    
877
    def get_settings(self):
878
        try:
879
            return self._get_settings()
880
        except:
881
            import traceback
882
            LOG.error("Failed to parse settings: %s", traceback.format_exc())
883
            return None
884

    
885
    def set_settings(self, settings):
886
        _settings = self._memobj.settings
887
        for element in settings:
888
            if not isinstance(element, RadioSetting):
889
                self.set_settings(element)
890
                continue
891
            else:
892
                try:
893
                    name = element.get_name()
894
                    if "." in name:
895
                        bits = name.split(".")
896
                        obj = self._memobj
897
                        for bit in bits[:-1]:
898
                            if "/" in bit:
899
                                bit, index = bit.split("/", 1)
900
                                index = int(index)
901
                                obj = getattr(obj, bit)[index]
902
                            else:
903
                                obj = getattr(obj, bit)
904
                        setting = bits[-1]
905
                    else:
906
                        obj = _settings
907
                        setting = element.get_name()
908

    
909
                    if element.has_apply_callback():
910
                        LOG.debug("Using apply callback")
911
                        element.run_apply_callback()
912
                    elif setting == "keylock_off":
913
                        setattr(obj, setting, not int(element.value))
914
                    elif setting == "smfont_off":
915
                        setattr(obj, setting, not int(element.value))
916
                    elif setting == "aliasen_off":
917
                        setattr(obj, setting, not int(element.value))
918
                    elif setting == "txstop_off":
919
                        setattr(obj, setting, not int(element.value))
920
                    elif setting == "dw_off":
921
                        setattr(obj, setting, not int(element.value))
922
                    elif setting == "fmen_off":
923
                        setattr(obj, setting, not int(element.value))
924
                    elif setting == "fmscan_off":
925
                        setattr(obj, setting, not int(element.value))
926
                    elif setting == "keypadmic_off":
927
                        setattr(obj, setting, not int(element.value))
928
                    elif setting == "dtmftime":
929
                        setattr(obj, setting, int(element.value) + 5)
930
                    elif setting == "dtmfspace":
931
                        setattr(obj, setting, int(element.value) + 5)
932
                    elif setting == "dtmfdelay":
933
                        setattr(obj, setting, int(element.value) * 5)
934
                    elif setting == "dtmfpretime":
935
                        setattr(obj, setting, (int(element.value) + 1) * 10)
936
                    elif setting == "dtmfdelay2":
937
                        setattr(obj, setting, int(element.value) * 5)
938
                    elif setting == "lptime":
939
                        setattr(obj, setting, int(element.value) + 5)
940
                    else:
941
                        LOG.debug("Setting %s = %s" % (setting, element.value))
942
                        setattr(obj, setting, element.value)
943
                except Exception, e:
944
                    LOG.debug(element.get_name())
945
                    raise
946

    
947
    @classmethod
948
    def match_model(cls, filedata, filename):
949
        if filedata[0x168:0x170].startswith(cls._file_ident) and \
950
           filedata[0x170:0x178].startswith(cls._model_ident):
951
            return True
952
        else:
953
            return False
954

    
955

    
956
@directory.register
957
class JetstreamJT270MRadio(LeixenVV898Radio):
958

    
959
    """Jetstream JT270M"""
960
    VENDOR = "Jetstream"
961
    MODEL = "JT270M"
962

    
963
    _file_ident = "JET"
964
    _model_ident = 'LX-\x89\x85\x53'
965

    
966

    
967
class VV898E(chirp_common.Alias):
968

    
969
    '''Leixen has called this radio both 898E and S historically, ident is
970
    identical'''
971
    VENDOR = "Leixen"
972
    MODEL = "VV-898E"
973

    
974

    
975
@directory.register
976
class LeixenVV898SRadio(LeixenVV898Radio):
977

    
978
    """Leixen VV-898S, also VV-898E which is identical"""
979
    VENDOR = "Leixen"
980
    MODEL = "VV-898S"
981
    ALIASES = [VV898E, ]
982

    
983
    _model_ident = 'LX-\x89\x85\x75'
984
    _mem_formatter = {'unknownormode': 'mode:1',
985
                      'modeorpower': 'power:2',
986
                      'chanstart': 0x0D00,
987
                      'namestart': 0x19B0,
988
                      'defaults': 3}
989
    _power_levels = [chirp_common.PowerLevel("Low", watts=5),
990
                     chirp_common.PowerLevel("Med", watts=10),
991
                     chirp_common.PowerLevel("High", watts=25)]
992

    
993

    
994
@directory.register
995
class LeixenVV898SDualBankRadio(LeixenVV898SRadio):
996

    
997
    """Jetstream JT270MH"""
998
    VENDOR = "Leixen"
999
    MODEL = "VV898SDualBank"
1000

    
1001
    _file_ident = "Leixen"
1002
    _model_ident = 'LX-\x89\x85\x85'
1003
    _ranges = [
1004
        (0x0000, 0x013f),
1005
        (0x0148, 0x0167),
1006
        (0x0184, 0x018f),
1007
        (0x0190, 0x01cf),
1008
        (0x0900, 0x090f),
1009
        (0x0920, 0x0927),
1010
        (0x0c00, 0x2000),
1011
    ]
1012
    _mem_formatter = {'unknownormode': 'mode:1',
1013
                      'modeorpower': 'power:2',
1014
                      'chanstart': 0x0C00,
1015
                      'namestart': 0x1900,
1016
                      'defaults': 6}
1017

    
1018
    def get_features(self):
1019
        rf = super(LeixenVV898SDualBankRadio, self).get_features()
1020
        rf.has_sub_devices = self.VARIANT == ''
1021
        rf.memory_bounds = (1, 99)
1022
        return rf
1023

    
1024
    def get_sub_devices(self):
1025
        return [LeixenVV898SDualBankRadioA(self._mmap),
1026
                LeixenVV898SDualBankRadioB(self._mmap)]
1027

    
1028
    def _get_memobjs(self, number):
1029
        number = number * 2 - self._offset
1030
        _mem = self._memobj.memory[number]
1031
        _name = self._memobj.name[number]
1032
        return _mem, _name
1033

    
1034

    
1035
class LeixenVV898SDualBankRadioA(LeixenVV898SDualBankRadio):
1036
    VARIANT = 'A Band'
1037
    _offset = 1
1038

    
1039

    
1040
class LeixenVV898SDualBankRadioB(LeixenVV898SDualBankRadio):
1041
    VARIANT = 'B Band'
1042
    _offset = 2
1043

    
1044

    
1045
@directory.register
1046
class JetstreamJT270MH(LeixenVV898SDualBankRadio):
1047

    
1048
    """Jetstream JT270MH, same ident as dual bank Leixens"""
1049
    VENDOR = "Jetstream"
1050
    MODEL = "JT270MH"
1051
    _file_ident = "JET"