Project

General

Profile

Bug #6139 » btech.py

Add new fingerprint on tthe wild for the QYT KT8900D - Pavel Milanes, 10/15/2018 08:30 AM

 
1
# Copyright 2016-2017:
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
LOG = logging.getLogger(__name__)
23

    
24
from time import sleep
25
from chirp import chirp_common, directory, memmap
26
from chirp import bitwise, errors, util
27
from chirp.settings import RadioSettingGroup, RadioSetting, \
28
    RadioSettingValueBoolean, RadioSettingValueList, \
29
    RadioSettingValueString, RadioSettingValueInteger, \
30
    RadioSettingValueFloat, RadioSettings, InvalidValueError
31
from textwrap import dedent
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 = ["Black", "White", "Red", "Blue", "Green", "Yellow", "Indego",
63
               "Purple", "Gray"]
64
LIST_DTMFST = ["OFF", "Keyboard", "ANI", "Keyboad + ANI"]
65
LIST_EMCTP = ["TX alarm sound", "TX ANI", "Both"]
66
LIST_EMCTPX = ["Off"] + LIST_EMCTP
67
LIST_LANGUA = ["English", "Chinese"]
68
LIST_MDF = ["Frequency", "Channel", "Name"]
69
LIST_OFF1TO9 = ["Off"] + ["%s seconds" % x for x in range(1, 10)]
70
LIST_OFF1TO10 = ["Off"] + ["%s seconds" % x for x in range(1, 11)]
71
LIST_OFF1TO50 = ["Off"] + ["%s seconds" % x for x in range(1, 51)]
72
LIST_PONMSG = ["Full", "Message", "Battery voltage"]
73
LIST_REPM = ["Off", "Carrier", "CTCSS or DCS", "Tone", "DTMF"]
74
LIST_REPS = ["1000 Hz", "1450 Hz", "1750 Hz", "2100Hz"]
75
LIST_RPTDL = ["Off"] + ["%s ms" % x for x in range(1, 10)]
76
LIST_SCMODE = ["Off", "PTT-SC", "MEM-SC", "PON-SC"]
77
LIST_SHIFT = ["Off", "+", "-"]
78
LIST_SKIPTX = ["Off", "Skip 1", "Skip 2"]
79
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0]
80
LIST_STEP = [str(x) for x in STEPS]
81
LIST_SYNC = ["Off", "AB", "CD", "AB+CD"]
82
LIST_TMR = ["OFF", "M+A", "M+B", "M+C", "M+D", "M+A+B", "M+A+C", "M+A+D",
83
            "M+B+C", "M+B+D", "M+C+D", "M+A+B+C", "M+A+B+D", "M+A+C+D",
84
            "M+B+C+D", "A+B+C+D"]
85
LIST_TOT = ["%s sec" % x for x in range(15, 615, 15)]
86
LIST_TXDISP = ["Power", "Mic Volume"]
87
LIST_TXP = ["High", "Low"]
88
LIST_SCREV = ["TO (timeout)", "CO (carrier operated)", "SE (search)"]
89
LIST_VFOMR = ["Frequency", "Channel"]
90
LIST_WIDE = ["Wide", "Narrow"]
91

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

    
123
# This is a general serial timeout for all serial read functions.
124
# Practice has show that about 0.7 sec will be enough to cover all radios.
125
STIMEOUT = 0.7
126

    
127
# this var controls the verbosity in the debug and by default it's low (False)
128
# make it True and you will to get a very verbose debug.log
129
debug = False
130

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

    
135

    
136
##### ID strings #####################################################
137

    
138
# BTECH UV2501 pre-production units
139
UV2501pp_fp = "M2C294"
140
# BTECH UV2501 pre-production units 2 + and 1st Gen radios
141
UV2501pp2_fp = "M29204"
142
# B-TECH UV-2501 second generation (2G) radios
143
UV2501G2_fp = "BTG214"
144
# B-TECH UV-2501 third generation (3G) radios
145
UV2501G3_fp = "BTG324"
146

    
147
# B-TECH UV-2501+220 pre-production units
148
UV2501_220pp_fp = "M3C281"
149
# extra block read for the 2501+220 pre-production units
150
# the same for all of this radios so far
151
UV2501_220pp_id = "      280528"
152
# B-TECH UV-2501+220
153
UV2501_220_fp = "M3G201"
154
# new variant, let's call it Generation 2
155
UV2501_220G2_fp = "BTG211"
156
# B-TECH UV-2501+220 third generation (3G)
157
UV2501_220G3_fp = "BTG311"
158

    
159
# B-TECH UV-5001 pre-production units + 1st Gen radios
160
UV5001pp_fp = "V19204"
161
# B-TECH UV-5001 alpha units
162
UV5001alpha_fp = "V28204"
163
# B-TECH UV-5001 second generation (2G) radios
164
UV5001G2_fp = "BTG214"
165
# B-TECH UV-5001 second generation (2G2)
166
UV5001G22_fp = "V2G204"
167
# B-TECH UV-5001 third generation (3G)
168
UV5001G3_fp = "BTG304"
169

    
170
# B-TECH UV-25X2
171
UV25X2_fp = "UC2012"
172

    
173
# B-TECH UV-25X4
174
UV25X4_fp = "UC4014"
175

    
176
# B-TECH UV-50X2
177
UV50X2_fp = "UC2M12"
178

    
179
# special var to know when we found a BTECH Gen 3
180
BTECH3 = [UV2501G3_fp, UV2501_220G3_fp, UV5001G3_fp]
181

    
182

    
183
# WACCOM Mini-8900
184
MINI8900_fp = "M28854"
185

    
186

    
187
# QYT KT-UV980
188
KTUV980_fp = "H28854"
189

    
190
# QYT KT8900
191
KT8900_fp = "M29154"
192
# New generations KT8900
193
KT8900_fp1 = "M2C234"
194
KT8900_fp2 = "M2G1F4"
195
KT8900_fp3 = "M2G2F4"
196
KT8900_fp4 = "M2G304"
197
KT8900_fp5 = "M2G314"
198
# this radio has an extra ID
199
KT8900_id = "303688"
200

    
201
# KT8900R
202
KT8900R_fp = "M3G1F4"
203
# Second Generation
204
KT8900R_fp1 = "M3G214"
205
# another model
206
KT8900R_fp2 = "M3C234"
207
# another model G4?
208
KT8900R_fp3 = "M39164"
209
# another model
210
KT8900R_fp4 = "M3G314"
211
# this radio has an extra ID
212
KT8900R_id = "280528"
213

    
214
# KT7900D (quad band)
215
KT7900D_fp = "VC4004"
216
KT7900D_fp1 = "VC4284"
217

    
218
# QB25 (quad band) - a clone of KT7900D
219
QB25_fp = "QB-25"
220

    
221
# KT8900D (dual band)
222
KT8900D_fp = "VC2002"
223
KT8900D_fp1 = "VC8632"
224

    
225
# LUITON LT-588UV
226
LT588UV_fp = "V2G1F4"
227
# Added by rstrickoff gen 2 id
228
LT588UV_fp1 = "V2G214"
229

    
230

    
231
#### MAGICS
232
# for the Waccom Mini-8900
233
MSTRING_MINI8900 = "\x55\xA5\xB5\x45\x55\x45\x4d\x02"
234
# for the B-TECH UV-2501+220 (including pre production ones)
235
MSTRING_220 = "\x55\x20\x15\x12\x12\x01\x4d\x02"
236
# for the QYT KT8900 & R
237
MSTRING_KT8900 = "\x55\x20\x15\x09\x16\x45\x4D\x02"
238
MSTRING_KT8900R = "\x55\x20\x15\x09\x25\x01\x4D\x02"
239
# magic string for all other models
240
MSTRING = "\x55\x20\x15\x09\x20\x45\x4d\x02"
241
# for the QYT KT7900D & KT8900D
242
MSTRING_KT8900D = "\x55\x20\x16\x08\x01\xFF\xDC\x02"
243
# for the BTECH UV-25X2 and UV-50X2
244
MSTRING_UV25X2 = "\x55\x20\x16\x12\x28\xFF\xDC\x02"
245
# for the BTECH UV-25X4
246
MSTRING_UV25X4 = "\x55\x20\x16\x11\x18\xFF\xDC\x02"
247

    
248

    
249
def _clean_buffer(radio):
250
    """Cleaning the read serial buffer, hard timeout to survive an infinite
251
    data stream"""
252

    
253
    # touching the serial timeout to optimize the flushing
254
    # restored at the end to the default value
255
    radio.pipe.timeout = 0.1
256
    dump = "1"
257
    datacount = 0
258

    
259
    try:
260
        while len(dump) > 0:
261
            dump = radio.pipe.read(100)
262
            datacount += len(dump)
263
            # hard limit to survive a infinite serial data stream
264
            # 5 times bigger than a normal rx block (69 bytes)
265
            if datacount > 345:
266
                seriale = "Please check your serial port selection."
267
                raise errors.RadioError(seriale)
268

    
269
        # restore the default serial timeout
270
        radio.pipe.timeout = STIMEOUT
271

    
272
    except Exception:
273
        raise errors.RadioError("Unknown error cleaning the serial buffer")
274

    
275

    
276
def _rawrecv(radio, amount):
277
    """Raw read from the radio device, less intensive way"""
278

    
279
    data = ""
280

    
281
    try:
282
        data = radio.pipe.read(amount)
283

    
284
        # DEBUG
285
        if debug is True:
286
            LOG.debug("<== (%d) bytes:\n\n%s" %
287
                      (len(data), util.hexprint(data)))
288

    
289
        # fail if no data is received
290
        if len(data) == 0:
291
            raise errors.RadioError("No data received from radio")
292

    
293
        # notice on the logs if short
294
        if len(data) < amount:
295
            LOG.warn("Short reading %d bytes from the %d requested." %
296
                     (len(data), amount))
297

    
298
    except:
299
        raise errors.RadioError("Error reading data from radio")
300

    
301
    return data
302

    
303

    
304
def _send(radio, data):
305
    """Send data to the radio device"""
306

    
307
    try:
308
        for byte in data:
309
            radio.pipe.write(byte)
310
            # Some OS (mainly Linux ones) are too fast on the serial and
311
            # get the MCU inside the radio stuck in the early stages, this
312
            # hits some models more than others.
313
            #
314
            # To cope with that we introduce a delay on the writes.
315
            # Many option have been tested (delaying only after error occures,
316
            # after short reads, only for linux, ...)
317
            # Finally, a static delay was chosen as simplest of all solutions
318
            # (Michael Wagner, OE4AMW)
319
            # (for details, see issue 3993)
320
            sleep(0.002)
321

    
322
        # DEBUG
323
        if debug is True:
324
            LOG.debug("==> (%d) bytes:\n\n%s" %
325
                      (len(data), util.hexprint(data)))
326
    except:
327
        raise errors.RadioError("Error sending data to radio")
328

    
329

    
330
def _make_frame(cmd, addr, length, data=""):
331
    """Pack the info in the headder format"""
332
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
333
    # add the data if set
334
    if len(data) != 0:
335
        frame += data
336

    
337
    return frame
338

    
339

    
340
def _recv(radio, addr):
341
    """Get data from the radio all at once to lower syscalls load"""
342

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

    
346
    # get the whole block
347
    block = _rawrecv(radio, BLOCK_SIZE + 5)
348

    
349
    # basic check
350
    if len(block) < (BLOCK_SIZE + 5):
351
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
352

    
353
    # checking for the ack
354
    if block[0] != ACK_CMD:
355
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
356

    
357
    # header validation
358
    c, a, l = struct.unpack(">BHB", block[1:5])
359
    if a != addr or l != BLOCK_SIZE or c != ord("X"):
360
        LOG.debug("Invalid header for block 0x%04x" % addr)
361
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
362
        raise errors.RadioError("Invalid header for block 0x%04x:" % addr)
363

    
364
    # return the data
365
    return block[5:]
366

    
367

    
368
def _start_clone_mode(radio, status):
369
    """Put the radio in clone mode and get the ident string, 3 tries"""
370

    
371
    # cleaning the serial buffer
372
    _clean_buffer(radio)
373

    
374
    # prep the data to show in the UI
375
    status.cur = 0
376
    status.msg = "Identifying the radio..."
377
    status.max = 3
378
    radio.status_fn(status)
379

    
380
    try:
381
        for a in range(0, status.max):
382
            # Update the UI
383
            status.cur = a + 1
384
            radio.status_fn(status)
385

    
386
            # send the magic word
387
            _send(radio, radio._magic)
388

    
389
            # Now you get a x06 of ACK if all goes well
390
            ack = radio.pipe.read(1)
391

    
392
            if ack == "\x06":
393
                # DEBUG
394
                LOG.info("Magic ACK received")
395
                status.cur = status.max
396
                radio.status_fn(status)
397

    
398
                return True
399

    
400
        return False
401

    
402
    except errors.RadioError:
403
        raise
404
    except Exception, e:
405
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
406

    
407

    
408
def _do_ident(radio, status, upload=False):
409
    """Put the radio in PROGRAM mode & identify it"""
410
    #  set the serial discipline
411
    radio.pipe.baudrate = 9600
412
    radio.pipe.parity = "N"
413

    
414
    # open the radio into program mode
415
    if _start_clone_mode(radio, status) is False:
416
        msg = "Radio did not enter clone mode"
417
        # warning about old versions of QYT KT8900
418
        if radio.MODEL == "KT8900":
419
            msg += ". You may want to try it as a WACCOM MINI-8900, there is a"
420
            msg += " known variant of this radios that is a clone of it."
421
        raise errors.RadioError(msg)
422

    
423
    # Ok, get the ident string
424
    ident = _rawrecv(radio, 49)
425

    
426
    # basic check for the ident
427
    if len(ident) != 49:
428
        raise errors.RadioError("Radio send a short ident block.")
429

    
430
    # check if ident is OK
431
    itis = False
432
    for fp in radio._fileid:
433
        if fp in ident:
434
            # got it!
435
            itis = True
436
            # checking if we are dealing with a Gen 3 BTECH
437
            if radio.VENDOR == "BTECH" and fp in BTECH3:
438
                radio.btech3 = True
439

    
440
            break
441

    
442
    if itis is False:
443
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
444
        raise errors.RadioError("Radio identification failed.")
445

    
446
    # some radios needs a extra read and check for a code on it, this ones
447
    # has the check value in the _id2 var, others simply False
448
    if radio._id2 is not False:
449
        # lower the timeout here as this radios are reseting due to timeout
450
        radio.pipe.timeout = 0.05
451

    
452
        # query & receive the extra ID
453
        _send(radio, _make_frame("S", 0x3DF0, 16))
454
        id2 = _rawrecv(radio, 21)
455

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

    
463
        # ok, the correct string must be in the received data
464
        if radio._id2 not in id2:
465
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
466
                      (radio.MODEL, util.hexprint(id2)))
467
            raise errors.RadioError("The extra ID is wrong, aborting.")
468

    
469
        # this radios need a extra request/answer here on the upload
470
        # the amount of data received depends of the radio type
471
        #
472
        # also the first block of TX must no have the ACK at the beginning
473
        # see _upload for this.
474
        if upload is True:
475
            # send an ACK
476
            _send(radio, ACK_CMD)
477

    
478
            # the amount of data depend on the radio, so far we have two radios
479
            # reading two bytes with an ACK at the end and just ONE with just
480
            # one byte (QYT KT8900)
481
            # the JT-6188 appears a clone of the last, but reads TWO bytes.
482
            #
483
            # we will read two bytes with a custom timeout to not penalize the
484
            # users for this.
485
            #
486
            # we just check for a response and last byte being a ACK, that is
487
            # the common stone for all radios (3 so far)
488
            ack = _rawrecv(radio, 2)
489

    
490
            # checking
491
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
492
                raise errors.RadioError("Radio didn't ACK the upload")
493

    
494
            # restore the default serial timeout
495
            radio.pipe.timeout = STIMEOUT
496

    
497
    # DEBUG
498
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
499

    
500
    return True
501

    
502

    
503
def _download(radio):
504
    """Get the memory map"""
505

    
506
    # UI progress
507
    status = chirp_common.Status()
508

    
509
    # put radio in program mode and identify it
510
    _do_ident(radio, status)
511

    
512
    # the models that doesn't have the extra ID have to make a dummy read here
513
    if radio._id2 is False:
514
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
515
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
516

    
517
        if debug is True:
518
            LOG.info("Dummy first block read done, got this:\n\n %s",
519
                     util.hexprint(discard))
520

    
521
    # reset the progress bar in the UI
522
    status.max = MEM_SIZE / BLOCK_SIZE
523
    status.msg = "Cloning from radio..."
524
    status.cur = 0
525
    radio.status_fn(status)
526

    
527
    # cleaning the serial buffer
528
    _clean_buffer(radio)
529

    
530
    data = ""
531
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
532
        # sending the read request
533
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
534

    
535
        # read
536
        d = _recv(radio, addr)
537

    
538
        # aggregate the data
539
        data += d
540

    
541
        # UI Update
542
        status.cur = addr / BLOCK_SIZE
543
        status.msg = "Cloning from radio..."
544
        radio.status_fn(status)
545

    
546
    return data
547

    
548

    
549
def _upload(radio):
550
    """Upload procedure"""
551

    
552
    # The UPLOAD mem is restricted to lower than 0x3100,
553
    # so we will overide that here localy
554
    MEM_SIZE = 0x3100
555

    
556
    # UI progress
557
    status = chirp_common.Status()
558

    
559
    # put radio in program mode and identify it
560
    _do_ident(radio, status, True)
561

    
562
    # get the data to upload to radio
563
    data = radio.get_mmap()
564

    
565
    # Reset the UI progress
566
    status.max = MEM_SIZE / TX_BLOCK_SIZE
567
    status.cur = 0
568
    status.msg = "Cloning to radio..."
569
    radio.status_fn(status)
570

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

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

    
578
    # the fun start here
579
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
580
        # getting the block of data to send
581
        d = data[addr:addr + TX_BLOCK_SIZE]
582

    
583
        # build the frame to send
584
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
585

    
586
        # first block must not send the ACK at the beginning for the
587
        # ones that has the extra id, since this have to do a extra step
588
        if addr == 0 and radio._id2 is not False:
589
            frame = frame[1:]
590

    
591
        # send the frame
592
        _send(radio, frame)
593

    
594
        # receiving the response
595
        ack = _rawrecv(radio, 1)
596

    
597
        # basic check
598
        if len(ack) != 1:
599
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
600

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

    
604
         # UI Update
605
        status.cur = addr / TX_BLOCK_SIZE
606
        status.msg = "Cloning to radio..."
607
        radio.status_fn(status)
608

    
609

    
610
def model_match(cls, data):
611
    """Match the opened/downloaded image to the correct version"""
612
    rid = data[0x3f70:0x3f76]
613

    
614
    if rid in cls._fileid:
615
        return True
616

    
617
    return False
618

    
619

    
620
def _decode_ranges(low, high):
621
    """Unpack the data in the ranges zones in the memmap and return
622
    a tuple with the integer corresponding to the Mhz it means"""
623
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
624
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
625
    ilow *= 1000000
626
    ihigh *= 1000000
627

    
628
    return (ilow, ihigh)
629

    
630

    
631
def _split(rf, f1, f2):
632
    """Returns False if the two freqs are in the same band (no split)
633
    or True otherwise"""
634

    
635
    # determine if the two freqs are in the same band
636
    for low, high in rf.valid_bands:
637
        if f1 >= low and f1 <= high and \
638
                f2 >= low and f2 <= high:
639
            # if the two freqs are on the same Band this is not a split
640
            return False
641

    
642
    # if you get here is because the freq pairs are split
643
    return True
644

    
645

    
646
class BTechMobileCommon(chirp_common.CloneModeRadio,
647
                        chirp_common.ExperimentalRadio):
648
    """BTECH's UV-5001 and alike radios"""
649
    VENDOR = "BTECH"
650
    MODEL = ""
651
    IDENT = ""
652
    BANDS = 2
653
    COLOR_LCD = False
654
    NAME_LENGTH = 6
655
    _power_levels = [chirp_common.PowerLevel("High", watts=25),
656
                     chirp_common.PowerLevel("Low", watts=10)]
657
    _vhf_range = (130000000, 180000000)
658
    _220_range = (200000000, 271000000)
659
    _uhf_range = (400000000, 521000000)
660
    _350_range = (350000000, 391000000)
661
    _upper = 199
662
    _magic = MSTRING
663
    _fileid = None
664
    _id2 = False
665
    btech3 = False
666

    
667
    @classmethod
668
    def get_prompts(cls):
669
        rp = chirp_common.RadioPrompts()
670
        rp.experimental = \
671
            ('This driver is experimental.\n'
672
             '\n'
673
             'Please keep a copy of your memories with the original software '
674
             'if you treasure them, this driver is new and may contain'
675
             ' bugs.\n'
676
             '\n'
677
             )
678
        rp.pre_download = _(dedent("""\
679
            Follow these instructions to download your info:
680

    
681
            1 - Turn off your radio
682
            2 - Connect your interface cable
683
            3 - Turn on your radio
684
            4 - Do the download of your radio data
685

    
686
            """))
687
        rp.pre_upload = _(dedent("""\
688
            Follow these instructions to upload your info:
689

    
690
            1 - Turn off your radio
691
            2 - Connect your interface cable
692
            3 - Turn on your radio
693
            4 - Do the upload of your radio data
694

    
695
            """))
696
        return rp
697

    
698
    def get_features(self):
699
        """Get the radio's features"""
700

    
701
        # we will use the following var as global
702
        global POWER_LEVELS
703

    
704
        rf = chirp_common.RadioFeatures()
705
        rf.has_settings = True
706
        rf.has_bank = False
707
        rf.has_tuning_step = False
708
        rf.can_odd_split = True
709
        rf.has_name = True
710
        rf.has_offset = True
711
        rf.has_mode = True
712
        rf.has_dtcs = True
713
        rf.has_rx_dtcs = True
714
        rf.has_dtcs_polarity = True
715
        rf.has_ctone = True
716
        rf.has_cross = True
717
        rf.valid_modes = MODES
718
        rf.valid_characters = VALID_CHARS
719
        rf.valid_name_length = self.NAME_LENGTH
720
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
721
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
722
        rf.valid_cross_modes = [
723
            "Tone->Tone",
724
            "DTCS->",
725
            "->DTCS",
726
            "Tone->DTCS",
727
            "DTCS->Tone",
728
            "->Tone",
729
            "DTCS->DTCS"]
730
        rf.valid_skips = SKIP_VALUES
731
        rf.valid_dtcs_codes = DTCS
732
        rf.memory_bounds = (0, self._upper)
733

    
734
        # power levels
735
        POWER_LEVELS = self._power_levels
736
        rf.valid_power_levels = POWER_LEVELS
737

    
738
        # normal dual bands
739
        rf.valid_bands = [self._vhf_range, self._uhf_range]
740

    
741
        # 220 band
742
        if self.BANDS == 3 or self.BANDS == 4:
743
            rf.valid_bands.append(self._220_range)
744

    
745
        # 350 band
746
        if self.BANDS == 4:
747
            rf.valid_bands.append(self._350_range)
748

    
749
        return rf
750

    
751
    def sync_in(self):
752
        """Download from radio"""
753
        data = _download(self)
754
        self._mmap = memmap.MemoryMap(data)
755
        self.process_mmap()
756

    
757
    def sync_out(self):
758
        """Upload to radio"""
759
        try:
760
            _upload(self)
761
        except errors.RadioError:
762
            raise
763
        except Exception, e:
764
            raise errors.RadioError("Error: %s" % e)
765

    
766
    def get_raw_memory(self, number):
767
        return repr(self._memobj.memory[number])
768

    
769
    def _decode_tone(self, val):
770
        """Parse the tone data to decode from mem, it returns:
771
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
772
        pol = None
773

    
774
        if val in [0, 65535]:
775
            return '', None, None
776
        elif val > 0x0258:
777
            a = val / 10.0
778
            return 'Tone', a, pol
779
        else:
780
            if val > 0x69:
781
                index = val - 0x6A
782
                pol = "R"
783
            else:
784
                index = val - 1
785
                pol = "N"
786

    
787
            tone = DTCS[index]
788
            return 'DTCS', tone, pol
789

    
790
    def _encode_tone(self, memval, mode, val, pol):
791
        """Parse the tone data to encode from UI to mem"""
792
        if mode == '' or mode is None:
793
            memval.set_raw("\x00\x00")
794
        elif mode == 'Tone':
795
            memval.set_value(val * 10)
796
        elif mode == 'DTCS':
797
            # detect the index in the DTCS list
798
            try:
799
                index = DTCS.index(val)
800
                if pol == "N":
801
                    index += 1
802
                else:
803
                    index += 0x6A
804
                memval.set_value(index)
805
            except:
806
                msg = "Digital Tone '%d' is not supported" % value
807
                LOG.error(msg)
808
                raise errors.RadioError(msg)
809
        else:
810
            msg = "Internal error: invalid mode '%s'" % mode
811
            LOG.error(msg)
812
            raise errors.InvalidDataError(msg)
813

    
814
    def get_memory(self, number):
815
        """Get the mem representation from the radio image"""
816
        _mem = self._memobj.memory[number]
817
        _names = self._memobj.names[number]
818

    
819
        # Create a high-level memory object to return to the UI
820
        mem = chirp_common.Memory()
821

    
822
        # Memory number
823
        mem.number = number
824

    
825
        if _mem.get_raw()[0] == "\xFF":
826
            mem.empty = True
827
            return mem
828

    
829
        # Freq and offset
830
        mem.freq = int(_mem.rxfreq) * 10
831
        # tx freq can be blank
832
        if _mem.get_raw()[4] == "\xFF":
833
            # TX freq not set
834
            mem.offset = 0
835
            mem.duplex = "off"
836
        else:
837
            # TX freq set
838
            offset = (int(_mem.txfreq) * 10) - mem.freq
839
            if offset != 0:
840
                if _split(self.get_features(), mem.freq, int(_mem.txfreq) * 10):
841
                    mem.duplex = "split"
842
                    mem.offset = int(_mem.txfreq) * 10
843
                elif offset < 0:
844
                    mem.offset = abs(offset)
845
                    mem.duplex = "-"
846
                elif offset > 0:
847
                    mem.offset = offset
848
                    mem.duplex = "+"
849
            else:
850
                mem.offset = 0
851

    
852
        # name TAG of the channel
853
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
854

    
855
        # power
856
        mem.power = POWER_LEVELS[int(_mem.power)]
857

    
858
        # wide/narrow
859
        mem.mode = MODES[int(_mem.wide)]
860

    
861
        # skip
862
        mem.skip = SKIP_VALUES[_mem.add]
863

    
864
        # tone data
865
        rxtone = txtone = None
866
        txtone = self._decode_tone(_mem.txtone)
867
        rxtone = self._decode_tone(_mem.rxtone)
868
        chirp_common.split_tone_decode(mem, txtone, rxtone)
869

    
870
        # Extra
871
        mem.extra = RadioSettingGroup("extra", "Extra")
872

    
873
        if not self.COLOR_LCD or \
874
            (self.COLOR_LCD and not self.VENDOR == "BTECH"):
875
            scramble = RadioSetting("scramble", "Scramble",
876
                                    RadioSettingValueBoolean(bool(
877
                                        _mem.scramble)))
878
            mem.extra.append(scramble)
879

    
880
        bcl = RadioSetting("bcl", "Busy channel lockout",
881
                           RadioSettingValueBoolean(bool(_mem.bcl)))
882
        mem.extra.append(bcl)
883

    
884
        pttid = RadioSetting("pttid", "PTT ID",
885
                             RadioSettingValueList(PTTID_LIST,
886
                                                   PTTID_LIST[_mem.pttid]))
887
        mem.extra.append(pttid)
888

    
889
        # validating scode
890
        scode = _mem.scode if _mem.scode != 15 else 0
891
        pttidcode = RadioSetting("scode", "PTT ID signal code",
892
                                 RadioSettingValueList(
893
                                     PTTIDCODE_LIST,
894
                                     PTTIDCODE_LIST[scode]))
895
        mem.extra.append(pttidcode)
896

    
897
        optsig = RadioSetting("optsig", "Optional signaling",
898
                              RadioSettingValueList(
899
                                  OPTSIG_LIST,
900
                                  OPTSIG_LIST[_mem.optsig]))
901
        mem.extra.append(optsig)
902

    
903
        spmute = RadioSetting("spmute", "Speaker mute",
904
                              RadioSettingValueList(
905
                                  SPMUTE_LIST,
906
                                  SPMUTE_LIST[_mem.spmute]))
907
        mem.extra.append(spmute)
908

    
909
        return mem
910

    
911
    def set_memory(self, mem):
912
        """Set the memory data in the eeprom img from the UI"""
913
        # get the eprom representation of this channel
914
        _mem = self._memobj.memory[mem.number]
915
        _names = self._memobj.names[mem.number]
916

    
917
        mem_was_empty = False
918
        # same method as used in get_memory for determining if mem is empty
919
        # doing this BEFORE overwriting it with new values ...
920
        if _mem.get_raw()[0] == "\xFF":
921
            LOG.debug("This mem was empty before")
922
            mem_was_empty = True
923

    
924
        # if empty memmory
925
        if mem.empty:
926
            # the channel itself
927
            _mem.set_raw("\xFF" * 16)
928
            # the name tag
929
            _names.set_raw("\xFF" * 16)
930
            return
931

    
932
        if mem_was_empty:
933
            # Zero the whole memory if we're making it unempty for
934
            # the first time
935
            LOG.debug('Zeroing new memory')
936
            _mem.set_raw('\x00' * 16)
937

    
938
        # frequency
939
        _mem.rxfreq = mem.freq / 10
940

    
941
        # duplex
942
        if mem.duplex == "+":
943
            _mem.txfreq = (mem.freq + mem.offset) / 10
944
        elif mem.duplex == "-":
945
            _mem.txfreq = (mem.freq - mem.offset) / 10
946
        elif mem.duplex == "off":
947
            for i in _mem.txfreq:
948
                i.set_raw("\xFF")
949
        elif mem.duplex == "split":
950
            _mem.txfreq = mem.offset / 10
951
        else:
952
            _mem.txfreq = mem.freq / 10
953

    
954
        # tone data
955
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
956
            chirp_common.split_tone_encode(mem)
957
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
958
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
959

    
960
        # name TAG of the channel
961
        if len(mem.name) < self.NAME_LENGTH:
962
            # we must pad to self.NAME_LENGTH chars, " " = "\xFF"
963
            mem.name = str(mem.name).ljust(self.NAME_LENGTH, " ")
964
        _names.name = str(mem.name).replace(" ", "\xFF")
965

    
966
        # power, # default power level is high
967
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
968

    
969
        # wide/narrow
970
        _mem.wide = MODES.index(mem.mode)
971

    
972
        # scan add property
973
        _mem.add = SKIP_VALUES.index(mem.skip)
974

    
975
        # reseting unknowns, this have to be set by hand
976
        _mem.unknown0 = 0
977
        _mem.unknown1 = 0
978
        _mem.unknown2 = 0
979
        _mem.unknown3 = 0
980
        _mem.unknown4 = 0
981
        _mem.unknown5 = 0
982
        _mem.unknown6 = 0
983

    
984
        def _zero_settings():
985
            _mem.spmute = 0
986
            _mem.optsig = 0
987
            _mem.scramble = 0
988
            _mem.bcl = 0
989
            _mem.pttid = 0
990
            _mem.scode = 0
991

    
992
        if self.COLOR_LCD and _mem.scramble:
993
            LOG.info('Resetting scramble bit for BTECH COLOR_LCD variant')
994
            _mem.scramble = 0
995

    
996
        # extra settings
997
        if len(mem.extra) > 0:
998
            # there are setting, parse
999
            LOG.debug("Extra-Setting supplied. Setting them.")
1000
            # Zero them all first so any not provided by model don't
1001
            # stay set
1002
            _zero_settings()
1003
            for setting in mem.extra:
1004
                setattr(_mem, setting.get_name(), setting.value)
1005
        else:
1006
            if mem.empty:
1007
                LOG.debug("New mem is empty.")
1008
            else:
1009
                LOG.debug("New mem is NOT empty")
1010
                # set extra-settings to default ONLY when apreviously empty or
1011
                # deleted memory was edited to prevent errors such as #4121
1012
                if mem_was_empty:
1013
                    LOG.debug("old mem was empty. Setting default for extras.")
1014
                    _zero_settings()
1015

    
1016
        return mem
1017

    
1018
    def get_settings(self):
1019
        """Translate the bit in the mem_struct into settings in the UI"""
1020
        _mem = self._memobj
1021
        basic = RadioSettingGroup("basic", "Basic Settings")
1022
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1023
        other = RadioSettingGroup("other", "Other Settings")
1024
        work = RadioSettingGroup("work", "Work Mode Settings")
1025
        top = RadioSettings(basic, advanced, other, work)
1026

    
1027
        # Basic
1028
        if self.COLOR_LCD:
1029
            tmr = RadioSetting("settings.tmr", "Transceiver multi-receive",
1030
                               RadioSettingValueList(
1031
                                   LIST_TMR,
1032
                                   LIST_TMR[_mem.settings.tmr]))
1033
            basic.append(tmr)
1034
        else:
1035
            tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1036
                               RadioSettingValueBoolean(_mem.settings.tdr))
1037
            basic.append(tdr)
1038

    
1039
        sql = RadioSetting("settings.sql", "Squelch level",
1040
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1041
        basic.append(sql)
1042

    
1043
        tot = RadioSetting("settings.tot", "Time out timer",
1044
                           RadioSettingValueList(
1045
                               LIST_TOT,
1046
                               LIST_TOT[_mem.settings.tot]))
1047
        basic.append(tot)
1048

    
1049
        if self.VENDOR == "BTECH" or self.COLOR_LCD:
1050
            apo = RadioSetting("settings.apo", "Auto power off timer",
1051
                               RadioSettingValueList(
1052
                                   LIST_APO,
1053
                                   LIST_APO[_mem.settings.apo]))
1054
            basic.append(apo)
1055
        else:
1056
            toa = RadioSetting("settings.apo", "Time out alert timer",
1057
                               RadioSettingValueList(
1058
                                   LIST_OFF1TO10,
1059
                                   LIST_OFF1TO10[_mem.settings.apo]))
1060
            basic.append(toa)
1061

    
1062
        abr = RadioSetting("settings.abr", "Backlight timer",
1063
                           RadioSettingValueList(
1064
                               LIST_OFF1TO50,
1065
                               LIST_OFF1TO50[_mem.settings.abr]))
1066
        basic.append(abr)
1067

    
1068
        beep = RadioSetting("settings.beep", "Key beep",
1069
                            RadioSettingValueBoolean(_mem.settings.beep))
1070
        basic.append(beep)
1071

    
1072
        dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1073
                              RadioSettingValueList(
1074
                                  LIST_DTMFST,
1075
                                  LIST_DTMFST[_mem.settings.dtmfst]))
1076
        basic.append(dtmfst)
1077

    
1078
        if not self.COLOR_LCD:
1079
            prisc = RadioSetting("settings.prisc", "Priority scan",
1080
                                 RadioSettingValueBoolean(
1081
                                     _mem.settings.prisc))
1082
            basic.append(prisc)
1083

    
1084
            prich = RadioSetting("settings.prich", "Priority channel",
1085
                                 RadioSettingValueInteger(0, 199,
1086
                                     _mem.settings.prich))
1087
            basic.append(prich)
1088

    
1089
        screv = RadioSetting("settings.screv", "Scan resume method",
1090
                             RadioSettingValueList(
1091
                                 LIST_SCREV,
1092
                                 LIST_SCREV[_mem.settings.screv]))
1093
        basic.append(screv)
1094

    
1095
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1096
                             RadioSettingValueInteger(0, 30,
1097
                                 _mem.settings.pttlt))
1098
        basic.append(pttlt)
1099

    
1100
        if self.VENDOR == "BTECH" and self.COLOR_LCD:
1101
            emctp = RadioSetting("settings.emctp", "Alarm mode",
1102
                                 RadioSettingValueList(
1103
                                     LIST_EMCTPX,
1104
                                     LIST_EMCTPX[_mem.settings.emctp]))
1105
            basic.append(emctp)
1106
        else:
1107
            emctp = RadioSetting("settings.emctp", "Alarm mode",
1108
                                 RadioSettingValueList(
1109
                                     LIST_EMCTP,
1110
                                     LIST_EMCTP[_mem.settings.emctp]))
1111
            basic.append(emctp)
1112

    
1113
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1114
                             RadioSettingValueInteger(0, 199,
1115
                                 _mem.settings.emcch))
1116
        basic.append(emcch)
1117

    
1118
        if self.COLOR_LCD:
1119
            if _mem.settings.sigbp > 0x01:
1120
                val = 0x00
1121
            else:
1122
                val = _mem.settings.sigbp
1123
            sigbp = RadioSetting("settings.sigbp", "Roger beep",
1124
                                 RadioSettingValueBoolean(val))
1125
            basic.append(sigbp)
1126
        else:
1127
            ringt = RadioSetting("settings.ringt", "Ring time",
1128
                                 RadioSettingValueList(
1129
                                     LIST_OFF1TO9,
1130
                                     LIST_OFF1TO9[_mem.settings.ringt]))
1131
            basic.append(ringt)
1132

    
1133
        camdf = RadioSetting("settings.camdf", "Display mode A",
1134
                             RadioSettingValueList(
1135
                                 LIST_MDF,
1136
                                 LIST_MDF[_mem.settings.camdf]))
1137
        basic.append(camdf)
1138

    
1139
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1140
                             RadioSettingValueList(
1141
                                 LIST_MDF,
1142
                                 LIST_MDF[_mem.settings.cbmdf]))
1143
        basic.append(cbmdf)
1144

    
1145
        if self.COLOR_LCD:
1146
            ccmdf = RadioSetting("settings.ccmdf", "Display mode C",
1147
                                 RadioSettingValueList(
1148
                                     LIST_MDF,
1149
                                     LIST_MDF[_mem.settings.ccmdf]))
1150
            basic.append(ccmdf)
1151

    
1152
            cdmdf = RadioSetting("settings.cdmdf", "Display mode D",
1153
                                 RadioSettingValueList(
1154
                                     LIST_MDF,
1155
                                     LIST_MDF[_mem.settings.cdmdf]))
1156
            basic.append(cdmdf)
1157

    
1158
            langua = RadioSetting("settings.langua", "Language",
1159
                                  RadioSettingValueList(
1160
                                      LIST_LANGUA,
1161
                                      LIST_LANGUA[_mem.settings.langua]))
1162
            basic.append(langua)
1163

    
1164
        if self.VENDOR == "BTECH":
1165
            if self.COLOR_LCD:
1166
                sync = RadioSetting("settings.sync", "Channel display sync",
1167
                                    RadioSettingValueList(
1168
                                        LIST_SYNC,
1169
                                        LIST_SYNC[_mem.settings.sync]))
1170
                basic.append(sync)
1171
            else:
1172
                sync = RadioSetting("settings.sync", "A/B channel sync",
1173
                                    RadioSettingValueBoolean(
1174
                                        _mem.settings.sync))
1175
                basic.append(sync)
1176
        else:
1177
            autolk = RadioSetting("settings.sync", "Auto keylock",
1178
                                  RadioSettingValueBoolean(
1179
                                      _mem.settings.sync))
1180
            basic.append(autolk)
1181

    
1182
        if not self.COLOR_LCD:
1183
            ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1184
                                  RadioSettingValueList(
1185
                                      LIST_PONMSG,
1186
                                      LIST_PONMSG[_mem.settings.ponmsg]))
1187
            basic.append(ponmsg)
1188

    
1189
        if self.COLOR_LCD:
1190
            mainfc = RadioSetting("settings.mainfc",
1191
                                  "Main LCD foreground color",
1192
                                      RadioSettingValueList(
1193
                                          LIST_COLOR8,
1194
                                          LIST_COLOR8[_mem.settings.mainfc]))
1195
            basic.append(mainfc)
1196

    
1197
            mainbc = RadioSetting("settings.mainbc",
1198
                                  "Main LCD background color",
1199
                                      RadioSettingValueList(
1200
                                          LIST_COLOR8,
1201
                                          LIST_COLOR8[_mem.settings.mainbc]))
1202
            basic.append(mainbc)
1203

    
1204
            menufc = RadioSetting("settings.menufc", "Menu foreground color",
1205
                                  RadioSettingValueList(
1206
                                      LIST_COLOR8,
1207
                                      LIST_COLOR8[_mem.settings.menufc]))
1208
            basic.append(menufc)
1209

    
1210
            menubc = RadioSetting("settings.menubc", "Menu background color",
1211
                                  RadioSettingValueList(
1212
                                      LIST_COLOR8,
1213
                                      LIST_COLOR8[_mem.settings.menubc]))
1214
            basic.append(menubc)
1215

    
1216
            stafc = RadioSetting("settings.stafc",
1217
                                 "Top status foreground color",
1218
                                     RadioSettingValueList(
1219
                                         LIST_COLOR8,
1220
                                         LIST_COLOR8[_mem.settings.stafc]))
1221
            basic.append(stafc)
1222

    
1223
            stabc = RadioSetting("settings.stabc",
1224
                                 "Top status background color",
1225
                                     RadioSettingValueList(
1226
                                         LIST_COLOR8,
1227
                                         LIST_COLOR8[_mem.settings.stabc]))
1228
            basic.append(stabc)
1229

    
1230
            sigfc = RadioSetting("settings.sigfc",
1231
                                 "Bottom status foreground color",
1232
                                     RadioSettingValueList(
1233
                                         LIST_COLOR8,
1234
                                         LIST_COLOR8[_mem.settings.sigfc]))
1235
            basic.append(sigfc)
1236

    
1237
            sigbc = RadioSetting("settings.sigbc",
1238
                                 "Bottom status background color",
1239
                                     RadioSettingValueList(
1240
                                         LIST_COLOR8,
1241
                                         LIST_COLOR8[_mem.settings.sigbc]))
1242
            basic.append(sigbc)
1243

    
1244
            rxfc = RadioSetting("settings.rxfc", "Receiving character color",
1245
                                RadioSettingValueList(
1246
                                    LIST_COLOR8,
1247
                                    LIST_COLOR8[_mem.settings.rxfc]))
1248
            basic.append(rxfc)
1249

    
1250
            txfc = RadioSetting("settings.txfc",
1251
                                "Transmitting character color",
1252
                                    RadioSettingValueList(
1253
                                        LIST_COLOR8,
1254
                                        LIST_COLOR8[_mem.settings.txfc]))
1255
            basic.append(txfc)
1256

    
1257
            txdisp = RadioSetting("settings.txdisp",
1258
                                  "Transmitting status display",
1259
                                      RadioSettingValueList(
1260
                                          LIST_TXDISP,
1261
                                          LIST_TXDISP[_mem.settings.txdisp]))
1262
            basic.append(txdisp)
1263
        else:
1264
            wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1265
                                 RadioSettingValueList(
1266
                                     LIST_COLOR4,
1267
                                     LIST_COLOR4[_mem.settings.wtled]))
1268
            basic.append(wtled)
1269

    
1270
            rxled = RadioSetting("settings.rxled", "RX backlight Color",
1271
                                 RadioSettingValueList(
1272
                                     LIST_COLOR4,
1273
                                     LIST_COLOR4[_mem.settings.rxled]))
1274
            basic.append(rxled)
1275

    
1276
            txled = RadioSetting("settings.txled", "TX backlight Color",
1277
                                 RadioSettingValueList(
1278
                                     LIST_COLOR4,
1279
                                     LIST_COLOR4[_mem.settings.txled]))
1280
            basic.append(txled)
1281

    
1282
        anil = RadioSetting("settings.anil", "ANI length",
1283
                            RadioSettingValueList(
1284
                                LIST_ANIL,
1285
                                LIST_ANIL[_mem.settings.anil]))
1286
        basic.append(anil)
1287

    
1288
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1289
                            RadioSettingValueList(
1290
                                LIST_REPS,
1291
                                LIST_REPS[_mem.settings.reps]))
1292
        basic.append(reps)
1293

    
1294
        repm = RadioSetting("settings.repm", "Relay condition",
1295
                            RadioSettingValueList(
1296
                                LIST_REPM,
1297
                                LIST_REPM[_mem.settings.repm]))
1298
        basic.append(repm)
1299

    
1300
        if self.VENDOR == "BTECH" or self.COLOR_LCD:
1301
            if self.COLOR_LCD:
1302
                tmrmr = RadioSetting("settings.tmrmr", "TMR return time",
1303
                                     RadioSettingValueList(
1304
                                         LIST_OFF1TO50,
1305
                                         LIST_OFF1TO50[_mem.settings.tmrmr]))
1306
                basic.append(tmrmr)
1307
            else:
1308
                tdrab = RadioSetting("settings.tdrab", "TDR return time",
1309
                                     RadioSettingValueList(
1310
                                         LIST_OFF1TO50,
1311
                                         LIST_OFF1TO50[_mem.settings.tdrab]))
1312
                basic.append(tdrab)
1313

    
1314
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1315
                               RadioSettingValueBoolean(_mem.settings.ste))
1316
            basic.append(ste)
1317

    
1318
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1319
                                 RadioSettingValueList(
1320
                                     LIST_OFF1TO9,
1321
                                     LIST_OFF1TO9[_mem.settings.rpste]))
1322
            basic.append(rpste)
1323

    
1324
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1325
                                 RadioSettingValueList(
1326
                                     LIST_RPTDL,
1327
                                     LIST_RPTDL[_mem.settings.rptdl]))
1328
            basic.append(rptdl)
1329

    
1330
        if str(_mem.fingerprint.fp) in BTECH3:
1331
            mgain = RadioSetting("settings.mgain", "Mic gain",
1332
                                 RadioSettingValueInteger(0, 120,
1333
                                     _mem.settings.mgain))
1334
            basic.append(mgain)
1335

    
1336
        if str(_mem.fingerprint.fp) in BTECH3 or self.COLOR_LCD:
1337
            dtmfg = RadioSetting("settings.dtmfg", "DTMF gain",
1338
                                 RadioSettingValueInteger(0, 60,
1339
                                     _mem.settings.dtmfg))
1340
            basic.append(dtmfg)
1341

    
1342
        if self.VENDOR == "BTECH" and self.COLOR_LCD:
1343
            mgain = RadioSetting("settings.mgain", "Mic gain",
1344
                                 RadioSettingValueInteger(0, 120,
1345
                                     _mem.settings.mgain))
1346
            basic.append(mgain)
1347

    
1348
            skiptx = RadioSetting("settings.skiptx", "Skip TX",
1349
                                  RadioSettingValueList(
1350
                                      LIST_SKIPTX,
1351
                                      LIST_SKIPTX[_mem.settings.skiptx]))
1352
            basic.append(skiptx)
1353

    
1354
            scmode = RadioSetting("settings.scmode", "Scan mode",
1355
                                  RadioSettingValueList(
1356
                                      LIST_SCMODE,
1357
                                      LIST_SCMODE[_mem.settings.scmode]))
1358
            basic.append(scmode)
1359

    
1360
        # Advanced
1361
        def _filter(name):
1362
            filtered = ""
1363
            for char in str(name):
1364
                if char in VALID_CHARS:
1365
                    filtered += char
1366
                else:
1367
                    filtered += " "
1368
            return filtered
1369

    
1370
        _msg = self._memobj.poweron_msg
1371
        if self.COLOR_LCD:
1372
            line1 = RadioSetting("poweron_msg.line1",
1373
                                 "Power-on message line 1",
1374
                                     RadioSettingValueString(0, 8, _filter(
1375
                                         _msg.line1)))
1376
            advanced.append(line1)
1377
            line2 = RadioSetting("poweron_msg.line2",
1378
                                 "Power-on message line 2",
1379
                                     RadioSettingValueString(0, 8, _filter(
1380
                                         _msg.line2)))
1381
            advanced.append(line2)
1382
            line3 = RadioSetting("poweron_msg.line3",
1383
                                 "Power-on message line 3",
1384
                                     RadioSettingValueString(0, 8, _filter(
1385
                                         _msg.line3)))
1386
            advanced.append(line3)
1387
            line4 = RadioSetting("poweron_msg.line4",
1388
                                 "Power-on message line 4",
1389
                                     RadioSettingValueString(0, 8, _filter(
1390
                                         _msg.line4)))
1391
            advanced.append(line4)
1392
            line5 = RadioSetting("poweron_msg.line5",
1393
                                 "Power-on message line 5",
1394
                                     RadioSettingValueString(0, 8, _filter(
1395
                                         _msg.line5)))
1396
            advanced.append(line5)
1397
            line6 = RadioSetting("poweron_msg.line6",
1398
                                 "Power-on message line 6",
1399
                                     RadioSettingValueString(0, 8, _filter(
1400
                                         _msg.line6)))
1401
            advanced.append(line6)
1402
            line7 = RadioSetting("poweron_msg.line7",
1403
                                 "Power-on message line 7",
1404
                                     RadioSettingValueString(0, 8, _filter(
1405
                                         _msg.line7)))
1406
            advanced.append(line7)
1407
            line8 = RadioSetting("poweron_msg.line8", "Static message",
1408
                                 RadioSettingValueString(0, 8, _filter(
1409
                                     _msg.line8)))
1410
            advanced.append(line8)
1411
        else:
1412
            line1 = RadioSetting("poweron_msg.line1",
1413
                                 "Power-on message line 1",
1414
                                     RadioSettingValueString(0, 6, _filter(
1415
                                         _msg.line1)))
1416
            advanced.append(line1)
1417
            line2 = RadioSetting("poweron_msg.line2",
1418
                                 "Power-on message line 2",
1419
                                     RadioSettingValueString(0, 6, _filter(
1420
                                         _msg.line2)))
1421
            advanced.append(line2)
1422

    
1423
        if self.MODEL in ("UV-2501", "UV-5001"):
1424
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1425
                                   RadioSettingValueBoolean(
1426
                                       _mem.settings2.vfomren))
1427
            advanced.append(vfomren)
1428

    
1429
            reseten = RadioSetting("settings2.reseten", "RESET",
1430
                                   RadioSettingValueBoolean(
1431
                                       _mem.settings2.reseten))
1432
            advanced.append(reseten)
1433

    
1434
            menuen = RadioSetting("settings2.menuen", "Menu",
1435
                                  RadioSettingValueBoolean(
1436
                                      _mem.settings2.menuen))
1437
            advanced.append(menuen)
1438

    
1439
        # Other
1440
        def convert_bytes_to_limit(bytes):
1441
            limit = ""
1442
            for byte in bytes:
1443
                if byte < 10:
1444
                    limit += chr(byte + 0x30)
1445
                else:
1446
                    break
1447
            return limit
1448

    
1449
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1450
            _ranges = self._memobj.ranges220
1451
            ranges = "ranges220"
1452
        else:
1453
            _ranges = self._memobj.ranges
1454
            ranges = "ranges"
1455

    
1456
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1457
        val = RadioSettingValueString(0, 3, _limit)
1458
        val.set_mutable(False)
1459
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1460
        other.append(vhf_low)
1461

    
1462
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1463
        val = RadioSettingValueString(0, 3, _limit)
1464
        val.set_mutable(False)
1465
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1466
        other.append(vhf_high)
1467

    
1468
        if self.BANDS == 3 or self.BANDS == 4:
1469
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1470
            val = RadioSettingValueString(0, 3, _limit)
1471
            val.set_mutable(False)
1472
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1473
            other.append(vhf2_low)
1474

    
1475
            _limit = convert_bytes_to_limit(_ranges.vhf2_high)
1476
            val = RadioSettingValueString(0, 3, _limit)
1477
            val.set_mutable(False)
1478
            vhf2_high = RadioSetting("%s.vhf2_high" % ranges, "VHF2 high", val)
1479
            other.append(vhf2_high)
1480

    
1481
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1482
        val = RadioSettingValueString(0, 3, _limit)
1483
        val.set_mutable(False)
1484
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1485
        other.append(uhf_low)
1486

    
1487
        _limit = convert_bytes_to_limit(_ranges.uhf_high)
1488
        val = RadioSettingValueString(0, 3, _limit)
1489
        val.set_mutable(False)
1490
        uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
1491
        other.append(uhf_high)
1492

    
1493
        if self.BANDS == 4:
1494
            _limit = convert_bytes_to_limit(_ranges.uhf2_low)
1495
            val = RadioSettingValueString(0, 3, _limit)
1496
            val.set_mutable(False)
1497
            uhf2_low = RadioSetting("%s.uhf2_low" % ranges, "UHF2 low", val)
1498
            other.append(uhf2_low)
1499

    
1500
            _limit = convert_bytes_to_limit(_ranges.uhf2_high)
1501
            val = RadioSettingValueString(0, 3, _limit)
1502
            val.set_mutable(False)
1503
            uhf2_high = RadioSetting("%s.uhf2_high" % ranges, "UHF2 high", val)
1504
            other.append(uhf2_high)
1505

    
1506
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1507
        val.set_mutable(False)
1508
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1509
        other.append(fp)
1510

    
1511

    
1512
        # Work
1513
        if self.COLOR_LCD:
1514
            dispab = RadioSetting("settings2.dispab", "Display",
1515
                                  RadioSettingValueList(
1516
                                      LIST_ABCD,
1517
                                      LIST_ABCD[_mem.settings2.dispab]))
1518
            work.append(dispab)
1519
        else:
1520
            dispab = RadioSetting("settings2.dispab", "Display",
1521
                                  RadioSettingValueList(
1522
                                      LIST_AB,
1523
                                      LIST_AB[_mem.settings2.dispab]))
1524
            work.append(dispab)
1525

    
1526
        if self.COLOR_LCD:
1527
            vfomra = RadioSetting("settings2.vfomra", "VFO/MR A mode",
1528
                                  RadioSettingValueList(
1529
                                      LIST_VFOMR,
1530
                                      LIST_VFOMR[_mem.settings2.vfomra]))
1531
            work.append(vfomra)
1532

    
1533
            vfomrb = RadioSetting("settings2.vfomrb", "VFO/MR B mode",
1534
                                  RadioSettingValueList(
1535
                                      LIST_VFOMR,
1536
                                      LIST_VFOMR[_mem.settings2.vfomrb]))
1537
            work.append(vfomrb)
1538

    
1539
            vfomrc = RadioSetting("settings2.vfomrc", "VFO/MR C mode",
1540
                                  RadioSettingValueList(
1541
                                      LIST_VFOMR,
1542
                                      LIST_VFOMR[_mem.settings2.vfomrc]))
1543
            work.append(vfomrc)
1544

    
1545
            vfomrd = RadioSetting("settings2.vfomrd", "VFO/MR D mode",
1546
                                  RadioSettingValueList(
1547
                                      LIST_VFOMR,
1548
                                      LIST_VFOMR[_mem.settings2.vfomrd]))
1549
            work.append(vfomrd)
1550
        else:
1551
            vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1552
                                 RadioSettingValueList(
1553
                                     LIST_VFOMR,
1554
                                     LIST_VFOMR[_mem.settings2.vfomr]))
1555
            work.append(vfomr)
1556

    
1557

    
1558
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1559
                           RadioSettingValueBoolean(_mem.settings2.keylock))
1560
        work.append(keylock)
1561

    
1562
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1563
                             RadioSettingValueInteger(0, 199,
1564
                                 _mem.settings2.mrcha))
1565
        work.append(mrcha)
1566

    
1567
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1568
                             RadioSettingValueInteger(0, 199,
1569
                                 _mem.settings2.mrchb))
1570
        work.append(mrchb)
1571

    
1572
        if self.COLOR_LCD:
1573
            mrchc = RadioSetting("settings2.mrchc", "MR C channel",
1574
                                 RadioSettingValueInteger(0, 199,
1575
                                     _mem.settings2.mrchc))
1576
            work.append(mrchc)
1577

    
1578
            mrchd = RadioSetting("settings2.mrchd", "MR D channel",
1579
                                 RadioSettingValueInteger(0, 199,
1580
                                     _mem.settings2.mrchd))
1581
            work.append(mrchd)
1582

    
1583
        def convert_bytes_to_freq(bytes):
1584
            real_freq = 0
1585
            for byte in bytes:
1586
                real_freq = (real_freq * 10) + byte
1587
            return chirp_common.format_freq(real_freq * 10)
1588

    
1589
        def my_validate(value):
1590
            _vhf_lower = int(convert_bytes_to_limit(_ranges.vhf_low))
1591
            _vhf_upper = int(convert_bytes_to_limit(_ranges.vhf_high))
1592
            _uhf_lower = int(convert_bytes_to_limit(_ranges.uhf_low))
1593
            _uhf_upper = int(convert_bytes_to_limit(_ranges.uhf_high))
1594
            if self.BANDS == 3 or self.BANDS == 4:
1595
                _vhf2_lower = int(convert_bytes_to_limit(_ranges.vhf2_low))
1596
                _vhf2_upper = int(convert_bytes_to_limit(_ranges.vhf2_high))
1597
            if self.BANDS == 4:
1598
                _uhf2_lower = int(convert_bytes_to_limit(_ranges.uhf2_low))
1599
                _uhf2_upper = int(convert_bytes_to_limit(_ranges.uhf2_high))
1600

    
1601
            value = chirp_common.parse_freq(value)
1602
            msg = ("Can't be less then %i.0000")
1603
            if value > 99000000 and value < _vhf_lower * 1000000:
1604
                raise InvalidValueError(msg % (_vhf_lower))
1605
            msg = ("Can't be betweeb %i.9975-%i.0000")
1606
            if self.BANDS == 2:
1607
                if (_vhf_upper + 1) * 1000000 <= value and \
1608
                    value < _uhf_lower * 1000000:
1609
                    raise InvalidValueError(msg % (_vhf_upper, _uhf_lower))
1610
            if self.BANDS == 3:
1611
                if (_vhf_upper + 1) * 1000000 <= value and \
1612
                    value < _vhf2_lower * 1000000:
1613
                    raise InvalidValueError(msg % (_vhf_upper, _vhf2_lower))
1614
                if (_vhf2_upper + 1) * 1000000 <= value and \
1615
                    value < _uhf_lower * 1000000:
1616
                    raise InvalidValueError(msg % (_vhf2_upper, _uhf_lower))
1617
            if self.BANDS == 4:
1618
                if (_vhf_upper + 1) * 1000000 <= value and \
1619
                    value < _vhf2_lower * 1000000:
1620
                    raise InvalidValueError(msg % (_vhf_upper, _vhf2_lower))
1621
                if (_vhf2_upper + 1) * 1000000 <= value and \
1622
                    value < _uhf2_lower * 1000000:
1623
                    raise InvalidValueError(msg % (_vhf2_upper, _uhf2_lower))
1624
                if (_uhf2_upper + 1) * 1000000 <= value and \
1625
                    value < _uhf_lower * 1000000:
1626
                    raise InvalidValueError(msg % (_uhf2_upper, _uhf_lower))
1627
            msg = ("Can't be greater then %i.9975")
1628
            if value > 99000000 and value >= _uhf_upper * 1000000:
1629
                raise InvalidValueError(msg % (_uhf_upper))
1630
            return chirp_common.format_freq(value)
1631

    
1632
        def apply_freq(setting, obj):
1633
            value = chirp_common.parse_freq(str(setting.value)) / 10
1634
            for i in range(7, -1, -1):
1635
                obj.freq[i] = value % 10
1636
                value /= 10
1637

    
1638
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1639
                                        _mem.vfo.a.freq))
1640
        val1a.set_validate_callback(my_validate)
1641
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1642
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1643
        work.append(vfoafreq)
1644

    
1645
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1646
                                        _mem.vfo.b.freq))
1647
        val1b.set_validate_callback(my_validate)
1648
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1649
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1650
        work.append(vfobfreq)
1651

    
1652
        if self.COLOR_LCD:
1653
            val1c = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1654
                                            _mem.vfo.c.freq))
1655
            val1c.set_validate_callback(my_validate)
1656
            vfocfreq = RadioSetting("vfo.c.freq", "VFO C frequency", val1c)
1657
            vfocfreq.set_apply_callback(apply_freq, _mem.vfo.c)
1658
            work.append(vfocfreq)
1659

    
1660
            val1d = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1661
                                            _mem.vfo.d.freq))
1662
            val1d.set_validate_callback(my_validate)
1663
            vfodfreq = RadioSetting("vfo.d.freq", "VFO D frequency", val1d)
1664
            vfodfreq.set_apply_callback(apply_freq, _mem.vfo.d)
1665
            work.append(vfodfreq)
1666

    
1667
        vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1668
                                  RadioSettingValueList(
1669
                                      LIST_SHIFT,
1670
                                      LIST_SHIFT[_mem.vfo.a.shiftd]))
1671
        work.append(vfoashiftd)
1672

    
1673
        vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1674
                                  RadioSettingValueList(
1675
                                      LIST_SHIFT,
1676
                                      LIST_SHIFT[_mem.vfo.b.shiftd]))
1677
        work.append(vfobshiftd)
1678

    
1679
        if self.COLOR_LCD:
1680
            vfocshiftd = RadioSetting("vfo.c.shiftd", "VFO C shift",
1681
                                      RadioSettingValueList(
1682
                                          LIST_SHIFT,
1683
                                          LIST_SHIFT[_mem.vfo.c.shiftd]))
1684
            work.append(vfocshiftd)
1685

    
1686
            vfodshiftd = RadioSetting("vfo.d.shiftd", "VFO D shift",
1687
                                      RadioSettingValueList(
1688
                                          LIST_SHIFT,
1689
                                          LIST_SHIFT[_mem.vfo.d.shiftd]))
1690
            work.append(vfodshiftd)
1691

    
1692
        def convert_bytes_to_offset(bytes):
1693
            real_offset = 0
1694
            for byte in bytes:
1695
                real_offset = (real_offset * 10) + byte
1696
            return chirp_common.format_freq(real_offset * 1000)
1697

    
1698
        def apply_offset(setting, obj):
1699
            value = chirp_common.parse_freq(str(setting.value)) / 1000
1700
            for i in range(5, -1, -1):
1701
                obj.offset[i] = value % 10
1702
                value /= 10
1703

    
1704
        if self.COLOR_LCD:
1705
            val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1706
                                            _mem.vfo.a.offset))
1707
            vfoaoffset = RadioSetting("vfo.a.offset",
1708
                                      "VFO A offset (0.000-999.999)", val1a)
1709
            vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1710
            work.append(vfoaoffset)
1711

    
1712
            val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1713
                                            _mem.vfo.b.offset))
1714
            vfoboffset = RadioSetting("vfo.b.offset",
1715
                                      "VFO B offset (0.000-999.999)", val1b)
1716
            vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1717
            work.append(vfoboffset)
1718

    
1719
            val1c = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1720
                                            _mem.vfo.c.offset))
1721
            vfocoffset = RadioSetting("vfo.c.offset",
1722
                                      "VFO C offset (0.000-999.999)", val1c)
1723
            vfocoffset.set_apply_callback(apply_offset, _mem.vfo.c)
1724
            work.append(vfocoffset)
1725

    
1726
            val1d = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1727
                                            _mem.vfo.d.offset))
1728
            vfodoffset = RadioSetting("vfo.d.offset",
1729
                                      "VFO D offset (0.000-999.999)", val1d)
1730
            vfodoffset.set_apply_callback(apply_offset, _mem.vfo.d)
1731
            work.append(vfodoffset)
1732
        else:
1733
            val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1734
                                            _mem.vfo.a.offset))
1735
            vfoaoffset = RadioSetting("vfo.a.offset",
1736
                                      "VFO A offset (0.000-99.999)", val1a)
1737
            vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1738
            work.append(vfoaoffset)
1739

    
1740
            val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1741
                                            _mem.vfo.b.offset))
1742
            vfoboffset = RadioSetting("vfo.b.offset",
1743
                                      "VFO B offset (0.000-99.999)", val1b)
1744
            vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1745
            work.append(vfoboffset)
1746

    
1747

    
1748
        vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1749
                               RadioSettingValueList(
1750
                                   LIST_TXP,
1751
                                   LIST_TXP[_mem.vfo.a.power]))
1752
        work.append(vfoatxp)
1753

    
1754
        vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1755
                               RadioSettingValueList(
1756
                                   LIST_TXP,
1757
                                   LIST_TXP[_mem.vfo.b.power]))
1758
        work.append(vfobtxp)
1759

    
1760
        if self.COLOR_LCD:
1761
            vfoctxp = RadioSetting("vfo.c.power", "VFO C power",
1762
                                   RadioSettingValueList(
1763
                                       LIST_TXP,
1764
                                       LIST_TXP[_mem.vfo.c.power]))
1765
            work.append(vfoctxp)
1766

    
1767
            vfodtxp = RadioSetting("vfo.d.power", "VFO D power",
1768
                                   RadioSettingValueList(
1769
                                       LIST_TXP,
1770
                                       LIST_TXP[_mem.vfo.d.power]))
1771
            work.append(vfodtxp)
1772

    
1773
        vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1774
                                RadioSettingValueList(
1775
                                    LIST_WIDE,
1776
                                    LIST_WIDE[_mem.vfo.a.wide]))
1777
        work.append(vfoawide)
1778

    
1779
        vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1780
                                RadioSettingValueList(
1781
                                    LIST_WIDE,
1782
                                    LIST_WIDE[_mem.vfo.b.wide]))
1783
        work.append(vfobwide)
1784

    
1785
        if self.COLOR_LCD:
1786
            vfocwide = RadioSetting("vfo.c.wide", "VFO C bandwidth",
1787
                                    RadioSettingValueList(
1788
                                        LIST_WIDE,
1789
                                        LIST_WIDE[_mem.vfo.c.wide]))
1790
            work.append(vfocwide)
1791

    
1792
            vfodwide = RadioSetting("vfo.d.wide", "VFO D bandwidth",
1793
                                    RadioSettingValueList(
1794
                                        LIST_WIDE,
1795
                                        LIST_WIDE[_mem.vfo.d.wide]))
1796
            work.append(vfodwide)
1797

    
1798
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
1799
                                RadioSettingValueList(
1800
                                    LIST_STEP,
1801
                                    LIST_STEP[_mem.vfo.a.step]))
1802
        work.append(vfoastep)
1803

    
1804
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
1805
                                RadioSettingValueList(
1806
                                    LIST_STEP,
1807
                                    LIST_STEP[_mem.vfo.b.step]))
1808
        work.append(vfobstep)
1809

    
1810
        if self.COLOR_LCD:
1811
            vfocstep = RadioSetting("vfo.c.step", "VFO C step",
1812
                                    RadioSettingValueList(
1813
                                        LIST_STEP,
1814
                                        LIST_STEP[_mem.vfo.c.step]))
1815
            work.append(vfocstep)
1816

    
1817
            vfodstep = RadioSetting("vfo.d.step", "VFO D step",
1818
                                    RadioSettingValueList(
1819
                                        LIST_STEP,
1820
                                        LIST_STEP[_mem.vfo.d.step]))
1821
            work.append(vfodstep)
1822

    
1823
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
1824
                                  RadioSettingValueList(
1825
                                      OPTSIG_LIST,
1826
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
1827
        work.append(vfoaoptsig)
1828

    
1829
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
1830
                                  RadioSettingValueList(
1831
                                      OPTSIG_LIST,
1832
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
1833
        work.append(vfoboptsig)
1834

    
1835
        if self.COLOR_LCD:
1836
            vfocoptsig = RadioSetting("vfo.c.optsig", "VFO C optional signal",
1837
                                      RadioSettingValueList(
1838
                                          OPTSIG_LIST,
1839
                                          OPTSIG_LIST[_mem.vfo.c.optsig]))
1840
            work.append(vfocoptsig)
1841

    
1842
            vfodoptsig = RadioSetting("vfo.d.optsig", "VFO D optional signal",
1843
                                      RadioSettingValueList(
1844
                                          OPTSIG_LIST,
1845
                                          OPTSIG_LIST[_mem.vfo.d.optsig]))
1846
            work.append(vfodoptsig)
1847

    
1848
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
1849
                                  RadioSettingValueList(
1850
                                      SPMUTE_LIST,
1851
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
1852
        work.append(vfoaspmute)
1853

    
1854
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
1855
                                  RadioSettingValueList(
1856
                                      SPMUTE_LIST,
1857
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
1858
        work.append(vfobspmute)
1859

    
1860
        if self.COLOR_LCD:
1861
            vfocspmute = RadioSetting("vfo.c.spmute", "VFO C speaker mute",
1862
                                      RadioSettingValueList(
1863
                                          SPMUTE_LIST,
1864
                                          SPMUTE_LIST[_mem.vfo.c.spmute]))
1865
            work.append(vfocspmute)
1866

    
1867
            vfodspmute = RadioSetting("vfo.d.spmute", "VFO D speaker mute",
1868
                                      RadioSettingValueList(
1869
                                          SPMUTE_LIST,
1870
                                          SPMUTE_LIST[_mem.vfo.d.spmute]))
1871
            work.append(vfodspmute)
1872

    
1873
        if not self.COLOR_LCD or \
1874
            (self.COLOR_LCD and not self.VENDOR == "BTECH"):
1875
            vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
1876
                                   RadioSettingValueBoolean(
1877
                                       _mem.vfo.a.scramble))
1878
            work.append(vfoascr)
1879

    
1880
            vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
1881
                                   RadioSettingValueBoolean(
1882
                                       _mem.vfo.b.scramble))
1883
            work.append(vfobscr)
1884

    
1885
        if self.COLOR_LCD and not self.VENDOR == "BTECH":
1886
            vfocscr = RadioSetting("vfo.c.scramble", "VFO C scramble",
1887
                                   RadioSettingValueBoolean(
1888
                                       _mem.vfo.c.scramble))
1889
            work.append(vfocscr)
1890

    
1891
            vfodscr = RadioSetting("vfo.d.scramble", "VFO D scramble",
1892
                                   RadioSettingValueBoolean(
1893
                                       _mem.vfo.d.scramble))
1894
            work.append(vfodscr)
1895

    
1896
        vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
1897
                                 RadioSettingValueList(
1898
                                     PTTIDCODE_LIST,
1899
                                     PTTIDCODE_LIST[_mem.vfo.a.scode]))
1900
        work.append(vfoascode)
1901

    
1902
        vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
1903
                                 RadioSettingValueList(
1904
                                     PTTIDCODE_LIST,
1905
                                     PTTIDCODE_LIST[_mem.vfo.b.scode]))
1906
        work.append(vfobscode)
1907

    
1908
        if self.COLOR_LCD:
1909
            vfocscode = RadioSetting("vfo.c.scode", "VFO C PTT-ID",
1910
                                     RadioSettingValueList(
1911
                                         PTTIDCODE_LIST,
1912
                                         PTTIDCODE_LIST[_mem.vfo.c.scode]))
1913
            work.append(vfocscode)
1914

    
1915
            vfodscode = RadioSetting("vfo.d.scode", "VFO D PTT-ID",
1916
                                     RadioSettingValueList(
1917
                                         PTTIDCODE_LIST,
1918
                                         PTTIDCODE_LIST[_mem.vfo.d.scode]))
1919
            work.append(vfodscode)
1920

    
1921
        pttid = RadioSetting("settings.pttid", "PTT ID",
1922
                             RadioSettingValueList(
1923
                                 PTTID_LIST,
1924
                                 PTTID_LIST[_mem.settings.pttid]))
1925
        work.append(pttid)
1926

    
1927
        if not self.COLOR_LCD:
1928
            #FM presets
1929
            fm_presets = RadioSettingGroup("fm_presets", "FM Presets")
1930
            top.append(fm_presets)
1931

    
1932
            def fm_validate(value):
1933
                if value == 0:
1934
                    return chirp_common.format_freq(value)
1935
                if not (87.5 <= value and value <= 108.0):  # 87.5-108MHz
1936
                    msg = ("FM-Preset-Frequency: Must be between 87.5 and 108 MHz")
1937
                    raise InvalidValueError(msg)
1938
                return value
1939

    
1940
            def apply_fm_preset_name(setting, obj):
1941
                valstring = str (setting.value)
1942
                for i in range(0,6):
1943
                    if valstring[i] in VALID_CHARS:
1944
                        obj[i] = valstring[i]
1945
                    else:
1946
                        obj[i] = '0xff'
1947

    
1948
            def apply_fm_freq(setting, obj):
1949
                value = chirp_common.parse_freq(str(setting.value)) / 10
1950
                for i in range(7, -1, -1):
1951
                    obj.freq[i] = value % 10
1952
                    value /= 10
1953

    
1954
            _presets = self._memobj.fm_radio_preset
1955
            i = 1
1956
            for preset in _presets:
1957
                line = RadioSetting("fm_presets_"+ str(i),
1958
                                    "Station name " + str(i),
1959
                                        RadioSettingValueString(0, 6, _filter(
1960
                                            preset.broadcast_station_name)))
1961
                line.set_apply_callback(apply_fm_preset_name,
1962
                                        preset.broadcast_station_name)
1963

    
1964
                val = RadioSettingValueFloat(0, 108,
1965
                                             convert_bytes_to_freq(
1966
                                                 preset.freq))
1967
                fmfreq = RadioSetting("fm_presets_"+ str(i) + "_freq",
1968
                                      "Frequency "+ str(i), val)
1969
                val.set_validate_callback(fm_validate)
1970
                fmfreq.set_apply_callback(apply_fm_freq, preset)
1971
                fm_presets.append(line)
1972
                fm_presets.append(fmfreq)
1973

    
1974
                i = i + 1
1975

    
1976
         # DTMF-Setting
1977
        dtmf_enc_settings = RadioSettingGroup ("dtmf_enc_settings",
1978
                                               "DTMF Encoding Settings")
1979
        dtmf_dec_settings = RadioSettingGroup ("dtmf_dec_settings",
1980
                                               "DTMF Decoding Settings")
1981
        top.append(dtmf_enc_settings)
1982
        top.append(dtmf_dec_settings)
1983
        txdisable = RadioSetting("dtmf_settings.txdisable",
1984
                                 "TX-Disable",
1985
                                 RadioSettingValueBoolean(
1986
                                     _mem.dtmf_settings.txdisable))
1987
        dtmf_enc_settings.append(txdisable)
1988

    
1989
        rxdisable = RadioSetting("dtmf_settings.rxdisable",
1990
                                 "RX-Disable",
1991
                                 RadioSettingValueBoolean(
1992
                                     _mem.dtmf_settings.rxdisable))
1993
        dtmf_enc_settings.append(rxdisable)
1994

    
1995
        dtmfspeed_on = RadioSetting(
1996
            "dtmf_settings.dtmfspeed_on",
1997
            "DTMF Speed (On Time)",
1998
            RadioSettingValueList(LIST_DTMF_SPEED,
1999
                                  LIST_DTMF_SPEED[
2000
                                      _mem.dtmf_settings.dtmfspeed_on]))
2001
        dtmf_enc_settings.append(dtmfspeed_on)
2002

    
2003
        dtmfspeed_off = RadioSetting(
2004
            "dtmf_settings.dtmfspeed_off",
2005
            "DTMF Speed (Off Time)",
2006
            RadioSettingValueList(LIST_DTMF_SPEED,
2007
                                  LIST_DTMF_SPEED[
2008
                                      _mem.dtmf_settings.dtmfspeed_off]))
2009
        dtmf_enc_settings.append(dtmfspeed_off)
2010

    
2011
        def memory2string(dmtf_mem):
2012
            dtmf_string = ""
2013
            for digit in dmtf_mem:
2014
                if digit != 255:
2015
                    index = LIST_DTMF_VALUES.index(digit)
2016
                    dtmf_string = dtmf_string + LIST_DTMF_DIGITS[index]
2017
            return dtmf_string
2018

    
2019
        def apply_dmtf_frame(setting, obj):
2020
            LOG.debug("Setting DTMF-Code: " + str(setting.value) )
2021
            val_string = str(setting.value)
2022
            for i in range(0,16):
2023
                obj[i] = 255
2024
            i = 0
2025
            for current_char in val_string:
2026
                current_char = current_char.upper()
2027
                index = LIST_DTMF_DIGITS.index(current_char)
2028
                obj[i] = LIST_DTMF_VALUES[ index ]
2029
                i = i + 1
2030

    
2031
        codes = self._memobj.dtmf_codes
2032
        i = 1
2033
        for dtmfcode in codes:
2034
            val = RadioSettingValueString(0, 16,
2035
                                          memory2string(dtmfcode.code),
2036
                                          False, CHARSET_DTMF_DIGITS)
2037
            line = RadioSetting("dtmf_code_" + str(i) + "_code",
2038
                                "DMTF Code " + str(i), val)
2039
            line.set_apply_callback(apply_dmtf_frame, dtmfcode.code)
2040
            dtmf_enc_settings.append(line)
2041
            i = i + 1
2042

    
2043
        line = RadioSetting("dtmf_settings.mastervice",
2044
                            "Master and Vice ID",
2045
                            RadioSettingValueBoolean(
2046
                                _mem.dtmf_settings.mastervice))
2047
        dtmf_dec_settings.append(line)
2048

    
2049
        val = RadioSettingValueString(0, 16,
2050
                                      memory2string(
2051
                                          _mem.dtmf_settings.masterid),
2052
                                          False, CHARSET_DTMF_DIGITS)
2053
        line = RadioSetting("dtmf_settings.masterid",
2054
                            "Master Control ID ", val)
2055
        line.set_apply_callback(apply_dmtf_frame,
2056
                                _mem.dtmf_settings.masterid)
2057
        dtmf_dec_settings.append(line)
2058

    
2059
        line = RadioSetting("dtmf_settings.minspection",
2060
                            "Master Inspection",
2061
                            RadioSettingValueBoolean(
2062
                                _mem.dtmf_settings.minspection))
2063
        dtmf_dec_settings.append(line)
2064

    
2065
        line = RadioSetting("dtmf_settings.mmonitor",
2066
                            "Master Monitor",
2067
                            RadioSettingValueBoolean(
2068
                                _mem.dtmf_settings.mmonitor))
2069
        dtmf_dec_settings.append(line)
2070

    
2071
        line = RadioSetting("dtmf_settings.mstun",
2072
                            "Master Stun",
2073
                            RadioSettingValueBoolean(
2074
                                _mem.dtmf_settings.mstun))
2075
        dtmf_dec_settings.append(line)
2076

    
2077
        line = RadioSetting("dtmf_settings.mkill",
2078
                            "Master Kill",
2079
                            RadioSettingValueBoolean(
2080
                                _mem.dtmf_settings.mkill))
2081
        dtmf_dec_settings.append(line)
2082

    
2083
        line = RadioSetting("dtmf_settings.mrevive",
2084
                            "Master Revive",
2085
                            RadioSettingValueBoolean(
2086
                                _mem.dtmf_settings.mrevive))
2087
        dtmf_dec_settings.append(line)
2088

    
2089
        val = RadioSettingValueString(0, 16,
2090
                                      memory2string(
2091
                                          _mem.dtmf_settings.viceid),
2092
                                          False, CHARSET_DTMF_DIGITS)
2093
        line = RadioSetting("dtmf_settings.viceid",
2094
                            "Vice Control ID ", val)
2095
        line.set_apply_callback(apply_dmtf_frame,
2096
                                _mem.dtmf_settings.viceid)
2097
        dtmf_dec_settings.append(line)
2098

    
2099
        line = RadioSetting("dtmf_settings.vinspection",
2100
                            "Vice Inspection",
2101
                            RadioSettingValueBoolean(
2102
                                _mem.dtmf_settings.vinspection))
2103
        dtmf_dec_settings.append(line)
2104

    
2105
        line = RadioSetting("dtmf_settings.vmonitor",
2106
                            "Vice Monitor",
2107
                            RadioSettingValueBoolean(
2108
                                _mem.dtmf_settings.vmonitor))
2109
        dtmf_dec_settings.append(line)
2110

    
2111
        line = RadioSetting("dtmf_settings.vstun",
2112
                            "Vice Stun",
2113
                            RadioSettingValueBoolean(
2114
                                _mem.dtmf_settings.vstun))
2115
        dtmf_dec_settings.append(line)
2116

    
2117
        line = RadioSetting("dtmf_settings.vkill",
2118
                            "Vice Kill",
2119
                            RadioSettingValueBoolean(
2120
                                _mem.dtmf_settings.vkill))
2121
        dtmf_dec_settings.append(line)
2122

    
2123
        line = RadioSetting("dtmf_settings.vrevive",
2124
                            "Vice Revive",
2125
                            RadioSettingValueBoolean(
2126
                                _mem.dtmf_settings.vrevive))
2127
        dtmf_dec_settings.append(line)
2128

    
2129
        val = RadioSettingValueString(0, 16,
2130
                                      memory2string(
2131
                                          _mem.dtmf_settings.inspection),
2132
                                          False, CHARSET_DTMF_DIGITS)
2133
        line = RadioSetting("dtmf_settings.inspection",
2134
                            "Inspection", val)
2135
        line.set_apply_callback(apply_dmtf_frame,
2136
                                _mem.dtmf_settings.inspection)
2137
        dtmf_dec_settings.append(line)
2138

    
2139
        val = RadioSettingValueString(0, 16,
2140
                                      memory2string(
2141
                                          _mem.dtmf_settings.alarmcode),
2142
                                          False, CHARSET_DTMF_DIGITS)
2143
        line = RadioSetting("dtmf_settings.alarmcode",
2144
                            "Alarm", val)
2145
        line.set_apply_callback(apply_dmtf_frame,
2146
                                _mem.dtmf_settings.alarmcode)
2147
        dtmf_dec_settings.append(line)
2148

    
2149
        val = RadioSettingValueString(0, 16,
2150
                                      memory2string(
2151
                                          _mem.dtmf_settings.kill),
2152
                                          False, CHARSET_DTMF_DIGITS)
2153
        line = RadioSetting("dtmf_settings.kill",
2154
                            "Kill", val)
2155
        line.set_apply_callback(apply_dmtf_frame,
2156
                                _mem.dtmf_settings.kill)
2157
        dtmf_dec_settings.append(line)
2158

    
2159
        val = RadioSettingValueString(0, 16,
2160
                                      memory2string(
2161
                                          _mem.dtmf_settings.monitor),
2162
                                          False, CHARSET_DTMF_DIGITS)
2163
        line = RadioSetting("dtmf_settings.monitor",
2164
                            "Monitor", val)
2165
        line.set_apply_callback(apply_dmtf_frame,
2166
                                _mem.dtmf_settings.monitor)
2167
        dtmf_dec_settings.append(line)
2168

    
2169
        val = RadioSettingValueString(0, 16,
2170
                                      memory2string(
2171
                                          _mem.dtmf_settings.stun),
2172
                                          False, CHARSET_DTMF_DIGITS)
2173
        line = RadioSetting("dtmf_settings.stun",
2174
                            "Stun", val)
2175
        line.set_apply_callback(apply_dmtf_frame,
2176
                                _mem.dtmf_settings.stun)
2177
        dtmf_dec_settings.append(line)
2178

    
2179
        val = RadioSettingValueString(0, 16,
2180
                                      memory2string(
2181
                                          _mem.dtmf_settings.revive),
2182
                                          False, CHARSET_DTMF_DIGITS)
2183
        line = RadioSetting("dtmf_settings.revive",
2184
                            "Revive", val)
2185
        line.set_apply_callback(apply_dmtf_frame,
2186
                                _mem.dtmf_settings.revive)
2187
        dtmf_dec_settings.append(line)
2188

    
2189
        def apply_dmtf_listvalue(setting, obj):
2190
            LOG.debug("Setting value: "+ str(setting.value) + " from list")
2191
            val = str(setting.value)
2192
            index = LIST_DTMF_SPECIAL_DIGITS.index(val)
2193
            val = LIST_DTMF_SPECIAL_VALUES[index]
2194
            obj.set_value(val)
2195

    
2196
        idx = LIST_DTMF_SPECIAL_VALUES.index(_mem.dtmf_settings.groupcode)
2197
        line = RadioSetting(
2198
            "dtmf_settings.groupcode",
2199
            "Group Code",
2200
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2201
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2202
        line.set_apply_callback(apply_dmtf_listvalue,
2203
                                _mem.dtmf_settings.groupcode)
2204
        dtmf_dec_settings.append(line)
2205

    
2206
        idx = LIST_DTMF_SPECIAL_VALUES.index(_mem.dtmf_settings.spacecode)
2207
        line = RadioSetting(
2208
            "dtmf_settings.spacecode",
2209
            "Space Code",
2210
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2211
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2212
        line.set_apply_callback(apply_dmtf_listvalue,
2213
                                _mem.dtmf_settings.spacecode)
2214
        dtmf_dec_settings.append(line)
2215

    
2216
        if self.COLOR_LCD:
2217
            line = RadioSetting(
2218
                "dtmf_settings.resettime",
2219
                "Reset time",
2220
                RadioSettingValueList(LIST_5TONE_RESET_COLOR,
2221
                                      LIST_5TONE_RESET_COLOR[
2222
                                          _mem.dtmf_settings.resettime]))
2223
            dtmf_dec_settings.append(line)
2224
        else:
2225
            line = RadioSetting(
2226
                "dtmf_settings.resettime",
2227
                "Reset time",
2228
                RadioSettingValueList(LIST_5TONE_RESET,
2229
                                      LIST_5TONE_RESET[
2230
                                          _mem.dtmf_settings.resettime]))
2231
            dtmf_dec_settings.append(line)
2232

    
2233
        line = RadioSetting(
2234
            "dtmf_settings.delayproctime",
2235
            "Delay processing time",
2236
            RadioSettingValueList(LIST_DTMF_DELAY,
2237
                                  LIST_DTMF_DELAY[
2238
                                      _mem.dtmf_settings.delayproctime]))
2239
        dtmf_dec_settings.append(line)
2240

    
2241

    
2242
        # 5 Tone Settings
2243
        stds_5tone = RadioSettingGroup ("stds_5tone", "Standards")
2244
        codes_5tone = RadioSettingGroup ("codes_5tone", "Codes")
2245

    
2246
        group_5tone = RadioSettingGroup ("group_5tone", "5 Tone Settings")
2247
        group_5tone.append(stds_5tone)
2248
        group_5tone.append(codes_5tone)
2249

    
2250
        top.append(group_5tone)
2251

    
2252
        def apply_list_value(setting, obj):
2253
            options = setting.value.get_options()
2254
            obj.set_value ( options.index(str(setting.value)) )
2255

    
2256
        _5tone_standards = self._memobj._5tone_std_settings
2257
        i = 0
2258
        for standard in _5tone_standards:
2259
            std_5tone = RadioSettingGroup ("std_5tone_" + str(i),
2260
                                           LIST_5TONE_STANDARDS[i])
2261
            stds_5tone.append(std_5tone)
2262

    
2263
            period = standard.period
2264
            if period == 255:
2265
                LOG.debug("Period for " + LIST_5TONE_STANDARDS[i] +
2266
                          " is not yet configured. Setting to 70ms.")
2267
                period = 5
2268

    
2269
            if period <= len( LIST_5TONE_STANDARD_PERIODS ):
2270
                line = RadioSetting(
2271
                    "_5tone_std_settings_" + str(i) + "_period",
2272
                    "Period (ms)", RadioSettingValueList
2273
                    (LIST_5TONE_STANDARD_PERIODS,
2274
                     LIST_5TONE_STANDARD_PERIODS[period]))
2275
                line.set_apply_callback(apply_list_value, standard.period)
2276
                std_5tone.append(line)
2277
            else:
2278
                LOG.debug("Invalid value for 5tone period! Disabling.")
2279

    
2280
            group_tone = standard.group_tone
2281
            if group_tone == 255:
2282
                LOG.debug("Group-Tone for " + LIST_5TONE_STANDARDS[i] +
2283
                          " is not yet configured. Setting to A.")
2284
                group_tone = 10
2285

    
2286
            if group_tone <= len( LIST_5TONE_DIGITS ):
2287
                line = RadioSetting(
2288
                    "_5tone_std_settings_" + str(i) + "_grouptone",
2289
                    "Group Tone",
2290
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2291
                                          LIST_5TONE_DIGITS[
2292
                                              group_tone]))
2293
                line.set_apply_callback(apply_list_value,
2294
                                        standard.group_tone)
2295
                std_5tone.append(line)
2296
            else:
2297
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2298

    
2299
            repeat_tone = standard.repeat_tone
2300
            if repeat_tone == 255:
2301
                LOG.debug("Repeat-Tone for " + LIST_5TONE_STANDARDS[i] +
2302
                          " is not yet configured. Setting to E.")
2303
                repeat_tone = 14
2304

    
2305
            if repeat_tone <= len( LIST_5TONE_DIGITS ):
2306
                line = RadioSetting(
2307
                    "_5tone_std_settings_" + str(i) + "_repttone",
2308
                    "Repeat Tone",
2309
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2310
                                          LIST_5TONE_DIGITS[
2311
                                              repeat_tone]))
2312
                line.set_apply_callback(apply_list_value,
2313
                                        standard.repeat_tone)
2314
                std_5tone.append(line)
2315
            else:
2316
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2317
            i = i + 1
2318

    
2319
        def my_apply_5tonestdlist_value(setting, obj):
2320
            if LIST_5TONE_STANDARDS.index(str(setting.value)) == 15:
2321
                obj.set_value(0xFF)
2322
            else:
2323
                obj.set_value( LIST_5TONE_STANDARDS.
2324
                              index(str(setting.value)) )
2325

    
2326
        def apply_5tone_frame(setting, obj):
2327
            LOG.debug("Setting 5 Tone: " + str(setting.value) )
2328
            valstring = str(setting.value)
2329
            if len(valstring) == 0:
2330
                for i in range(0,5):
2331
                    obj[i] = 255
2332
            else:
2333
                validFrame = True
2334
                for i in range(0,5):
2335
                    currentChar = valstring[i].upper()
2336
                    if currentChar in LIST_5TONE_DIGITS:
2337
                        obj[i] = LIST_5TONE_DIGITS.index(currentChar)
2338
                    else:
2339
                        validFrame = False
2340
                        LOG.debug("invalid char: " + str(currentChar))
2341
                if not validFrame:
2342
                    LOG.debug("setting whole frame to FF" )
2343
                    for i in range(0,5):
2344
                        obj[i] = 255
2345

    
2346
        def validate_5tone_frame(value):
2347
            if (len(str(value)) != 5) and (len(str(value)) != 0) :
2348
                msg = ("5 Tone must have 5 digits or 0 digits")
2349
                raise InvalidValueError(msg)
2350
            for digit in str(value):
2351
                if digit.upper() not in LIST_5TONE_DIGITS:
2352
                    msg = (str(digit) + " is not a valid digit for 5tones")
2353
                    raise InvalidValueError(msg)
2354
            return value
2355

    
2356
        def frame2string(frame):
2357
            frameString = ""
2358
            for digit in frame:
2359
                if digit != 255:
2360
                    frameString = frameString + LIST_5TONE_DIGITS[digit]
2361
            return frameString
2362

    
2363
        _5tone_codes = self._memobj._5tone_codes
2364
        i = 1
2365
        for code in _5tone_codes:
2366
            code_5tone = RadioSettingGroup ("code_5tone_" + str(i),
2367
                                            "5 Tone code " + str(i))
2368
            codes_5tone.append(code_5tone)
2369
            if (code.standard == 255 ):
2370
                currentVal = 15
2371
            else:
2372
                currentVal = code.standard
2373
            line = RadioSetting("_5tone_code_" + str(i) + "_std",
2374
                                " Standard",
2375
                                RadioSettingValueList(LIST_5TONE_STANDARDS,
2376
                                                      LIST_5TONE_STANDARDS[
2377
                                                          currentVal]) )
2378
            line.set_apply_callback(my_apply_5tonestdlist_value,
2379
                                    code.standard)
2380
            code_5tone.append(line)
2381

    
2382
            val = RadioSettingValueString(0, 6,
2383
                                          frame2string(code.frame1), False)
2384
            line = RadioSetting("_5tone_code_" + str(i) + "_frame1",
2385
                                " Frame 1", val)
2386
            val.set_validate_callback(validate_5tone_frame)
2387
            line.set_apply_callback(apply_5tone_frame, code.frame1)
2388
            code_5tone.append(line)
2389

    
2390
            val = RadioSettingValueString(0, 6,
2391
                                          frame2string(code.frame2), False)
2392
            line = RadioSetting("_5tone_code_" + str(i) + "_frame2",
2393
                                " Frame 2", val)
2394
            val.set_validate_callback(validate_5tone_frame)
2395
            line.set_apply_callback(apply_5tone_frame, code.frame2)
2396
            code_5tone.append(line)
2397

    
2398
            val = RadioSettingValueString(0, 6,
2399
                                          frame2string(code.frame3), False)
2400
            line = RadioSetting("_5tone_code_" + str(i) + "_frame3",
2401
                                " Frame 3", val)
2402
            val.set_validate_callback(validate_5tone_frame)
2403
            line.set_apply_callback(apply_5tone_frame, code.frame3)
2404
            code_5tone.append(line)
2405
            i = i + 1
2406

    
2407
        _5_tone_decode1 = RadioSetting(
2408
            "_5tone_settings._5tone_decode_call_frame1",
2409
            "5 Tone decode call Frame 1",
2410
            RadioSettingValueBoolean(
2411
                _mem._5tone_settings._5tone_decode_call_frame1))
2412
        group_5tone.append(_5_tone_decode1)
2413

    
2414
        _5_tone_decode2 = RadioSetting(
2415
            "_5tone_settings._5tone_decode_call_frame2",
2416
            "5 Tone decode call Frame 2",
2417
            RadioSettingValueBoolean(
2418
                _mem._5tone_settings._5tone_decode_call_frame2))
2419
        group_5tone.append(_5_tone_decode2)
2420

    
2421
        _5_tone_decode3 = RadioSetting(
2422
            "_5tone_settings._5tone_decode_call_frame3",
2423
            "5 Tone decode call Frame 3",
2424
            RadioSettingValueBoolean(
2425
                _mem._5tone_settings._5tone_decode_call_frame3))
2426
        group_5tone.append(_5_tone_decode3)
2427

    
2428
        _5_tone_decode_disp1 = RadioSetting(
2429
            "_5tone_settings._5tone_decode_disp_frame1",
2430
            "5 Tone decode disp Frame 1",
2431
            RadioSettingValueBoolean(
2432
                _mem._5tone_settings._5tone_decode_disp_frame1))
2433
        group_5tone.append(_5_tone_decode_disp1)
2434

    
2435
        _5_tone_decode_disp2 = RadioSetting(
2436
            "_5tone_settings._5tone_decode_disp_frame2",
2437
            "5 Tone decode disp Frame 2",
2438
            RadioSettingValueBoolean(
2439
                _mem._5tone_settings._5tone_decode_disp_frame2))
2440
        group_5tone.append(_5_tone_decode_disp2)
2441

    
2442
        _5_tone_decode_disp3 = RadioSetting(
2443
            "_5tone_settings._5tone_decode_disp_frame3",
2444
            "5 Tone decode disp Frame 3",
2445
            RadioSettingValueBoolean(
2446
                _mem._5tone_settings._5tone_decode_disp_frame3))
2447
        group_5tone.append(_5_tone_decode_disp3)
2448

    
2449
        decode_standard = _mem._5tone_settings.decode_standard
2450
        if decode_standard == 255:
2451
            decode_standard = 0
2452
        if decode_standard <= len (LIST_5TONE_STANDARDS_without_none) :
2453
            line = RadioSetting("_5tone_settings.decode_standard",
2454
                                "5 Tone-decode Standard",
2455
                                RadioSettingValueList(
2456
                                    LIST_5TONE_STANDARDS_without_none,
2457
                                    LIST_5TONE_STANDARDS_without_none[
2458
                                        decode_standard]))
2459
            group_5tone.append(line)
2460
        else:
2461
            LOG.debug("Invalid decode std...")
2462

    
2463
        _5tone_delay1 = _mem._5tone_settings._5tone_delay1
2464
        if _5tone_delay1 == 255:
2465
            _5tone_delay1 = 20
2466

    
2467
        if _5tone_delay1 <= len( LIST_5TONE_DELAY ):
2468
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2469
                                         LIST_5TONE_DELAY[
2470
                                             _5tone_delay1])
2471
            line = RadioSetting("_5tone_settings._5tone_delay1",
2472
                                "5 Tone Delay Frame 1", list)
2473
            group_5tone.append(line)
2474
        else:
2475
            LOG.debug("Invalid value for 5tone delay (frame1) ! Disabling.")
2476

    
2477
        _5tone_delay2 = _mem._5tone_settings._5tone_delay2
2478
        if _5tone_delay2 == 255:
2479
            _5tone_delay2 = 20
2480
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2481

    
2482
        if _5tone_delay2 <= len( LIST_5TONE_DELAY ):
2483
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2484
                                         LIST_5TONE_DELAY[
2485
                                             _5tone_delay2])
2486
            line = RadioSetting("_5tone_settings._5tone_delay2",
2487
                                "5 Tone Delay Frame 2", list)
2488
            group_5tone.append(line)
2489
        else:
2490
            LOG.debug("Invalid value for 5tone delay (frame2)! Disabling.")
2491

    
2492
        _5tone_delay3 = _mem._5tone_settings._5tone_delay3
2493
        if _5tone_delay3 == 255:
2494
            _5tone_delay3 = 20
2495
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2496

    
2497
        if _5tone_delay3 <= len( LIST_5TONE_DELAY ):
2498
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2499
                                         LIST_5TONE_DELAY[
2500
                                             _5tone_delay3])
2501
            line = RadioSetting("_5tone_settings._5tone_delay3",
2502
                                "5 Tone Delay Frame 3", list )
2503
            group_5tone.append(line)
2504
        else:
2505
            LOG.debug("Invalid value for 5tone delay (frame3)! Disabling.")
2506

    
2507
        ext_length = _mem._5tone_settings._5tone_first_digit_ext_length
2508
        if ext_length == 255:
2509
            ext_length = 0
2510
            LOG.debug("1st Tone ext lenght unconfigured! Resetting to 0")
2511

    
2512
        if ext_length <= len(
2513
            LIST_5TONE_DELAY ):
2514
            list = RadioSettingValueList(
2515
                LIST_5TONE_DELAY,
2516
                LIST_5TONE_DELAY[
2517
                    ext_length])
2518
            line = RadioSetting(
2519
                "_5tone_settings._5tone_first_digit_ext_length",
2520
                "First digit extend length", list)
2521
            group_5tone.append(line)
2522
        else:
2523
            LOG.debug("Invalid value for 5tone ext length! Disabling.")
2524

    
2525
        decode_reset_time = _mem._5tone_settings.decode_reset_time
2526
        if decode_reset_time == 255:
2527
            decode_reset_time = 59
2528
            LOG.debug("Decode reset time unconfigured. resetting.")
2529
        if decode_reset_time <= len(LIST_5TONE_RESET):
2530
            list = RadioSettingValueList(
2531
                LIST_5TONE_RESET,
2532
                LIST_5TONE_RESET[
2533
                    decode_reset_time])
2534
            line = RadioSetting("_5tone_settings.decode_reset_time",
2535
                                "Decode reset time", list)
2536
            group_5tone.append(line)
2537
        else:
2538
            LOG.debug("Invalid value decode reset time! Disabling.")
2539

    
2540
        # 2 Tone
2541
        encode_2tone = RadioSettingGroup ("encode_2tone", "2 Tone Encode")
2542
        decode_2tone = RadioSettingGroup ("decode_2tone", "2 Code Decode")
2543

    
2544
        top.append(encode_2tone)
2545
        top.append(decode_2tone)
2546

    
2547
        duration_1st_tone = self._memobj._2tone.duration_1st_tone
2548
        if duration_1st_tone == 255:
2549
            LOG.debug("Duration of first 2 Tone digit is not yet " +
2550
                      "configured. Setting to 600ms")
2551
            duration_1st_tone = 60
2552

    
2553
        if duration_1st_tone <= len( LIST_5TONE_DELAY ):
2554
            line = RadioSetting("_2tone.duration_1st_tone",
2555
                                "Duration 1st Tone",
2556
                                RadioSettingValueList(LIST_5TONE_DELAY,
2557
                                                      LIST_5TONE_DELAY[
2558
                                                          duration_1st_tone]))
2559
            encode_2tone.append(line)
2560

    
2561
        duration_2nd_tone = self._memobj._2tone.duration_2nd_tone
2562
        if duration_2nd_tone == 255:
2563
            LOG.debug("Duration of second 2 Tone digit is not yet " +
2564
                      "configured. Setting to 600ms")
2565
            duration_2nd_tone = 60
2566

    
2567
        if duration_2nd_tone <= len( LIST_5TONE_DELAY ):
2568
            line = RadioSetting("_2tone.duration_2nd_tone",
2569
                                "Duration 2nd Tone",
2570
                                RadioSettingValueList(LIST_5TONE_DELAY,
2571
                                                      LIST_5TONE_DELAY[
2572
                                                          duration_2nd_tone]))
2573
            encode_2tone.append(line)
2574

    
2575
        duration_gap = self._memobj._2tone.duration_gap
2576
        if duration_gap == 255:
2577
            LOG.debug("Duration of gap is not yet " +
2578
                      "configured. Setting to 300ms")
2579
            duration_gap = 30
2580

    
2581
        if duration_gap <= len( LIST_5TONE_DELAY ):
2582
            line = RadioSetting("_2tone.duration_gap", "Duration of gap",
2583
                                RadioSettingValueList(LIST_5TONE_DELAY,
2584
                                                      LIST_5TONE_DELAY[
2585
                                                          duration_gap]))
2586
            encode_2tone.append(line)
2587

    
2588
        def _2tone_validate(value):
2589
            if value == 0:
2590
                return 65535
2591
            if value == 65535:
2592
                return value
2593
            if not (300 <= value and value <= 3000):
2594
                msg = ("2 Tone Frequency: Must be between 300 and 3000 Hz")
2595
                raise InvalidValueError(msg)
2596
            return value
2597

    
2598
        def apply_2tone_freq(setting, obj):
2599
            val = int(setting.value)
2600
            if (val == 0) or (val == 65535):
2601
                obj.set_value(65535)
2602
            else:
2603
                obj.set_value(val)
2604

    
2605
        i = 1
2606
        for code in  self._memobj._2tone._2tone_encode:
2607
            code_2tone = RadioSettingGroup ("code_2tone_" + str(i),
2608
                                           "Encode Code " + str(i))
2609
            encode_2tone.append(code_2tone)
2610

    
2611
            tmp = code.freq1
2612
            if tmp == 65535:
2613
                tmp = 0
2614
            val1 = RadioSettingValueInteger(0, 65535, tmp)
2615
            freq1 = RadioSetting("2tone_code_"+ str(i) + "_freq1",
2616
                                 "Frequency 1", val1)
2617
            val1.set_validate_callback(_2tone_validate)
2618
            freq1.set_apply_callback(apply_2tone_freq, code.freq1)
2619
            code_2tone.append(freq1)
2620

    
2621
            tmp = code.freq2
2622
            if tmp == 65535:
2623
                tmp = 0
2624
            val2 = RadioSettingValueInteger(0, 65535, tmp)
2625
            freq2 = RadioSetting("2tone_code_"+ str(i) + "_freq2",
2626
                                 "Frequency 2", val2)
2627
            val2.set_validate_callback(_2tone_validate)
2628
            freq2.set_apply_callback(apply_2tone_freq, code.freq2)
2629
            code_2tone.append(freq2)
2630

    
2631
            i = i + 1
2632

    
2633
        decode_reset_time = _mem._2tone.reset_time
2634
        if decode_reset_time == 255:
2635
            decode_reset_time = 59
2636
            LOG.debug("Decode reset time unconfigured. resetting.")
2637
        if decode_reset_time <= len(LIST_5TONE_RESET):
2638
            list = RadioSettingValueList(
2639
                LIST_5TONE_RESET,
2640
                LIST_5TONE_RESET[
2641
                    decode_reset_time])
2642
            line = RadioSetting("_2tone.reset_time",
2643
                                "Decode reset time", list)
2644
            decode_2tone.append(line)
2645
        else:
2646
            LOG.debug("Invalid value decode reset time! Disabling.")
2647

    
2648
        def apply_2tone_freq_pair(setting, obj):
2649
            val = int(setting.value)
2650
            derived_val = 65535
2651
            frqname = str(setting._name[-5:])
2652
            derivedname = "derived_from_" + frqname
2653

    
2654
            if (val == 0):
2655
                val = 65535
2656
                derived_val = 65535
2657
            else:
2658
                derived_val = int(round(2304000.0/val))
2659

    
2660
            obj[frqname].set_value( val )
2661
            obj[derivedname].set_value( derived_val )
2662

    
2663
            LOG.debug("Apply " + frqname + ": " + str(val) + " | "
2664
                      + derivedname + ": " + str(derived_val))
2665

    
2666
        i = 1
2667
        for decode_code in  self._memobj._2tone._2tone_decode:
2668
            _2tone_dec_code = RadioSettingGroup ("code_2tone_" + str(i),
2669
                                           "Decode Code " + str(i))
2670
            decode_2tone.append(_2tone_dec_code)
2671

    
2672
            j = 1
2673
            for dec in decode_code.decs:
2674
                val = dec.dec
2675
                if val == 255:
2676
                    LOG.debug("Dec for Code " + str(i) + " Dec " + str(j) +
2677
                              " is not yet configured. Setting to 0.")
2678
                    val = 0
2679

    
2680
                if val <= len( LIST_2TONE_DEC ):
2681
                    line = RadioSetting(
2682
                        "_2tone_dec_settings_" + str(i) + "_dec_" + str(j),
2683
                        "Dec " + str(j), RadioSettingValueList
2684
                        (LIST_2TONE_DEC,
2685
                         LIST_2TONE_DEC[val]))
2686
                    line.set_apply_callback(apply_list_value, dec.dec)
2687
                    _2tone_dec_code.append(line)
2688
                else:
2689
                    LOG.debug("Invalid value for 2tone dec! Disabling.")
2690

    
2691
                val = dec.response
2692
                if val == 255:
2693
                    LOG.debug("Response for Code " + str(i) + " Dec " + str(j)+
2694
                              " is not yet configured. Setting to 0.")
2695
                    val = 0
2696

    
2697
                if val <= len( LIST_2TONE_RESPONSE ):
2698
                    line = RadioSetting(
2699
                        "_2tone_dec_settings_" + str(i) + "_resp_" + str(j),
2700
                        "Response " + str(j), RadioSettingValueList
2701
                        (LIST_2TONE_RESPONSE,
2702
                         LIST_2TONE_RESPONSE[val]))
2703
                    line.set_apply_callback(apply_list_value, dec.response)
2704
                    _2tone_dec_code.append(line)
2705
                else:
2706
                    LOG.debug("Invalid value for 2tone response! Disabling.")
2707

    
2708
                val = dec.alert
2709
                if val == 255:
2710
                    LOG.debug("Alert for Code " + str(i) + " Dec " + str(j) +
2711
                              " is not yet configured. Setting to 0.")
2712
                    val = 0
2713

    
2714
                if val <= len( PTTIDCODE_LIST ):
2715
                    line = RadioSetting(
2716
                        "_2tone_dec_settings_" + str(i) + "_alert_" + str(j),
2717
                        "Alert " + str(j), RadioSettingValueList
2718
                        (PTTIDCODE_LIST,
2719
                         PTTIDCODE_LIST[val]))
2720
                    line.set_apply_callback(apply_list_value, dec.alert)
2721
                    _2tone_dec_code.append(line)
2722
                else:
2723
                    LOG.debug("Invalid value for 2tone alert! Disabling.")
2724
                j = j + 1
2725

    
2726
            freq = self._memobj._2tone.freqs[i-1]
2727
            for char in ['A', 'B', 'C', 'D']:
2728
                setting_name = "freq" + str(char)
2729

    
2730
                tmp = freq[setting_name]
2731
                if tmp == 65535:
2732
                    tmp = 0
2733
                if tmp != 0:
2734
                    expected = int(round(2304000.0/tmp))
2735
                    from_mem = freq["derived_from_" + setting_name]
2736
                    if expected != from_mem:
2737
                        LOG.error("Expected " + str(expected) +
2738
                                  " but read " + str(from_mem ) +
2739
                                  ". Disabling 2Tone Decode Freqs!")
2740
                        break
2741
                val = RadioSettingValueInteger(0, 65535, tmp)
2742
                frq = RadioSetting("2tone_dec_"+ str(i) + "_freq" + str(char),
2743
                                         ("Decode Frequency " +str(char)), val)
2744
                val.set_validate_callback(_2tone_validate)
2745
                frq.set_apply_callback(apply_2tone_freq_pair, freq)
2746
                _2tone_dec_code.append(frq)
2747

    
2748
            i = i + 1
2749

    
2750
        return top
2751

    
2752
    def set_settings(self, settings):
2753
        _settings = self._memobj.settings
2754
        for element in settings:
2755
            if not isinstance(element, RadioSetting):
2756
                if element.get_name() == "fm_preset":
2757
                    self._set_fm_preset(element)
2758
                else:
2759
                    self.set_settings(element)
2760
                    continue
2761
            else:
2762
                try:
2763
                    name = element.get_name()
2764
                    if "." in name:
2765
                        bits = name.split(".")
2766
                        obj = self._memobj
2767
                        for bit in bits[:-1]:
2768
                            if "/" in bit:
2769
                                bit, index = bit.split("/", 1)
2770
                                index = int(index)
2771
                                obj = getattr(obj, bit)[index]
2772
                            else:
2773
                                obj = getattr(obj, bit)
2774
                        setting = bits[-1]
2775
                    else:
2776
                        obj = _settings
2777
                        setting = element.get_name()
2778

    
2779
                    if element.has_apply_callback():
2780
                        LOG.debug("Using apply callback")
2781
                        element.run_apply_callback()
2782
                    elif element.value.get_mutable():
2783
                        LOG.debug("Setting %s = %s" % (setting, element.value))
2784
                        setattr(obj, setting, element.value)
2785
                except Exception, e:
2786
                    LOG.debug(element.get_name())
2787
                    raise
2788

    
2789
    @classmethod
2790
    def match_model(cls, filedata, filename):
2791
        match_size = False
2792
        match_model = False
2793

    
2794
        # testing the file data size
2795
        if len(filedata) == MEM_SIZE:
2796
            match_size = True
2797

    
2798
        # testing the firmware model fingerprint
2799
        match_model = model_match(cls, filedata)
2800

    
2801
        if match_size and match_model:
2802
            return True
2803
        else:
2804
            return False
2805

    
2806

    
2807
MEM_FORMAT = """
2808
#seekto 0x0000;
2809
struct {
2810
  lbcd rxfreq[4];
2811
  lbcd txfreq[4];
2812
  ul16 rxtone;
2813
  ul16 txtone;
2814
  u8 unknown0:4,
2815
     scode:4;
2816
  u8 unknown1:2,
2817
     spmute:1,
2818
     unknown2:3,
2819
     optsig:2;
2820
  u8 unknown3:3,
2821
     scramble:1,
2822
     unknown4:3,
2823
     power:1;
2824
  u8 unknown5:1,
2825
     wide:1,
2826
     unknown6:2,
2827
     bcl:1,
2828
     add:1,
2829
     pttid:2;
2830
} memory[200];
2831

    
2832
#seekto 0x0E00;
2833
struct {
2834
  u8 tdr;
2835
  u8 unknown1;
2836
  u8 sql;
2837
  u8 unknown2[2];
2838
  u8 tot;
2839
  u8 apo;           // BTech radios use this as the Auto Power Off time
2840
                    // other radios use this as pre-Time Out Alert
2841
  u8 unknown3;
2842
  u8 abr;
2843
  u8 beep;
2844
  u8 unknown4[4];
2845
  u8 dtmfst;
2846
  u8 unknown5[2];
2847
  u8 prisc;
2848
  u8 prich;
2849
  u8 screv;
2850
  u8 unknown6[2];
2851
  u8 pttid;
2852
  u8 pttlt;
2853
  u8 unknown7;
2854
  u8 emctp;
2855
  u8 emcch;
2856
  u8 ringt;
2857
  u8 unknown8;
2858
  u8 camdf;
2859
  u8 cbmdf;
2860
  u8 sync;          // BTech radios use this as the display sync setting
2861
                    // other radios use this as the auto keypad lock setting
2862
  u8 ponmsg;
2863
  u8 wtled;
2864
  u8 rxled;
2865
  u8 txled;
2866
  u8 unknown9[5];
2867
  u8 anil;
2868
  u8 reps;
2869
  u8 repm;
2870
  u8 tdrab;
2871
  u8 ste;
2872
  u8 rpste;
2873
  u8 rptdl;
2874
  u8 mgain;
2875
  u8 dtmfg;
2876
} settings;
2877

    
2878
#seekto 0x0E80;
2879
struct {
2880
  u8 unknown1;
2881
  u8 vfomr;
2882
  u8 keylock;
2883
  u8 unknown2;
2884
  u8 unknown3:4,
2885
     vfomren:1,
2886
     unknown4:1,
2887
     reseten:1,
2888
     menuen:1;
2889
  u8 unknown5[11];
2890
  u8 dispab;
2891
  u8 mrcha;
2892
  u8 mrchb;
2893
  u8 menu;
2894
} settings2;
2895

    
2896
#seekto 0x0EC0;
2897
struct {
2898
  char line1[6];
2899
  char line2[6];
2900
} poweron_msg;
2901

    
2902
struct settings_vfo {
2903
  u8 freq[8];
2904
  u8 offset[6];
2905
  u8 unknown2[2];
2906
  ul16 rxtone;
2907
  ul16 txtone;
2908
  u8 scode;
2909
  u8 spmute;
2910
  u8 optsig;
2911
  u8 scramble;
2912
  u8 wide;
2913
  u8 power;
2914
  u8 shiftd;
2915
  u8 step;
2916
  u8 unknown3[4];
2917
};
2918

    
2919
#seekto 0x0F00;
2920
struct {
2921
  struct settings_vfo a;
2922
  struct settings_vfo b;
2923
} vfo;
2924

    
2925
#seekto 0x1000;
2926
struct {
2927
  char name[6];
2928
  u8 unknown1[10];
2929
} names[200];
2930

    
2931
#seekto 0x2400;
2932
struct {
2933
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
2934
  u8 group_tone;
2935
  u8 repeat_tone;
2936
  u8 unused[13];
2937
} _5tone_std_settings[15];
2938

    
2939
#seekto 0x2500;
2940
struct {
2941
  u8 frame1[5];
2942
  u8 frame2[5];
2943
  u8 frame3[5];
2944
  u8 standard;   // one out of LIST_5TONE_STANDARDS
2945
} _5tone_codes[15];
2946

    
2947
#seekto 0x25F0;
2948
struct {
2949
  u8 _5tone_delay1; // * 10ms
2950
  u8 _5tone_delay2; // * 10ms
2951
  u8 _5tone_delay3; // * 10ms
2952
  u8 _5tone_first_digit_ext_length;
2953
  u8 unknown1;
2954
  u8 unknown2;
2955
  u8 unknown3;
2956
  u8 unknown4;
2957
  u8 decode_standard;
2958
  u8 unknown5:5,
2959
     _5tone_decode_call_frame3:1,
2960
     _5tone_decode_call_frame2:1,
2961
     _5tone_decode_call_frame1:1;
2962
  u8 unknown6:5,
2963
     _5tone_decode_disp_frame3:1,
2964
     _5tone_decode_disp_frame2:1,
2965
     _5tone_decode_disp_frame1:1;
2966
  u8 decode_reset_time; // * 100 + 100ms
2967
} _5tone_settings;
2968

    
2969
#seekto 0x2900;
2970
struct {
2971
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
2972
} dtmf_codes[15];
2973

    
2974
#seekto 0x29F0;
2975
struct {
2976
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
2977
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
2978
  u8 unknown0[14];
2979
  u8 inspection[16];
2980
  u8 monitor[16];
2981
  u8 alarmcode[16];
2982
  u8 stun[16];
2983
  u8 kill[16];
2984
  u8 revive[16];
2985
  u8 unknown1[16];
2986
  u8 unknown2[16];
2987
  u8 unknown3[16];
2988
  u8 unknown4[16];
2989
  u8 unknown5[16];
2990
  u8 unknown6[16];
2991
  u8 unknown7[16];
2992
  u8 masterid[16];
2993
  u8 viceid[16];
2994
  u8 unused01:7,
2995
     mastervice:1;
2996
  u8 unused02:3,
2997
     mrevive:1,
2998
     mkill:1,
2999
     mstun:1,
3000
     mmonitor:1,
3001
     minspection:1;
3002
  u8 unused03:3,
3003
     vrevive:1,
3004
     vkill:1,
3005
     vstun:1,
3006
     vmonitor:1,
3007
     vinspection:1;
3008
  u8 unused04:6,
3009
     txdisable:1,
3010
     rxdisable:1;
3011
  u8 groupcode;
3012
  u8 spacecode;
3013
  u8 delayproctime; // * 100 + 100ms
3014
  u8 resettime;     // * 100 + 100ms
3015
} dtmf_settings;
3016

    
3017
#seekto 0x2D00;
3018
struct {
3019
  struct {
3020
    ul16 freq1;
3021
    u8 unused01[6];
3022
    ul16 freq2;
3023
    u8 unused02[6];
3024
  } _2tone_encode[15];
3025
  u8 duration_1st_tone; // *10ms
3026
  u8 duration_2nd_tone; // *10ms
3027
  u8 duration_gap;      // *10ms
3028
  u8 unused03[13];
3029
  struct {
3030
    struct {
3031
      u8 dec;      // one out of LIST_2TONE_DEC
3032
      u8 response; // one out of LIST_2TONE_RESPONSE
3033
      u8 alert;    // 1-16
3034
    } decs[4];
3035
    u8 unused04[4];
3036
  } _2tone_decode[15];
3037
  u8 unused05[16];
3038

    
3039
  struct {
3040
    ul16 freqA;
3041
    ul16 freqB;
3042
    ul16 freqC;
3043
    ul16 freqD;
3044
    // unknown what those values mean, but they are
3045
    // derived from configured frequencies
3046
    ul16 derived_from_freqA; // 2304000/freqA
3047
    ul16 derived_from_freqB; // 2304000/freqB
3048
    ul16 derived_from_freqC; // 2304000/freqC
3049
    ul16 derived_from_freqD; // 2304000/freqD
3050
  }freqs[15];
3051
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
3052
} _2tone;
3053

    
3054
#seekto 0x3000;
3055
struct {
3056
  u8 freq[8];
3057
  char broadcast_station_name[6];
3058
  u8 unknown[2];
3059
} fm_radio_preset[16];
3060

    
3061
#seekto 0x3C90;
3062
struct {
3063
  u8 vhf_low[3];
3064
  u8 vhf_high[3];
3065
  u8 uhf_low[3];
3066
  u8 uhf_high[3];
3067
} ranges;
3068

    
3069
// the UV-2501+220 & KT8900R has different zones for storing ranges
3070

    
3071
#seekto 0x3CD0;
3072
struct {
3073
  u8 vhf_low[3];
3074
  u8 vhf_high[3];
3075
  u8 unknown1[4];
3076
  u8 unknown2[6];
3077
  u8 vhf2_low[3];
3078
  u8 vhf2_high[3];
3079
  u8 unknown3[4];
3080
  u8 unknown4[6];
3081
  u8 uhf_low[3];
3082
  u8 uhf_high[3];
3083
} ranges220;
3084

    
3085
#seekto 0x3F70;
3086
struct {
3087
  char fp[6];
3088
} fingerprint;
3089

    
3090
"""
3091

    
3092

    
3093
class BTech(BTechMobileCommon):
3094
    """BTECH's UV-5001 and alike radios"""
3095
    BANDS = 2
3096
    COLOR_LCD = False
3097
    NAME_LENGTH = 6
3098

    
3099
    def set_options(self):
3100
        """This is to read the options from the image and set it in the
3101
        environment, for now just the limits of the freqs in the VHF/UHF
3102
        ranges"""
3103

    
3104
        # setting the correct ranges for each radio type
3105
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3106
            # the model 2501+220 has a segment in 220
3107
            # and a different position in the memmap
3108
            # also the QYT KT8900R
3109
            ranges = self._memobj.ranges220
3110
        else:
3111
            ranges = self._memobj.ranges
3112

    
3113
        # the normal dual bands
3114
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3115
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3116

    
3117
        # DEBUG
3118
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3119
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3120

    
3121
        # 220Mhz radios case
3122
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3123
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3124
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3125
            self._220_range = vhf2
3126

    
3127
        # set the class with the real data
3128
        self._vhf_range = vhf
3129
        self._uhf_range = uhf
3130

    
3131
    def process_mmap(self):
3132
        """Process the mem map into the mem object"""
3133

    
3134
        # Get it
3135
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
3136

    
3137
        # load specific parameters from the radio image
3138
        self.set_options()
3139

    
3140

    
3141
# Declaring Aliases (Clones of the real radios)
3142
class JT2705M(chirp_common.Alias):
3143
    VENDOR = "Jetstream"
3144
    MODEL = "JT2705M"
3145

    
3146

    
3147
class JT6188Mini(chirp_common.Alias):
3148
    VENDOR = "Juentai"
3149
    MODEL = "JT-6188 Mini"
3150

    
3151

    
3152
class JT6188Plus(chirp_common.Alias):
3153
    VENDOR = "Juentai"
3154
    MODEL = "JT-6188 Plus"
3155

    
3156

    
3157
class SSGT890(chirp_common.Alias):
3158
    VENDOR = "Sainsonic"
3159
    MODEL = "GT-890"
3160

    
3161

    
3162
class ZastoneMP300(chirp_common.Alias):
3163
    VENDOR = "Zastone"
3164
    MODEL = "MP-300"
3165

    
3166

    
3167
# real radios
3168
@directory.register
3169
class UV2501(BTech):
3170
    """Baofeng Tech UV2501"""
3171
    MODEL = "UV-2501"
3172
    _fileid = [UV2501G3_fp,
3173
               UV2501G2_fp,
3174
               UV2501pp2_fp,
3175
               UV2501pp_fp]
3176

    
3177

    
3178
@directory.register
3179
class UV2501_220(BTech):
3180
    """Baofeng Tech UV2501+220"""
3181
    MODEL = "UV-2501+220"
3182
    BANDS = 3
3183
    _magic = MSTRING_220
3184
    _id2 = UV2501_220pp_id
3185
    _fileid = [UV2501_220G3_fp,
3186
               UV2501_220G2_fp,
3187
               UV2501_220_fp,
3188
               UV2501_220pp_fp]
3189

    
3190

    
3191
@directory.register
3192
class UV5001(BTech):
3193
    """Baofeng Tech UV5001"""
3194
    MODEL = "UV-5001"
3195
    _fileid = [UV5001G3_fp,
3196
               UV5001G22_fp,
3197
               UV5001G2_fp,
3198
               UV5001alpha_fp,
3199
               UV5001pp_fp]
3200
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
3201
                     chirp_common.PowerLevel("Low", watts=10)]
3202

    
3203

    
3204
@directory.register
3205
class MINI8900(BTech):
3206
    """WACCOM MINI-8900"""
3207
    VENDOR = "WACCOM"
3208
    MODEL = "MINI-8900"
3209
    _magic = MSTRING_MINI8900
3210
    _fileid = [MINI8900_fp, ]
3211
    # Clones
3212
    ALIASES = [JT6188Plus, ]
3213

    
3214

    
3215
@directory.register
3216
class KTUV980(BTech):
3217
    """QYT KT-UV980"""
3218
    VENDOR = "QYT"
3219
    MODEL = "KT-UV980"
3220
    _vhf_range = (136000000, 175000000)
3221
    _uhf_range = (400000000, 481000000)
3222
    _magic = MSTRING_MINI8900
3223
    _fileid = [KTUV980_fp, ]
3224
    # Clones
3225
    ALIASES = [JT2705M, ]
3226

    
3227
# Please note that there is a version of this radios that is a clone of the
3228
# Waccom Mini8900, maybe an early version?
3229
@directory.register
3230
class KT9800(BTech):
3231
    """QYT KT8900"""
3232
    VENDOR = "QYT"
3233
    MODEL = "KT8900"
3234
    _vhf_range = (136000000, 175000000)
3235
    _uhf_range = (400000000, 481000000)
3236
    _magic = MSTRING_KT8900
3237
    _fileid = [KT8900_fp,
3238
               KT8900_fp1,
3239
               KT8900_fp2,
3240
               KT8900_fp3,
3241
               KT8900_fp4,
3242
               KT8900_fp5]
3243
    _id2 = KT8900_id
3244
    # Clones
3245
    ALIASES = [JT6188Mini, SSGT890, ZastoneMP300]
3246

    
3247

    
3248
@directory.register
3249
class KT9800R(BTech):
3250
    """QYT KT8900R"""
3251
    VENDOR = "QYT"
3252
    MODEL = "KT8900R"
3253
    BANDS = 3
3254
    _vhf_range = (136000000, 175000000)
3255
    _220_range = (240000000, 271000000)
3256
    _uhf_range = (400000000, 481000000)
3257
    _magic = MSTRING_KT8900R
3258
    _fileid = [KT8900R_fp,
3259
               KT8900R_fp1,
3260
               KT8900R_fp2,
3261
               KT8900R_fp3,
3262
               KT8900R_fp4]
3263
    _id2 = KT8900R_id
3264

    
3265

    
3266
@directory.register
3267
class LT588UV(BTech):
3268
    """LUITON LT-588UV"""
3269
    VENDOR = "LUITON"
3270
    MODEL = "LT-588UV"
3271
    _vhf_range = (136000000, 175000000)
3272
    _uhf_range = (400000000, 481000000)
3273
    _magic = MSTRING_KT8900
3274
    _fileid = [LT588UV_fp,
3275
               LT588UV_fp1]
3276
    _power_levels = [chirp_common.PowerLevel("High", watts=60),
3277
                     chirp_common.PowerLevel("Low", watts=10)]
3278

    
3279

    
3280
COLOR_MEM_FORMAT = """
3281
#seekto 0x0000;
3282
struct {
3283
  lbcd rxfreq[4];
3284
  lbcd txfreq[4];
3285
  ul16 rxtone;
3286
  ul16 txtone;
3287
  u8 unknown0:4,
3288
     scode:4;
3289
  u8 unknown1:2,
3290
     spmute:1,
3291
     unknown2:3,
3292
     optsig:2;
3293
  u8 unknown3:3,
3294
     scramble:1,
3295
     unknown4:3,
3296
     power:1;
3297
  u8 unknown5:1,
3298
     wide:1,
3299
     unknown6:2,
3300
     bcl:1,
3301
     add:1,
3302
     pttid:2;
3303
} memory[200];
3304

    
3305
#seekto 0x0E00;
3306
struct {
3307
  u8 tmr;
3308
  u8 unknown1;
3309
  u8 sql;
3310
  u8 unknown2[2];
3311
  u8 tot;
3312
  u8 apo;
3313
  u8 unknown3;
3314
  u8 abr;
3315
  u8 beep;
3316
  u8 unknown4[4];
3317
  u8 dtmfst;
3318
  u8 unknown5[2];
3319
  u8 screv;
3320
  u8 unknown6[2];
3321
  u8 pttid;
3322
  u8 pttlt;
3323
  u8 unknown7;
3324
  u8 emctp;
3325
  u8 emcch;
3326
  u8 sigbp;
3327
  u8 unknown8;
3328
  u8 camdf;
3329
  u8 cbmdf;
3330
  u8 ccmdf;
3331
  u8 cdmdf;
3332
  u8 langua;
3333
  u8 sync;          // BTech radios use this as the display sync
3334
                    // setting, other radios use this as the auto
3335
                    // keypad lock setting
3336
  u8 mainfc;
3337
  u8 mainbc;
3338
  u8 menufc;
3339
  u8 menubc;
3340
  u8 stafc;
3341
  u8 stabc;
3342
  u8 sigfc;
3343
  u8 sigbc;
3344
  u8 rxfc;
3345
  u8 txfc;
3346
  u8 txdisp;
3347
  u8 unknown9[5];
3348
  u8 anil;
3349
  u8 reps;
3350
  u8 repm;
3351
  u8 tmrmr;
3352
  u8 ste;
3353
  u8 rpste;
3354
  u8 rptdl;
3355
  u8 dtmfg;
3356
  u8 mgain;
3357
  u8 skiptx;
3358
  u8 scmode;
3359
} settings;
3360

    
3361
#seekto 0x0E80;
3362
struct {
3363
  u8 unknown1;
3364
  u8 vfomr;
3365
  u8 keylock;
3366
  u8 unknown2;
3367
  u8 unknown3:4,
3368
     vfomren:1,
3369
     unknown4:1,
3370
     reseten:1,
3371
     menuen:1;
3372
  u8 unknown5[11];
3373
  u8 dispab;
3374
  u8 unknown6[2];
3375
  u8 menu;
3376
  u8 unknown7[7];
3377
  u8 vfomra;
3378
  u8 vfomrb;
3379
  u8 vfomrc;
3380
  u8 vfomrd;
3381
  u8 mrcha;
3382
  u8 mrchb;
3383
  u8 mrchc;
3384
  u8 mrchd;
3385
} settings2;
3386

    
3387
struct settings_vfo {
3388
  u8 freq[8];
3389
  u8 offset[6];
3390
  u8 unknown2[2];
3391
  ul16 rxtone;
3392
  ul16 txtone;
3393
  u8 scode;
3394
  u8 spmute;
3395
  u8 optsig;
3396
  u8 scramble;
3397
  u8 wide;
3398
  u8 power;
3399
  u8 shiftd;
3400
  u8 step;
3401
  u8 unknown3[4];
3402
};
3403

    
3404
#seekto 0x0F00;
3405
struct {
3406
  struct settings_vfo a;
3407
  struct settings_vfo b;
3408
  struct settings_vfo c;
3409
  struct settings_vfo d;
3410
} vfo;
3411

    
3412
#seekto 0x0F80;
3413
struct {
3414
  char line1[8];
3415
  char line2[8];
3416
  char line3[8];
3417
  char line4[8];
3418
  char line5[8];
3419
  char line6[8];
3420
  char line7[8];
3421
  char line8[8];
3422
} poweron_msg;
3423

    
3424
#seekto 0x1000;
3425
struct {
3426
  char name[8];
3427
  u8 unknown1[8];
3428
} names[200];
3429

    
3430
#seekto 0x2400;
3431
struct {
3432
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3433
  u8 group_tone;
3434
  u8 repeat_tone;
3435
  u8 unused[13];
3436
} _5tone_std_settings[15];
3437

    
3438
#seekto 0x2500;
3439
struct {
3440
  u8 frame1[5];
3441
  u8 frame2[5];
3442
  u8 frame3[5];
3443
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3444
} _5tone_codes[15];
3445

    
3446
#seekto 0x25F0;
3447
struct {
3448
  u8 _5tone_delay1; // * 10ms
3449
  u8 _5tone_delay2; // * 10ms
3450
  u8 _5tone_delay3; // * 10ms
3451
  u8 _5tone_first_digit_ext_length;
3452
  u8 unknown1;
3453
  u8 unknown2;
3454
  u8 unknown3;
3455
  u8 unknown4;
3456
  u8 decode_standard;
3457
  u8 unknown5:5,
3458
     _5tone_decode_call_frame3:1,
3459
     _5tone_decode_call_frame2:1,
3460
     _5tone_decode_call_frame1:1;
3461
  u8 unknown6:5,
3462
     _5tone_decode_disp_frame3:1,
3463
     _5tone_decode_disp_frame2:1,
3464
     _5tone_decode_disp_frame1:1;
3465
  u8 decode_reset_time; // * 100 + 100ms
3466
} _5tone_settings;
3467

    
3468
#seekto 0x2900;
3469
struct {
3470
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3471
} dtmf_codes[15];
3472

    
3473
#seekto 0x29F0;
3474
struct {
3475
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
3476
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
3477
  u8 unknown0[14];
3478
  u8 inspection[16];
3479
  u8 monitor[16];
3480
  u8 alarmcode[16];
3481
  u8 stun[16];
3482
  u8 kill[16];
3483
  u8 revive[16];
3484
  u8 unknown1[16];
3485
  u8 unknown2[16];
3486
  u8 unknown3[16];
3487
  u8 unknown4[16];
3488
  u8 unknown5[16];
3489
  u8 unknown6[16];
3490
  u8 unknown7[16];
3491
  u8 masterid[16];
3492
  u8 viceid[16];
3493
  u8 unused01:7,
3494
     mastervice:1;
3495
  u8 unused02:3,
3496
     mrevive:1,
3497
     mkill:1,
3498
     mstun:1,
3499
     mmonitor:1,
3500
     minspection:1;
3501
  u8 unused03:3,
3502
     vrevive:1,
3503
     vkill:1,
3504
     vstun:1,
3505
     vmonitor:1,
3506
     vinspection:1;
3507
  u8 unused04:6,
3508
     txdisable:1,
3509
     rxdisable:1;
3510
  u8 groupcode;
3511
  u8 spacecode;
3512
  u8 delayproctime; // * 100 + 100ms
3513
  u8 resettime;     // * 100 + 100ms
3514
} dtmf_settings;
3515

    
3516
#seekto 0x2D00;
3517
struct {
3518
  struct {
3519
    ul16 freq1;
3520
    u8 unused01[6];
3521
    ul16 freq2;
3522
    u8 unused02[6];
3523
  } _2tone_encode[15];
3524
  u8 duration_1st_tone; // *10ms
3525
  u8 duration_2nd_tone; // *10ms
3526
  u8 duration_gap;      // *10ms
3527
  u8 unused03[13];
3528
  struct {
3529
    struct {
3530
      u8 dec;      // one out of LIST_2TONE_DEC
3531
      u8 response; // one out of LIST_2TONE_RESPONSE
3532
      u8 alert;    // 1-16
3533
    } decs[4];
3534
    u8 unused04[4];
3535
  } _2tone_decode[15];
3536
  u8 unused05[16];
3537

    
3538
  struct {
3539
    ul16 freqA;
3540
    ul16 freqB;
3541
    ul16 freqC;
3542
    ul16 freqD;
3543
    // unknown what those values mean, but they are
3544
    // derived from configured frequencies
3545
    ul16 derived_from_freqA; // 2304000/freqA
3546
    ul16 derived_from_freqB; // 2304000/freqB
3547
    ul16 derived_from_freqC; // 2304000/freqC
3548
    ul16 derived_from_freqD; // 2304000/freqD
3549
  }freqs[15];
3550
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
3551
} _2tone;
3552

    
3553
#seekto 0x3D80;
3554
struct {
3555
  u8 vhf_low[3];
3556
  u8 vhf_high[3];
3557
  u8 unknown1[4];
3558
  u8 unknown2[6];
3559
  u8 vhf2_low[3];
3560
  u8 vhf2_high[3];
3561
  u8 unknown3[4];
3562
  u8 unknown4[6];
3563
  u8 uhf_low[3];
3564
  u8 uhf_high[3];
3565
  u8 unknown5[4];
3566
  u8 unknown6[6];
3567
  u8 uhf2_low[3];
3568
  u8 uhf2_high[3];
3569
} ranges;
3570

    
3571
#seekto 0x3F70;
3572
struct {
3573
  char fp[6];
3574
} fingerprint;
3575

    
3576
"""
3577

    
3578

    
3579
class BTechColor(BTechMobileCommon):
3580
    """BTECH's Color LCD Mobile and alike radios"""
3581
    COLOR_LCD = True
3582
    NAME_LENGTH = 8
3583

    
3584
    def process_mmap(self):
3585
        """Process the mem map into the mem object"""
3586

    
3587
        # Get it
3588
        self._memobj = bitwise.parse(COLOR_MEM_FORMAT, self._mmap)
3589

    
3590
        # load specific parameters from the radio image
3591
        self.set_options()
3592

    
3593
    def set_options(self):
3594
        """This is to read the options from the image and set it in the
3595
        environment, for now just the limits of the freqs in the VHF/UHF
3596
        ranges"""
3597

    
3598
        # setting the correct ranges for each radio type
3599
        ranges = self._memobj.ranges
3600

    
3601
        # the normal dual bands
3602
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3603
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3604

    
3605
        # DEBUG
3606
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3607
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3608

    
3609
        # the additional bands
3610
        if self.MODEL in ["UV-25X4", "KT7900D"]:
3611
            # 200Mhz band
3612
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3613
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3614
            self._220_range = vhf2
3615

    
3616
            # 350Mhz band
3617
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
3618
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
3619
            self._350_range = uhf2
3620

    
3621
        # set the class with the real data
3622
        self._vhf_range = vhf
3623
        self._uhf_range = uhf
3624

    
3625

    
3626
# Declaring Aliases (Clones of the real radios)
3627
class SKT8900D(chirp_common.Alias):
3628
    VENDOR = "Surecom"
3629
    MODEL = "S-KT8900D"
3630

    
3631

    
3632
class QB25(chirp_common.Alias):
3633
    VENDOR = "Radioddity"
3634
    MODEL = "QB25"
3635

    
3636

    
3637
# real radios
3638
@directory.register
3639
class UV25X2(BTechColor):
3640
    """Baofeng Tech UV25X2"""
3641
    MODEL = "UV-25X2"
3642
    BANDS = 2
3643
    _vhf_range = (130000000, 180000000)
3644
    _uhf_range = (400000000, 521000000)
3645
    _magic = MSTRING_UV25X2
3646
    _fileid = [UV25X2_fp, ]
3647

    
3648

    
3649
@directory.register
3650
class UV25X4(BTechColor):
3651
    """Baofeng Tech UV25X4"""
3652
    MODEL = "UV-25X4"
3653
    BANDS = 4
3654
    _vhf_range = (130000000, 180000000)
3655
    _220_range = (200000000, 271000000)
3656
    _uhf_range = (400000000, 521000000)
3657
    _350_range = (350000000, 391000000)
3658
    _magic = MSTRING_UV25X4
3659
    _fileid = [UV25X4_fp, ]
3660

    
3661

    
3662
@directory.register
3663
class UV50X2(BTechColor):
3664
    """Baofeng Tech UV50X2"""
3665
    MODEL = "UV-50X2"
3666
    BANDS = 2
3667
    _vhf_range = (130000000, 180000000)
3668
    _uhf_range = (400000000, 521000000)
3669
    _magic = MSTRING_UV25X2
3670
    _fileid = [UV50X2_fp, ]
3671
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
3672
                     chirp_common.PowerLevel("Low", watts=10)]
3673

    
3674

    
3675
@directory.register
3676
class KT7900D(BTechColor):
3677
    """QYT KT7900D"""
3678
    VENDOR = "QYT"
3679
    MODEL = "KT7900D"
3680
    BANDS = 4
3681
    _vhf_range = (136000000, 175000000)
3682
    _220_range = (200000000, 271000000)
3683
    _uhf_range = (400000000, 481000000)
3684
    _350_range = (350000000, 371000000)
3685
    _magic = MSTRING_KT8900D
3686
    _fileid = [KT7900D_fp, KT7900D_fp1, QB25_fp, ]
3687
    # Clones
3688
    ALIASES = [SKT8900D, QB25, ]
3689

    
3690

    
3691
@directory.register
3692
class KT8900D(BTechColor):
3693
    """QYT KT8900D"""
3694
    VENDOR = "QYT"
3695
    MODEL = "KT8900D"
3696
    BANDS = 2
3697
    _vhf_range = (136000000, 175000000)
3698
    _uhf_range = (400000000, 481000000)
3699
    _magic = MSTRING_KT8900D
3700
    _fileid = [KT8900D_fp, KT8900D_fp1]
(2-2/3)