Project

General

Profile

Bug #8599 » btech_vc5264.py

Custom driver module for testing radios with MCU Version VC5264 - Jim Unroe, 12/28/2020 08:34 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
KT7900D_fp6 = "VC5264"
240

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

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

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

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

    
258

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

    
280

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

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

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

    
301
        # restore the default serial timeout
302
        radio.pipe.timeout = STIMEOUT
303

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

    
307

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

    
311
    data = ""
312

    
313
    try:
314
        data = radio.pipe.read(amount)
315

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

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

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

    
330
    except:
331
        raise errors.RadioError("Error reading data from radio")
332

    
333
    return data
334

    
335

    
336
def _send(radio, data):
337
    """Send data to the radio device"""
338

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

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

    
361

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

    
369
    return frame
370

    
371

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

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

    
378
    # get the whole block
379
    block = _rawrecv(radio, BLOCK_SIZE + 5)
380

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

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

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

    
396
    # return the data
397
    return block[5:]
398

    
399

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

    
403
    # cleaning the serial buffer
404
    _clean_buffer(radio)
405

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

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

    
418
            # send the magic word
419
            _send(radio, radio._magic)
420

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

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

    
430
                return True
431

    
432
        return False
433

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

    
439

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

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

    
455
    # Ok, get the ident string
456
    ident = _rawrecv(radio, 49)
457

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

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

    
472
            break
473

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

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

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

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

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

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

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

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

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

    
532
            # restore the default serial timeout
533
            radio.pipe.timeout = STIMEOUT
534

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

    
538
    return True
539

    
540

    
541
def _download(radio):
542
    """Get the memory map"""
543

    
544
    # UI progress
545
    status = chirp_common.Status()
546

    
547
    # put radio in program mode and identify it
548
    _do_ident(radio, status)
549

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

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

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

    
565
    # cleaning the serial buffer
566
    _clean_buffer(radio)
567

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

    
573
        # read
574
        d = _recv(radio, addr)
575

    
576
        # aggregate the data
577
        data += d
578

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

    
584
    return data
585

    
586

    
587
def _upload(radio):
588
    """Upload procedure"""
589

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

    
594
    # UI progress
595
    status = chirp_common.Status()
596

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

    
600
    # get the data to upload to radio
601
    data = radio.get_mmap()
602

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

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

    
613
    # cleaning the serial buffer
614
    _clean_buffer(radio)
615

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

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

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

    
629
        # send the frame
630
        _send(radio, frame)
631

    
632
        # receiving the response
633
        ack = _rawrecv(radio, 1)
634

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

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

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

    
647

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

    
652
    if rid in cls._fileid:
653
        return True
654

    
655
    return False
656

    
657

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

    
666
    return (ilow, ihigh)
667

    
668

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

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

    
680
    # if you get here is because the freq pairs are split
681
    return True
682

    
683

    
684
class BTechMobileCommon(chirp_common.CloneModeRadio,
685
                        chirp_common.ExperimentalRadio):
686
    """BTECH's UV-5001 and alike radios"""
687
    VENDOR = "BTECH"
688
    MODEL = ""
689
    IDENT = ""
690
    BANDS = 2
691
    COLOR_LCD = False
692
    COLOR_LCD2 = False
693
    COLOR_LCD3 = False
694
    NAME_LENGTH = 6
695
    UPLOAD_MEM_SIZE = 0X3100
696
    _power_levels = [chirp_common.PowerLevel("High", watts=25),
697
                     chirp_common.PowerLevel("Low", watts=10)]
698
    _vhf_range = (130000000, 180000000)
699
    _220_range = (200000000, 271000000)
700
    _uhf_range = (400000000, 521000000)
701
    _350_range = (350000000, 391000000)
702
    _upper = 199
703
    _magic = MSTRING
704
    _fileid = None
705
    _id2 = False
706
    btech3 = False
707

    
708
    @classmethod
709
    def get_prompts(cls):
710
        rp = chirp_common.RadioPrompts()
711
        rp.experimental = \
712
            ('This driver is experimental.\n'
713
             '\n'
714
             'Please keep a copy of your memories with the original software '
715
             'if you treasure them, this driver is new and may contain'
716
             ' bugs.\n'
717
             '\n'
718
             )
719
        rp.pre_download = _(dedent("""\
720
            Follow these instructions to download your info:
721

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

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

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

    
736
            """))
737
        return rp
738

    
739
    def get_features(self):
740
        """Get the radio's features"""
741

    
742
        # we will use the following var as global
743
        global POWER_LEVELS
744

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

    
776
        # power levels
777
        POWER_LEVELS = self._power_levels
778
        rf.valid_power_levels = POWER_LEVELS
779

    
780
        # normal dual bands
781
        rf.valid_bands = [self._vhf_range, self._uhf_range]
782

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

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

    
791
        return rf
792

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

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

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

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

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

    
829
            tone = DTCS[index]
830
            return 'DTCS', tone, pol
831

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

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

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

    
864
        # Memory number
865
        mem.number = number
866

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

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

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

    
898
        # power
899
        mem.power = POWER_LEVELS[int(_mem.power)]
900

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

    
904
        # skip
905
        mem.skip = SKIP_VALUES[_mem.add]
906

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

    
913
        # Extra
914
        mem.extra = RadioSettingGroup("extra", "Extra")
915

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

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

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

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

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

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

    
952
        return mem
953

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

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

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

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

    
981
        # frequency
982
        _mem.rxfreq = mem.freq / 10
983

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

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

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

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

    
1012
        # wide/narrow
1013
        _mem.wide = MODES.index(mem.mode)
1014

    
1015
        # scan add property
1016
        _mem.add = SKIP_VALUES.index(mem.skip)
1017

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

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

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

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

    
1059
        return mem
1060

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2186
                i = i + 1
2187

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2477
        top.append(group_5tone)
2478

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2690
        _5tone_delay1 = _mem._5tone_settings._5tone_delay1
2691
        if _5tone_delay1 == 255:
2692
            _5tone_delay1 = 20
2693

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

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

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

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

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

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

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

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

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

    
2770
        top.append(encode_2tone)
2771
        top.append(decode_2tone)
2772

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

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

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

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

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

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

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

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

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

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

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

    
2857
            i = i + 1
2858

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

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

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

    
2886
            obj[frqname].set_value(val)
2887
            obj[derivedname].set_value(derived_val)
2888

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

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

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

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

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

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

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

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

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

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

    
2974
            i = i + 1
2975

    
2976
        return top
2977

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

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

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

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

    
3024
        # testing the firmware model fingerprint
3025
        match_model = model_match(cls, filedata)
3026

    
3027
        if match_size and match_model:
3028
            return True
3029
        else:
3030
            return False
3031

    
3032

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3295
// the UV-2501+220 & KT8900R has different zones for storing ranges
3296

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

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

    
3316
"""
3317

    
3318

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

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

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

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

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

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

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

    
3357
    def process_mmap(self):
3358
        """Process the mem map into the mem object"""
3359

    
3360
        # Get it
3361
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
3362

    
3363
        # load specific parameters from the radio image
3364
        self.set_options()
3365

    
3366

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

    
3372

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

    
3377

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

    
3382

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

    
3387

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

    
3392

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

    
3403

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

    
3416

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

    
3429

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

    
3440

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

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

    
3456

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

    
3475

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

    
3493

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

    
3507

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3804
"""
3805

    
3806

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

    
3813
    def process_mmap(self):
3814
        """Process the mem map into the mem object"""
3815

    
3816
        # Get it
3817
        self._memobj = bitwise.parse(COLOR_MEM_FORMAT, self._mmap)
3818

    
3819
        # load specific parameters from the radio image
3820
        self.set_options()
3821

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

    
3827
        # setting the correct ranges for each radio type
3828
        ranges = self._memobj.ranges
3829

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

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

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

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

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

    
3854

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

    
3860

    
3861
class QB25(chirp_common.Alias):
3862
    VENDOR = "Radioddity"
3863
    MODEL = "QB25"
3864

    
3865

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

    
3877

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

    
3890

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

    
3903

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

    
3921

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

    
3934

    
3935
GMRS_MEM_FORMAT = """
3936
#seekto 0x0000;
3937
struct {
3938
  lbcd rxfreq[4];
3939
  lbcd txfreq[4];
3940
  ul16 rxtone;
3941
  ul16 txtone;
3942
  u8 unknown0:4,
3943
     scode:4;
3944
  u8 unknown1:2,
3945
     spmute:2,
3946
     unknown2:2,
3947
     optsig:2;
3948
  u8 unknown3:3,
3949
     scramble:1,
3950
     unknown4:2,
3951
     power:2;
3952
  u8 unknown5:1,
3953
     wide:1,
3954
     unknown6:2,
3955
     bcl:1,
3956
     add:1,
3957
     pttid:2;
3958
} memory[256];
3959

    
3960
#seekto 0x1000;
3961
struct {
3962
  char name[7];
3963
  u8 unknown1[9];
3964
} names[256];
3965

    
3966
#seekto 0x2400;
3967
struct {
3968
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3969
  u8 group_tone;
3970
  u8 repeat_tone;
3971
  u8 unused[13];
3972
} _5tone_std_settings[15];
3973

    
3974
#seekto 0x2500;
3975
struct {
3976
  u8 frame1[5];
3977
  u8 frame2[5];
3978
  u8 frame3[5];
3979
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3980
} _5tone_codes[15];
3981

    
3982
#seekto 0x25F0;
3983
struct {
3984
  u8 _5tone_delay1; // * 10ms
3985
  u8 _5tone_delay2; // * 10ms
3986
  u8 _5tone_delay3; // * 10ms
3987
  u8 _5tone_first_digit_ext_length;
3988
  u8 unknown1;
3989
  u8 unknown2;
3990
  u8 unknown3;
3991
  u8 unknown4;
3992
  u8 decode_standard;
3993
  u8 unknown5:5,
3994
     _5tone_decode_call_frame3:1,
3995
     _5tone_decode_call_frame2:1,
3996
     _5tone_decode_call_frame1:1;
3997
  u8 unknown6:5,
3998
     _5tone_decode_disp_frame3:1,
3999
     _5tone_decode_disp_frame2:1,
4000
     _5tone_decode_disp_frame1:1;
4001
  u8 decode_reset_time; // * 100 + 100ms
4002
} _5tone_settings;
4003

    
4004
#seekto 0x2900;
4005
struct {
4006
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
4007
} dtmf_codes[15];
4008

    
4009
#seekto 0x29F0;
4010
struct {
4011
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
4012
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
4013
  u8 unknown0[14];
4014
  u8 inspection[16];
4015
  u8 monitor[16];
4016
  u8 alarmcode[16];
4017
  u8 stun[16];
4018
  u8 kill[16];
4019
  u8 revive[16];
4020
  u8 unknown1[16];
4021
  u8 unknown2[16];
4022
  u8 unknown3[16];
4023
  u8 unknown4[16];
4024
  u8 unknown5[16];
4025
  u8 unknown6[16];
4026
  u8 unknown7[16];
4027
  u8 masterid[16];
4028
  u8 viceid[16];
4029
  u8 unused01:7,
4030
     mastervice:1;
4031
  u8 unused02:3,
4032
     mrevive:1,
4033
     mkill:1,
4034
     mstun:1,
4035
     mmonitor:1,
4036
     minspection:1;
4037
  u8 unused03:3,
4038
     vrevive:1,
4039
     vkill:1,
4040
     vstun:1,
4041
     vmonitor:1,
4042
     vinspection:1;
4043
  u8 unused04:6,
4044
     txdisable:1,
4045
     rxdisable:1;
4046
  u8 groupcode;
4047
  u8 spacecode;
4048
  u8 delayproctime; // * 100 + 100ms
4049
  u8 resettime;     // * 100 + 100ms
4050
} dtmf_settings;
4051

    
4052
#seekto 0x2D00;
4053
struct {
4054
  struct {
4055
    ul16 freq1;
4056
    u8 unused01[6];
4057
    ul16 freq2;
4058
    u8 unused02[6];
4059
  } _2tone_encode[15];
4060
  u8 duration_1st_tone; // *10ms
4061
  u8 duration_2nd_tone; // *10ms
4062
  u8 duration_gap;      // *10ms
4063
  u8 unused03[13];
4064
  struct {
4065
    struct {
4066
      u8 dec;      // one out of LIST_2TONE_DEC
4067
      u8 response; // one out of LIST_2TONE_RESPONSE
4068
      u8 alert;    // 1-16
4069
    } decs[4];
4070
    u8 unused04[4];
4071
  } _2tone_decode[15];
4072
  u8 unused05[16];
4073

    
4074
  struct {
4075
    ul16 freqA;
4076
    ul16 freqB;
4077
    ul16 freqC;
4078
    ul16 freqD;
4079
    // unknown what those values mean, but they are
4080
    // derived from configured frequencies
4081
    ul16 derived_from_freqA; // 2304000/freqA
4082
    ul16 derived_from_freqB; // 2304000/freqB
4083
    ul16 derived_from_freqC; // 2304000/freqC
4084
    ul16 derived_from_freqD; // 2304000/freqD
4085
  }freqs[15];
4086
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
4087
} _2tone;
4088

    
4089
#seekto 0x3000;
4090
struct {
4091
  u8 freq[8];
4092
  char broadcast_station_name[6];
4093
  u8 unknown[2];
4094
} fm_radio_preset[16];
4095

    
4096
#seekto 0x3200;
4097
struct {
4098
  u8 tmr;
4099
  u8 unknown1;
4100
  u8 sql;
4101
  u8 unknown2;
4102
  u8 autolk;
4103
  u8 tot;
4104
  u8 apo;
4105
  u8 unknown3;
4106
  u8 abr;
4107
  u8 beep;
4108
  u8 unknown4[4];
4109
  u8 dtmfst;
4110
  u8 unknown5[2];
4111
  u8 screv;
4112
  u8 unknown6[2];
4113
  u8 pttid;
4114
  u8 pttlt;
4115
  u8 unknown7;
4116
  u8 emctp;
4117
  u8 emcch;
4118
  u8 sigbp;
4119
  u8 unknown8;
4120
  u8 camdf;
4121
  u8 cbmdf;
4122
  u8 ccmdf;
4123
  u8 cdmdf;
4124
  u8 langua;
4125
  u8 sync;
4126

    
4127

    
4128
  u8 stfc;
4129
  u8 mffc;
4130
  u8 sfafc;
4131
  u8 sfbfc;
4132
  u8 sfcfc;
4133
  u8 sfdfc;
4134
  u8 subfc;
4135
  u8 fmfc;
4136
  u8 sigfc;
4137
  u8 modfc;
4138
  u8 menufc;
4139
  u8 txfc;
4140
  u8 txdisp;
4141
  u8 unknown9[5];
4142
  u8 anil;
4143
  u8 reps;
4144
  u8 repm;
4145
  u8 tmrmr;
4146
  u8 ste;
4147
  u8 rpste;
4148
  u8 rptdl;
4149
  u8 dtmfg;
4150
  u8 mgain;
4151
  u8 skiptx;
4152
  u8 scmode;
4153
} settings;
4154

    
4155
#seekto 0x3280;
4156
struct {
4157
  u8 unknown1;
4158
  u8 vfomr;
4159
  u8 keylock;
4160
  u8 unknown2;
4161
  u8 unknown3:4,
4162
     vfomren:1,
4163
     unknown4:1,
4164
     reseten:1,
4165
     menuen:1;
4166
  u8 unknown5[11];
4167
  u8 dispab;
4168
  u8 unknown6[2];
4169
  u8 smenu;
4170
  u8 unknown7[7];
4171
  u8 vfomra;
4172
  u8 vfomrb;
4173
  u8 vfomrc;
4174
  u8 vfomrd;
4175
  u8 mrcha;
4176
  u8 mrchb;
4177
  u8 mrchc;
4178
  u8 mrchd;
4179
} settings2;
4180

    
4181
struct settings_vfo {
4182
  u8 freq[8];
4183
  u8 offset[6];
4184
  u8 unknown2[2];
4185
  ul16 rxtone;
4186
  ul16 txtone;
4187
  u8 scode;
4188
  u8 spmute;
4189
  u8 optsig;
4190
  u8 scramble;
4191
  u8 wide;
4192
  u8 power;
4193
  u8 shiftd;
4194
  u8 step;
4195
  u8 unknown3[4];
4196
};
4197

    
4198
#seekto 0x3300;
4199
struct {
4200
  struct settings_vfo a;
4201
  struct settings_vfo b;
4202
  struct settings_vfo c;
4203
  struct settings_vfo d;
4204
} vfo;
4205

    
4206
#seekto 0x3D80;
4207
struct {
4208
  u8 vhf_low[3];
4209
  u8 vhf_high[3];
4210
  u8 unknown1[4];
4211
  u8 unknown2[6];
4212
  u8 vhf2_low[3];
4213
  u8 vhf2_high[3];
4214
  u8 unknown3[4];
4215
  u8 unknown4[6];
4216
  u8 uhf_low[3];
4217
  u8 uhf_high[3];
4218
  u8 unknown5[4];
4219
  u8 unknown6[6];
4220
  u8 uhf2_low[3];
4221
  u8 uhf2_high[3];
4222
} ranges;
4223

    
4224
#seekto 0x33B0;
4225
struct {
4226
  char line[16];
4227
} static_msg;
4228

    
4229
#seekto 0x3F70;
4230
struct {
4231
  char fp[6];
4232
} fingerprint;
4233

    
4234
"""
4235

    
4236

    
4237
class BTechGMRS(BTechMobileCommon):
4238
    """BTECH's GMRS Mobile"""
4239
    COLOR_LCD = True
4240
    COLOR_LCD2 = True
4241
    NAME_LENGTH = 7
4242
    UPLOAD_MEM_SIZE = 0X3400
4243

    
4244
    def process_mmap(self):
4245
        """Process the mem map into the mem object"""
4246

    
4247
        # Get it
4248
        self._memobj = bitwise.parse(GMRS_MEM_FORMAT, self._mmap)
4249

    
4250
        # load specific parameters from the radio image
4251
        self.set_options()
4252

    
4253
    def set_options(self):
4254
        """This is to read the options from the image and set it in the
4255
        environment, for now just the limits of the freqs in the VHF/UHF
4256
        ranges"""
4257

    
4258
        # setting the correct ranges for each radio type
4259
        ranges = self._memobj.ranges
4260

    
4261
        # the normal dual bands
4262
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
4263
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
4264

    
4265
        # DEBUG
4266
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
4267
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
4268

    
4269
        # set the class with the real data
4270
        self._vhf_range = vhf
4271
        self._uhf_range = uhf
4272

    
4273

    
4274
# real radios
4275
@directory.register
4276
class GMRS50X1(BTechGMRS):
4277
    """Baofeng Tech GMRS50X1"""
4278
    MODEL = "GMRS-50X1"
4279
    BANDS = 2
4280
    LIST_TMR = LIST_TMR16
4281
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
4282
                     chirp_common.PowerLevel("Mid", watts=10),
4283
                     chirp_common.PowerLevel("Low", watts=5)]
4284
    _vhf_range = (136000000, 175000000)
4285
    _uhf_range = (400000000, 521000000)
4286
    _upper = 255
4287
    _magic = MSTRING_GMRS50X1
4288
    _fileid = [GMRS50X1_fp1, GMRS50X1_fp, ]
4289

    
4290

    
4291
COLORHT_MEM_FORMAT = """
4292
#seekto 0x0000;
4293
struct {
4294
  lbcd rxfreq[4];
4295
  lbcd txfreq[4];
4296
  ul16 rxtone;
4297
  ul16 txtone;
4298
  u8 unknown0:4,
4299
     scode:4;
4300
  u8 unknown1:2,
4301
     spmute:2,
4302
     unknown2:2,
4303
     optsig:2;
4304
  u8 unknown3:3,
4305
     scramble:1,
4306
     unknown4:3,
4307
     power:1;
4308
  u8 unknown5:1,
4309
     wide:1,
4310
     unknown6:2,
4311
     bcl:1,
4312
     add:1,
4313
     pttid:2;
4314
} memory[200];
4315

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

    
4373
#seekto 0x0E80;
4374
struct {
4375
  u8 unknown1;
4376
  u8 vfomr;
4377
  u8 keylock;
4378
  u8 unknown2;
4379
  u8 unknown3:4,
4380
     vfomren:1,
4381
     unknown4:1,
4382
     reseten:1,
4383
     menuen:1;
4384
  u8 unknown5[11];
4385
  u8 dispab;
4386
  u8 unknown6[2];
4387
  u8 menu;
4388
  u8 unknown7[7];
4389
  u8 vfomra;
4390
  u8 vfomrb;
4391
  u8 vfomrc;
4392
  u8 vfomrd;
4393
  u8 mrcha;
4394
  u8 mrchb;
4395
  u8 mrchc;
4396
  u8 mrchd;
4397
} settings2;
4398

    
4399
struct settings_vfo {
4400
  u8 freq[8];
4401
  u8 offset[6];
4402
  u8 unknown2[2];
4403
  ul16 rxtone;
4404
  ul16 txtone;
4405
  u8 scode;
4406
  u8 spmute;
4407
  u8 optsig;
4408
  u8 scramble;
4409
  u8 wide;
4410
  u8 power;
4411
  u8 shiftd;
4412
  u8 step;
4413
  u8 unknown3[4];
4414
};
4415

    
4416
#seekto 0x0F00;
4417
struct {
4418
  struct settings_vfo a;
4419
  struct settings_vfo b;
4420
  struct settings_vfo c;
4421
  struct settings_vfo d;
4422
} vfo;
4423

    
4424
#seekto 0x0FE0;
4425
struct {
4426
  char line[16];
4427
} static_msg;
4428

    
4429
#seekto 0x1000;
4430
struct {
4431
  char name[8];
4432
  u8 unknown1[8];
4433
} names[200];
4434

    
4435
#seekto 0x2400;
4436
struct {
4437
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
4438
  u8 group_tone;
4439
  u8 repeat_tone;
4440
  u8 unused[13];
4441
} _5tone_std_settings[15];
4442

    
4443
#seekto 0x2500;
4444
struct {
4445
  u8 frame1[5];
4446
  u8 frame2[5];
4447
  u8 frame3[5];
4448
  u8 standard;   // one out of LIST_5TONE_STANDARDS
4449
} _5tone_codes[15];
4450

    
4451
#seekto 0x25F0;
4452
struct {
4453
  u8 _5tone_delay1; // * 10ms
4454
  u8 _5tone_delay2; // * 10ms
4455
  u8 _5tone_delay3; // * 10ms
4456
  u8 _5tone_first_digit_ext_length;
4457
  u8 unknown1;
4458
  u8 unknown2;
4459
  u8 unknown3;
4460
  u8 unknown4;
4461
  u8 decode_standard;
4462
  u8 unknown5:5,
4463
     _5tone_decode_call_frame3:1,
4464
     _5tone_decode_call_frame2:1,
4465
     _5tone_decode_call_frame1:1;
4466
  u8 unknown6:5,
4467
     _5tone_decode_disp_frame3:1,
4468
     _5tone_decode_disp_frame2:1,
4469
     _5tone_decode_disp_frame1:1;
4470
  u8 decode_reset_time; // * 100 + 100ms
4471
} _5tone_settings;
4472

    
4473
#seekto 0x2900;
4474
struct {
4475
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
4476
} dtmf_codes[15];
4477

    
4478
#seekto 0x29F0;
4479
struct {
4480
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
4481
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
4482
  u8 unknown0[14];
4483
  u8 inspection[16];
4484
  u8 monitor[16];
4485
  u8 alarmcode[16];
4486
  u8 stun[16];
4487
  u8 kill[16];
4488
  u8 revive[16];
4489
  u8 unknown1[16];
4490
  u8 unknown2[16];
4491
  u8 unknown3[16];
4492
  u8 unknown4[16];
4493
  u8 unknown5[16];
4494
  u8 unknown6[16];
4495
  u8 unknown7[16];
4496
  u8 masterid[16];
4497
  u8 viceid[16];
4498
  u8 unused01:7,
4499
     mastervice:1;
4500
  u8 unused02:3,
4501
     mrevive:1,
4502
     mkill:1,
4503
     mstun:1,
4504
     mmonitor:1,
4505
     minspection:1;
4506
  u8 unused03:3,
4507
     vrevive:1,
4508
     vkill:1,
4509
     vstun:1,
4510
     vmonitor:1,
4511
     vinspection:1;
4512
  u8 unused04:6,
4513
     txdisable:1,
4514
     rxdisable:1;
4515
  u8 groupcode;
4516
  u8 spacecode;
4517
  u8 delayproctime; // * 100 + 100ms
4518
  u8 resettime;     // * 100 + 100ms
4519
} dtmf_settings;
4520

    
4521
#seekto 0x2D00;
4522
struct {
4523
  struct {
4524
    ul16 freq1;
4525
    u8 unused01[6];
4526
    ul16 freq2;
4527
    u8 unused02[6];
4528
  } _2tone_encode[15];
4529
  u8 duration_1st_tone; // *10ms
4530
  u8 duration_2nd_tone; // *10ms
4531
  u8 duration_gap;      // *10ms
4532
  u8 unused03[13];
4533
  struct {
4534
    struct {
4535
      u8 dec;      // one out of LIST_2TONE_DEC
4536
      u8 response; // one out of LIST_2TONE_RESPONSE
4537
      u8 alert;    // 1-16
4538
    } decs[4];
4539
    u8 unused04[4];
4540
  } _2tone_decode[15];
4541
  u8 unused05[16];
4542

    
4543
  struct {
4544
    ul16 freqA;
4545
    ul16 freqB;
4546
    ul16 freqC;
4547
    ul16 freqD;
4548
    // unknown what those values mean, but they are
4549
    // derived from configured frequencies
4550
    ul16 derived_from_freqA; // 2304000/freqA
4551
    ul16 derived_from_freqB; // 2304000/freqB
4552
    ul16 derived_from_freqC; // 2304000/freqC
4553
    ul16 derived_from_freqD; // 2304000/freqD
4554
  }freqs[15];
4555
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
4556
} _2tone;
4557

    
4558
#seekto 0x3D80;
4559
struct {
4560
  u8 vhf_low[3];
4561
  u8 vhf_high[3];
4562
  u8 unknown1[4];
4563
  u8 unknown2[6];
4564
  u8 vhf2_low[3];
4565
  u8 vhf2_high[3];
4566
  u8 unknown3[4];
4567
  u8 unknown4[6];
4568
  u8 uhf_low[3];
4569
  u8 uhf_high[3];
4570
  u8 unknown5[4];
4571
  u8 unknown6[6];
4572
  u8 uhf2_low[3];
4573
  u8 uhf2_high[3];
4574
} ranges;
4575

    
4576
#seekto 0x3F70;
4577
struct {
4578
  char fp[6];
4579
} fingerprint;
4580

    
4581
"""
4582

    
4583

    
4584
class QYTColorHT(BTechMobileCommon):
4585
    """QTY's Color LCD Handheld and alike radios"""
4586
    COLOR_LCD = True
4587
    COLOR_LCD3 = True
4588
    NAME_LENGTH = 8
4589
    LIST_TMR = LIST_TMR15
4590

    
4591
    def process_mmap(self):
4592
        """Process the mem map into the mem object"""
4593

    
4594
        # Get it
4595
        self._memobj = bitwise.parse(COLORHT_MEM_FORMAT, self._mmap)
4596

    
4597
        # load specific parameters from the radio image
4598
        self.set_options()
4599

    
4600
    def set_options(self):
4601
        """This is to read the options from the image and set it in the
4602
        environment, for now just the limits of the freqs in the VHF/UHF
4603
        ranges"""
4604

    
4605
        # setting the correct ranges for each radio type
4606
        ranges = self._memobj.ranges
4607

    
4608
        # the normal dual bands
4609
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
4610
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
4611

    
4612
        # DEBUG
4613
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
4614
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
4615

    
4616
        # the additional bands
4617
        if self.MODEL in ["KT-8R"]:
4618
            # 200Mhz band
4619
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
4620
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
4621
            self._220_range = vhf2
4622

    
4623
            # 350Mhz band
4624
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
4625
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
4626
            self._350_range = uhf2
4627

    
4628
        # set the class with the real data
4629
        self._vhf_range = vhf
4630
        self._uhf_range = uhf
4631

    
4632

    
4633
# real radios
4634
@directory.register
4635
class KT8R(QYTColorHT):
4636
    """QYT KT8R"""
4637
    VENDOR = "QYT"
4638
    MODEL = "KT-8R"
4639
    BANDS = 4
4640
    LIST_TMR = LIST_TMR15
4641
    _vhf_range = (136000000, 175000000)
4642
    _220_range = (200000000, 261000000)
4643
    _uhf_range = (400000000, 481000000)
4644
    _350_range = (350000000, 391000000)
4645
    _magic = MSTRING_KT8R
4646
    _fileid = [KT8R_fp2, KT8R_fp1, KT8R_fp, ]
4647
    _power_levels = [chirp_common.PowerLevel("High", watts=5),
4648
                     chirp_common.PowerLevel("Low", watts=1)]
(2-2/2)