db25-g_test_#6.py

Jim Unroe, 10/21/2021 01:26 pm

Download (157.6 kB)

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

    
18
import time
19
import struct
20
import logging
21

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

    
31
LOG = logging.getLogger(__name__)
32

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

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

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

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

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

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

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

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

    
147
GMRS_FREQS1 = [462.5625, 462.5875, 462.6125, 462.6375, 462.6625,
148
               462.6875, 462.7125]
149
GMRS_FREQS2 = [467.5625, 467.5875, 467.6125, 467.6375, 467.6625,
150
               467.6875, 467.7125]
151
GMRS_FREQS3 = [462.5500, 462.5750, 462.6000, 462.6250, 462.6500,
152
               462.6750, 462.7000, 462.7250]
153
GMRS_FREQS = GMRS_FREQS1 + GMRS_FREQS2 + GMRS_FREQS3 * 2
154

    
155

    
156
# #### ID strings #####################################################
157

    
158
# BTECH UV2501 pre-production units
159
UV2501pp_fp = "M2C294"
160
# BTECH UV2501 pre-production units 2 + and 1st Gen radios
161
UV2501pp2_fp = "M29204"
162
# B-TECH UV-2501 second generation (2G) radios
163
UV2501G2_fp = "BTG214"
164
# B-TECH UV-2501 third generation (3G) radios
165
UV2501G3_fp = "BTG324"
166

    
167
# B-TECH UV-2501+220 pre-production units
168
UV2501_220pp_fp = "M3C281"
169
# extra block read for the 2501+220 pre-production units
170
# the same for all of this radios so far
171
UV2501_220pp_id = "      280528"
172
# B-TECH UV-2501+220
173
UV2501_220_fp = "M3G201"
174
# new variant, let's call it Generation 2
175
UV2501_220G2_fp = "BTG211"
176
# B-TECH UV-2501+220 third generation (3G)
177
UV2501_220G3_fp = "BTG311"
178

    
179
# B-TECH UV-5001 pre-production units + 1st Gen radios
180
UV5001pp_fp = "V19204"
181
# B-TECH UV-5001 alpha units
182
UV5001alpha_fp = "V28204"
183
# B-TECH UV-5001 second generation (2G) radios
184
UV5001G2_fp = "BTG214"
185
# B-TECH UV-5001 second generation (2G2)
186
UV5001G22_fp = "V2G204"
187
# B-TECH UV-5001 third generation (3G)
188
UV5001G3_fp = "BTG304"
189

    
190
# B-TECH UV-25X2
191
UV25X2_fp = "UC2012"
192

    
193
# B-TECH UV-25X4
194
UV25X4_fp = "UC4014"
195

    
196
# B-TECH UV-50X2
197
UV50X2_fp = "UC2M12"
198

    
199
# B-TECH GMRS-50X1
200
GMRS50X1_fp = "NC1802"
201
GMRS50X1_fp1 = "NC1932"
202

    
203
# special var to know when we found a BTECH Gen 3
204
BTECH3 = [UV2501G3_fp, UV2501_220G3_fp, UV5001G3_fp]
205

    
206

    
207
# WACCOM Mini-8900
208
MINI8900_fp = "M28854"
209

    
210

    
211
# QYT KT-UV980
212
KTUV980_fp = "H28854"
213

    
214
# QYT KT8900
215
KT8900_fp = "M29154"
216
# New generations KT8900
217
KT8900_fp1 = "M2C234"
218
KT8900_fp2 = "M2G1F4"
219
KT8900_fp3 = "M2G2F4"
220
KT8900_fp4 = "M2G304"
221
KT8900_fp5 = "M2G314"
222
KT8900_fp6 = "M2G424"
223
# this radio has an extra ID
224
KT8900_id = "303688"
225
# another extra ID in sep/2021
226
KT8900_id2 = "\x05\x58\x3d\xf0\x10"
227

    
228
# KT8900R
229
KT8900R_fp = "M3G1F4"
230
# Second Generation
231
KT8900R_fp1 = "M3G214"
232
# another model
233
KT8900R_fp2 = "M3C234"
234
# another model G4?
235
KT8900R_fp3 = "M39164"
236
# another model
237
KT8900R_fp4 = "M3G314"
238
# this radio has an extra ID
239
KT8900R_id = "280528"
240
# another extra ID in dec/2018
241
KT8900R_id2 = "\x05\x58\x3d\xf0\x10"
242

    
243
# KT7900D (quad band)
244
KT7900D_fp = "VC4004"
245
KT7900D_fp1 = "VC4284"
246
KT7900D_fp2 = "VC4264"
247
KT7900D_fp3 = "VC4114"
248
KT7900D_fp4 = "VC4104"
249
KT7900D_fp5 = "VC4254"
250
KT7900D_fp6 = "VC5264"
251

    
252
# QB25 (quad band) - a clone of KT7900D
253
QB25_fp = "QB-25"
254

    
255
# KT8900D (dual band)
256
KT8900D_fp = "VC2002"
257
KT8900D_fp1 = "VC8632"
258
KT8900D_fp2 = "VC3402"
259
KT8900D_fp3 = "VC7062"
260

    
261
# LUITON LT-588UV
262
LT588UV_fp = "V2G1F4"
263
# Added by rstrickoff gen 2 id
264
LT588UV_fp1 = "V2G214"
265

    
266
# QYT KT-8R (quad band ht)
267
KT8R_fp = "MCB264"
268
KT8R_fp1 = "MCB284"
269
KT8R_fp2 = "MC5264"
270

    
271
# QYT KT5800 (dual band)
272
KT5800_fp = "VCB222"
273

    
274
# Radioddity DB25-G (gmrs)
275
DB25G_fp = "VC6182"
276

    
277

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

    
299

    
300
def _clean_buffer(radio):
301
    """Cleaning the read serial buffer, hard timeout to survive an infinite
302
    data stream"""
303

    
304
    # touching the serial timeout to optimize the flushing
305
    # restored at the end to the default value
306
    radio.pipe.timeout = 0.1
307
    dump = "1"
308
    datacount = 0
309

    
310
    try:
311
        while len(dump) > 0:
312
            dump = radio.pipe.read(100)
313
            datacount += len(dump)
314
            # hard limit to survive a infinite serial data stream
315
            # 5 times bigger than a normal rx block (69 bytes)
316
            if datacount > 345:
317
                seriale = "Please check your serial port selection."
318
                raise errors.RadioError(seriale)
319

    
320
        # restore the default serial timeout
321
        radio.pipe.timeout = STIMEOUT
322

    
323
    except Exception:
324
        raise errors.RadioError("Unknown error cleaning the serial buffer")
325

    
326

    
327
def _rawrecv(radio, amount):
328
    """Raw read from the radio device, less intensive way"""
329

    
330
    data = ""
331

    
332
    try:
333
        data = radio.pipe.read(amount)
334

    
335
        # DEBUG
336
        if debug is True:
337
            LOG.debug("<== (%d) bytes:\n\n%s" %
338
                      (len(data), util.hexprint(data)))
339

    
340
        # fail if no data is received
341
        if len(data) == 0:
342
            raise errors.RadioError("No data received from radio")
343

    
344
        # notice on the logs if short
345
        if len(data) < amount:
346
            LOG.warn("Short reading %d bytes from the %d requested." %
347
                     (len(data), amount))
348

    
349
    except:
350
        raise errors.RadioError("Error reading data from radio")
351

    
352
    return data
353

    
354

    
355
def _send(radio, data):
356
    """Send data to the radio device"""
357

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

    
373
        # DEBUG
374
        if debug is True:
375
            LOG.debug("==> (%d) bytes:\n\n%s" %
376
                      (len(data), util.hexprint(data)))
377
    except:
378
        raise errors.RadioError("Error sending data to radio")
379

    
380

    
381
def _make_frame(cmd, addr, length, data=""):
382
    """Pack the info in the headder format"""
383
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
384
    # add the data if set
385
    if len(data) != 0:
386
        frame += data
387

    
388
    return frame
389

    
390

    
391
def _recv(radio, addr):
392
    """Get data from the radio all at once to lower syscalls load"""
393

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

    
397
    # get the whole block
398
    block = _rawrecv(radio, BLOCK_SIZE + 5)
399

    
400
    # basic check
401
    if len(block) < (BLOCK_SIZE + 5):
402
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
403

    
404
    # checking for the ack
405
    if block[0] != ACK_CMD:
406
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
407

    
408
    # header validation
409
    c, a, l = struct.unpack(">BHB", block[1:5])
410
    if a != addr or l != BLOCK_SIZE or c != ord("X"):
411
        LOG.debug("Invalid header for block 0x%04x" % addr)
412
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
413
        raise errors.RadioError("Invalid header for block 0x%04x:" % addr)
414

    
415
    # return the data
416
    return block[5:]
417

    
418

    
419
def _start_clone_mode(radio, status):
420
    """Put the radio in clone mode and get the ident string, 3 tries"""
421

    
422
    # cleaning the serial buffer
423
    _clean_buffer(radio)
424

    
425
    # prep the data to show in the UI
426
    status.cur = 0
427
    status.msg = "Identifying the radio..."
428
    status.max = 3
429
    radio.status_fn(status)
430

    
431
    try:
432
        for a in range(0, status.max):
433
            # Update the UI
434
            status.cur = a + 1
435
            radio.status_fn(status)
436

    
437
            # send the magic word
438
            _send(radio, radio._magic)
439

    
440
            # Now you get a x06 of ACK if all goes well
441
            ack = radio.pipe.read(1)
442

    
443
            if ack == "\x06":
444
                # DEBUG
445
                LOG.info("Magic ACK received")
446
                status.cur = status.max
447
                radio.status_fn(status)
448

    
449
                return True
450

    
451
        return False
452

    
453
    except errors.RadioError:
454
        raise
455
    except Exception, e:
456
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
457

    
458

    
459
def _do_ident(radio, status, upload=False):
460
    """Put the radio in PROGRAM mode & identify it"""
461
    #  set the serial discipline
462
    radio.pipe.baudrate = 9600
463
    radio.pipe.parity = "N"
464

    
465
    # open the radio into program mode
466
    if _start_clone_mode(radio, status) is False:
467
        msg = "Radio did not enter clone mode"
468
        # warning about old versions of QYT KT8900
469
        if radio.MODEL == "KT8900":
470
            msg += ". You may want to try it as a WACCOM MINI-8900, there is a"
471
            msg += " known variant of this radios that is a clone of it."
472
        raise errors.RadioError(msg)
473

    
474
    # Ok, get the ident string
475
    ident = _rawrecv(radio, 49)
476

    
477
    # basic check for the ident
478
    if len(ident) != 49:
479
        raise errors.RadioError("Radio send a short ident block.")
480

    
481
    # check if ident is OK
482
    itis = False
483
    for fp in radio._fileid:
484
        if fp in ident:
485
            # got it!
486
            itis = True
487
            # checking if we are dealing with a Gen 3 BTECH
488
            if radio.VENDOR == "BTECH" and fp in BTECH3:
489
                radio.btech3 = True
490

    
491
            break
492

    
493
    if itis is False:
494
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
495
        raise errors.RadioError("Radio identification failed.")
496

    
497
    # some radios needs a extra read and check for a code on it, this ones
498
    # has the check value in the _id2 var, others simply False
499
    if radio._id2 is not False:
500
        # lower the timeout here as this radios are reseting due to timeout
501
        radio.pipe.timeout = 0.05
502

    
503
        # query & receive the extra ID
504
        _send(radio, _make_frame("S", 0x3DF0, 16))
505
        id2 = _rawrecv(radio, 21)
506

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

    
514
        # ok, the correct string must be in the received data
515
        # the radio._id2 var will be always a list
516
        flag2 = False
517
        for _id2 in radio._id2:
518
            if _id2 in id2:
519
                flag2 = True
520

    
521
        if not flag2:
522
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
523
                      (radio.MODEL, util.hexprint(id2)))
524
            raise errors.RadioError("The extra ID is wrong, aborting.")
525

    
526
        # this radios need a extra request/answer here on the upload
527
        # the amount of data received depends of the radio type
528
        #
529
        # also the first block of TX must no have the ACK at the beginning
530
        # see _upload for this.
531
        if upload is True:
532
            # send an ACK
533
            _send(radio, ACK_CMD)
534

    
535
            # the amount of data depend on the radio, so far we have two radios
536
            # reading two bytes with an ACK at the end and just ONE with just
537
            # one byte (QYT KT8900)
538
            # the JT-6188 appears a clone of the last, but reads TWO bytes.
539
            #
540
            # we will read two bytes with a custom timeout to not penalize the
541
            # users for this.
542
            #
543
            # we just check for a response and last byte being a ACK, that is
544
            # the common stone for all radios (3 so far)
545
            ack = _rawrecv(radio, 2)
546

    
547
            # checking
548
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
549
                raise errors.RadioError("Radio didn't ACK the upload")
550

    
551
            # restore the default serial timeout
552
            radio.pipe.timeout = STIMEOUT
553

    
554
    # DEBUG
555
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
556

    
557
    return True
558

    
559

    
560
def _download(radio):
561
    """Get the memory map"""
562

    
563
    # UI progress
564
    status = chirp_common.Status()
565

    
566
    # put radio in program mode and identify it
567
    _do_ident(radio, status)
568

    
569
    # the models that doesn't have the extra ID have to make a dummy read here
570
    if radio._id2 is False:
571
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
572
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
573

    
574
        if debug is True:
575
            LOG.info("Dummy first block read done, got this:\n\n %s",
576
                     util.hexprint(discard))
577

    
578
    # reset the progress bar in the UI
579
    status.max = MEM_SIZE / BLOCK_SIZE
580
    status.msg = "Cloning from radio..."
581
    status.cur = 0
582
    radio.status_fn(status)
583

    
584
    # cleaning the serial buffer
585
    _clean_buffer(radio)
586

    
587
    data = ""
588
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
589
        # sending the read request
590
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
591

    
592
        # read
593
        d = _recv(radio, addr)
594

    
595
        # aggregate the data
596
        data += d
597

    
598
        # UI Update
599
        status.cur = addr / BLOCK_SIZE
600
        status.msg = "Cloning from radio..."
601
        radio.status_fn(status)
602

    
603
    return data
604

    
605

    
606
def _upload(radio):
607
    """Upload procedure"""
608

    
609
    # The UPLOAD mem is restricted to lower than 0x3100,
610
    # so we will overide that here localy
611
    MEM_SIZE = radio.UPLOAD_MEM_SIZE
612

    
613
    # UI progress
614
    status = chirp_common.Status()
615

    
616
    # put radio in program mode and identify it
617
    _do_ident(radio, status, True)
618

    
619
    # get the data to upload to radio
620
    data = radio.get_mmap()
621

    
622
    # Reset the UI progress
623
    status.max = MEM_SIZE / TX_BLOCK_SIZE
624
    status.cur = 0
625
    status.msg = "Cloning to radio..."
626
    radio.status_fn(status)
627

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

    
632
    # cleaning the serial buffer
633
    _clean_buffer(radio)
634

    
635
    # the fun start here
636
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
637
        # getting the block of data to send
638
        d = data[addr:addr + TX_BLOCK_SIZE]
639

    
640
        # build the frame to send
641
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
642

    
643
        # first block must not send the ACK at the beginning for the
644
        # ones that has the extra id, since this have to do a extra step
645
        if addr == 0 and radio._id2 is not False:
646
            frame = frame[1:]
647

    
648
        # send the frame
649
        _send(radio, frame)
650

    
651
        # receiving the response
652
        ack = _rawrecv(radio, 1)
653

    
654
        # basic check
655
        if len(ack) != 1:
656
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
657

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

    
661
        # UI Update
662
        status.cur = addr / TX_BLOCK_SIZE
663
        status.msg = "Cloning to radio..."
664
        radio.status_fn(status)
665

    
666

    
667
def model_match(cls, data):
668
    """Match the opened/downloaded image to the correct version"""
669
    rid = data[0x3f70:0x3f76]
670

    
671
    if rid in cls._fileid:
672
        return True
673

    
674
    return False
675

    
676

    
677
def _decode_ranges(low, high):
678
    """Unpack the data in the ranges zones in the memmap and return
679
    a tuple with the integer corresponding to the Mhz it means"""
680
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
681
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
682
    ilow *= 1000000
683
    ihigh *= 1000000
684

    
685
    return (ilow, ihigh)
686

    
687

    
688
def _split(rf, f1, f2):
689
    """Returns False if the two freqs are in the same band (no split)
690
    or True otherwise"""
691

    
692
    # determine if the two freqs are in the same band
693
    for low, high in rf.valid_bands:
694
        if f1 >= low and f1 <= high and \
695
                f2 >= low and f2 <= high:
696
            # if the two freqs are on the same Band this is not a split
697
            return False
698

    
699
    # if you get here is because the freq pairs are split
700
    return True
701

    
702

    
703
class BTechMobileCommon(chirp_common.CloneModeRadio,
704
                        chirp_common.ExperimentalRadio):
705
    """BTECH's UV-5001 and alike radios"""
706
    VENDOR = "BTECH"
707
    MODEL = ""
708
    IDENT = ""
709
    BANDS = 2
710
    COLOR_LCD = False
711
    COLOR_LCD2 = False
712
    COLOR_LCD3 = False
713
    NAME_LENGTH = 6
714
    UPLOAD_MEM_SIZE = 0X3100
715
    _power_levels = [chirp_common.PowerLevel("High", watts=25),
716
                     chirp_common.PowerLevel("Low", watts=10)]
717
    _vhf_range = (130000000, 180000000)
718
    _220_range = (200000000, 271000000)
719
    _uhf_range = (400000000, 521000000)
720
    _350_range = (350000000, 391000000)
721
    _upper = 199
722
    _magic = MSTRING
723
    _fileid = None
724
    _id2 = False
725
    btech3 = False
726

    
727
    @classmethod
728
    def get_prompts(cls):
729
        rp = chirp_common.RadioPrompts()
730
        rp.experimental = \
731
            ('This driver is experimental.\n'
732
             '\n'
733
             'Please keep a copy of your memories with the original software '
734
             'if you treasure them, this driver is new and may contain'
735
             ' bugs.\n'
736
             '\n'
737
             )
738
        rp.pre_download = _(dedent("""\
739
            Follow these instructions to download your info:
740

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

    
746
            """))
747
        rp.pre_upload = _(dedent("""\
748
            Follow these instructions to upload your info:
749

    
750
            1 - Turn off your radio
751
            2 - Connect your interface cable
752
            3 - Turn on your radio
753
            4 - Do the upload of your radio data
754

    
755
            """))
756
        return rp
757

    
758
    def get_features(self):
759
        """Get the radio's features"""
760

    
761
        # we will use the following var as global
762
        global POWER_LEVELS
763

    
764
        rf = chirp_common.RadioFeatures()
765
        rf.has_settings = True
766
        rf.has_bank = False
767
        rf.has_tuning_step = False
768
        rf.can_odd_split = True
769
        rf.has_name = True
770
        rf.has_offset = True
771
        rf.has_mode = True
772
        rf.has_dtcs = True
773
        rf.has_rx_dtcs = True
774
        rf.has_dtcs_polarity = True
775
        rf.has_ctone = True
776
        rf.has_cross = True
777
        rf.valid_modes = MODES
778
        rf.valid_characters = VALID_CHARS
779
        rf.valid_name_length = self.NAME_LENGTH
780
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
781
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
782
        rf.valid_cross_modes = [
783
            "Tone->Tone",
784
            "DTCS->",
785
            "->DTCS",
786
            "Tone->DTCS",
787
            "DTCS->Tone",
788
            "->Tone",
789
            "DTCS->DTCS"]
790
        rf.valid_skips = SKIP_VALUES
791
        rf.valid_dtcs_codes = DTCS
792
        rf.valid_tuning_steps = STEPS
793
        rf.memory_bounds = (0, self._upper)
794

    
795
        # power levels
796
        POWER_LEVELS = self._power_levels
797
        rf.valid_power_levels = POWER_LEVELS
798

    
799
        # normal dual bands
800
        rf.valid_bands = [self._vhf_range, self._uhf_range]
801

    
802
        # 220 band
803
        if self.BANDS == 3 or self.BANDS == 4:
804
            rf.valid_bands.append(self._220_range)
805

    
806
        # 350 band
807
        if self.BANDS == 4:
808
            rf.valid_bands.append(self._350_range)
809

    
810
        return rf
811

    
812
    def validate_memory(self, mem):
813
        msgs = chirp_common.CloneModeRadio.validate_memory(self, mem)
814

    
815
        _msg_duplex1 = 'Memory location only supports "Low"'
816
        _msg_duplex2 = 'Memory location only supports "off"'
817
        _msg_duplex3 = 'Memory location only supports "(None)", "+" or "off"'
818

    
819
        if self._gmrs:
820
            if mem.number < 1 or mem.number > 30:
821
                if float(mem.freq) / 1000000 in GMRS_FREQS1:
822
                    if mem.duplex not in ['', 'off']:
823
                        # warn user wrong Duplex
824
                        msgs.append(chirp_common.ValidationError(_msg_duplex2))
825
                    if mem.power != self._power_levels[2]:
826
                        # warn user wrong Duplex
827
                        msgs.append(chirp_common.ValidationError(_msg_duplex1))
828

    
829
                if float(mem.freq) / 1000000 in GMRS_FREQS2:
830
                    if mem.duplex not in ['off', ]:
831
                        # warn user wrong Duplex
832
                        msgs.append(chirp_common.ValidationError(_msg_duplex2))
833

    
834
                if float(mem.freq) / 1000000 in GMRS_FREQS3:
835
                    if mem.duplex not in ['', '+', 'off']:
836
                        # warn user wrong Duplex
837
                        msgs.append(chirp_common.ValidationError(_msg_duplex3))
838

    
839
        return msgs
840

    
841
    def sync_in(self):
842
        """Download from radio"""
843
        data = _download(self)
844
        self._mmap = memmap.MemoryMap(data)
845
        self.process_mmap()
846

    
847
    def sync_out(self):
848
        """Upload to radio"""
849
        try:
850
            _upload(self)
851
        except errors.RadioError:
852
            raise
853
        except Exception, e:
854
            raise errors.RadioError("Error: %s" % e)
855

    
856
    def get_raw_memory(self, number):
857
        return repr(self._memobj.memory[number])
858

    
859
    def _decode_tone(self, val):
860
        """Parse the tone data to decode from mem, it returns:
861
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
862
        pol = None
863

    
864
        if val in [0, 65535]:
865
            return '', None, None
866
        elif val > 0x0258:
867
            a = val / 10.0
868
            return 'Tone', a, pol
869
        else:
870
            if val > 0x69:
871
                index = val - 0x6A
872
                pol = "R"
873
            else:
874
                index = val - 1
875
                pol = "N"
876

    
877
            tone = DTCS[index]
878
            return 'DTCS', tone, pol
879

    
880
    def _encode_tone(self, memval, mode, val, pol):
881
        """Parse the tone data to encode from UI to mem"""
882
        if mode == '' or mode is None:
883
            memval.set_raw("\x00\x00")
884
        elif mode == 'Tone':
885
            memval.set_value(val * 10)
886
        elif mode == 'DTCS':
887
            # detect the index in the DTCS list
888
            try:
889
                index = DTCS.index(val)
890
                if pol == "N":
891
                    index += 1
892
                else:
893
                    index += 0x6A
894
                memval.set_value(index)
895
            except:
896
                msg = "Digital Tone '%d' is not supported" % value
897
                LOG.error(msg)
898
                raise errors.RadioError(msg)
899
        else:
900
            msg = "Internal error: invalid mode '%s'" % mode
901
            LOG.error(msg)
902
            raise errors.InvalidDataError(msg)
903

    
904
    def get_memory(self, number):
905
        """Get the mem representation from the radio image"""
906
        _mem = self._memobj.memory[number]
907
        _names = self._memobj.names[number]
908

    
909
        # Create a high-level memory object to return to the UI
910
        mem = chirp_common.Memory()
911

    
912
        # Memory number
913
        mem.number = number
914

    
915
        if _mem.get_raw()[0] == "\xFF":
916
            mem.empty = True
917
            return mem
918

    
919
        # Freq and offset
920
        mem.freq = int(_mem.rxfreq) * 10
921
        # tx freq can be blank
922
        if _mem.get_raw()[4] == "\xFF":
923
            # TX freq not set
924
            mem.offset = 0
925
            mem.duplex = "off"
926
        else:
927
            # TX freq set
928
            offset = (int(_mem.txfreq) * 10) - mem.freq
929
            if offset != 0:
930
                if _split(self.get_features(), mem.freq, int(
931
                          _mem.txfreq) * 10):
932
                    mem.duplex = "split"
933
                    mem.offset = int(_mem.txfreq) * 10
934
                elif offset < 0:
935
                    mem.offset = abs(offset)
936
                    mem.duplex = "-"
937
                elif offset > 0:
938
                    mem.offset = offset
939
                    mem.duplex = "+"
940
            else:
941
                mem.offset = 0
942

    
943
        # name TAG of the channel
944
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
945

    
946
        # power
947
        mem.power = POWER_LEVELS[int(_mem.power)]
948

    
949
        # wide/narrow
950
        mem.mode = MODES[int(_mem.wide)]
951

    
952
        # skip
953
        mem.skip = SKIP_VALUES[_mem.add]
954

    
955
        # tone data
956
        rxtone = txtone = None
957
        txtone = self._decode_tone(_mem.txtone)
958
        rxtone = self._decode_tone(_mem.rxtone)
959
        chirp_common.split_tone_decode(mem, txtone, rxtone)
960

    
961
        # Extra
962
        mem.extra = RadioSettingGroup("extra", "Extra")
963

    
964
        if not self.COLOR_LCD or \
965
                (self.COLOR_LCD and not self.VENDOR == "BTECH"):
966
            scramble = RadioSetting("scramble", "Scramble",
967
                                    RadioSettingValueBoolean(bool(
968
                                        _mem.scramble)))
969
            mem.extra.append(scramble)
970

    
971
        bcl = RadioSetting("bcl", "Busy channel lockout",
972
                           RadioSettingValueBoolean(bool(_mem.bcl)))
973
        mem.extra.append(bcl)
974

    
975
        pttid = RadioSetting("pttid", "PTT ID",
976
                             RadioSettingValueList(PTTID_LIST,
977
                                                   PTTID_LIST[_mem.pttid]))
978
        mem.extra.append(pttid)
979

    
980
        # validating scode
981
        scode = _mem.scode if _mem.scode != 15 else 0
982
        pttidcode = RadioSetting("scode", "PTT ID signal code",
983
                                 RadioSettingValueList(
984
                                     PTTIDCODE_LIST,
985
                                     PTTIDCODE_LIST[scode]))
986
        mem.extra.append(pttidcode)
987

    
988
        optsig = RadioSetting("optsig", "Optional signaling",
989
                              RadioSettingValueList(
990
                                  OPTSIG_LIST,
991
                                  OPTSIG_LIST[_mem.optsig]))
992
        mem.extra.append(optsig)
993

    
994
        spmute = RadioSetting("spmute", "Speaker mute",
995
                              RadioSettingValueList(
996
                                  SPMUTE_LIST,
997
                                  SPMUTE_LIST[_mem.spmute]))
998
        mem.extra.append(spmute)
999

    
1000
        return mem
1001

    
1002
    def set_memory(self, mem):
1003
        """Set the memory data in the eeprom img from the UI"""
1004
        # get the eprom representation of this channel
1005
        _mem = self._memobj.memory[mem.number]
1006
        _names = self._memobj.names[mem.number]
1007

    
1008
        mem_was_empty = False
1009
        # same method as used in get_memory for determining if mem is empty
1010
        # doing this BEFORE overwriting it with new values ...
1011
        if _mem.get_raw()[0] == "\xFF":
1012
            LOG.debug("This mem was empty before")
1013
            mem_was_empty = True
1014

    
1015
        # if empty memmory
1016
        if mem.empty:
1017
            # the channel itself
1018
            _mem.set_raw("\xFF" * 16)
1019
            # the name tag
1020
            _names.set_raw("\xFF" * 16)
1021
            return
1022

    
1023
        if mem_was_empty:
1024
            # Zero the whole memory if we're making it unempty for
1025
            # the first time
1026
            LOG.debug('Zeroing new memory')
1027
            _mem.set_raw('\x00' * 16)
1028

    
1029
        if self._gmrs:
1030
            if mem.number >= 1 and mem.number <= 30:
1031
                GMRS_FREQ = int(GMRS_FREQS[mem.number - 1] * 1000000)
1032
                mem.freq = GMRS_FREQ
1033
                if mem.number <= 22:
1034
                    mem.duplex = ''
1035
                    mem.offset = 0
1036
                    if mem.number <= 7:
1037
                        mem.power = self._power_levels[2]
1038
                    if mem.number >= 8 and mem.number <= 14:
1039
                        mem.duplex = 'off'
1040
                        mem.mode = "NFM"
1041
                        mem.power = self._power_levels[2]
1042
                if mem.number > 22:
1043
                    mem.duplex = '+'
1044
                    mem.offset = 5000000
1045
            elif float(mem.freq) / 1000000 in GMRS_FREQS:
1046
                if float(mem.freq) / 1000000 in GMRS_FREQS1:
1047
                    mem.duplex = ''
1048
                    mem.offset = 0
1049
                    ##mem.mode = "NFM"
1050
                    mem.power = self._power_levels[2]
1051
                if float(mem.freq) / 1000000 in GMRS_FREQS2:
1052
                    mem.duplex = 'off'
1053
                    mem.offset = 0
1054
                    mem.mode = "NFM"
1055
                    mem.power = self._power_levels[2]
1056
                if float(mem.freq) / 1000000 in GMRS_FREQS3:
1057
                    if mem.duplex == '+':
1058
                        mem.offset = 5000000
1059
                    else:
1060
                        mem.offset = 0
1061
            else:
1062
                mem.duplex = 'off'
1063
                mem.offset = 0
1064

    
1065
        # frequency
1066
        _mem.rxfreq = mem.freq / 10
1067

    
1068
        # duplex
1069
        if mem.duplex == "+":
1070
            _mem.txfreq = (mem.freq + mem.offset) / 10
1071
        elif mem.duplex == "-":
1072
            _mem.txfreq = (mem.freq - mem.offset) / 10
1073
        elif mem.duplex == "off":
1074
            for i in _mem.txfreq:
1075
                i.set_raw("\xFF")
1076
        elif mem.duplex == "split":
1077
            _mem.txfreq = mem.offset / 10
1078
        else:
1079
            _mem.txfreq = mem.freq / 10
1080

    
1081
        # tone data
1082
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1083
            chirp_common.split_tone_encode(mem)
1084
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1085
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1086

    
1087
        # name TAG of the channel
1088
        if len(mem.name) < self.NAME_LENGTH:
1089
            # we must pad to self.NAME_LENGTH chars, " " = "\xFF"
1090
            mem.name = str(mem.name).ljust(self.NAME_LENGTH, " ")
1091
        _names.name = str(mem.name).replace(" ", "\xFF")
1092

    
1093
        # power, # default power level is high
1094
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1095

    
1096
        # wide/narrow
1097
        _mem.wide = MODES.index(mem.mode)
1098

    
1099
        # scan add property
1100
        _mem.add = SKIP_VALUES.index(mem.skip)
1101

    
1102
        # reseting unknowns, this have to be set by hand
1103
        _mem.unknown0 = 0
1104
        _mem.unknown1 = 0
1105
        _mem.unknown2 = 0
1106
        _mem.unknown3 = 0
1107
        _mem.unknown4 = 0
1108
        _mem.unknown5 = 0
1109
        _mem.unknown6 = 0
1110

    
1111
        def _zero_settings():
1112
            _mem.spmute = 0
1113
            _mem.optsig = 0
1114
            _mem.scramble = 0
1115
            _mem.bcl = 0
1116
            _mem.pttid = 0
1117
            _mem.scode = 0
1118

    
1119
        if self.COLOR_LCD and _mem.scramble:
1120
            LOG.info('Resetting scramble bit for BTECH COLOR_LCD variant')
1121
            _mem.scramble = 0
1122

    
1123
        # extra settings
1124
        if len(mem.extra) > 0:
1125
            # there are setting, parse
1126
            LOG.debug("Extra-Setting supplied. Setting them.")
1127
            # Zero them all first so any not provided by model don't
1128
            # stay set
1129
            _zero_settings()
1130
            for setting in mem.extra:
1131
                setattr(_mem, setting.get_name(), setting.value)
1132
        else:
1133
            if mem.empty:
1134
                LOG.debug("New mem is empty.")
1135
            else:
1136
                LOG.debug("New mem is NOT empty")
1137
                # set extra-settings to default ONLY when apreviously empty or
1138
                # deleted memory was edited to prevent errors such as #4121
1139
                if mem_was_empty:
1140
                    LOG.debug("old mem was empty. Setting default for extras.")
1141
                    _zero_settings()
1142

    
1143
        return mem
1144

    
1145
    def get_settings(self):
1146
        """Translate the bit in the mem_struct into settings in the UI"""
1147
        _mem = self._memobj
1148
        basic = RadioSettingGroup("basic", "Basic Settings")
1149
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1150
        other = RadioSettingGroup("other", "Other Settings")
1151
        work = RadioSettingGroup("work", "Work Mode Settings")
1152
        top = RadioSettings(basic, advanced, other, work)
1153

    
1154
        # Basic
1155
        if self.COLOR_LCD:
1156
            tmr = RadioSetting("settings.tmr", "Transceiver multi-receive",
1157
                               RadioSettingValueList(
1158
                                   self.LIST_TMR,
1159
                                   self.LIST_TMR[_mem.settings.tmr]))
1160
            basic.append(tmr)
1161
        else:
1162
            tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1163
                               RadioSettingValueBoolean(_mem.settings.tdr))
1164
            basic.append(tdr)
1165

    
1166
        sql = RadioSetting("settings.sql", "Squelch level",
1167
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1168
        basic.append(sql)
1169

    
1170
        if self.MODEL == "GMRS-50X1":
1171
            autolk = RadioSetting("settings.autolk", "Auto keylock",
1172
                                  RadioSettingValueBoolean(
1173
                                      _mem.settings.autolk))
1174
            basic.append(autolk)
1175

    
1176
        if self.MODEL == "DB25-G":
1177
            mgain2 = RadioSetting("settings.mgain2", "Mic gain",
1178
                                  RadioSettingValueInteger(0, 127,
1179
                                                           _mem.settings.mgain2))
1180
            basic.append(mgain2)
1181

    
1182
        tot = RadioSetting("settings.tot", "Time out timer",
1183
                           RadioSettingValueList(
1184
                               LIST_TOT,
1185
                               LIST_TOT[_mem.settings.tot]))
1186
        basic.append(tot)
1187

    
1188
        if self.MODEL == "KT-8R":
1189
                save = RadioSetting("settings.save", "Battery Save",
1190
                                    RadioSettingValueBoolean(
1191
                                        _mem.settings.save))
1192
                basic.append(save)
1193

    
1194
        if not self.MODEL == "KT-8R":
1195
            if self.VENDOR == "BTECH" or self.COLOR_LCD:
1196
                apo = RadioSetting("settings.apo", "Auto power off timer",
1197
                                   RadioSettingValueList(
1198
                                       LIST_APO,
1199
                                       LIST_APO[_mem.settings.apo]))
1200
                basic.append(apo)
1201
            else:
1202
                toa = RadioSetting("settings.apo", "Time out alert timer",
1203
                                   RadioSettingValueList(
1204
                                       LIST_OFF1TO10,
1205
                                       LIST_OFF1TO10[_mem.settings.apo]))
1206
                basic.append(toa)
1207

    
1208
        abr = RadioSetting("settings.abr", "Backlight timer",
1209
                           RadioSettingValueList(
1210
                               LIST_OFF1TO50,
1211
                               LIST_OFF1TO50[_mem.settings.abr]))
1212
        basic.append(abr)
1213

    
1214
        beep = RadioSetting("settings.beep", "Key beep",
1215
                            RadioSettingValueBoolean(_mem.settings.beep))
1216
        basic.append(beep)
1217

    
1218
        if self.MODEL == "KT-8R":
1219
                dsub = RadioSetting("settings.dsub", "CTCSS/DCS code display",
1220
                                    RadioSettingValueBoolean(
1221
                                        _mem.settings.dsub))
1222
                basic.append(dsub)
1223

    
1224
        if self.MODEL == "KT-8R":
1225
                dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1226
                                      RadioSettingValueBoolean(
1227
                                          _mem.settings.dtmfst))
1228
                basic.append(dtmfst)
1229
        else:
1230
            dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1231
                                  RadioSettingValueList(
1232
                                      LIST_DTMFST,
1233
                                      LIST_DTMFST[_mem.settings.dtmfst]))
1234
            basic.append(dtmfst)
1235

    
1236
        if not self.COLOR_LCD:
1237
            prisc = RadioSetting("settings.prisc", "Priority scan",
1238
                                 RadioSettingValueBoolean(
1239
                                     _mem.settings.prisc))
1240
            basic.append(prisc)
1241

    
1242
            prich = RadioSetting("settings.prich", "Priority channel",
1243
                                 RadioSettingValueInteger(0, self._upper,
1244
                                                          _mem.settings.prich))
1245
            basic.append(prich)
1246

    
1247
        screv = RadioSetting("settings.screv", "Scan resume method",
1248
                             RadioSettingValueList(
1249
                                 LIST_SCREV,
1250
                                 LIST_SCREV[_mem.settings.screv]))
1251
        basic.append(screv)
1252

    
1253
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1254
                             RadioSettingValueInteger(0, 30,
1255
                                                      _mem.settings.pttlt))
1256
        basic.append(pttlt)
1257

    
1258
        if self.VENDOR == "BTECH" and self.COLOR_LCD:
1259
            emctp = RadioSetting("settings.emctp", "Alarm mode",
1260
                                 RadioSettingValueList(
1261
                                     LIST_EMCTPX,
1262
                                     LIST_EMCTPX[_mem.settings.emctp]))
1263
            basic.append(emctp)
1264
        else:
1265
            emctp = RadioSetting("settings.emctp", "Alarm mode",
1266
                                 RadioSettingValueList(
1267
                                     LIST_EMCTP,
1268
                                     LIST_EMCTP[_mem.settings.emctp]))
1269
            basic.append(emctp)
1270

    
1271
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1272
                             RadioSettingValueInteger(0, self._upper,
1273
                                                      _mem.settings.emcch))
1274
        basic.append(emcch)
1275

    
1276
        if self.COLOR_LCD:
1277
            if _mem.settings.sigbp > 0x01:
1278
                val = 0x00
1279
            else:
1280
                val = _mem.settings.sigbp
1281
            sigbp = RadioSetting("settings.sigbp", "Signal beep",
1282
                                 RadioSettingValueBoolean(val))
1283
            basic.append(sigbp)
1284
        else:
1285
            ringt = RadioSetting("settings.ringt", "Ring time",
1286
                                 RadioSettingValueList(
1287
                                     LIST_OFF1TO9,
1288
                                     LIST_OFF1TO9[_mem.settings.ringt]))
1289
            basic.append(ringt)
1290

    
1291
        camdf = RadioSetting("settings.camdf", "Display mode A",
1292
                             RadioSettingValueList(
1293
                                 LIST_MDF,
1294
                                 LIST_MDF[_mem.settings.camdf]))
1295
        basic.append(camdf)
1296

    
1297
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1298
                             RadioSettingValueList(
1299
                                 LIST_MDF,
1300
                                 LIST_MDF[_mem.settings.cbmdf]))
1301
        basic.append(cbmdf)
1302

    
1303
        if self.COLOR_LCD:
1304
            ccmdf = RadioSetting("settings.ccmdf", "Display mode C",
1305
                                 RadioSettingValueList(
1306
                                     LIST_MDF,
1307
                                     LIST_MDF[_mem.settings.ccmdf]))
1308
            basic.append(ccmdf)
1309

    
1310
            cdmdf = RadioSetting("settings.cdmdf", "Display mode D",
1311
                                 RadioSettingValueList(
1312
                                     LIST_MDF,
1313
                                     LIST_MDF[_mem.settings.cdmdf]))
1314
            basic.append(cdmdf)
1315

    
1316
            langua = RadioSetting("settings.langua", "Language",
1317
                                  RadioSettingValueList(
1318
                                      LIST_LANGUA,
1319
                                      LIST_LANGUA[_mem.settings.langua]))
1320
            basic.append(langua)
1321

    
1322
        if self.MODEL == "KT-8R":
1323
            voice = RadioSetting("settings.voice", "Voice prompt",
1324
                                 RadioSettingValueList(
1325
                                     LIST_VOICE,
1326
                                     LIST_VOICE[_mem.settings.voice]))
1327
            basic.append(voice)
1328

    
1329
            vox = RadioSetting("settings.vox", "VOX",
1330
                               RadioSettingValueList(
1331
                                   LIST_VOX,
1332
                                   LIST_VOX[_mem.settings.vox]))
1333
            basic.append(vox)
1334

    
1335
            voxt = RadioSetting("settings.voxt", "VOX delay time",
1336
                                RadioSettingValueList(
1337
                                    LIST_VOXT,
1338
                                    LIST_VOXT[_mem.settings.voxt]))
1339
            basic.append(voxt)
1340

    
1341
        if self.VENDOR == "BTECH":
1342
            if self.COLOR_LCD:
1343
                sync = RadioSetting("settings.sync", "Channel display sync",
1344
                                    RadioSettingValueList(
1345
                                        LIST_SYNC,
1346
                                        LIST_SYNC[_mem.settings.sync]))
1347
                basic.append(sync)
1348
            else:
1349
                sync = RadioSetting("settings.sync", "A/B channel sync",
1350
                                    RadioSettingValueBoolean(
1351
                                        _mem.settings.sync))
1352
                basic.append(sync)
1353
        else:
1354
            autolk = RadioSetting("settings.sync", "Auto keylock",
1355
                                  RadioSettingValueBoolean(
1356
                                      _mem.settings.sync))
1357
            basic.append(autolk)
1358

    
1359
        if not self.COLOR_LCD:
1360
            ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1361
                                  RadioSettingValueList(
1362
                                      LIST_PONMSG,
1363
                                      LIST_PONMSG[_mem.settings.ponmsg]))
1364
            basic.append(ponmsg)
1365

    
1366
        if self.COLOR_LCD and not (self.COLOR_LCD2 or self.COLOR_LCD3):
1367
            mainfc = RadioSetting("settings.mainfc",
1368
                                  "Main LCD foreground color",
1369
                                  RadioSettingValueList(
1370
                                      LIST_COLOR9,
1371
                                      LIST_COLOR9[_mem.settings.mainfc]))
1372
            basic.append(mainfc)
1373

    
1374
            mainbc = RadioSetting("settings.mainbc",
1375
                                  "Main LCD background color",
1376
                                  RadioSettingValueList(
1377
                                      LIST_COLOR9,
1378
                                      LIST_COLOR9[_mem.settings.mainbc]))
1379
            basic.append(mainbc)
1380

    
1381
            menufc = RadioSetting("settings.menufc", "Menu foreground color",
1382
                                  RadioSettingValueList(
1383
                                      LIST_COLOR9,
1384
                                      LIST_COLOR9[_mem.settings.menufc]))
1385
            basic.append(menufc)
1386

    
1387
            menubc = RadioSetting("settings.menubc", "Menu background color",
1388
                                  RadioSettingValueList(
1389
                                      LIST_COLOR9,
1390
                                      LIST_COLOR9[_mem.settings.menubc]))
1391
            basic.append(menubc)
1392

    
1393
            stafc = RadioSetting("settings.stafc",
1394
                                 "Top status foreground color",
1395
                                 RadioSettingValueList(
1396
                                     LIST_COLOR9,
1397
                                     LIST_COLOR9[_mem.settings.stafc]))
1398
            basic.append(stafc)
1399

    
1400
            stabc = RadioSetting("settings.stabc",
1401
                                 "Top status background color",
1402
                                 RadioSettingValueList(
1403
                                     LIST_COLOR9,
1404
                                     LIST_COLOR9[_mem.settings.stabc]))
1405
            basic.append(stabc)
1406

    
1407
            sigfc = RadioSetting("settings.sigfc",
1408
                                 "Bottom status foreground color",
1409
                                 RadioSettingValueList(
1410
                                     LIST_COLOR9,
1411
                                     LIST_COLOR9[_mem.settings.sigfc]))
1412
            basic.append(sigfc)
1413

    
1414
            sigbc = RadioSetting("settings.sigbc",
1415
                                 "Bottom status background color",
1416
                                 RadioSettingValueList(
1417
                                     LIST_COLOR9,
1418
                                     LIST_COLOR9[_mem.settings.sigbc]))
1419
            basic.append(sigbc)
1420

    
1421
            rxfc = RadioSetting("settings.rxfc", "Receiving character color",
1422
                                RadioSettingValueList(
1423
                                    LIST_COLOR9,
1424
                                    LIST_COLOR9[_mem.settings.rxfc]))
1425
            basic.append(rxfc)
1426

    
1427
            txfc = RadioSetting("settings.txfc",
1428
                                "Transmitting character color",
1429
                                RadioSettingValueList(
1430
                                    LIST_COLOR9,
1431
                                    LIST_COLOR9[_mem.settings.txfc]))
1432
            basic.append(txfc)
1433

    
1434
            txdisp = RadioSetting("settings.txdisp",
1435
                                  "Transmitting status display",
1436
                                  RadioSettingValueList(
1437
                                      LIST_TXDISP,
1438
                                      LIST_TXDISP[_mem.settings.txdisp]))
1439
            basic.append(txdisp)
1440
        elif self.COLOR_LCD2 or self.COLOR_LCD3:
1441
            stfc = RadioSetting("settings.stfc",
1442
                                "ST-FC",
1443
                                RadioSettingValueList(
1444
                                    LIST_COLOR8,
1445
                                    LIST_COLOR8[_mem.settings.stfc]))
1446
            basic.append(stfc)
1447

    
1448
            mffc = RadioSetting("settings.mffc",
1449
                                "MF-FC",
1450
                                RadioSettingValueList(
1451
                                    LIST_COLOR8,
1452
                                    LIST_COLOR8[_mem.settings.mffc]))
1453
            basic.append(mffc)
1454

    
1455
            sfafc = RadioSetting("settings.sfafc",
1456
                                 "SFA-FC",
1457
                                 RadioSettingValueList(
1458
                                     LIST_COLOR8,
1459
                                     LIST_COLOR8[_mem.settings.sfafc]))
1460
            basic.append(sfafc)
1461

    
1462
            sfbfc = RadioSetting("settings.sfbfc",
1463
                                 "SFB-FC",
1464
                                 RadioSettingValueList(
1465
                                     LIST_COLOR8,
1466
                                     LIST_COLOR8[_mem.settings.sfbfc]))
1467
            basic.append(sfbfc)
1468

    
1469
            sfcfc = RadioSetting("settings.sfcfc",
1470
                                 "SFC-FC",
1471
                                 RadioSettingValueList(
1472
                                     LIST_COLOR8,
1473
                                     LIST_COLOR8[_mem.settings.sfcfc]))
1474
            basic.append(sfcfc)
1475

    
1476
            sfdfc = RadioSetting("settings.sfdfc",
1477
                                 "SFD-FC",
1478
                                 RadioSettingValueList(
1479
                                     LIST_COLOR8,
1480
                                     LIST_COLOR8[_mem.settings.sfdfc]))
1481
            basic.append(sfdfc)
1482

    
1483
            subfc = RadioSetting("settings.subfc",
1484
                                 "SUB-FC",
1485
                                 RadioSettingValueList(
1486
                                     LIST_COLOR8,
1487
                                     LIST_COLOR8[_mem.settings.subfc]))
1488
            basic.append(subfc)
1489

    
1490
            fmfc = RadioSetting("settings.fmfc",
1491
                                "FM-FC",
1492
                                RadioSettingValueList(
1493
                                    LIST_COLOR8,
1494
                                    LIST_COLOR8[_mem.settings.fmfc]))
1495
            basic.append(fmfc)
1496

    
1497
            sigfc = RadioSetting("settings.sigfc",
1498
                                 "SIG-FC",
1499
                                 RadioSettingValueList(
1500
                                     LIST_COLOR8,
1501
                                     LIST_COLOR8[_mem.settings.sigfc]))
1502
            basic.append(sigfc)
1503

    
1504
            if not self.MODEL == "KT-8R":
1505
                modfc = RadioSetting("settings.modfc",
1506
                                     "MOD-FC",
1507
                                     RadioSettingValueList(
1508
                                         LIST_COLOR8,
1509
                                         LIST_COLOR8[_mem.settings.modfc]))
1510
                basic.append(modfc)
1511

    
1512
            menufc = RadioSetting("settings.menufc",
1513
                                  "MENUFC",
1514
                                  RadioSettingValueList(
1515
                                      LIST_COLOR8,
1516
                                      LIST_COLOR8[_mem.settings.menufc]))
1517
            basic.append(menufc)
1518

    
1519
            txfc = RadioSetting("settings.txfc",
1520
                                "TX-FC",
1521
                                RadioSettingValueList(
1522
                                    LIST_COLOR8,
1523
                                    LIST_COLOR8[_mem.settings.txfc]))
1524
            basic.append(txfc)
1525

    
1526
            if self.MODEL == "KT-8R":
1527
                rxfc = RadioSetting("settings.rxfc",
1528
                                    "RX-FC",
1529
                                    RadioSettingValueList(
1530
                                        LIST_COLOR8,
1531
                                        LIST_COLOR8[_mem.settings.rxfc]))
1532
                basic.append(rxfc)
1533

    
1534
            if not self.MODEL == "KT-8R":
1535
                txdisp = RadioSetting("settings.txdisp",
1536
                                      "Transmitting status display",
1537
                                      RadioSettingValueList(
1538
                                          LIST_TXDISP,
1539
                                          LIST_TXDISP[_mem.settings.txdisp]))
1540
                basic.append(txdisp)
1541
        else:
1542
            wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1543
                                 RadioSettingValueList(
1544
                                     LIST_COLOR4,
1545
                                     LIST_COLOR4[_mem.settings.wtled]))
1546
            basic.append(wtled)
1547

    
1548
            rxled = RadioSetting("settings.rxled", "RX backlight Color",
1549
                                 RadioSettingValueList(
1550
                                     LIST_COLOR4,
1551
                                     LIST_COLOR4[_mem.settings.rxled]))
1552
            basic.append(rxled)
1553

    
1554
            txled = RadioSetting("settings.txled", "TX backlight Color",
1555
                                 RadioSettingValueList(
1556
                                     LIST_COLOR4,
1557
                                     LIST_COLOR4[_mem.settings.txled]))
1558
            basic.append(txled)
1559

    
1560
        anil = RadioSetting("settings.anil", "ANI length",
1561
                            RadioSettingValueList(
1562
                                LIST_ANIL,
1563
                                LIST_ANIL[_mem.settings.anil]))
1564
        basic.append(anil)
1565

    
1566
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1567
                            RadioSettingValueList(
1568
                                LIST_REPS,
1569
                                LIST_REPS[_mem.settings.reps]))
1570
        basic.append(reps)
1571

    
1572
        if not self.MODEL == "GMRS-50X1" and not self.MODEL == "KT-8R":
1573
            repm = RadioSetting("settings.repm", "Relay condition",
1574
                                RadioSettingValueList(
1575
                                    LIST_REPM,
1576
                                    LIST_REPM[_mem.settings.repm]))
1577
            basic.append(repm)
1578

    
1579
        if self.VENDOR == "BTECH" or self.COLOR_LCD:
1580
            if self.COLOR_LCD:
1581
                tmrmr = RadioSetting("settings.tmrmr", "TMR return time",
1582
                                     RadioSettingValueList(
1583
                                         LIST_OFF1TO50,
1584
                                         LIST_OFF1TO50[_mem.settings.tmrmr]))
1585
                basic.append(tmrmr)
1586
            else:
1587
                tdrab = RadioSetting("settings.tdrab", "TDR return time",
1588
                                     RadioSettingValueList(
1589
                                         LIST_OFF1TO50,
1590
                                         LIST_OFF1TO50[_mem.settings.tdrab]))
1591
                basic.append(tdrab)
1592

    
1593
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1594
                               RadioSettingValueBoolean(_mem.settings.ste))
1595
            basic.append(ste)
1596

    
1597
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1598
                                 RadioSettingValueList(
1599
                                     LIST_OFF1TO9,
1600
                                     LIST_OFF1TO9[_mem.settings.rpste]))
1601
            basic.append(rpste)
1602

    
1603
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1604
                                 RadioSettingValueList(
1605
                                     LIST_RPTDL,
1606
                                     LIST_RPTDL[_mem.settings.rptdl]))
1607
            basic.append(rptdl)
1608

    
1609
        if self.MODEL == "DB25-G":
1610
            mgain = RadioSetting("settings.mgain", "Auto power-on",
1611
                                 RadioSettingValueBoolean(_mem.settings.mgain))
1612
            basic.append(mgain)
1613

    
1614
        if str(_mem.fingerprint.fp) in BTECH3:
1615
            mgain = RadioSetting("settings.mgain", "Mic gain",
1616
                                 RadioSettingValueInteger(0, 120,
1617
                                                          _mem.settings.mgain))
1618
            basic.append(mgain)
1619

    
1620
        if str(_mem.fingerprint.fp) in BTECH3 or self.COLOR_LCD:
1621
            dtmfg = RadioSetting("settings.dtmfg", "DTMF gain",
1622
                                 RadioSettingValueInteger(0, 60,
1623
                                                          _mem.settings.dtmfg))
1624
            basic.append(dtmfg)
1625

    
1626
        if self.VENDOR == "BTECH" and self.COLOR_LCD:
1627
            mgain = RadioSetting("settings.mgain", "Mic gain",
1628
                                 RadioSettingValueInteger(0, 120,
1629
                                                          _mem.settings.mgain))
1630
            basic.append(mgain)
1631

    
1632
            skiptx = RadioSetting("settings.skiptx", "Skip TX",
1633
                                  RadioSettingValueList(
1634
                                      LIST_SKIPTX,
1635
                                      LIST_SKIPTX[_mem.settings.skiptx]))
1636
            basic.append(skiptx)
1637

    
1638
            scmode = RadioSetting("settings.scmode", "Scan mode",
1639
                                  RadioSettingValueList(
1640
                                      LIST_SCMODE,
1641
                                      LIST_SCMODE[_mem.settings.scmode]))
1642
            basic.append(scmode)
1643

    
1644
        if self.MODEL == "KT-8R":
1645
            tmrtx = RadioSetting("settings.tmrtx", "TX in multi-standby",
1646
                                 RadioSettingValueList(
1647
                                     LIST_TMRTX,
1648
                                     LIST_TMRTX[_mem.settings.tmrtx]))
1649
            basic.append(tmrtx)
1650

    
1651
        # Advanced
1652
        def _filter(name):
1653
            filtered = ""
1654
            for char in str(name):
1655
                if char in VALID_CHARS:
1656
                    filtered += char
1657
                else:
1658
                    filtered += " "
1659
            return filtered
1660

    
1661
        if self.COLOR_LCD and not (self.COLOR_LCD2 or self.COLOR_LCD3):
1662
            _msg = self._memobj.poweron_msg
1663
            line1 = RadioSetting("poweron_msg.line1",
1664
                                 "Power-on message line 1",
1665
                                 RadioSettingValueString(0, 8, _filter(
1666
                                                         _msg.line1)))
1667
            advanced.append(line1)
1668
            line2 = RadioSetting("poweron_msg.line2",
1669
                                 "Power-on message line 2",
1670
                                 RadioSettingValueString(0, 8, _filter(
1671
                                                         _msg.line2)))
1672
            advanced.append(line2)
1673
            line3 = RadioSetting("poweron_msg.line3",
1674
                                 "Power-on message line 3",
1675
                                 RadioSettingValueString(0, 8, _filter(
1676
                                                         _msg.line3)))
1677
            advanced.append(line3)
1678
            line4 = RadioSetting("poweron_msg.line4",
1679
                                 "Power-on message line 4",
1680
                                 RadioSettingValueString(0, 8, _filter(
1681
                                                         _msg.line4)))
1682
            advanced.append(line4)
1683
            line5 = RadioSetting("poweron_msg.line5",
1684
                                 "Power-on message line 5",
1685
                                 RadioSettingValueString(0, 8, _filter(
1686
                                                         _msg.line5)))
1687
            advanced.append(line5)
1688
            line6 = RadioSetting("poweron_msg.line6",
1689
                                 "Power-on message line 6",
1690
                                 RadioSettingValueString(0, 8, _filter(
1691
                                                         _msg.line6)))
1692
            advanced.append(line6)
1693
            line7 = RadioSetting("poweron_msg.line7",
1694
                                 "Power-on message line 7",
1695
                                 RadioSettingValueString(0, 8, _filter(
1696
                                                         _msg.line7)))
1697
            advanced.append(line7)
1698
            line8 = RadioSetting("poweron_msg.line8", "Static message",
1699
                                 RadioSettingValueString(0, 8, _filter(
1700
                                                         _msg.line8)))
1701
            advanced.append(line8)
1702
        elif self.COLOR_LCD2 or self.COLOR_LCD3:
1703
            _msg = self._memobj.static_msg
1704
            line = RadioSetting("static_msg.line", "Static message",
1705
                                RadioSettingValueString(0, 16, _filter(
1706
                                    _msg.line)))
1707
            advanced.append(line)
1708
        else:
1709
            _msg = self._memobj.poweron_msg
1710
            line1 = RadioSetting("poweron_msg.line1",
1711
                                 "Power-on message line 1",
1712
                                 RadioSettingValueString(0, 6, _filter(
1713
                                                         _msg.line1)))
1714
            advanced.append(line1)
1715
            line2 = RadioSetting("poweron_msg.line2",
1716
                                 "Power-on message line 2",
1717
                                 RadioSettingValueString(0, 6, _filter(
1718
                                                         _msg.line2)))
1719
            advanced.append(line2)
1720

    
1721
        if self.MODEL in ("UV-2501", "UV-5001"):
1722
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1723
                                   RadioSettingValueBoolean(
1724
                                       _mem.settings2.vfomren))
1725
            advanced.append(vfomren)
1726

    
1727
            reseten = RadioSetting("settings2.reseten", "RESET",
1728
                                   RadioSettingValueBoolean(
1729
                                       _mem.settings2.reseten))
1730
            advanced.append(reseten)
1731

    
1732
            menuen = RadioSetting("settings2.menuen", "Menu",
1733
                                  RadioSettingValueBoolean(
1734
                                      _mem.settings2.menuen))
1735
            advanced.append(menuen)
1736

    
1737
        # Other
1738
        def convert_bytes_to_limit(bytes):
1739
            limit = ""
1740
            for byte in bytes:
1741
                if byte < 10:
1742
                    limit += chr(byte + 0x30)
1743
                else:
1744
                    break
1745
            return limit
1746

    
1747
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1748
            _ranges = self._memobj.ranges220
1749
            ranges = "ranges220"
1750
        else:
1751
            _ranges = self._memobj.ranges
1752
            ranges = "ranges"
1753

    
1754
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1755
        val = RadioSettingValueString(0, 3, _limit)
1756
        val.set_mutable(False)
1757
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1758
        other.append(vhf_low)
1759

    
1760
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1761
        val = RadioSettingValueString(0, 3, _limit)
1762
        val.set_mutable(False)
1763
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1764
        other.append(vhf_high)
1765

    
1766
        if self.BANDS == 3 or self.BANDS == 4:
1767
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1768
            val = RadioSettingValueString(0, 3, _limit)
1769
            val.set_mutable(False)
1770
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1771
            other.append(vhf2_low)
1772

    
1773
            _limit = convert_bytes_to_limit(_ranges.vhf2_high)
1774
            val = RadioSettingValueString(0, 3, _limit)
1775
            val.set_mutable(False)
1776
            vhf2_high = RadioSetting("%s.vhf2_high" % ranges, "VHF2 high", val)
1777
            other.append(vhf2_high)
1778

    
1779
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1780
        val = RadioSettingValueString(0, 3, _limit)
1781
        val.set_mutable(False)
1782
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1783
        other.append(uhf_low)
1784

    
1785
        _limit = convert_bytes_to_limit(_ranges.uhf_high)
1786
        val = RadioSettingValueString(0, 3, _limit)
1787
        val.set_mutable(False)
1788
        uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
1789
        other.append(uhf_high)
1790

    
1791
        if self.BANDS == 4:
1792
            _limit = convert_bytes_to_limit(_ranges.uhf2_low)
1793
            val = RadioSettingValueString(0, 3, _limit)
1794
            val.set_mutable(False)
1795
            uhf2_low = RadioSetting("%s.uhf2_low" % ranges, "UHF2 low", val)
1796
            other.append(uhf2_low)
1797

    
1798
            _limit = convert_bytes_to_limit(_ranges.uhf2_high)
1799
            val = RadioSettingValueString(0, 3, _limit)
1800
            val.set_mutable(False)
1801
            uhf2_high = RadioSetting("%s.uhf2_high" % ranges, "UHF2 high", val)
1802
            other.append(uhf2_high)
1803

    
1804
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1805
        val.set_mutable(False)
1806
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1807
        other.append(fp)
1808

    
1809
        # Work
1810
        if self.COLOR_LCD:
1811
            dispab = RadioSetting("settings2.dispab", "Display",
1812
                                  RadioSettingValueList(
1813
                                      LIST_ABCD,
1814
                                      LIST_ABCD[_mem.settings2.dispab]))
1815
            work.append(dispab)
1816
        else:
1817
            dispab = RadioSetting("settings2.dispab", "Display",
1818
                                  RadioSettingValueList(
1819
                                      LIST_AB,
1820
                                      LIST_AB[_mem.settings2.dispab]))
1821
            work.append(dispab)
1822

    
1823
        if self.COLOR_LCD:
1824
            vfomra = RadioSetting("settings2.vfomra", "VFO/MR A mode",
1825
                                  RadioSettingValueList(
1826
                                      LIST_VFOMR,
1827
                                      LIST_VFOMR[_mem.settings2.vfomra]))
1828
            work.append(vfomra)
1829

    
1830
            vfomrb = RadioSetting("settings2.vfomrb", "VFO/MR B mode",
1831
                                  RadioSettingValueList(
1832
                                      LIST_VFOMR,
1833
                                      LIST_VFOMR[_mem.settings2.vfomrb]))
1834
            work.append(vfomrb)
1835

    
1836
            vfomrc = RadioSetting("settings2.vfomrc", "VFO/MR C mode",
1837
                                  RadioSettingValueList(
1838
                                      LIST_VFOMR,
1839
                                      LIST_VFOMR[_mem.settings2.vfomrc]))
1840
            work.append(vfomrc)
1841

    
1842
            vfomrd = RadioSetting("settings2.vfomrd", "VFO/MR D mode",
1843
                                  RadioSettingValueList(
1844
                                      LIST_VFOMR,
1845
                                      LIST_VFOMR[_mem.settings2.vfomrd]))
1846
            work.append(vfomrd)
1847
        else:
1848
            vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1849
                                 RadioSettingValueList(
1850
                                     LIST_VFOMR,
1851
                                     LIST_VFOMR[_mem.settings2.vfomr]))
1852
            work.append(vfomr)
1853

    
1854
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1855
                               RadioSettingValueBoolean(
1856
                                   _mem.settings2.keylock))
1857
        work.append(keylock)
1858

    
1859
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1860
                             RadioSettingValueInteger(0, self._upper,
1861
                                                      _mem.settings2.mrcha))
1862
        work.append(mrcha)
1863

    
1864
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1865
                             RadioSettingValueInteger(0, self._upper,
1866
                                                      _mem.settings2.mrchb))
1867
        work.append(mrchb)
1868

    
1869
        if self.COLOR_LCD:
1870
            mrchc = RadioSetting("settings2.mrchc", "MR C channel",
1871
                                 RadioSettingValueInteger(
1872
                                     0, self._upper, _mem.settings2.mrchc))
1873
            work.append(mrchc)
1874

    
1875
            mrchd = RadioSetting("settings2.mrchd", "MR D channel",
1876
                                 RadioSettingValueInteger(
1877
                                     0, self._upper, _mem.settings2.mrchd))
1878
            work.append(mrchd)
1879

    
1880
        def convert_bytes_to_freq(bytes):
1881
            real_freq = 0
1882
            for byte in bytes:
1883
                real_freq = (real_freq * 10) + byte
1884
            return chirp_common.format_freq(real_freq * 10)
1885

    
1886
        def my_validate(value):
1887
            _vhf_lower = int(convert_bytes_to_limit(_ranges.vhf_low))
1888
            _vhf_upper = int(convert_bytes_to_limit(_ranges.vhf_high))
1889
            _uhf_lower = int(convert_bytes_to_limit(_ranges.uhf_low))
1890
            _uhf_upper = int(convert_bytes_to_limit(_ranges.uhf_high))
1891
            if self.BANDS == 3 or self.BANDS == 4:
1892
                _vhf2_lower = int(convert_bytes_to_limit(_ranges.vhf2_low))
1893
                _vhf2_upper = int(convert_bytes_to_limit(_ranges.vhf2_high))
1894
            if self.BANDS == 4:
1895
                _uhf2_lower = int(convert_bytes_to_limit(_ranges.uhf2_low))
1896
                _uhf2_upper = int(convert_bytes_to_limit(_ranges.uhf2_high))
1897

    
1898
            value = chirp_common.parse_freq(value)
1899
            msg = ("Can't be less then %i.0000")
1900
            if value > 99000000 and value < _vhf_lower * 1000000:
1901
                raise InvalidValueError(msg % (_vhf_lower))
1902
            msg = ("Can't be betweeb %i.9975-%i.0000")
1903
            if self.BANDS == 2:
1904
                if (_vhf_upper + 1) * 1000000 <= value and \
1905
                        value < _uhf_lower * 1000000:
1906
                    raise InvalidValueError(msg % (_vhf_upper, _uhf_lower))
1907
            if self.BANDS == 3:
1908
                if (_vhf_upper + 1) * 1000000 <= value and \
1909
                        value < _vhf2_lower * 1000000:
1910
                    raise InvalidValueError(msg % (_vhf_upper, _vhf2_lower))
1911
                if (_vhf2_upper + 1) * 1000000 <= value and \
1912
                        value < _uhf_lower * 1000000:
1913
                    raise InvalidValueError(msg % (_vhf2_upper, _uhf_lower))
1914
            if self.BANDS == 4:
1915
                if (_vhf_upper + 1) * 1000000 <= value and \
1916
                        value < _vhf2_lower * 1000000:
1917
                    raise InvalidValueError(msg % (_vhf_upper, _vhf2_lower))
1918
                if (_vhf2_upper + 1) * 1000000 <= value and \
1919
                        value < _uhf2_lower * 1000000:
1920
                    raise InvalidValueError(msg % (_vhf2_upper, _uhf2_lower))
1921
                if (_uhf2_upper + 1) * 1000000 <= value and \
1922
                        value < _uhf_lower * 1000000:
1923
                    raise InvalidValueError(msg % (_uhf2_upper, _uhf_lower))
1924
            msg = ("Can't be greater then %i.9975")
1925
            if value > 99000000 and value >= _uhf_upper * 1000000:
1926
                raise InvalidValueError(msg % (_uhf_upper))
1927
            return chirp_common.format_freq(value)
1928

    
1929
        def apply_freq(setting, obj):
1930
            value = chirp_common.parse_freq(str(setting.value)) / 10
1931
            for i in range(7, -1, -1):
1932
                obj.freq[i] = value % 10
1933
                value /= 10
1934

    
1935
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1936
                                        _mem.vfo.a.freq))
1937
        val1a.set_validate_callback(my_validate)
1938
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1939
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1940
        work.append(vfoafreq)
1941

    
1942
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1943
                                        _mem.vfo.b.freq))
1944
        val1b.set_validate_callback(my_validate)
1945
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1946
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1947
        work.append(vfobfreq)
1948

    
1949
        if self.COLOR_LCD:
1950
            val1c = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1951
                                            _mem.vfo.c.freq))
1952
            val1c.set_validate_callback(my_validate)
1953
            vfocfreq = RadioSetting("vfo.c.freq", "VFO C frequency", val1c)
1954
            vfocfreq.set_apply_callback(apply_freq, _mem.vfo.c)
1955
            work.append(vfocfreq)
1956

    
1957
            val1d = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1958
                                            _mem.vfo.d.freq))
1959
            val1d.set_validate_callback(my_validate)
1960
            vfodfreq = RadioSetting("vfo.d.freq", "VFO D frequency", val1d)
1961
            vfodfreq.set_apply_callback(apply_freq, _mem.vfo.d)
1962
            work.append(vfodfreq)
1963

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

    
1971
            vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1972
                                      RadioSettingValueList(
1973
                                          LIST_SHIFT,
1974
                                          LIST_SHIFT[_mem.vfo.b.shiftd]))
1975
            work.append(vfobshiftd)
1976

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

    
1984
                vfodshiftd = RadioSetting("vfo.d.shiftd", "VFO D shift",
1985
                                          RadioSettingValueList(
1986
                                              LIST_SHIFT,
1987
                                              LIST_SHIFT[_mem.vfo.d.shiftd]))
1988
                work.append(vfodshiftd)
1989

    
1990
        def convert_bytes_to_offset(bytes):
1991
            real_offset = 0
1992
            for byte in bytes:
1993
                real_offset = (real_offset * 10) + byte
1994
            return chirp_common.format_freq(real_offset * 1000)
1995

    
1996
        def apply_offset(setting, obj):
1997
            value = chirp_common.parse_freq(str(setting.value)) / 1000
1998
            for i in range(5, -1, -1):
1999
                obj.offset[i] = value % 10
2000
                value /= 10
2001

    
2002
        if not self.MODEL == "GMRS-50X1":
2003
            if self.COLOR_LCD:
2004
                val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
2005
                                                _mem.vfo.a.offset))
2006
                vfoaoffset = RadioSetting("vfo.a.offset",
2007
                                          "VFO A offset (0.000-999.999)",
2008
                                          val1a)
2009
                vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
2010
                work.append(vfoaoffset)
2011

    
2012
                val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
2013
                                                _mem.vfo.b.offset))
2014
                vfoboffset = RadioSetting("vfo.b.offset",
2015
                                          "VFO B offset (0.000-999.999)",
2016
                                          val1b)
2017
                vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
2018
                work.append(vfoboffset)
2019

    
2020
                val1c = RadioSettingValueString(0, 10, convert_bytes_to_offset(
2021
                                                _mem.vfo.c.offset))
2022
                vfocoffset = RadioSetting("vfo.c.offset",
2023
                                          "VFO C offset (0.000-999.999)",
2024
                                          val1c)
2025
                vfocoffset.set_apply_callback(apply_offset, _mem.vfo.c)
2026
                work.append(vfocoffset)
2027

    
2028
                val1d = RadioSettingValueString(0, 10, convert_bytes_to_offset(
2029
                                                _mem.vfo.d.offset))
2030
                vfodoffset = RadioSetting("vfo.d.offset",
2031
                                          "VFO D offset (0.000-999.999)",
2032
                                          val1d)
2033
                vfodoffset.set_apply_callback(apply_offset, _mem.vfo.d)
2034
                work.append(vfodoffset)
2035
            else:
2036
                val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
2037
                                                _mem.vfo.a.offset))
2038
                vfoaoffset = RadioSetting("vfo.a.offset",
2039
                                          "VFO A offset (0.000-99.999)", val1a)
2040
                vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
2041
                work.append(vfoaoffset)
2042

    
2043
                val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
2044
                                                _mem.vfo.b.offset))
2045
                vfoboffset = RadioSetting("vfo.b.offset",
2046
                                          "VFO B offset (0.000-99.999)", val1b)
2047
                vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
2048
                work.append(vfoboffset)
2049

    
2050
        if not self.MODEL == "GMRS-50X1":
2051
            vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
2052
                                   RadioSettingValueList(
2053
                                       LIST_TXP,
2054
                                       LIST_TXP[_mem.vfo.a.power]))
2055
            work.append(vfoatxp)
2056

    
2057
            vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
2058
                                   RadioSettingValueList(
2059
                                       LIST_TXP,
2060
                                       LIST_TXP[_mem.vfo.b.power]))
2061
            work.append(vfobtxp)
2062

    
2063
            if self.COLOR_LCD:
2064
                vfoctxp = RadioSetting("vfo.c.power", "VFO C power",
2065
                                       RadioSettingValueList(
2066
                                           LIST_TXP,
2067
                                           LIST_TXP[_mem.vfo.c.power]))
2068
                work.append(vfoctxp)
2069

    
2070
                vfodtxp = RadioSetting("vfo.d.power", "VFO D power",
2071
                                       RadioSettingValueList(
2072
                                           LIST_TXP,
2073
                                           LIST_TXP[_mem.vfo.d.power]))
2074
                work.append(vfodtxp)
2075

    
2076
        if not self.MODEL == "GMRS-50X1":
2077
            vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
2078
                                    RadioSettingValueList(
2079
                                        LIST_WIDE,
2080
                                        LIST_WIDE[_mem.vfo.a.wide]))
2081
            work.append(vfoawide)
2082

    
2083
            vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
2084
                                    RadioSettingValueList(
2085
                                        LIST_WIDE,
2086
                                        LIST_WIDE[_mem.vfo.b.wide]))
2087
            work.append(vfobwide)
2088

    
2089
            if self.COLOR_LCD:
2090
                vfocwide = RadioSetting("vfo.c.wide", "VFO C bandwidth",
2091
                                        RadioSettingValueList(
2092
                                            LIST_WIDE,
2093
                                            LIST_WIDE[_mem.vfo.c.wide]))
2094
                work.append(vfocwide)
2095

    
2096
                vfodwide = RadioSetting("vfo.d.wide", "VFO D bandwidth",
2097
                                        RadioSettingValueList(
2098
                                            LIST_WIDE,
2099
                                            LIST_WIDE[_mem.vfo.d.wide]))
2100
                work.append(vfodwide)
2101

    
2102
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
2103
                                RadioSettingValueList(
2104
                                    LIST_STEP,
2105
                                    LIST_STEP[_mem.vfo.a.step]))
2106
        work.append(vfoastep)
2107

    
2108
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
2109
                                RadioSettingValueList(
2110
                                    LIST_STEP,
2111
                                    LIST_STEP[_mem.vfo.b.step]))
2112
        work.append(vfobstep)
2113

    
2114
        if self.COLOR_LCD:
2115
            vfocstep = RadioSetting("vfo.c.step", "VFO C step",
2116
                                    RadioSettingValueList(
2117
                                        LIST_STEP,
2118
                                        LIST_STEP[_mem.vfo.c.step]))
2119
            work.append(vfocstep)
2120

    
2121
            vfodstep = RadioSetting("vfo.d.step", "VFO D step",
2122
                                    RadioSettingValueList(
2123
                                        LIST_STEP,
2124
                                        LIST_STEP[_mem.vfo.d.step]))
2125
            work.append(vfodstep)
2126

    
2127
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
2128
                                  RadioSettingValueList(
2129
                                      OPTSIG_LIST,
2130
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
2131
        work.append(vfoaoptsig)
2132

    
2133
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
2134
                                  RadioSettingValueList(
2135
                                      OPTSIG_LIST,
2136
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
2137
        work.append(vfoboptsig)
2138

    
2139
        if self.COLOR_LCD:
2140
            vfocoptsig = RadioSetting("vfo.c.optsig", "VFO C optional signal",
2141
                                      RadioSettingValueList(
2142
                                          OPTSIG_LIST,
2143
                                          OPTSIG_LIST[_mem.vfo.c.optsig]))
2144
            work.append(vfocoptsig)
2145

    
2146
            vfodoptsig = RadioSetting("vfo.d.optsig", "VFO D optional signal",
2147
                                      RadioSettingValueList(
2148
                                          OPTSIG_LIST,
2149
                                          OPTSIG_LIST[_mem.vfo.d.optsig]))
2150
            work.append(vfodoptsig)
2151

    
2152
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
2153
                                  RadioSettingValueList(
2154
                                      SPMUTE_LIST,
2155
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
2156
        work.append(vfoaspmute)
2157

    
2158
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
2159
                                  RadioSettingValueList(
2160
                                      SPMUTE_LIST,
2161
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
2162
        work.append(vfobspmute)
2163

    
2164
        if self.COLOR_LCD:
2165
            vfocspmute = RadioSetting("vfo.c.spmute", "VFO C speaker mute",
2166
                                      RadioSettingValueList(
2167
                                          SPMUTE_LIST,
2168
                                          SPMUTE_LIST[_mem.vfo.c.spmute]))
2169
            work.append(vfocspmute)
2170

    
2171
            vfodspmute = RadioSetting("vfo.d.spmute", "VFO D speaker mute",
2172
                                      RadioSettingValueList(
2173
                                          SPMUTE_LIST,
2174
                                          SPMUTE_LIST[_mem.vfo.d.spmute]))
2175
            work.append(vfodspmute)
2176

    
2177
        if not self.COLOR_LCD or \
2178
                (self.COLOR_LCD and not self.VENDOR == "BTECH"):
2179
            vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
2180
                                   RadioSettingValueBoolean(
2181
                                       _mem.vfo.a.scramble))
2182
            work.append(vfoascr)
2183

    
2184
            vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
2185
                                   RadioSettingValueBoolean(
2186
                                       _mem.vfo.b.scramble))
2187
            work.append(vfobscr)
2188

    
2189
        if self.COLOR_LCD and not self.VENDOR == "BTECH":
2190
            vfocscr = RadioSetting("vfo.c.scramble", "VFO C scramble",
2191
                                   RadioSettingValueBoolean(
2192
                                       _mem.vfo.c.scramble))
2193
            work.append(vfocscr)
2194

    
2195
            vfodscr = RadioSetting("vfo.d.scramble", "VFO D scramble",
2196
                                   RadioSettingValueBoolean(
2197
                                       _mem.vfo.d.scramble))
2198
            work.append(vfodscr)
2199

    
2200
        if not self.MODEL == "GMRS-50X1":
2201
            vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
2202
                                     RadioSettingValueList(
2203
                                         PTTIDCODE_LIST,
2204
                                         PTTIDCODE_LIST[_mem.vfo.a.scode]))
2205
            work.append(vfoascode)
2206

    
2207
            vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
2208
                                     RadioSettingValueList(
2209
                                         PTTIDCODE_LIST,
2210
                                         PTTIDCODE_LIST[_mem.vfo.b.scode]))
2211
            work.append(vfobscode)
2212

    
2213
            if self.COLOR_LCD:
2214
                vfocscode = RadioSetting("vfo.c.scode", "VFO C PTT-ID",
2215
                                         RadioSettingValueList(
2216
                                             PTTIDCODE_LIST,
2217
                                             PTTIDCODE_LIST[_mem.vfo.c.scode]))
2218
                work.append(vfocscode)
2219

    
2220
                vfodscode = RadioSetting("vfo.d.scode", "VFO D PTT-ID",
2221
                                         RadioSettingValueList(
2222
                                             PTTIDCODE_LIST,
2223
                                             PTTIDCODE_LIST[_mem.vfo.d.scode]))
2224
                work.append(vfodscode)
2225

    
2226
        if not self.MODEL == "GMRS-50X1":
2227
            pttid = RadioSetting("settings.pttid", "PTT ID",
2228
                                 RadioSettingValueList(
2229
                                     PTTID_LIST,
2230
                                     PTTID_LIST[_mem.settings.pttid]))
2231
            work.append(pttid)
2232

    
2233
        if not self.COLOR_LCD:
2234
            # FM presets
2235
            fm_presets = RadioSettingGroup("fm_presets", "FM Presets")
2236
            top.append(fm_presets)
2237

    
2238
            def fm_validate(value):
2239
                if value == 0:
2240
                    return chirp_common.format_freq(value)
2241
                if not (87.5 <= value and value <= 108.0):  # 87.5-108MHz
2242
                    msg = ("FM-Preset-Frequency: " +
2243
                           "Must be between 87.5 and 108 MHz")
2244
                    raise InvalidValueError(msg)
2245
                return value
2246

    
2247
            def apply_fm_preset_name(setting, obj):
2248
                valstring = str(setting.value)
2249
                for i in range(0, 6):
2250
                    if valstring[i] in VALID_CHARS:
2251
                        obj[i] = valstring[i]
2252
                    else:
2253
                        obj[i] = '0xff'
2254

    
2255
            def apply_fm_freq(setting, obj):
2256
                value = chirp_common.parse_freq(str(setting.value)) / 10
2257
                for i in range(7, -1, -1):
2258
                    obj.freq[i] = value % 10
2259
                    value /= 10
2260

    
2261
            _presets = self._memobj.fm_radio_preset
2262
            i = 1
2263
            for preset in _presets:
2264
                line = RadioSetting("fm_presets_" + str(i),
2265
                                    "Station name " + str(i),
2266
                                    RadioSettingValueString(0, 6, _filter(
2267
                                        preset.broadcast_station_name)))
2268
                line.set_apply_callback(apply_fm_preset_name,
2269
                                        preset.broadcast_station_name)
2270

    
2271
                val = RadioSettingValueFloat(0, 108,
2272
                                             convert_bytes_to_freq(
2273
                                                 preset.freq))
2274
                fmfreq = RadioSetting("fm_presets_" + str(i) + "_freq",
2275
                                      "Frequency " + str(i), val)
2276
                val.set_validate_callback(fm_validate)
2277
                fmfreq.set_apply_callback(apply_fm_freq, preset)
2278
                fm_presets.append(line)
2279
                fm_presets.append(fmfreq)
2280

    
2281
                i = i + 1
2282

    
2283
        # DTMF-Setting
2284
        dtmf_enc_settings = RadioSettingGroup("dtmf_enc_settings",
2285
                                              "DTMF Encoding Settings")
2286
        dtmf_dec_settings = RadioSettingGroup("dtmf_dec_settings",
2287
                                              "DTMF Decoding Settings")
2288
        top.append(dtmf_enc_settings)
2289
        top.append(dtmf_dec_settings)
2290
        txdisable = RadioSetting("dtmf_settings.txdisable",
2291
                                 "TX-Disable",
2292
                                 RadioSettingValueBoolean(
2293
                                     _mem.dtmf_settings.txdisable))
2294
        dtmf_enc_settings.append(txdisable)
2295

    
2296
        rxdisable = RadioSetting("dtmf_settings.rxdisable",
2297
                                 "RX-Disable",
2298
                                 RadioSettingValueBoolean(
2299
                                     _mem.dtmf_settings.rxdisable))
2300
        dtmf_enc_settings.append(rxdisable)
2301

    
2302
        if _mem.dtmf_settings.dtmfspeed_on > 0x0F:
2303
            val = 0x03
2304
        else:
2305
            val = _mem.dtmf_settings.dtmfspeed_on
2306
        dtmfspeed_on = RadioSetting(
2307
            "dtmf_settings.dtmfspeed_on",
2308
            "DTMF Speed (On Time)",
2309
            RadioSettingValueList(LIST_DTMF_SPEED,
2310
                                  LIST_DTMF_SPEED[
2311
                                      val]))
2312
        dtmf_enc_settings.append(dtmfspeed_on)
2313

    
2314
        if _mem.dtmf_settings.dtmfspeed_off > 0x0F:
2315
            val = 0x03
2316
        else:
2317
            val = _mem.dtmf_settings.dtmfspeed_off
2318
        dtmfspeed_off = RadioSetting(
2319
            "dtmf_settings.dtmfspeed_off",
2320
            "DTMF Speed (Off Time)",
2321
            RadioSettingValueList(LIST_DTMF_SPEED,
2322
                                  LIST_DTMF_SPEED[
2323
                                      val]))
2324
        dtmf_enc_settings.append(dtmfspeed_off)
2325

    
2326
        def memory2string(dmtf_mem):
2327
            dtmf_string = ""
2328
            for digit in dmtf_mem:
2329
                if digit != 255:
2330
                    index = LIST_DTMF_VALUES.index(digit)
2331
                    dtmf_string = dtmf_string + LIST_DTMF_DIGITS[index]
2332
            return dtmf_string
2333

    
2334
        def apply_dmtf_frame(setting, obj):
2335
            LOG.debug("Setting DTMF-Code: " + str(setting.value))
2336
            val_string = str(setting.value)
2337
            for i in range(0, 16):
2338
                obj[i] = 255
2339
            i = 0
2340
            for current_char in val_string:
2341
                current_char = current_char.upper()
2342
                index = LIST_DTMF_DIGITS.index(current_char)
2343
                obj[i] = LIST_DTMF_VALUES[index]
2344
                i = i + 1
2345

    
2346
        codes = self._memobj.dtmf_codes
2347
        i = 1
2348
        for dtmfcode in codes:
2349
            val = RadioSettingValueString(0, 16, memory2string(
2350
                                              dtmfcode.code),
2351
                                          False, CHARSET_DTMF_DIGITS)
2352
            line = RadioSetting("dtmf_code_" + str(i) + "_code",
2353
                                "DMTF Code " + str(i), val)
2354
            line.set_apply_callback(apply_dmtf_frame, dtmfcode.code)
2355
            dtmf_enc_settings.append(line)
2356
            i = i + 1
2357

    
2358
        line = RadioSetting("dtmf_settings.mastervice",
2359
                            "Master and Vice ID",
2360
                            RadioSettingValueBoolean(
2361
                                _mem.dtmf_settings.mastervice))
2362
        dtmf_dec_settings.append(line)
2363

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

    
2373
        line = RadioSetting("dtmf_settings.minspection",
2374
                            "Master Inspection",
2375
                            RadioSettingValueBoolean(
2376
                                _mem.dtmf_settings.minspection))
2377
        dtmf_dec_settings.append(line)
2378

    
2379
        line = RadioSetting("dtmf_settings.mmonitor",
2380
                            "Master Monitor",
2381
                            RadioSettingValueBoolean(
2382
                                _mem.dtmf_settings.mmonitor))
2383
        dtmf_dec_settings.append(line)
2384

    
2385
        line = RadioSetting("dtmf_settings.mstun",
2386
                            "Master Stun",
2387
                            RadioSettingValueBoolean(
2388
                                _mem.dtmf_settings.mstun))
2389
        dtmf_dec_settings.append(line)
2390

    
2391
        line = RadioSetting("dtmf_settings.mkill",
2392
                            "Master Kill",
2393
                            RadioSettingValueBoolean(
2394
                                _mem.dtmf_settings.mkill))
2395
        dtmf_dec_settings.append(line)
2396

    
2397
        line = RadioSetting("dtmf_settings.mrevive",
2398
                            "Master Revive",
2399
                            RadioSettingValueBoolean(
2400
                                _mem.dtmf_settings.mrevive))
2401
        dtmf_dec_settings.append(line)
2402

    
2403
        val = RadioSettingValueString(0, 16, memory2string(
2404
                                          _mem.dtmf_settings.viceid),
2405
                                      False, CHARSET_DTMF_DIGITS)
2406
        line = RadioSetting("dtmf_settings.viceid",
2407
                            "Vice Control ID ", val)
2408
        line.set_apply_callback(apply_dmtf_frame,
2409
                                _mem.dtmf_settings.viceid)
2410
        dtmf_dec_settings.append(line)
2411

    
2412
        line = RadioSetting("dtmf_settings.vinspection",
2413
                            "Vice Inspection",
2414
                            RadioSettingValueBoolean(
2415
                                _mem.dtmf_settings.vinspection))
2416
        dtmf_dec_settings.append(line)
2417

    
2418
        line = RadioSetting("dtmf_settings.vmonitor",
2419
                            "Vice Monitor",
2420
                            RadioSettingValueBoolean(
2421
                                _mem.dtmf_settings.vmonitor))
2422
        dtmf_dec_settings.append(line)
2423

    
2424
        line = RadioSetting("dtmf_settings.vstun",
2425
                            "Vice Stun",
2426
                            RadioSettingValueBoolean(
2427
                                _mem.dtmf_settings.vstun))
2428
        dtmf_dec_settings.append(line)
2429

    
2430
        line = RadioSetting("dtmf_settings.vkill",
2431
                            "Vice Kill",
2432
                            RadioSettingValueBoolean(
2433
                                _mem.dtmf_settings.vkill))
2434
        dtmf_dec_settings.append(line)
2435

    
2436
        line = RadioSetting("dtmf_settings.vrevive",
2437
                            "Vice Revive",
2438
                            RadioSettingValueBoolean(
2439
                                _mem.dtmf_settings.vrevive))
2440
        dtmf_dec_settings.append(line)
2441

    
2442
        val = RadioSettingValueString(0, 16, memory2string(
2443
                                          _mem.dtmf_settings.inspection),
2444
                                      False, CHARSET_DTMF_DIGITS)
2445
        line = RadioSetting("dtmf_settings.inspection",
2446
                            "Inspection", val)
2447
        line.set_apply_callback(apply_dmtf_frame,
2448
                                _mem.dtmf_settings.inspection)
2449
        dtmf_dec_settings.append(line)
2450

    
2451
        val = RadioSettingValueString(0, 16, memory2string(
2452
                                          _mem.dtmf_settings.alarmcode),
2453
                                      False, CHARSET_DTMF_DIGITS)
2454
        line = RadioSetting("dtmf_settings.alarmcode",
2455
                            "Alarm", val)
2456
        line.set_apply_callback(apply_dmtf_frame,
2457
                                _mem.dtmf_settings.alarmcode)
2458
        dtmf_dec_settings.append(line)
2459

    
2460
        val = RadioSettingValueString(0, 16, memory2string(
2461
                                          _mem.dtmf_settings.kill),
2462
                                      False, CHARSET_DTMF_DIGITS)
2463
        line = RadioSetting("dtmf_settings.kill",
2464
                            "Kill", val)
2465
        line.set_apply_callback(apply_dmtf_frame,
2466
                                _mem.dtmf_settings.kill)
2467
        dtmf_dec_settings.append(line)
2468

    
2469
        val = RadioSettingValueString(0, 16, memory2string(
2470
                                          _mem.dtmf_settings.monitor),
2471
                                      False, CHARSET_DTMF_DIGITS)
2472
        line = RadioSetting("dtmf_settings.monitor",
2473
                            "Monitor", val)
2474
        line.set_apply_callback(apply_dmtf_frame,
2475
                                _mem.dtmf_settings.monitor)
2476
        dtmf_dec_settings.append(line)
2477

    
2478
        val = RadioSettingValueString(0, 16, memory2string(
2479
                                          _mem.dtmf_settings.stun),
2480
                                      False, CHARSET_DTMF_DIGITS)
2481
        line = RadioSetting("dtmf_settings.stun",
2482
                            "Stun", val)
2483
        line.set_apply_callback(apply_dmtf_frame,
2484
                                _mem.dtmf_settings.stun)
2485
        dtmf_dec_settings.append(line)
2486

    
2487
        val = RadioSettingValueString(0, 16, memory2string(
2488
                                          _mem.dtmf_settings.revive),
2489
                                      False, CHARSET_DTMF_DIGITS)
2490
        line = RadioSetting("dtmf_settings.revive",
2491
                            "Revive", val)
2492
        line.set_apply_callback(apply_dmtf_frame,
2493
                                _mem.dtmf_settings.revive)
2494
        dtmf_dec_settings.append(line)
2495

    
2496
        def apply_dmtf_listvalue(setting, obj):
2497
            LOG.debug("Setting value: " + str(setting.value) + " from list")
2498
            val = str(setting.value)
2499
            index = LIST_DTMF_SPECIAL_DIGITS.index(val)
2500
            val = LIST_DTMF_SPECIAL_VALUES[index]
2501
            obj.set_value(val)
2502

    
2503
        if _mem.dtmf_settings.groupcode not in LIST_DTMF_SPECIAL_VALUES:
2504
            val = 0x0B
2505
        else:
2506
            val = _mem.dtmf_settings.groupcode
2507
        idx = LIST_DTMF_SPECIAL_VALUES.index(val)
2508
        line = RadioSetting(
2509
            "dtmf_settings.groupcode",
2510
            "Group Code",
2511
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2512
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2513
        line.set_apply_callback(apply_dmtf_listvalue,
2514
                                _mem.dtmf_settings.groupcode)
2515
        dtmf_dec_settings.append(line)
2516

    
2517
        if _mem.dtmf_settings.spacecode not in LIST_DTMF_SPECIAL_VALUES:
2518
            val = 0x0C
2519
        else:
2520
            val = _mem.dtmf_settings.spacecode
2521
        idx = LIST_DTMF_SPECIAL_VALUES.index(val)
2522
        line = RadioSetting(
2523
            "dtmf_settings.spacecode",
2524
            "Space Code",
2525
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2526
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2527
        line.set_apply_callback(apply_dmtf_listvalue,
2528
                                _mem.dtmf_settings.spacecode)
2529
        dtmf_dec_settings.append(line)
2530

    
2531
        if self.COLOR_LCD:
2532
            if _mem.dtmf_settings.resettime > 0x63:
2533
                val = 0x4F
2534
            else:
2535
                val = _mem.dtmf_settings.resettime
2536
            line = RadioSetting(
2537
                "dtmf_settings.resettime",
2538
                "Reset time",
2539
                RadioSettingValueList(LIST_5TONE_RESET_COLOR,
2540
                                      LIST_5TONE_RESET_COLOR[
2541
                                          val]))
2542
            dtmf_dec_settings.append(line)
2543
        else:
2544
            line = RadioSetting(
2545
                "dtmf_settings.resettime",
2546
                "Reset time",
2547
                RadioSettingValueList(LIST_5TONE_RESET,
2548
                                      LIST_5TONE_RESET[
2549
                                          _mem.dtmf_settings.resettime]))
2550
            dtmf_dec_settings.append(line)
2551

    
2552
        if _mem.dtmf_settings.delayproctime > 0x27:
2553
            val = 0x04
2554
        else:
2555
            val = _mem.dtmf_settings.delayproctime
2556
        line = RadioSetting(
2557
            "dtmf_settings.delayproctime",
2558
            "Delay processing time",
2559
            RadioSettingValueList(LIST_DTMF_DELAY,
2560
                                  LIST_DTMF_DELAY[
2561
                                      val]))
2562
        dtmf_dec_settings.append(line)
2563

    
2564
        # 5 Tone Settings
2565
        stds_5tone = RadioSettingGroup("stds_5tone", "Standards")
2566
        codes_5tone = RadioSettingGroup("codes_5tone", "Codes")
2567

    
2568
        group_5tone = RadioSettingGroup("group_5tone", "5 Tone Settings")
2569
        group_5tone.append(stds_5tone)
2570
        group_5tone.append(codes_5tone)
2571

    
2572
        top.append(group_5tone)
2573

    
2574
        def apply_list_value(setting, obj):
2575
            options = setting.value.get_options()
2576
            obj.set_value(options.index(str(setting.value)))
2577

    
2578
        _5tone_standards = self._memobj._5tone_std_settings
2579
        i = 0
2580
        for standard in _5tone_standards:
2581
            std_5tone = RadioSettingGroup("std_5tone_" + str(i),
2582
                                          LIST_5TONE_STANDARDS[i])
2583
            stds_5tone.append(std_5tone)
2584

    
2585
            period = standard.period
2586
            if period == 255:
2587
                LOG.debug("Period for " + LIST_5TONE_STANDARDS[i] +
2588
                          " is not yet configured. Setting to 70ms.")
2589
                period = 5
2590

    
2591
            if period <= len(LIST_5TONE_STANDARD_PERIODS):
2592
                line = RadioSetting(
2593
                    "_5tone_std_settings_" + str(i) + "_period",
2594
                    "Period (ms)", RadioSettingValueList
2595
                    (LIST_5TONE_STANDARD_PERIODS,
2596
                     LIST_5TONE_STANDARD_PERIODS[period]))
2597
                line.set_apply_callback(apply_list_value, standard.period)
2598
                std_5tone.append(line)
2599
            else:
2600
                LOG.debug("Invalid value for 5tone period! Disabling.")
2601

    
2602
            group_tone = standard.group_tone
2603
            if group_tone == 255:
2604
                LOG.debug("Group-Tone for " + LIST_5TONE_STANDARDS[i] +
2605
                          " is not yet configured. Setting to A.")
2606
                group_tone = 10
2607

    
2608
            if group_tone <= len(LIST_5TONE_DIGITS):
2609
                line = RadioSetting(
2610
                    "_5tone_std_settings_" + str(i) + "_grouptone",
2611
                    "Group Tone",
2612
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2613
                                          LIST_5TONE_DIGITS[
2614
                                              group_tone]))
2615
                line.set_apply_callback(apply_list_value,
2616
                                        standard.group_tone)
2617
                std_5tone.append(line)
2618
            else:
2619
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2620

    
2621
            repeat_tone = standard.repeat_tone
2622
            if repeat_tone == 255:
2623
                LOG.debug("Repeat-Tone for " + LIST_5TONE_STANDARDS[i] +
2624
                          " is not yet configured. Setting to E.")
2625
                repeat_tone = 14
2626

    
2627
            if repeat_tone <= len(LIST_5TONE_DIGITS):
2628
                line = RadioSetting(
2629
                    "_5tone_std_settings_" + str(i) + "_repttone",
2630
                    "Repeat Tone",
2631
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2632
                                          LIST_5TONE_DIGITS[
2633
                                              repeat_tone]))
2634
                line.set_apply_callback(apply_list_value,
2635
                                        standard.repeat_tone)
2636
                std_5tone.append(line)
2637
            else:
2638
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2639
            i = i + 1
2640

    
2641
        def my_apply_5tonestdlist_value(setting, obj):
2642
            if LIST_5TONE_STANDARDS.index(str(setting.value)) == 15:
2643
                obj.set_value(0xFF)
2644
            else:
2645
                obj.set_value(LIST_5TONE_STANDARDS.
2646
                              index(str(setting.value)))
2647

    
2648
        def apply_5tone_frame(setting, obj):
2649
            LOG.debug("Setting 5 Tone: " + str(setting.value))
2650
            valstring = str(setting.value)
2651
            if len(valstring) == 0:
2652
                for i in range(0, 5):
2653
                    obj[i] = 255
2654
            else:
2655
                validFrame = True
2656
                for i in range(0, 5):
2657
                    currentChar = valstring[i].upper()
2658
                    if currentChar in LIST_5TONE_DIGITS:
2659
                        obj[i] = LIST_5TONE_DIGITS.index(currentChar)
2660
                    else:
2661
                        validFrame = False
2662
                        LOG.debug("invalid char: " + str(currentChar))
2663
                if not validFrame:
2664
                    LOG.debug("setting whole frame to FF")
2665
                    for i in range(0, 5):
2666
                        obj[i] = 255
2667

    
2668
        def validate_5tone_frame(value):
2669
            if (len(str(value)) != 5) and (len(str(value)) != 0):
2670
                msg = ("5 Tone must have 5 digits or 0 digits")
2671
                raise InvalidValueError(msg)
2672
            for digit in str(value):
2673
                if digit.upper() not in LIST_5TONE_DIGITS:
2674
                    msg = (str(digit) + " is not a valid digit for 5tones")
2675
                    raise InvalidValueError(msg)
2676
            return value
2677

    
2678
        def frame2string(frame):
2679
            frameString = ""
2680
            for digit in frame:
2681
                if digit != 255:
2682
                    frameString = frameString + LIST_5TONE_DIGITS[digit]
2683
            return frameString
2684

    
2685
        _5tone_codes = self._memobj._5tone_codes
2686
        i = 1
2687
        for code in _5tone_codes:
2688
            code_5tone = RadioSettingGroup("code_5tone_" + str(i),
2689
                                           "5 Tone code " + str(i))
2690
            codes_5tone.append(code_5tone)
2691
            if (code.standard == 255):
2692
                currentVal = 15
2693
            else:
2694
                currentVal = code.standard
2695
            line = RadioSetting("_5tone_code_" + str(i) + "_std",
2696
                                " Standard",
2697
                                RadioSettingValueList(LIST_5TONE_STANDARDS,
2698
                                                      LIST_5TONE_STANDARDS[
2699
                                                          currentVal]))
2700
            line.set_apply_callback(my_apply_5tonestdlist_value,
2701
                                    code.standard)
2702
            code_5tone.append(line)
2703

    
2704
            val = RadioSettingValueString(0, 6,
2705
                                          frame2string(code.frame1), False)
2706
            line = RadioSetting("_5tone_code_" + str(i) + "_frame1",
2707
                                " Frame 1", val)
2708
            val.set_validate_callback(validate_5tone_frame)
2709
            line.set_apply_callback(apply_5tone_frame, code.frame1)
2710
            code_5tone.append(line)
2711

    
2712
            val = RadioSettingValueString(0, 6,
2713
                                          frame2string(code.frame2), False)
2714
            line = RadioSetting("_5tone_code_" + str(i) + "_frame2",
2715
                                " Frame 2", val)
2716
            val.set_validate_callback(validate_5tone_frame)
2717
            line.set_apply_callback(apply_5tone_frame, code.frame2)
2718
            code_5tone.append(line)
2719

    
2720
            val = RadioSettingValueString(0, 6,
2721
                                          frame2string(code.frame3), False)
2722
            line = RadioSetting("_5tone_code_" + str(i) + "_frame3",
2723
                                " Frame 3", val)
2724
            val.set_validate_callback(validate_5tone_frame)
2725
            line.set_apply_callback(apply_5tone_frame, code.frame3)
2726
            code_5tone.append(line)
2727
            i = i + 1
2728

    
2729
        _5_tone_decode1 = RadioSetting(
2730
            "_5tone_settings._5tone_decode_call_frame1",
2731
            "5 Tone decode call Frame 1",
2732
            RadioSettingValueBoolean(
2733
                _mem._5tone_settings._5tone_decode_call_frame1))
2734
        group_5tone.append(_5_tone_decode1)
2735

    
2736
        _5_tone_decode2 = RadioSetting(
2737
            "_5tone_settings._5tone_decode_call_frame2",
2738
            "5 Tone decode call Frame 2",
2739
            RadioSettingValueBoolean(
2740
                _mem._5tone_settings._5tone_decode_call_frame2))
2741
        group_5tone.append(_5_tone_decode2)
2742

    
2743
        _5_tone_decode3 = RadioSetting(
2744
            "_5tone_settings._5tone_decode_call_frame3",
2745
            "5 Tone decode call Frame 3",
2746
            RadioSettingValueBoolean(
2747
                _mem._5tone_settings._5tone_decode_call_frame3))
2748
        group_5tone.append(_5_tone_decode3)
2749

    
2750
        _5_tone_decode_disp1 = RadioSetting(
2751
            "_5tone_settings._5tone_decode_disp_frame1",
2752
            "5 Tone decode disp Frame 1",
2753
            RadioSettingValueBoolean(
2754
                _mem._5tone_settings._5tone_decode_disp_frame1))
2755
        group_5tone.append(_5_tone_decode_disp1)
2756

    
2757
        _5_tone_decode_disp2 = RadioSetting(
2758
            "_5tone_settings._5tone_decode_disp_frame2",
2759
            "5 Tone decode disp Frame 2",
2760
            RadioSettingValueBoolean(
2761
                _mem._5tone_settings._5tone_decode_disp_frame2))
2762
        group_5tone.append(_5_tone_decode_disp2)
2763

    
2764
        _5_tone_decode_disp3 = RadioSetting(
2765
            "_5tone_settings._5tone_decode_disp_frame3",
2766
            "5 Tone decode disp Frame 3",
2767
            RadioSettingValueBoolean(
2768
                _mem._5tone_settings._5tone_decode_disp_frame3))
2769
        group_5tone.append(_5_tone_decode_disp3)
2770

    
2771
        decode_standard = _mem._5tone_settings.decode_standard
2772
        if decode_standard == 255:
2773
            decode_standard = 0
2774
        if decode_standard <= len(LIST_5TONE_STANDARDS_without_none):
2775
            line = RadioSetting("_5tone_settings.decode_standard",
2776
                                "5 Tone-decode Standard",
2777
                                RadioSettingValueList(
2778
                                    LIST_5TONE_STANDARDS_without_none,
2779
                                    LIST_5TONE_STANDARDS_without_none[
2780
                                        decode_standard]))
2781
            group_5tone.append(line)
2782
        else:
2783
            LOG.debug("Invalid decode std...")
2784

    
2785
        _5tone_delay1 = _mem._5tone_settings._5tone_delay1
2786
        if _5tone_delay1 == 255:
2787
            _5tone_delay1 = 20
2788

    
2789
        if _5tone_delay1 <= len(LIST_5TONE_DELAY):
2790
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2791
                                         LIST_5TONE_DELAY[
2792
                                             _5tone_delay1])
2793
            line = RadioSetting("_5tone_settings._5tone_delay1",
2794
                                "5 Tone Delay Frame 1", list)
2795
            group_5tone.append(line)
2796
        else:
2797
            LOG.debug("Invalid value for 5tone delay (frame1) ! Disabling.")
2798

    
2799
        _5tone_delay2 = _mem._5tone_settings._5tone_delay2
2800
        if _5tone_delay2 == 255:
2801
            _5tone_delay2 = 20
2802
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2803

    
2804
        if _5tone_delay2 <= len(LIST_5TONE_DELAY):
2805
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2806
                                         LIST_5TONE_DELAY[
2807
                                             _5tone_delay2])
2808
            line = RadioSetting("_5tone_settings._5tone_delay2",
2809
                                "5 Tone Delay Frame 2", list)
2810
            group_5tone.append(line)
2811
        else:
2812
            LOG.debug("Invalid value for 5tone delay (frame2)! Disabling.")
2813

    
2814
        _5tone_delay3 = _mem._5tone_settings._5tone_delay3
2815
        if _5tone_delay3 == 255:
2816
            _5tone_delay3 = 20
2817
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2818

    
2819
        if _5tone_delay3 <= len(LIST_5TONE_DELAY):
2820
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2821
                                         LIST_5TONE_DELAY[
2822
                                             _5tone_delay3])
2823
            line = RadioSetting("_5tone_settings._5tone_delay3",
2824
                                "5 Tone Delay Frame 3", list)
2825
            group_5tone.append(line)
2826
        else:
2827
            LOG.debug("Invalid value for 5tone delay (frame3)! Disabling.")
2828

    
2829
        ext_length = _mem._5tone_settings._5tone_first_digit_ext_length
2830
        if ext_length == 255:
2831
            ext_length = 0
2832
            LOG.debug("1st Tone ext lenght unconfigured! Resetting to 0")
2833

    
2834
        if ext_length <= len(LIST_5TONE_DELAY):
2835
            list = RadioSettingValueList(
2836
                LIST_5TONE_DELAY,
2837
                LIST_5TONE_DELAY[
2838
                    ext_length])
2839
            line = RadioSetting(
2840
                "_5tone_settings._5tone_first_digit_ext_length",
2841
                "First digit extend length", list)
2842
            group_5tone.append(line)
2843
        else:
2844
            LOG.debug("Invalid value for 5tone ext length! Disabling.")
2845

    
2846
        decode_reset_time = _mem._5tone_settings.decode_reset_time
2847
        if decode_reset_time == 255:
2848
            decode_reset_time = 59
2849
            LOG.debug("Decode reset time unconfigured. resetting.")
2850
        if decode_reset_time <= len(LIST_5TONE_RESET):
2851
            list = RadioSettingValueList(
2852
                LIST_5TONE_RESET,
2853
                LIST_5TONE_RESET[
2854
                    decode_reset_time])
2855
            line = RadioSetting("_5tone_settings.decode_reset_time",
2856
                                "Decode reset time", list)
2857
            group_5tone.append(line)
2858
        else:
2859
            LOG.debug("Invalid value decode reset time! Disabling.")
2860

    
2861
        # 2 Tone
2862
        encode_2tone = RadioSettingGroup("encode_2tone", "2 Tone Encode")
2863
        decode_2tone = RadioSettingGroup("decode_2tone", "2 Code Decode")
2864

    
2865
        top.append(encode_2tone)
2866
        top.append(decode_2tone)
2867

    
2868
        duration_1st_tone = self._memobj._2tone.duration_1st_tone
2869
        if duration_1st_tone == 255:
2870
            LOG.debug("Duration of first 2 Tone digit is not yet " +
2871
                      "configured. Setting to 600ms")
2872
            duration_1st_tone = 60
2873

    
2874
        if duration_1st_tone <= len(LIST_5TONE_DELAY):
2875
            line = RadioSetting("_2tone.duration_1st_tone",
2876
                                "Duration 1st Tone",
2877
                                RadioSettingValueList(LIST_5TONE_DELAY,
2878
                                                      LIST_5TONE_DELAY[
2879
                                                          duration_1st_tone]))
2880
            encode_2tone.append(line)
2881

    
2882
        duration_2nd_tone = self._memobj._2tone.duration_2nd_tone
2883
        if duration_2nd_tone == 255:
2884
            LOG.debug("Duration of second 2 Tone digit is not yet " +
2885
                      "configured. Setting to 600ms")
2886
            duration_2nd_tone = 60
2887

    
2888
        if duration_2nd_tone <= len(LIST_5TONE_DELAY):
2889
            line = RadioSetting("_2tone.duration_2nd_tone",
2890
                                "Duration 2nd Tone",
2891
                                RadioSettingValueList(LIST_5TONE_DELAY,
2892
                                                      LIST_5TONE_DELAY[
2893
                                                          duration_2nd_tone]))
2894
            encode_2tone.append(line)
2895

    
2896
        duration_gap = self._memobj._2tone.duration_gap
2897
        if duration_gap == 255:
2898
            LOG.debug("Duration of gap is not yet " +
2899
                      "configured. Setting to 300ms")
2900
            duration_gap = 30
2901

    
2902
        if duration_gap <= len(LIST_5TONE_DELAY):
2903
            line = RadioSetting("_2tone.duration_gap", "Duration of gap",
2904
                                RadioSettingValueList(LIST_5TONE_DELAY,
2905
                                                      LIST_5TONE_DELAY[
2906
                                                          duration_gap]))
2907
            encode_2tone.append(line)
2908

    
2909
        def _2tone_validate(value):
2910
            if value == 0:
2911
                return 65535
2912
            if value == 65535:
2913
                return value
2914
            if not (300 <= value and value <= 3000):
2915
                msg = ("2 Tone Frequency: Must be between 300 and 3000 Hz")
2916
                raise InvalidValueError(msg)
2917
            return value
2918

    
2919
        def apply_2tone_freq(setting, obj):
2920
            val = int(setting.value)
2921
            if (val == 0) or (val == 65535):
2922
                obj.set_value(65535)
2923
            else:
2924
                obj.set_value(val)
2925

    
2926
        i = 1
2927
        for code in self._memobj._2tone._2tone_encode:
2928
            code_2tone = RadioSettingGroup("code_2tone_" + str(i),
2929
                                           "Encode Code " + str(i))
2930
            encode_2tone.append(code_2tone)
2931

    
2932
            tmp = code.freq1
2933
            if tmp == 65535:
2934
                tmp = 0
2935
            val1 = RadioSettingValueInteger(0, 65535, tmp)
2936
            freq1 = RadioSetting("2tone_code_" + str(i) + "_freq1",
2937
                                 "Frequency 1", val1)
2938
            val1.set_validate_callback(_2tone_validate)
2939
            freq1.set_apply_callback(apply_2tone_freq, code.freq1)
2940
            code_2tone.append(freq1)
2941

    
2942
            tmp = code.freq2
2943
            if tmp == 65535:
2944
                tmp = 0
2945
            val2 = RadioSettingValueInteger(0, 65535, tmp)
2946
            freq2 = RadioSetting("2tone_code_" + str(i) + "_freq2",
2947
                                 "Frequency 2", val2)
2948
            val2.set_validate_callback(_2tone_validate)
2949
            freq2.set_apply_callback(apply_2tone_freq, code.freq2)
2950
            code_2tone.append(freq2)
2951

    
2952
            i = i + 1
2953

    
2954
        decode_reset_time = _mem._2tone.reset_time
2955
        if decode_reset_time == 255:
2956
            decode_reset_time = 59
2957
            LOG.debug("Decode reset time unconfigured. resetting.")
2958
        if decode_reset_time <= len(LIST_5TONE_RESET):
2959
            list = RadioSettingValueList(
2960
                LIST_5TONE_RESET,
2961
                LIST_5TONE_RESET[
2962
                    decode_reset_time])
2963
            line = RadioSetting("_2tone.reset_time",
2964
                                "Decode reset time", list)
2965
            decode_2tone.append(line)
2966
        else:
2967
            LOG.debug("Invalid value decode reset time! Disabling.")
2968

    
2969
        def apply_2tone_freq_pair(setting, obj):
2970
            val = int(setting.value)
2971
            derived_val = 65535
2972
            frqname = str(setting._name[-5:])
2973
            derivedname = "derived_from_" + frqname
2974

    
2975
            if (val == 0):
2976
                val = 65535
2977
                derived_val = 65535
2978
            else:
2979
                derived_val = int(round(2304000.0/val))
2980

    
2981
            obj[frqname].set_value(val)
2982
            obj[derivedname].set_value(derived_val)
2983

    
2984
            LOG.debug("Apply " + frqname + ": " + str(val) + " | " +
2985
                      derivedname + ": " + str(derived_val))
2986

    
2987
        i = 1
2988
        for decode_code in self._memobj._2tone._2tone_decode:
2989
            _2tone_dec_code = RadioSettingGroup("code_2tone_" + str(i),
2990
                                                "Decode Code " + str(i))
2991
            decode_2tone.append(_2tone_dec_code)
2992

    
2993
            j = 1
2994
            for dec in decode_code.decs:
2995
                val = dec.dec
2996
                if val == 255:
2997
                    LOG.debug("Dec for Code " + str(i) + " Dec " + str(j) +
2998
                              " is not yet configured. Setting to 0.")
2999
                    val = 0
3000

    
3001
                if val <= len(LIST_2TONE_DEC):
3002
                    line = RadioSetting(
3003
                        "_2tone_dec_settings_" + str(i) + "_dec_" + str(j),
3004
                        "Dec " + str(j), RadioSettingValueList
3005
                        (LIST_2TONE_DEC,
3006
                         LIST_2TONE_DEC[val]))
3007
                    line.set_apply_callback(apply_list_value, dec.dec)
3008
                    _2tone_dec_code.append(line)
3009
                else:
3010
                    LOG.debug("Invalid value for 2tone dec! Disabling.")
3011

    
3012
                val = dec.response
3013
                if val == 255:
3014
                    LOG.debug("Response for Code " + str(i) + " Dec " +
3015
                              str(j) + " is not yet configured. Setting to 0.")
3016
                    val = 0
3017

    
3018
                if val <= len(LIST_2TONE_RESPONSE):
3019
                    line = RadioSetting(
3020
                        "_2tone_dec_settings_" + str(i) + "_resp_" + str(j),
3021
                        "Response " + str(j), RadioSettingValueList
3022
                        (LIST_2TONE_RESPONSE,
3023
                         LIST_2TONE_RESPONSE[val]))
3024
                    line.set_apply_callback(apply_list_value, dec.response)
3025
                    _2tone_dec_code.append(line)
3026
                else:
3027
                    LOG.debug("Invalid value for 2tone response! Disabling.")
3028

    
3029
                val = dec.alert
3030
                if val == 255:
3031
                    LOG.debug("Alert for Code " + str(i) + " Dec " + str(j) +
3032
                              " is not yet configured. Setting to 0.")
3033
                    val = 0
3034

    
3035
                if val <= len(PTTIDCODE_LIST):
3036
                    line = RadioSetting(
3037
                        "_2tone_dec_settings_" + str(i) + "_alert_" + str(j),
3038
                        "Alert " + str(j), RadioSettingValueList
3039
                        (PTTIDCODE_LIST,
3040
                         PTTIDCODE_LIST[val]))
3041
                    line.set_apply_callback(apply_list_value, dec.alert)
3042
                    _2tone_dec_code.append(line)
3043
                else:
3044
                    LOG.debug("Invalid value for 2tone alert! Disabling.")
3045
                j = j + 1
3046

    
3047
            freq = self._memobj._2tone.freqs[i-1]
3048
            for char in ['A', 'B', 'C', 'D']:
3049
                setting_name = "freq" + str(char)
3050

    
3051
                tmp = freq[setting_name]
3052
                if tmp == 65535:
3053
                    tmp = 0
3054
                if tmp != 0:
3055
                    expected = int(round(2304000.0/tmp))
3056
                    from_mem = freq["derived_from_" + setting_name]
3057
                    if expected != from_mem:
3058
                        LOG.error("Expected " + str(expected) +
3059
                                  " but read " + str(from_mem) +
3060
                                  ". Disabling 2Tone Decode Freqs!")
3061
                        break
3062
                val = RadioSettingValueInteger(0, 65535, tmp)
3063
                frq = RadioSetting("2tone_dec_" + str(i) + "_freq" + str(char),
3064
                                   ("Decode Frequency " + str(char)), val)
3065
                val.set_validate_callback(_2tone_validate)
3066
                frq.set_apply_callback(apply_2tone_freq_pair, freq)
3067
                _2tone_dec_code.append(frq)
3068

    
3069
            i = i + 1
3070

    
3071
        return top
3072

    
3073
    def set_settings(self, settings):
3074
        _settings = self._memobj.settings
3075
        for element in settings:
3076
            if not isinstance(element, RadioSetting):
3077
                if element.get_name() == "fm_preset":
3078
                    self._set_fm_preset(element)
3079
                else:
3080
                    self.set_settings(element)
3081
                    continue
3082
            else:
3083
                try:
3084
                    name = element.get_name()
3085
                    if "." in name:
3086
                        bits = name.split(".")
3087
                        obj = self._memobj
3088
                        for bit in bits[:-1]:
3089
                            if "/" in bit:
3090
                                bit, index = bit.split("/", 1)
3091
                                index = int(index)
3092
                                obj = getattr(obj, bit)[index]
3093
                            else:
3094
                                obj = getattr(obj, bit)
3095
                        setting = bits[-1]
3096
                    else:
3097
                        obj = _settings
3098
                        setting = element.get_name()
3099

    
3100
                    if element.has_apply_callback():
3101
                        LOG.debug("Using apply callback")
3102
                        element.run_apply_callback()
3103
                    elif element.value.get_mutable():
3104
                        LOG.debug("Setting %s = %s" % (setting, element.value))
3105
                        setattr(obj, setting, element.value)
3106
                except Exception, e:
3107
                    LOG.debug(element.get_name())
3108
                    raise
3109

    
3110
    @classmethod
3111
    def match_model(cls, filedata, filename):
3112
        match_size = False
3113
        match_model = False
3114

    
3115
        # testing the file data size
3116
        if len(filedata) == MEM_SIZE:
3117
            match_size = True
3118

    
3119
        # testing the firmware model fingerprint
3120
        match_model = model_match(cls, filedata)
3121

    
3122
        if match_size and match_model:
3123
            return True
3124
        else:
3125
            return False
3126

    
3127

    
3128
MEM_FORMAT = """
3129
#seekto 0x0000;
3130
struct {
3131
  lbcd rxfreq[4];
3132
  lbcd txfreq[4];
3133
  ul16 rxtone;
3134
  ul16 txtone;
3135
  u8 unknown0:4,
3136
     scode:4;
3137
  u8 unknown1:2,
3138
     spmute:2,
3139
     unknown2:2,
3140
     optsig:2;
3141
  u8 unknown3:3,
3142
     scramble:1,
3143
     unknown4:3,
3144
     power:1;
3145
  u8 unknown5:1,
3146
     wide:1,
3147
     unknown6:2,
3148
     bcl:1,
3149
     add:1,
3150
     pttid:2;
3151
} memory[200];
3152

    
3153
#seekto 0x0E00;
3154
struct {
3155
  u8 tdr;
3156
  u8 unknown1;
3157
  u8 sql;
3158
  u8 unknown2[2];
3159
  u8 tot;
3160
  u8 apo;           // BTech radios use this as the Auto Power Off time
3161
                    // other radios use this as pre-Time Out Alert
3162
  u8 unknown3;
3163
  u8 abr;
3164
  u8 beep;
3165
  u8 unknown4[4];
3166
  u8 dtmfst;
3167
  u8 unknown5[2];
3168
  u8 prisc;
3169
  u8 prich;
3170
  u8 screv;
3171
  u8 unknown6[2];
3172
  u8 pttid;
3173
  u8 pttlt;
3174
  u8 unknown7;
3175
  u8 emctp;
3176
  u8 emcch;
3177
  u8 ringt;
3178
  u8 unknown8;
3179
  u8 camdf;
3180
  u8 cbmdf;
3181
  u8 sync;          // BTech radios use this as the display sync setting
3182
                    // other radios use this as the auto keypad lock setting
3183
  u8 ponmsg;
3184
  u8 wtled;
3185
  u8 rxled;
3186
  u8 txled;
3187
  u8 unknown9[5];
3188
  u8 anil;
3189
  u8 reps;
3190
  u8 repm;
3191
  u8 tdrab;
3192
  u8 ste;
3193
  u8 rpste;
3194
  u8 rptdl;
3195
  u8 mgain;
3196
  u8 dtmfg;
3197
} settings;
3198

    
3199
#seekto 0x0E80;
3200
struct {
3201
  u8 unknown1;
3202
  u8 vfomr;
3203
  u8 keylock;
3204
  u8 unknown2;
3205
  u8 unknown3:4,
3206
     vfomren:1,
3207
     unknown4:1,
3208
     reseten:1,
3209
     menuen:1;
3210
  u8 unknown5[11];
3211
  u8 dispab;
3212
  u8 mrcha;
3213
  u8 mrchb;
3214
  u8 menu;
3215
} settings2;
3216

    
3217
#seekto 0x0EC0;
3218
struct {
3219
  char line1[6];
3220
  char line2[6];
3221
} poweron_msg;
3222

    
3223
struct settings_vfo {
3224
  u8 freq[8];
3225
  u8 offset[6];
3226
  u8 unknown2[2];
3227
  ul16 rxtone;
3228
  ul16 txtone;
3229
  u8 scode;
3230
  u8 spmute;
3231
  u8 optsig;
3232
  u8 scramble;
3233
  u8 wide;
3234
  u8 power;
3235
  u8 shiftd;
3236
  u8 step;
3237
  u8 unknown3[4];
3238
};
3239

    
3240
#seekto 0x0F00;
3241
struct {
3242
  struct settings_vfo a;
3243
  struct settings_vfo b;
3244
} vfo;
3245

    
3246
#seekto 0x1000;
3247
struct {
3248
  char name[6];
3249
  u8 unknown1[10];
3250
} names[200];
3251

    
3252
#seekto 0x2400;
3253
struct {
3254
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3255
  u8 group_tone;
3256
  u8 repeat_tone;
3257
  u8 unused[13];
3258
} _5tone_std_settings[15];
3259

    
3260
#seekto 0x2500;
3261
struct {
3262
  u8 frame1[5];
3263
  u8 frame2[5];
3264
  u8 frame3[5];
3265
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3266
} _5tone_codes[15];
3267

    
3268
#seekto 0x25F0;
3269
struct {
3270
  u8 _5tone_delay1; // * 10ms
3271
  u8 _5tone_delay2; // * 10ms
3272
  u8 _5tone_delay3; // * 10ms
3273
  u8 _5tone_first_digit_ext_length;
3274
  u8 unknown1;
3275
  u8 unknown2;
3276
  u8 unknown3;
3277
  u8 unknown4;
3278
  u8 decode_standard;
3279
  u8 unknown5:5,
3280
     _5tone_decode_call_frame3:1,
3281
     _5tone_decode_call_frame2:1,
3282
     _5tone_decode_call_frame1:1;
3283
  u8 unknown6:5,
3284
     _5tone_decode_disp_frame3:1,
3285
     _5tone_decode_disp_frame2:1,
3286
     _5tone_decode_disp_frame1:1;
3287
  u8 decode_reset_time; // * 100 + 100ms
3288
} _5tone_settings;
3289

    
3290
#seekto 0x2900;
3291
struct {
3292
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3293
} dtmf_codes[15];
3294

    
3295
#seekto 0x29F0;
3296
struct {
3297
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
3298
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
3299
  u8 unknown0[14];
3300
  u8 inspection[16];
3301
  u8 monitor[16];
3302
  u8 alarmcode[16];
3303
  u8 stun[16];
3304
  u8 kill[16];
3305
  u8 revive[16];
3306
  u8 unknown1[16];
3307
  u8 unknown2[16];
3308
  u8 unknown3[16];
3309
  u8 unknown4[16];
3310
  u8 unknown5[16];
3311
  u8 unknown6[16];
3312
  u8 unknown7[16];
3313
  u8 masterid[16];
3314
  u8 viceid[16];
3315
  u8 unused01:7,
3316
     mastervice:1;
3317
  u8 unused02:3,
3318
     mrevive:1,
3319
     mkill:1,
3320
     mstun:1,
3321
     mmonitor:1,
3322
     minspection:1;
3323
  u8 unused03:3,
3324
     vrevive:1,
3325
     vkill:1,
3326
     vstun:1,
3327
     vmonitor:1,
3328
     vinspection:1;
3329
  u8 unused04:6,
3330
     txdisable:1,
3331
     rxdisable:1;
3332
  u8 groupcode;
3333
  u8 spacecode;
3334
  u8 delayproctime; // * 100 + 100ms
3335
  u8 resettime;     // * 100 + 100ms
3336
} dtmf_settings;
3337

    
3338
#seekto 0x2D00;
3339
struct {
3340
  struct {
3341
    ul16 freq1;
3342
    u8 unused01[6];
3343
    ul16 freq2;
3344
    u8 unused02[6];
3345
  } _2tone_encode[15];
3346
  u8 duration_1st_tone; // *10ms
3347
  u8 duration_2nd_tone; // *10ms
3348
  u8 duration_gap;      // *10ms
3349
  u8 unused03[13];
3350
  struct {
3351
    struct {
3352
      u8 dec;      // one out of LIST_2TONE_DEC
3353
      u8 response; // one out of LIST_2TONE_RESPONSE
3354
      u8 alert;    // 1-16
3355
    } decs[4];
3356
    u8 unused04[4];
3357
  } _2tone_decode[15];
3358
  u8 unused05[16];
3359

    
3360
  struct {
3361
    ul16 freqA;
3362
    ul16 freqB;
3363
    ul16 freqC;
3364
    ul16 freqD;
3365
    // unknown what those values mean, but they are
3366
    // derived from configured frequencies
3367
    ul16 derived_from_freqA; // 2304000/freqA
3368
    ul16 derived_from_freqB; // 2304000/freqB
3369
    ul16 derived_from_freqC; // 2304000/freqC
3370
    ul16 derived_from_freqD; // 2304000/freqD
3371
  }freqs[15];
3372
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
3373
} _2tone;
3374

    
3375
#seekto 0x3000;
3376
struct {
3377
  u8 freq[8];
3378
  char broadcast_station_name[6];
3379
  u8 unknown[2];
3380
} fm_radio_preset[16];
3381

    
3382
#seekto 0x3C90;
3383
struct {
3384
  u8 vhf_low[3];
3385
  u8 vhf_high[3];
3386
  u8 uhf_low[3];
3387
  u8 uhf_high[3];
3388
} ranges;
3389

    
3390
// the UV-2501+220 & KT8900R has different zones for storing ranges
3391

    
3392
#seekto 0x3CD0;
3393
struct {
3394
  u8 vhf_low[3];
3395
  u8 vhf_high[3];
3396
  u8 unknown1[4];
3397
  u8 unknown2[6];
3398
  u8 vhf2_low[3];
3399
  u8 vhf2_high[3];
3400
  u8 unknown3[4];
3401
  u8 unknown4[6];
3402
  u8 uhf_low[3];
3403
  u8 uhf_high[3];
3404
} ranges220;
3405

    
3406
#seekto 0x3F70;
3407
struct {
3408
  char fp[6];
3409
} fingerprint;
3410

    
3411
"""
3412

    
3413

    
3414
class BTech(BTechMobileCommon):
3415
    """BTECH's UV-5001 and alike radios"""
3416
    BANDS = 2
3417
    COLOR_LCD = False
3418
    NAME_LENGTH = 6
3419

    
3420
    def set_options(self):
3421
        """This is to read the options from the image and set it in the
3422
        environment, for now just the limits of the freqs in the VHF/UHF
3423
        ranges"""
3424

    
3425
        # setting the correct ranges for each radio type
3426
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3427
            # the model 2501+220 has a segment in 220
3428
            # and a different position in the memmap
3429
            # also the QYT KT8900R
3430
            ranges = self._memobj.ranges220
3431
        else:
3432
            ranges = self._memobj.ranges
3433

    
3434
        # the normal dual bands
3435
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3436
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3437

    
3438
        # DEBUG
3439
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3440
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3441

    
3442
        # 220Mhz radios case
3443
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3444
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3445
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3446
            self._220_range = vhf2
3447

    
3448
        # set the class with the real data
3449
        self._vhf_range = vhf
3450
        self._uhf_range = uhf
3451

    
3452
    def process_mmap(self):
3453
        """Process the mem map into the mem object"""
3454

    
3455
        # Get it
3456
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
3457

    
3458
        # load specific parameters from the radio image
3459
        self.set_options()
3460

    
3461

    
3462
# Declaring Aliases (Clones of the real radios)
3463
class JT2705M(chirp_common.Alias):
3464
    VENDOR = "Jetstream"
3465
    MODEL = "JT2705M"
3466

    
3467

    
3468
class JT6188Mini(chirp_common.Alias):
3469
    VENDOR = "Juentai"
3470
    MODEL = "JT-6188 Mini"
3471

    
3472

    
3473
class JT6188Plus(chirp_common.Alias):
3474
    VENDOR = "Juentai"
3475
    MODEL = "JT-6188 Plus"
3476

    
3477

    
3478
class SSGT890(chirp_common.Alias):
3479
    VENDOR = "Sainsonic"
3480
    MODEL = "GT-890"
3481

    
3482

    
3483
class ZastoneMP300(chirp_common.Alias):
3484
    VENDOR = "Zastone"
3485
    MODEL = "MP-300"
3486

    
3487

    
3488
# real radios
3489
@directory.register
3490
class UV2501(BTech):
3491
    """Baofeng Tech UV2501"""
3492
    MODEL = "UV-2501"
3493
    _fileid = [UV2501G3_fp,
3494
               UV2501G2_fp,
3495
               UV2501pp2_fp,
3496
               UV2501pp_fp]
3497

    
3498

    
3499
@directory.register
3500
class UV2501_220(BTech):
3501
    """Baofeng Tech UV2501+220"""
3502
    MODEL = "UV-2501+220"
3503
    BANDS = 3
3504
    _magic = MSTRING_220
3505
    _id2 = [UV2501_220pp_id, ]
3506
    _fileid = [UV2501_220G3_fp,
3507
               UV2501_220G2_fp,
3508
               UV2501_220_fp,
3509
               UV2501_220pp_fp]
3510

    
3511

    
3512
@directory.register
3513
class UV5001(BTech):
3514
    """Baofeng Tech UV5001"""
3515
    MODEL = "UV-5001"
3516
    _fileid = [UV5001G3_fp,
3517
               UV5001G22_fp,
3518
               UV5001G2_fp,
3519
               UV5001alpha_fp,
3520
               UV5001pp_fp]
3521
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
3522
                     chirp_common.PowerLevel("Low", watts=10)]
3523

    
3524

    
3525
@directory.register
3526
class MINI8900(BTech):
3527
    """WACCOM MINI-8900"""
3528
    VENDOR = "WACCOM"
3529
    MODEL = "MINI-8900"
3530
    _magic = MSTRING_MINI8900
3531
    _fileid = [MINI8900_fp, ]
3532
    # Clones
3533
    ALIASES = [JT6188Plus, ]
3534

    
3535

    
3536
@directory.register
3537
class KTUV980(BTech):
3538
    """QYT KT-UV980"""
3539
    VENDOR = "QYT"
3540
    MODEL = "KT-UV980"
3541
    _vhf_range = (136000000, 175000000)
3542
    _uhf_range = (400000000, 481000000)
3543
    _magic = MSTRING_MINI8900
3544
    _fileid = [KTUV980_fp, ]
3545
    # Clones
3546
    ALIASES = [JT2705M, ]
3547

    
3548
# Please note that there is a version of this radios that is a clone of the
3549
# Waccom Mini8900, maybe an early version?
3550

    
3551

    
3552
class OTGRadioV1(chirp_common.Alias):
3553
    VENDOR = 'OTGSTUFF'
3554
    MODEL = 'OTG Radio v1'
3555

    
3556

    
3557
@directory.register
3558
class KT9800(BTech):
3559
    """QYT KT8900"""
3560
    VENDOR = "QYT"
3561
    MODEL = "KT8900"
3562
    _vhf_range = (136000000, 175000000)
3563
    _uhf_range = (400000000, 481000000)
3564
    _magic = MSTRING_KT8900
3565
    _fileid = [KT8900_fp,
3566
               KT8900_fp1,
3567
               KT8900_fp2,
3568
               KT8900_fp3,
3569
               KT8900_fp4,
3570
               KT8900_fp5,
3571
               KT8900_fp6]
3572
    _id2 = [KT8900_id, KT8900_id2]
3573
    # Clones
3574
    ALIASES = [JT6188Mini, SSGT890, ZastoneMP300]
3575

    
3576

    
3577
@directory.register
3578
class KT9800R(BTech):
3579
    """QYT KT8900R"""
3580
    VENDOR = "QYT"
3581
    MODEL = "KT8900R"
3582
    BANDS = 3
3583
    _vhf_range = (136000000, 175000000)
3584
    _220_range = (240000000, 271000000)
3585
    _uhf_range = (400000000, 481000000)
3586
    _magic = MSTRING_KT8900R
3587
    _fileid = [KT8900R_fp,
3588
               KT8900R_fp1,
3589
               KT8900R_fp2,
3590
               KT8900R_fp3,
3591
               KT8900R_fp4]
3592
    _id2 = [KT8900R_id, KT8900R_id2]
3593

    
3594

    
3595
@directory.register
3596
class LT588UV(BTech):
3597
    """LUITON LT-588UV"""
3598
    VENDOR = "LUITON"
3599
    MODEL = "LT-588UV"
3600
    _vhf_range = (136000000, 175000000)
3601
    _uhf_range = (400000000, 481000000)
3602
    _magic = MSTRING_KT8900
3603
    _fileid = [LT588UV_fp,
3604
               LT588UV_fp1]
3605
    _power_levels = [chirp_common.PowerLevel("High", watts=60),
3606
                     chirp_common.PowerLevel("Low", watts=10)]
3607

    
3608

    
3609
COLOR_MEM_FORMAT = """
3610
#seekto 0x0000;
3611
struct {
3612
  lbcd rxfreq[4];
3613
  lbcd txfreq[4];
3614
  ul16 rxtone;
3615
  ul16 txtone;
3616
  u8 unknown0:4,
3617
     scode:4;
3618
  u8 unknown1:2,
3619
     spmute:2,
3620
     unknown2:2,
3621
     optsig:2;
3622
  u8 unknown3:3,
3623
     scramble:1,
3624
     unknown4:2,
3625
     power:2;
3626
  u8 unknown5:1,
3627
     wide:1,
3628
     unknown6:2,
3629
     bcl:1,
3630
     add:1,
3631
     pttid:2;
3632
} memory[200];
3633

    
3634
#seekto 0x0E00;
3635
struct {
3636
  u8 tmr;              // 0e00
3637
  u8 unknown1;
3638
  u8 sql;
3639
  u8 unknown2;
3640
  u8 mgain2;
3641
  u8 tot;
3642
  u8 apo;
3643
  u8 unknown3;
3644
  u8 abr;
3645
  u8 beep;             // 0e09
3646
  u8 unknown4[4];
3647
  u8 dtmfst;           // 0e0e
3648
  u8 unknown5[2];
3649
  u8 screv;            // 0e11
3650
  u8 unknown6[2];
3651
  u8 pttid;            // 0314
3652
  u8 pttlt;
3653
  u8 unknown7;
3654
  u8 emctp;
3655
  u8 emcch;
3656
  u8 sigbp;
3657
  u8 unknown8;
3658
  u8 camdf;
3659
  u8 cbmdf;
3660
  u8 ccmdf;
3661
  u8 cdmdf;
3662
  u8 langua;           // 0e1f
3663
  u8 sync;          // BTech radios use this as the display sync
3664
                    // setting, other radios use this as the auto
3665
                    // keypad lock setting
3666
  u8 mainfc;           // 0e21
3667
  u8 mainbc;
3668
  u8 menufc;
3669
  u8 menubc;
3670
  u8 stafc;
3671
  u8 stabc;
3672
  u8 sigfc;
3673
  u8 sigbc;
3674
  u8 rxfc;
3675
  u8 txfc;
3676
  u8 txdisp;           // 0e2b
3677
  u8 unknown9[5];
3678
  u8 anil;             // 0e31
3679
  u8 reps;
3680
  u8 repm;
3681
  u8 tmrmr;
3682
  u8 ste;
3683
  u8 rpste;
3684
  u8 rptdl;
3685
  u8 dtmfg;
3686
  u8 mgain;            // used by db25-g for ponyey
3687
  u8 skiptx;
3688
  u8 scmode;           // 0e3b
3689
} settings;
3690

    
3691
#seekto 0x0E80;
3692
struct {
3693
  u8 unknown1;
3694
  u8 vfomr;
3695
  u8 keylock;
3696
  u8 unknown2;
3697
  u8 unknown3:4,
3698
     vfomren:1,
3699
     unknown4:1,
3700
     reseten:1,
3701
     menuen:1;
3702
  u8 unknown5[11];
3703
  u8 dispab;
3704
  u8 unknown6[2];
3705
  u8 menu;
3706
  u8 unknown7[7];
3707
  u8 vfomra;
3708
  u8 vfomrb;
3709
  u8 vfomrc;
3710
  u8 vfomrd;
3711
  u8 mrcha;
3712
  u8 mrchb;
3713
  u8 mrchc;
3714
  u8 mrchd;
3715
} settings2;
3716

    
3717
struct settings_vfo {
3718
  u8 freq[8];
3719
  u8 offset[6];
3720
  u8 unknown2[2];
3721
  ul16 rxtone;
3722
  ul16 txtone;
3723
  u8 scode;
3724
  u8 spmute;
3725
  u8 optsig;
3726
  u8 scramble;
3727
  u8 wide;
3728
  u8 power;
3729
  u8 shiftd;
3730
  u8 step;
3731
  u8 unknown3[4];
3732
};
3733

    
3734
#seekto 0x0F00;
3735
struct {
3736
  struct settings_vfo a;
3737
  struct settings_vfo b;
3738
  struct settings_vfo c;
3739
  struct settings_vfo d;
3740
} vfo;
3741

    
3742
#seekto 0x0F80;
3743
struct {
3744
  char line1[8];
3745
  char line2[8];
3746
  char line3[8];
3747
  char line4[8];
3748
  char line5[8];
3749
  char line6[8];
3750
  char line7[8];
3751
  char line8[8];
3752
} poweron_msg;
3753

    
3754
#seekto 0x1000;
3755
struct {
3756
  char name[8];
3757
  u8 unknown1[8];
3758
} names[200];
3759

    
3760
#seekto 0x2400;
3761
struct {
3762
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3763
  u8 group_tone;
3764
  u8 repeat_tone;
3765
  u8 unused[13];
3766
} _5tone_std_settings[15];
3767

    
3768
#seekto 0x2500;
3769
struct {
3770
  u8 frame1[5];
3771
  u8 frame2[5];
3772
  u8 frame3[5];
3773
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3774
} _5tone_codes[15];
3775

    
3776
#seekto 0x25F0;
3777
struct {
3778
  u8 _5tone_delay1; // * 10ms
3779
  u8 _5tone_delay2; // * 10ms
3780
  u8 _5tone_delay3; // * 10ms
3781
  u8 _5tone_first_digit_ext_length;
3782
  u8 unknown1;
3783
  u8 unknown2;
3784
  u8 unknown3;
3785
  u8 unknown4;
3786
  u8 decode_standard;
3787
  u8 unknown5:5,
3788
     _5tone_decode_call_frame3:1,
3789
     _5tone_decode_call_frame2:1,
3790
     _5tone_decode_call_frame1:1;
3791
  u8 unknown6:5,
3792
     _5tone_decode_disp_frame3:1,
3793
     _5tone_decode_disp_frame2:1,
3794
     _5tone_decode_disp_frame1:1;
3795
  u8 decode_reset_time; // * 100 + 100ms
3796
} _5tone_settings;
3797

    
3798
#seekto 0x2900;
3799
struct {
3800
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3801
} dtmf_codes[15];
3802

    
3803
#seekto 0x29F0;
3804
struct {
3805
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
3806
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
3807
  u8 unknown0[14];
3808
  u8 inspection[16];
3809
  u8 monitor[16];
3810
  u8 alarmcode[16];
3811
  u8 stun[16];
3812
  u8 kill[16];
3813
  u8 revive[16];
3814
  u8 unknown1[16];
3815
  u8 unknown2[16];
3816
  u8 unknown3[16];
3817
  u8 unknown4[16];
3818
  u8 unknown5[16];
3819
  u8 unknown6[16];
3820
  u8 unknown7[16];
3821
  u8 masterid[16];
3822
  u8 viceid[16];
3823
  u8 unused01:7,
3824
     mastervice:1;
3825
  u8 unused02:3,
3826
     mrevive:1,
3827
     mkill:1,
3828
     mstun:1,
3829
     mmonitor:1,
3830
     minspection:1;
3831
  u8 unused03:3,
3832
     vrevive:1,
3833
     vkill:1,
3834
     vstun:1,
3835
     vmonitor:1,
3836
     vinspection:1;
3837
  u8 unused04:6,
3838
     txdisable:1,
3839
     rxdisable:1;
3840
  u8 groupcode;
3841
  u8 spacecode;
3842
  u8 delayproctime; // * 100 + 100ms
3843
  u8 resettime;     // * 100 + 100ms
3844
} dtmf_settings;
3845

    
3846
#seekto 0x2D00;
3847
struct {
3848
  struct {
3849
    ul16 freq1;
3850
    u8 unused01[6];
3851
    ul16 freq2;
3852
    u8 unused02[6];
3853
  } _2tone_encode[15];
3854
  u8 duration_1st_tone; // *10ms
3855
  u8 duration_2nd_tone; // *10ms
3856
  u8 duration_gap;      // *10ms
3857
  u8 unused03[13];
3858
  struct {
3859
    struct {
3860
      u8 dec;      // one out of LIST_2TONE_DEC
3861
      u8 response; // one out of LIST_2TONE_RESPONSE
3862
      u8 alert;    // 1-16
3863
    } decs[4];
3864
    u8 unused04[4];
3865
  } _2tone_decode[15];
3866
  u8 unused05[16];
3867

    
3868
  struct {
3869
    ul16 freqA;
3870
    ul16 freqB;
3871
    ul16 freqC;
3872
    ul16 freqD;
3873
    // unknown what those values mean, but they are
3874
    // derived from configured frequencies
3875
    ul16 derived_from_freqA; // 2304000/freqA
3876
    ul16 derived_from_freqB; // 2304000/freqB
3877
    ul16 derived_from_freqC; // 2304000/freqC
3878
    ul16 derived_from_freqD; // 2304000/freqD
3879
  }freqs[15];
3880
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
3881
} _2tone;
3882

    
3883
#seekto 0x3D80;
3884
struct {
3885
  u8 vhf_low[3];
3886
  u8 vhf_high[3];
3887
  u8 unknown1[4];
3888
  u8 unknown2[6];
3889
  u8 vhf2_low[3];
3890
  u8 vhf2_high[3];
3891
  u8 unknown3[4];
3892
  u8 unknown4[6];
3893
  u8 uhf_low[3];
3894
  u8 uhf_high[3];
3895
  u8 unknown5[4];
3896
  u8 unknown6[6];
3897
  u8 uhf2_low[3];
3898
  u8 uhf2_high[3];
3899
} ranges;
3900

    
3901
#seekto 0x3F70;
3902
struct {
3903
  char fp[6];
3904
} fingerprint;
3905

    
3906
"""
3907

    
3908

    
3909
class BTechColor(BTechMobileCommon):
3910
    """BTECH's Color LCD Mobile and alike radios"""
3911
    COLOR_LCD = True
3912
    NAME_LENGTH = 8
3913
    LIST_TMR = LIST_TMR16
3914
    _gmrs = False
3915

    
3916
    def process_mmap(self):
3917
        """Process the mem map into the mem object"""
3918

    
3919
        # Get it
3920
        self._memobj = bitwise.parse(COLOR_MEM_FORMAT, self._mmap)
3921

    
3922
        # load specific parameters from the radio image
3923
        self.set_options()
3924

    
3925
    def set_options(self):
3926
        """This is to read the options from the image and set it in the
3927
        environment, for now just the limits of the freqs in the VHF/UHF
3928
        ranges"""
3929

    
3930
        # setting the correct ranges for each radio type
3931
        ranges = self._memobj.ranges
3932

    
3933
        # the normal dual bands
3934
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3935
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3936

    
3937
        # DEBUG
3938
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3939
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3940

    
3941
        # the additional bands
3942
        if self.MODEL in ["UV-25X4", "KT7900D"]:
3943
            # 200Mhz band
3944
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3945
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3946
            self._220_range = vhf2
3947

    
3948
            # 350Mhz band
3949
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
3950
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
3951
            self._350_range = uhf2
3952

    
3953
        # set the class with the real data
3954
        self._vhf_range = vhf
3955
        self._uhf_range = uhf
3956

    
3957

    
3958
# Declaring Aliases (Clones of the real radios)
3959
class SKT8900D(chirp_common.Alias):
3960
    VENDOR = "Surecom"
3961
    MODEL = "S-KT8900D"
3962

    
3963

    
3964
class QB25(chirp_common.Alias):
3965
    VENDOR = "Radioddity"
3966
    MODEL = "QB25"
3967

    
3968

    
3969
# real radios
3970
@directory.register
3971
class UV25X2(BTechColor):
3972
    """Baofeng Tech UV25X2"""
3973
    MODEL = "UV-25X2"
3974
    BANDS = 2
3975
    _vhf_range = (130000000, 180000000)
3976
    _uhf_range = (400000000, 521000000)
3977
    _magic = MSTRING_UV25X2
3978
    _fileid = [UV25X2_fp, ]
3979

    
3980

    
3981
@directory.register
3982
class UV25X4(BTechColor):
3983
    """Baofeng Tech UV25X4"""
3984
    MODEL = "UV-25X4"
3985
    BANDS = 4
3986
    _vhf_range = (130000000, 180000000)
3987
    _220_range = (200000000, 271000000)
3988
    _uhf_range = (400000000, 521000000)
3989
    _350_range = (350000000, 391000000)
3990
    _magic = MSTRING_UV25X4
3991
    _fileid = [UV25X4_fp, ]
3992

    
3993

    
3994
@directory.register
3995
class UV50X2(BTechColor):
3996
    """Baofeng Tech UV50X2"""
3997
    MODEL = "UV-50X2"
3998
    BANDS = 2
3999
    _vhf_range = (130000000, 180000000)
4000
    _uhf_range = (400000000, 521000000)
4001
    _magic = MSTRING_UV25X2
4002
    _fileid = [UV50X2_fp, ]
4003
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
4004
                     chirp_common.PowerLevel("Low", watts=10)]
4005

    
4006

    
4007
@directory.register
4008
class KT7900D(BTechColor):
4009
    """QYT KT7900D"""
4010
    VENDOR = "QYT"
4011
    MODEL = "KT7900D"
4012
    BANDS = 4
4013
    LIST_TMR = LIST_TMR15
4014
    _vhf_range = (136000000, 175000000)
4015
    _220_range = (200000000, 271000000)
4016
    _uhf_range = (400000000, 481000000)
4017
    _350_range = (350000000, 371000000)
4018
    _magic = MSTRING_KT8900D
4019
    _fileid = [KT7900D_fp, KT7900D_fp1, KT7900D_fp2, KT7900D_fp3, KT7900D_fp4,
4020
               KT7900D_fp5, KT7900D_fp6, QB25_fp, ]
4021
    # Clones
4022
    ALIASES = [SKT8900D, QB25, ]
4023

    
4024

    
4025
@directory.register
4026
class KT8900D(BTechColor):
4027
    """QYT KT8900D"""
4028
    VENDOR = "QYT"
4029
    MODEL = "KT8900D"
4030
    BANDS = 2
4031
    LIST_TMR = LIST_TMR15
4032
    _vhf_range = (136000000, 175000000)
4033
    _uhf_range = (400000000, 481000000)
4034
    _magic = MSTRING_KT8900D
4035
    _fileid = [KT8900D_fp3, KT8900D_fp2, KT8900D_fp1, KT8900D_fp]
4036

    
4037
    # Clones
4038
    ALIASES = [OTGRadioV1]
4039

    
4040

    
4041
@directory.register
4042
class KT5800(BTechColor):
4043
    """QYT KT5800"""
4044
    VENDOR = "QYT"
4045
    MODEL = "KT5800"
4046
    BANDS = 2
4047
    LIST_TMR = LIST_TMR15
4048
    _vhf_range = (136000000, 175000000)
4049
    _uhf_range = (400000000, 481000000)
4050
    _magic = MSTRING_KT8900D
4051
    _fileid = [KT5800_fp, ]
4052

    
4053

    
4054
@directory.register
4055
class DB25G(BTechColor):
4056
    """Radioddity DB25-G"""
4057
    VENDOR = "Radioddity"
4058
    MODEL = "DB25-G"
4059
    BANDS = 2
4060
    LIST_TMR = LIST_TMR15
4061
    _vhf_range = (136000000, 175000000)
4062
    _uhf_range = (400000000, 481000000)
4063
    _magic = MSTRING_KT8900D
4064
    _fileid = [DB25G_fp, ]
4065
    _gmrs = True
4066
    _power_levels = [chirp_common.PowerLevel("High", watts=25),
4067
                     chirp_common.PowerLevel("Mid", watts=15),
4068
                     chirp_common.PowerLevel("Low", watts=5)]
4069

    
4070
    @classmethod
4071
    def match_model(cls, filedata, filename):
4072
        # This model is only ever matched via metadata
4073
        return False
4074

    
4075

    
4076
GMRS_MEM_FORMAT = """
4077
#seekto 0x0000;
4078
struct {
4079
  lbcd rxfreq[4];
4080
  lbcd txfreq[4];
4081
  ul16 rxtone;
4082
  ul16 txtone;
4083
  u8 unknown0:4,
4084
     scode:4;
4085
  u8 unknown1:2,
4086
     spmute:2,
4087
     unknown2:2,
4088
     optsig:2;
4089
  u8 unknown3:3,
4090
     scramble:1,
4091
     unknown4:2,
4092
     power:2;
4093
  u8 unknown5:1,
4094
     wide:1,
4095
     unknown6:2,
4096
     bcl:1,
4097
     add:1,
4098
     pttid:2;
4099
} memory[256];
4100

    
4101
#seekto 0x1000;
4102
struct {
4103
  char name[7];
4104
  u8 unknown1[9];
4105
} names[256];
4106

    
4107
#seekto 0x2400;
4108
struct {
4109
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
4110
  u8 group_tone;
4111
  u8 repeat_tone;
4112
  u8 unused[13];
4113
} _5tone_std_settings[15];
4114

    
4115
#seekto 0x2500;
4116
struct {
4117
  u8 frame1[5];
4118
  u8 frame2[5];
4119
  u8 frame3[5];
4120
  u8 standard;   // one out of LIST_5TONE_STANDARDS
4121
} _5tone_codes[15];
4122

    
4123
#seekto 0x25F0;
4124
struct {
4125
  u8 _5tone_delay1; // * 10ms
4126
  u8 _5tone_delay2; // * 10ms
4127
  u8 _5tone_delay3; // * 10ms
4128
  u8 _5tone_first_digit_ext_length;
4129
  u8 unknown1;
4130
  u8 unknown2;
4131
  u8 unknown3;
4132
  u8 unknown4;
4133
  u8 decode_standard;
4134
  u8 unknown5:5,
4135
     _5tone_decode_call_frame3:1,
4136
     _5tone_decode_call_frame2:1,
4137
     _5tone_decode_call_frame1:1;
4138
  u8 unknown6:5,
4139
     _5tone_decode_disp_frame3:1,
4140
     _5tone_decode_disp_frame2:1,
4141
     _5tone_decode_disp_frame1:1;
4142
  u8 decode_reset_time; // * 100 + 100ms
4143
} _5tone_settings;
4144

    
4145
#seekto 0x2900;
4146
struct {
4147
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
4148
} dtmf_codes[15];
4149

    
4150
#seekto 0x29F0;
4151
struct {
4152
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
4153
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
4154
  u8 unknown0[14];
4155
  u8 inspection[16];
4156
  u8 monitor[16];
4157
  u8 alarmcode[16];
4158
  u8 stun[16];
4159
  u8 kill[16];
4160
  u8 revive[16];
4161
  u8 unknown1[16];
4162
  u8 unknown2[16];
4163
  u8 unknown3[16];
4164
  u8 unknown4[16];
4165
  u8 unknown5[16];
4166
  u8 unknown6[16];
4167
  u8 unknown7[16];
4168
  u8 masterid[16];
4169
  u8 viceid[16];
4170
  u8 unused01:7,
4171
     mastervice:1;
4172
  u8 unused02:3,
4173
     mrevive:1,
4174
     mkill:1,
4175
     mstun:1,
4176
     mmonitor:1,
4177
     minspection:1;
4178
  u8 unused03:3,
4179
     vrevive:1,
4180
     vkill:1,
4181
     vstun:1,
4182
     vmonitor:1,
4183
     vinspection:1;
4184
  u8 unused04:6,
4185
     txdisable:1,
4186
     rxdisable:1;
4187
  u8 groupcode;
4188
  u8 spacecode;
4189
  u8 delayproctime; // * 100 + 100ms
4190
  u8 resettime;     // * 100 + 100ms
4191
} dtmf_settings;
4192

    
4193
#seekto 0x2D00;
4194
struct {
4195
  struct {
4196
    ul16 freq1;
4197
    u8 unused01[6];
4198
    ul16 freq2;
4199
    u8 unused02[6];
4200
  } _2tone_encode[15];
4201
  u8 duration_1st_tone; // *10ms
4202
  u8 duration_2nd_tone; // *10ms
4203
  u8 duration_gap;      // *10ms
4204
  u8 unused03[13];
4205
  struct {
4206
    struct {
4207
      u8 dec;      // one out of LIST_2TONE_DEC
4208
      u8 response; // one out of LIST_2TONE_RESPONSE
4209
      u8 alert;    // 1-16
4210
    } decs[4];
4211
    u8 unused04[4];
4212
  } _2tone_decode[15];
4213
  u8 unused05[16];
4214

    
4215
  struct {
4216
    ul16 freqA;
4217
    ul16 freqB;
4218
    ul16 freqC;
4219
    ul16 freqD;
4220
    // unknown what those values mean, but they are
4221
    // derived from configured frequencies
4222
    ul16 derived_from_freqA; // 2304000/freqA
4223
    ul16 derived_from_freqB; // 2304000/freqB
4224
    ul16 derived_from_freqC; // 2304000/freqC
4225
    ul16 derived_from_freqD; // 2304000/freqD
4226
  }freqs[15];
4227
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
4228
} _2tone;
4229

    
4230
#seekto 0x3000;
4231
struct {
4232
  u8 freq[8];
4233
  char broadcast_station_name[6];
4234
  u8 unknown[2];
4235
} fm_radio_preset[16];
4236

    
4237
#seekto 0x3200;
4238
struct {
4239
  u8 tmr;
4240
  u8 unknown1;
4241
  u8 sql;
4242
  u8 unknown2;
4243
  u8 autolk;
4244
  u8 tot;
4245
  u8 apo;
4246
  u8 unknown3;
4247
  u8 abr;
4248
  u8 beep;
4249
  u8 unknown4[4];
4250
  u8 dtmfst;
4251
  u8 unknown5[2];
4252
  u8 screv;
4253
  u8 unknown6[2];
4254
  u8 pttid;
4255
  u8 pttlt;
4256
  u8 unknown7;
4257
  u8 emctp;
4258
  u8 emcch;
4259
  u8 sigbp;
4260
  u8 unknown8;
4261
  u8 camdf;
4262
  u8 cbmdf;
4263
  u8 ccmdf;
4264
  u8 cdmdf;
4265
  u8 langua;
4266
  u8 sync;
4267

    
4268

    
4269
  u8 stfc;
4270
  u8 mffc;
4271
  u8 sfafc;
4272
  u8 sfbfc;
4273
  u8 sfcfc;
4274
  u8 sfdfc;
4275
  u8 subfc;
4276
  u8 fmfc;
4277
  u8 sigfc;
4278
  u8 modfc;
4279
  u8 menufc;
4280
  u8 txfc;
4281
  u8 txdisp;
4282
  u8 unknown9[5];
4283
  u8 anil;
4284
  u8 reps;
4285
  u8 repm;
4286
  u8 tmrmr;
4287
  u8 ste;
4288
  u8 rpste;
4289
  u8 rptdl;
4290
  u8 dtmfg;
4291
  u8 mgain;
4292
  u8 skiptx;
4293
  u8 scmode;
4294
} settings;
4295

    
4296
#seekto 0x3280;
4297
struct {
4298
  u8 unknown1;
4299
  u8 vfomr;
4300
  u8 keylock;
4301
  u8 unknown2;
4302
  u8 unknown3:4,
4303
     vfomren:1,
4304
     unknown4:1,
4305
     reseten:1,
4306
     menuen:1;
4307
  u8 unknown5[11];
4308
  u8 dispab;
4309
  u8 unknown6[2];
4310
  u8 smenu;
4311
  u8 unknown7[7];
4312
  u8 vfomra;
4313
  u8 vfomrb;
4314
  u8 vfomrc;
4315
  u8 vfomrd;
4316
  u8 mrcha;
4317
  u8 mrchb;
4318
  u8 mrchc;
4319
  u8 mrchd;
4320
} settings2;
4321

    
4322
struct settings_vfo {
4323
  u8 freq[8];
4324
  u8 offset[6];
4325
  u8 unknown2[2];
4326
  ul16 rxtone;
4327
  ul16 txtone;
4328
  u8 scode;
4329
  u8 spmute;
4330
  u8 optsig;
4331
  u8 scramble;
4332
  u8 wide;
4333
  u8 power;
4334
  u8 shiftd;
4335
  u8 step;
4336
  u8 unknown3[4];
4337
};
4338

    
4339
#seekto 0x3300;
4340
struct {
4341
  struct settings_vfo a;
4342
  struct settings_vfo b;
4343
  struct settings_vfo c;
4344
  struct settings_vfo d;
4345
} vfo;
4346

    
4347
#seekto 0x3D80;
4348
struct {
4349
  u8 vhf_low[3];
4350
  u8 vhf_high[3];
4351
  u8 unknown1[4];
4352
  u8 unknown2[6];
4353
  u8 vhf2_low[3];
4354
  u8 vhf2_high[3];
4355
  u8 unknown3[4];
4356
  u8 unknown4[6];
4357
  u8 uhf_low[3];
4358
  u8 uhf_high[3];
4359
  u8 unknown5[4];
4360
  u8 unknown6[6];
4361
  u8 uhf2_low[3];
4362
  u8 uhf2_high[3];
4363
} ranges;
4364

    
4365
#seekto 0x33B0;
4366
struct {
4367
  char line[16];
4368
} static_msg;
4369

    
4370
#seekto 0x3F70;
4371
struct {
4372
  char fp[6];
4373
} fingerprint;
4374

    
4375
"""
4376

    
4377

    
4378
class BTechGMRS(BTechMobileCommon):
4379
    """BTECH's GMRS Mobile"""
4380
    COLOR_LCD = True
4381
    COLOR_LCD2 = True
4382
    NAME_LENGTH = 7
4383
    UPLOAD_MEM_SIZE = 0X3400
4384

    
4385
    def process_mmap(self):
4386
        """Process the mem map into the mem object"""
4387

    
4388
        # Get it
4389
        self._memobj = bitwise.parse(GMRS_MEM_FORMAT, self._mmap)
4390

    
4391
        # load specific parameters from the radio image
4392
        self.set_options()
4393

    
4394
    def set_options(self):
4395
        """This is to read the options from the image and set it in the
4396
        environment, for now just the limits of the freqs in the VHF/UHF
4397
        ranges"""
4398

    
4399
        # setting the correct ranges for each radio type
4400
        ranges = self._memobj.ranges
4401

    
4402
        # the normal dual bands
4403
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
4404
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
4405

    
4406
        # DEBUG
4407
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
4408
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
4409

    
4410
        # set the class with the real data
4411
        self._vhf_range = vhf
4412
        self._uhf_range = uhf
4413

    
4414

    
4415
# real radios
4416
@directory.register
4417
class GMRS50X1(BTechGMRS):
4418
    """Baofeng Tech GMRS50X1"""
4419
    MODEL = "GMRS-50X1"
4420
    BANDS = 2
4421
    LIST_TMR = LIST_TMR16
4422
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
4423
                     chirp_common.PowerLevel("Mid", watts=10),
4424
                     chirp_common.PowerLevel("Low", watts=5)]
4425
    _vhf_range = (136000000, 175000000)
4426
    _uhf_range = (400000000, 521000000)
4427
    _upper = 255
4428
    _magic = MSTRING_GMRS50X1
4429
    _fileid = [GMRS50X1_fp1, GMRS50X1_fp, ]
4430

    
4431

    
4432
COLORHT_MEM_FORMAT = """
4433
#seekto 0x0000;
4434
struct {
4435
  lbcd rxfreq[4];
4436
  lbcd txfreq[4];
4437
  ul16 rxtone;
4438
  ul16 txtone;
4439
  u8 unknown0:4,
4440
     scode:4;
4441
  u8 unknown1:2,
4442
     spmute:2,
4443
     unknown2:2,
4444
     optsig:2;
4445
  u8 unknown3:3,
4446
     scramble:1,
4447
     unknown4:3,
4448
     power:1;
4449
  u8 unknown5:1,
4450
     wide:1,
4451
     unknown6:2,
4452
     bcl:1,
4453
     add:1,
4454
     pttid:2;
4455
} memory[200];
4456

    
4457
#seekto 0x0E00;
4458
struct {
4459
  u8 tmr;
4460
  u8 unknownE01;
4461
  u8 sql;
4462
  u8 unknownE03[2];
4463
  u8 tot;
4464
  u8 save;
4465
  u8 unknownE07;
4466
  u8 abr;
4467
  u8 beep;
4468
  u8 unknownE0A[4];
4469
  u8 dsub;
4470
  u8 dtmfst;
4471
  u8 screv;
4472
  u8 unknownE11[3];
4473
  u8 pttid;
4474
  u8 unknownE15;
4475
  u8 pttlt;
4476
  u8 unknownE17;
4477
  u8 emctp;
4478
  u8 emcch;
4479
  u8 sigbp;
4480
  u8 unknownE1B;
4481
  u8 camdf;
4482
  u8 cbmdf;
4483
  u8 ccmdf;
4484
  u8 cdmdf;
4485
  u8 langua;
4486
  u8 voice;
4487
  u8 vox;
4488
  u8 voxt;
4489
  u8 sync;          // BTech radios use this as the display sync setting
4490
                    // other radios use this as the auto keypad lock setting
4491
  u8 stfc;
4492
  u8 mffc;
4493
  u8 sfafc;
4494
  u8 sfbfc;
4495
  u8 sfcfc;
4496
  u8 sfdfc;
4497
  u8 subfc;
4498
  u8 fmfc;
4499
  u8 sigfc;
4500
  u8 menufc;
4501
  u8 txfc;
4502
  u8 rxfc;
4503
  u8 unknownE31[5];
4504
  u8 anil;
4505
  u8 reps;
4506
  u8 tmrmr;
4507
  u8 ste;
4508
  u8 rpste;
4509
  u8 rptdl;
4510
  u8 dtmfg;
4511
  u8 tmrtx;
4512
} settings;
4513

    
4514
#seekto 0x0E80;
4515
struct {
4516
  u8 unknown1;
4517
  u8 vfomr;
4518
  u8 keylock;
4519
  u8 unknown2;
4520
  u8 unknown3:4,
4521
     vfomren:1,
4522
     unknown4:1,
4523
     reseten:1,
4524
     menuen:1;
4525
  u8 unknown5[11];
4526
  u8 dispab;
4527
  u8 unknown6[2];
4528
  u8 menu;
4529
  u8 unknown7[7];
4530
  u8 vfomra;
4531
  u8 vfomrb;
4532
  u8 vfomrc;
4533
  u8 vfomrd;
4534
  u8 mrcha;
4535
  u8 mrchb;
4536
  u8 mrchc;
4537
  u8 mrchd;
4538
} settings2;
4539

    
4540
struct settings_vfo {
4541 <