Project

General

Profile

Bug #8513 » btech_with_mc5264.py

Jim Unroe, 12/02/2020 04:14 PM

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

    
18
import time
19
import struct
20
import logging
21

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

    
31
LOG = logging.getLogger(__name__)
32

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

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

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

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

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

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

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

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

    
147

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

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

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

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

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

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

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

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

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

    
198

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

    
202

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

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

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

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

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

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

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

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

    
257

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

    
279

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

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

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

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

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

    
306

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

    
310
    data = ""
311

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

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

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

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

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

    
332
    return data
333

    
334

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

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

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

    
360

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

    
368
    return frame
369

    
370

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

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

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

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

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

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

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

    
398

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

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

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

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

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

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

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

    
429
                return True
430

    
431
        return False
432

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

    
438

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

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

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

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

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

    
471
            break
472

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

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

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

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

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

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

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

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

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

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

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

    
537
    return True
538

    
539

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

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

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

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

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

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

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

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

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

    
575
        # aggregate the data
576
        data += d
577

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

    
583
    return data
584

    
585

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
646

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

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

    
654
    return False
655

    
656

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

    
665
    return (ilow, ihigh)
666

    
667

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

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

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

    
682

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

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

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

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

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

    
735
            """))
736
        return rp
737

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

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

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

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

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

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

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

    
790
        return rf
791

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

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

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

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

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

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

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

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

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

    
863
        # Memory number
864
        mem.number = number
865

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
951
        return mem
952

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1058
        return mem
1059

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2185
                i = i + 1
2186

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2476
        top.append(group_5tone)
2477

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2856
            i = i + 1
2857

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2973
            i = i + 1
2974

    
2975
        return top
2976

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

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

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

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

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

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

    
3031

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3315
"""
3316

    
3317

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

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

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

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

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

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

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

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

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

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

    
3365

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

    
3371

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

    
3376

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

    
3381

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

    
3386

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

    
3391

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

    
3402

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

    
3415

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

    
3428

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

    
3439

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

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

    
3455

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

    
3474

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

    
3492

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

    
3506

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3803
"""
3804

    
3805

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

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

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

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

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

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

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

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

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

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

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

    
3853

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

    
3859

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

    
3864

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

    
3876

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

    
3889

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

    
3902

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

    
3920

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

    
3933

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

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

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

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

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

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

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

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

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

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

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

    
4126

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

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

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

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

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

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

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

    
4233
"""
4234

    
4235

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

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

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

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

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

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

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

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

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

    
4272

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

    
4289

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4580
"""
4581

    
4582

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

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

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

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

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

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

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

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

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

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

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

    
4631

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