btech_kt8900.py

Jim Unroe, 09/14/2021 07:50 am

Download (153 kB)

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

    
18
import time
19
import struct
20
import logging
21

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

    
31
LOG = logging.getLogger(__name__)
32

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

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

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

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

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

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

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

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

    
147

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

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

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

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

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

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

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

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

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

    
198

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

    
202

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

    
206
# QYT KT8900
207
KT8900_fp = "M29154"
208
# New generations KT8900
209
KT8900_fp1 = "M2C234"
210
KT8900_fp2 = "M2G1F4"
211
KT8900_fp3 = "M2G2F4"
212
KT8900_fp4 = "M2G304"
213
KT8900_fp5 = "M2G314"
214
KT8900_fp6 = "M2G424"
215
# this radio has an extra ID
216
KT8900_id = "303688"
217
# another extra ID in sep/2021
218
KT8900_id2 = "\x05\x58\x3d\xf0\x10"
219

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

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

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

    
247
# KT8900D (dual band)
248
KT8900D_fp = "VC2002"
249
KT8900D_fp1 = "VC8632"
250
KT8900D_fp2 = "VC3402"
251

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

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

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

    
265

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

    
287

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

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

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

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

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

    
314

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

    
318
    data = ""
319

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

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

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

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

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

    
340
    return data
341

    
342

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

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

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

    
368

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

    
376
    return frame
377

    
378

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

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

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

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

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

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

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

    
406

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

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

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

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

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

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

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

    
437
                return True
438

    
439
        return False
440

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

    
446

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

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

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

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

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

    
479
            break
480

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

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

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

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

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

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

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

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

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

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

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

    
545
    return True
546

    
547

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

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

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

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

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

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

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

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

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

    
583
        # aggregate the data
584
        data += d
585

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

    
591
    return data
592

    
593

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
654

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

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

    
662
    return False
663

    
664

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

    
673
    return (ilow, ihigh)
674

    
675

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

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

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

    
690

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

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

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

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

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

    
743
            """))
744
        return rp
745

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

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

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

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

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

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

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

    
798
        return rf
799

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

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

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

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

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

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

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

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

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

    
871
        # Memory number
872
        mem.number = number
873

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
959
        return mem
960

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1066
        return mem
1067

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2193
                i = i + 1
2194

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2484
        top.append(group_5tone)
2485

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2864
            i = i + 1
2865

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2981
            i = i + 1
2982

    
2983
        return top
2984

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

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

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

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

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

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

    
3039

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3323
"""
3324

    
3325

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

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

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

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

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

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

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

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

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

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

    
3373

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

    
3379

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

    
3384

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

    
3389

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

    
3394

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

    
3399

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

    
3410

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

    
3423

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

    
3436

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

    
3447

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

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

    
3463

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

    
3468

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

    
3488

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

    
3506

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

    
3520

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
3817
"""
3818

    
3819

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

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

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

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

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

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

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

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

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

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

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

    
3867

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

    
3873

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

    
3878

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

    
3890

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

    
3903

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

    
3916

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

    
3934

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

    
3947
    # Clones
3948
    ALIASES = [OTGRadioV1]
3949

    
3950

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

    
3963

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

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

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

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

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

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

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

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

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

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

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

    
4156

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

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

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

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

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

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

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

    
4263
"""
4264

    
4265

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

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

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

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

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

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

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

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

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

    
4302

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

    
4319

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

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

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

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

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

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

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

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

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

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

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

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

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

    
4572
  struct {
4573
    ul16 freqA;
4574
    ul16 freqB;
4575
    ul16 freqC;