btech.py

Modified btech.py by R.Wilson - Roy Wilson, 10/23/2021 02:39 pm

Download (153.1 kB)

 
1
# Copyright 2016-2021:
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
KT8900_fp6 = "M2G424"
215
# this radio has an extra ID
216
KT8900_id = "303688"
217
# another extra ID in sep/2021
218
KT8900_id2 = "\x05\x58\x3d\xf0\x10"
219

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

    
235
# KT7900D (quad band)
236
KT7900D_fp = "VC4004"
237
KT7900D_fp1 = "VC4284"
238
KT7900D_fp2 = "VC4264"
239
KT7900D_fp3 = "VC4114"
240
KT7900D_fp4 = "VC4104"
241
KT7900D_fp5 = "VC4254"
242
KT7900D_fp6 = "VC5264"
243

    
244
# QB25 (quad band) - a clone of KT7900D
245
QB25_fp = "QB-25"
246

    
247
# KT8900D (dual band)
248
KT8900D_fp = "VC2002"
249
KT8900D_fp1 = "VC8632"
250
KT8900D_fp2 = "VC6042"
251
KT8900D_fp3 = "VC7062"
252

    
253
# LUITON LT-588UV
254
LT588UV_fp = "V2G1F4"
255
# Added by rstrickoff gen 2 id
256
LT588UV_fp1 = "V2G214"
257

    
258
# QYT KT-8R (quad band ht)
259
KT8R_fp = "MCB264"
260
KT8R_fp1 = "MCB284"
261
KT8R_fp2 = "MC5264"
262

    
263
# QYT KT5800 (dual band)
264
KT5800_fp = "VCB222"
265

    
266

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

    
288

    
289
def _clean_buffer(radio):
290
    """Cleaning the read serial buffer, hard timeout to survive an infinite
291
    data stream"""
292

    
293
    # touching the serial timeout to optimize the flushing
294
    # restored at the end to the default value
295
    radio.pipe.timeout = 0.1
296
    dump = "1"
297
    datacount = 0
298

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

    
309
        # restore the default serial timeout
310
        radio.pipe.timeout = STIMEOUT
311

    
312
    except Exception:
313
        raise errors.RadioError("Unknown error cleaning the serial buffer")
314

    
315

    
316
def _rawrecv(radio, amount):
317
    """Raw read from the radio device, less intensive way"""
318

    
319
    data = ""
320

    
321
    try:
322
        data = radio.pipe.read(amount)
323

    
324
        # DEBUG
325
        if debug is True:
326
            LOG.debug("<== (%d) bytes:\n\n%s" %
327
                      (len(data), util.hexprint(data)))
328

    
329
        # fail if no data is received
330
        if len(data) == 0:
331
            raise errors.RadioError("No data received from radio")
332

    
333
        # notice on the logs if short
334
        if len(data) < amount:
335
            LOG.warn("Short reading %d bytes from the %d requested." %
336
                     (len(data), amount))
337

    
338
    except:
339
        raise errors.RadioError("Error reading data from radio")
340

    
341
    return data
342

    
343

    
344
def _send(radio, data):
345
    """Send data to the radio device"""
346

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

    
362
        # DEBUG
363
        if debug is True:
364
            LOG.debug("==> (%d) bytes:\n\n%s" %
365
                      (len(data), util.hexprint(data)))
366
    except:
367
        raise errors.RadioError("Error sending data to radio")
368

    
369

    
370
def _make_frame(cmd, addr, length, data=""):
371
    """Pack the info in the headder format"""
372
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
373
    # add the data if set
374
    if len(data) != 0:
375
        frame += data
376

    
377
    return frame
378

    
379

    
380
def _recv(radio, addr):
381
    """Get data from the radio all at once to lower syscalls load"""
382

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

    
386
    # get the whole block
387
    block = _rawrecv(radio, BLOCK_SIZE + 5)
388

    
389
    # basic check
390
    if len(block) < (BLOCK_SIZE + 5):
391
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
392

    
393
    # checking for the ack
394
    if block[0] != ACK_CMD:
395
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
396

    
397
    # header validation
398
    c, a, l = struct.unpack(">BHB", block[1:5])
399
    if a != addr or l != BLOCK_SIZE or c != ord("X"):
400
        LOG.debug("Invalid header for block 0x%04x" % addr)
401
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
402
        raise errors.RadioError("Invalid header for block 0x%04x:" % addr)
403

    
404
    # return the data
405
    return block[5:]
406

    
407

    
408
def _start_clone_mode(radio, status):
409
    """Put the radio in clone mode and get the ident string, 3 tries"""
410

    
411
    # cleaning the serial buffer
412
    _clean_buffer(radio)
413

    
414
    # prep the data to show in the UI
415
    status.cur = 0
416
    status.msg = "Identifying the radio..."
417
    status.max = 3
418
    radio.status_fn(status)
419

    
420
    try:
421
        for a in range(0, status.max):
422
            # Update the UI
423
            status.cur = a + 1
424
            radio.status_fn(status)
425

    
426
            # send the magic word
427
            _send(radio, radio._magic)
428

    
429
            # Now you get a x06 of ACK if all goes well
430
            ack = radio.pipe.read(1)
431

    
432
            if ack == "\x06":
433
                # DEBUG
434
                LOG.info("Magic ACK received")
435
                status.cur = status.max
436
                radio.status_fn(status)
437

    
438
                return True
439

    
440
        return False
441

    
442
    except errors.RadioError:
443
        raise
444
    except Exception, e:
445
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
446

    
447

    
448
def _do_ident(radio, status, upload=False):
449
    """Put the radio in PROGRAM mode & identify it"""
450
    #  set the serial discipline
451
    radio.pipe.baudrate = 9600
452
    radio.pipe.parity = "N"
453

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

    
463
    # Ok, get the ident string
464
    ident = _rawrecv(radio, 49)
465

    
466
    # basic check for the ident
467
    if len(ident) != 49:
468
        raise errors.RadioError("Radio send a short ident block.")
469

    
470
    # check if ident is OK
471
    itis = False
472
    for fp in radio._fileid:
473
        if fp in ident:
474
            # got it!
475
            itis = True
476
            # checking if we are dealing with a Gen 3 BTECH
477
            if radio.VENDOR == "BTECH" and fp in BTECH3:
478
                radio.btech3 = True
479

    
480
            break
481

    
482
    if itis is False:
483
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
484
        raise errors.RadioError("Radio identification failed.")
485

    
486
    # some radios needs a extra read and check for a code on it, this ones
487
    # has the check value in the _id2 var, others simply False
488
    if radio._id2 is not False:
489
        # lower the timeout here as this radios are reseting due to timeout
490
        radio.pipe.timeout = 0.05
491

    
492
        # query & receive the extra ID
493
        _send(radio, _make_frame("S", 0x3DF0, 16))
494
        id2 = _rawrecv(radio, 21)
495

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

    
503
        # ok, the correct string must be in the received data
504
        # the radio._id2 var will be always a list
505
        flag2 = False
506
        for _id2 in radio._id2:
507
            if _id2 in id2:
508
                flag2 = True
509

    
510
        if not flag2:
511
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
512
                      (radio.MODEL, util.hexprint(id2)))
513
            raise errors.RadioError("The extra ID is wrong, aborting.")
514

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

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

    
536
            # checking
537
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
538
                raise errors.RadioError("Radio didn't ACK the upload")
539

    
540
            # restore the default serial timeout
541
            radio.pipe.timeout = STIMEOUT
542

    
543
    # DEBUG
544
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
545

    
546
    return True
547

    
548

    
549
def _download(radio):
550
    """Get the memory map"""
551

    
552
    # UI progress
553
    status = chirp_common.Status()
554

    
555
    # put radio in program mode and identify it
556
    _do_ident(radio, status)
557

    
558
    # the models that doesn't have the extra ID have to make a dummy read here
559
    if radio._id2 is False:
560
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
561
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
562

    
563
        if debug is True:
564
            LOG.info("Dummy first block read done, got this:\n\n %s",
565
                     util.hexprint(discard))
566

    
567
    # reset the progress bar in the UI
568
    status.max = MEM_SIZE / BLOCK_SIZE
569
    status.msg = "Cloning from radio..."
570
    status.cur = 0
571
    radio.status_fn(status)
572

    
573
    # cleaning the serial buffer
574
    _clean_buffer(radio)
575

    
576
    data = ""
577
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
578
        # sending the read request
579
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
580

    
581
        # read
582
        d = _recv(radio, addr)
583

    
584
        # aggregate the data
585
        data += d
586

    
587
        # UI Update
588
        status.cur = addr / BLOCK_SIZE
589
        status.msg = "Cloning from radio..."
590
        radio.status_fn(status)
591

    
592
    return data
593

    
594

    
595
def _upload(radio):
596
    """Upload procedure"""
597

    
598
    # The UPLOAD mem is restricted to lower than 0x3100,
599
    # so we will overide that here localy
600
    MEM_SIZE = radio.UPLOAD_MEM_SIZE
601

    
602
    # UI progress
603
    status = chirp_common.Status()
604

    
605
    # put radio in program mode and identify it
606
    _do_ident(radio, status, True)
607

    
608
    # get the data to upload to radio
609
    data = radio.get_mmap()
610

    
611
    # Reset the UI progress
612
    status.max = MEM_SIZE / TX_BLOCK_SIZE
613
    status.cur = 0
614
    status.msg = "Cloning to radio..."
615
    radio.status_fn(status)
616

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

    
621
    # cleaning the serial buffer
622
    _clean_buffer(radio)
623

    
624
    # the fun start here
625
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
626
        # getting the block of data to send
627
        d = data[addr:addr + TX_BLOCK_SIZE]
628

    
629
        # build the frame to send
630
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
631

    
632
        # first block must not send the ACK at the beginning for the
633
        # ones that has the extra id, since this have to do a extra step
634
        if addr == 0 and radio._id2 is not False:
635
            frame = frame[1:]
636

    
637
        # send the frame
638
        _send(radio, frame)
639

    
640
        # receiving the response
641
        ack = _rawrecv(radio, 1)
642

    
643
        # basic check
644
        if len(ack) != 1:
645
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
646

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

    
650
        # UI Update
651
        status.cur = addr / TX_BLOCK_SIZE
652
        status.msg = "Cloning to radio..."
653
        radio.status_fn(status)
654

    
655

    
656
def model_match(cls, data):
657
    """Match the opened/downloaded image to the correct version"""
658
    rid = data[0x3f70:0x3f76]
659

    
660
    if rid in cls._fileid:
661
        return True
662

    
663
    return False
664

    
665

    
666
def _decode_ranges(low, high):
667
    """Unpack the data in the ranges zones in the memmap and return
668
    a tuple with the integer corresponding to the Mhz it means"""
669
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
670
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
671
    ilow *= 1000000
672
    ihigh *= 1000000
673

    
674
    return (ilow, ihigh)
675

    
676

    
677
def _split(rf, f1, f2):
678
    """Returns False if the two freqs are in the same band (no split)
679
    or True otherwise"""
680

    
681
    # determine if the two freqs are in the same band
682
    for low, high in rf.valid_bands:
683
        if f1 >= low and f1 <= high and \
684
                f2 >= low and f2 <= high:
685
            # if the two freqs are on the same Band this is not a split
686
            return False
687

    
688
    # if you get here is because the freq pairs are split
689
    return True
690

    
691

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

    
716
    @classmethod
717
    def get_prompts(cls):
718
        rp = chirp_common.RadioPrompts()
719
        rp.experimental = \
720
            ('This driver is experimental.\n'
721
             '\n'
722
             'Please keep a copy of your memories with the original software '
723
             'if you treasure them, this driver is new and may contain'
724
             ' bugs.\n'
725
             '\n'
726
             )
727
        rp.pre_download = _(dedent("""\
728
            Follow these instructions to download 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 download of your radio data
734

    
735
            """))
736
        rp.pre_upload = _(dedent("""\
737
            Follow these instructions to upload your info:
738

    
739
            1 - Turn off your radio
740
            2 - Connect your interface cable
741
            3 - Turn on your radio
742
            4 - Do the upload of your radio data
743

    
744
            """))
745
        return rp
746

    
747
    def get_features(self):
748
        """Get the radio's features"""
749

    
750
        # we will use the following var as global
751
        global POWER_LEVELS
752

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

    
784
        # power levels
785
        POWER_LEVELS = self._power_levels
786
        rf.valid_power_levels = POWER_LEVELS
787

    
788
        # normal dual bands
789
        rf.valid_bands = [self._vhf_range, self._uhf_range]
790

    
791
        # 220 band
792
        if self.BANDS == 3 or self.BANDS == 4:
793
            rf.valid_bands.append(self._220_range)
794

    
795
        # 350 band
796
        if self.BANDS == 4:
797
            rf.valid_bands.append(self._350_range)
798

    
799
        return rf
800

    
801
    def sync_in(self):
802
        """Download from radio"""
803
        data = _download(self)
804
        self._mmap = memmap.MemoryMap(data)
805
        self.process_mmap()
806

    
807
    def sync_out(self):
808
        """Upload to radio"""
809
        try:
810
            _upload(self)
811
        except errors.RadioError:
812
            raise
813
        except Exception, e:
814
            raise errors.RadioError("Error: %s" % e)
815

    
816
    def get_raw_memory(self, number):
817
        return repr(self._memobj.memory[number])
818

    
819
    def _decode_tone(self, val):
820
        """Parse the tone data to decode from mem, it returns:
821
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
822
        pol = None
823

    
824
        if val in [0, 65535]:
825
            return '', None, None
826
        elif val > 0x0258:
827
            a = val / 10.0
828
            return 'Tone', a, pol
829
        else:
830
            if val > 0x69:
831
                index = val - 0x6A
832
                pol = "R"
833
            else:
834
                index = val - 1
835
                pol = "N"
836

    
837
            tone = DTCS[index]
838
            return 'DTCS', tone, pol
839

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

    
864
    def get_memory(self, number):
865
        """Get the mem representation from the radio image"""
866
        _mem = self._memobj.memory[number]
867
        _names = self._memobj.names[number]
868

    
869
        # Create a high-level memory object to return to the UI
870
        mem = chirp_common.Memory()
871

    
872
        # Memory number
873
        mem.number = number
874

    
875
        if _mem.get_raw()[0] == "\xFF":
876
            mem.empty = True
877
            return mem
878

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

    
903
        # name TAG of the channel
904
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
905

    
906
        # power
907
        mem.power = POWER_LEVELS[int(_mem.power)]
908

    
909
        # wide/narrow
910
        mem.mode = MODES[int(_mem.wide)]
911

    
912
        # skip
913
        mem.skip = SKIP_VALUES[_mem.add]
914

    
915
        # tone data
916
        rxtone = txtone = None
917
        txtone = self._decode_tone(_mem.txtone)
918
        rxtone = self._decode_tone(_mem.rxtone)
919
        chirp_common.split_tone_decode(mem, txtone, rxtone)
920

    
921
        # Extra
922
        mem.extra = RadioSettingGroup("extra", "Extra")
923

    
924
        if not self.COLOR_LCD or \
925
                (self.COLOR_LCD and not self.VENDOR == "BTECH"):
926
            scramble = RadioSetting("scramble", "Scramble",
927
                                    RadioSettingValueBoolean(bool(
928
                                        _mem.scramble)))
929
            mem.extra.append(scramble)
930

    
931
        bcl = RadioSetting("bcl", "Busy channel lockout",
932
                           RadioSettingValueBoolean(bool(_mem.bcl)))
933
        mem.extra.append(bcl)
934

    
935
        pttid = RadioSetting("pttid", "PTT ID",
936
                             RadioSettingValueList(PTTID_LIST,
937
                                                   PTTID_LIST[_mem.pttid]))
938
        mem.extra.append(pttid)
939

    
940
        # validating scode
941
        scode = _mem.scode if _mem.scode != 15 else 0
942
        pttidcode = RadioSetting("scode", "PTT ID signal code",
943
                                 RadioSettingValueList(
944
                                     PTTIDCODE_LIST,
945
                                     PTTIDCODE_LIST[scode]))
946
        mem.extra.append(pttidcode)
947

    
948
        optsig = RadioSetting("optsig", "Optional signaling",
949
                              RadioSettingValueList(
950
                                  OPTSIG_LIST,
951
                                  OPTSIG_LIST[_mem.optsig]))
952
        mem.extra.append(optsig)
953

    
954
        spmute = RadioSetting("spmute", "Speaker mute",
955
                              RadioSettingValueList(
956
                                  SPMUTE_LIST,
957
                                  SPMUTE_LIST[_mem.spmute]))
958
        mem.extra.append(spmute)
959

    
960
        return mem
961

    
962
    def set_memory(self, mem):
963
        """Set the memory data in the eeprom img from the UI"""
964
        # get the eprom representation of this channel
965
        _mem = self._memobj.memory[mem.number]
966
        _names = self._memobj.names[mem.number]
967

    
968
        mem_was_empty = False
969
        # same method as used in get_memory for determining if mem is empty
970
        # doing this BEFORE overwriting it with new values ...
971
        if _mem.get_raw()[0] == "\xFF":
972
            LOG.debug("This mem was empty before")
973
            mem_was_empty = True
974

    
975
        # if empty memmory
976
        if mem.empty:
977
            # the channel itself
978
            _mem.set_raw("\xFF" * 16)
979
            # the name tag
980
            _names.set_raw("\xFF" * 16)
981
            return
982

    
983
        if mem_was_empty:
984
            # Zero the whole memory if we're making it unempty for
985
            # the first time
986
            LOG.debug('Zeroing new memory')
987
            _mem.set_raw('\x00' * 16)
988

    
989
        # frequency
990
        _mem.rxfreq = mem.freq / 10
991

    
992
        # duplex
993
        if mem.duplex == "+":
994
            _mem.txfreq = (mem.freq + mem.offset) / 10
995
        elif mem.duplex == "-":
996
            _mem.txfreq = (mem.freq - mem.offset) / 10
997
        elif mem.duplex == "off":
998
            for i in _mem.txfreq:
999
                i.set_raw("\xFF")
1000
        elif mem.duplex == "split":
1001
            _mem.txfreq = mem.offset / 10
1002
        else:
1003
            _mem.txfreq = mem.freq / 10
1004

    
1005
        # tone data
1006
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1007
            chirp_common.split_tone_encode(mem)
1008
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1009
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1010

    
1011
        # name TAG of the channel
1012
        if len(mem.name) < self.NAME_LENGTH:
1013
            # we must pad to self.NAME_LENGTH chars, " " = "\xFF"
1014
            mem.name = str(mem.name).ljust(self.NAME_LENGTH, " ")
1015
        _names.name = str(mem.name).replace(" ", "\xFF")
1016

    
1017
        # power, # default power level is high
1018
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1019

    
1020
        # wide/narrow
1021
        _mem.wide = MODES.index(mem.mode)
1022

    
1023
        # scan add property
1024
        _mem.add = SKIP_VALUES.index(mem.skip)
1025

    
1026
        # reseting unknowns, this have to be set by hand
1027
        _mem.unknown0 = 0
1028
        _mem.unknown1 = 0
1029
        _mem.unknown2 = 0
1030
        _mem.unknown3 = 0
1031
        _mem.unknown4 = 0
1032
        _mem.unknown5 = 0
1033
        _mem.unknown6 = 0
1034

    
1035
        def _zero_settings():
1036
            _mem.spmute = 0
1037
            _mem.optsig = 0
1038
            _mem.scramble = 0
1039
            _mem.bcl = 0
1040
            _mem.pttid = 0
1041
            _mem.scode = 0
1042

    
1043
        if self.COLOR_LCD and _mem.scramble:
1044
            LOG.info('Resetting scramble bit for BTECH COLOR_LCD variant')
1045
            _mem.scramble = 0
1046

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

    
1067
        return mem
1068

    
1069
    def get_settings(self):
1070
        """Translate the bit in the mem_struct into settings in the UI"""
1071
        _mem = self._memobj
1072
        basic = RadioSettingGroup("basic", "Basic Settings")
1073
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1074
        other = RadioSettingGroup("other", "Other Settings")
1075
        work = RadioSettingGroup("work", "Work Mode Settings")
1076
        top = RadioSettings(basic, advanced, other, work)
1077

    
1078
        # Basic
1079
        if self.COLOR_LCD:
1080
            tmr = RadioSetting("settings.tmr", "Transceiver multi-receive",
1081
                               RadioSettingValueList(
1082
                                   self.LIST_TMR,
1083
                                   self.LIST_TMR[_mem.settings.tmr]))
1084
            basic.append(tmr)
1085
        else:
1086
            tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1087
                               RadioSettingValueBoolean(_mem.settings.tdr))
1088
            basic.append(tdr)
1089

    
1090
        sql = RadioSetting("settings.sql", "Squelch level",
1091
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1092
        basic.append(sql)
1093

    
1094
        if self.MODEL == "GMRS-50X1":
1095
            autolk = RadioSetting("settings.autolk", "Auto keylock",
1096
                                  RadioSettingValueBoolean(
1097
                                      _mem.settings.autolk))
1098
            basic.append(autolk)
1099

    
1100
        tot = RadioSetting("settings.tot", "Time out timer",
1101
                           RadioSettingValueList(
1102
                               LIST_TOT,
1103
                               LIST_TOT[_mem.settings.tot]))
1104
        basic.append(tot)
1105

    
1106
        if self.MODEL == "KT-8R":
1107
                save = RadioSetting("settings.save", "Battery Save",
1108
                                    RadioSettingValueBoolean(
1109
                                        _mem.settings.save))
1110
                basic.append(save)
1111

    
1112
        if not self.MODEL == "KT-8R":
1113
            if self.VENDOR == "BTECH" or self.COLOR_LCD:
1114
                apo = RadioSetting("settings.apo", "Auto power off timer",
1115
                                   RadioSettingValueList(
1116
                                       LIST_APO,
1117
                                       LIST_APO[_mem.settings.apo]))
1118
                basic.append(apo)
1119
            else:
1120
                toa = RadioSetting("settings.apo", "Time out alert timer",
1121
                                   RadioSettingValueList(
1122
                                       LIST_OFF1TO10,
1123
                                       LIST_OFF1TO10[_mem.settings.apo]))
1124
                basic.append(toa)
1125

    
1126
        abr = RadioSetting("settings.abr", "Backlight timer",
1127
                           RadioSettingValueList(
1128
                               LIST_OFF1TO50,
1129
                               LIST_OFF1TO50[_mem.settings.abr]))
1130
        basic.append(abr)
1131

    
1132
        beep = RadioSetting("settings.beep", "Key beep",
1133
                            RadioSettingValueBoolean(_mem.settings.beep))
1134
        basic.append(beep)
1135

    
1136
        if self.MODEL == "KT-8R":
1137
                dsub = RadioSetting("settings.dsub", "CTCSS/DCS code display",
1138
                                    RadioSettingValueBoolean(
1139
                                        _mem.settings.dsub))
1140
                basic.append(dsub)
1141

    
1142
        if self.MODEL == "KT-8R":
1143
                dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1144
                                      RadioSettingValueBoolean(
1145
                                          _mem.settings.dtmfst))
1146
                basic.append(dtmfst)
1147
        else:
1148
            dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1149
                                  RadioSettingValueList(
1150
                                      LIST_DTMFST,
1151
                                      LIST_DTMFST[_mem.settings.dtmfst]))
1152
            basic.append(dtmfst)
1153

    
1154
        if not self.COLOR_LCD:
1155
            prisc = RadioSetting("settings.prisc", "Priority scan",
1156
                                 RadioSettingValueBoolean(
1157
                                     _mem.settings.prisc))
1158
            basic.append(prisc)
1159

    
1160
            prich = RadioSetting("settings.prich", "Priority channel",
1161
                                 RadioSettingValueInteger(0, self._upper,
1162
                                                          _mem.settings.prich))
1163
            basic.append(prich)
1164

    
1165
        screv = RadioSetting("settings.screv", "Scan resume method",
1166
                             RadioSettingValueList(
1167
                                 LIST_SCREV,
1168
                                 LIST_SCREV[_mem.settings.screv]))
1169
        basic.append(screv)
1170

    
1171
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1172
                             RadioSettingValueInteger(0, 30,
1173
                                                      _mem.settings.pttlt))
1174
        basic.append(pttlt)
1175

    
1176
        if self.VENDOR == "BTECH" and self.COLOR_LCD:
1177
            emctp = RadioSetting("settings.emctp", "Alarm mode",
1178
                                 RadioSettingValueList(
1179
                                     LIST_EMCTPX,
1180
                                     LIST_EMCTPX[_mem.settings.emctp]))
1181
            basic.append(emctp)
1182
        else:
1183
            emctp = RadioSetting("settings.emctp", "Alarm mode",
1184
                                 RadioSettingValueList(
1185
                                     LIST_EMCTP,
1186
                                     LIST_EMCTP[_mem.settings.emctp]))
1187
            basic.append(emctp)
1188

    
1189
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1190
                             RadioSettingValueInteger(0, self._upper,
1191
                                                      _mem.settings.emcch))
1192
        basic.append(emcch)
1193

    
1194
        if self.COLOR_LCD:
1195
            if _mem.settings.sigbp > 0x01:
1196
                val = 0x00
1197
            else:
1198
                val = _mem.settings.sigbp
1199
            sigbp = RadioSetting("settings.sigbp", "Signal beep",
1200
                                 RadioSettingValueBoolean(val))
1201
            basic.append(sigbp)
1202
        else:
1203
            ringt = RadioSetting("settings.ringt", "Ring time",
1204
                                 RadioSettingValueList(
1205
                                     LIST_OFF1TO9,
1206
                                     LIST_OFF1TO9[_mem.settings.ringt]))
1207
            basic.append(ringt)
1208

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

    
1215
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1216
                             RadioSettingValueList(
1217
                                 LIST_MDF,
1218
                                 LIST_MDF[_mem.settings.cbmdf]))
1219
        basic.append(cbmdf)
1220

    
1221
        if self.COLOR_LCD:
1222
            ccmdf = RadioSetting("settings.ccmdf", "Display mode C",
1223
                                 RadioSettingValueList(
1224
                                     LIST_MDF,
1225
                                     LIST_MDF[_mem.settings.ccmdf]))
1226
            basic.append(ccmdf)
1227

    
1228
            cdmdf = RadioSetting("settings.cdmdf", "Display mode D",
1229
                                 RadioSettingValueList(
1230
                                     LIST_MDF,
1231
                                     LIST_MDF[_mem.settings.cdmdf]))
1232
            basic.append(cdmdf)
1233

    
1234
            langua = RadioSetting("settings.langua", "Language",
1235
                                  RadioSettingValueList(
1236
                                      LIST_LANGUA,
1237
                                      LIST_LANGUA[_mem.settings.langua]))
1238
            basic.append(langua)
1239

    
1240
        if self.MODEL == "KT-8R":
1241
            voice = RadioSetting("settings.voice", "Voice prompt",
1242
                                 RadioSettingValueList(
1243
                                     LIST_VOICE,
1244
                                     LIST_VOICE[_mem.settings.voice]))
1245
            basic.append(voice)
1246

    
1247
            vox = RadioSetting("settings.vox", "VOX",
1248
                               RadioSettingValueList(
1249
                                   LIST_VOX,
1250
                                   LIST_VOX[_mem.settings.vox]))
1251
            basic.append(vox)
1252

    
1253
            voxt = RadioSetting("settings.voxt", "VOX delay time",
1254
                                RadioSettingValueList(
1255
                                    LIST_VOXT,
1256
                                    LIST_VOXT[_mem.settings.voxt]))
1257
            basic.append(voxt)
1258

    
1259
        if self.VENDOR == "BTECH":
1260
            if self.COLOR_LCD:
1261
                sync = RadioSetting("settings.sync", "Channel display sync",
1262
                                    RadioSettingValueList(
1263
                                        LIST_SYNC,
1264
                                        LIST_SYNC[_mem.settings.sync]))
1265
                basic.append(sync)
1266
            else:
1267
                sync = RadioSetting("settings.sync", "A/B channel sync",
1268
                                    RadioSettingValueBoolean(
1269
                                        _mem.settings.sync))
1270
                basic.append(sync)
1271
        else:
1272
            autolk = RadioSetting("settings.sync", "Auto keylock",
1273
                                  RadioSettingValueBoolean(
1274
                                      _mem.settings.sync))
1275
            basic.append(autolk)
1276

    
1277
        if not self.COLOR_LCD:
1278
            ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1279
                                  RadioSettingValueList(
1280
                                      LIST_PONMSG,
1281
                                      LIST_PONMSG[_mem.settings.ponmsg]))
1282
            basic.append(ponmsg)
1283

    
1284
        if self.COLOR_LCD and not (self.COLOR_LCD2 or self.COLOR_LCD3):
1285
            mainfc = RadioSetting("settings.mainfc",
1286
                                  "Main LCD foreground color",
1287
                                  RadioSettingValueList(
1288
                                      LIST_COLOR9,
1289
                                      LIST_COLOR9[_mem.settings.mainfc]))
1290
            basic.append(mainfc)
1291

    
1292
            mainbc = RadioSetting("settings.mainbc",
1293
                                  "Main LCD background color",
1294
                                  RadioSettingValueList(
1295
                                      LIST_COLOR9,
1296
                                      LIST_COLOR9[_mem.settings.mainbc]))
1297
            basic.append(mainbc)
1298

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

    
1305
            menubc = RadioSetting("settings.menubc", "Menu background color",
1306
                                  RadioSettingValueList(
1307
                                      LIST_COLOR9,
1308
                                      LIST_COLOR9[_mem.settings.menubc]))
1309
            basic.append(menubc)
1310

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

    
1318
            stabc = RadioSetting("settings.stabc",
1319
                                 "Top status background color",
1320
                                 RadioSettingValueList(
1321
                                     LIST_COLOR9,
1322
                                     LIST_COLOR9[_mem.settings.stabc]))
1323
            basic.append(stabc)
1324

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

    
1332
            sigbc = RadioSetting("settings.sigbc",
1333
                                 "Bottom status background color",
1334
                                 RadioSettingValueList(
1335
                                     LIST_COLOR9,
1336
                                     LIST_COLOR9[_mem.settings.sigbc]))
1337
            basic.append(sigbc)
1338

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

    
1345
            txfc = RadioSetting("settings.txfc",
1346
                                "Transmitting character color",
1347
                                RadioSettingValueList(
1348
                                    LIST_COLOR9,
1349
                                    LIST_COLOR9[_mem.settings.txfc]))
1350
            basic.append(txfc)
1351

    
1352
            txdisp = RadioSetting("settings.txdisp",
1353
                                  "Transmitting status display",
1354
                                  RadioSettingValueList(
1355
                                      LIST_TXDISP,
1356
                                      LIST_TXDISP[_mem.settings.txdisp]))
1357
            basic.append(txdisp)
1358
        elif self.COLOR_LCD2 or self.COLOR_LCD3:
1359
            stfc = RadioSetting("settings.stfc",
1360
                                "ST-FC",
1361
                                RadioSettingValueList(
1362
                                    LIST_COLOR8,
1363
                                    LIST_COLOR8[_mem.settings.stfc]))
1364
            basic.append(stfc)
1365

    
1366
            mffc = RadioSetting("settings.mffc",
1367
                                "MF-FC",
1368
                                RadioSettingValueList(
1369
                                    LIST_COLOR8,
1370
                                    LIST_COLOR8[_mem.settings.mffc]))
1371
            basic.append(mffc)
1372

    
1373
            sfafc = RadioSetting("settings.sfafc",
1374
                                 "SFA-FC",
1375
                                 RadioSettingValueList(
1376
                                     LIST_COLOR8,
1377
                                     LIST_COLOR8[_mem.settings.sfafc]))
1378
            basic.append(sfafc)
1379

    
1380
            sfbfc = RadioSetting("settings.sfbfc",
1381
                                 "SFB-FC",
1382
                                 RadioSettingValueList(
1383
                                     LIST_COLOR8,
1384
                                     LIST_COLOR8[_mem.settings.sfbfc]))
1385
            basic.append(sfbfc)
1386

    
1387
            sfcfc = RadioSetting("settings.sfcfc",
1388
                                 "SFC-FC",
1389
                                 RadioSettingValueList(
1390
                                     LIST_COLOR8,
1391
                                     LIST_COLOR8[_mem.settings.sfcfc]))
1392
            basic.append(sfcfc)
1393

    
1394
            sfdfc = RadioSetting("settings.sfdfc",
1395
                                 "SFD-FC",
1396
                                 RadioSettingValueList(
1397
                                     LIST_COLOR8,
1398
                                     LIST_COLOR8[_mem.settings.sfdfc]))
1399
            basic.append(sfdfc)
1400

    
1401
            subfc = RadioSetting("settings.subfc",
1402
                                 "SUB-FC",
1403
                                 RadioSettingValueList(
1404
                                     LIST_COLOR8,
1405
                                     LIST_COLOR8[_mem.settings.subfc]))
1406
            basic.append(subfc)
1407

    
1408
            fmfc = RadioSetting("settings.fmfc",
1409
                                "FM-FC",
1410
                                RadioSettingValueList(
1411
                                    LIST_COLOR8,
1412
                                    LIST_COLOR8[_mem.settings.fmfc]))
1413
            basic.append(fmfc)
1414

    
1415
            sigfc = RadioSetting("settings.sigfc",
1416
                                 "SIG-FC",
1417
                                 RadioSettingValueList(
1418
                                     LIST_COLOR8,
1419
                                     LIST_COLOR8[_mem.settings.sigfc]))
1420
            basic.append(sigfc)
1421

    
1422
            if not self.MODEL == "KT-8R":
1423
                modfc = RadioSetting("settings.modfc",
1424
                                     "MOD-FC",
1425
                                     RadioSettingValueList(
1426
                                         LIST_COLOR8,
1427
                                         LIST_COLOR8[_mem.settings.modfc]))
1428
                basic.append(modfc)
1429

    
1430
            menufc = RadioSetting("settings.menufc",
1431
                                  "MENUFC",
1432
                                  RadioSettingValueList(
1433
                                      LIST_COLOR8,
1434
                                      LIST_COLOR8[_mem.settings.menufc]))
1435
            basic.append(menufc)
1436

    
1437
            txfc = RadioSetting("settings.txfc",
1438
                                "TX-FC",
1439
                                RadioSettingValueList(
1440
                                    LIST_COLOR8,
1441
                                    LIST_COLOR8[_mem.settings.txfc]))
1442
            basic.append(txfc)
1443

    
1444
            if self.MODEL == "KT-8R":
1445
                rxfc = RadioSetting("settings.rxfc",
1446
                                    "RX-FC",
1447
                                    RadioSettingValueList(
1448
                                        LIST_COLOR8,
1449
                                        LIST_COLOR8[_mem.settings.rxfc]))
1450
                basic.append(rxfc)
1451

    
1452
            if not self.MODEL == "KT-8R":
1453
                txdisp = RadioSetting("settings.txdisp",
1454
                                      "Transmitting status display",
1455
                                      RadioSettingValueList(
1456
                                          LIST_TXDISP,
1457
                                          LIST_TXDISP[_mem.settings.txdisp]))
1458
                basic.append(txdisp)
1459
        else:
1460
            wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1461
                                 RadioSettingValueList(
1462
                                     LIST_COLOR4,
1463
                                     LIST_COLOR4[_mem.settings.wtled]))
1464
            basic.append(wtled)
1465

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

    
1472
            txled = RadioSetting("settings.txled", "TX backlight Color",
1473
                                 RadioSettingValueList(
1474
                                     LIST_COLOR4,
1475
                                     LIST_COLOR4[_mem.settings.txled]))
1476
            basic.append(txled)
1477

    
1478
        anil = RadioSetting("settings.anil", "ANI length",
1479
                            RadioSettingValueList(
1480
                                LIST_ANIL,
1481
                                LIST_ANIL[_mem.settings.anil]))
1482
        basic.append(anil)
1483

    
1484
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1485
                            RadioSettingValueList(
1486
                                LIST_REPS,
1487
                                LIST_REPS[_mem.settings.reps]))
1488
        basic.append(reps)
1489

    
1490
        if not self.MODEL == "GMRS-50X1" and not self.MODEL == "KT-8R":
1491
            repm = RadioSetting("settings.repm", "Relay condition",
1492
                                RadioSettingValueList(
1493
                                    LIST_REPM,
1494
                                    LIST_REPM[_mem.settings.repm]))
1495
            basic.append(repm)
1496

    
1497
        if self.VENDOR == "BTECH" or self.COLOR_LCD:
1498
            if self.COLOR_LCD:
1499
                tmrmr = RadioSetting("settings.tmrmr", "TMR return time",
1500
                                     RadioSettingValueList(
1501
                                         LIST_OFF1TO50,
1502
                                         LIST_OFF1TO50[_mem.settings.tmrmr]))
1503
                basic.append(tmrmr)
1504
            else:
1505
                tdrab = RadioSetting("settings.tdrab", "TDR return time",
1506
                                     RadioSettingValueList(
1507
                                         LIST_OFF1TO50,
1508
                                         LIST_OFF1TO50[_mem.settings.tdrab]))
1509
                basic.append(tdrab)
1510

    
1511
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1512
                               RadioSettingValueBoolean(_mem.settings.ste))
1513
            basic.append(ste)
1514

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

    
1521
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1522
                                 RadioSettingValueList(
1523
                                     LIST_RPTDL,
1524
                                     LIST_RPTDL[_mem.settings.rptdl]))
1525
            basic.append(rptdl)
1526

    
1527
        if str(_mem.fingerprint.fp) in BTECH3:
1528
            mgain = RadioSetting("settings.mgain", "Mic gain",
1529
                                 RadioSettingValueInteger(0, 120,
1530
                                                          _mem.settings.mgain))
1531
            basic.append(mgain)
1532

    
1533
        if str(_mem.fingerprint.fp) in BTECH3 or self.COLOR_LCD:
1534
            dtmfg = RadioSetting("settings.dtmfg", "DTMF gain",
1535
                                 RadioSettingValueInteger(0, 60,
1536
                                                          _mem.settings.dtmfg))
1537
            basic.append(dtmfg)
1538

    
1539
        if self.VENDOR == "BTECH" and self.COLOR_LCD:
1540
            mgain = RadioSetting("settings.mgain", "Mic gain",
1541
                                 RadioSettingValueInteger(0, 120,
1542
                                                          _mem.settings.mgain))
1543
            basic.append(mgain)
1544

    
1545
            skiptx = RadioSetting("settings.skiptx", "Skip TX",
1546
                                  RadioSettingValueList(
1547
                                      LIST_SKIPTX,
1548
                                      LIST_SKIPTX[_mem.settings.skiptx]))
1549
            basic.append(skiptx)
1550

    
1551
            scmode = RadioSetting("settings.scmode", "Scan mode",
1552
                                  RadioSettingValueList(
1553
                                      LIST_SCMODE,
1554
                                      LIST_SCMODE[_mem.settings.scmode]))
1555
            basic.append(scmode)
1556

    
1557
        if self.MODEL == "KT-8R":
1558
            tmrtx = RadioSetting("settings.tmrtx", "TX in multi-standby",
1559
                                 RadioSettingValueList(
1560
                                     LIST_TMRTX,
1561
                                     LIST_TMRTX[_mem.settings.tmrtx]))
1562
            basic.append(tmrtx)
1563

    
1564
        # Advanced
1565
        def _filter(name):
1566
            filtered = ""
1567
            for char in str(name):
1568
                if char in VALID_CHARS:
1569
                    filtered += char
1570
                else:
1571
                    filtered += " "
1572
            return filtered
1573

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

    
1634
        if self.MODEL in ("UV-2501", "UV-5001"):
1635
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1636
                                   RadioSettingValueBoolean(
1637
                                       _mem.settings2.vfomren))
1638
            advanced.append(vfomren)
1639

    
1640
            reseten = RadioSetting("settings2.reseten", "RESET",
1641
                                   RadioSettingValueBoolean(
1642
                                       _mem.settings2.reseten))
1643
            advanced.append(reseten)
1644

    
1645
            menuen = RadioSetting("settings2.menuen", "Menu",
1646
                                  RadioSettingValueBoolean(
1647
                                      _mem.settings2.menuen))
1648
            advanced.append(menuen)
1649

    
1650
        # Other
1651
        def convert_bytes_to_limit(bytes):
1652
            limit = ""
1653
            for byte in bytes:
1654
                if byte < 10:
1655
                    limit += chr(byte + 0x30)
1656
                else:
1657
                    break
1658
            return limit
1659

    
1660
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1661
            _ranges = self._memobj.ranges220
1662
            ranges = "ranges220"
1663
        else:
1664
            _ranges = self._memobj.ranges
1665
            ranges = "ranges"
1666

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

    
1673
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1674
        val = RadioSettingValueString(0, 3, _limit)
1675
        val.set_mutable(False)
1676
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1677
        other.append(vhf_high)
1678

    
1679
        if self.BANDS == 3 or self.BANDS == 4:
1680
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1681
            val = RadioSettingValueString(0, 3, _limit)
1682
            val.set_mutable(False)
1683
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1684
            other.append(vhf2_low)
1685

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

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

    
1698
        _limit = convert_bytes_to_limit(_ranges.uhf_high)
1699
        val = RadioSettingValueString(0, 3, _limit)
1700
        val.set_mutable(False)
1701
        uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
1702
        other.append(uhf_high)
1703

    
1704
        if self.BANDS == 4:
1705
            _limit = convert_bytes_to_limit(_ranges.uhf2_low)
1706
            val = RadioSettingValueString(0, 3, _limit)
1707
            val.set_mutable(False)
1708
            uhf2_low = RadioSetting("%s.uhf2_low" % ranges, "UHF2 low", val)
1709
            other.append(uhf2_low)
1710

    
1711
            _limit = convert_bytes_to_limit(_ranges.uhf2_high)
1712
            val = RadioSettingValueString(0, 3, _limit)
1713
            val.set_mutable(False)
1714
            uhf2_high = RadioSetting("%s.uhf2_high" % ranges, "UHF2 high", val)
1715
            other.append(uhf2_high)
1716

    
1717
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1718
        val.set_mutable(False)
1719
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1720
        other.append(fp)
1721

    
1722
        # Work
1723
        if self.COLOR_LCD:
1724
            dispab = RadioSetting("settings2.dispab", "Display",
1725
                                  RadioSettingValueList(
1726
                                      LIST_ABCD,
1727
                                      LIST_ABCD[_mem.settings2.dispab]))
1728
            work.append(dispab)
1729
        else:
1730
            dispab = RadioSetting("settings2.dispab", "Display",
1731
                                  RadioSettingValueList(
1732
                                      LIST_AB,
1733
                                      LIST_AB[_mem.settings2.dispab]))
1734
            work.append(dispab)
1735

    
1736
        if self.COLOR_LCD:
1737
            vfomra = RadioSetting("settings2.vfomra", "VFO/MR A mode",
1738
                                  RadioSettingValueList(
1739
                                      LIST_VFOMR,
1740
                                      LIST_VFOMR[_mem.settings2.vfomra]))
1741
            work.append(vfomra)
1742

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

    
1749
            vfomrc = RadioSetting("settings2.vfomrc", "VFO/MR C mode",
1750
                                  RadioSettingValueList(
1751
                                      LIST_VFOMR,
1752
                                      LIST_VFOMR[_mem.settings2.vfomrc]))
1753
            work.append(vfomrc)
1754

    
1755
            vfomrd = RadioSetting("settings2.vfomrd", "VFO/MR D mode",
1756
                                  RadioSettingValueList(
1757
                                      LIST_VFOMR,
1758
                                      LIST_VFOMR[_mem.settings2.vfomrd]))
1759
            work.append(vfomrd)
1760
        else:
1761
            vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1762
                                 RadioSettingValueList(
1763
                                     LIST_VFOMR,
1764
                                     LIST_VFOMR[_mem.settings2.vfomr]))
1765
            work.append(vfomr)
1766

    
1767
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1768
                               RadioSettingValueBoolean(
1769
                                   _mem.settings2.keylock))
1770
        work.append(keylock)
1771

    
1772
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1773
                             RadioSettingValueInteger(0, self._upper,
1774
                                                      _mem.settings2.mrcha))
1775
        work.append(mrcha)
1776

    
1777
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1778
                             RadioSettingValueInteger(0, self._upper,
1779
                                                      _mem.settings2.mrchb))
1780
        work.append(mrchb)
1781

    
1782
        if self.COLOR_LCD:
1783
            mrchc = RadioSetting("settings2.mrchc", "MR C channel",
1784
                                 RadioSettingValueInteger(
1785
                                     0, self._upper, _mem.settings2.mrchc))
1786
            work.append(mrchc)
1787

    
1788
            mrchd = RadioSetting("settings2.mrchd", "MR D channel",
1789
                                 RadioSettingValueInteger(
1790
                                     0, self._upper, _mem.settings2.mrchd))
1791
            work.append(mrchd)
1792

    
1793
        def convert_bytes_to_freq(bytes):
1794
            real_freq = 0
1795
            for byte in bytes:
1796
                real_freq = (real_freq * 10) + byte
1797
            return chirp_common.format_freq(real_freq * 10)
1798

    
1799
        def my_validate(value):
1800
            _vhf_lower = int(convert_bytes_to_limit(_ranges.vhf_low))
1801
            _vhf_upper = int(convert_bytes_to_limit(_ranges.vhf_high))
1802
            _uhf_lower = int(convert_bytes_to_limit(_ranges.uhf_low))
1803
            _uhf_upper = int(convert_bytes_to_limit(_ranges.uhf_high))
1804
            if self.BANDS == 3 or self.BANDS == 4:
1805
                _vhf2_lower = int(convert_bytes_to_limit(_ranges.vhf2_low))
1806
                _vhf2_upper = int(convert_bytes_to_limit(_ranges.vhf2_high))
1807
            if self.BANDS == 4:
1808
                _uhf2_lower = int(convert_bytes_to_limit(_ranges.uhf2_low))
1809
                _uhf2_upper = int(convert_bytes_to_limit(_ranges.uhf2_high))
1810

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

    
1842
        def apply_freq(setting, obj):
1843
            value = chirp_common.parse_freq(str(setting.value)) / 10
1844
            for i in range(7, -1, -1):
1845
                obj.freq[i] = value % 10
1846
                value /= 10
1847

    
1848
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1849
                                        _mem.vfo.a.freq))
1850
        val1a.set_validate_callback(my_validate)
1851
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1852
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1853
        work.append(vfoafreq)
1854

    
1855
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1856
                                        _mem.vfo.b.freq))
1857
        val1b.set_validate_callback(my_validate)
1858
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1859
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1860
        work.append(vfobfreq)
1861

    
1862
        if self.COLOR_LCD:
1863
            val1c = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1864
                                            _mem.vfo.c.freq))
1865
            val1c.set_validate_callback(my_validate)
1866
            vfocfreq = RadioSetting("vfo.c.freq", "VFO C frequency", val1c)
1867
            vfocfreq.set_apply_callback(apply_freq, _mem.vfo.c)
1868
            work.append(vfocfreq)
1869

    
1870
            val1d = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1871
                                            _mem.vfo.d.freq))
1872
            val1d.set_validate_callback(my_validate)
1873
            vfodfreq = RadioSetting("vfo.d.freq", "VFO D frequency", val1d)
1874
            vfodfreq.set_apply_callback(apply_freq, _mem.vfo.d)
1875
            work.append(vfodfreq)
1876

    
1877
        if not self.MODEL == "GMRS-50X1":
1878
            vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1879
                                      RadioSettingValueList(
1880
                                          LIST_SHIFT,
1881
                                          LIST_SHIFT[_mem.vfo.a.shiftd]))
1882
            work.append(vfoashiftd)
1883

    
1884
            vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1885
                                      RadioSettingValueList(
1886
                                          LIST_SHIFT,
1887
                                          LIST_SHIFT[_mem.vfo.b.shiftd]))
1888
            work.append(vfobshiftd)
1889

    
1890
            if self.COLOR_LCD:
1891
                vfocshiftd = RadioSetting("vfo.c.shiftd", "VFO C shift",
1892
                                          RadioSettingValueList(
1893
                                              LIST_SHIFT,
1894
                                              LIST_SHIFT[_mem.vfo.c.shiftd]))
1895
                work.append(vfocshiftd)
1896

    
1897
                vfodshiftd = RadioSetting("vfo.d.shiftd", "VFO D shift",
1898
                                          RadioSettingValueList(
1899
                                              LIST_SHIFT,
1900
                                              LIST_SHIFT[_mem.vfo.d.shiftd]))
1901
                work.append(vfodshiftd)
1902

    
1903
        def convert_bytes_to_offset(bytes):
1904
            real_offset = 0
1905
            for byte in bytes:
1906
                real_offset = (real_offset * 10) + byte
1907
            return chirp_common.format_freq(real_offset * 1000)
1908

    
1909
        def apply_offset(setting, obj):
1910
            value = chirp_common.parse_freq(str(setting.value)) / 1000
1911
            for i in range(5, -1, -1):
1912
                obj.offset[i] = value % 10
1913
                value /= 10
1914

    
1915
        if not self.MODEL == "GMRS-50X1":
1916
            if self.COLOR_LCD:
1917
                val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1918
                                                _mem.vfo.a.offset))
1919
                vfoaoffset = RadioSetting("vfo.a.offset",
1920
                                          "VFO A offset (0.000-999.999)",
1921
                                          val1a)
1922
                vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1923
                work.append(vfoaoffset)
1924

    
1925
                val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1926
                                                _mem.vfo.b.offset))
1927
                vfoboffset = RadioSetting("vfo.b.offset",
1928
                                          "VFO B offset (0.000-999.999)",
1929
                                          val1b)
1930
                vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1931
                work.append(vfoboffset)
1932

    
1933
                val1c = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1934
                                                _mem.vfo.c.offset))
1935
                vfocoffset = RadioSetting("vfo.c.offset",
1936
                                          "VFO C offset (0.000-999.999)",
1937
                                          val1c)
1938
                vfocoffset.set_apply_callback(apply_offset, _mem.vfo.c)
1939
                work.append(vfocoffset)
1940

    
1941
                val1d = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1942
                                                _mem.vfo.d.offset))
1943
                vfodoffset = RadioSetting("vfo.d.offset",
1944
                                          "VFO D offset (0.000-999.999)",
1945
                                          val1d)
1946
                vfodoffset.set_apply_callback(apply_offset, _mem.vfo.d)
1947
                work.append(vfodoffset)
1948
            else:
1949
                val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1950
                                                _mem.vfo.a.offset))
1951
                vfoaoffset = RadioSetting("vfo.a.offset",
1952
                                          "VFO A offset (0.000-99.999)", val1a)
1953
                vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1954
                work.append(vfoaoffset)
1955

    
1956
                val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1957
                                                _mem.vfo.b.offset))
1958
                vfoboffset = RadioSetting("vfo.b.offset",
1959
                                          "VFO B offset (0.000-99.999)", val1b)
1960
                vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1961
                work.append(vfoboffset)
1962

    
1963
        if not self.MODEL == "GMRS-50X1":
1964
            vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1965
                                   RadioSettingValueList(
1966
                                       LIST_TXP,
1967
                                       LIST_TXP[_mem.vfo.a.power]))
1968
            work.append(vfoatxp)
1969

    
1970
            vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1971
                                   RadioSettingValueList(
1972
                                       LIST_TXP,
1973
                                       LIST_TXP[_mem.vfo.b.power]))
1974
            work.append(vfobtxp)
1975

    
1976
            if self.COLOR_LCD:
1977
                vfoctxp = RadioSetting("vfo.c.power", "VFO C power",
1978
                                       RadioSettingValueList(
1979
                                           LIST_TXP,
1980
                                           LIST_TXP[_mem.vfo.c.power]))
1981
                work.append(vfoctxp)
1982

    
1983
                vfodtxp = RadioSetting("vfo.d.power", "VFO D power",
1984
                                       RadioSettingValueList(
1985
                                           LIST_TXP,
1986
                                           LIST_TXP[_mem.vfo.d.power]))
1987
                work.append(vfodtxp)
1988

    
1989
        if not self.MODEL == "GMRS-50X1":
1990
            vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1991
                                    RadioSettingValueList(
1992
                                        LIST_WIDE,
1993
                                        LIST_WIDE[_mem.vfo.a.wide]))
1994
            work.append(vfoawide)
1995

    
1996
            vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1997
                                    RadioSettingValueList(
1998
                                        LIST_WIDE,
1999
                                        LIST_WIDE[_mem.vfo.b.wide]))
2000
            work.append(vfobwide)
2001

    
2002
            if self.COLOR_LCD:
2003
                vfocwide = RadioSetting("vfo.c.wide", "VFO C bandwidth",
2004
                                        RadioSettingValueList(
2005
                                            LIST_WIDE,
2006
                                            LIST_WIDE[_mem.vfo.c.wide]))
2007
                work.append(vfocwide)
2008

    
2009
                vfodwide = RadioSetting("vfo.d.wide", "VFO D bandwidth",
2010
                                        RadioSettingValueList(
2011
                                            LIST_WIDE,
2012
                                            LIST_WIDE[_mem.vfo.d.wide]))
2013
                work.append(vfodwide)
2014

    
2015
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
2016
                                RadioSettingValueList(
2017
                                    LIST_STEP,
2018
                                    LIST_STEP[_mem.vfo.a.step]))
2019
        work.append(vfoastep)
2020

    
2021
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
2022
                                RadioSettingValueList(
2023
                                    LIST_STEP,
2024
                                    LIST_STEP[_mem.vfo.b.step]))
2025
        work.append(vfobstep)
2026

    
2027
        if self.COLOR_LCD:
2028
            vfocstep = RadioSetting("vfo.c.step", "VFO C step",
2029
                                    RadioSettingValueList(
2030
                                        LIST_STEP,
2031
                                        LIST_STEP[_mem.vfo.c.step]))
2032
            work.append(vfocstep)
2033

    
2034
            vfodstep = RadioSetting("vfo.d.step", "VFO D step",
2035
                                    RadioSettingValueList(
2036
                                        LIST_STEP,
2037
                                        LIST_STEP[_mem.vfo.d.step]))
2038
            work.append(vfodstep)
2039

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

    
2046
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
2047
                                  RadioSettingValueList(
2048
                                      OPTSIG_LIST,
2049
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
2050
        work.append(vfoboptsig)
2051

    
2052
        if self.COLOR_LCD:
2053
            vfocoptsig = RadioSetting("vfo.c.optsig", "VFO C optional signal",
2054
                                      RadioSettingValueList(
2055
                                          OPTSIG_LIST,
2056
                                          OPTSIG_LIST[_mem.vfo.c.optsig]))
2057
            work.append(vfocoptsig)
2058

    
2059
            vfodoptsig = RadioSetting("vfo.d.optsig", "VFO D optional signal",
2060
                                      RadioSettingValueList(
2061
                                          OPTSIG_LIST,
2062
                                          OPTSIG_LIST[_mem.vfo.d.optsig]))
2063
            work.append(vfodoptsig)
2064

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

    
2071
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
2072
                                  RadioSettingValueList(
2073
                                      SPMUTE_LIST,
2074
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
2075
        work.append(vfobspmute)
2076

    
2077
        if self.COLOR_LCD:
2078
            vfocspmute = RadioSetting("vfo.c.spmute", "VFO C speaker mute",
2079
                                      RadioSettingValueList(
2080
                                          SPMUTE_LIST,
2081
                                          SPMUTE_LIST[_mem.vfo.c.spmute]))
2082
            work.append(vfocspmute)
2083

    
2084
            vfodspmute = RadioSetting("vfo.d.spmute", "VFO D speaker mute",
2085
                                      RadioSettingValueList(
2086
                                          SPMUTE_LIST,
2087
                                          SPMUTE_LIST[_mem.vfo.d.spmute]))
2088
            work.append(vfodspmute)
2089

    
2090
        if not self.COLOR_LCD or \
2091
                (self.COLOR_LCD and not self.VENDOR == "BTECH"):
2092
            vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
2093
                                   RadioSettingValueBoolean(
2094
                                       _mem.vfo.a.scramble))
2095
            work.append(vfoascr)
2096

    
2097
            vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
2098
                                   RadioSettingValueBoolean(
2099
                                       _mem.vfo.b.scramble))
2100
            work.append(vfobscr)
2101

    
2102
        if self.COLOR_LCD and not self.VENDOR == "BTECH":
2103
            vfocscr = RadioSetting("vfo.c.scramble", "VFO C scramble",
2104
                                   RadioSettingValueBoolean(
2105
                                       _mem.vfo.c.scramble))
2106
            work.append(vfocscr)
2107

    
2108
            vfodscr = RadioSetting("vfo.d.scramble", "VFO D scramble",
2109
                                   RadioSettingValueBoolean(
2110
                                       _mem.vfo.d.scramble))
2111
            work.append(vfodscr)
2112

    
2113
        if not self.MODEL == "GMRS-50X1":
2114
            vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
2115
                                     RadioSettingValueList(
2116
                                         PTTIDCODE_LIST,
2117
                                         PTTIDCODE_LIST[_mem.vfo.a.scode]))
2118
            work.append(vfoascode)
2119

    
2120
            vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
2121
                                     RadioSettingValueList(
2122
                                         PTTIDCODE_LIST,
2123
                                         PTTIDCODE_LIST[_mem.vfo.b.scode]))
2124
            work.append(vfobscode)
2125

    
2126
            if self.COLOR_LCD:
2127
                vfocscode = RadioSetting("vfo.c.scode", "VFO C PTT-ID",
2128
                                         RadioSettingValueList(
2129
                                             PTTIDCODE_LIST,
2130
                                             PTTIDCODE_LIST[_mem.vfo.c.scode]))
2131
                work.append(vfocscode)
2132

    
2133
                vfodscode = RadioSetting("vfo.d.scode", "VFO D PTT-ID",
2134
                                         RadioSettingValueList(
2135
                                             PTTIDCODE_LIST,
2136
                                             PTTIDCODE_LIST[_mem.vfo.d.scode]))
2137
                work.append(vfodscode)
2138

    
2139
        if not self.MODEL == "GMRS-50X1":
2140
            pttid = RadioSetting("settings.pttid", "PTT ID",
2141
                                 RadioSettingValueList(
2142
                                     PTTID_LIST,
2143
                                     PTTID_LIST[_mem.settings.pttid]))
2144
            work.append(pttid)
2145

    
2146
        if not self.COLOR_LCD:
2147
            # FM presets
2148
            fm_presets = RadioSettingGroup("fm_presets", "FM Presets")
2149
            top.append(fm_presets)
2150

    
2151
            def fm_validate(value):
2152
                if value == 0:
2153
                    return chirp_common.format_freq(value)
2154
                if not (87.5 <= value and value <= 108.0):  # 87.5-108MHz
2155
                    msg = ("FM-Preset-Frequency: " +
2156
                           "Must be between 87.5 and 108 MHz")
2157
                    raise InvalidValueError(msg)
2158
                return value
2159

    
2160
            def apply_fm_preset_name(setting, obj):
2161
                valstring = str(setting.value)
2162
                for i in range(0, 6):
2163
                    if valstring[i] in VALID_CHARS:
2164
                        obj[i] = valstring[i]
2165
                    else:
2166
                        obj[i] = '0xff'
2167

    
2168
            def apply_fm_freq(setting, obj):
2169
                value = chirp_common.parse_freq(str(setting.value)) / 10
2170
                for i in range(7, -1, -1):
2171
                    obj.freq[i] = value % 10
2172
                    value /= 10
2173

    
2174
            _presets = self._memobj.fm_radio_preset
2175
            i = 1
2176
            for preset in _presets:
2177
                line = RadioSetting("fm_presets_" + str(i),
2178
                                    "Station name " + str(i),
2179
                                    RadioSettingValueString(0, 6, _filter(
2180
                                        preset.broadcast_station_name)))
2181
                line.set_apply_callback(apply_fm_preset_name,
2182
                                        preset.broadcast_station_name)
2183

    
2184
                val = RadioSettingValueFloat(0, 108,
2185
                                             convert_bytes_to_freq(
2186
                                                 preset.freq))
2187
                fmfreq = RadioSetting("fm_presets_" + str(i) + "_freq",
2188
                                      "Frequency " + str(i), val)
2189
                val.set_validate_callback(fm_validate)
2190
                fmfreq.set_apply_callback(apply_fm_freq, preset)
2191
                fm_presets.append(line)
2192
                fm_presets.append(fmfreq)
2193

    
2194
                i = i + 1
2195

    
2196
        # DTMF-Setting
2197
        dtmf_enc_settings = RadioSettingGroup("dtmf_enc_settings",
2198
                                              "DTMF Encoding Settings")
2199
        dtmf_dec_settings = RadioSettingGroup("dtmf_dec_settings",
2200
                                              "DTMF Decoding Settings")
2201
        top.append(dtmf_enc_settings)
2202
        top.append(dtmf_dec_settings)
2203
        txdisable = RadioSetting("dtmf_settings.txdisable",
2204
                                 "TX-Disable",
2205
                                 RadioSettingValueBoolean(
2206
                                     _mem.dtmf_settings.txdisable))
2207
        dtmf_enc_settings.append(txdisable)
2208

    
2209
        rxdisable = RadioSetting("dtmf_settings.rxdisable",
2210
                                 "RX-Disable",
2211
                                 RadioSettingValueBoolean(
2212
                                     _mem.dtmf_settings.rxdisable))
2213
        dtmf_enc_settings.append(rxdisable)
2214

    
2215
        if _mem.dtmf_settings.dtmfspeed_on > 0x0F:
2216
            val = 0x03
2217
        else:
2218
            val = _mem.dtmf_settings.dtmfspeed_on
2219
        dtmfspeed_on = RadioSetting(
2220
            "dtmf_settings.dtmfspeed_on",
2221
            "DTMF Speed (On Time)",
2222
            RadioSettingValueList(LIST_DTMF_SPEED,
2223
                                  LIST_DTMF_SPEED[
2224
                                      val]))
2225
        dtmf_enc_settings.append(dtmfspeed_on)
2226

    
2227
        if _mem.dtmf_settings.dtmfspeed_off > 0x0F:
2228
            val = 0x03
2229
        else:
2230
            val = _mem.dtmf_settings.dtmfspeed_off
2231
        dtmfspeed_off = RadioSetting(
2232
            "dtmf_settings.dtmfspeed_off",
2233
            "DTMF Speed (Off Time)",
2234
            RadioSettingValueList(LIST_DTMF_SPEED,
2235
                                  LIST_DTMF_SPEED[
2236
                                      val]))
2237
        dtmf_enc_settings.append(dtmfspeed_off)
2238

    
2239
        def memory2string(dmtf_mem):
2240
            dtmf_string = ""
2241
            for digit in dmtf_mem:
2242
                if digit != 255:
2243
                    index = LIST_DTMF_VALUES.index(digit)
2244
                    dtmf_string = dtmf_string + LIST_DTMF_DIGITS[index]
2245
            return dtmf_string
2246

    
2247
        def apply_dmtf_frame(setting, obj):
2248
            LOG.debug("Setting DTMF-Code: " + str(setting.value))
2249
            val_string = str(setting.value)
2250
            for i in range(0, 16):
2251
                obj[i] = 255
2252
            i = 0
2253
            for current_char in val_string:
2254
                current_char = current_char.upper()
2255
                index = LIST_DTMF_DIGITS.index(current_char)
2256
                obj[i] = LIST_DTMF_VALUES[index]
2257
                i = i + 1
2258

    
2259
        codes = self._memobj.dtmf_codes
2260
        i = 1
2261
        for dtmfcode in codes:
2262
            val = RadioSettingValueString(0, 16, memory2string(
2263
                                              dtmfcode.code),
2264
                                          False, CHARSET_DTMF_DIGITS)
2265
            line = RadioSetting("dtmf_code_" + str(i) + "_code",
2266
                                "DMTF Code " + str(i), val)
2267
            line.set_apply_callback(apply_dmtf_frame, dtmfcode.code)
2268
            dtmf_enc_settings.append(line)
2269
            i = i + 1
2270

    
2271
        line = RadioSetting("dtmf_settings.mastervice",
2272
                            "Master and Vice ID",
2273
                            RadioSettingValueBoolean(
2274
                                _mem.dtmf_settings.mastervice))
2275
        dtmf_dec_settings.append(line)
2276

    
2277
        val = RadioSettingValueString(0, 16, memory2string(
2278
                                          _mem.dtmf_settings.masterid),
2279
                                      False, CHARSET_DTMF_DIGITS)
2280
        line = RadioSetting("dtmf_settings.masterid",
2281
                            "Master Control ID ", val)
2282
        line.set_apply_callback(apply_dmtf_frame,
2283
                                _mem.dtmf_settings.masterid)
2284
        dtmf_dec_settings.append(line)
2285

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

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

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

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

    
2310
        line = RadioSetting("dtmf_settings.mrevive",
2311
                            "Master Revive",
2312
                            RadioSettingValueBoolean(
2313
                                _mem.dtmf_settings.mrevive))
2314
        dtmf_dec_settings.append(line)
2315

    
2316
        val = RadioSettingValueString(0, 16, memory2string(
2317
                                          _mem.dtmf_settings.viceid),
2318
                                      False, CHARSET_DTMF_DIGITS)
2319
        line = RadioSetting("dtmf_settings.viceid",
2320
                            "Vice Control ID ", val)
2321
        line.set_apply_callback(apply_dmtf_frame,
2322
                                _mem.dtmf_settings.viceid)
2323
        dtmf_dec_settings.append(line)
2324

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

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

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

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

    
2349
        line = RadioSetting("dtmf_settings.vrevive",
2350
                            "Vice Revive",
2351
                            RadioSettingValueBoolean(
2352
                                _mem.dtmf_settings.vrevive))
2353
        dtmf_dec_settings.append(line)
2354

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

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

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

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

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

    
2400
        val = RadioSettingValueString(0, 16, memory2string(
2401
                                          _mem.dtmf_settings.revive),
2402
                                      False, CHARSET_DTMF_DIGITS)
2403
        line = RadioSetting("dtmf_settings.revive",
2404
                            "Revive", val)
2405
        line.set_apply_callback(apply_dmtf_frame,
2406
                                _mem.dtmf_settings.revive)
2407
        dtmf_dec_settings.append(line)
2408

    
2409
        def apply_dmtf_listvalue(setting, obj):
2410
            LOG.debug("Setting value: " + str(setting.value) + " from list")
2411
            val = str(setting.value)
2412
            index = LIST_DTMF_SPECIAL_DIGITS.index(val)
2413
            val = LIST_DTMF_SPECIAL_VALUES[index]
2414
            obj.set_value(val)
2415

    
2416
        if _mem.dtmf_settings.groupcode not in LIST_DTMF_SPECIAL_VALUES:
2417
            val = 0x0B
2418
        else:
2419
            val = _mem.dtmf_settings.groupcode
2420
        idx = LIST_DTMF_SPECIAL_VALUES.index(val)
2421
        line = RadioSetting(
2422
            "dtmf_settings.groupcode",
2423
            "Group Code",
2424
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2425
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2426
        line.set_apply_callback(apply_dmtf_listvalue,
2427
                                _mem.dtmf_settings.groupcode)
2428
        dtmf_dec_settings.append(line)
2429

    
2430
        if _mem.dtmf_settings.spacecode not in LIST_DTMF_SPECIAL_VALUES:
2431
            val = 0x0C
2432
        else:
2433
            val = _mem.dtmf_settings.spacecode
2434
        idx = LIST_DTMF_SPECIAL_VALUES.index(val)
2435
        line = RadioSetting(
2436
            "dtmf_settings.spacecode",
2437
            "Space Code",
2438
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2439
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2440
        line.set_apply_callback(apply_dmtf_listvalue,
2441
                                _mem.dtmf_settings.spacecode)
2442
        dtmf_dec_settings.append(line)
2443

    
2444
        if self.COLOR_LCD:
2445
            if _mem.dtmf_settings.resettime > 0x63:
2446
                val = 0x4F
2447
            else:
2448
                val = _mem.dtmf_settings.resettime
2449
            line = RadioSetting(
2450
                "dtmf_settings.resettime",
2451
                "Reset time",
2452
                RadioSettingValueList(LIST_5TONE_RESET_COLOR,
2453
                                      LIST_5TONE_RESET_COLOR[
2454
                                          val]))
2455
            dtmf_dec_settings.append(line)
2456
        else:
2457
            line = RadioSetting(
2458
                "dtmf_settings.resettime",
2459
                "Reset time",
2460
                RadioSettingValueList(LIST_5TONE_RESET,
2461
                                      LIST_5TONE_RESET[
2462
                                          _mem.dtmf_settings.resettime]))
2463
            dtmf_dec_settings.append(line)
2464

    
2465
        if _mem.dtmf_settings.delayproctime > 0x27:
2466
            val = 0x04
2467
        else:
2468
            val = _mem.dtmf_settings.delayproctime
2469
        line = RadioSetting(
2470
            "dtmf_settings.delayproctime",
2471
            "Delay processing time",
2472
            RadioSettingValueList(LIST_DTMF_DELAY,
2473
                                  LIST_DTMF_DELAY[
2474
                                      val]))
2475
        dtmf_dec_settings.append(line)
2476

    
2477
        # 5 Tone Settings
2478
        stds_5tone = RadioSettingGroup("stds_5tone", "Standards")
2479
        codes_5tone = RadioSettingGroup("codes_5tone", "Codes")
2480

    
2481
        group_5tone = RadioSettingGroup("group_5tone", "5 Tone Settings")
2482
        group_5tone.append(stds_5tone)
2483
        group_5tone.append(codes_5tone)
2484

    
2485
        top.append(group_5tone)
2486

    
2487
        def apply_list_value(setting, obj):
2488
            options = setting.value.get_options()
2489
            obj.set_value(options.index(str(setting.value)))
2490

    
2491
        _5tone_standards = self._memobj._5tone_std_settings
2492
        i = 0
2493
        for standard in _5tone_standards:
2494
            std_5tone = RadioSettingGroup("std_5tone_" + str(i),
2495
                                          LIST_5TONE_STANDARDS[i])
2496
            stds_5tone.append(std_5tone)
2497

    
2498
            period = standard.period
2499
            if period == 255:
2500
                LOG.debug("Period for " + LIST_5TONE_STANDARDS[i] +
2501
                          " is not yet configured. Setting to 70ms.")
2502
                period = 5
2503

    
2504
            if period <= len(LIST_5TONE_STANDARD_PERIODS):
2505
                line = RadioSetting(
2506
                    "_5tone_std_settings_" + str(i) + "_period",
2507
                    "Period (ms)", RadioSettingValueList
2508
                    (LIST_5TONE_STANDARD_PERIODS,
2509
                     LIST_5TONE_STANDARD_PERIODS[period]))
2510
                line.set_apply_callback(apply_list_value, standard.period)
2511
                std_5tone.append(line)
2512
            else:
2513
                LOG.debug("Invalid value for 5tone period! Disabling.")
2514

    
2515
            group_tone = standard.group_tone
2516
            if group_tone == 255:
2517
                LOG.debug("Group-Tone for " + LIST_5TONE_STANDARDS[i] +
2518
                          " is not yet configured. Setting to A.")
2519
                group_tone = 10
2520

    
2521
            if group_tone <= len(LIST_5TONE_DIGITS):
2522
                line = RadioSetting(
2523
                    "_5tone_std_settings_" + str(i) + "_grouptone",
2524
                    "Group Tone",
2525
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2526
                                          LIST_5TONE_DIGITS[
2527
                                              group_tone]))
2528
                line.set_apply_callback(apply_list_value,
2529
                                        standard.group_tone)
2530
                std_5tone.append(line)
2531
            else:
2532
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2533

    
2534
            repeat_tone = standard.repeat_tone
2535
            if repeat_tone == 255:
2536
                LOG.debug("Repeat-Tone for " + LIST_5TONE_STANDARDS[i] +
2537
                          " is not yet configured. Setting to E.")
2538
                repeat_tone = 14
2539

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

    
2554
        def my_apply_5tonestdlist_value(setting, obj):
2555
            if LIST_5TONE_STANDARDS.index(str(setting.value)) == 15:
2556
                obj.set_value(0xFF)
2557
            else:
2558
                obj.set_value(LIST_5TONE_STANDARDS.
2559
                              index(str(setting.value)))
2560

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

    
2581
        def validate_5tone_frame(value):
2582
            if (len(str(value)) != 5) and (len(str(value)) != 0):
2583
                msg = ("5 Tone must have 5 digits or 0 digits")
2584
                raise InvalidValueError(msg)
2585
            for digit in str(value):
2586
                if digit.upper() not in LIST_5TONE_DIGITS:
2587
                    msg = (str(digit) + " is not a valid digit for 5tones")
2588
                    raise InvalidValueError(msg)
2589
            return value
2590

    
2591
        def frame2string(frame):
2592
            frameString = ""
2593
            for digit in frame:
2594
                if digit != 255:
2595
                    frameString = frameString + LIST_5TONE_DIGITS[digit]
2596
            return frameString
2597

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

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

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

    
2633
            val = RadioSettingValueString(0, 6,
2634
                                          frame2string(code.frame3), False)
2635
            line = RadioSetting("_5tone_code_" + str(i) + "_frame3",
2636
                                " Frame 3", val)
2637
            val.set_validate_callback(validate_5tone_frame)
2638
            line.set_apply_callback(apply_5tone_frame, code.frame3)
2639
            code_5tone.append(line)
2640
            i = i + 1
2641

    
2642
        _5_tone_decode1 = RadioSetting(
2643
            "_5tone_settings._5tone_decode_call_frame1",
2644
            "5 Tone decode call Frame 1",
2645
            RadioSettingValueBoolean(
2646
                _mem._5tone_settings._5tone_decode_call_frame1))
2647
        group_5tone.append(_5_tone_decode1)
2648

    
2649
        _5_tone_decode2 = RadioSetting(
2650
            "_5tone_settings._5tone_decode_call_frame2",
2651
            "5 Tone decode call Frame 2",
2652
            RadioSettingValueBoolean(
2653
                _mem._5tone_settings._5tone_decode_call_frame2))
2654
        group_5tone.append(_5_tone_decode2)
2655

    
2656
        _5_tone_decode3 = RadioSetting(
2657
            "_5tone_settings._5tone_decode_call_frame3",
2658
            "5 Tone decode call Frame 3",
2659
            RadioSettingValueBoolean(
2660
                _mem._5tone_settings._5tone_decode_call_frame3))
2661
        group_5tone.append(_5_tone_decode3)
2662

    
2663
        _5_tone_decode_disp1 = RadioSetting(
2664
            "_5tone_settings._5tone_decode_disp_frame1",
2665
            "5 Tone decode disp Frame 1",
2666
            RadioSettingValueBoolean(
2667
                _mem._5tone_settings._5tone_decode_disp_frame1))
2668
        group_5tone.append(_5_tone_decode_disp1)
2669

    
2670
        _5_tone_decode_disp2 = RadioSetting(
2671
            "_5tone_settings._5tone_decode_disp_frame2",
2672
            "5 Tone decode disp Frame 2",
2673
            RadioSettingValueBoolean(
2674
                _mem._5tone_settings._5tone_decode_disp_frame2))
2675
        group_5tone.append(_5_tone_decode_disp2)
2676

    
2677
        _5_tone_decode_disp3 = RadioSetting(
2678
            "_5tone_settings._5tone_decode_disp_frame3",
2679
            "5 Tone decode disp Frame 3",
2680
            RadioSettingValueBoolean(
2681
                _mem._5tone_settings._5tone_decode_disp_frame3))
2682
        group_5tone.append(_5_tone_decode_disp3)
2683

    
2684
        decode_standard = _mem._5tone_settings.decode_standard
2685
        if decode_standard == 255:
2686
            decode_standard = 0
2687
        if decode_standard <= len(LIST_5TONE_STANDARDS_without_none):
2688
            line = RadioSetting("_5tone_settings.decode_standard",
2689
                                "5 Tone-decode Standard",
2690
                                RadioSettingValueList(
2691
                                    LIST_5TONE_STANDARDS_without_none,
2692
                                    LIST_5TONE_STANDARDS_without_none[
2693
                                        decode_standard]))
2694
            group_5tone.append(line)
2695
        else:
2696
            LOG.debug("Invalid decode std...")
2697

    
2698
        _5tone_delay1 = _mem._5tone_settings._5tone_delay1
2699
        if _5tone_delay1 == 255:
2700
            _5tone_delay1 = 20
2701

    
2702
        if _5tone_delay1 <= len(LIST_5TONE_DELAY):
2703
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2704
                                         LIST_5TONE_DELAY[
2705
                                             _5tone_delay1])
2706
            line = RadioSetting("_5tone_settings._5tone_delay1",
2707
                                "5 Tone Delay Frame 1", list)
2708
            group_5tone.append(line)
2709
        else:
2710
            LOG.debug("Invalid value for 5tone delay (frame1) ! Disabling.")
2711

    
2712
        _5tone_delay2 = _mem._5tone_settings._5tone_delay2
2713
        if _5tone_delay2 == 255:
2714
            _5tone_delay2 = 20
2715
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2716

    
2717
        if _5tone_delay2 <= len(LIST_5TONE_DELAY):
2718
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2719
                                         LIST_5TONE_DELAY[
2720
                                             _5tone_delay2])
2721
            line = RadioSetting("_5tone_settings._5tone_delay2",
2722
                                "5 Tone Delay Frame 2", list)
2723
            group_5tone.append(line)
2724
        else:
2725
            LOG.debug("Invalid value for 5tone delay (frame2)! Disabling.")
2726

    
2727
        _5tone_delay3 = _mem._5tone_settings._5tone_delay3
2728
        if _5tone_delay3 == 255:
2729
            _5tone_delay3 = 20
2730
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2731

    
2732
        if _5tone_delay3 <= len(LIST_5TONE_DELAY):
2733
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2734
                                         LIST_5TONE_DELAY[
2735
                                             _5tone_delay3])
2736
            line = RadioSetting("_5tone_settings._5tone_delay3",
2737
                                "5 Tone Delay Frame 3", list)
2738
            group_5tone.append(line)
2739
        else:
2740
            LOG.debug("Invalid value for 5tone delay (frame3)! Disabling.")
2741

    
2742
        ext_length = _mem._5tone_settings._5tone_first_digit_ext_length
2743
        if ext_length == 255:
2744
            ext_length = 0
2745
            LOG.debug("1st Tone ext lenght unconfigured! Resetting to 0")
2746

    
2747
        if ext_length <= len(LIST_5TONE_DELAY):
2748
            list = RadioSettingValueList(
2749
                LIST_5TONE_DELAY,
2750
                LIST_5TONE_DELAY[
2751
                    ext_length])
2752
            line = RadioSetting(
2753
                "_5tone_settings._5tone_first_digit_ext_length",
2754
                "First digit extend length", list)
2755
            group_5tone.append(line)
2756
        else:
2757
            LOG.debug("Invalid value for 5tone ext length! Disabling.")
2758

    
2759
        decode_reset_time = _mem._5tone_settings.decode_reset_time
2760
        if decode_reset_time == 255:
2761
            decode_reset_time = 59
2762
            LOG.debug("Decode reset time unconfigured. resetting.")
2763
        if decode_reset_time <= len(LIST_5TONE_RESET):
2764
            list = RadioSettingValueList(
2765
                LIST_5TONE_RESET,
2766
                LIST_5TONE_RESET[
2767
                    decode_reset_time])
2768
            line = RadioSetting("_5tone_settings.decode_reset_time",
2769
                                "Decode reset time", list)
2770
            group_5tone.append(line)
2771
        else:
2772
            LOG.debug("Invalid value decode reset time! Disabling.")
2773

    
2774
        # 2 Tone
2775
        encode_2tone = RadioSettingGroup("encode_2tone", "2 Tone Encode")
2776
        decode_2tone = RadioSettingGroup("decode_2tone", "2 Code Decode")
2777

    
2778
        top.append(encode_2tone)
2779
        top.append(decode_2tone)
2780

    
2781
        duration_1st_tone = self._memobj._2tone.duration_1st_tone
2782
        if duration_1st_tone == 255:
2783
            LOG.debug("Duration of first 2 Tone digit is not yet " +
2784
                      "configured. Setting to 600ms")
2785
            duration_1st_tone = 60
2786

    
2787
        if duration_1st_tone <= len(LIST_5TONE_DELAY):
2788
            line = RadioSetting("_2tone.duration_1st_tone",
2789
                                "Duration 1st Tone",
2790
                                RadioSettingValueList(LIST_5TONE_DELAY,
2791
                                                      LIST_5TONE_DELAY[
2792
                                                          duration_1st_tone]))
2793
            encode_2tone.append(line)
2794

    
2795
        duration_2nd_tone = self._memobj._2tone.duration_2nd_tone
2796
        if duration_2nd_tone == 255:
2797
            LOG.debug("Duration of second 2 Tone digit is not yet " +
2798
                      "configured. Setting to 600ms")
2799
            duration_2nd_tone = 60
2800

    
2801
        if duration_2nd_tone <= len(LIST_5TONE_DELAY):
2802
            line = RadioSetting("_2tone.duration_2nd_tone",
2803
                                "Duration 2nd Tone",
2804
                                RadioSettingValueList(LIST_5TONE_DELAY,
2805
                                                      LIST_5TONE_DELAY[
2806
                                                          duration_2nd_tone]))
2807
            encode_2tone.append(line)
2808

    
2809
        duration_gap = self._memobj._2tone.duration_gap
2810
        if duration_gap == 255:
2811
            LOG.debug("Duration of gap is not yet " +
2812
                      "configured. Setting to 300ms")
2813
            duration_gap = 30
2814

    
2815
        if duration_gap <= len(LIST_5TONE_DELAY):
2816
            line = RadioSetting("_2tone.duration_gap", "Duration of gap",
2817
                                RadioSettingValueList(LIST_5TONE_DELAY,
2818
                                                      LIST_5TONE_DELAY[
2819
                                                          duration_gap]))
2820
            encode_2tone.append(line)
2821

    
2822
        def _2tone_validate(value):
2823
            if value == 0:
2824
                return 65535
2825
            if value == 65535:
2826
                return value
2827
            if not (300 <= value and value <= 3000):
2828
                msg = ("2 Tone Frequency: Must be between 300 and 3000 Hz")
2829
                raise InvalidValueError(msg)
2830
            return value
2831

    
2832
        def apply_2tone_freq(setting, obj):
2833
            val = int(setting.value)
2834
            if (val == 0) or (val == 65535):
2835
                obj.set_value(65535)
2836
            else:
2837
                obj.set_value(val)
2838

    
2839
        i = 1
2840
        for code in self._memobj._2tone._2tone_encode:
2841
            code_2tone = RadioSettingGroup("code_2tone_" + str(i),
2842
                                           "Encode Code " + str(i))
2843
            encode_2tone.append(code_2tone)
2844

    
2845
            tmp = code.freq1
2846
            if tmp == 65535:
2847
                tmp = 0
2848
            val1 = RadioSettingValueInteger(0, 65535, tmp)
2849
            freq1 = RadioSetting("2tone_code_" + str(i) + "_freq1",
2850
                                 "Frequency 1", val1)
2851
            val1.set_validate_callback(_2tone_validate)
2852
            freq1.set_apply_callback(apply_2tone_freq, code.freq1)
2853
            code_2tone.append(freq1)
2854

    
2855
            tmp = code.freq2
2856
            if tmp == 65535:
2857
                tmp = 0
2858
            val2 = RadioSettingValueInteger(0, 65535, tmp)
2859
            freq2 = RadioSetting("2tone_code_" + str(i) + "_freq2",
2860
                                 "Frequency 2", val2)
2861
            val2.set_validate_callback(_2tone_validate)
2862
            freq2.set_apply_callback(apply_2tone_freq, code.freq2)
2863
            code_2tone.append(freq2)
2864

    
2865
            i = i + 1
2866

    
2867
        decode_reset_time = _mem._2tone.reset_time
2868
        if decode_reset_time == 255:
2869
            decode_reset_time = 59
2870
            LOG.debug("Decode reset time unconfigured. resetting.")
2871
        if decode_reset_time <= len(LIST_5TONE_RESET):
2872
            list = RadioSettingValueList(
2873
                LIST_5TONE_RESET,
2874
                LIST_5TONE_RESET[
2875
                    decode_reset_time])
2876
            line = RadioSetting("_2tone.reset_time",
2877
                                "Decode reset time", list)
2878
            decode_2tone.append(line)
2879
        else:
2880
            LOG.debug("Invalid value decode reset time! Disabling.")
2881

    
2882
        def apply_2tone_freq_pair(setting, obj):
2883
            val = int(setting.value)
2884
            derived_val = 65535
2885
            frqname = str(setting._name[-5:])
2886
            derivedname = "derived_from_" + frqname
2887

    
2888
            if (val == 0):
2889
                val = 65535
2890
                derived_val = 65535
2891
            else:
2892
                derived_val = int(round(2304000.0/val))
2893

    
2894
            obj[frqname].set_value(val)
2895
            obj[derivedname].set_value(derived_val)
2896

    
2897
            LOG.debug("Apply " + frqname + ": " + str(val) + " | " +
2898
                      derivedname + ": " + str(derived_val))
2899

    
2900
        i = 1
2901
        for decode_code in self._memobj._2tone._2tone_decode:
2902
            _2tone_dec_code = RadioSettingGroup("code_2tone_" + str(i),
2903
                                                "Decode Code " + str(i))
2904
            decode_2tone.append(_2tone_dec_code)
2905

    
2906
            j = 1
2907
            for dec in decode_code.decs:
2908
                val = dec.dec
2909
                if val == 255:
2910
                    LOG.debug("Dec for Code " + str(i) + " Dec " + str(j) +
2911
                              " is not yet configured. Setting to 0.")
2912
                    val = 0
2913

    
2914
                if val <= len(LIST_2TONE_DEC):
2915
                    line = RadioSetting(
2916
                        "_2tone_dec_settings_" + str(i) + "_dec_" + str(j),
2917
                        "Dec " + str(j), RadioSettingValueList
2918
                        (LIST_2TONE_DEC,
2919
                         LIST_2TONE_DEC[val]))
2920
                    line.set_apply_callback(apply_list_value, dec.dec)
2921
                    _2tone_dec_code.append(line)
2922
                else:
2923
                    LOG.debug("Invalid value for 2tone dec! Disabling.")
2924

    
2925
                val = dec.response
2926
                if val == 255:
2927
                    LOG.debug("Response for Code " + str(i) + " Dec " +
2928
                              str(j) + " is not yet configured. Setting to 0.")
2929
                    val = 0
2930

    
2931
                if val <= len(LIST_2TONE_RESPONSE):
2932
                    line = RadioSetting(
2933
                        "_2tone_dec_settings_" + str(i) + "_resp_" + str(j),
2934
                        "Response " + str(j), RadioSettingValueList
2935
                        (LIST_2TONE_RESPONSE,
2936
                         LIST_2TONE_RESPONSE[val]))
2937
                    line.set_apply_callback(apply_list_value, dec.response)
2938
                    _2tone_dec_code.append(line)
2939
                else:
2940
                    LOG.debug("Invalid value for 2tone response! Disabling.")
2941

    
2942
                val = dec.alert
2943
                if val == 255:
2944
                    LOG.debug("Alert for Code " + str(i) + " Dec " + str(j) +
2945
                              " is not yet configured. Setting to 0.")
2946
                    val = 0
2947

    
2948
                if val <= len(PTTIDCODE_LIST):
2949
                    line = RadioSetting(
2950
                        "_2tone_dec_settings_" + str(i) + "_alert_" + str(j),
2951
                        "Alert " + str(j), RadioSettingValueList
2952
                        (PTTIDCODE_LIST,
2953
                         PTTIDCODE_LIST[val]))
2954
                    line.set_apply_callback(apply_list_value, dec.alert)
2955
                    _2tone_dec_code.append(line)
2956
                else:
2957
                    LOG.debug("Invalid value for 2tone alert! Disabling.")
2958
                j = j + 1
2959

    
2960
            freq = self._memobj._2tone.freqs[i-1]
2961
            for char in ['A', 'B', 'C', 'D']:
2962
                setting_name = "freq" + str(char)
2963

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

    
2982
            i = i + 1
2983

    
2984
        return top
2985

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

    
3013
                    if element.has_apply_callback():
3014
                        LOG.debug("Using apply callback")
3015
                        element.run_apply_callback()
3016
                    elif element.value.get_mutable():
3017
                        LOG.debug("Setting %s = %s" % (setting, element.value))
3018
                        setattr(obj, setting, element.value)
3019
                except Exception, e:
3020
                    LOG.debug(element.get_name())
3021
                    raise
3022

    
3023
    @classmethod
3024
    def match_model(cls, filedata, filename):
3025
        match_size = False
3026
        match_model = False
3027

    
3028
        # testing the file data size
3029
        if len(filedata) == MEM_SIZE:
3030
            match_size = True
3031

    
3032
        # testing the firmware model fingerprint
3033
        match_model = model_match(cls, filedata)
3034

    
3035
        if match_size and match_model:
3036
            return True
3037
        else:
3038
            return False
3039

    
3040

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

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

    
3112
#seekto 0x0E80;
3113
struct {
3114
  u8 unknown1;
3115
  u8 vfomr;
3116
  u8 keylock;
3117
  u8 unknown2;
3118
  u8 unknown3:4,
3119
     vfomren:1,
3120
     unknown4:1,
3121
     reseten:1,
3122
     menuen:1;
3123
  u8 unknown5[11];
3124
  u8 dispab;
3125
  u8 mrcha;
3126
  u8 mrchb;
3127
  u8 menu;
3128
} settings2;
3129

    
3130
#seekto 0x0EC0;
3131
struct {
3132
  char line1[6];
3133
  char line2[6];
3134
} poweron_msg;
3135

    
3136
struct settings_vfo {
3137
  u8 freq[8];
3138
  u8 offset[6];
3139
  u8 unknown2[2];
3140
  ul16 rxtone;
3141
  ul16 txtone;
3142
  u8 scode;
3143
  u8 spmute;
3144
  u8 optsig;
3145
  u8 scramble;
3146
  u8 wide;
3147
  u8 power;
3148
  u8 shiftd;
3149
  u8 step;
3150
  u8 unknown3[4];
3151
};
3152

    
3153
#seekto 0x0F00;
3154
struct {
3155
  struct settings_vfo a;
3156
  struct settings_vfo b;
3157
} vfo;
3158

    
3159
#seekto 0x1000;
3160
struct {
3161
  char name[6];
3162
  u8 unknown1[10];
3163
} names[200];
3164

    
3165
#seekto 0x2400;
3166
struct {
3167
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3168
  u8 group_tone;
3169
  u8 repeat_tone;
3170
  u8 unused[13];
3171
} _5tone_std_settings[15];
3172

    
3173
#seekto 0x2500;
3174
struct {
3175
  u8 frame1[5];
3176
  u8 frame2[5];
3177
  u8 frame3[5];
3178
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3179
} _5tone_codes[15];
3180

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

    
3203
#seekto 0x2900;
3204
struct {
3205
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3206
} dtmf_codes[15];
3207

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

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

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

    
3288
#seekto 0x3000;
3289
struct {
3290
  u8 freq[8];
3291
  char broadcast_station_name[6];
3292
  u8 unknown[2];
3293
} fm_radio_preset[16];
3294

    
3295
#seekto 0x3C90;
3296
struct {
3297
  u8 vhf_low[3];
3298
  u8 vhf_high[3];
3299
  u8 uhf_low[3];
3300
  u8 uhf_high[3];
3301
} ranges;
3302

    
3303
// the UV-2501+220 & KT8900R has different zones for storing ranges
3304

    
3305
#seekto 0x3CD0;
3306
struct {
3307
  u8 vhf_low[3];
3308
  u8 vhf_high[3];
3309
  u8 unknown1[4];
3310
  u8 unknown2[6];
3311
  u8 vhf2_low[3];
3312
  u8 vhf2_high[3];
3313
  u8 unknown3[4];
3314
  u8 unknown4[6];
3315
  u8 uhf_low[3];
3316
  u8 uhf_high[3];
3317
} ranges220;
3318

    
3319
#seekto 0x3F70;
3320
struct {
3321
  char fp[6];
3322
} fingerprint;
3323

    
3324
"""
3325

    
3326

    
3327
class BTech(BTechMobileCommon):
3328
    """BTECH's UV-5001 and alike radios"""
3329
    BANDS = 2
3330
    COLOR_LCD = False
3331
    NAME_LENGTH = 6
3332

    
3333
    def set_options(self):
3334
        """This is to read the options from the image and set it in the
3335
        environment, for now just the limits of the freqs in the VHF/UHF
3336
        ranges"""
3337

    
3338
        # setting the correct ranges for each radio type
3339
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3340
            # the model 2501+220 has a segment in 220
3341
            # and a different position in the memmap
3342
            # also the QYT KT8900R
3343
            ranges = self._memobj.ranges220
3344
        else:
3345
            ranges = self._memobj.ranges
3346

    
3347
        # the normal dual bands
3348
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3349
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3350

    
3351
        # DEBUG
3352
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3353
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3354

    
3355
        # 220Mhz radios case
3356
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3357
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3358
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3359
            self._220_range = vhf2
3360

    
3361
        # set the class with the real data
3362
        self._vhf_range = vhf
3363
        self._uhf_range = uhf
3364

    
3365
    def process_mmap(self):
3366
        """Process the mem map into the mem object"""
3367

    
3368
        # Get it
3369
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
3370

    
3371
        # load specific parameters from the radio image
3372
        self.set_options()
3373

    
3374

    
3375
# Declaring Aliases (Clones of the real radios)
3376
class JT2705M(chirp_common.Alias):
3377
    VENDOR = "Jetstream"
3378
    MODEL = "JT2705M"
3379

    
3380

    
3381
class JT6188Mini(chirp_common.Alias):
3382
    VENDOR = "Juentai"
3383
    MODEL = "JT-6188 Mini"
3384

    
3385

    
3386
class JT6188Plus(chirp_common.Alias):
3387
    VENDOR = "Juentai"
3388
    MODEL = "JT-6188 Plus"
3389

    
3390

    
3391
class SSGT890(chirp_common.Alias):
3392
    VENDOR = "Sainsonic"
3393
    MODEL = "GT-890"
3394

    
3395

    
3396
class ZastoneMP300(chirp_common.Alias):
3397
    VENDOR = "Zastone"
3398
    MODEL = "MP-300"
3399

    
3400

    
3401
# real radios
3402
@directory.register
3403
class UV2501(BTech):
3404
    """Baofeng Tech UV2501"""
3405
    MODEL = "UV-2501"
3406
    _fileid = [UV2501G3_fp,
3407
               UV2501G2_fp,
3408
               UV2501pp2_fp,
3409
               UV2501pp_fp]
3410

    
3411

    
3412
@directory.register
3413
class UV2501_220(BTech):
3414
    """Baofeng Tech UV2501+220"""
3415
    MODEL = "UV-2501+220"
3416
    BANDS = 3
3417
    _magic = MSTRING_220
3418
    _id2 = [UV2501_220pp_id, ]
3419
    _fileid = [UV2501_220G3_fp,
3420
               UV2501_220G2_fp,
3421
               UV2501_220_fp,
3422
               UV2501_220pp_fp]
3423

    
3424

    
3425
@directory.register
3426
class UV5001(BTech):
3427
    """Baofeng Tech UV5001"""
3428
    MODEL = "UV-5001"
3429
    _fileid = [UV5001G3_fp,
3430
               UV5001G22_fp,
3431
               UV5001G2_fp,
3432
               UV5001alpha_fp,
3433
               UV5001pp_fp]
3434
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
3435
                     chirp_common.PowerLevel("Low", watts=10)]
3436

    
3437

    
3438
@directory.register
3439
class MINI8900(BTech):
3440
    """WACCOM MINI-8900"""
3441
    VENDOR = "WACCOM"
3442
    MODEL = "MINI-8900"
3443
    _magic = MSTRING_MINI8900
3444
    _fileid = [MINI8900_fp, ]
3445
    # Clones
3446
    ALIASES = [JT6188Plus, ]
3447

    
3448

    
3449
@directory.register
3450
class KTUV980(BTech):
3451
    """QYT KT-UV980"""
3452
    VENDOR = "QYT"
3453
    MODEL = "KT-UV980"
3454
    _vhf_range = (136000000, 175000000)
3455
    _uhf_range = (400000000, 481000000)
3456
    _magic = MSTRING_MINI8900
3457
    _fileid = [KTUV980_fp, ]
3458
    # Clones
3459
    ALIASES = [JT2705M, ]
3460

    
3461
# Please note that there is a version of this radios that is a clone of the
3462
# Waccom Mini8900, maybe an early version?
3463

    
3464

    
3465
class OTGRadioV1(chirp_common.Alias):
3466
    VENDOR = 'OTGSTUFF'
3467
    MODEL = 'OTG Radio v1'
3468

    
3469

    
3470
@directory.register
3471
class KT9800(BTech):
3472
    """QYT KT8900"""
3473
    VENDOR = "QYT"
3474
    MODEL = "KT8900"
3475
    _vhf_range = (136000000, 175000000)
3476
    _uhf_range = (400000000, 481000000)
3477
    _magic = MSTRING_KT8900
3478
    _fileid = [KT8900_fp,
3479
               KT8900_fp1,
3480
               KT8900_fp2,
3481
               KT8900_fp3,
3482
               KT8900_fp4,
3483
               KT8900_fp5,
3484
               KT8900_fp6]
3485
    _id2 = [KT8900_id, KT8900_id2]
3486
    # Clones
3487
    ALIASES = [JT6188Mini, SSGT890, ZastoneMP300]
3488

    
3489

    
3490
@directory.register
3491
class KT9800R(BTech):
3492
    """QYT KT8900R"""
3493
    VENDOR = "QYT"
3494
    MODEL = "KT8900R"
3495
    BANDS = 3
3496
    _vhf_range = (136000000, 175000000)
3497
    _220_range = (240000000, 271000000)
3498
    _uhf_range = (400000000, 481000000)
3499
    _magic = MSTRING_KT8900R
3500
    _fileid = [KT8900R_fp,
3501
               KT8900R_fp1,
3502
               KT8900R_fp2,
3503
               KT8900R_fp3,
3504
               KT8900R_fp4]
3505
    _id2 = [KT8900R_id, KT8900R_id2]
3506

    
3507

    
3508
@directory.register
3509
class LT588UV(BTech):
3510
    """LUITON LT-588UV"""
3511
    VENDOR = "LUITON"
3512
    MODEL = "LT-588UV"
3513
    _vhf_range = (136000000, 175000000)
3514
    _uhf_range = (400000000, 481000000)
3515
    _magic = MSTRING_KT8900
3516
    _fileid = [LT588UV_fp,
3517
               LT588UV_fp1]
3518
    _power_levels = [chirp_common.PowerLevel("High", watts=60),
3519
                     chirp_common.PowerLevel("Low", watts=10)]
3520

    
3521

    
3522
COLOR_MEM_FORMAT = """
3523
#seekto 0x0000;
3524
struct {
3525
  lbcd rxfreq[4];
3526
  lbcd txfreq[4];
3527
  ul16 rxtone;
3528
  ul16 txtone;
3529
  u8 unknown0:4,
3530
     scode:4;
3531
  u8 unknown1:2,
3532
     spmute:2,
3533
     unknown2:2,
3534
     optsig:2;
3535
  u8 unknown3:3,
3536
     scramble:1,
3537
     unknown4:3,
3538
     power:1;
3539
  u8 unknown5:1,
3540
     wide:1,
3541
     unknown6:2,
3542
     bcl:1,
3543
     add:1,
3544
     pttid:2;
3545
} memory[200];
3546

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

    
3603
#seekto 0x0E80;
3604
struct {
3605
  u8 unknown1;
3606
  u8 vfomr;
3607
  u8 keylock;
3608
  u8 unknown2;
3609
  u8 unknown3:4,
3610
     vfomren:1,
3611
     unknown4:1,
3612
     reseten:1,
3613
     menuen:1;
3614
  u8 unknown5[11];
3615
  u8 dispab;
3616
  u8 unknown6[2];
3617
  u8 menu;
3618
  u8 unknown7[7];
3619
  u8 vfomra;
3620
  u8 vfomrb;
3621
  u8 vfomrc;
3622
  u8 vfomrd;
3623
  u8 mrcha;
3624
  u8 mrchb;
3625
  u8 mrchc;
3626
  u8 mrchd;
3627
} settings2;
3628

    
3629
struct settings_vfo {
3630
  u8 freq[8];
3631
  u8 offset[6];
3632
  u8 unknown2[2];
3633
  ul16 rxtone;
3634
  ul16 txtone;
3635
  u8 scode;
3636
  u8 spmute;
3637
  u8 optsig;
3638
  u8 scramble;
3639
  u8 wide;
3640
  u8 power;
3641
  u8 shiftd;
3642
  u8 step;
3643
  u8 unknown3[4];
3644
};
3645

    
3646
#seekto 0x0F00;
3647
struct {
3648
  struct settings_vfo a;
3649
  struct settings_vfo b;
3650
  struct settings_vfo c;
3651
  struct settings_vfo d;
3652
} vfo;
3653

    
3654
#seekto 0x0F80;
3655
struct {
3656
  char line1[8];
3657
  char line2[8];
3658
  char line3[8];
3659
  char line4[8];
3660
  char line5[8];
3661
  char line6[8];
3662
  char line7[8];
3663
  char line8[8];
3664
} poweron_msg;
3665

    
3666
#seekto 0x1000;
3667
struct {
3668
  char name[8];
3669
  u8 unknown1[8];
3670
} names[200];
3671

    
3672
#seekto 0x2400;
3673
struct {
3674
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3675
  u8 group_tone;
3676
  u8 repeat_tone;
3677
  u8 unused[13];
3678
} _5tone_std_settings[15];
3679

    
3680
#seekto 0x2500;
3681
struct {
3682
  u8 frame1[5];
3683
  u8 frame2[5];
3684
  u8 frame3[5];
3685
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3686
} _5tone_codes[15];
3687

    
3688
#seekto 0x25F0;
3689
struct {
3690
  u8 _5tone_delay1; // * 10ms
3691
  u8 _5tone_delay2; // * 10ms
3692
  u8 _5tone_delay3; // * 10ms
3693
  u8 _5tone_first_digit_ext_length;
3694
  u8 unknown1;
3695
  u8 unknown2;
3696
  u8 unknown3;
3697
  u8 unknown4;
3698
  u8 decode_standard;
3699
  u8 unknown5:5,
3700
     _5tone_decode_call_frame3:1,
3701
     _5tone_decode_call_frame2:1,
3702
     _5tone_decode_call_frame1:1;
3703
  u8 unknown6:5,
3704
     _5tone_decode_disp_frame3:1,
3705
     _5tone_decode_disp_frame2:1,
3706
     _5tone_decode_disp_frame1:1;
3707
  u8 decode_reset_time; // * 100 + 100ms
3708
} _5tone_settings;
3709

    
3710
#seekto 0x2900;
3711
struct {
3712
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3713
} dtmf_codes[15];
3714

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

    
3758
#seekto 0x2D00;
3759
struct {
3760
  struct {
3761
    ul16 freq1;
3762
    u8 unused01[6];
3763
    ul16 freq2;
3764
    u8 unused02[6];
3765
  } _2tone_encode[15];
3766
  u8 duration_1st_tone; // *10ms
3767
  u8 duration_2nd_tone; // *10ms
3768
  u8 duration_gap;      // *10ms
3769
  u8 unused03[13];
3770
  struct {
3771
    struct {
3772
      u8 dec;      // one out of LIST_2TONE_DEC
3773
      u8 response; // one out of LIST_2TONE_RESPONSE
3774
      u8 alert;    // 1-16
3775
    } decs[4];
3776
    u8 unused04[4];
3777
  } _2tone_decode[15];
3778
  u8 unused05[16];
3779

    
3780
  struct {
3781
    ul16 freqA;
3782
    ul16 freqB;
3783
    ul16 freqC;
3784
    ul16 freqD;
3785
    // unknown what those values mean, but they are
3786
    // derived from configured frequencies
3787
    ul16 derived_from_freqA; // 2304000/freqA
3788
    ul16 derived_from_freqB; // 2304000/freqB
3789
    ul16 derived_from_freqC; // 2304000/freqC
3790
    ul16 derived_from_freqD; // 2304000/freqD
3791
  }freqs[15];
3792
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
3793
} _2tone;
3794

    
3795
#seekto 0x3D80;
3796
struct {
3797
  u8 vhf_low[3];
3798
  u8 vhf_high[3];
3799
  u8 unknown1[4];
3800
  u8 unknown2[6];
3801
  u8 vhf2_low[3];
3802
  u8 vhf2_high[3];
3803
  u8 unknown3[4];
3804
  u8 unknown4[6];
3805
  u8 uhf_low[3];
3806
  u8 uhf_high[3];
3807
  u8 unknown5[4];
3808
  u8 unknown6[6];
3809
  u8 uhf2_low[3];
3810
  u8 uhf2_high[3];
3811
} ranges;
3812

    
3813
#seekto 0x3F70;
3814
struct {
3815
  char fp[6];
3816
} fingerprint;
3817

    
3818
"""
3819

    
3820

    
3821
class BTechColor(BTechMobileCommon):
3822
    """BTECH's Color LCD Mobile and alike radios"""
3823
    COLOR_LCD = True
3824
    NAME_LENGTH = 8
3825
    LIST_TMR = LIST_TMR16
3826

    
3827
    def process_mmap(self):
3828
        """Process the mem map into the mem object"""
3829

    
3830
        # Get it
3831
        self._memobj = bitwise.parse(COLOR_MEM_FORMAT, self._mmap)
3832

    
3833
        # load specific parameters from the radio image
3834
        self.set_options()
3835

    
3836
    def set_options(self):
3837
        """This is to read the options from the image and set it in the
3838
        environment, for now just the limits of the freqs in the VHF/UHF
3839
        ranges"""
3840

    
3841
        # setting the correct ranges for each radio type
3842
        ranges = self._memobj.ranges
3843

    
3844
        # the normal dual bands
3845
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3846
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3847

    
3848
        # DEBUG
3849
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3850
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3851

    
3852
        # the additional bands
3853
        if self.MODEL in ["UV-25X4", "KT7900D"]:
3854
            # 200Mhz band
3855
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3856
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3857
            self._220_range = vhf2
3858

    
3859
            # 350Mhz band
3860
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
3861
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
3862
            self._350_range = uhf2
3863

    
3864
        # set the class with the real data
3865
        self._vhf_range = vhf
3866
        self._uhf_range = uhf
3867

    
3868

    
3869
# Declaring Aliases (Clones of the real radios)
3870
class SKT8900D(chirp_common.Alias):
3871
    VENDOR = "Surecom"
3872
    MODEL = "S-KT8900D"
3873

    
3874

    
3875
class QB25(chirp_common.Alias):
3876
    VENDOR = "Radioddity"
3877
    MODEL = "QB25"
3878

    
3879

    
3880
# real radios
3881
@directory.register
3882
class UV25X2(BTechColor):
3883
    """Baofeng Tech UV25X2"""
3884
    MODEL = "UV-25X2"
3885
    BANDS = 2
3886
    _vhf_range = (130000000, 180000000)
3887
    _uhf_range = (400000000, 521000000)
3888
    _magic = MSTRING_UV25X2
3889
    _fileid = [UV25X2_fp, ]
3890

    
3891

    
3892
@directory.register
3893
class UV25X4(BTechColor):
3894
    """Baofeng Tech UV25X4"""
3895
    MODEL = "UV-25X4"
3896
    BANDS = 4
3897
    _vhf_range = (130000000, 180000000)
3898
    _220_range = (200000000, 271000000)
3899
    _uhf_range = (400000000, 521000000)
3900
    _350_range = (350000000, 391000000)
3901
    _magic = MSTRING_UV25X4
3902
    _fileid = [UV25X4_fp, ]
3903

    
3904

    
3905
@directory.register
3906
class UV50X2(BTechColor):
3907
    """Baofeng Tech UV50X2"""
3908
    MODEL = "UV-50X2"
3909
    BANDS = 2
3910
    _vhf_range = (130000000, 180000000)
3911
    _uhf_range = (400000000, 521000000)
3912
    _magic = MSTRING_UV25X2
3913
    _fileid = [UV50X2_fp, ]
3914
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
3915
                     chirp_common.PowerLevel("Low", watts=10)]
3916

    
3917

    
3918
@directory.register
3919
class KT7900D(BTechColor):
3920
    """QYT KT7900D"""
3921
    VENDOR = "QYT"
3922
    MODEL = "KT7900D"
3923
    BANDS = 4
3924
    LIST_TMR = LIST_TMR15
3925
    _vhf_range = (136000000, 175000000)
3926
    _220_range = (200000000, 271000000)
3927
    _uhf_range = (400000000, 481000000)
3928
    _350_range = (350000000, 371000000)
3929
    _magic = MSTRING_KT8900D
3930
    _fileid = [KT7900D_fp, KT7900D_fp1, KT7900D_fp2, KT7900D_fp3, KT7900D_fp4,
3931
               KT7900D_fp5, KT7900D_fp6, QB25_fp, ]
3932
    # Clones
3933
    ALIASES = [SKT8900D, QB25, ]
3934

    
3935

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

    
3948
    # Clones
3949
    ALIASES = [OTGRadioV1]
3950

    
3951

    
3952
@directory.register
3953
class KT5800(BTechColor):
3954
    """QYT KT5800"""
3955
    VENDOR = "QYT"
3956
    MODEL = "KT5800"
3957
    BANDS = 2
3958
    LIST_TMR = LIST_TMR15
3959
    _vhf_range = (136000000, 175000000)
3960
    _uhf_range = (400000000, 481000000)
3961
    _magic = MSTRING_KT8900D
3962
    _fileid = [KT5800_fp, ]
3963

    
3964

    
3965
GMRS_MEM_FORMAT = """
3966
#seekto 0x0000;
3967
struct {
3968
  lbcd rxfreq[4];
3969
  lbcd txfreq[4];
3970
  ul16 rxtone;
3971
  ul16 txtone;
3972
  u8 unknown0:4,
3973
     scode:4;
3974
  u8 unknown1:2,
3975
     spmute:2,
3976
     unknown2:2,
3977
     optsig:2;
3978
  u8 unknown3:3,
3979
     scramble:1,
3980
     unknown4:2,
3981
     power:2;
3982
  u8 unknown5:1,
3983
     wide:1,
3984
     unknown6:2,
3985
     bcl:1,
3986
     add:1,
3987
     pttid:2;
3988
} memory[256];
3989

    
3990
#seekto 0x1000;
3991
struct {
3992
  char name[7];
3993
  u8 unknown1[9];
3994
} names[256];
3995

    
3996
#seekto 0x2400;
3997
struct {
3998
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3999
  u8 group_tone;
4000
  u8 repeat_tone;
4001
  u8 unused[13];
4002
} _5tone_std_settings[15];
4003

    
4004
#seekto 0x2500;
4005
struct {
4006
  u8 frame1[5];
4007
  u8 frame2[5];
4008
  u8 frame3[5];
4009
  u8 standard;   // one out of LIST_5TONE_STANDARDS
4010
} _5tone_codes[15];
4011

    
4012
#seekto 0x25F0;
4013
struct {
4014
  u8 _5tone_delay1; // * 10ms
4015
  u8 _5tone_delay2; // * 10ms
4016
  u8 _5tone_delay3; // * 10ms
4017
  u8 _5tone_first_digit_ext_length;
4018
  u8 unknown1;
4019
  u8 unknown2;
4020
  u8 unknown3;
4021
  u8 unknown4;
4022
  u8 decode_standard;
4023
  u8 unknown5:5,
4024
     _5tone_decode_call_frame3:1,
4025
     _5tone_decode_call_frame2:1,
4026
     _5tone_decode_call_frame1:1;
4027
  u8 unknown6:5,
4028
     _5tone_decode_disp_frame3:1,
4029
     _5tone_decode_disp_frame2:1,
4030
     _5tone_decode_disp_frame1:1;
4031
  u8 decode_reset_time; // * 100 + 100ms
4032
} _5tone_settings;
4033

    
4034
#seekto 0x2900;
4035
struct {
4036
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
4037
} dtmf_codes[15];
4038

    
4039
#seekto 0x29F0;
4040
struct {
4041
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
4042
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
4043
  u8 unknown0[14];
4044
  u8 inspection[16];
4045
  u8 monitor[16];
4046
  u8 alarmcode[16];
4047
  u8 stun[16];
4048
  u8 kill[16];
4049
  u8 revive[16];
4050
  u8 unknown1[16];
4051
  u8 unknown2[16];
4052
  u8 unknown3[16];
4053
  u8 unknown4[16];
4054
  u8 unknown5[16];
4055
  u8 unknown6[16];
4056
  u8 unknown7[16];
4057
  u8 masterid[16];
4058
  u8 viceid[16];
4059
  u8 unused01:7,
4060
     mastervice:1;
4061
  u8 unused02:3,
4062
     mrevive:1,
4063
     mkill:1,
4064
     mstun:1,
4065
     mmonitor:1,
4066
     minspection:1;
4067
  u8 unused03:3,
4068
     vrevive:1,
4069
     vkill:1,
4070
     vstun:1,
4071
     vmonitor:1,
4072
     vinspection:1;
4073
  u8 unused04:6,
4074
     txdisable:1,
4075
     rxdisable:1;
4076
  u8 groupcode;
4077
  u8 spacecode;
4078
  u8 delayproctime; // * 100 + 100ms
4079
  u8 resettime;     // * 100 + 100ms
4080
} dtmf_settings;
4081

    
4082
#seekto 0x2D00;
4083
struct {
4084
  struct {
4085
    ul16 freq1;
4086
    u8 unused01[6];
4087
    ul16 freq2;
4088
    u8 unused02[6];
4089
  } _2tone_encode[15];
4090
  u8 duration_1st_tone; // *10ms
4091
  u8 duration_2nd_tone; // *10ms
4092
  u8 duration_gap;      // *10ms
4093
  u8 unused03[13];
4094
  struct {
4095
    struct {
4096
      u8 dec;      // one out of LIST_2TONE_DEC
4097
      u8 response; // one out of LIST_2TONE_RESPONSE
4098
      u8 alert;    // 1-16
4099
    } decs[4];
4100
    u8 unused04[4];
4101
  } _2tone_decode[15];
4102
  u8 unused05[16];
4103

    
4104
  struct {
4105
    ul16 freqA;
4106
    ul16 freqB;
4107
    ul16 freqC;
4108
    ul16 freqD;
4109
    // unknown what those values mean, but they are
4110
    // derived from configured frequencies
4111
    ul16 derived_from_freqA; // 2304000/freqA
4112
    ul16 derived_from_freqB; // 2304000/freqB
4113
    ul16 derived_from_freqC; // 2304000/freqC
4114
    ul16 derived_from_freqD; // 2304000/freqD
4115
  }freqs[15];
4116
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
4117
} _2tone;
4118

    
4119
#seekto 0x3000;
4120
struct {
4121
  u8 freq[8];
4122
  char broadcast_station_name[6];
4123
  u8 unknown[2];
4124
} fm_radio_preset[16];
4125

    
4126
#seekto 0x3200;
4127
struct {
4128
  u8 tmr;
4129
  u8 unknown1;
4130
  u8 sql;
4131
  u8 unknown2;
4132
  u8 autolk;
4133
  u8 tot;
4134
  u8 apo;
4135
  u8 unknown3;
4136
  u8 abr;
4137
  u8 beep;
4138
  u8 unknown4[4];
4139
  u8 dtmfst;
4140
  u8 unknown5[2];
4141
  u8 screv;
4142
  u8 unknown6[2];
4143
  u8 pttid;
4144
  u8 pttlt;
4145
  u8 unknown7;
4146
  u8 emctp;
4147
  u8 emcch;
4148
  u8 sigbp;
4149
  u8 unknown8;
4150
  u8 camdf;
4151
  u8 cbmdf;
4152
  u8 ccmdf;
4153
  u8 cdmdf;
4154
  u8 langua;
4155
  u8 sync;
4156

    
4157

    
4158
  u8 stfc;
4159
  u8 mffc;
4160
  u8 sfafc;
4161
  u8 sfbfc;
4162
  u8 sfcfc;
4163
  u8 sfdfc;
4164
  u8 subfc;
4165
  u8 fmfc;
4166
  u8 sigfc;
4167
  u8 modfc;
4168
  u8 menufc;
4169
  u8 txfc;
4170
  u8 txdisp;
4171
  u8 unknown9[5];
4172
  u8 anil;
4173
  u8 reps;
4174
  u8 repm;
4175
  u8 tmrmr;
4176
  u8 ste;
4177
  u8 rpste;
4178
  u8 rptdl;
4179
  u8 dtmfg;
4180
  u8 mgain;
4181
  u8 skiptx;
4182
  u8 scmode;
4183
} settings;
4184

    
4185
#seekto 0x3280;
4186
struct {
4187
  u8 unknown1;
4188
  u8 vfomr;
4189
  u8 keylock;
4190
  u8 unknown2;
4191
  u8 unknown3:4,
4192
     vfomren:1,
4193
     unknown4:1,
4194
     reseten:1,
4195
     menuen:1;
4196
  u8 unknown5[11];
4197
  u8 dispab;
4198
  u8 unknown6[2];
4199
  u8 smenu;
4200
  u8 unknown7[7];
4201
  u8 vfomra;
4202
  u8 vfomrb;
4203
  u8 vfomrc;
4204
  u8 vfomrd;
4205
  u8 mrcha;
4206
  u8 mrchb;
4207
  u8 mrchc;
4208
  u8 mrchd;
4209
} settings2;
4210

    
4211
struct settings_vfo {
4212
  u8 freq[8];
4213
  u8 offset[6];
4214
  u8 unknown2[2];
4215
  ul16 rxtone;
4216
  ul16 txtone;
4217
  u8 scode;
4218
  u8 spmute;
4219
  u8 optsig;
4220
  u8 scramble;
4221
  u8 wide;
4222
  u8 power;
4223
  u8 shiftd;
4224
  u8 step;
4225
  u8 unknown3[4];
4226
};
4227

    
4228
#seekto 0x3300;
4229
struct {
4230
  struct settings_vfo a;
4231
  struct settings_vfo b;
4232
  struct settings_vfo c;
4233
  struct settings_vfo d;
4234
} vfo;
4235

    
4236
#seekto 0x3D80;
4237
struct {
4238
  u8 vhf_low[3];
4239
  u8 vhf_high[3];
4240
  u8 unknown1[4];
4241
  u8 unknown2[6];
4242
  u8 vhf2_low[3];
4243
  u8 vhf2_high[3];
4244
  u8 unknown3[4];
4245
  u8 unknown4[6];
4246
  u8 uhf_low[3];
4247
  u8 uhf_high[3];
4248
  u8 unknown5[4];
4249
  u8 unknown6[6];
4250
  u8 uhf2_low[3];
4251
  u8 uhf2_high[3];
4252
} ranges;
4253

    
4254
#seekto 0x33B0;
4255
struct {
4256
  char line[16];
4257
} static_msg;
4258

    
4259
#seekto 0x3F70;
4260
struct {
4261
  char fp[6];
4262
} fingerprint;
4263

    
4264
"""
4265

    
4266

    
4267
class BTechGMRS(BTechMobileCommon):
4268
    """BTECH's GMRS Mobile"""
4269
    COLOR_LCD = True
4270
    COLOR_LCD2 = True
4271
    NAME_LENGTH = 7
4272
    UPLOAD_MEM_SIZE = 0X3400
4273

    
4274
    def process_mmap(self):
4275
        """Process the mem map into the mem object"""
4276

    
4277
        # Get it
4278
        self._memobj = bitwise.parse(GMRS_MEM_FORMAT, self._mmap)
4279

    
4280
        # load specific parameters from the radio image
4281
        self.set_options()
4282

    
4283
    def set_options(self):
4284
        """This is to read the options from the image and set it in the
4285
        environment, for now just the limits of the freqs in the VHF/UHF
4286
        ranges"""
4287

    
4288
        # setting the correct ranges for each radio type
4289
        ranges = self._memobj.ranges
4290

    
4291
        # the normal dual bands
4292
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
4293
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
4294

    
4295
        # DEBUG
4296
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
4297
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
4298

    
4299
        # set the class with the real data
4300
        self._vhf_range = vhf
4301
        self._uhf_range = uhf
4302

    
4303

    
4304
# real radios
4305
@directory.register
4306
class GMRS50X1(BTechGMRS):
4307
    """Baofeng Tech GMRS50X1"""
4308
    MODEL = "GMRS-50X1"
4309
    BANDS = 2
4310
    LIST_TMR = LIST_TMR16
4311
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
4312
                     chirp_common.PowerLevel("Mid", watts=10),
4313
                     chirp_common.PowerLevel("Low", watts=5)]
4314
    _vhf_range = (136000000, 175000000)
4315
    _uhf_range = (400000000, 521000000)
4316
    _upper = 255
4317
    _magic = MSTRING_GMRS50X1
4318
    _fileid = [GMRS50X1_fp1, GMRS50X1_fp, ]
4319

    
4320

    
4321
COLORHT_MEM_FORMAT = """
4322
#seekto 0x0000;
4323
struct {
4324
  lbcd rxfreq[4];
4325
  lbcd txfreq[4];
4326
  ul16 rxtone;
4327
  ul16 txtone;
4328
  u8 unknown0:4,
4329
     scode:4;
4330
  u8 unknown1:2,
4331
     spmute:2,
4332
     unknown2:2,
4333
     optsig:2;
4334
  u8 unknown3:3,
4335
     scramble:1,
4336
     unknown4:3,
4337
     power:1;
4338
  u8 unknown5:1,
4339
     wide:1,
4340
     unknown6:2,
4341
     bcl:1,
4342
     add:1,
4343
     pttid:2;
4344
} memory[200];
4345

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

    
4403
#seekto 0x0E80;
4404
struct {
4405
  u8 unknown1;
4406
  u8 vfomr;
4407
  u8 keylock;
4408
  u8 unknown2;
4409
  u8 unknown3:4,
4410
     vfomren:1,
4411
     unknown4:1,
4412
     reseten:1,
4413
     menuen:1;
4414
  u8 unknown5[11];
4415
  u8 dispab;
4416
  u8 unknown6[2];
4417
  u8 menu;
4418
  u8 unknown7[7];
4419
  u8 vfomra;
4420
  u8 vfomrb;
4421
  u8 vfomrc;
4422
  u8 vfomrd;
4423
  u8 mrcha;
4424
  u8 mrchb;
4425
  u8 mrchc;
4426
  u8 mrchd;
4427
} settings2;
4428

    
4429
struct settings_vfo {
4430
  u8 freq[8];
4431
  u8 offset[6];
4432
  u8 unknown2[2];
4433
  ul16 rxtone;
4434
  ul16 txtone;
4435
  u8 scode;
4436
  u8 spmute;
4437
  u8 optsig;
4438
  u8 scramble;
4439
  u8 wide;
4440
  u8 power;
4441
  u8 shiftd;
4442
  u8 step;
4443
  u8 unknown3[4];
4444
};
4445

    
4446
#seekto 0x0F00;
4447
struct {
4448
  struct settings_vfo a;
4449
  struct settings_vfo b;
4450
  struct settings_vfo c;
4451
  struct settings_vfo d;
4452
} vfo;
4453

    
4454
#seekto 0x0FE0;
4455
struct {
4456
  char line[16];
4457
} static_msg;
4458

    
4459
#seekto 0x1000;
4460
struct {
4461
  char name[8];
4462
  u8 unknown1[8];
4463
} names[200];
4464

    
4465
#seekto 0x2400;
4466
struct {
4467
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
4468
  u8 group_tone;
4469
  u8 repeat_tone;
4470
  u8 unused[13];
4471
} _5tone_std_settings[15];
4472

    
4473
#seekto 0x2500;
4474
struct {
4475
  u8 frame1[5];
4476
  u8 frame2[5];
4477
  u8 frame3[5];
4478
  u8 standard;   // one out of LIST_5TONE_STANDARDS
4479
} _5tone_codes[15];
4480

    
4481
#seekto 0x25F0;
4482
struct {
4483
  u8 _5tone_delay1; // * 10ms
4484
  u8 _5tone_delay2; // * 10ms
4485
  u8 _5tone_delay3; // * 10ms
4486
  u8 _5tone_first_digit_ext_length;
4487
  u8 unknown1;
4488
  u8 unknown2;
4489
  u8 unknown3;
4490
  u8 unknown4;
4491
  u8 decode_standard;
4492
  u8 unknown5:5,
4493
     _5tone_decode_call_frame3:1,
4494
     _5tone_decode_call_frame2:1,
4495
     _5tone_decode_call_frame1:1;
4496
  u8 unknown6:5,
4497
     _5tone_decode_disp_frame3:1,
4498
     _5tone_decode_disp_frame2:1,
4499
     _5tone_decode_disp_frame1:1;
4500
  u8 decode_reset_time; // * 100 + 100ms
4501
} _5tone_settings;
4502

    
4503
#seekto 0x2900;
4504
struct {
4505
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
4506
} dtmf_codes[15];
4507

    
4508
#seekto 0x29F0;
4509
struct {
4510
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
4511
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
4512
  u8 unknown0[14];
4513
  u8 inspection[16];
4514
  u8 monitor[16];
4515
  u8 alarmcode[16];
4516
  u8 stun[16];
4517
  u8 kill[16];
4518
  u8 revive[16];
4519
  u8 unknown1[16];
4520
  u8 unknown2[16];
4521
  u8 unknown3[16];
4522
  u8 unknown4[16];
4523
  u8 unknown5[16];
4524
  u8 unknown6[16];
4525
  u8 unknown7[16];
4526
  u8 masterid[16];
4527
  u8 viceid[16];
4528
  u8 unused01:7,
4529
     mastervice:1;
4530
  u8 unused02:3,
4531
     mrevive:1,
4532
     mkill:1,
4533
     mstun:1,
4534
     mmonitor:1,
4535
     minspection:1;
4536
  u8 unused03:3,
4537
     vrevive:1,
4538
     vkill:1,
4539
     vstun:1,
4540
     vmonitor:1,
4541
     vinspection:1;
4542
  u8 unused04:6,
4543
     txdisable:1,
4544
     rxdisable:1;
4545
  u8 groupcode;
4546
  u8 spacecode;
4547
  u8 delayproctime; // * 100 + 100ms
4548
  u8 resettime;     // * 100 + 100ms
4549
} dtmf_settings;
4550

    
4551
#seekto 0x2D00;
4552
struct {
4553
  struct {
4554
    ul16 freq1;
4555
    u8 unused01[6];
4556
    ul16 freq2;
4557
    u8 unused02[6];
4558
  } _2tone_encode[15];
4559
  u8 duration_1st_tone; // *10ms
4560
  u8 duration_2nd_tone; // *10ms
4561
  u8 duration_gap;      // *10ms
4562
  u8 unused03[13];
4563
  struct {
4564
    struct {
4565
      u8 dec;      // one out of LIST_2TONE_DEC
4566
      u8 response; // one out of LIST_2TONE_RESPONSE
4567
      u8 alert;    // 1-16
4568
    } decs[4];
4569
    u8 unused04[4];
4570
  } _2tone_decode[15];
4571
  u8 unused05[16];
4572

    
4573
  struct {
4574
    ul16 freqA;
4575