Project

General

Profile

Feature #9455 » btech.py

Roy Wilson, 10/23/2021 04:47 PM

 
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 = "VC3042"
251
KT8900D_fp3 = "VC7062"
252
KT8900D_fp4 = "VC6042"
253

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

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

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

    
267

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

    
289

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

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

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

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

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

    
316

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

    
320
    data = ""
321

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

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

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

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

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

    
342
    return data
343

    
344

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

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

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

    
370

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

    
378
    return frame
379

    
380

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

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

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

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

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

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

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

    
408

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

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

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

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

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

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

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

    
439
                return True
440

    
441
        return False
442

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

    
448

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

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

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

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

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

    
481
            break
482

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

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

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

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

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

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

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

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

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

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

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

    
547
    return True
548

    
549

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

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

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

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

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

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

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

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

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

    
585
        # aggregate the data
586
        data += d
587

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

    
593
    return data
594

    
595

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
656

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

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

    
664
    return False
665

    
666

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

    
675
    return (ilow, ihigh)
676

    
677

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

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

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

    
692

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

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

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

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

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

    
745
            """))
746
        return rp
747

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

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

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

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

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

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

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

    
800
        return rf
801

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

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

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

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

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

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

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

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

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

    
873
        # Memory number
874
        mem.number = number
875

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
961
        return mem
962

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1068
        return mem
1069

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2195
                i = i + 1
2196

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2486
        top.append(group_5tone)
2487

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2866
            i = i + 1
2867

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2983
            i = i + 1
2984

    
2985
        return top
2986

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

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

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

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

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

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

    
3041

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3325
"""
3326

    
3327

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

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

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

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

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

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

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

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

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

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

    
3375

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

    
3381

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

    
3386

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

    
3391

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

    
3396

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

    
3401

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

    
3412

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

    
3425

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

    
3438

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

    
3449

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

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

    
3465

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

    
3470

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

    
3490

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

    
3508

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

    
3522

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3819
"""
3820

    
3821

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

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

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

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

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

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

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

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

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

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

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

    
3869

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

    
3875

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

    
3880

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

    
3892

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

    
3905

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

    
3918

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

    
3936

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

    
3949
    # Clones
3950
    ALIASES = [OTGRadioV1]
3951

    
3952

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

    
3965

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

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

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

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

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

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

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

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

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

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

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

    
4158

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

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

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

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

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

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

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

    
4265
"""
4266

    
4267

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

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

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

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

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

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

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

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

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

    
4304

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

    
4321

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4574
  struct {
4575
    ul16 freqA;
4576
    ul16 freqB;
4577
    ul16 freqC;
4578
    ul16 freqD;
4579
    // unknown what those values mean, but they are
4580
    // derived from configured frequencies
4581
    ul16 derived_from_freqA; // 2304000/freqA
4582
    ul16 derived_from_freqB; // 2304000/freqB
4583
    ul16 derived_from_freqC; // 2304000/freqC
4584
    ul16 derived_from_freqD; // 2304000/freqD
4585
  }freqs[15];
4586
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
4587
} _2tone;
4588

    
4589
#seekto 0x3D80;
4590
struct {
4591
  u8 vhf_low[3];
4592
  u8 vhf_high[3];
4593
  u8 unknown1[4];
4594
  u8 unknown2[6];
4595
  u8 vhf2_low[3];
4596
  u8 vhf2_high[3];
4597
  u8 unknown3[4];
4598
  u8 unknown4[6];
4599
  u8 uhf_low[3];
4600
  u8 uhf_high[3];
4601
  u8 unknown5[4];
4602
  u8 unknown6[6];
4603
  u8 uhf2_low[3];
4604
  u8 uhf2_high[3];
4605
} ranges;
4606

    
4607
#seekto 0x3F70;
4608
struct {
4609
  char fp[6];
4610
} fingerprint;
4611

    
4612
"""
4613

    
4614

    
4615
class QYTColorHT(BTechMobileCommon):
4616
    """QTY's Color LCD Handheld and alike radios"""
4617
    COLOR_LCD = True
4618
    COLOR_LCD3 = True
4619
    NAME_LENGTH = 8
4620
    LIST_TMR = LIST_TMR15
4621

    
4622
    def process_mmap(self):
4623
        """Process the mem map into the mem object"""
4624

    
4625
        # Get it
4626
        self._memobj = bitwise.parse(COLORHT_MEM_FORMAT, self._mmap)
4627

    
4628
        # load specific parameters from the radio image
4629
        self.set_options()
4630

    
4631
    def set_options(self):
4632
        """This is to read the options from the image and set it in the
4633
        environment, for now just the limits of the freqs in the VHF/UHF
4634
        ranges"""
4635

    
4636
        # setting the correct ranges for each radio type
4637
        ranges = self._memobj.ranges
4638

    
4639
        # the normal dual bands
4640
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
4641
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
4642

    
4643
        # DEBUG
4644
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
4645
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
4646

    
4647
        # the additional bands
4648
        if self.MODEL in ["KT-8R"]:
4649
            # 200Mhz band
4650
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
4651
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
4652
            self._220_range = vhf2
4653

    
4654
            # 350Mhz band
4655
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
4656
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
4657
            self._350_range = uhf2
4658

    
4659
        # set the class with the real data
4660
        self._vhf_range = vhf
4661
        self._uhf_range = uhf
4662

    
4663

    
4664
# real radios
4665
@directory.register
4666
class KT8R(QYTColorHT):
4667
    """QYT KT8R"""
4668
    VENDOR = "QYT"
4669
    MODEL = "KT-8R"
4670
    BANDS = 4
4671
    LIST_TMR = LIST_TMR15
4672
    _vhf_range = (136000000, 175000000)
4673
    _220_range = (200000000, 261000000)
4674
    _uhf_range = (400000000, 481000000)
4675
    _350_range = (350000000, 391000000)
4676
    _magic = MSTRING_KT8R
4677
    _fileid = [KT8R_fp2, KT8R_fp1, KT8R_fp, ]
4678
    _power_levels = [chirp_common.PowerLevel("High", watts=5),
4679
                     chirp_common.PowerLevel("Low", watts=1)]
(4-4/6)