Project

General

Profile

New Model #6493 ยป btech_kt5800.py

Test driver module for QYT KT-5800 - Jim Unroe, 12/25/2020 10:43 AM

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

    
18
import time
19
import struct
20
import logging
21

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

    
31
LOG = logging.getLogger(__name__)
32

    
33
# A note about the memmory in these radios
34
#
35
# The real memory of these radios extends to 0x4000
36
# On read the factory software only uses up to 0x3200
37
# On write it just uploads the contents up to 0x3100
38
#
39
# The mem beyond 0x3200 holds the ID data
40

    
41
MEM_SIZE = 0x4000
42
BLOCK_SIZE = 0x40
43
TX_BLOCK_SIZE = 0x10
44
ACK_CMD = "\x06"
45
MODES = ["FM", "NFM"]
46
SKIP_VALUES = ["S", ""]
47
TONES = chirp_common.TONES
48
DTCS = sorted(chirp_common.DTCS_CODES + [645])
49

    
50
# lists related to "extra" settings
51
PTTID_LIST = ["OFF", "BOT", "EOT", "BOTH"]
52
PTTIDCODE_LIST = ["%s" % x for x in range(1, 16)]
53
OPTSIG_LIST = ["OFF", "DTMF", "2TONE", "5TONE"]
54
SPMUTE_LIST = ["Tone/DTCS", "Tone/DTCS and Optsig", "Tone/DTCS or Optsig"]
55

    
56
# lists
57
LIST_AB = ["A", "B"]
58
LIST_ABCD = LIST_AB + ["C", "D"]
59
LIST_ANIL = ["3", "4", "5"]
60
LIST_APO = ["Off"] + ["%s minutes" % x for x in range(30, 330, 30)]
61
LIST_COLOR4 = ["Off", "Blue", "Orange", "Purple"]
62
LIST_COLOR8 = ["White", "Red", "Blue", "Green", "Yellow", "Indego",
63
               "Purple", "Gray"]
64
LIST_COLOR9 = ["Black"] + LIST_COLOR8
65
LIST_DTMFST = ["OFF", "Keyboard", "ANI", "Keyboad + ANI"]
66
LIST_EMCTP = ["TX alarm sound", "TX ANI", "Both"]
67
LIST_EMCTPX = ["Off"] + LIST_EMCTP
68
LIST_LANGUA = ["English", "Chinese"]
69
LIST_MDF = ["Frequency", "Channel", "Name"]
70
LIST_OFF1TO9 = ["Off"] + ["%s seconds" % x for x in range(1, 10)]
71
LIST_OFF1TO10 = ["Off"] + ["%s seconds" % x for x in range(1, 11)]
72
LIST_OFF1TO50 = ["Off"] + ["%s seconds" % x for x in range(1, 51)]
73
LIST_PONMSG = ["Full", "Message", "Battery voltage"]
74
LIST_REPM = ["Off", "Carrier", "CTCSS or DCS", "Tone", "DTMF"]
75
LIST_REPS = ["1000 Hz", "1450 Hz", "1750 Hz", "2100Hz"]
76
LIST_RPTDL = ["Off"] + ["%s ms" % x for x in range(1, 10)]
77
LIST_SCMODE = ["Off", "PTT-SC", "MEM-SC", "PON-SC"]
78
LIST_SHIFT = ["Off", "+", "-"]
79
LIST_SKIPTX = ["Off", "Skip 1", "Skip 2"]
80
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0]
81
LIST_STEP = [str(x) for x in STEPS]
82
LIST_SYNC = ["Off", "AB", "CD", "AB+CD"]
83
# the first 12 TMR choices common to all color display mobile radios
84
LIST_TMR12 = ["OFF", "M+A", "M+B", "M+C", "M+D", "M+A+B", "M+A+C", "M+A+D",
85
              "M+B+C", "M+B+D", "M+C+D", "M+A+B+C"]
86
# the 16 choice list for color display mobile radios that correctly implement
87
# the full 16 TMR choices
88
LIST_TMR16 = LIST_TMR12 + ["M+A+B+D", "M+A+C+D", "M+B+C+D", "A+B+C+D"]
89
# the 15 choice list for color mobile radios that are missing the M+A+B+D
90
# choice in the TMR menu
91
LIST_TMR15 = LIST_TMR12 + ["M+A+C+D", "M+B+C+D", "A+B+C+D"]
92
LIST_TMRTX = ["Track", "Fixed"]
93
LIST_TOT = ["%s sec" % x for x in range(15, 615, 15)]
94
LIST_TXDISP = ["Power", "Mic Volume"]
95
LIST_TXP = ["High", "Low"]
96
LIST_TXP3 = ["High", "Mid", "Low"]
97
LIST_SCREV = ["TO (timeout)", "CO (carrier operated)", "SE (search)"]
98
LIST_VFOMR = ["Frequency", "Channel"]
99
LIST_VOICE = ["Off"] + LIST_LANGUA
100
LIST_VOX = ["Off"] + ["%s" % x for x in range(1, 11)]
101
LIST_VOXT = ["%s seconds" % x for x in range(0, 21)]
102
LIST_WIDE = ["Wide", "Narrow"]
103

    
104
# lists related to DTMF, 2TONE and 5TONE settings
105
LIST_5TONE_STANDARDS = ["CCIR1", "CCIR2", "PCCIR", "ZVEI1", "ZVEI2", "ZVEI3",
106
                        "PZVEI", "DZVEI", "PDZVEI", "EEA", "EIA", "EURO",
107
                        "CCITT", "NATEL", "MODAT", "none"]
108
LIST_5TONE_STANDARDS_without_none = ["CCIR1", "CCIR2", "PCCIR", "ZVEI1",
109
                                     "ZVEI2", "ZVEI3",
110
                                     "PZVEI", "DZVEI", "PDZVEI", "EEA", "EIA",
111
                                     "EURO", "CCITT", "NATEL", "MODAT"]
112
LIST_5TONE_STANDARD_PERIODS = ["20", "30", "40", "50", "60", "70", "80", "90",
113
                               "100", "110", "120", "130", "140", "150", "160",
114
                               "170", "180", "190", "200"]
115
LIST_5TONE_DIGITS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
116
                     "B", "C", "D", "E", "F"]
117
LIST_5TONE_DELAY = ["%s ms" % x for x in range(0, 1010, 10)]
118
LIST_5TONE_RESET = ["%s ms" % x for x in range(100, 8100, 100)]
119
LIST_5TONE_RESET_COLOR = ["%s ms" % x for x in range(100, 20100, 100)]
120
LIST_DTMF_SPEED = ["%s ms" % x for x in range(50, 2010, 10)]
121
LIST_DTMF_DIGITS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B",
122
                    "C", "D", "#", "*"]
123
LIST_DTMF_VALUES = [0x0A, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
124
                    0x0D, 0x0E, 0x0F, 0x00, 0x0C, 0x0B]
125
LIST_DTMF_SPECIAL_DIGITS = ["*", "#", "A", "B", "C", "D"]
126
LIST_DTMF_SPECIAL_VALUES = [0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00]
127
LIST_DTMF_DELAY = ["%s ms" % x for x in range(100, 4100, 100)]
128
CHARSET_DTMF_DIGITS = "0123456789AaBbCcDd#*"
129
LIST_2TONE_DEC = ["A-B", "A-C", "A-D",
130
                  "B-A", "B-C", "B-D",
131
                  "C-A", "C-B", "C-D",
132
                  "D-A", "D-B", "D-C"]
133
LIST_2TONE_RESPONSE = ["None", "Alert", "Transpond", "Alert+Transpond"]
134

    
135
# This is a general serial timeout for all serial read functions.
136
# Practice has show that about 0.7 sec will be enough to cover all radios.
137
STIMEOUT = 0.7
138

    
139
# this var controls the verbosity in the debug and by default it's low (False)
140
# make it True and you will to get a very verbose debug.log
141
debug = False
142

    
143
# valid chars on the LCD, Note that " " (space) is stored as "\xFF"
144
VALID_CHARS = chirp_common.CHARSET_ALPHANUMERIC + \
145
    "`{|}!\"#$%&'()*+,-./:;<=>?@[]^_"
146

    
147

    
148
# #### ID strings #####################################################
149

    
150
# BTECH UV2501 pre-production units
151
UV2501pp_fp = "M2C294"
152
# BTECH UV2501 pre-production units 2 + and 1st Gen radios
153
UV2501pp2_fp = "M29204"
154
# B-TECH UV-2501 second generation (2G) radios
155
UV2501G2_fp = "BTG214"
156
# B-TECH UV-2501 third generation (3G) radios
157
UV2501G3_fp = "BTG324"
158

    
159
# B-TECH UV-2501+220 pre-production units
160
UV2501_220pp_fp = "M3C281"
161
# extra block read for the 2501+220 pre-production units
162
# the same for all of this radios so far
163
UV2501_220pp_id = "      280528"
164
# B-TECH UV-2501+220
165
UV2501_220_fp = "M3G201"
166
# new variant, let's call it Generation 2
167
UV2501_220G2_fp = "BTG211"
168
# B-TECH UV-2501+220 third generation (3G)
169
UV2501_220G3_fp = "BTG311"
170

    
171
# B-TECH UV-5001 pre-production units + 1st Gen radios
172
UV5001pp_fp = "V19204"
173
# B-TECH UV-5001 alpha units
174
UV5001alpha_fp = "V28204"
175
# B-TECH UV-5001 second generation (2G) radios
176
UV5001G2_fp = "BTG214"
177
# B-TECH UV-5001 second generation (2G2)
178
UV5001G22_fp = "V2G204"
179
# B-TECH UV-5001 third generation (3G)
180
UV5001G3_fp = "BTG304"
181

    
182
# B-TECH UV-25X2
183
UV25X2_fp = "UC2012"
184

    
185
# B-TECH UV-25X4
186
UV25X4_fp = "UC4014"
187

    
188
# B-TECH UV-50X2
189
UV50X2_fp = "UC2M12"
190

    
191
# B-TECH GMRS-50X1
192
GMRS50X1_fp = "NC1802"
193
GMRS50X1_fp1 = "NC1932"
194

    
195
# special var to know when we found a BTECH Gen 3
196
BTECH3 = [UV2501G3_fp, UV2501_220G3_fp, UV5001G3_fp]
197

    
198

    
199
# WACCOM Mini-8900
200
MINI8900_fp = "M28854"
201

    
202

    
203
# QYT KT-UV980
204
KTUV980_fp = "H28854"
205

    
206
# QYT KT8900
207
KT8900_fp = "M29154"
208
# New generations KT8900
209
KT8900_fp1 = "M2C234"
210
KT8900_fp2 = "M2G1F4"
211
KT8900_fp3 = "M2G2F4"
212
KT8900_fp4 = "M2G304"
213
KT8900_fp5 = "M2G314"
214
# this radio has an extra ID
215
KT8900_id = "303688"
216

    
217
# KT8900R
218
KT8900R_fp = "M3G1F4"
219
# Second Generation
220
KT8900R_fp1 = "M3G214"
221
# another model
222
KT8900R_fp2 = "M3C234"
223
# another model G4?
224
KT8900R_fp3 = "M39164"
225
# another model
226
KT8900R_fp4 = "M3G314"
227
# this radio has an extra ID
228
KT8900R_id = "280528"
229
# another extra ID in dec/2018
230
KT8900R_id2 = "\x05\x58\x3d\xf0\x10"
231

    
232
# KT7900D (quad band)
233
KT7900D_fp = "VC4004"
234
KT7900D_fp1 = "VC4284"
235
KT7900D_fp2 = "VC4264"
236
KT7900D_fp3 = "VC4114"
237
KT7900D_fp4 = "VC4104"
238
KT7900D_fp5 = "VC4254"
239

    
240
# QB25 (quad band) - a clone of KT7900D
241
QB25_fp = "QB-25"
242

    
243
# KT8900D (dual band)
244
KT8900D_fp = "VC2002"
245
KT8900D_fp1 = "VC8632"
246

    
247
# LUITON LT-588UV
248
LT588UV_fp = "V2G1F4"
249
# Added by rstrickoff gen 2 id
250
LT588UV_fp1 = "V2G214"
251

    
252
# QYT KT-8R (quad band ht)
253
KT8R_fp = "MCB264"
254
KT8R_fp1 = "MCB284"
255
KT8R_fp2 = "MC5264"
256

    
257
# QYT KT5800 (dual band)
258
KT5800_fp = "VCB222"
259

    
260

    
261
# ### MAGICS
262
# for the Waccom Mini-8900
263
MSTRING_MINI8900 = "\x55\xA5\xB5\x45\x55\x45\x4d\x02"
264
# for the B-TECH UV-2501+220 (including pre production ones)
265
MSTRING_220 = "\x55\x20\x15\x12\x12\x01\x4d\x02"
266
# for the QYT KT8900 & R
267
MSTRING_KT8900 = "\x55\x20\x15\x09\x16\x45\x4D\x02"
268
MSTRING_KT8900R = "\x55\x20\x15\x09\x25\x01\x4D\x02"
269
# magic string for all other models
270
MSTRING = "\x55\x20\x15\x09\x20\x45\x4d\x02"
271
# for the QYT KT7900D & KT8900D
272
MSTRING_KT8900D = "\x55\x20\x16\x08\x01\xFF\xDC\x02"
273
# for the BTECH UV-25X2 and UV-50X2
274
MSTRING_UV25X2 = "\x55\x20\x16\x12\x28\xFF\xDC\x02"
275
# for the BTECH UV-25X4
276
MSTRING_UV25X4 = "\x55\x20\x16\x11\x18\xFF\xDC\x02"
277
# for the BTECH GMRS-50X1
278
MSTRING_GMRS50X1 = "\x55\x20\x18\x10\x18\xFF\xDC\x02"
279
# for the QYT KT-8R
280
MSTRING_KT8R = "\x55\x20\x17\x07\x03\xFF\xDC\x02"
281

    
282

    
283
def _clean_buffer(radio):
284
    """Cleaning the read serial buffer, hard timeout to survive an infinite
285
    data stream"""
286

    
287
    # touching the serial timeout to optimize the flushing
288
    # restored at the end to the default value
289
    radio.pipe.timeout = 0.1
290
    dump = "1"
291
    datacount = 0
292

    
293
    try:
294
        while len(dump) > 0:
295
            dump = radio.pipe.read(100)
296
            datacount += len(dump)
297
            # hard limit to survive a infinite serial data stream
298
            # 5 times bigger than a normal rx block (69 bytes)
299
            if datacount > 345:
300
                seriale = "Please check your serial port selection."
301
                raise errors.RadioError(seriale)
302

    
303
        # restore the default serial timeout
304
        radio.pipe.timeout = STIMEOUT
305

    
306
    except Exception:
307
        raise errors.RadioError("Unknown error cleaning the serial buffer")
308

    
309

    
310
def _rawrecv(radio, amount):
311
    """Raw read from the radio device, less intensive way"""
312

    
313
    data = ""
314

    
315
    try:
316
        data = radio.pipe.read(amount)
317

    
318
        # DEBUG
319
        if debug is True:
320
            LOG.debug("<== (%d) bytes:\n\n%s" %
321
                      (len(data), util.hexprint(data)))
322

    
323
        # fail if no data is received
324
        if len(data) == 0:
325
            raise errors.RadioError("No data received from radio")
326

    
327
        # notice on the logs if short
328
        if len(data) < amount:
329
            LOG.warn("Short reading %d bytes from the %d requested." %
330
                     (len(data), amount))
331

    
332
    except:
333
        raise errors.RadioError("Error reading data from radio")
334

    
335
    return data
336

    
337

    
338
def _send(radio, data):
339
    """Send data to the radio device"""
340

    
341
    try:
342
        for byte in data:
343
            radio.pipe.write(byte)
344
            # Some OS (mainly Linux ones) are too fast on the serial and
345
            # get the MCU inside the radio stuck in the early stages, this
346
            # hits some models more than others.
347
            #
348
            # To cope with that we introduce a delay on the writes.
349
            # Many option have been tested (delaying only after error occures,
350
            # after short reads, only for linux, ...)
351
            # Finally, a static delay was chosen as simplest of all solutions
352
            # (Michael Wagner, OE4AMW)
353
            # (for details, see issue 3993)
354
            sleep(0.002)
355

    
356
        # DEBUG
357
        if debug is True:
358
            LOG.debug("==> (%d) bytes:\n\n%s" %
359
                      (len(data), util.hexprint(data)))
360
    except:
361
        raise errors.RadioError("Error sending data to radio")
362

    
363

    
364
def _make_frame(cmd, addr, length, data=""):
365
    """Pack the info in the headder format"""
366
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
367
    # add the data if set
368
    if len(data) != 0:
369
        frame += data
370

    
371
    return frame
372

    
373

    
374
def _recv(radio, addr):
375
    """Get data from the radio all at once to lower syscalls load"""
376

    
377
    # Get the full 69 bytes at a time to reduce load
378
    # 1 byte ACK + 4 bytes header + 64 bytes of data (BLOCK_SIZE)
379

    
380
    # get the whole block
381
    block = _rawrecv(radio, BLOCK_SIZE + 5)
382

    
383
    # basic check
384
    if len(block) < (BLOCK_SIZE + 5):
385
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
386

    
387
    # checking for the ack
388
    if block[0] != ACK_CMD:
389
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
390

    
391
    # header validation
392
    c, a, l = struct.unpack(">BHB", block[1:5])
393
    if a != addr or l != BLOCK_SIZE or c != ord("X"):
394
        LOG.debug("Invalid header for block 0x%04x" % addr)
395
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
396
        raise errors.RadioError("Invalid header for block 0x%04x:" % addr)
397

    
398
    # return the data
399
    return block[5:]
400

    
401

    
402
def _start_clone_mode(radio, status):
403
    """Put the radio in clone mode and get the ident string, 3 tries"""
404

    
405
    # cleaning the serial buffer
406
    _clean_buffer(radio)
407

    
408
    # prep the data to show in the UI
409
    status.cur = 0
410
    status.msg = "Identifying the radio..."
411
    status.max = 3
412
    radio.status_fn(status)
413

    
414
    try:
415
        for a in range(0, status.max):
416
            # Update the UI
417
            status.cur = a + 1
418
            radio.status_fn(status)
419

    
420
            # send the magic word
421
            _send(radio, radio._magic)
422

    
423
            # Now you get a x06 of ACK if all goes well
424
            ack = radio.pipe.read(1)
425

    
426
            if ack == "\x06":
427
                # DEBUG
428
                LOG.info("Magic ACK received")
429
                status.cur = status.max
430
                radio.status_fn(status)
431

    
432
                return True
433

    
434
        return False
435

    
436
    except errors.RadioError:
437
        raise
438
    except Exception, e:
439
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
440

    
441

    
442
def _do_ident(radio, status, upload=False):
443
    """Put the radio in PROGRAM mode & identify it"""
444
    #  set the serial discipline
445
    radio.pipe.baudrate = 9600
446
    radio.pipe.parity = "N"
447

    
448
    # open the radio into program mode
449
    if _start_clone_mode(radio, status) is False:
450
        msg = "Radio did not enter clone mode"
451
        # warning about old versions of QYT KT8900
452
        if radio.MODEL == "KT8900":
453
            msg += ". You may want to try it as a WACCOM MINI-8900, there is a"
454
            msg += " known variant of this radios that is a clone of it."
455
        raise errors.RadioError(msg)
456

    
457
    # Ok, get the ident string
458
    ident = _rawrecv(radio, 49)
459

    
460
    # basic check for the ident
461
    if len(ident) != 49:
462
        raise errors.RadioError("Radio send a short ident block.")
463

    
464
    # check if ident is OK
465
    itis = False
466
    for fp in radio._fileid:
467
        if fp in ident:
468
            # got it!
469
            itis = True
470
            # checking if we are dealing with a Gen 3 BTECH
471
            if radio.VENDOR == "BTECH" and fp in BTECH3:
472
                radio.btech3 = True
473

    
474
            break
475

    
476
    if itis is False:
477
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
478
        raise errors.RadioError("Radio identification failed.")
479

    
480
    # some radios needs a extra read and check for a code on it, this ones
481
    # has the check value in the _id2 var, others simply False
482
    if radio._id2 is not False:
483
        # lower the timeout here as this radios are reseting due to timeout
484
        radio.pipe.timeout = 0.05
485

    
486
        # query & receive the extra ID
487
        _send(radio, _make_frame("S", 0x3DF0, 16))
488
        id2 = _rawrecv(radio, 21)
489

    
490
        # WARNING !!!!!!
491
        # different radios send a response with a different amount of data
492
        # it seems that it's padded with \xff, \x20 and some times with \x00
493
        # we just care about the first 16, our magic string is in there
494
        if len(id2) < 16:
495
            raise errors.RadioError("The extra ID is short, aborting.")
496

    
497
        # ok, the correct string must be in the received data
498
        # the radio._id2 var will be always a list
499
        flag2 = False
500
        for _id2 in radio._id2:
501
            if _id2 in id2:
502
                flag2 = True
503

    
504
        if not flag2:
505
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
506
                      (radio.MODEL, util.hexprint(id2)))
507
            raise errors.RadioError("The extra ID is wrong, aborting.")
508

    
509
        # this radios need a extra request/answer here on the upload
510
        # the amount of data received depends of the radio type
511
        #
512
        # also the first block of TX must no have the ACK at the beginning
513
        # see _upload for this.
514
        if upload is True:
515
            # send an ACK
516
            _send(radio, ACK_CMD)
517

    
518
            # the amount of data depend on the radio, so far we have two radios
519
            # reading two bytes with an ACK at the end and just ONE with just
520
            # one byte (QYT KT8900)
521
            # the JT-6188 appears a clone of the last, but reads TWO bytes.
522
            #
523
            # we will read two bytes with a custom timeout to not penalize the
524
            # users for this.
525
            #
526
            # we just check for a response and last byte being a ACK, that is
527
            # the common stone for all radios (3 so far)
528
            ack = _rawrecv(radio, 2)
529

    
530
            # checking
531
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
532
                raise errors.RadioError("Radio didn't ACK the upload")
533

    
534
            # restore the default serial timeout
535
            radio.pipe.timeout = STIMEOUT
536

    
537
    # DEBUG
538
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
539

    
540
    return True
541

    
542

    
543
def _download(radio):
544
    """Get the memory map"""
545

    
546
    # UI progress
547
    status = chirp_common.Status()
548

    
549
    # put radio in program mode and identify it
550
    _do_ident(radio, status)
551

    
552
    # the models that doesn't have the extra ID have to make a dummy read here
553
    if radio._id2 is False:
554
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
555
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
556

    
557
        if debug is True:
558
            LOG.info("Dummy first block read done, got this:\n\n %s",
559
                     util.hexprint(discard))
560

    
561
    # reset the progress bar in the UI
562
    status.max = MEM_SIZE / BLOCK_SIZE
563
    status.msg = "Cloning from radio..."
564
    status.cur = 0
565
    radio.status_fn(status)
566

    
567
    # cleaning the serial buffer
568
    _clean_buffer(radio)
569

    
570
    data = ""
571
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
572
        # sending the read request
573
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
574

    
575
        # read
576
        d = _recv(radio, addr)
577

    
578
        # aggregate the data
579
        data += d
580

    
581
        # UI Update
582
        status.cur = addr / BLOCK_SIZE
583
        status.msg = "Cloning from radio..."
584
        radio.status_fn(status)
585

    
586
    return data
587

    
588

    
589
def _upload(radio):
590
    """Upload procedure"""
591

    
592
    # The UPLOAD mem is restricted to lower than 0x3100,
593
    # so we will overide that here localy
594
    MEM_SIZE = radio.UPLOAD_MEM_SIZE
595

    
596
    # UI progress
597
    status = chirp_common.Status()
598

    
599
    # put radio in program mode and identify it
600
    _do_ident(radio, status, True)
601

    
602
    # get the data to upload to radio
603
    data = radio.get_mmap()
604

    
605
    # Reset the UI progress
606
    status.max = MEM_SIZE / TX_BLOCK_SIZE
607
    status.cur = 0
608
    status.msg = "Cloning to radio..."
609
    radio.status_fn(status)
610

    
611
    # the radios that doesn't have the extra ID 'may' do a dummy write, I found
612
    # that leveraging the bad ACK and NOT doing the dummy write is ok, as the
613
    # dummy write is accepted (it actually writes to the mem!) by the radio.
614

    
615
    # cleaning the serial buffer
616
    _clean_buffer(radio)
617

    
618
    # the fun start here
619
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
620
        # getting the block of data to send
621
        d = data[addr:addr + TX_BLOCK_SIZE]
622

    
623
        # build the frame to send
624
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
625

    
626
        # first block must not send the ACK at the beginning for the
627
        # ones that has the extra id, since this have to do a extra step
628
        if addr == 0 and radio._id2 is not False:
629
            frame = frame[1:]
630

    
631
        # send the frame
632
        _send(radio, frame)
633

    
634
        # receiving the response
635
        ack = _rawrecv(radio, 1)
636

    
637
        # basic check
638
        if len(ack) != 1:
639
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
640

    
641
        if ack not in "\x06\x05":
642
            raise errors.RadioError("Bad ACK writing block 0x%04x:" % addr)
643

    
644
        # UI Update
645
        status.cur = addr / TX_BLOCK_SIZE
646
        status.msg = "Cloning to radio..."
647
        radio.status_fn(status)
648

    
649

    
650
def model_match(cls, data):
651
    """Match the opened/downloaded image to the correct version"""
652
    rid = data[0x3f70:0x3f76]
653

    
654
    if rid in cls._fileid:
655
        return True
656

    
657
    return False
658

    
659

    
660
def _decode_ranges(low, high):
661
    """Unpack the data in the ranges zones in the memmap and return
662
    a tuple with the integer corresponding to the Mhz it means"""
663
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
664
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
665
    ilow *= 1000000
666
    ihigh *= 1000000
667

    
668
    return (ilow, ihigh)
669

    
670

    
671
def _split(rf, f1, f2):
672
    """Returns False if the two freqs are in the same band (no split)
673
    or True otherwise"""
674

    
675
    # determine if the two freqs are in the same band
676
    for low, high in rf.valid_bands:
677
        if f1 >= low and f1 <= high and \
678
                f2 >= low and f2 <= high:
679
            # if the two freqs are on the same Band this is not a split
680
            return False
681

    
682
    # if you get here is because the freq pairs are split
683
    return True
684

    
685

    
686
class BTechMobileCommon(chirp_common.CloneModeRadio,
687
                        chirp_common.ExperimentalRadio):
688
    """BTECH's UV-5001 and alike radios"""
689
    VENDOR = "BTECH"
690
    MODEL = ""
691
    IDENT = ""
692
    BANDS = 2
693
    COLOR_LCD = False
694
    COLOR_LCD2 = False
695
    COLOR_LCD3 = False
696
    NAME_LENGTH = 6
697
    UPLOAD_MEM_SIZE = 0X3100
698
    _power_levels = [chirp_common.PowerLevel("High", watts=25),
699
                     chirp_common.PowerLevel("Low", watts=10)]
700
    _vhf_range = (130000000, 180000000)
701
    _220_range = (200000000, 271000000)
702
    _uhf_range = (400000000, 521000000)
703
    _350_range = (350000000, 391000000)
704
    _upper = 199
705
    _magic = MSTRING
706
    _fileid = None
707
    _id2 = False
708
    btech3 = False
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 software '
717
             'if you treasure them, this driver is new and may contain'
718
             ' bugs.\n'
719
             '\n'
720
             )
721
        rp.pre_download = _(dedent("""\
722
            Follow these instructions to download your info:
723

    
724
            1 - Turn off your radio
725
            2 - Connect your interface cable
726
            3 - Turn on your radio
727
            4 - Do the download of your radio data
728

    
729
            """))
730
        rp.pre_upload = _(dedent("""\
731
            Follow these instructions to upload your info:
732

    
733
            1 - Turn off your radio
734
            2 - Connect your interface cable
735
            3 - Turn on your radio
736
            4 - Do the upload of your radio data
737

    
738
            """))
739
        return rp
740

    
741
    def get_features(self):
742
        """Get the radio's features"""
743

    
744
        # we will use the following var as global
745
        global POWER_LEVELS
746

    
747
        rf = chirp_common.RadioFeatures()
748
        rf.has_settings = True
749
        rf.has_bank = False
750
        rf.has_tuning_step = False
751
        rf.can_odd_split = True
752
        rf.has_name = True
753
        rf.has_offset = True
754
        rf.has_mode = True
755
        rf.has_dtcs = True
756
        rf.has_rx_dtcs = True
757
        rf.has_dtcs_polarity = True
758
        rf.has_ctone = True
759
        rf.has_cross = True
760
        rf.valid_modes = MODES
761
        rf.valid_characters = VALID_CHARS
762
        rf.valid_name_length = self.NAME_LENGTH
763
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
764
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
765
        rf.valid_cross_modes = [
766
            "Tone->Tone",
767
            "DTCS->",
768
            "->DTCS",
769
            "Tone->DTCS",
770
            "DTCS->Tone",
771
            "->Tone",
772
            "DTCS->DTCS"]
773
        rf.valid_skips = SKIP_VALUES
774
        rf.valid_dtcs_codes = DTCS
775
        rf.valid_tuning_steps = STEPS
776
        rf.memory_bounds = (0, self._upper)
777

    
778
        # power levels
779
        POWER_LEVELS = self._power_levels
780
        rf.valid_power_levels = POWER_LEVELS
781

    
782
        # normal dual bands
783
        rf.valid_bands = [self._vhf_range, self._uhf_range]
784

    
785
        # 220 band
786
        if self.BANDS == 3 or self.BANDS == 4:
787
            rf.valid_bands.append(self._220_range)
788

    
789
        # 350 band
790
        if self.BANDS == 4:
791
            rf.valid_bands.append(self._350_range)
792

    
793
        return rf
794

    
795
    def sync_in(self):
796
        """Download from radio"""
797
        data = _download(self)
798
        self._mmap = memmap.MemoryMap(data)
799
        self.process_mmap()
800

    
801
    def sync_out(self):
802
        """Upload to radio"""
803
        try:
804
            _upload(self)
805
        except errors.RadioError:
806
            raise
807
        except Exception, e:
808
            raise errors.RadioError("Error: %s" % e)
809

    
810
    def get_raw_memory(self, number):
811
        return repr(self._memobj.memory[number])
812

    
813
    def _decode_tone(self, val):
814
        """Parse the tone data to decode from mem, it returns:
815
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
816
        pol = None
817

    
818
        if val in [0, 65535]:
819
            return '', None, None
820
        elif val > 0x0258:
821
            a = val / 10.0
822
            return 'Tone', a, pol
823
        else:
824
            if val > 0x69:
825
                index = val - 0x6A
826
                pol = "R"
827
            else:
828
                index = val - 1
829
                pol = "N"
830

    
831
            tone = DTCS[index]
832
            return 'DTCS', tone, pol
833

    
834
    def _encode_tone(self, memval, mode, val, pol):
835
        """Parse the tone data to encode from UI to mem"""
836
        if mode == '' or mode is None:
837
            memval.set_raw("\x00\x00")
838
        elif mode == 'Tone':
839
            memval.set_value(val * 10)
840
        elif mode == 'DTCS':
841
            # detect the index in the DTCS list
842
            try:
843
                index = DTCS.index(val)
844
                if pol == "N":
845
                    index += 1
846
                else:
847
                    index += 0x6A
848
                memval.set_value(index)
849
            except:
850
                msg = "Digital Tone '%d' is not supported" % value
851
                LOG.error(msg)
852
                raise errors.RadioError(msg)
853
        else:
854
            msg = "Internal error: invalid mode '%s'" % mode
855
            LOG.error(msg)
856
            raise errors.InvalidDataError(msg)
857

    
858
    def get_memory(self, number):
859
        """Get the mem representation from the radio image"""
860
        _mem = self._memobj.memory[number]
861
        _names = self._memobj.names[number]
862

    
863
        # Create a high-level memory object to return to the UI
864
        mem = chirp_common.Memory()
865

    
866
        # Memory number
867
        mem.number = number
868

    
869
        if _mem.get_raw()[0] == "\xFF":
870
            mem.empty = True
871
            return mem
872

    
873
        # Freq and offset
874
        mem.freq = int(_mem.rxfreq) * 10
875
        # tx freq can be blank
876
        if _mem.get_raw()[4] == "\xFF":
877
            # TX freq not set
878
            mem.offset = 0
879
            mem.duplex = "off"
880
        else:
881
            # TX freq set
882
            offset = (int(_mem.txfreq) * 10) - mem.freq
883
            if offset != 0:
884
                if _split(self.get_features(), mem.freq, int(
885
                          _mem.txfreq) * 10):
886
                    mem.duplex = "split"
887
                    mem.offset = int(_mem.txfreq) * 10
888
                elif offset < 0:
889
                    mem.offset = abs(offset)
890
                    mem.duplex = "-"
891
                elif offset > 0:
892
                    mem.offset = offset
893
                    mem.duplex = "+"
894
            else:
895
                mem.offset = 0
896

    
897
        # name TAG of the channel
898
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
899

    
900
        # power
901
        mem.power = POWER_LEVELS[int(_mem.power)]
902

    
903
        # wide/narrow
904
        mem.mode = MODES[int(_mem.wide)]
905

    
906
        # skip
907
        mem.skip = SKIP_VALUES[_mem.add]
908

    
909
        # tone data
910
        rxtone = txtone = None
911
        txtone = self._decode_tone(_mem.txtone)
912
        rxtone = self._decode_tone(_mem.rxtone)
913
        chirp_common.split_tone_decode(mem, txtone, rxtone)
914

    
915
        # Extra
916
        mem.extra = RadioSettingGroup("extra", "Extra")
917

    
918
        if not self.COLOR_LCD or \
919
                (self.COLOR_LCD and not self.VENDOR == "BTECH"):
920
            scramble = RadioSetting("scramble", "Scramble",
921
                                    RadioSettingValueBoolean(bool(
922
                                        _mem.scramble)))
923
            mem.extra.append(scramble)
924

    
925
        bcl = RadioSetting("bcl", "Busy channel lockout",
926
                           RadioSettingValueBoolean(bool(_mem.bcl)))
927
        mem.extra.append(bcl)
928

    
929
        pttid = RadioSetting("pttid", "PTT ID",
930
                             RadioSettingValueList(PTTID_LIST,
931
                                                   PTTID_LIST[_mem.pttid]))
932
        mem.extra.append(pttid)
933

    
934
        # validating scode
935
        scode = _mem.scode if _mem.scode != 15 else 0
936
        pttidcode = RadioSetting("scode", "PTT ID signal code",
937
                                 RadioSettingValueList(
938
                                     PTTIDCODE_LIST,
939
                                     PTTIDCODE_LIST[scode]))
940
        mem.extra.append(pttidcode)
941

    
942
        optsig = RadioSetting("optsig", "Optional signaling",
943
                              RadioSettingValueList(
944
                                  OPTSIG_LIST,
945
                                  OPTSIG_LIST[_mem.optsig]))
946
        mem.extra.append(optsig)
947

    
948
        spmute = RadioSetting("spmute", "Speaker mute",
949
                              RadioSettingValueList(
950
                                  SPMUTE_LIST,
951
                                  SPMUTE_LIST[_mem.spmute]))
952
        mem.extra.append(spmute)
953

    
954
        return mem
955

    
956
    def set_memory(self, mem):
957
        """Set the memory data in the eeprom img from the UI"""
958
        # get the eprom representation of this channel
959
        _mem = self._memobj.memory[mem.number]
960
        _names = self._memobj.names[mem.number]
961

    
962
        mem_was_empty = False
963
        # same method as used in get_memory for determining if mem is empty
964
        # doing this BEFORE overwriting it with new values ...
965
        if _mem.get_raw()[0] == "\xFF":
966
            LOG.debug("This mem was empty before")
967
            mem_was_empty = True
968

    
969
        # if empty memmory
970
        if mem.empty:
971
            # the channel itself
972
            _mem.set_raw("\xFF" * 16)
973
            # the name tag
974
            _names.set_raw("\xFF" * 16)
975
            return
976

    
977
        if mem_was_empty:
978
            # Zero the whole memory if we're making it unempty for
979
            # the first time
980
            LOG.debug('Zeroing new memory')
981
            _mem.set_raw('\x00' * 16)
982

    
983
        # frequency
984
        _mem.rxfreq = mem.freq / 10
985

    
986
        # duplex
987
        if mem.duplex == "+":
988
            _mem.txfreq = (mem.freq + mem.offset) / 10
989
        elif mem.duplex == "-":
990
            _mem.txfreq = (mem.freq - mem.offset) / 10
991
        elif mem.duplex == "off":
992
            for i in _mem.txfreq:
993
                i.set_raw("\xFF")
994
        elif mem.duplex == "split":
995
            _mem.txfreq = mem.offset / 10
996
        else:
997
            _mem.txfreq = mem.freq / 10
998

    
999
        # tone data
1000
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1001
            chirp_common.split_tone_encode(mem)
1002
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1003
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1004

    
1005
        # name TAG of the channel
1006
        if len(mem.name) < self.NAME_LENGTH:
1007
            # we must pad to self.NAME_LENGTH chars, " " = "\xFF"
1008
            mem.name = str(mem.name).ljust(self.NAME_LENGTH, " ")
1009
        _names.name = str(mem.name).replace(" ", "\xFF")
1010

    
1011
        # power, # default power level is high
1012
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1013

    
1014
        # wide/narrow
1015
        _mem.wide = MODES.index(mem.mode)
1016

    
1017
        # scan add property
1018
        _mem.add = SKIP_VALUES.index(mem.skip)
1019

    
1020
        # reseting unknowns, this have to be set by hand
1021
        _mem.unknown0 = 0
1022
        _mem.unknown1 = 0
1023
        _mem.unknown2 = 0
1024
        _mem.unknown3 = 0
1025
        _mem.unknown4 = 0
1026
        _mem.unknown5 = 0
1027
        _mem.unknown6 = 0
1028

    
1029
        def _zero_settings():
1030
            _mem.spmute = 0
1031
            _mem.optsig = 0
1032
            _mem.scramble = 0
1033
            _mem.bcl = 0
1034
            _mem.pttid = 0
1035
            _mem.scode = 0
1036

    
1037
        if self.COLOR_LCD and _mem.scramble:
1038
            LOG.info('Resetting scramble bit for BTECH COLOR_LCD variant')
1039
            _mem.scramble = 0
1040

    
1041
        # extra settings
1042
        if len(mem.extra) > 0:
1043
            # there are setting, parse
1044
            LOG.debug("Extra-Setting supplied. Setting them.")
1045
            # Zero them all first so any not provided by model don't
1046
            # stay set
1047
            _zero_settings()
1048
            for setting in mem.extra:
1049
                setattr(_mem, setting.get_name(), setting.value)
1050
        else:
1051
            if mem.empty:
1052
                LOG.debug("New mem is empty.")
1053
            else:
1054
                LOG.debug("New mem is NOT empty")
1055
                # set extra-settings to default ONLY when apreviously empty or
1056
                # deleted memory was edited to prevent errors such as #4121
1057
                if mem_was_empty:
1058
                    LOG.debug("old mem was empty. Setting default for extras.")
1059
                    _zero_settings()
1060

    
1061
        return mem
1062

    
1063
    def get_settings(self):
1064
        """Translate the bit in the mem_struct into settings in the UI"""
1065
        _mem = self._memobj
1066
        basic = RadioSettingGroup("basic", "Basic Settings")
1067
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1068
        other = RadioSettingGroup("other", "Other Settings")
1069
        work = RadioSettingGroup("work", "Work Mode Settings")
1070
        top = RadioSettings(basic, advanced, other, work)
1071

    
1072
        # Basic
1073
        if self.COLOR_LCD:
1074
            tmr = RadioSetting("settings.tmr", "Transceiver multi-receive",
1075
                               RadioSettingValueList(
1076
                                   self.LIST_TMR,
1077
                                   self.LIST_TMR[_mem.settings.tmr]))
1078
            basic.append(tmr)
1079
        else:
1080
            tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1081
                               RadioSettingValueBoolean(_mem.settings.tdr))
1082
            basic.append(tdr)
1083

    
1084
        sql = RadioSetting("settings.sql", "Squelch level",
1085
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1086
        basic.append(sql)
1087

    
1088
        if self.MODEL == "GMRS-50X1":
1089
            autolk = RadioSetting("settings.autolk", "Auto keylock",
1090
                                  RadioSettingValueBoolean(
1091
                                      _mem.settings.autolk))
1092
            basic.append(autolk)
1093

    
1094
        tot = RadioSetting("settings.tot", "Time out timer",
1095
                           RadioSettingValueList(
1096
                               LIST_TOT,
1097
                               LIST_TOT[_mem.settings.tot]))
1098
        basic.append(tot)
1099

    
1100
        if self.MODEL == "KT-8R":
1101
                save = RadioSetting("settings.save", "Battery Save",
1102
                                    RadioSettingValueBoolean(
1103
                                        _mem.settings.save))
1104
                basic.append(save)
1105

    
1106
        if not self.MODEL == "KT-8R":
1107
            if self.VENDOR == "BTECH" or self.COLOR_LCD:
1108
                apo = RadioSetting("settings.apo", "Auto power off timer",
1109
                                   RadioSettingValueList(
1110
                                       LIST_APO,
1111
                                       LIST_APO[_mem.settings.apo]))
1112
                basic.append(apo)
1113
            else:
1114
                toa = RadioSetting("settings.apo", "Time out alert timer",
1115
                                   RadioSettingValueList(
1116
                                       LIST_OFF1TO10,
1117
                                       LIST_OFF1TO10[_mem.settings.apo]))
1118
                basic.append(toa)
1119

    
1120
        abr = RadioSetting("settings.abr", "Backlight timer",
1121
                           RadioSettingValueList(
1122
                               LIST_OFF1TO50,
1123
                               LIST_OFF1TO50[_mem.settings.abr]))
1124
        basic.append(abr)
1125

    
1126
        beep = RadioSetting("settings.beep", "Key beep",
1127
                            RadioSettingValueBoolean(_mem.settings.beep))
1128
        basic.append(beep)
1129

    
1130
        if self.MODEL == "KT-8R":
1131
                dsub = RadioSetting("settings.dsub", "CTCSS/DCS code display",
1132
                                    RadioSettingValueBoolean(
1133
                                        _mem.settings.dsub))
1134
                basic.append(dsub)
1135

    
1136
        if self.MODEL == "KT-8R":
1137
                dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1138
                                      RadioSettingValueBoolean(
1139
                                          _mem.settings.dtmfst))
1140
                basic.append(dtmfst)
1141
        else:
1142
            dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1143
                                  RadioSettingValueList(
1144
                                      LIST_DTMFST,
1145
                                      LIST_DTMFST[_mem.settings.dtmfst]))
1146
            basic.append(dtmfst)
1147

    
1148
        if not self.COLOR_LCD:
1149
            prisc = RadioSetting("settings.prisc", "Priority scan",
1150
                                 RadioSettingValueBoolean(
1151
                                     _mem.settings.prisc))
1152
            basic.append(prisc)
1153

    
1154
            prich = RadioSetting("settings.prich", "Priority channel",
1155
                                 RadioSettingValueInteger(0, self._upper,
1156
                                                          _mem.settings.prich))
1157
            basic.append(prich)
1158

    
1159
        screv = RadioSetting("settings.screv", "Scan resume method",
1160
                             RadioSettingValueList(
1161
                                 LIST_SCREV,
1162
                                 LIST_SCREV[_mem.settings.screv]))
1163
        basic.append(screv)
1164

    
1165
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1166
                             RadioSettingValueInteger(0, 30,
1167
                                                      _mem.settings.pttlt))
1168
        basic.append(pttlt)
1169

    
1170
        if self.VENDOR == "BTECH" and self.COLOR_LCD:
1171
            emctp = RadioSetting("settings.emctp", "Alarm mode",
1172
                                 RadioSettingValueList(
1173
                                     LIST_EMCTPX,
1174
                                     LIST_EMCTPX[_mem.settings.emctp]))
1175
            basic.append(emctp)
1176
        else:
1177
            emctp = RadioSetting("settings.emctp", "Alarm mode",
1178
                                 RadioSettingValueList(
1179
                                     LIST_EMCTP,
1180
                                     LIST_EMCTP[_mem.settings.emctp]))
1181
            basic.append(emctp)
1182

    
1183
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1184
                             RadioSettingValueInteger(0, self._upper,
1185
                                                      _mem.settings.emcch))
1186
        basic.append(emcch)
1187

    
1188
        if self.COLOR_LCD:
1189
            if _mem.settings.sigbp > 0x01:
1190
                val = 0x00
1191
            else:
1192
                val = _mem.settings.sigbp
1193
            sigbp = RadioSetting("settings.sigbp", "Signal beep",
1194
                                 RadioSettingValueBoolean(val))
1195
            basic.append(sigbp)
1196
        else:
1197
            ringt = RadioSetting("settings.ringt", "Ring time",
1198
                                 RadioSettingValueList(
1199
                                     LIST_OFF1TO9,
1200
                                     LIST_OFF1TO9[_mem.settings.ringt]))
1201
            basic.append(ringt)
1202

    
1203
        camdf = RadioSetting("settings.camdf", "Display mode A",
1204
                             RadioSettingValueList(
1205
                                 LIST_MDF,
1206
                                 LIST_MDF[_mem.settings.camdf]))
1207
        basic.append(camdf)
1208

    
1209
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1210
                             RadioSettingValueList(
1211
                                 LIST_MDF,
1212
                                 LIST_MDF[_mem.settings.cbmdf]))
1213
        basic.append(cbmdf)
1214

    
1215
        if self.COLOR_LCD:
1216
            ccmdf = RadioSetting("settings.ccmdf", "Display mode C",
1217
                                 RadioSettingValueList(
1218
                                     LIST_MDF,
1219
                                     LIST_MDF[_mem.settings.ccmdf]))
1220
            basic.append(ccmdf)
1221

    
1222
            cdmdf = RadioSetting("settings.cdmdf", "Display mode D",
1223
                                 RadioSettingValueList(
1224
                                     LIST_MDF,
1225
                                     LIST_MDF[_mem.settings.cdmdf]))
1226
            basic.append(cdmdf)
1227

    
1228
            langua = RadioSetting("settings.langua", "Language",
1229
                                  RadioSettingValueList(
1230
                                      LIST_LANGUA,
1231
                                      LIST_LANGUA[_mem.settings.langua]))
1232
            basic.append(langua)
1233

    
1234
        if self.MODEL == "KT-8R":
1235
            voice = RadioSetting("settings.voice", "Voice prompt",
1236
                                 RadioSettingValueList(
1237
                                     LIST_VOICE,
1238
                                     LIST_VOICE[_mem.settings.voice]))
1239
            basic.append(voice)
1240

    
1241
            vox = RadioSetting("settings.vox", "VOX",
1242
                               RadioSettingValueList(
1243
                                   LIST_VOX,
1244
                                   LIST_VOX[_mem.settings.vox]))
1245
            basic.append(vox)
1246

    
1247
            voxt = RadioSetting("settings.voxt", "VOX delay time",
1248
                                RadioSettingValueList(
1249
                                    LIST_VOXT,
1250
                                    LIST_VOXT[_mem.settings.voxt]))
1251
            basic.append(voxt)
1252

    
1253
        if self.VENDOR == "BTECH":
1254
            if self.COLOR_LCD:
1255
                sync = RadioSetting("settings.sync", "Channel display sync",
1256
                                    RadioSettingValueList(
1257
                                        LIST_SYNC,
1258
                                        LIST_SYNC[_mem.settings.sync]))
1259
                basic.append(sync)
1260
            else:
1261
                sync = RadioSetting("settings.sync", "A/B channel sync",
1262
                                    RadioSettingValueBoolean(
1263
                                        _mem.settings.sync))
1264
                basic.append(sync)
1265
        else:
1266
            autolk = RadioSetting("settings.sync", "Auto keylock",
1267
                                  RadioSettingValueBoolean(
1268
                                      _mem.settings.sync))
1269
            basic.append(autolk)
1270

    
1271
        if not self.COLOR_LCD:
1272
            ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1273
                                  RadioSettingValueList(
1274
                                      LIST_PONMSG,
1275
                                      LIST_PONMSG[_mem.settings.ponmsg]))
1276
            basic.append(ponmsg)
1277

    
1278
        if self.COLOR_LCD and not (self.COLOR_LCD2 or self.COLOR_LCD3):
1279
            mainfc = RadioSetting("settings.mainfc",
1280
                                  "Main LCD foreground color",
1281
                                  RadioSettingValueList(
1282
                                      LIST_COLOR9,
1283
                                      LIST_COLOR9[_mem.settings.mainfc]))
1284
            basic.append(mainfc)
1285

    
1286
            mainbc = RadioSetting("settings.mainbc",
1287
                                  "Main LCD background color",
1288
                                  RadioSettingValueList(
1289
                                      LIST_COLOR9,
1290
                                      LIST_COLOR9[_mem.settings.mainbc]))
1291
            basic.append(mainbc)
1292

    
1293
            menufc = RadioSetting("settings.menufc", "Menu foreground color",
1294
                                  RadioSettingValueList(
1295
                                      LIST_COLOR9,
1296
                                      LIST_COLOR9[_mem.settings.menufc]))
1297
            basic.append(menufc)
1298

    
1299
            menubc = RadioSetting("settings.menubc", "Menu background color",
1300
                                  RadioSettingValueList(
1301
                                      LIST_COLOR9,
1302
                                      LIST_COLOR9[_mem.settings.menubc]))
1303
            basic.append(menubc)
1304

    
1305
            stafc = RadioSetting("settings.stafc",
1306
                                 "Top status foreground color",
1307
                                 RadioSettingValueList(
1308
                                     LIST_COLOR9,
1309
                                     LIST_COLOR9[_mem.settings.stafc]))
1310
            basic.append(stafc)
1311

    
1312
            stabc = RadioSetting("settings.stabc",
1313
                                 "Top status background color",
1314
                                 RadioSettingValueList(
1315
                                     LIST_COLOR9,
1316
                                     LIST_COLOR9[_mem.settings.stabc]))
1317
            basic.append(stabc)
1318

    
1319
            sigfc = RadioSetting("settings.sigfc",
1320
                                 "Bottom status foreground color",
1321
                                 RadioSettingValueList(
1322
                                     LIST_COLOR9,
1323
                                     LIST_COLOR9[_mem.settings.sigfc]))
1324
            basic.append(sigfc)
1325

    
1326
            sigbc = RadioSetting("settings.sigbc",
1327
                                 "Bottom status background color",
1328
                                 RadioSettingValueList(
1329
                                     LIST_COLOR9,
1330
                                     LIST_COLOR9[_mem.settings.sigbc]))
1331
            basic.append(sigbc)
1332

    
1333
            rxfc = RadioSetting("settings.rxfc", "Receiving character color",
1334
                                RadioSettingValueList(
1335
                                    LIST_COLOR9,
1336
                                    LIST_COLOR9[_mem.settings.rxfc]))
1337
            basic.append(rxfc)
1338

    
1339
            txfc = RadioSetting("settings.txfc",
1340
                                "Transmitting character color",
1341
                                RadioSettingValueList(
1342
                                    LIST_COLOR9,
1343
                                    LIST_COLOR9[_mem.settings.txfc]))
1344
            basic.append(txfc)
1345

    
1346
            txdisp = RadioSetting("settings.txdisp",
1347
                                  "Transmitting status display",
1348
                                  RadioSettingValueList(
1349
                                      LIST_TXDISP,
1350
                                      LIST_TXDISP[_mem.settings.txdisp]))
1351
            basic.append(txdisp)
1352
        elif self.COLOR_LCD2 or self.COLOR_LCD3:
1353
            stfc = RadioSetting("settings.stfc",
1354
                                "ST-FC",
1355
                                RadioSettingValueList(
1356
                                    LIST_COLOR8,
1357
                                    LIST_COLOR8[_mem.settings.stfc]))
1358
            basic.append(stfc)
1359

    
1360
            mffc = RadioSetting("settings.mffc",
1361
                                "MF-FC",
1362
                                RadioSettingValueList(
1363
                                    LIST_COLOR8,
1364
                                    LIST_COLOR8[_mem.settings.mffc]))
1365
            basic.append(mffc)
1366

    
1367
            sfafc = RadioSetting("settings.sfafc",
1368
                                 "SFA-FC",
1369
                                 RadioSettingValueList(
1370
                                     LIST_COLOR8,
1371
                                     LIST_COLOR8[_mem.settings.sfafc]))
1372
            basic.append(sfafc)
1373

    
1374
            sfbfc = RadioSetting("settings.sfbfc",
1375
                                 "SFB-FC",
1376
                                 RadioSettingValueList(
1377
                                     LIST_COLOR8,
1378
                                     LIST_COLOR8[_mem.settings.sfbfc]))
1379
            basic.append(sfbfc)
1380

    
1381
            sfcfc = RadioSetting("settings.sfcfc",
1382
                                 "SFC-FC",
1383
                                 RadioSettingValueList(
1384
                                     LIST_COLOR8,
1385
                                     LIST_COLOR8[_mem.settings.sfcfc]))
1386
            basic.append(sfcfc)
1387

    
1388
            sfdfc = RadioSetting("settings.sfdfc",
1389
                                 "SFD-FC",
1390
                                 RadioSettingValueList(
1391
                                     LIST_COLOR8,
1392
                                     LIST_COLOR8[_mem.settings.sfdfc]))
1393
            basic.append(sfdfc)
1394

    
1395
            subfc = RadioSetting("settings.subfc",
1396
                                 "SUB-FC",
1397
                                 RadioSettingValueList(
1398
                                     LIST_COLOR8,
1399
                                     LIST_COLOR8[_mem.settings.subfc]))
1400
            basic.append(subfc)
1401

    
1402
            fmfc = RadioSetting("settings.fmfc",
1403
                                "FM-FC",
1404
                                RadioSettingValueList(
1405
                                    LIST_COLOR8,
1406
                                    LIST_COLOR8[_mem.settings.fmfc]))
1407
            basic.append(fmfc)
1408

    
1409
            sigfc = RadioSetting("settings.sigfc",
1410
                                 "SIG-FC",
1411
                                 RadioSettingValueList(
1412
                                     LIST_COLOR8,
1413
                                     LIST_COLOR8[_mem.settings.sigfc]))
1414
            basic.append(sigfc)
1415

    
1416
            if not self.MODEL == "KT-8R":
1417
                modfc = RadioSetting("settings.modfc",
1418
                                     "MOD-FC",
1419
                                     RadioSettingValueList(
1420
                                         LIST_COLOR8,
1421
                                         LIST_COLOR8[_mem.settings.modfc]))
1422
                basic.append(modfc)
1423

    
1424
            menufc = RadioSetting("settings.menufc",
1425
                                  "MENUFC",
1426
                                  RadioSettingValueList(
1427
                                      LIST_COLOR8,
1428
                                      LIST_COLOR8[_mem.settings.menufc]))
1429
            basic.append(menufc)
1430

    
1431
            txfc = RadioSetting("settings.txfc",
1432
                                "TX-FC",
1433
                                RadioSettingValueList(
1434
                                    LIST_COLOR8,
1435
                                    LIST_COLOR8[_mem.settings.txfc]))
1436
            basic.append(txfc)
1437

    
1438
            if self.MODEL == "KT-8R":
1439
                rxfc = RadioSetting("settings.rxfc",
1440
                                    "RX-FC",
1441
                                    RadioSettingValueList(
1442
                                        LIST_COLOR8,
1443
                                        LIST_COLOR8[_mem.settings.rxfc]))
1444
                basic.append(rxfc)
1445

    
1446
            if not self.MODEL == "KT-8R":
1447
                txdisp = RadioSetting("settings.txdisp",
1448
                                      "Transmitting status display",
1449
                                      RadioSettingValueList(
1450
                                          LIST_TXDISP,
1451
                                          LIST_TXDISP[_mem.settings.txdisp]))
1452
                basic.append(txdisp)
1453
        else:
1454
            wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1455
                                 RadioSettingValueList(
1456
                                     LIST_COLOR4,
1457
                                     LIST_COLOR4[_mem.settings.wtled]))
1458
            basic.append(wtled)
1459

    
1460
            rxled = RadioSetting("settings.rxled", "RX backlight Color",
1461
                                 RadioSettingValueList(
1462
                                     LIST_COLOR4,
1463
                                     LIST_COLOR4[_mem.settings.rxled]))
1464
            basic.append(rxled)
1465

    
1466
            txled = RadioSetting("settings.txled", "TX backlight Color",
1467
                                 RadioSettingValueList(
1468
                                     LIST_COLOR4,
1469
                                     LIST_COLOR4[_mem.settings.txled]))
1470
            basic.append(txled)
1471

    
1472
        anil = RadioSetting("settings.anil", "ANI length",
1473
                            RadioSettingValueList(
1474
                                LIST_ANIL,
1475
                                LIST_ANIL[_mem.settings.anil]))
1476
        basic.append(anil)
1477

    
1478
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1479
                            RadioSettingValueList(
1480
                                LIST_REPS,
1481
                                LIST_REPS[_mem.settings.reps]))
1482
        basic.append(reps)
1483

    
1484
        if not self.MODEL == "GMRS-50X1" and not self.MODEL == "KT-8R":
1485
            repm = RadioSetting("settings.repm", "Relay condition",
1486
                                RadioSettingValueList(
1487
                                    LIST_REPM,
1488
                                    LIST_REPM[_mem.settings.repm]))
1489
            basic.append(repm)
1490

    
1491
        if self.VENDOR == "BTECH" or self.COLOR_LCD:
1492
            if self.COLOR_LCD:
1493
                tmrmr = RadioSetting("settings.tmrmr", "TMR return time",
1494
                                     RadioSettingValueList(
1495
                                         LIST_OFF1TO50,
1496
                                         LIST_OFF1TO50[_mem.settings.tmrmr]))
1497
                basic.append(tmrmr)
1498
            else:
1499
                tdrab = RadioSetting("settings.tdrab", "TDR return time",
1500
                                     RadioSettingValueList(
1501
                                         LIST_OFF1TO50,
1502
                                         LIST_OFF1TO50[_mem.settings.tdrab]))
1503
                basic.append(tdrab)
1504

    
1505
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1506
                               RadioSettingValueBoolean(_mem.settings.ste))
1507
            basic.append(ste)
1508

    
1509
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1510
                                 RadioSettingValueList(
1511
                                     LIST_OFF1TO9,
1512
                                     LIST_OFF1TO9[_mem.settings.rpste]))
1513
            basic.append(rpste)
1514

    
1515
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1516
                                 RadioSettingValueList(
1517
                                     LIST_RPTDL,
1518
                                     LIST_RPTDL[_mem.settings.rptdl]))
1519
            basic.append(rptdl)
1520

    
1521
        if str(_mem.fingerprint.fp) in BTECH3:
1522
            mgain = RadioSetting("settings.mgain", "Mic gain",
1523
                                 RadioSettingValueInteger(0, 120,
1524
                                                          _mem.settings.mgain))
1525
            basic.append(mgain)
1526

    
1527
        if str(_mem.fingerprint.fp) in BTECH3 or self.COLOR_LCD:
1528
            dtmfg = RadioSetting("settings.dtmfg", "DTMF gain",
1529
                                 RadioSettingValueInteger(0, 60,
1530
                                                          _mem.settings.dtmfg))
1531
            basic.append(dtmfg)
1532

    
1533
        if self.VENDOR == "BTECH" and self.COLOR_LCD:
1534
            mgain = RadioSetting("settings.mgain", "Mic gain",
1535
                                 RadioSettingValueInteger(0, 120,
1536
                                                          _mem.settings.mgain))
1537
            basic.append(mgain)
1538

    
1539
            skiptx = RadioSetting("settings.skiptx", "Skip TX",
1540
                                  RadioSettingValueList(
1541
                                      LIST_SKIPTX,
1542
                                      LIST_SKIPTX[_mem.settings.skiptx]))
1543
            basic.append(skiptx)
1544

    
1545
            scmode = RadioSetting("settings.scmode", "Scan mode",
1546
                                  RadioSettingValueList(
1547
                                      LIST_SCMODE,
1548
                                      LIST_SCMODE[_mem.settings.scmode]))
1549
            basic.append(scmode)
1550

    
1551
        if self.MODEL == "KT-8R":
1552
            tmrtx = RadioSetting("settings.tmrtx", "TX in multi-standby",
1553
                                 RadioSettingValueList(
1554
                                     LIST_TMRTX,
1555
                                     LIST_TMRTX[_mem.settings.tmrtx]))
1556
            basic.append(tmrtx)
1557

    
1558
        # Advanced
1559
        def _filter(name):
1560
            filtered = ""
1561
            for char in str(name):
1562
                if char in VALID_CHARS:
1563
                    filtered += char
1564
                else:
1565
                    filtered += " "
1566
            return filtered
1567

    
1568
        if self.COLOR_LCD and not (self.COLOR_LCD2 or self.COLOR_LCD3):
1569
            _msg = self._memobj.poweron_msg
1570
            line1 = RadioSetting("poweron_msg.line1",
1571
                                 "Power-on message line 1",
1572
                                 RadioSettingValueString(0, 8, _filter(
1573
                                                         _msg.line1)))
1574
            advanced.append(line1)
1575
            line2 = RadioSetting("poweron_msg.line2",
1576
                                 "Power-on message line 2",
1577
                                 RadioSettingValueString(0, 8, _filter(
1578
                                                         _msg.line2)))
1579
            advanced.append(line2)
1580
            line3 = RadioSetting("poweron_msg.line3",
1581
                                 "Power-on message line 3",
1582
                                 RadioSettingValueString(0, 8, _filter(
1583
                                                         _msg.line3)))
1584
            advanced.append(line3)
1585
            line4 = RadioSetting("poweron_msg.line4",
1586
                                 "Power-on message line 4",
1587
                                 RadioSettingValueString(0, 8, _filter(
1588
                                                         _msg.line4)))
1589
            advanced.append(line4)
1590
            line5 = RadioSetting("poweron_msg.line5",
1591
                                 "Power-on message line 5",
1592
                                 RadioSettingValueString(0, 8, _filter(
1593
                                                         _msg.line5)))
1594
            advanced.append(line5)
1595
            line6 = RadioSetting("poweron_msg.line6",
1596
                                 "Power-on message line 6",
1597
                                 RadioSettingValueString(0, 8, _filter(
1598
                                                         _msg.line6)))
1599
            advanced.append(line6)
1600
            line7 = RadioSetting("poweron_msg.line7",
1601
                                 "Power-on message line 7",
1602
                                 RadioSettingValueString(0, 8, _filter(
1603
                                                         _msg.line7)))
1604
            advanced.append(line7)
1605
            line8 = RadioSetting("poweron_msg.line8", "Static message",
1606
                                 RadioSettingValueString(0, 8, _filter(
1607
                                                         _msg.line8)))
1608
            advanced.append(line8)
1609
        elif self.COLOR_LCD2 or self.COLOR_LCD3:
1610
            _msg = self._memobj.static_msg
1611
            line = RadioSetting("static_msg.line", "Static message",
1612
                                RadioSettingValueString(0, 16, _filter(
1613
                                    _msg.line)))
1614
            advanced.append(line)
1615
        else:
1616
            _msg = self._memobj.poweron_msg
1617
            line1 = RadioSetting("poweron_msg.line1",
1618
                                 "Power-on message line 1",
1619
                                 RadioSettingValueString(0, 6, _filter(
1620
                                                         _msg.line1)))
1621
            advanced.append(line1)
1622
            line2 = RadioSetting("poweron_msg.line2",
1623
                                 "Power-on message line 2",
1624
                                 RadioSettingValueString(0, 6, _filter(
1625
                                                         _msg.line2)))
1626
            advanced.append(line2)
1627

    
1628
        if self.MODEL in ("UV-2501", "UV-5001"):
1629
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1630
                                   RadioSettingValueBoolean(
1631
                                       _mem.settings2.vfomren))
1632
            advanced.append(vfomren)
1633

    
1634
            reseten = RadioSetting("settings2.reseten", "RESET",
1635
                                   RadioSettingValueBoolean(
1636
                                       _mem.settings2.reseten))
1637
            advanced.append(reseten)
1638

    
1639
            menuen = RadioSetting("settings2.menuen", "Menu",
1640
                                  RadioSettingValueBoolean(
1641
                                      _mem.settings2.menuen))
1642
            advanced.append(menuen)
1643

    
1644
        # Other
1645
        def convert_bytes_to_limit(bytes):
1646
            limit = ""
1647
            for byte in bytes:
1648
                if byte < 10:
1649
                    limit += chr(byte + 0x30)
1650
                else:
1651
                    break
1652
            return limit
1653

    
1654
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1655
            _ranges = self._memobj.ranges220
1656
            ranges = "ranges220"
1657
        else:
1658
            _ranges = self._memobj.ranges
1659
            ranges = "ranges"
1660

    
1661
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1662
        val = RadioSettingValueString(0, 3, _limit)
1663
        val.set_mutable(False)
1664
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1665
        other.append(vhf_low)
1666

    
1667
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1668
        val = RadioSettingValueString(0, 3, _limit)
1669
        val.set_mutable(False)
1670
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1671
        other.append(vhf_high)
1672

    
1673
        if self.BANDS == 3 or self.BANDS == 4:
1674
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1675
            val = RadioSettingValueString(0, 3, _limit)
1676
            val.set_mutable(False)
1677
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1678
            other.append(vhf2_low)
1679

    
1680
            _limit = convert_bytes_to_limit(_ranges.vhf2_high)
1681
            val = RadioSettingValueString(0, 3, _limit)
1682
            val.set_mutable(False)
1683
            vhf2_high = RadioSetting("%s.vhf2_high" % ranges, "VHF2 high", val)
1684
            other.append(vhf2_high)
1685

    
1686
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1687
        val = RadioSettingValueString(0, 3, _limit)
1688
        val.set_mutable(False)
1689
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1690
        other.append(uhf_low)
1691

    
1692
        _limit = convert_bytes_to_limit(_ranges.uhf_high)
1693
        val = RadioSettingValueString(0, 3, _limit)
1694
        val.set_mutable(False)
1695
        uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
1696
        other.append(uhf_high)
1697

    
1698
        if self.BANDS == 4:
1699
            _limit = convert_bytes_to_limit(_ranges.uhf2_low)
1700
            val = RadioSettingValueString(0, 3, _limit)
1701
            val.set_mutable(False)
1702
            uhf2_low = RadioSetting("%s.uhf2_low" % ranges, "UHF2 low", val)
1703
            other.append(uhf2_low)
1704

    
1705
            _limit = convert_bytes_to_limit(_ranges.uhf2_high)
1706
            val = RadioSettingValueString(0, 3, _limit)
1707
            val.set_mutable(False)
1708
            uhf2_high = RadioSetting("%s.uhf2_high" % ranges, "UHF2 high", val)
1709
            other.append(uhf2_high)
1710

    
1711
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1712
        val.set_mutable(False)
1713
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1714
        other.append(fp)
1715

    
1716
        # Work
1717
        if self.COLOR_LCD:
1718
            dispab = RadioSetting("settings2.dispab", "Display",
1719
                                  RadioSettingValueList(
1720
                                      LIST_ABCD,
1721
                                      LIST_ABCD[_mem.settings2.dispab]))
1722
            work.append(dispab)
1723
        else:
1724
            dispab = RadioSetting("settings2.dispab", "Display",
1725
                                  RadioSettingValueList(
1726
                                      LIST_AB,
1727
                                      LIST_AB[_mem.settings2.dispab]))
1728
            work.append(dispab)
1729

    
1730
        if self.COLOR_LCD:
1731
            vfomra = RadioSetting("settings2.vfomra", "VFO/MR A mode",
1732
                                  RadioSettingValueList(
1733
                                      LIST_VFOMR,
1734
                                      LIST_VFOMR[_mem.settings2.vfomra]))
1735
            work.append(vfomra)
1736

    
1737
            vfomrb = RadioSetting("settings2.vfomrb", "VFO/MR B mode",
1738
                                  RadioSettingValueList(
1739
                                      LIST_VFOMR,
1740
                                      LIST_VFOMR[_mem.settings2.vfomrb]))
1741
            work.append(vfomrb)
1742

    
1743
            vfomrc = RadioSetting("settings2.vfomrc", "VFO/MR C mode",
1744
                                  RadioSettingValueList(
1745
                                      LIST_VFOMR,
1746
                                      LIST_VFOMR[_mem.settings2.vfomrc]))
1747
            work.append(vfomrc)
1748

    
1749
            vfomrd = RadioSetting("settings2.vfomrd", "VFO/MR D mode",
1750
                                  RadioSettingValueList(
1751
                                      LIST_VFOMR,
1752
                                      LIST_VFOMR[_mem.settings2.vfomrd]))
1753
            work.append(vfomrd)
1754
        else:
1755
            vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1756
                                 RadioSettingValueList(
1757
                                     LIST_VFOMR,
1758
                                     LIST_VFOMR[_mem.settings2.vfomr]))
1759
            work.append(vfomr)
1760

    
1761
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1762
                               RadioSettingValueBoolean(
1763
                                   _mem.settings2.keylock))
1764
        work.append(keylock)
1765

    
1766
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1767
                             RadioSettingValueInteger(0, self._upper,
1768
                                                      _mem.settings2.mrcha))
1769
        work.append(mrcha)
1770

    
1771
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1772
                             RadioSettingValueInteger(0, self._upper,
1773
                                                      _mem.settings2.mrchb))
1774
        work.append(mrchb)
1775

    
1776
        if self.COLOR_LCD:
1777
            mrchc = RadioSetting("settings2.mrchc", "MR C channel",
1778
                                 RadioSettingValueInteger(
1779
                                     0, self._upper, _mem.settings2.mrchc))
1780
            work.append(mrchc)
1781

    
1782
            mrchd = RadioSetting("settings2.mrchd", "MR D channel",
1783
                                 RadioSettingValueInteger(
1784
                                     0, self._upper, _mem.settings2.mrchd))
1785
            work.append(mrchd)
1786

    
1787
        def convert_bytes_to_freq(bytes):
1788
            real_freq = 0
1789
            for byte in bytes:
1790
                real_freq = (real_freq * 10) + byte
1791
            return chirp_common.format_freq(real_freq * 10)
1792

    
1793
        def my_validate(value):
1794
            _vhf_lower = int(convert_bytes_to_limit(_ranges.vhf_low))
1795
            _vhf_upper = int(convert_bytes_to_limit(_ranges.vhf_high))
1796
            _uhf_lower = int(convert_bytes_to_limit(_ranges.uhf_low))
1797
            _uhf_upper = int(convert_bytes_to_limit(_ranges.uhf_high))
1798
            if self.BANDS == 3 or self.BANDS == 4:
1799
                _vhf2_lower = int(convert_bytes_to_limit(_ranges.vhf2_low))
1800
                _vhf2_upper = int(convert_bytes_to_limit(_ranges.vhf2_high))
1801
            if self.BANDS == 4:
1802
                _uhf2_lower = int(convert_bytes_to_limit(_ranges.uhf2_low))
1803
                _uhf2_upper = int(convert_bytes_to_limit(_ranges.uhf2_high))
1804

    
1805
            value = chirp_common.parse_freq(value)
1806
            msg = ("Can't be less then %i.0000")
1807
            if value > 99000000 and value < _vhf_lower * 1000000:
1808
                raise InvalidValueError(msg % (_vhf_lower))
1809
            msg = ("Can't be betweeb %i.9975-%i.0000")
1810
            if self.BANDS == 2:
1811
                if (_vhf_upper + 1) * 1000000 <= value and \
1812
                        value < _uhf_lower * 1000000:
1813
                    raise InvalidValueError(msg % (_vhf_upper, _uhf_lower))
1814
            if self.BANDS == 3:
1815
                if (_vhf_upper + 1) * 1000000 <= value and \
1816
                        value < _vhf2_lower * 1000000:
1817
                    raise InvalidValueError(msg % (_vhf_upper, _vhf2_lower))
1818
                if (_vhf2_upper + 1) * 1000000 <= value and \
1819
                        value < _uhf_lower * 1000000:
1820
                    raise InvalidValueError(msg % (_vhf2_upper, _uhf_lower))
1821
            if self.BANDS == 4:
1822
                if (_vhf_upper + 1) * 1000000 <= value and \
1823
                        value < _vhf2_lower * 1000000:
1824
                    raise InvalidValueError(msg % (_vhf_upper, _vhf2_lower))
1825
                if (_vhf2_upper + 1) * 1000000 <= value and \
1826
                        value < _uhf2_lower * 1000000:
1827
                    raise InvalidValueError(msg % (_vhf2_upper, _uhf2_lower))
1828
                if (_uhf2_upper + 1) * 1000000 <= value and \
1829
                        value < _uhf_lower * 1000000:
1830
                    raise InvalidValueError(msg % (_uhf2_upper, _uhf_lower))
1831
            msg = ("Can't be greater then %i.9975")
1832
            if value > 99000000 and value >= _uhf_upper * 1000000:
1833
                raise InvalidValueError(msg % (_uhf_upper))
1834
            return chirp_common.format_freq(value)
1835

    
1836
        def apply_freq(setting, obj):
1837
            value = chirp_common.parse_freq(str(setting.value)) / 10
1838
            for i in range(7, -1, -1):
1839
                obj.freq[i] = value % 10
1840
                value /= 10
1841

    
1842
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1843
                                        _mem.vfo.a.freq))
1844
        val1a.set_validate_callback(my_validate)
1845
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1846
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1847
        work.append(vfoafreq)
1848

    
1849
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1850
                                        _mem.vfo.b.freq))
1851
        val1b.set_validate_callback(my_validate)
1852
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1853
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1854
        work.append(vfobfreq)
1855

    
1856
        if self.COLOR_LCD:
1857
            val1c = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1858
                                            _mem.vfo.c.freq))
1859
            val1c.set_validate_callback(my_validate)
1860
            vfocfreq = RadioSetting("vfo.c.freq", "VFO C frequency", val1c)
1861
            vfocfreq.set_apply_callback(apply_freq, _mem.vfo.c)
1862
            work.append(vfocfreq)
1863

    
1864
            val1d = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1865
                                            _mem.vfo.d.freq))
1866
            val1d.set_validate_callback(my_validate)
1867
            vfodfreq = RadioSetting("vfo.d.freq", "VFO D frequency", val1d)
1868
            vfodfreq.set_apply_callback(apply_freq, _mem.vfo.d)
1869
            work.append(vfodfreq)
1870

    
1871
        if not self.MODEL == "GMRS-50X1":
1872
            vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1873
                                      RadioSettingValueList(
1874
                                          LIST_SHIFT,
1875
                                          LIST_SHIFT[_mem.vfo.a.shiftd]))
1876
            work.append(vfoashiftd)
1877

    
1878
            vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1879
                                      RadioSettingValueList(
1880
                                          LIST_SHIFT,
1881
                                          LIST_SHIFT[_mem.vfo.b.shiftd]))
1882
            work.append(vfobshiftd)
1883

    
1884
            if self.COLOR_LCD:
1885
                vfocshiftd = RadioSetting("vfo.c.shiftd", "VFO C shift",
1886
                                          RadioSettingValueList(
1887
                                              LIST_SHIFT,
1888
                                              LIST_SHIFT[_mem.vfo.c.shiftd]))
1889
                work.append(vfocshiftd)
1890

    
1891
                vfodshiftd = RadioSetting("vfo.d.shiftd", "VFO D shift",
1892
                                          RadioSettingValueList(
1893
                                              LIST_SHIFT,
1894
                                              LIST_SHIFT[_mem.vfo.d.shiftd]))
1895
                work.append(vfodshiftd)
1896

    
1897
        def convert_bytes_to_offset(bytes):
1898
            real_offset = 0
1899
            for byte in bytes:
1900
                real_offset = (real_offset * 10) + byte
1901
            return chirp_common.format_freq(real_offset * 1000)
1902

    
1903
        def apply_offset(setting, obj):
1904
            value = chirp_common.parse_freq(str(setting.value)) / 1000
1905
            for i in range(5, -1, -1):
1906
                obj.offset[i] = value % 10
1907
                value /= 10
1908

    
1909
        if not self.MODEL == "GMRS-50X1":
1910
            if self.COLOR_LCD:
1911
                val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1912
                                                _mem.vfo.a.offset))
1913
                vfoaoffset = RadioSetting("vfo.a.offset",
1914
                                          "VFO A offset (0.000-999.999)",
1915
                                          val1a)
1916
                vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1917
                work.append(vfoaoffset)
1918

    
1919
                val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1920
                                                _mem.vfo.b.offset))
1921
                vfoboffset = RadioSetting("vfo.b.offset",
1922
                                          "VFO B offset (0.000-999.999)",
1923
                                          val1b)
1924
                vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1925
                work.append(vfoboffset)
1926

    
1927
                val1c = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1928
                                                _mem.vfo.c.offset))
1929
                vfocoffset = RadioSetting("vfo.c.offset",
1930
                                          "VFO C offset (0.000-999.999)",
1931
                                          val1c)
1932
                vfocoffset.set_apply_callback(apply_offset, _mem.vfo.c)
1933
                work.append(vfocoffset)
1934

    
1935
                val1d = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1936
                                                _mem.vfo.d.offset))
1937
                vfodoffset = RadioSetting("vfo.d.offset",
1938
                                          "VFO D offset (0.000-999.999)",
1939
                                          val1d)
1940
                vfodoffset.set_apply_callback(apply_offset, _mem.vfo.d)
1941
                work.append(vfodoffset)
1942
            else:
1943
                val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1944
                                                _mem.vfo.a.offset))
1945
                vfoaoffset = RadioSetting("vfo.a.offset",
1946
                                          "VFO A offset (0.000-99.999)", val1a)
1947
                vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1948
                work.append(vfoaoffset)
1949

    
1950
                val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1951
                                                _mem.vfo.b.offset))
1952
                vfoboffset = RadioSetting("vfo.b.offset",
1953
                                          "VFO B offset (0.000-99.999)", val1b)
1954
                vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1955
                work.append(vfoboffset)
1956

    
1957
        if not self.MODEL == "GMRS-50X1":
1958
            vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1959
                                   RadioSettingValueList(
1960
                                       LIST_TXP,
1961
                                       LIST_TXP[_mem.vfo.a.power]))
1962
            work.append(vfoatxp)
1963

    
1964
            vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1965
                                   RadioSettingValueList(
1966
                                       LIST_TXP,
1967
                                       LIST_TXP[_mem.vfo.b.power]))
1968
            work.append(vfobtxp)
1969

    
1970
            if self.COLOR_LCD:
1971
                vfoctxp = RadioSetting("vfo.c.power", "VFO C power",
1972
                                       RadioSettingValueList(
1973
                                           LIST_TXP,
1974
                                           LIST_TXP[_mem.vfo.c.power]))
1975
                work.append(vfoctxp)
1976

    
1977
                vfodtxp = RadioSetting("vfo.d.power", "VFO D power",
1978
                                       RadioSettingValueList(
1979
                                           LIST_TXP,
1980
                                           LIST_TXP[_mem.vfo.d.power]))
1981
                work.append(vfodtxp)
1982

    
1983
        if not self.MODEL == "GMRS-50X1":
1984
            vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1985
                                    RadioSettingValueList(
1986
                                        LIST_WIDE,
1987
                                        LIST_WIDE[_mem.vfo.a.wide]))
1988
            work.append(vfoawide)
1989

    
1990
            vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1991
                                    RadioSettingValueList(
1992
                                        LIST_WIDE,
1993
                                        LIST_WIDE[_mem.vfo.b.wide]))
1994
            work.append(vfobwide)
1995

    
1996
            if self.COLOR_LCD:
1997
                vfocwide = RadioSetting("vfo.c.wide", "VFO C bandwidth",
1998
                                        RadioSettingValueList(
1999
                                            LIST_WIDE,
2000
                                            LIST_WIDE[_mem.vfo.c.wide]))
2001
                work.append(vfocwide)
2002

    
2003
                vfodwide = RadioSetting("vfo.d.wide", "VFO D bandwidth",
2004
                                        RadioSettingValueList(
2005
                                            LIST_WIDE,
2006
                                            LIST_WIDE[_mem.vfo.d.wide]))
2007
                work.append(vfodwide)
2008

    
2009
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
2010
                                RadioSettingValueList(
2011
                                    LIST_STEP,
2012
                                    LIST_STEP[_mem.vfo.a.step]))
2013
        work.append(vfoastep)
2014

    
2015
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
2016
                                RadioSettingValueList(
2017
                                    LIST_STEP,
2018
                                    LIST_STEP[_mem.vfo.b.step]))
2019
        work.append(vfobstep)
2020

    
2021
        if self.COLOR_LCD:
2022
            vfocstep = RadioSetting("vfo.c.step", "VFO C step",
2023
                                    RadioSettingValueList(
2024
                                        LIST_STEP,
2025
                                        LIST_STEP[_mem.vfo.c.step]))
2026
            work.append(vfocstep)
2027

    
2028
            vfodstep = RadioSetting("vfo.d.step", "VFO D step",
2029
                                    RadioSettingValueList(
2030
                                        LIST_STEP,
2031
                                        LIST_STEP[_mem.vfo.d.step]))
2032
            work.append(vfodstep)
2033

    
2034
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
2035
                                  RadioSettingValueList(
2036
                                      OPTSIG_LIST,
2037
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
2038
        work.append(vfoaoptsig)
2039

    
2040
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
2041
                                  RadioSettingValueList(
2042
                                      OPTSIG_LIST,
2043
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
2044
        work.append(vfoboptsig)
2045

    
2046
        if self.COLOR_LCD:
2047
            vfocoptsig = RadioSetting("vfo.c.optsig", "VFO C optional signal",
2048
                                      RadioSettingValueList(
2049
                                          OPTSIG_LIST,
2050
                                          OPTSIG_LIST[_mem.vfo.c.optsig]))
2051
            work.append(vfocoptsig)
2052

    
2053
            vfodoptsig = RadioSetting("vfo.d.optsig", "VFO D optional signal",
2054
                                      RadioSettingValueList(
2055
                                          OPTSIG_LIST,
2056
                                          OPTSIG_LIST[_mem.vfo.d.optsig]))
2057
            work.append(vfodoptsig)
2058

    
2059
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
2060
                                  RadioSettingValueList(
2061
                                      SPMUTE_LIST,
2062
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
2063
        work.append(vfoaspmute)
2064

    
2065
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
2066
                                  RadioSettingValueList(
2067
                                      SPMUTE_LIST,
2068
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
2069
        work.append(vfobspmute)
2070

    
2071
        if self.COLOR_LCD:
2072
            vfocspmute = RadioSetting("vfo.c.spmute", "VFO C speaker mute",
2073
                                      RadioSettingValueList(
2074
                                          SPMUTE_LIST,
2075
                                          SPMUTE_LIST[_mem.vfo.c.spmute]))
2076
            work.append(vfocspmute)
2077

    
2078
            vfodspmute = RadioSetting("vfo.d.spmute", "VFO D speaker mute",
2079
                                      RadioSettingValueList(
2080
                                          SPMUTE_LIST,
2081
                                          SPMUTE_LIST[_mem.vfo.d.spmute]))
2082
            work.append(vfodspmute)
2083

    
2084
        if not self.COLOR_LCD or \
2085
                (self.COLOR_LCD and not self.VENDOR == "BTECH"):
2086
            vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
2087
                                   RadioSettingValueBoolean(
2088
                                       _mem.vfo.a.scramble))
2089
            work.append(vfoascr)
2090

    
2091
            vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
2092
                                   RadioSettingValueBoolean(
2093
                                       _mem.vfo.b.scramble))
2094
            work.append(vfobscr)
2095

    
2096
        if self.COLOR_LCD and not self.VENDOR == "BTECH":
2097
            vfocscr = RadioSetting("vfo.c.scramble", "VFO C scramble",
2098
                                   RadioSettingValueBoolean(
2099
                                       _mem.vfo.c.scramble))
2100
            work.append(vfocscr)
2101

    
2102
            vfodscr = RadioSetting("vfo.d.scramble", "VFO D scramble",
2103
                                   RadioSettingValueBoolean(
2104
                                       _mem.vfo.d.scramble))
2105
            work.append(vfodscr)
2106

    
2107
        if not self.MODEL == "GMRS-50X1":
2108
            vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
2109
                                     RadioSettingValueList(
2110
                                         PTTIDCODE_LIST,
2111
                                         PTTIDCODE_LIST[_mem.vfo.a.scode]))
2112
            work.append(vfoascode)
2113

    
2114
            vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
2115
                                     RadioSettingValueList(
2116
                                         PTTIDCODE_LIST,
2117
                                         PTTIDCODE_LIST[_mem.vfo.b.scode]))
2118
            work.append(vfobscode)
2119

    
2120
            if self.COLOR_LCD:
2121
                vfocscode = RadioSetting("vfo.c.scode", "VFO C PTT-ID",
2122
                                         RadioSettingValueList(
2123
                                             PTTIDCODE_LIST,
2124
                                             PTTIDCODE_LIST[_mem.vfo.c.scode]))
2125
                work.append(vfocscode)
2126

    
2127
                vfodscode = RadioSetting("vfo.d.scode", "VFO D PTT-ID",
2128
                                         RadioSettingValueList(
2129
                                             PTTIDCODE_LIST,
2130
                                             PTTIDCODE_LIST[_mem.vfo.d.scode]))
2131
                work.append(vfodscode)
2132

    
2133
        if not self.MODEL == "GMRS-50X1":
2134
            pttid = RadioSetting("settings.pttid", "PTT ID",
2135
                                 RadioSettingValueList(
2136
                                     PTTID_LIST,
2137
                                     PTTID_LIST[_mem.settings.pttid]))
2138
            work.append(pttid)
2139

    
2140
        if not self.COLOR_LCD:
2141
            # FM presets
2142
            fm_presets = RadioSettingGroup("fm_presets", "FM Presets")
2143
            top.append(fm_presets)
2144

    
2145
            def fm_validate(value):
2146
                if value == 0:
2147
                    return chirp_common.format_freq(value)
2148
                if not (87.5 <= value and value <= 108.0):  # 87.5-108MHz
2149
                    msg = ("FM-Preset-Frequency: " +
2150
                           "Must be between 87.5 and 108 MHz")
2151
                    raise InvalidValueError(msg)
2152
                return value
2153

    
2154
            def apply_fm_preset_name(setting, obj):
2155
                valstring = str(setting.value)
2156
                for i in range(0, 6):
2157
                    if valstring[i] in VALID_CHARS:
2158
                        obj[i] = valstring[i]
2159
                    else:
2160
                        obj[i] = '0xff'
2161

    
2162
            def apply_fm_freq(setting, obj):
2163
                value = chirp_common.parse_freq(str(setting.value)) / 10
2164
                for i in range(7, -1, -1):
2165
                    obj.freq[i] = value % 10
2166
                    value /= 10
2167

    
2168
            _presets = self._memobj.fm_radio_preset
2169
            i = 1
2170
            for preset in _presets:
2171
                line = RadioSetting("fm_presets_" + str(i),
2172
                                    "Station name " + str(i),
2173
                                    RadioSettingValueString(0, 6, _filter(
2174
                                        preset.broadcast_station_name)))
2175
                line.set_apply_callback(apply_fm_preset_name,
2176
                                        preset.broadcast_station_name)
2177

    
2178
                val = RadioSettingValueFloat(0, 108,
2179
                                             convert_bytes_to_freq(
2180
                                                 preset.freq))
2181
                fmfreq = RadioSetting("fm_presets_" + str(i) + "_freq",
2182
                                      "Frequency " + str(i), val)
2183
                val.set_validate_callback(fm_validate)
2184
                fmfreq.set_apply_callback(apply_fm_freq, preset)
2185
                fm_presets.append(line)
2186
                fm_presets.append(fmfreq)
2187

    
2188
                i = i + 1
2189

    
2190
        # DTMF-Setting
2191
        dtmf_enc_settings = RadioSettingGroup("dtmf_enc_settings",
2192
                                              "DTMF Encoding Settings")
2193
        dtmf_dec_settings = RadioSettingGroup("dtmf_dec_settings",
2194
                                              "DTMF Decoding Settings")
2195
        top.append(dtmf_enc_settings)
2196
        top.append(dtmf_dec_settings)
2197
        txdisable = RadioSetting("dtmf_settings.txdisable",
2198
                                 "TX-Disable",
2199
                                 RadioSettingValueBoolean(
2200
                                     _mem.dtmf_settings.txdisable))
2201
        dtmf_enc_settings.append(txdisable)
2202

    
2203
        rxdisable = RadioSetting("dtmf_settings.rxdisable",
2204
                                 "RX-Disable",
2205
                                 RadioSettingValueBoolean(
2206
                                     _mem.dtmf_settings.rxdisable))
2207
        dtmf_enc_settings.append(rxdisable)
2208

    
2209
        if _mem.dtmf_settings.dtmfspeed_on > 0x0F:
2210
            val = 0x03
2211
        else:
2212
            val = _mem.dtmf_settings.dtmfspeed_on
2213
        dtmfspeed_on = RadioSetting(
2214
            "dtmf_settings.dtmfspeed_on",
2215
            "DTMF Speed (On Time)",
2216
            RadioSettingValueList(LIST_DTMF_SPEED,
2217
                                  LIST_DTMF_SPEED[
2218
                                      val]))
2219
        dtmf_enc_settings.append(dtmfspeed_on)
2220

    
2221
        if _mem.dtmf_settings.dtmfspeed_off > 0x0F:
2222
            val = 0x03
2223
        else:
2224
            val = _mem.dtmf_settings.dtmfspeed_off
2225
        dtmfspeed_off = RadioSetting(
2226
            "dtmf_settings.dtmfspeed_off",
2227
            "DTMF Speed (Off Time)",
2228
            RadioSettingValueList(LIST_DTMF_SPEED,
2229
                                  LIST_DTMF_SPEED[
2230
                                      val]))
2231
        dtmf_enc_settings.append(dtmfspeed_off)
2232

    
2233
        def memory2string(dmtf_mem):
2234
            dtmf_string = ""
2235
            for digit in dmtf_mem:
2236
                if digit != 255:
2237
                    index = LIST_DTMF_VALUES.index(digit)
2238
                    dtmf_string = dtmf_string + LIST_DTMF_DIGITS[index]
2239
            return dtmf_string
2240

    
2241
        def apply_dmtf_frame(setting, obj):
2242
            LOG.debug("Setting DTMF-Code: " + str(setting.value))
2243
            val_string = str(setting.value)
2244
            for i in range(0, 16):
2245
                obj[i] = 255
2246
            i = 0
2247
            for current_char in val_string:
2248
                current_char = current_char.upper()
2249
                index = LIST_DTMF_DIGITS.index(current_char)
2250
                obj[i] = LIST_DTMF_VALUES[index]
2251
                i = i + 1
2252

    
2253
        codes = self._memobj.dtmf_codes
2254
        i = 1
2255
        for dtmfcode in codes:
2256
            val = RadioSettingValueString(0, 16, memory2string(
2257
                                              dtmfcode.code),
2258
                                          False, CHARSET_DTMF_DIGITS)
2259
            line = RadioSetting("dtmf_code_" + str(i) + "_code",
2260
                                "DMTF Code " + str(i), val)
2261
            line.set_apply_callback(apply_dmtf_frame, dtmfcode.code)
2262
            dtmf_enc_settings.append(line)
2263
            i = i + 1
2264

    
2265
        line = RadioSetting("dtmf_settings.mastervice",
2266
                            "Master and Vice ID",
2267
                            RadioSettingValueBoolean(
2268
                                _mem.dtmf_settings.mastervice))
2269
        dtmf_dec_settings.append(line)
2270

    
2271
        val = RadioSettingValueString(0, 16, memory2string(
2272
                                          _mem.dtmf_settings.masterid),
2273
                                      False, CHARSET_DTMF_DIGITS)
2274
        line = RadioSetting("dtmf_settings.masterid",
2275
                            "Master Control ID ", val)
2276
        line.set_apply_callback(apply_dmtf_frame,
2277
                                _mem.dtmf_settings.masterid)
2278
        dtmf_dec_settings.append(line)
2279

    
2280
        line = RadioSetting("dtmf_settings.minspection",
2281
                            "Master Inspection",
2282
                            RadioSettingValueBoolean(
2283
                                _mem.dtmf_settings.minspection))
2284
        dtmf_dec_settings.append(line)
2285

    
2286
        line = RadioSetting("dtmf_settings.mmonitor",
2287
                            "Master Monitor",
2288
                            RadioSettingValueBoolean(
2289
                                _mem.dtmf_settings.mmonitor))
2290
        dtmf_dec_settings.append(line)
2291

    
2292
        line = RadioSetting("dtmf_settings.mstun",
2293
                            "Master Stun",
2294
                            RadioSettingValueBoolean(
2295
                                _mem.dtmf_settings.mstun))
2296
        dtmf_dec_settings.append(line)
2297

    
2298
        line = RadioSetting("dtmf_settings.mkill",
2299
                            "Master Kill",
2300
                            RadioSettingValueBoolean(
2301
                                _mem.dtmf_settings.mkill))
2302
        dtmf_dec_settings.append(line)
2303

    
2304
        line = RadioSetting("dtmf_settings.mrevive",
2305
                            "Master Revive",
2306
                            RadioSettingValueBoolean(
2307
                                _mem.dtmf_settings.mrevive))
2308
        dtmf_dec_settings.append(line)
2309

    
2310
        val = RadioSettingValueString(0, 16, memory2string(
2311
                                          _mem.dtmf_settings.viceid),
2312
                                      False, CHARSET_DTMF_DIGITS)
2313
        line = RadioSetting("dtmf_settings.viceid",
2314
                            "Vice Control ID ", val)
2315
        line.set_apply_callback(apply_dmtf_frame,
2316
                                _mem.dtmf_settings.viceid)
2317
        dtmf_dec_settings.append(line)
2318

    
2319
        line = RadioSetting("dtmf_settings.vinspection",
2320
                            "Vice Inspection",
2321
                            RadioSettingValueBoolean(
2322
                                _mem.dtmf_settings.vinspection))
2323
        dtmf_dec_settings.append(line)
2324

    
2325
        line = RadioSetting("dtmf_settings.vmonitor",
2326
                            "Vice Monitor",
2327
                            RadioSettingValueBoolean(
2328
                                _mem.dtmf_settings.vmonitor))
2329
        dtmf_dec_settings.append(line)
2330

    
2331
        line = RadioSetting("dtmf_settings.vstun",
2332
                            "Vice Stun",
2333
                            RadioSettingValueBoolean(
2334
                                _mem.dtmf_settings.vstun))
2335
        dtmf_dec_settings.append(line)
2336

    
2337
        line = RadioSetting("dtmf_settings.vkill",
2338
                            "Vice Kill",
2339
                            RadioSettingValueBoolean(
2340
                                _mem.dtmf_settings.vkill))
2341
        dtmf_dec_settings.append(line)
2342

    
2343
        line = RadioSetting("dtmf_settings.vrevive",
2344
                            "Vice Revive",
2345
                            RadioSettingValueBoolean(
2346
                                _mem.dtmf_settings.vrevive))
2347
        dtmf_dec_settings.append(line)
2348

    
2349
        val = RadioSettingValueString(0, 16, memory2string(
2350
                                          _mem.dtmf_settings.inspection),
2351
                                      False, CHARSET_DTMF_DIGITS)
2352
        line = RadioSetting("dtmf_settings.inspection",
2353
                            "Inspection", val)
2354
        line.set_apply_callback(apply_dmtf_frame,
2355
                                _mem.dtmf_settings.inspection)
2356
        dtmf_dec_settings.append(line)
2357

    
2358
        val = RadioSettingValueString(0, 16, memory2string(
2359
                                          _mem.dtmf_settings.alarmcode),
2360
                                      False, CHARSET_DTMF_DIGITS)
2361
        line = RadioSetting("dtmf_settings.alarmcode",
2362
                            "Alarm", val)
2363
        line.set_apply_callback(apply_dmtf_frame,
2364
                                _mem.dtmf_settings.alarmcode)
2365
        dtmf_dec_settings.append(line)
2366

    
2367
        val = RadioSettingValueString(0, 16, memory2string(
2368
                                          _mem.dtmf_settings.kill),
2369
                                      False, CHARSET_DTMF_DIGITS)
2370
        line = RadioSetting("dtmf_settings.kill",
2371
                            "Kill", val)
2372
        line.set_apply_callback(apply_dmtf_frame,
2373
                                _mem.dtmf_settings.kill)
2374
        dtmf_dec_settings.append(line)
2375

    
2376
        val = RadioSettingValueString(0, 16, memory2string(
2377
                                          _mem.dtmf_settings.monitor),
2378
                                      False, CHARSET_DTMF_DIGITS)
2379
        line = RadioSetting("dtmf_settings.monitor",
2380
                            "Monitor", val)
2381
        line.set_apply_callback(apply_dmtf_frame,
2382
                                _mem.dtmf_settings.monitor)
2383
        dtmf_dec_settings.append(line)
2384

    
2385
        val = RadioSettingValueString(0, 16, memory2string(
2386
                                          _mem.dtmf_settings.stun),
2387
                                      False, CHARSET_DTMF_DIGITS)
2388
        line = RadioSetting("dtmf_settings.stun",
2389
                            "Stun", val)
2390
        line.set_apply_callback(apply_dmtf_frame,
2391
                                _mem.dtmf_settings.stun)
2392
        dtmf_dec_settings.append(line)
2393

    
2394
        val = RadioSettingValueString(0, 16, memory2string(
2395
                                          _mem.dtmf_settings.revive),
2396
                                      False, CHARSET_DTMF_DIGITS)
2397
        line = RadioSetting("dtmf_settings.revive",
2398
                            "Revive", val)
2399
        line.set_apply_callback(apply_dmtf_frame,
2400
                                _mem.dtmf_settings.revive)
2401
        dtmf_dec_settings.append(line)
2402

    
2403
        def apply_dmtf_listvalue(setting, obj):
2404
            LOG.debug("Setting value: " + str(setting.value) + " from list")
2405
            val = str(setting.value)
2406
            index = LIST_DTMF_SPECIAL_DIGITS.index(val)
2407
            val = LIST_DTMF_SPECIAL_VALUES[index]
2408
            obj.set_value(val)
2409

    
2410
        if _mem.dtmf_settings.groupcode not in LIST_DTMF_SPECIAL_VALUES:
2411
            val = 0x0B
2412
        else:
2413
            val = _mem.dtmf_settings.groupcode
2414
        idx = LIST_DTMF_SPECIAL_VALUES.index(val)
2415
        line = RadioSetting(
2416
            "dtmf_settings.groupcode",
2417
            "Group Code",
2418
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2419
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2420
        line.set_apply_callback(apply_dmtf_listvalue,
2421
                                _mem.dtmf_settings.groupcode)
2422
        dtmf_dec_settings.append(line)
2423

    
2424
        if _mem.dtmf_settings.spacecode not in LIST_DTMF_SPECIAL_VALUES:
2425
            val = 0x0C
2426
        else:
2427
            val = _mem.dtmf_settings.spacecode
2428
        idx = LIST_DTMF_SPECIAL_VALUES.index(val)
2429
        line = RadioSetting(
2430
            "dtmf_settings.spacecode",
2431
            "Space Code",
2432
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2433
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2434
        line.set_apply_callback(apply_dmtf_listvalue,
2435
                                _mem.dtmf_settings.spacecode)
2436
        dtmf_dec_settings.append(line)
2437

    
2438
        if self.COLOR_LCD:
2439
            if _mem.dtmf_settings.resettime > 0x63:
2440
                val = 0x4F
2441
            else:
2442
                val = _mem.dtmf_settings.resettime
2443
            line = RadioSetting(
2444
                "dtmf_settings.resettime",
2445
                "Reset time",
2446
                RadioSettingValueList(LIST_5TONE_RESET_COLOR,
2447
                                      LIST_5TONE_RESET_COLOR[
2448
                                          val]))
2449
            dtmf_dec_settings.append(line)
2450
        else:
2451
            line = RadioSetting(
2452
                "dtmf_settings.resettime",
2453
                "Reset time",
2454
                RadioSettingValueList(LIST_5TONE_RESET,
2455
                                      LIST_5TONE_RESET[
2456
                                          _mem.dtmf_settings.resettime]))
2457
            dtmf_dec_settings.append(line)
2458

    
2459
        if _mem.dtmf_settings.delayproctime > 0x27:
2460
            val = 0x04
2461
        else:
2462
            val = _mem.dtmf_settings.delayproctime
2463
        line = RadioSetting(
2464
            "dtmf_settings.delayproctime",
2465
            "Delay processing time",
2466
            RadioSettingValueList(LIST_DTMF_DELAY,
2467
                                  LIST_DTMF_DELAY[
2468
                                      val]))
2469
        dtmf_dec_settings.append(line)
2470

    
2471
        # 5 Tone Settings
2472
        stds_5tone = RadioSettingGroup("stds_5tone", "Standards")
2473
        codes_5tone = RadioSettingGroup("codes_5tone", "Codes")
2474

    
2475
        group_5tone = RadioSettingGroup("group_5tone", "5 Tone Settings")
2476
        group_5tone.append(stds_5tone)
2477
        group_5tone.append(codes_5tone)
2478

    
2479
        top.append(group_5tone)
2480

    
2481
        def apply_list_value(setting, obj):
2482
            options = setting.value.get_options()
2483
            obj.set_value(options.index(str(setting.value)))
2484

    
2485
        _5tone_standards = self._memobj._5tone_std_settings
2486
        i = 0
2487
        for standard in _5tone_standards:
2488
            std_5tone = RadioSettingGroup("std_5tone_" + str(i),
2489
                                          LIST_5TONE_STANDARDS[i])
2490
            stds_5tone.append(std_5tone)
2491

    
2492
            period = standard.period
2493
            if period == 255:
2494
                LOG.debug("Period for " + LIST_5TONE_STANDARDS[i] +
2495
                          " is not yet configured. Setting to 70ms.")
2496
                period = 5
2497

    
2498
            if period <= len(LIST_5TONE_STANDARD_PERIODS):
2499
                line = RadioSetting(
2500
                    "_5tone_std_settings_" + str(i) + "_period",
2501
                    "Period (ms)", RadioSettingValueList
2502
                    (LIST_5TONE_STANDARD_PERIODS,
2503
                     LIST_5TONE_STANDARD_PERIODS[period]))
2504
                line.set_apply_callback(apply_list_value, standard.period)
2505
                std_5tone.append(line)
2506
            else:
2507
                LOG.debug("Invalid value for 5tone period! Disabling.")
2508

    
2509
            group_tone = standard.group_tone
2510
            if group_tone == 255:
2511
                LOG.debug("Group-Tone for " + LIST_5TONE_STANDARDS[i] +
2512
                          " is not yet configured. Setting to A.")
2513
                group_tone = 10
2514

    
2515
            if group_tone <= len(LIST_5TONE_DIGITS):
2516
                line = RadioSetting(
2517
                    "_5tone_std_settings_" + str(i) + "_grouptone",
2518
                    "Group Tone",
2519
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2520
                                          LIST_5TONE_DIGITS[
2521
                                              group_tone]))
2522
                line.set_apply_callback(apply_list_value,
2523
                                        standard.group_tone)
2524
                std_5tone.append(line)
2525
            else:
2526
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2527

    
2528
            repeat_tone = standard.repeat_tone
2529
            if repeat_tone == 255:
2530
                LOG.debug("Repeat-Tone for " + LIST_5TONE_STANDARDS[i] +
2531
                          " is not yet configured. Setting to E.")
2532
                repeat_tone = 14
2533

    
2534
            if repeat_tone <= len(LIST_5TONE_DIGITS):
2535
                line = RadioSetting(
2536
                    "_5tone_std_settings_" + str(i) + "_repttone",
2537
                    "Repeat Tone",
2538
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2539
                                          LIST_5TONE_DIGITS[
2540
                                              repeat_tone]))
2541
                line.set_apply_callback(apply_list_value,
2542
                                        standard.repeat_tone)
2543
                std_5tone.append(line)
2544
            else:
2545
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2546
            i = i + 1
2547

    
2548
        def my_apply_5tonestdlist_value(setting, obj):
2549
            if LIST_5TONE_STANDARDS.index(str(setting.value)) == 15:
2550
                obj.set_value(0xFF)
2551
            else:
2552
                obj.set_value(LIST_5TONE_STANDARDS.
2553
                              index(str(setting.value)))
2554

    
2555
        def apply_5tone_frame(setting, obj):
2556
            LOG.debug("Setting 5 Tone: " + str(setting.value))
2557
            valstring = str(setting.value)
2558
            if len(valstring) == 0:
2559
                for i in range(0, 5):
2560
                    obj[i] = 255
2561
            else:
2562
                validFrame = True
2563
                for i in range(0, 5):
2564
                    currentChar = valstring[i].upper()
2565
                    if currentChar in LIST_5TONE_DIGITS:
2566
                        obj[i] = LIST_5TONE_DIGITS.index(currentChar)
2567
                    else:
2568
                        validFrame = False
2569
                        LOG.debug("invalid char: " + str(currentChar))
2570
                if not validFrame:
2571
                    LOG.debug("setting whole frame to FF")
2572
                    for i in range(0, 5):
2573
                        obj[i] = 255
2574

    
2575
        def validate_5tone_frame(value):
2576
            if (len(str(value)) != 5) and (len(str(value)) != 0):
2577
                msg = ("5 Tone must have 5 digits or 0 digits")
2578
                raise InvalidValueError(msg)
2579
            for digit in str(value):
2580
                if digit.upper() not in LIST_5TONE_DIGITS:
2581
                    msg = (str(digit) + " is not a valid digit for 5tones")
2582
                    raise InvalidValueError(msg)
2583
            return value
2584

    
2585
        def frame2string(frame):
2586
            frameString = ""
2587
            for digit in frame:
2588
                if digit != 255:
2589
                    frameString = frameString + LIST_5TONE_DIGITS[digit]
2590
            return frameString
2591

    
2592
        _5tone_codes = self._memobj._5tone_codes
2593
        i = 1
2594
        for code in _5tone_codes:
2595
            code_5tone = RadioSettingGroup("code_5tone_" + str(i),
2596
                                           "5 Tone code " + str(i))
2597
            codes_5tone.append(code_5tone)
2598
            if (code.standard == 255):
2599
                currentVal = 15
2600
            else:
2601
                currentVal = code.standard
2602
            line = RadioSetting("_5tone_code_" + str(i) + "_std",
2603
                                " Standard",
2604
                                RadioSettingValueList(LIST_5TONE_STANDARDS,
2605
                                                      LIST_5TONE_STANDARDS[
2606
                                                          currentVal]))
2607
            line.set_apply_callback(my_apply_5tonestdlist_value,
2608
                                    code.standard)
2609
            code_5tone.append(line)
2610

    
2611
            val = RadioSettingValueString(0, 6,
2612
                                          frame2string(code.frame1), False)
2613
            line = RadioSetting("_5tone_code_" + str(i) + "_frame1",
2614
                                " Frame 1", val)
2615
            val.set_validate_callback(validate_5tone_frame)
2616
            line.set_apply_callback(apply_5tone_frame, code.frame1)
2617
            code_5tone.append(line)
2618

    
2619
            val = RadioSettingValueString(0, 6,
2620
                                          frame2string(code.frame2), False)
2621
            line = RadioSetting("_5tone_code_" + str(i) + "_frame2",
2622
                                " Frame 2", val)
2623
            val.set_validate_callback(validate_5tone_frame)
2624
            line.set_apply_callback(apply_5tone_frame, code.frame2)
2625
            code_5tone.append(line)
2626

    
2627
            val = RadioSettingValueString(0, 6,
2628
                                          frame2string(code.frame3), False)
2629
            line = RadioSetting("_5tone_code_" + str(i) + "_frame3",
2630
                                " Frame 3", val)
2631
            val.set_validate_callback(validate_5tone_frame)
2632
            line.set_apply_callback(apply_5tone_frame, code.frame3)
2633
            code_5tone.append(line)
2634
            i = i + 1
2635

    
2636
        _5_tone_decode1 = RadioSetting(
2637
            "_5tone_settings._5tone_decode_call_frame1",
2638
            "5 Tone decode call Frame 1",
2639
            RadioSettingValueBoolean(
2640
                _mem._5tone_settings._5tone_decode_call_frame1))
2641
        group_5tone.append(_5_tone_decode1)
2642

    
2643
        _5_tone_decode2 = RadioSetting(
2644
            "_5tone_settings._5tone_decode_call_frame2",
2645
            "5 Tone decode call Frame 2",
2646
            RadioSettingValueBoolean(
2647
                _mem._5tone_settings._5tone_decode_call_frame2))
2648
        group_5tone.append(_5_tone_decode2)
2649

    
2650
        _5_tone_decode3 = RadioSetting(
2651
            "_5tone_settings._5tone_decode_call_frame3",
2652
            "5 Tone decode call Frame 3",
2653
            RadioSettingValueBoolean(
2654
                _mem._5tone_settings._5tone_decode_call_frame3))
2655
        group_5tone.append(_5_tone_decode3)
2656

    
2657
        _5_tone_decode_disp1 = RadioSetting(
2658
            "_5tone_settings._5tone_decode_disp_frame1",
2659
            "5 Tone decode disp Frame 1",
2660
            RadioSettingValueBoolean(
2661
                _mem._5tone_settings._5tone_decode_disp_frame1))
2662
        group_5tone.append(_5_tone_decode_disp1)
2663

    
2664
        _5_tone_decode_disp2 = RadioSetting(
2665
            "_5tone_settings._5tone_decode_disp_frame2",
2666
            "5 Tone decode disp Frame 2",
2667
            RadioSettingValueBoolean(
2668
                _mem._5tone_settings._5tone_decode_disp_frame2))
2669
        group_5tone.append(_5_tone_decode_disp2)
2670

    
2671
        _5_tone_decode_disp3 = RadioSetting(
2672
            "_5tone_settings._5tone_decode_disp_frame3",
2673
            "5 Tone decode disp Frame 3",
2674
            RadioSettingValueBoolean(
2675
                _mem._5tone_settings._5tone_decode_disp_frame3))
2676
        group_5tone.append(_5_tone_decode_disp3)
2677

    
2678
        decode_standard = _mem._5tone_settings.decode_standard
2679
        if decode_standard == 255:
2680
            decode_standard = 0
2681
        if decode_standard <= len(LIST_5TONE_STANDARDS_without_none):
2682
            line = RadioSetting("_5tone_settings.decode_standard",
2683
                                "5 Tone-decode Standard",
2684
                                RadioSettingValueList(
2685
                                    LIST_5TONE_STANDARDS_without_none,
2686
                                    LIST_5TONE_STANDARDS_without_none[
2687
                                        decode_standard]))
2688
            group_5tone.append(line)
2689
        else:
2690
            LOG.debug("Invalid decode std...")
2691

    
2692
        _5tone_delay1 = _mem._5tone_settings._5tone_delay1
2693
        if _5tone_delay1 == 255:
2694
            _5tone_delay1 = 20
2695

    
2696
        if _5tone_delay1 <= len(LIST_5TONE_DELAY):
2697
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2698
                                         LIST_5TONE_DELAY[
2699
                                             _5tone_delay1])
2700
            line = RadioSetting("_5tone_settings._5tone_delay1",
2701
                                "5 Tone Delay Frame 1", list)
2702
            group_5tone.append(line)
2703
        else:
2704
            LOG.debug("Invalid value for 5tone delay (frame1) ! Disabling.")
2705

    
2706
        _5tone_delay2 = _mem._5tone_settings._5tone_delay2
2707
        if _5tone_delay2 == 255:
2708
            _5tone_delay2 = 20
2709
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2710

    
2711
        if _5tone_delay2 <= len(LIST_5TONE_DELAY):
2712
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2713
                                         LIST_5TONE_DELAY[
2714
                                             _5tone_delay2])
2715
            line = RadioSetting("_5tone_settings._5tone_delay2",
2716
                                "5 Tone Delay Frame 2", list)
2717
            group_5tone.append(line)
2718
        else:
2719
            LOG.debug("Invalid value for 5tone delay (frame2)! Disabling.")
2720

    
2721
        _5tone_delay3 = _mem._5tone_settings._5tone_delay3
2722
        if _5tone_delay3 == 255:
2723
            _5tone_delay3 = 20
2724
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2725

    
2726
        if _5tone_delay3 <= len(LIST_5TONE_DELAY):
2727
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2728
                                         LIST_5TONE_DELAY[
2729
                                             _5tone_delay3])
2730
            line = RadioSetting("_5tone_settings._5tone_delay3",
2731
                                "5 Tone Delay Frame 3", list)
2732
            group_5tone.append(line)
2733
        else:
2734
            LOG.debug("Invalid value for 5tone delay (frame3)! Disabling.")
2735

    
2736
        ext_length = _mem._5tone_settings._5tone_first_digit_ext_length
2737
        if ext_length == 255:
2738
            ext_length = 0
2739
            LOG.debug("1st Tone ext lenght unconfigured! Resetting to 0")
2740

    
2741
        if ext_length <= len(LIST_5TONE_DELAY):
2742
            list = RadioSettingValueList(
2743
                LIST_5TONE_DELAY,
2744
                LIST_5TONE_DELAY[
2745
                    ext_length])
2746
            line = RadioSetting(
2747
                "_5tone_settings._5tone_first_digit_ext_length",
2748
                "First digit extend length", list)
2749
            group_5tone.append(line)
2750
        else:
2751
            LOG.debug("Invalid value for 5tone ext length! Disabling.")
2752

    
2753
        decode_reset_time = _mem._5tone_settings.decode_reset_time
2754
        if decode_reset_time == 255:
2755
            decode_reset_time = 59
2756
            LOG.debug("Decode reset time unconfigured. resetting.")
2757
        if decode_reset_time <= len(LIST_5TONE_RESET):
2758
            list = RadioSettingValueList(
2759
                LIST_5TONE_RESET,
2760
                LIST_5TONE_RESET[
2761
                    decode_reset_time])
2762
            line = RadioSetting("_5tone_settings.decode_reset_time",
2763
                                "Decode reset time", list)
2764
            group_5tone.append(line)
2765
        else:
2766
            LOG.debug("Invalid value decode reset time! Disabling.")
2767

    
2768
        # 2 Tone
2769
        encode_2tone = RadioSettingGroup("encode_2tone", "2 Tone Encode")
2770
        decode_2tone = RadioSettingGroup("decode_2tone", "2 Code Decode")
2771

    
2772
        top.append(encode_2tone)
2773
        top.append(decode_2tone)
2774

    
2775
        duration_1st_tone = self._memobj._2tone.duration_1st_tone
2776
        if duration_1st_tone == 255:
2777
            LOG.debug("Duration of first 2 Tone digit is not yet " +
2778
                      "configured. Setting to 600ms")
2779
            duration_1st_tone = 60
2780

    
2781
        if duration_1st_tone <= len(LIST_5TONE_DELAY):
2782
            line = RadioSetting("_2tone.duration_1st_tone",
2783
                                "Duration 1st Tone",
2784
                                RadioSettingValueList(LIST_5TONE_DELAY,
2785
                                                      LIST_5TONE_DELAY[
2786
                                                          duration_1st_tone]))
2787
            encode_2tone.append(line)
2788

    
2789
        duration_2nd_tone = self._memobj._2tone.duration_2nd_tone
2790
        if duration_2nd_tone == 255:
2791
            LOG.debug("Duration of second 2 Tone digit is not yet " +
2792
                      "configured. Setting to 600ms")
2793
            duration_2nd_tone = 60
2794

    
2795
        if duration_2nd_tone <= len(LIST_5TONE_DELAY):
2796
            line = RadioSetting("_2tone.duration_2nd_tone",
2797
                                "Duration 2nd Tone",
2798
                                RadioSettingValueList(LIST_5TONE_DELAY,
2799
                                                      LIST_5TONE_DELAY[
2800
                                                          duration_2nd_tone]))
2801
            encode_2tone.append(line)
2802

    
2803
        duration_gap = self._memobj._2tone.duration_gap
2804
        if duration_gap == 255:
2805
            LOG.debug("Duration of gap is not yet " +
2806
                      "configured. Setting to 300ms")
2807
            duration_gap = 30
2808

    
2809
        if duration_gap <= len(LIST_5TONE_DELAY):
2810
            line = RadioSetting("_2tone.duration_gap", "Duration of gap",
2811
                                RadioSettingValueList(LIST_5TONE_DELAY,
2812
                                                      LIST_5TONE_DELAY[
2813
                                                          duration_gap]))
2814
            encode_2tone.append(line)
2815

    
2816
        def _2tone_validate(value):
2817
            if value == 0:
2818
                return 65535
2819
            if value == 65535:
2820
                return value
2821
            if not (300 <= value and value <= 3000):
2822
                msg = ("2 Tone Frequency: Must be between 300 and 3000 Hz")
2823
                raise InvalidValueError(msg)
2824
            return value
2825

    
2826
        def apply_2tone_freq(setting, obj):
2827
            val = int(setting.value)
2828
            if (val == 0) or (val == 65535):
2829
                obj.set_value(65535)
2830
            else:
2831
                obj.set_value(val)
2832

    
2833
        i = 1
2834
        for code in self._memobj._2tone._2tone_encode:
2835
            code_2tone = RadioSettingGroup("code_2tone_" + str(i),
2836
                                           "Encode Code " + str(i))
2837
            encode_2tone.append(code_2tone)
2838

    
2839
            tmp = code.freq1
2840
            if tmp == 65535:
2841
                tmp = 0
2842
            val1 = RadioSettingValueInteger(0, 65535, tmp)
2843
            freq1 = RadioSetting("2tone_code_" + str(i) + "_freq1",
2844
                                 "Frequency 1", val1)
2845
            val1.set_validate_callback(_2tone_validate)
2846
            freq1.set_apply_callback(apply_2tone_freq, code.freq1)
2847
            code_2tone.append(freq1)
2848

    
2849
            tmp = code.freq2
2850
            if tmp == 65535:
2851
                tmp = 0
2852
            val2 = RadioSettingValueInteger(0, 65535, tmp)
2853
            freq2 = RadioSetting("2tone_code_" + str(i) + "_freq2",
2854
                                 "Frequency 2", val2)
2855
            val2.set_validate_callback(_2tone_validate)
2856
            freq2.set_apply_callback(apply_2tone_freq, code.freq2)
2857
            code_2tone.append(freq2)
2858

    
2859
            i = i + 1
2860

    
2861
        decode_reset_time = _mem._2tone.reset_time
2862
        if decode_reset_time == 255:
2863
            decode_reset_time = 59
2864
            LOG.debug("Decode reset time unconfigured. resetting.")
2865
        if decode_reset_time <= len(LIST_5TONE_RESET):
2866
            list = RadioSettingValueList(
2867
                LIST_5TONE_RESET,
2868
                LIST_5TONE_RESET[
2869
                    decode_reset_time])
2870
            line = RadioSetting("_2tone.reset_time",
2871
                                "Decode reset time", list)
2872
            decode_2tone.append(line)
2873
        else:
2874
            LOG.debug("Invalid value decode reset time! Disabling.")
2875

    
2876
        def apply_2tone_freq_pair(setting, obj):
2877
            val = int(setting.value)
2878
            derived_val = 65535
2879
            frqname = str(setting._name[-5:])
2880
            derivedname = "derived_from_" + frqname
2881

    
2882
            if (val == 0):
2883
                val = 65535
2884
                derived_val = 65535
2885
            else:
2886
                derived_val = int(round(2304000.0/val))
2887

    
2888
            obj[frqname].set_value(val)
2889
            obj[derivedname].set_value(derived_val)
2890

    
2891
            LOG.debug("Apply " + frqname + ": " + str(val) + " | " +
2892
                      derivedname + ": " + str(derived_val))
2893

    
2894
        i = 1
2895
        for decode_code in self._memobj._2tone._2tone_decode:
2896
            _2tone_dec_code = RadioSettingGroup("code_2tone_" + str(i),
2897
                                                "Decode Code " + str(i))
2898
            decode_2tone.append(_2tone_dec_code)
2899

    
2900
            j = 1
2901
            for dec in decode_code.decs:
2902
                val = dec.dec
2903
                if val == 255:
2904
                    LOG.debug("Dec for Code " + str(i) + " Dec " + str(j) +
2905
                              " is not yet configured. Setting to 0.")
2906
                    val = 0
2907

    
2908
                if val <= len(LIST_2TONE_DEC):
2909
                    line = RadioSetting(
2910
                        "_2tone_dec_settings_" + str(i) + "_dec_" + str(j),
2911
                        "Dec " + str(j), RadioSettingValueList
2912
                        (LIST_2TONE_DEC,
2913
                         LIST_2TONE_DEC[val]))
2914
                    line.set_apply_callback(apply_list_value, dec.dec)
2915
                    _2tone_dec_code.append(line)
2916
                else:
2917
                    LOG.debug("Invalid value for 2tone dec! Disabling.")
2918

    
2919
                val = dec.response
2920
                if val == 255:
2921
                    LOG.debug("Response for Code " + str(i) + " Dec " +
2922
                              str(j) + " is not yet configured. Setting to 0.")
2923
                    val = 0
2924

    
2925
                if val <= len(LIST_2TONE_RESPONSE):
2926
                    line = RadioSetting(
2927
                        "_2tone_dec_settings_" + str(i) + "_resp_" + str(j),
2928
                        "Response " + str(j), RadioSettingValueList
2929
                        (LIST_2TONE_RESPONSE,
2930
                         LIST_2TONE_RESPONSE[val]))
2931
                    line.set_apply_callback(apply_list_value, dec.response)
2932
                    _2tone_dec_code.append(line)
2933
                else:
2934
                    LOG.debug("Invalid value for 2tone response! Disabling.")
2935

    
2936
                val = dec.alert
2937
                if val == 255:
2938
                    LOG.debug("Alert for Code " + str(i) + " Dec " + str(j) +
2939
                              " is not yet configured. Setting to 0.")
2940
                    val = 0
2941

    
2942
                if val <= len(PTTIDCODE_LIST):
2943
                    line = RadioSetting(
2944
                        "_2tone_dec_settings_" + str(i) + "_alert_" + str(j),
2945
                        "Alert " + str(j), RadioSettingValueList
2946
                        (PTTIDCODE_LIST,
2947
                         PTTIDCODE_LIST[val]))
2948
                    line.set_apply_callback(apply_list_value, dec.alert)
2949
                    _2tone_dec_code.append(line)
2950
                else:
2951
                    LOG.debug("Invalid value for 2tone alert! Disabling.")
2952
                j = j + 1
2953

    
2954
            freq = self._memobj._2tone.freqs[i-1]
2955
            for char in ['A', 'B', 'C', 'D']:
2956
                setting_name = "freq" + str(char)
2957

    
2958
                tmp = freq[setting_name]
2959
                if tmp == 65535:
2960
                    tmp = 0
2961
                if tmp != 0:
2962
                    expected = int(round(2304000.0/tmp))
2963
                    from_mem = freq["derived_from_" + setting_name]
2964
                    if expected != from_mem:
2965
                        LOG.error("Expected " + str(expected) +
2966
                                  " but read " + str(from_mem) +
2967
                                  ". Disabling 2Tone Decode Freqs!")
2968
                        break
2969
                val = RadioSettingValueInteger(0, 65535, tmp)
2970
                frq = RadioSetting("2tone_dec_" + str(i) + "_freq" + str(char),
2971
                                   ("Decode Frequency " + str(char)), val)
2972
                val.set_validate_callback(_2tone_validate)
2973
                frq.set_apply_callback(apply_2tone_freq_pair, freq)
2974
                _2tone_dec_code.append(frq)
2975

    
2976
            i = i + 1
2977

    
2978
        return top
2979

    
2980
    def set_settings(self, settings):
2981
        _settings = self._memobj.settings
2982
        for element in settings:
2983
            if not isinstance(element, RadioSetting):
2984
                if element.get_name() == "fm_preset":
2985
                    self._set_fm_preset(element)
2986
                else:
2987
                    self.set_settings(element)
2988
                    continue
2989
            else:
2990
                try:
2991
                    name = element.get_name()
2992
                    if "." in name:
2993
                        bits = name.split(".")
2994
                        obj = self._memobj
2995
                        for bit in bits[:-1]:
2996
                            if "/" in bit:
2997
                                bit, index = bit.split("/", 1)
2998
                                index = int(index)
2999
                                obj = getattr(obj, bit)[index]
3000
                            else:
3001
                                obj = getattr(obj, bit)
3002
                        setting = bits[-1]
3003
                    else:
3004
                        obj = _settings
3005
                        setting = element.get_name()
3006

    
3007
                    if element.has_apply_callback():
3008
                        LOG.debug("Using apply callback")
3009
                        element.run_apply_callback()
3010
                    elif element.value.get_mutable():
3011
                        LOG.debug("Setting %s = %s" % (setting, element.value))
3012
                        setattr(obj, setting, element.value)
3013
                except Exception, e:
3014
                    LOG.debug(element.get_name())
3015
                    raise
3016

    
3017
    @classmethod
3018
    def match_model(cls, filedata, filename):
3019
        match_size = False
3020
        match_model = False
3021

    
3022
        # testing the file data size
3023
        if len(filedata) == MEM_SIZE:
3024
            match_size = True
3025

    
3026
        # testing the firmware model fingerprint
3027
        match_model = model_match(cls, filedata)
3028

    
3029
        if match_size and match_model:
3030
            return True
3031
        else:
3032
            return False
3033

    
3034

    
3035
MEM_FORMAT = """
3036
#seekto 0x0000;
3037
struct {
3038
  lbcd rxfreq[4];
3039
  lbcd txfreq[4];
3040
  ul16 rxtone;
3041
  ul16 txtone;
3042
  u8 unknown0:4,
3043
     scode:4;
3044
  u8 unknown1:2,
3045
     spmute:2,
3046
     unknown2:2,
3047
     optsig:2;
3048
  u8 unknown3:3,
3049
     scramble:1,
3050
     unknown4:3,
3051
     power:1;
3052
  u8 unknown5:1,
3053
     wide:1,
3054
     unknown6:2,
3055
     bcl:1,
3056
     add:1,
3057
     pttid:2;
3058
} memory[200];
3059

    
3060
#seekto 0x0E00;
3061
struct {
3062
  u8 tdr;
3063
  u8 unknown1;
3064
  u8 sql;
3065
  u8 unknown2[2];
3066
  u8 tot;
3067
  u8 apo;           // BTech radios use this as the Auto Power Off time
3068
                    // other radios use this as pre-Time Out Alert
3069
  u8 unknown3;
3070
  u8 abr;
3071
  u8 beep;
3072
  u8 unknown4[4];
3073
  u8 dtmfst;
3074
  u8 unknown5[2];
3075
  u8 prisc;
3076
  u8 prich;
3077
  u8 screv;
3078
  u8 unknown6[2];
3079
  u8 pttid;
3080
  u8 pttlt;
3081
  u8 unknown7;
3082
  u8 emctp;
3083
  u8 emcch;
3084
  u8 ringt;
3085
  u8 unknown8;
3086
  u8 camdf;
3087
  u8 cbmdf;
3088
  u8 sync;          // BTech radios use this as the display sync setting
3089
                    // other radios use this as the auto keypad lock setting
3090
  u8 ponmsg;
3091
  u8 wtled;
3092
  u8 rxled;
3093
  u8 txled;
3094
  u8 unknown9[5];
3095
  u8 anil;
3096
  u8 reps;
3097
  u8 repm;
3098
  u8 tdrab;
3099
  u8 ste;
3100
  u8 rpste;
3101
  u8 rptdl;
3102
  u8 mgain;
3103
  u8 dtmfg;
3104
} settings;
3105

    
3106
#seekto 0x0E80;
3107
struct {
3108
  u8 unknown1;
3109
  u8 vfomr;
3110
  u8 keylock;
3111
  u8 unknown2;
3112
  u8 unknown3:4,
3113
     vfomren:1,
3114
     unknown4:1,
3115
     reseten:1,
3116
     menuen:1;
3117
  u8 unknown5[11];
3118
  u8 dispab;
3119
  u8 mrcha;
3120
  u8 mrchb;
3121
  u8 menu;
3122
} settings2;
3123

    
3124
#seekto 0x0EC0;
3125
struct {
3126
  char line1[6];
3127
  char line2[6];
3128
} poweron_msg;
3129

    
3130
struct settings_vfo {
3131
  u8 freq[8];
3132
  u8 offset[6];
3133
  u8 unknown2[2];
3134
  ul16 rxtone;
3135
  ul16 txtone;
3136
  u8 scode;
3137
  u8 spmute;
3138
  u8 optsig;
3139
  u8 scramble;
3140
  u8 wide;
3141
  u8 power;
3142
  u8 shiftd;
3143
  u8 step;
3144
  u8 unknown3[4];
3145
};
3146

    
3147
#seekto 0x0F00;
3148
struct {
3149
  struct settings_vfo a;
3150
  struct settings_vfo b;
3151
} vfo;
3152

    
3153
#seekto 0x1000;
3154
struct {
3155
  char name[6];
3156
  u8 unknown1[10];
3157
} names[200];
3158

    
3159
#seekto 0x2400;
3160
struct {
3161
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3162
  u8 group_tone;
3163
  u8 repeat_tone;
3164
  u8 unused[13];
3165
} _5tone_std_settings[15];
3166

    
3167
#seekto 0x2500;
3168
struct {
3169
  u8 frame1[5];
3170
  u8 frame2[5];
3171
  u8 frame3[5];
3172
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3173
} _5tone_codes[15];
3174

    
3175
#seekto 0x25F0;
3176
struct {
3177
  u8 _5tone_delay1; // * 10ms
3178
  u8 _5tone_delay2; // * 10ms
3179
  u8 _5tone_delay3; // * 10ms
3180
  u8 _5tone_first_digit_ext_length;
3181
  u8 unknown1;
3182
  u8 unknown2;
3183
  u8 unknown3;
3184
  u8 unknown4;
3185
  u8 decode_standard;
3186
  u8 unknown5:5,
3187
     _5tone_decode_call_frame3:1,
3188
     _5tone_decode_call_frame2:1,
3189
     _5tone_decode_call_frame1:1;
3190
  u8 unknown6:5,
3191
     _5tone_decode_disp_frame3:1,
3192
     _5tone_decode_disp_frame2:1,
3193
     _5tone_decode_disp_frame1:1;
3194
  u8 decode_reset_time; // * 100 + 100ms
3195
} _5tone_settings;
3196

    
3197
#seekto 0x2900;
3198
struct {
3199
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3200
} dtmf_codes[15];
3201

    
3202
#seekto 0x29F0;
3203
struct {
3204
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
3205
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
3206
  u8 unknown0[14];
3207
  u8 inspection[16];
3208
  u8 monitor[16];
3209
  u8 alarmcode[16];
3210
  u8 stun[16];
3211
  u8 kill[16];
3212
  u8 revive[16];
3213
  u8 unknown1[16];
3214
  u8 unknown2[16];
3215
  u8 unknown3[16];
3216
  u8 unknown4[16];
3217
  u8 unknown5[16];
3218
  u8 unknown6[16];
3219
  u8 unknown7[16];
3220
  u8 masterid[16];
3221
  u8 viceid[16];
3222
  u8 unused01:7,
3223
     mastervice:1;
3224
  u8 unused02:3,
3225
     mrevive:1,
3226
     mkill:1,
3227
     mstun:1,
3228
     mmonitor:1,
3229
     minspection:1;
3230
  u8 unused03:3,
3231
     vrevive:1,
3232
     vkill:1,
3233
     vstun:1,
3234
     vmonitor:1,
3235
     vinspection:1;
3236
  u8 unused04:6,
3237
     txdisable:1,
3238
     rxdisable:1;
3239
  u8 groupcode;
3240
  u8 spacecode;
3241
  u8 delayproctime; // * 100 + 100ms
3242
  u8 resettime;     // * 100 + 100ms
3243
} dtmf_settings;
3244

    
3245
#seekto 0x2D00;
3246
struct {
3247
  struct {
3248
    ul16 freq1;
3249
    u8 unused01[6];
3250
    ul16 freq2;
3251
    u8 unused02[6];
3252
  } _2tone_encode[15];
3253
  u8 duration_1st_tone; // *10ms
3254
  u8 duration_2nd_tone; // *10ms
3255
  u8 duration_gap;      // *10ms
3256
  u8 unused03[13];
3257
  struct {
3258
    struct {
3259
      u8 dec;      // one out of LIST_2TONE_DEC
3260
      u8 response; // one out of LIST_2TONE_RESPONSE
3261
      u8 alert;    // 1-16
3262
    } decs[4];
3263
    u8 unused04[4];
3264
  } _2tone_decode[15];
3265
  u8 unused05[16];
3266

    
3267
  struct {
3268
    ul16 freqA;
3269
    ul16 freqB;
3270
    ul16 freqC;
3271
    ul16 freqD;
3272
    // unknown what those values mean, but they are
3273
    // derived from configured frequencies
3274
    ul16 derived_from_freqA; // 2304000/freqA
3275
    ul16 derived_from_freqB; // 2304000/freqB
3276
    ul16 derived_from_freqC; // 2304000/freqC
3277
    ul16 derived_from_freqD; // 2304000/freqD
3278
  }freqs[15];
3279
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
3280
} _2tone;
3281

    
3282
#seekto 0x3000;
3283
struct {
3284
  u8 freq[8];
3285
  char broadcast_station_name[6];
3286
  u8 unknown[2];
3287
} fm_radio_preset[16];
3288

    
3289
#seekto 0x3C90;
3290
struct {
3291
  u8 vhf_low[3];
3292
  u8 vhf_high[3];
3293
  u8 uhf_low[3];
3294
  u8 uhf_high[3];
3295
} ranges;
3296

    
3297
// the UV-2501+220 & KT8900R has different zones for storing ranges
3298

    
3299
#seekto 0x3CD0;
3300
struct {
3301
  u8 vhf_low[3];
3302
  u8 vhf_high[3];
3303
  u8 unknown1[4];
3304
  u8 unknown2[6];
3305
  u8 vhf2_low[3];
3306
  u8 vhf2_high[3];
3307
  u8 unknown3[4];
3308
  u8 unknown4[6];
3309
  u8 uhf_low[3];
3310
  u8 uhf_high[3];
3311
} ranges220;
3312

    
3313
#seekto 0x3F70;
3314
struct {
3315
  char fp[6];
3316
} fingerprint;
3317

    
3318
"""
3319

    
3320

    
3321
class BTech(BTechMobileCommon):
3322
    """BTECH's UV-5001 and alike radios"""
3323
    BANDS = 2
3324
    COLOR_LCD = False
3325
    NAME_LENGTH = 6
3326

    
3327
    def set_options(self):
3328
        """This is to read the options from the image and set it in the
3329
        environment, for now just the limits of the freqs in the VHF/UHF
3330
        ranges"""
3331

    
3332
        # setting the correct ranges for each radio type
3333
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3334
            # the model 2501+220 has a segment in 220
3335
            # and a different position in the memmap
3336
            # also the QYT KT8900R
3337
            ranges = self._memobj.ranges220
3338
        else:
3339
            ranges = self._memobj.ranges
3340

    
3341
        # the normal dual bands
3342
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3343
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3344

    
3345
        # DEBUG
3346
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3347
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3348

    
3349
        # 220Mhz radios case
3350
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3351
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3352
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3353
            self._220_range = vhf2
3354

    
3355
        # set the class with the real data
3356
        self._vhf_range = vhf
3357
        self._uhf_range = uhf
3358

    
3359
    def process_mmap(self):
3360
        """Process the mem map into the mem object"""
3361

    
3362
        # Get it
3363
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
3364

    
3365
        # load specific parameters from the radio image
3366
        self.set_options()
3367

    
3368

    
3369
# Declaring Aliases (Clones of the real radios)
3370
class JT2705M(chirp_common.Alias):
3371
    VENDOR = "Jetstream"
3372
    MODEL = "JT2705M"
3373

    
3374

    
3375
class JT6188Mini(chirp_common.Alias):
3376
    VENDOR = "Juentai"
3377
    MODEL = "JT-6188 Mini"
3378

    
3379

    
3380
class JT6188Plus(chirp_common.Alias):
3381
    VENDOR = "Juentai"
3382
    MODEL = "JT-6188 Plus"
3383

    
3384

    
3385
class SSGT890(chirp_common.Alias):
3386
    VENDOR = "Sainsonic"
3387
    MODEL = "GT-890"
3388

    
3389

    
3390
class ZastoneMP300(chirp_common.Alias):
3391
    VENDOR = "Zastone"
3392
    MODEL = "MP-300"
3393

    
3394

    
3395
# real radios
3396
@directory.register
3397
class UV2501(BTech):
3398
    """Baofeng Tech UV2501"""
3399
    MODEL = "UV-2501"
3400
    _fileid = [UV2501G3_fp,
3401
               UV2501G2_fp,
3402
               UV2501pp2_fp,
3403
               UV2501pp_fp]
3404

    
3405

    
3406
@directory.register
3407
class UV2501_220(BTech):
3408
    """Baofeng Tech UV2501+220"""
3409
    MODEL = "UV-2501+220"
3410
    BANDS = 3
3411
    _magic = MSTRING_220
3412
    _id2 = [UV2501_220pp_id, ]
3413
    _fileid = [UV2501_220G3_fp,
3414
               UV2501_220G2_fp,
3415
               UV2501_220_fp,
3416
               UV2501_220pp_fp]
3417

    
3418

    
3419
@directory.register
3420
class UV5001(BTech):
3421
    """Baofeng Tech UV5001"""
3422
    MODEL = "UV-5001"
3423
    _fileid = [UV5001G3_fp,
3424
               UV5001G22_fp,
3425
               UV5001G2_fp,
3426
               UV5001alpha_fp,
3427
               UV5001pp_fp]
3428
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
3429
                     chirp_common.PowerLevel("Low", watts=10)]
3430

    
3431

    
3432
@directory.register
3433
class MINI8900(BTech):
3434
    """WACCOM MINI-8900"""
3435
    VENDOR = "WACCOM"
3436
    MODEL = "MINI-8900"
3437
    _magic = MSTRING_MINI8900
3438
    _fileid = [MINI8900_fp, ]
3439
    # Clones
3440
    ALIASES = [JT6188Plus, ]
3441

    
3442

    
3443
@directory.register
3444
class KTUV980(BTech):
3445
    """QYT KT-UV980"""
3446
    VENDOR = "QYT"
3447
    MODEL = "KT-UV980"
3448
    _vhf_range = (136000000, 175000000)
3449
    _uhf_range = (400000000, 481000000)
3450
    _magic = MSTRING_MINI8900
3451
    _fileid = [KTUV980_fp, ]
3452
    # Clones
3453
    ALIASES = [JT2705M, ]
3454

    
3455
# Please note that there is a version of this radios that is a clone of the
3456
# Waccom Mini8900, maybe an early version?
3457

    
3458

    
3459
@directory.register
3460
class KT9800(BTech):
3461
    """QYT KT8900"""
3462
    VENDOR = "QYT"
3463
    MODEL = "KT8900"
3464
    _vhf_range = (136000000, 175000000)
3465
    _uhf_range = (400000000, 481000000)
3466
    _magic = MSTRING_KT8900
3467
    _fileid = [KT8900_fp,
3468
               KT8900_fp1,
3469
               KT8900_fp2,
3470
               KT8900_fp3,
3471
               KT8900_fp4,
3472
               KT8900_fp5]
3473
    _id2 = [KT8900_id, ]
3474
    # Clones
3475
    ALIASES = [JT6188Mini, SSGT890, ZastoneMP300]
3476

    
3477

    
3478
@directory.register
3479
class KT9800R(BTech):
3480
    """QYT KT8900R"""
3481
    VENDOR = "QYT"
3482
    MODEL = "KT8900R"
3483
    BANDS = 3
3484
    _vhf_range = (136000000, 175000000)
3485
    _220_range = (240000000, 271000000)
3486
    _uhf_range = (400000000, 481000000)
3487
    _magic = MSTRING_KT8900R
3488
    _fileid = [KT8900R_fp,
3489
               KT8900R_fp1,
3490
               KT8900R_fp2,
3491
               KT8900R_fp3,
3492
               KT8900R_fp4]
3493
    _id2 = [KT8900R_id, KT8900R_id2]
3494

    
3495

    
3496
@directory.register
3497
class LT588UV(BTech):
3498
    """LUITON LT-588UV"""
3499
    VENDOR = "LUITON"
3500
    MODEL = "LT-588UV"
3501
    _vhf_range = (136000000, 175000000)
3502
    _uhf_range = (400000000, 481000000)
3503
    _magic = MSTRING_KT8900
3504
    _fileid = [LT588UV_fp,
3505
               LT588UV_fp1]
3506
    _power_levels = [chirp_common.PowerLevel("High", watts=60),
3507
                     chirp_common.PowerLevel("Low", watts=10)]
3508

    
3509

    
3510
COLOR_MEM_FORMAT = """
3511
#seekto 0x0000;
3512
struct {
3513
  lbcd rxfreq[4];
3514
  lbcd txfreq[4];
3515
  ul16 rxtone;
3516
  ul16 txtone;
3517
  u8 unknown0:4,
3518
     scode:4;
3519
  u8 unknown1:2,
3520
     spmute:2,
3521
     unknown2:2,
3522
     optsig:2;
3523
  u8 unknown3:3,
3524
     scramble:1,
3525
     unknown4:3,
3526
     power:1;
3527
  u8 unknown5:1,
3528
     wide:1,
3529
     unknown6:2,
3530
     bcl:1,
3531
     add:1,
3532
     pttid:2;
3533
} memory[200];
3534

    
3535
#seekto 0x0E00;
3536
struct {
3537
  u8 tmr;
3538
  u8 unknown1;
3539
  u8 sql;
3540
  u8 unknown2[2];
3541
  u8 tot;
3542
  u8 apo;
3543
  u8 unknown3;
3544
  u8 abr;
3545
  u8 beep;
3546
  u8 unknown4[4];
3547
  u8 dtmfst;
3548
  u8 unknown5[2];
3549
  u8 screv;
3550
  u8 unknown6[2];
3551
  u8 pttid;
3552
  u8 pttlt;
3553
  u8 unknown7;
3554
  u8 emctp;
3555
  u8 emcch;
3556
  u8 sigbp;
3557
  u8 unknown8;
3558
  u8 camdf;
3559
  u8 cbmdf;
3560
  u8 ccmdf;
3561
  u8 cdmdf;
3562
  u8 langua;
3563
  u8 sync;          // BTech radios use this as the display sync
3564
                    // setting, other radios use this as the auto
3565
                    // keypad lock setting
3566
  u8 mainfc;
3567
  u8 mainbc;
3568
  u8 menufc;
3569
  u8 menubc;
3570
  u8 stafc;
3571
  u8 stabc;
3572
  u8 sigfc;
3573
  u8 sigbc;
3574
  u8 rxfc;
3575
  u8 txfc;
3576
  u8 txdisp;
3577
  u8 unknown9[5];
3578
  u8 anil;
3579
  u8 reps;
3580
  u8 repm;
3581
  u8 tmrmr;
3582
  u8 ste;
3583
  u8 rpste;
3584
  u8 rptdl;
3585
  u8 dtmfg;
3586
  u8 mgain;
3587
  u8 skiptx;
3588
  u8 scmode;
3589
} settings;
3590

    
3591
#seekto 0x0E80;
3592
struct {
3593
  u8 unknown1;
3594
  u8 vfomr;
3595
  u8 keylock;
3596
  u8 unknown2;
3597
  u8 unknown3:4,
3598
     vfomren:1,
3599
     unknown4:1,
3600
     reseten:1,
3601
     menuen:1;
3602
  u8 unknown5[11];
3603
  u8 dispab;
3604
  u8 unknown6[2];
3605
  u8 menu;
3606
  u8 unknown7[7];
3607
  u8 vfomra;
3608
  u8 vfomrb;
3609
  u8 vfomrc;
3610
  u8 vfomrd;
3611
  u8 mrcha;
3612
  u8 mrchb;
3613
  u8 mrchc;
3614
  u8 mrchd;
3615
} settings2;
3616

    
3617
struct settings_vfo {
3618
  u8 freq[8];
3619
  u8 offset[6];
3620
  u8 unknown2[2];
3621
  ul16 rxtone;
3622
  ul16 txtone;
3623
  u8 scode;
3624
  u8 spmute;
3625
  u8 optsig;
3626
  u8 scramble;
3627
  u8 wide;
3628
  u8 power;
3629
  u8 shiftd;
3630
  u8 step;
3631
  u8 unknown3[4];
3632
};
3633

    
3634
#seekto 0x0F00;
3635
struct {
3636
  struct settings_vfo a;
3637
  struct settings_vfo b;
3638
  struct settings_vfo c;
3639
  struct settings_vfo d;
3640
} vfo;
3641

    
3642
#seekto 0x0F80;
3643
struct {
3644
  char line1[8];
3645
  char line2[8];
3646
  char line3[8];
3647
  char line4[8];
3648
  char line5[8];
3649
  char line6[8];
3650
  char line7[8];
3651
  char line8[8];
3652
} poweron_msg;
3653

    
3654
#seekto 0x1000;
3655
struct {
3656
  char name[8];
3657
  u8 unknown1[8];
3658
} names[200];
3659

    
3660
#seekto 0x2400;
3661
struct {
3662
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3663
  u8 group_tone;
3664
  u8 repeat_tone;
3665
  u8 unused[13];
3666
} _5tone_std_settings[15];
3667

    
3668
#seekto 0x2500;
3669
struct {
3670
  u8 frame1[5];
3671
  u8 frame2[5];
3672
  u8 frame3[5];
3673
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3674
} _5tone_codes[15];
3675

    
3676
#seekto 0x25F0;
3677
struct {
3678
  u8 _5tone_delay1; // * 10ms
3679
  u8 _5tone_delay2; // * 10ms
3680
  u8 _5tone_delay3; // * 10ms
3681
  u8 _5tone_first_digit_ext_length;
3682
  u8 unknown1;
3683
  u8 unknown2;
3684
  u8 unknown3;
3685
  u8 unknown4;
3686
  u8 decode_standard;
3687
  u8 unknown5:5,
3688
     _5tone_decode_call_frame3:1,
3689
     _5tone_decode_call_frame2:1,
3690
     _5tone_decode_call_frame1:1;
3691
  u8 unknown6:5,
3692
     _5tone_decode_disp_frame3:1,
3693
     _5tone_decode_disp_frame2:1,
3694
     _5tone_decode_disp_frame1:1;
3695
  u8 decode_reset_time; // * 100 + 100ms
3696
} _5tone_settings;
3697

    
3698
#seekto 0x2900;
3699
struct {
3700
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3701
} dtmf_codes[15];
3702

    
3703
#seekto 0x29F0;
3704
struct {
3705
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
3706
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
3707
  u8 unknown0[14];
3708
  u8 inspection[16];
3709
  u8 monitor[16];
3710
  u8 alarmcode[16];
3711
  u8 stun[16];
3712
  u8 kill[16];
3713
  u8 revive[16];
3714
  u8 unknown1[16];
3715
  u8 unknown2[16];
3716
  u8 unknown3[16];
3717
  u8 unknown4[16];
3718
  u8 unknown5[16];
3719
  u8 unknown6[16];
3720
  u8 unknown7[16];
3721
  u8 masterid[16];
3722
  u8 viceid[16];
3723
  u8 unused01:7,
3724
     mastervice:1;
3725
  u8 unused02:3,
3726
     mrevive:1,
3727
     mkill:1,
3728
     mstun:1,
3729
     mmonitor:1,
3730
     minspection:1;
3731
  u8 unused03:3,
3732
     vrevive:1,
3733
     vkill:1,
3734
     vstun:1,
3735
     vmonitor:1,
3736
     vinspection:1;
3737
  u8 unused04:6,
3738
     txdisable:1,
3739
     rxdisable:1;
3740
  u8 groupcode;
3741
  u8 spacecode;
3742
  u8 delayproctime; // * 100 + 100ms
3743
  u8 resettime;     // * 100 + 100ms
3744
} dtmf_settings;
3745

    
3746
#seekto 0x2D00;
3747
struct {
3748
  struct {
3749
    ul16 freq1;
3750
    u8 unused01[6];
3751
    ul16 freq2;
3752
    u8 unused02[6];
3753
  } _2tone_encode[15];
3754
  u8 duration_1st_tone; // *10ms
3755
  u8 duration_2nd_tone; // *10ms
3756
  u8 duration_gap;      // *10ms
3757
  u8 unused03[13];
3758
  struct {
3759
    struct {
3760
      u8 dec;      // one out of LIST_2TONE_DEC
3761
      u8 response; // one out of LIST_2TONE_RESPONSE
3762
      u8 alert;    // 1-16
3763
    } decs[4];
3764
    u8 unused04[4];
3765
  } _2tone_decode[15];
3766
  u8 unused05[16];
3767

    
3768
  struct {
3769
    ul16 freqA;
3770
    ul16 freqB;
3771
    ul16 freqC;
3772
    ul16 freqD;
3773
    // unknown what those values mean, but they are
3774
    // derived from configured frequencies
3775
    ul16 derived_from_freqA; // 2304000/freqA
3776
    ul16 derived_from_freqB; // 2304000/freqB
3777
    ul16 derived_from_freqC; // 2304000/freqC
3778
    ul16 derived_from_freqD; // 2304000/freqD
3779
  }freqs[15];
3780
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
3781
} _2tone;
3782

    
3783
#seekto 0x3D80;
3784
struct {
3785
  u8 vhf_low[3];
3786
  u8 vhf_high[3];
3787
  u8 unknown1[4];
3788
  u8 unknown2[6];
3789
  u8 vhf2_low[3];
3790
  u8 vhf2_high[3];
3791
  u8 unknown3[4];
3792
  u8 unknown4[6];
3793
  u8 uhf_low[3];
3794
  u8 uhf_high[3];
3795
  u8 unknown5[4];
3796
  u8 unknown6[6];
3797
  u8 uhf2_low[3];
3798
  u8 uhf2_high[3];
3799
} ranges;
3800

    
3801
#seekto 0x3F70;
3802
struct {
3803
  char fp[6];
3804
} fingerprint;
3805

    
3806
"""
3807

    
3808

    
3809
class BTechColor(BTechMobileCommon):
3810
    """BTECH's Color LCD Mobile and alike radios"""
3811
    COLOR_LCD = True
3812
    NAME_LENGTH = 8
3813
    LIST_TMR = LIST_TMR16
3814

    
3815
    def process_mmap(self):
3816
        """Process the mem map into the mem object"""
3817

    
3818
        # Get it
3819
        self._memobj = bitwise.parse(COLOR_MEM_FORMAT, self._mmap)
3820

    
3821
        # load specific parameters from the radio image
3822
        self.set_options()
3823

    
3824
    def set_options(self):
3825
        """This is to read the options from the image and set it in the
3826
        environment, for now just the limits of the freqs in the VHF/UHF
3827
        ranges"""
3828

    
3829
        # setting the correct ranges for each radio type
3830
        ranges = self._memobj.ranges
3831

    
3832
        # the normal dual bands
3833
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3834
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3835

    
3836
        # DEBUG
3837
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3838
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3839

    
3840
        # the additional bands
3841
        if self.MODEL in ["UV-25X4", "KT7900D"]:
3842
            # 200Mhz band
3843
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3844
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3845
            self._220_range = vhf2
3846

    
3847
            # 350Mhz band
3848
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
3849
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
3850
            self._350_range = uhf2
3851

    
3852
        # set the class with the real data
3853
        self._vhf_range = vhf
3854
        self._uhf_range = uhf
3855

    
3856

    
3857
# Declaring Aliases (Clones of the real radios)
3858
class SKT8900D(chirp_common.Alias):
3859
    VENDOR = "Surecom"
3860
    MODEL = "S-KT8900D"
3861

    
3862

    
3863
class QB25(chirp_common.Alias):
3864
    VENDOR = "Radioddity"
3865
    MODEL = "QB25"
3866

    
3867

    
3868
# real radios
3869
@directory.register
3870
class UV25X2(BTechColor):
3871
    """Baofeng Tech UV25X2"""
3872
    MODEL = "UV-25X2"
3873
    BANDS = 2
3874
    _vhf_range = (130000000, 180000000)
3875
    _uhf_range = (400000000, 521000000)
3876
    _magic = MSTRING_UV25X2
3877
    _fileid = [UV25X2_fp, ]
3878

    
3879

    
3880
@directory.register
3881
class UV25X4(BTechColor):
3882
    """Baofeng Tech UV25X4"""
3883
    MODEL = "UV-25X4"
3884
    BANDS = 4
3885
    _vhf_range = (130000000, 180000000)
3886
    _220_range = (200000000, 271000000)
3887
    _uhf_range = (400000000, 521000000)
3888
    _350_range = (350000000, 391000000)
3889
    _magic = MSTRING_UV25X4
3890
    _fileid = [UV25X4_fp, ]
3891

    
3892

    
3893
@directory.register
3894
class UV50X2(BTechColor):
3895
    """Baofeng Tech UV50X2"""
3896
    MODEL = "UV-50X2"
3897
    BANDS = 2
3898
    _vhf_range = (130000000, 180000000)
3899
    _uhf_range = (400000000, 521000000)
3900
    _magic = MSTRING_UV25X2
3901
    _fileid = [UV50X2_fp, ]
3902
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
3903
                     chirp_common.PowerLevel("Low", watts=10)]
3904

    
3905

    
3906
@directory.register
3907
class KT7900D(BTechColor):
3908
    """QYT KT7900D"""
3909
    VENDOR = "QYT"
3910
    MODEL = "KT7900D"
3911
    BANDS = 4
3912
    LIST_TMR = LIST_TMR15
3913
    _vhf_range = (136000000, 175000000)
3914
    _220_range = (200000000, 271000000)
3915
    _uhf_range = (400000000, 481000000)
3916
    _350_range = (350000000, 371000000)
3917
    _magic = MSTRING_KT8900D
3918
    _fileid = [KT7900D_fp, KT7900D_fp1, KT7900D_fp2, KT7900D_fp3, KT7900D_fp4,
3919
               KT7900D_fp5, QB25_fp, ]
3920
    # Clones
3921
    ALIASES = [SKT8900D, QB25, ]
3922

    
3923

    
3924
@directory.register
3925
class KT8900D(BTechColor):
3926
    """QYT KT8900D"""
3927
    VENDOR = "QYT"
3928
    MODEL = "KT8900D"
3929
    BANDS = 2
3930
    LIST_TMR = LIST_TMR15
3931
    _vhf_range = (136000000, 175000000)
3932
    _uhf_range = (400000000, 481000000)
3933
    _magic = MSTRING_KT8900D
3934
    _fileid = [KT8900D_fp, KT8900D_fp1]
3935

    
3936

    
3937
@directory.register
3938
class KT5800(BTechColor):
3939
    """QYT KT5800"""
3940
    VENDOR = "QYT"
3941
    MODEL = "KT5800"
3942
    BANDS = 2
3943
    LIST_TMR = LIST_TMR15
3944
    _vhf_range = (136000000, 175000000)
3945
    _uhf_range = (400000000, 481000000)
3946
    _magic = MSTRING_KT8900D
3947
    _fileid = [KT5800_fp, ]
3948

    
3949

    
3950
GMRS_MEM_FORMAT = """
3951
#seekto 0x0000;
3952
struct {
3953
  lbcd rxfreq[4];
3954
  lbcd txfreq[4];
3955
  ul16 rxtone;
3956
  ul16 txtone;
3957
  u8 unknown0:4,
3958
     scode:4;
3959
  u8 unknown1:2,
3960
     spmute:2,
3961
     unknown2:2,
3962
     optsig:2;
3963
  u8 unknown3:3,
3964
     scramble:1,
3965
     unknown4:2,
3966
     power:2;
3967
  u8 unknown5:1,
3968
     wide:1,
3969
     unknown6:2,
3970
     bcl:1,
3971
     add:1,
3972
     pttid:2;
3973
} memory[256];
3974

    
3975
#seekto 0x1000;
3976
struct {
3977
  char name[7];
3978
  u8 unknown1[9];
3979
} names[256];
3980

    
3981
#seekto 0x2400;
3982
struct {
3983
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3984
  u8 group_tone;
3985
  u8 repeat_tone;
3986
  u8 unused[13];
3987
} _5tone_std_settings[15];
3988

    
3989
#seekto 0x2500;
3990
struct {
3991
  u8 frame1[5];
3992
  u8 frame2[5];
3993
  u8 frame3[5];
3994
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3995
} _5tone_codes[15];
3996

    
3997
#seekto 0x25F0;
3998
struct {
3999
  u8 _5tone_delay1; // * 10ms
4000
  u8 _5tone_delay2; // * 10ms
4001
  u8 _5tone_delay3; // * 10ms
4002
  u8 _5tone_first_digit_ext_length;
4003
  u8 unknown1;
4004
  u8 unknown2;
4005
  u8 unknown3;
4006
  u8 unknown4;
4007
  u8 decode_standard;
4008
  u8 unknown5:5,
4009
     _5tone_decode_call_frame3:1,
4010
     _5tone_decode_call_frame2:1,
4011
     _5tone_decode_call_frame1:1;
4012
  u8 unknown6:5,
4013
     _5tone_decode_disp_frame3:1,
4014
     _5tone_decode_disp_frame2:1,
4015
     _5tone_decode_disp_frame1:1;
4016
  u8 decode_reset_time; // * 100 + 100ms
4017
} _5tone_settings;
4018

    
4019
#seekto 0x2900;
4020
struct {
4021
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
4022
} dtmf_codes[15];
4023

    
4024
#seekto 0x29F0;
4025
struct {
4026
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
4027
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
4028
  u8 unknown0[14];
4029
  u8 inspection[16];
4030
  u8 monitor[16];
4031
  u8 alarmcode[16];
4032
  u8 stun[16];
4033
  u8 kill[16];
4034
  u8 revive[16];
4035
  u8 unknown1[16];
4036
  u8 unknown2[16];
4037
  u8 unknown3[16];
4038
  u8 unknown4[16];
4039
  u8 unknown5[16];
4040
  u8 unknown6[16];
4041
  u8 unknown7[16];
4042
  u8 masterid[16];
4043
  u8 viceid[16];
4044
  u8 unused01:7,
4045
     mastervice:1;
4046
  u8 unused02:3,
4047
     mrevive:1,
4048
     mkill:1,
4049
     mstun:1,
4050
     mmonitor:1,
4051
     minspection:1;
4052
  u8 unused03:3,
4053
     vrevive:1,
4054
     vkill:1,
4055
     vstun:1,
4056
     vmonitor:1,
4057
     vinspection:1;
4058
  u8 unused04:6,
4059
     txdisable:1,
4060
     rxdisable:1;
4061
  u8 groupcode;
4062
  u8 spacecode;
4063
  u8 delayproctime; // * 100 + 100ms
4064
  u8 resettime;     // * 100 + 100ms
4065
} dtmf_settings;
4066

    
4067
#seekto 0x2D00;
4068
struct {
4069
  struct {
4070
    ul16 freq1;
4071
    u8 unused01[6];
4072
    ul16 freq2;
4073
    u8 unused02[6];
4074
  } _2tone_encode[15];
4075
  u8 duration_1st_tone; // *10ms
4076
  u8 duration_2nd_tone; // *10ms
4077
  u8 duration_gap;      // *10ms
4078
  u8 unused03[13];
4079
  struct {
4080
    struct {
4081
      u8 dec;      // one out of LIST_2TONE_DEC
4082
      u8 response; // one out of LIST_2TONE_RESPONSE
4083
      u8 alert;    // 1-16
4084
    } decs[4];
4085
    u8 unused04[4];
4086
  } _2tone_decode[15];
4087
  u8 unused05[16];
4088

    
4089
  struct {
4090
    ul16 freqA;
4091
    ul16 freqB;
4092
    ul16 freqC;
4093
    ul16 freqD;
4094
    // unknown what those values mean, but they are
4095
    // derived from configured frequencies
4096
    ul16 derived_from_freqA; // 2304000/freqA
4097
    ul16 derived_from_freqB; // 2304000/freqB
4098
    ul16 derived_from_freqC; // 2304000/freqC
4099
    ul16 derived_from_freqD; // 2304000/freqD
4100
  }freqs[15];
4101
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
4102
} _2tone;
4103

    
4104
#seekto 0x3000;
4105
struct {
4106
  u8 freq[8];
4107
  char broadcast_station_name[6];
4108
  u8 unknown[2];
4109
} fm_radio_preset[16];
4110

    
4111
#seekto 0x3200;
4112
struct {
4113
  u8 tmr;
4114
  u8 unknown1;
4115
  u8 sql;
4116
  u8 unknown2;
4117
  u8 autolk;
4118
  u8 tot;
4119
  u8 apo;
4120
  u8 unknown3;
4121
  u8 abr;
4122
  u8 beep;
4123
  u8 unknown4[4];
4124
  u8 dtmfst;
4125
  u8 unknown5[2];
4126
  u8 screv;
4127
  u8 unknown6[2];
4128
  u8 pttid;
4129
  u8 pttlt;
4130
  u8 unknown7;
4131
  u8 emctp;
4132
  u8 emcch;
4133
  u8 sigbp;
4134
  u8 unknown8;
4135
  u8 camdf;
4136
  u8 cbmdf;
4137
  u8 ccmdf;
4138
  u8 cdmdf;
4139
  u8 langua;
4140
  u8 sync;
4141

    
4142

    
4143
  u8 stfc;
4144
  u8 mffc;
4145
  u8 sfafc;
4146
  u8 sfbfc;
4147
  u8 sfcfc;
4148
  u8 sfdfc;
4149
  u8 subfc;
4150
  u8 fmfc;
4151
  u8 sigfc;
4152
  u8 modfc;
4153
  u8 menufc;
4154
  u8 txfc;
4155
  u8 txdisp;
4156
  u8 unknown9[5];
4157
  u8 anil;
4158
  u8 reps;
4159
  u8 repm;
4160
  u8 tmrmr;
4161
  u8 ste;
4162
  u8 rpste;
4163
  u8 rptdl;
4164
  u8 dtmfg;
4165
  u8 mgain;
4166
  u8 skiptx;
4167
  u8 scmode;
4168
} settings;
4169

    
4170
#seekto 0x3280;
4171
struct {
4172
  u8 unknown1;
4173
  u8 vfomr;
4174
  u8 keylock;
4175
  u8 unknown2;
4176
  u8 unknown3:4,
4177
     vfomren:1,
4178
     unknown4:1,
4179
     reseten:1,
4180
     menuen:1;
4181
  u8 unknown5[11];
4182
  u8 dispab;
4183
  u8 unknown6[2];
4184
  u8 smenu;
4185
  u8 unknown7[7];
4186
  u8 vfomra;
4187
  u8 vfomrb;
4188
  u8 vfomrc;
4189
  u8 vfomrd;
4190
  u8 mrcha;
4191
  u8 mrchb;
4192
  u8 mrchc;
4193
  u8 mrchd;
4194
} settings2;
4195

    
4196
struct settings_vfo {
4197
  u8 freq[8];
4198
  u8 offset[6];
4199
  u8 unknown2[2];
4200
  ul16 rxtone;
4201
  ul16 txtone;
4202
  u8 scode;
4203
  u8 spmute;
4204
  u8 optsig;
4205
  u8 scramble;
4206
  u8 wide;
4207
  u8 power;
4208
  u8 shiftd;
4209
  u8 step;
4210
  u8 unknown3[4];
4211
};
4212

    
4213
#seekto 0x3300;
4214
struct {
4215
  struct settings_vfo a;
4216
  struct settings_vfo b;
4217
  struct settings_vfo c;
4218
  struct settings_vfo d;
4219
} vfo;
4220

    
4221
#seekto 0x3D80;
4222
struct {
4223
  u8 vhf_low[3];
4224
  u8 vhf_high[3];
4225
  u8 unknown1[4];
4226
  u8 unknown2[6];
4227
  u8 vhf2_low[3];
4228
  u8 vhf2_high[3];
4229
  u8 unknown3[4];
4230
  u8 unknown4[6];
4231
  u8 uhf_low[3];
4232
  u8 uhf_high[3];
4233
  u8 unknown5[4];
4234
  u8 unknown6[6];
4235
  u8 uhf2_low[3];
4236
  u8 uhf2_high[3];
4237
} ranges;
4238

    
4239
#seekto 0x33B0;
4240
struct {
4241
  char line[16];
4242
} static_msg;
4243

    
4244
#seekto 0x3F70;
4245
struct {
4246
  char fp[6];
4247
} fingerprint;
4248

    
4249
"""
4250

    
4251

    
4252
class BTechGMRS(BTechMobileCommon):
4253
    """BTECH's GMRS Mobile"""
4254
    COLOR_LCD = True
4255
    COLOR_LCD2 = True
4256
    NAME_LENGTH = 7
4257
    UPLOAD_MEM_SIZE = 0X3400
4258

    
4259
    def process_mmap(self):
4260
        """Process the mem map into the mem object"""
4261

    
4262
        # Get it
4263
        self._memobj = bitwise.parse(GMRS_MEM_FORMAT, self._mmap)
4264

    
4265
        # load specific parameters from the radio image
4266
        self.set_options()
4267

    
4268
    def set_options(self):
4269
        """This is to read the options from the image and set it in the
4270
        environment, for now just the limits of the freqs in the VHF/UHF
4271
        ranges"""
4272

    
4273
        # setting the correct ranges for each radio type
4274
        ranges = self._memobj.ranges
4275

    
4276
        # the normal dual bands
4277
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
4278
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
4279

    
4280
        # DEBUG
4281
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
4282
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
4283

    
4284
        # set the class with the real data
4285
        self._vhf_range = vhf
4286
        self._uhf_range = uhf
4287

    
4288

    
4289
# real radios
4290
@directory.register
4291
class GMRS50X1(BTechGMRS):
4292
    """Baofeng Tech GMRS50X1"""
4293
    MODEL = "GMRS-50X1"
4294
    BANDS = 2
4295
    LIST_TMR = LIST_TMR16
4296
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
4297
                     chirp_common.PowerLevel("Mid", watts=10),
4298
                     chirp_common.PowerLevel("Low", watts=5)]
4299
    _vhf_range = (136000000, 175000000)
4300
    _uhf_range = (400000000, 521000000)
4301
    _upper = 255
4302
    _magic = MSTRING_GMRS50X1
4303
    _fileid = [GMRS50X1_fp1, GMRS50X1_fp, ]
4304

    
4305

    
4306
COLORHT_MEM_FORMAT = """
4307
#seekto 0x0000;
4308
struct {
4309
  lbcd rxfreq[4];
4310
  lbcd txfreq[4];
4311
  ul16 rxtone;
4312
  ul16 txtone;
4313
  u8 unknown0:4,
4314
     scode:4;
4315
  u8 unknown1:2,
4316
     spmute:2,
4317
     unknown2:2,
4318
     optsig:2;
4319
  u8 unknown3:3,
4320
     scramble:1,
4321
     unknown4:3,
4322
     power:1;
4323
  u8 unknown5:1,
4324
     wide:1,
4325
     unknown6:2,
4326
     bcl:1,
4327
     add:1,
4328
     pttid:2;
4329
} memory[200];
4330

    
4331
#seekto 0x0E00;
4332
struct {
4333
  u8 tmr;
4334
  u8 unknownE01;
4335
  u8 sql;
4336
  u8 unknownE03[2];
4337
  u8 tot;
4338
  u8 save;
4339
  u8 unknownE07;
4340
  u8 abr;
4341
  u8 beep;
4342
  u8 unknownE0A[4];
4343
  u8 dsub;
4344
  u8 dtmfst;
4345
  u8 screv;
4346
  u8 unknownE11[3];
4347
  u8 pttid;
4348
  u8 unknownE15;
4349
  u8 pttlt;
4350
  u8 unknownE17;
4351
  u8 emctp;
4352
  u8 emcch;
4353
  u8 sigbp;
4354
  u8 unknownE1B;
4355
  u8 camdf;
4356
  u8 cbmdf;
4357
  u8 ccmdf;
4358
  u8 cdmdf;
4359
  u8 langua;
4360
  u8 voice;
4361
  u8 vox;
4362
  u8 voxt;
4363
  u8 sync;          // BTech radios use this as the display sync setting
4364
                    // other radios use this as the auto keypad lock setting
4365
  u8 stfc;
4366
  u8 mffc;
4367
  u8 sfafc;
4368
  u8 sfbfc;
4369
  u8 sfcfc;
4370
  u8 sfdfc;
4371
  u8 subfc;
4372
  u8 fmfc;
4373
  u8 sigfc;
4374
  u8 menufc;
4375
  u8 txfc;
4376
  u8 rxfc;
4377
  u8 unknownE31[5];
4378
  u8 anil;
4379
  u8 reps;
4380
  u8 tmrmr;
4381
  u8 ste;
4382
  u8 rpste;
4383
  u8 rptdl;
4384
  u8 dtmfg;
4385
  u8 tmrtx;
4386
} settings;
4387

    
4388
#seekto 0x0E80;
4389
struct {
4390
  u8 unknown1;
4391
  u8 vfomr;
4392
  u8 keylock;
4393
  u8 unknown2;
4394
  u8 unknown3:4,
4395
     vfomren:1,
4396
     unknown4:1,
4397
     reseten:1,
4398
     menuen:1;
4399
  u8 unknown5[11];
4400
  u8 dispab;
4401
  u8 unknown6[2];
4402
  u8 menu;
4403
  u8 unknown7[7];
4404
  u8 vfomra;
4405
  u8 vfomrb;
4406
  u8 vfomrc;
4407
  u8 vfomrd;
4408
  u8 mrcha;
4409
  u8 mrchb;
4410
  u8 mrchc;
4411
  u8 mrchd;
4412
} settings2;
4413

    
4414
struct settings_vfo {
4415
  u8 freq[8];
4416
  u8 offset[6];
4417
  u8 unknown2[2];
4418
  ul16 rxtone;
4419
  ul16 txtone;
4420
  u8 scode;
4421
  u8 spmute;
4422
  u8 optsig;
4423
  u8 scramble;
4424
  u8 wide;
4425
  u8 power;
4426
  u8 shiftd;
4427
  u8 step;
4428
  u8 unknown3[4];
4429
};
4430

    
4431
#seekto 0x0F00;
4432
struct {
4433
  struct settings_vfo a;
4434
  struct settings_vfo b;
4435
  struct settings_vfo c;
4436
  struct settings_vfo d;
4437
} vfo;
4438

    
4439
#seekto 0x0FE0;
4440
struct {
4441
  char line[16];
4442
} static_msg;
4443

    
4444
#seekto 0x1000;
4445
struct {
4446
  char name[8];
4447
  u8 unknown1[8];
4448
} names[200];
4449

    
4450
#seekto 0x2400;
4451
struct {
4452
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
4453
  u8 group_tone;
4454
  u8 repeat_tone;
4455
  u8 unused[13];
4456
} _5tone_std_settings[15];
4457

    
4458
#seekto 0x2500;
4459
struct {
4460
  u8 frame1[5];
4461
  u8 frame2[5];
4462
  u8 frame3[5];
4463
  u8 standard;   // one out of LIST_5TONE_STANDARDS
4464
} _5tone_codes[15];
4465

    
4466
#seekto 0x25F0;
4467
struct {
4468
  u8 _5tone_delay1; // * 10ms
4469
  u8 _5tone_delay2; // * 10ms
4470
  u8 _5tone_delay3; // * 10ms
4471
  u8 _5tone_first_digit_ext_length;
4472
  u8 unknown1;
4473
  u8 unknown2;
4474
  u8 unknown3;
4475
  u8 unknown4;
4476
  u8 decode_standard;
4477
  u8 unknown5:5,
4478
     _5tone_decode_call_frame3:1,
4479
     _5tone_decode_call_frame2:1,
4480
     _5tone_decode_call_frame1:1;
4481
  u8 unknown6:5,
4482
     _5tone_decode_disp_frame3:1,
4483
     _5tone_decode_disp_frame2:1,
4484
     _5tone_decode_disp_frame1:1;
4485
  u8 decode_reset_time; // * 100 + 100ms
4486
} _5tone_settings;
4487

    
4488
#seekto 0x2900;
4489
struct {
4490
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
4491
} dtmf_codes[15];
4492

    
4493
#seekto 0x29F0;
4494
struct {
4495
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
4496
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
4497
  u8 unknown0[14];
4498
  u8 inspection[16];
4499
  u8 monitor[16];
4500
  u8 alarmcode[16];
4501
  u8 stun[16];
4502
  u8 kill[16];
4503
  u8 revive[16];
4504
  u8 unknown1[16];
4505
  u8 unknown2[16];
4506
  u8 unknown3[16];
4507
  u8 unknown4[16];
4508
  u8 unknown5[16];
4509
  u8 unknown6[16];
4510
  u8 unknown7[16];
4511
  u8 masterid[16];
4512
  u8 viceid[16];
4513
  u8 unused01:7,
4514
     mastervice:1;
4515
  u8 unused02:3,
4516
     mrevive:1,
4517
     mkill:1,
4518
     mstun:1,
4519
     mmonitor:1,
4520
     minspection:1;
4521
  u8 unused03:3,
4522
     vrevive:1,
4523
     vkill:1,
4524
     vstun:1,
4525
     vmonitor:1,
4526
     vinspection:1;
4527
  u8 unused04:6,
4528
     txdisable:1,
4529
     rxdisable:1;
4530
  u8 groupcode;
4531
  u8 spacecode;
4532
  u8 delayproctime; // * 100 + 100ms
4533
  u8 resettime;     // * 100 + 100ms
4534
} dtmf_settings;
4535

    
4536
#seekto 0x2D00;
4537
struct {
4538
  struct {
4539
    ul16 freq1;
4540
    u8 unused01[6];
4541
    ul16 freq2;
4542
    u8 unused02[6];
4543
  } _2tone_encode[15];
4544
  u8 duration_1st_tone; // *10ms
4545
  u8 duration_2nd_tone; // *10ms
4546
  u8 duration_gap;      // *10ms
4547
  u8 unused03[13];
4548
  struct {
4549
    struct {
4550
      u8 dec;      // one out of LIST_2TONE_DEC
4551
      u8 response; // one out of LIST_2TONE_RESPONSE
4552
      u8 alert;    // 1-16
4553
    } decs[4];
4554
    u8 unused04[4];
4555
  } _2tone_decode[15];
4556
  u8 unused05[16];
4557

    
4558
  struct {
4559
    ul16 freqA;
4560
    ul16 freqB;
4561
    ul16 freqC;
4562
    ul16 freqD;
4563
    // unknown what those values mean, but they are
4564
    // derived from configured frequencies
4565
    ul16 derived_from_freqA; // 2304000/freqA
4566
    ul16 derived_from_freqB; // 2304000/freqB
4567
    ul16 derived_from_freqC; // 2304000/freqC
4568
    ul16 derived_from_freqD; // 2304000/freqD
4569
  }freqs[15];
4570
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
4571
} _2tone;
4572

    
4573
#seekto 0x3D80;
4574
struct {
4575
  u8 vhf_low[3];
4576
  u8 vhf_high[3];
4577
  u8 unknown1[4];
4578
  u8 unknown2[6];
4579
  u8 vhf2_low[3];
4580
  u8 vhf2_high[3];
4581
  u8 unknown3[4];
4582
  u8 unknown4[6];
4583
  u8 uhf_low[3];
4584
  u8 uhf_high[3];
4585
  u8 unknown5[4];
4586
  u8 unknown6[6];
4587
  u8 uhf2_low[3];
4588
  u8 uhf2_high[3];
4589
} ranges;
4590

    
4591
#seekto 0x3F70;
4592
struct {
4593
  char fp[6];
4594
} fingerprint;
4595

    
4596
"""
4597

    
4598

    
4599
class QYTColorHT(BTechMobileCommon):
4600
    """QTY's Color LCD Handheld and alike radios"""
4601
    COLOR_LCD = True
4602
    COLOR_LCD3 = True
4603
    NAME_LENGTH = 8
4604
    LIST_TMR = LIST_TMR15
4605

    
4606
    def process_mmap(self):
4607
        """Process the mem map into the mem object"""
4608

    
4609
        # Get it
4610
        self._memobj = bitwise.parse(COLORHT_MEM_FORMAT, self._mmap)
4611

    
4612
        # load specific parameters from the radio image
4613
        self.set_options()
4614

    
4615
    def set_options(self):
4616
        """This is to read the options from the image and set it in the
4617
        environment, for now just the limits of the freqs in the VHF/UHF
4618
        ranges"""
4619

    
4620
        # setting the correct ranges for each radio type
4621
        ranges = self._memobj.ranges
4622

    
4623
        # the normal dual bands
4624
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
4625
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
4626

    
4627
        # DEBUG
4628
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
4629
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
4630

    
4631
        # the additional bands
4632
        if self.MODEL in ["KT-8R"]:
4633
            # 200Mhz band
4634
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
4635
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
4636
            self._220_range = vhf2
4637

    
4638
            # 350Mhz band
4639
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
4640
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
4641
            self._350_range = uhf2
4642

    
4643
        # set the class with the real data
4644
        self._vhf_range = vhf
4645
        self._uhf_range = uhf
4646

    
4647

    
4648
# real radios
4649
@directory.register
4650
class KT8R(QYTColorHT):
4651
    """QYT KT8R"""
4652
    VENDOR = "QYT"
4653
    MODEL = "KT-8R"
4654
    BANDS = 4
4655
    LIST_TMR = LIST_TMR15
4656
    _vhf_range = (136000000, 175000000)
4657
    _220_range = (200000000, 261000000)
4658
    _uhf_range = (400000000, 481000000)
4659
    _350_range = (350000000, 391000000)
4660
    _magic = MSTRING_KT8R
4661
    _fileid = [KT8R_fp2, KT8R_fp1, KT8R_fp, ]
4662
    _power_levels = [chirp_common.PowerLevel("High", watts=5),
4663
                     chirp_common.PowerLevel("Low", watts=1)]
    (1-1/1)