btech_kt8900d_test2.py

same as before with stray double quote removed - Jim Unroe, 02/03/2017 01:52 pm

Download (125.4 kB)

 
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_DTMF_SPEED = ["%s ms" % x for x in range(50, 2010, 10)]
108
LIST_DTMF_DIGITS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B",
109
                    "C", "D", "#", "*"]
110
LIST_DTMF_VALUES = [0x0A, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
111
                    0x0D, 0x0E, 0x0F, 0x00, 0x0C, 0x0B ]
112
LIST_DTMF_SPECIAL_DIGITS = [ "*", "#", "A", "B", "C", "D"]
113
LIST_DTMF_SPECIAL_VALUES = [ 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x00]
114
LIST_DTMF_DELAY = ["%s ms" % x for x in range(100, 4100, 100)]
115
CHARSET_DTMF_DIGITS = "0123456789AaBbCcDd#*"
116
LIST_2TONE_DEC = ["A-B", "A-C", "A-D",
117
                  "B-A", "B-C", "B-D",
118
                  "C-A", "C-B", "C-D",
119
                  "D-A", "D-B", "D-C"]
120
LIST_2TONE_RESPONSE = ["None", "Alert", "Transpond", "Alert+Transpond"]
121

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

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

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

    
134

    
135
##### ID strings #####################################################
136

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

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

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

    
169
# special var to know when we found a BTECH Gen 3
170
BTECH3 = [UV2501G3_fp, UV2501_220G3_fp, UV5001G3_fp]
171

    
172

    
173
# WACCOM Mini-8900
174
MINI8900_fp = "M28854"
175

    
176

    
177
# QYT KT-UV980
178
KTUV980_fp = "H28854"
179

    
180
# QYT KT8900
181
KT8900_fp = "M29154"
182
# New generations KT8900
183
KT8900_fp1 = "M2C234"
184
KT8900_fp2 = "M2G1F4"
185
KT8900_fp3 = "M2G2F4"
186
KT8900_fp4 = "M2G304"
187
KT8900_fp5 = "M2G314"
188
# this radio has an extra ID
189
KT8900_id = "      303688"
190

    
191
# KT8900R
192
KT8900R_fp = "M3G1F4"
193
# Second Generation
194
KT8900R_fp1 = "M3G214"
195
# another model
196
KT8900R_fp2 = "M3C234"
197
# another model G4?
198
KT8900R_fp3 = "M39164"
199
# another model
200
KT8900R_fp4 = "M3G314"
201
# this radio has an extra ID
202
KT8900R_id = "280528"
203
# KT8900D
204
KT8900D_fp = "VC2002"
205

    
206
# LUITON LT-588UV
207
LT588UV_fp = "V2G1F4"
208
# Added by rstrickoff gen 2 id
209
LT588UV_fp1 = "V2G214"
210

    
211

    
212
#### MAGICS
213
# for the Waccom Mini-8900
214
MSTRING_MINI8900 = "\x55\xA5\xB5\x45\x55\x45\x4d\x02"
215
# for the B-TECH UV-2501+220 (including pre production ones)
216
MSTRING_220 = "\x55\x20\x15\x12\x12\x01\x4d\x02"
217
# for the QYT KT8900 & R
218
MSTRING_KT8900 = "\x55\x20\x15\x09\x16\x45\x4D\x02"
219
MSTRING_KT8900R = "\x55\x20\x15\x09\x25\x01\x4D\x02"
220
# magic string for all other models
221
MSTRING = "\x55\x20\x15\x09\x20\x45\x4d\x02"
222
# for the QYT KT8900D
223
MSTRING_KT8900D = "\x55\x20\x16\x08\x01\xFF\xDC\x02"
224

    
225

    
226
def _clean_buffer(radio):
227
    """Cleaning the read serial buffer, hard timeout to survive an infinite
228
    data stream"""
229

    
230
    # touching the serial timeout to optimize the flushing
231
    # restored at the end to the default value
232
    radio.pipe.timeout = 0.1
233
    dump = "1"
234
    datacount = 0
235

    
236
    try:
237
        while len(dump) > 0:
238
            dump = radio.pipe.read(100)
239
            datacount += len(dump)
240
            # hard limit to survive a infinite serial data stream
241
            # 5 times bigger than a normal rx block (69 bytes)
242
            if datacount > 345:
243
                seriale = "Please check your serial port selection."
244
                raise errors.RadioError(seriale)
245

    
246
        # restore the default serial timeout
247
        radio.pipe.timeout = STIMEOUT
248

    
249
    except Exception:
250
        raise errors.RadioError("Unknown error cleaning the serial buffer")
251

    
252

    
253
def _rawrecv(radio, amount):
254
    """Raw read from the radio device, less intensive way"""
255

    
256
    data = ""
257

    
258
    try:
259
        data = radio.pipe.read(amount)
260

    
261
        # DEBUG
262
        if debug is True:
263
            LOG.debug("<== (%d) bytes:\n\n%s" %
264
                      (len(data), util.hexprint(data)))
265

    
266
        # fail if no data is received
267
        if len(data) == 0:
268
            raise errors.RadioError("No data received from radio")
269

    
270
        # notice on the logs if short
271
        if len(data) < amount:
272
            LOG.warn("Short reading %d bytes from the %d requested." %
273
                     (len(data), amount))
274

    
275
    except:
276
        raise errors.RadioError("Error reading data from radio")
277

    
278
    return data
279

    
280

    
281
def _send(radio, data):
282
    """Send data to the radio device"""
283

    
284
    try:
285
        for byte in data:
286
            radio.pipe.write(byte)
287
            # Some OS (mainly Linux ones) are too fast on the serial and
288
            # get the MCU inside the radio stuck in the early stages, this
289
            # hits some models more than others.
290
            #
291
            # To cope with that we introduce a delay on the writes.
292
            # Many option have been tested (delaying only after error occures, 
293
            # after short reads, only for linux, ...)
294
            # Finally, a static delay was chosen as simplest of all solutions
295
            # (Michael Wagner, OE4AMW)
296
            # (for details, see issue 3993)
297
            sleep(0.002)
298

    
299
        # DEBUG
300
        if debug is True:
301
            LOG.debug("==> (%d) bytes:\n\n%s" %
302
                      (len(data), util.hexprint(data)))
303
    except:
304
        raise errors.RadioError("Error sending data to radio")
305

    
306

    
307
def _make_frame(cmd, addr, length, data=""):
308
    """Pack the info in the headder format"""
309
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
310
    # add the data if set
311
    if len(data) != 0:
312
        frame += data
313

    
314
    return frame
315

    
316

    
317
def _recv(radio, addr):
318
    """Get data from the radio all at once to lower syscalls load"""
319

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

    
323
    # get the whole block
324
    block = _rawrecv(radio, BLOCK_SIZE + 5)
325

    
326
    # basic check
327
    if len(block) < (BLOCK_SIZE + 5):
328
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
329

    
330
    # checking for the ack
331
    if block[0] != ACK_CMD:
332
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
333

    
334
    # header validation
335
    c, a, l = struct.unpack(">BHB", block[1:5])
336
    if a != addr or l != BLOCK_SIZE or c != ord("X"):
337
        LOG.debug("Invalid header for block 0x%04x" % addr)
338
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
339
        raise errors.RadioError("Invalid header for block 0x%04x:" % addr)
340

    
341
    # return the data
342
    return block[5:]
343

    
344

    
345
def _start_clone_mode(radio, status):
346
    """Put the radio in clone mode and get the ident string, 3 tries"""
347

    
348
    # cleaning the serial buffer
349
    _clean_buffer(radio)
350

    
351
    # prep the data to show in the UI
352
    status.cur = 0
353
    status.msg = "Identifying the radio..."
354
    status.max = 3
355
    radio.status_fn(status)
356

    
357
    try:
358
        for a in range(0, status.max):
359
            # Update the UI
360
            status.cur = a + 1
361
            radio.status_fn(status)
362

    
363
            # send the magic word
364
            _send(radio, radio._magic)
365

    
366
            # Now you get a x06 of ACK if all goes well
367
            ack = radio.pipe.read(1)
368

    
369
            if ack == "\x06":
370
                # DEBUG
371
                LOG.info("Magic ACK received")
372
                status.cur = status.max
373
                radio.status_fn(status)
374

    
375
                return True
376

    
377
        return False
378

    
379
    except errors.RadioError:
380
        raise
381
    except Exception, e:
382
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
383

    
384

    
385
def _do_ident(radio, status, upload=False):
386
    """Put the radio in PROGRAM mode & identify it"""
387
    #  set the serial discipline
388
    radio.pipe.baudrate = 9600
389
    radio.pipe.parity = "N"
390

    
391
    # open the radio into program mode
392
    if _start_clone_mode(radio, status) is False:
393
        msg = "Radio did not enter clone mode"
394
        # warning about old versions of QYT KT8900
395
        if radio.MODEL == "KT8900":
396
            msg += ". You may want to try it as a WACCOM MINI-8900, there is a"
397
            msg += " known variant of this radios that is a clone of it."
398
        raise errors.RadioError(msg)
399

    
400
    # Ok, get the ident string
401
    ident = _rawrecv(radio, 49)
402

    
403
    # basic check for the ident
404
    if len(ident) != 49:
405
        raise errors.RadioError("Radio send a short ident block.")
406

    
407
    # check if ident is OK
408
    itis = False
409
    for fp in radio._fileid:
410
        if fp in ident:
411
            # got it!
412
            itis = True
413
            # checking if we are dealing with a Gen 3 BTECH
414
            if radio.VENDOR == "BTECH" and fp in BTECH3:
415
                radio.btech3 = True
416

    
417
            break
418

    
419
    if itis is False:
420
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
421
        raise errors.RadioError("Radio identification failed.")
422

    
423
    # some radios needs a extra read and check for a code on it, this ones
424
    # has the check value in the _id2 var, others simply False
425
    if radio._id2 is not False:
426
        # lower the timeout here as this radios are reseting due to timeout
427
        radio.pipe.timeout = 0.05
428

    
429
        # query & receive the extra ID
430
        _send(radio, _make_frame("S", 0x3DF0, 16))
431
        id2 = _rawrecv(radio, 21)
432

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

    
440
        # ok, the correct string must be in the received data
441
        if radio._id2 not in id2:
442
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
443
                      (radio.MODEL, util.hexprint(id2)))
444
            raise errors.RadioError("The extra ID is wrong, aborting.")
445

    
446
        # this radios need a extra request/answer here on the upload
447
        # the amount of data received depends of the radio type
448
        #
449
        # also the first block of TX must no have the ACK at the beginning
450
        # see _upload for this.
451
        if upload is True:
452
            # send an ACK
453
            _send(radio, ACK_CMD)
454

    
455
            # the amount of data depend on the radio, so far we have two radios
456
            # reading two bytes with an ACK at the end and just ONE with just
457
            # one byte (QYT KT8900)
458
            # the JT-6188 appears a clone of the last, but reads TWO bytes.
459
            #
460
            # we will read two bytes with a custom timeout to not penalize the
461
            # users for this.
462
            #
463
            # we just check for a response and last byte being a ACK, that is
464
            # the common stone for all radios (3 so far)
465
            ack = _rawrecv(radio, 2)
466

    
467
            # checking
468
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
469
                raise errors.RadioError("Radio didn't ACK the upload")
470

    
471
            # restore the default serial timeout
472
            radio.pipe.timeout = STIMEOUT
473

    
474
    # DEBUG
475
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
476

    
477
    return True
478

    
479

    
480
def _download(radio):
481
    """Get the memory map"""
482

    
483
    # UI progress
484
    status = chirp_common.Status()
485

    
486
    # put radio in program mode and identify it
487
    _do_ident(radio, status)
488

    
489
    # the models that doesn't have the extra ID have to make a dummy read here
490
    if radio._id2 is False:
491
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
492
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
493

    
494
        if debug is True:
495
            LOG.info("Dummy first block read done, got this:\n\n %s",
496
                     util.hexprint(discard))
497

    
498
    # reset the progress bar in the UI
499
    status.max = MEM_SIZE / BLOCK_SIZE
500
    status.msg = "Cloning from radio..."
501
    status.cur = 0
502
    radio.status_fn(status)
503

    
504
    # cleaning the serial buffer
505
    _clean_buffer(radio)
506

    
507
    data = ""
508
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
509
        # sending the read request
510
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
511

    
512
        # read
513
        d = _recv(radio, addr)
514

    
515
        # aggregate the data
516
        data += d
517

    
518
        # UI Update
519
        status.cur = addr / BLOCK_SIZE
520
        status.msg = "Cloning from radio..."
521
        radio.status_fn(status)
522

    
523
    return data
524

    
525

    
526
def _upload(radio):
527
    """Upload procedure"""
528

    
529
    # The UPLOAD mem is restricted to lower than 0x3100,
530
    # so we will overide that here localy
531
    MEM_SIZE = 0x3100
532

    
533
    # UI progress
534
    status = chirp_common.Status()
535

    
536
    # put radio in program mode and identify it
537
    _do_ident(radio, status, True)
538

    
539
    # get the data to upload to radio
540
    data = radio.get_mmap()
541

    
542
    # Reset the UI progress
543
    status.max = MEM_SIZE / TX_BLOCK_SIZE
544
    status.cur = 0
545
    status.msg = "Cloning to radio..."
546
    radio.status_fn(status)
547

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

    
552
    # cleaning the serial buffer
553
    _clean_buffer(radio)
554

    
555
    # the fun start here
556
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
557
        # getting the block of data to send
558
        d = data[addr:addr + TX_BLOCK_SIZE]
559

    
560
        # build the frame to send
561
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
562

    
563
        # first block must not send the ACK at the beginning for the
564
        # ones that has the extra id, since this have to do a extra step
565
        if addr == 0 and radio._id2 is not False:
566
            frame = frame[1:]
567

    
568
        # send the frame
569
        _send(radio, frame)
570

    
571
        # receiving the response
572
        ack = _rawrecv(radio, 1)
573

    
574
        # basic check
575
        if len(ack) != 1:
576
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
577

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

    
581
         # UI Update
582
        status.cur = addr / TX_BLOCK_SIZE
583
        status.msg = "Cloning to radio..."
584
        radio.status_fn(status)
585

    
586

    
587
def model_match(cls, data):
588
    """Match the opened/downloaded image to the correct version"""
589
    rid = data[0x3f70:0x3f76]
590

    
591
    if rid in cls._fileid:
592
        return True
593

    
594
    return False
595

    
596

    
597
def _decode_ranges(low, high):
598
    """Unpack the data in the ranges zones in the memmap and return
599
    a tuple with the integer corresponding to the Mhz it means"""
600
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
601
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
602
    ilow *= 1000000
603
    ihigh *= 1000000
604

    
605
    return (ilow, ihigh)
606

    
607

    
608
def _split(rf, f1, f2):
609
    """Returns False if the two freqs are in the same band (no split)
610
    or True otherwise"""
611

    
612
    # determine if the two freqs are in the same band
613
    for low, high in rf.valid_bands:
614
        if f1 >= low and f1 <= high and \
615
                f2 >= low and f2 <= high:
616
            # if the two freqs are on the same Band this is not a split
617
            return False
618

    
619
    # if you get here is because the freq pairs are split
620
    return False
621

    
622

    
623
class BTechMobileCommon(chirp_common.CloneModeRadio,
624
                        chirp_common.ExperimentalRadio):
625
    """BTECH's UV-5001 and alike radios"""
626
    VENDOR = "BTECH"
627
    MODEL = ""
628
    IDENT = ""
629
    BANDS = 2
630
    COLOR_LCD = False
631
    NAME_LENGTH = 6
632
    _power_levels = [chirp_common.PowerLevel("High", watts=25),
633
                     chirp_common.PowerLevel("Low", watts=10)]
634
    _vhf_range = (130000000, 180000000)
635
    _220_range = (200000000, 271000000)
636
    _uhf_range = (400000000, 521000000)
637
    _350_range = (350000000, 391000000)
638
    _upper = 199
639
    _magic = MSTRING
640
    _fileid = None
641
    _id2 = False
642
    btech3 = False
643

    
644
    @classmethod
645
    def get_prompts(cls):
646
        rp = chirp_common.RadioPrompts()
647
        rp.experimental = \
648
            ('This driver is experimental.\n'
649
             '\n'
650
             'Please keep a copy of your memories with the original software '
651
             'if you treasure them, this driver is new and may contain'
652
             ' bugs.\n'
653
             '\n'
654
             )
655
        rp.pre_download = _(dedent("""\
656
            Follow these instructions to download your info:
657

    
658
            1 - Turn off your radio
659
            2 - Connect your interface cable
660
            3 - Turn on your radio
661
            4 - Do the download of your radio data
662

    
663
            """))
664
        rp.pre_upload = _(dedent("""\
665
            Follow these instructions to upload your info:
666

    
667
            1 - Turn off your radio
668
            2 - Connect your interface cable
669
            3 - Turn on your radio
670
            4 - Do the upload of your radio data
671

    
672
            """))
673
        return rp
674

    
675
    def get_features(self):
676
        """Get the radio's features"""
677

    
678
        # we will use the following var as global
679
        global POWER_LEVELS
680

    
681
        rf = chirp_common.RadioFeatures()
682
        rf.has_settings = True
683
        rf.has_bank = False
684
        rf.has_tuning_step = False
685
        rf.can_odd_split = True
686
        rf.has_name = True
687
        rf.has_offset = True
688
        rf.has_mode = True
689
        rf.has_dtcs = True
690
        rf.has_rx_dtcs = True
691
        rf.has_dtcs_polarity = True
692
        rf.has_ctone = True
693
        rf.has_cross = True
694
        rf.valid_modes = MODES
695
        rf.valid_characters = VALID_CHARS
696
        rf.valid_name_length = self.NAME_LENGTH
697
        rf.valid_duplexes = ["", "-", "+", "split", "off"]
698
        rf.valid_tmodes = ['', 'Tone', 'TSQL', 'DTCS', 'Cross']
699
        rf.valid_cross_modes = [
700
            "Tone->Tone",
701
            "DTCS->",
702
            "->DTCS",
703
            "Tone->DTCS",
704
            "DTCS->Tone",
705
            "->Tone",
706
            "DTCS->DTCS"]
707
        rf.valid_skips = SKIP_VALUES
708
        rf.valid_dtcs_codes = DTCS
709
        rf.memory_bounds = (0, self._upper)
710

    
711
        # power levels
712
        POWER_LEVELS = self._power_levels
713
        rf.valid_power_levels = POWER_LEVELS
714

    
715
        # normal dual bands
716
        rf.valid_bands = [self._vhf_range, self._uhf_range]
717

    
718
        # 220 band
719
        if self.BANDS == 3 or self.BANDS == 4:
720
            rf.valid_bands.append(self._220_range)
721

    
722
        # 350 band
723
        if self.BANDS == 4:
724
            rf.valid_bands.append(self._350_range)
725

    
726
        return rf
727

    
728
    def sync_in(self):
729
        """Download from radio"""
730
        data = _download(self)
731
        self._mmap = memmap.MemoryMap(data)
732
        self.process_mmap()
733

    
734
    def sync_out(self):
735
        """Upload to radio"""
736
        try:
737
            _upload(self)
738
        except errors.RadioError:
739
            raise
740
        except Exception, e:
741
            raise errors.RadioError("Error: %s" % e)
742

    
743
    def get_raw_memory(self, number):
744
        return repr(self._memobj.memory[number])
745

    
746
    def _decode_tone(self, val):
747
        """Parse the tone data to decode from mem, it returns:
748
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
749
        pol = None
750

    
751
        if val in [0, 65535]:
752
            return '', None, None
753
        elif val > 0x0258:
754
            a = val / 10.0
755
            return 'Tone', a, pol
756
        else:
757
            if val > 0x69:
758
                index = val - 0x6A
759
                pol = "R"
760
            else:
761
                index = val - 1
762
                pol = "N"
763

    
764
            tone = DTCS[index]
765
            return 'DTCS', tone, pol
766

    
767
    def _encode_tone(self, memval, mode, val, pol):
768
        """Parse the tone data to encode from UI to mem"""
769
        if mode == '' or mode is None:
770
            memval.set_raw("\x00\x00")
771
        elif mode == 'Tone':
772
            memval.set_value(val * 10)
773
        elif mode == 'DTCS':
774
            # detect the index in the DTCS list
775
            try:
776
                index = DTCS.index(val)
777
                if pol == "N":
778
                    index += 1
779
                else:
780
                    index += 0x6A
781
                memval.set_value(index)
782
            except:
783
                msg = "Digital Tone '%d' is not supported" % value
784
                LOG.error(msg)
785
                raise errors.RadioError(msg)
786
        else:
787
            msg = "Internal error: invalid mode '%s'" % mode
788
            LOG.error(msg)
789
            raise errors.InvalidDataError(msg)
790

    
791
    def get_memory(self, number):
792
        """Get the mem representation from the radio image"""
793
        _mem = self._memobj.memory[number]
794
        _names = self._memobj.names[number]
795

    
796
        # Create a high-level memory object to return to the UI
797
        mem = chirp_common.Memory()
798

    
799
        # Memory number
800
        mem.number = number
801

    
802
        if _mem.get_raw()[0] == "\xFF":
803
            mem.empty = True
804
            return mem
805

    
806
        # Freq and offset
807
        mem.freq = int(_mem.rxfreq) * 10
808
        # tx freq can be blank
809
        if _mem.get_raw()[4] == "\xFF":
810
            # TX freq not set
811
            mem.offset = 0
812
            mem.duplex = "off"
813
        else:
814
            # TX freq set
815
            offset = (int(_mem.txfreq) * 10) - mem.freq
816
            if offset != 0:
817
                if _split(self.get_features(), mem.freq, int(_mem.txfreq) * 10):
818
                    mem.duplex = "split"
819
                    mem.offset = int(_mem.txfreq) * 10
820
                elif offset < 0:
821
                    mem.offset = abs(offset)
822
                    mem.duplex = "-"
823
                elif offset > 0:
824
                    mem.offset = offset
825
                    mem.duplex = "+"
826
            else:
827
                mem.offset = 0
828

    
829
        # name TAG of the channel
830
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
831

    
832
        # power
833
        mem.power = POWER_LEVELS[int(_mem.power)]
834

    
835
        # wide/narrow
836
        mem.mode = MODES[int(_mem.wide)]
837

    
838
        # skip
839
        mem.skip = SKIP_VALUES[_mem.add]
840

    
841
        # tone data
842
        rxtone = txtone = None
843
        txtone = self._decode_tone(_mem.txtone)
844
        rxtone = self._decode_tone(_mem.rxtone)
845
        chirp_common.split_tone_decode(mem, txtone, rxtone)
846

    
847
        # Extra
848
        mem.extra = RadioSettingGroup("extra", "Extra")
849

    
850
        scramble = RadioSetting("scramble", "Scramble",
851
                                RadioSettingValueBoolean(bool(
852
                                    _mem.scramble)))
853
        mem.extra.append(scramble)
854

    
855
        bcl = RadioSetting("bcl", "Busy channel lockout",
856
                           RadioSettingValueBoolean(bool(_mem.bcl)))
857
        mem.extra.append(bcl)
858

    
859
        pttid = RadioSetting("pttid", "PTT ID",
860
                             RadioSettingValueList(PTTID_LIST,
861
                                                   PTTID_LIST[_mem.pttid]))
862
        mem.extra.append(pttid)
863

    
864
        # validating scode
865
        scode = _mem.scode if _mem.scode != 15 else 0
866
        pttidcode = RadioSetting("scode", "PTT ID signal code",
867
                                 RadioSettingValueList(
868
                                     PTTIDCODE_LIST,
869
                                     PTTIDCODE_LIST[scode]))
870
        mem.extra.append(pttidcode)
871

    
872
        optsig = RadioSetting("optsig", "Optional signaling",
873
                              RadioSettingValueList(
874
                                  OPTSIG_LIST,
875
                                  OPTSIG_LIST[_mem.optsig]))
876
        mem.extra.append(optsig)
877

    
878
        spmute = RadioSetting("spmute", "Speaker mute",
879
                              RadioSettingValueList(
880
                                  SPMUTE_LIST,
881
                                  SPMUTE_LIST[_mem.spmute]))
882
        mem.extra.append(spmute)
883

    
884
        return mem
885

    
886
    def set_memory(self, mem):
887
        """Set the memory data in the eeprom img from the UI"""
888
        # get the eprom representation of this channel
889
        _mem = self._memobj.memory[mem.number]
890
        _names = self._memobj.names[mem.number]
891

    
892
        mem_was_empty = False
893
        # same method as used in get_memory for determining if mem is empty
894
        # doing this BEFORE overwriting it with new values ...
895
        if _mem.get_raw()[0] == "\xFF":
896
            LOG.debug("This mem was empty before")
897
            mem_was_empty = True
898
        
899
        # if empty memmory
900
        if mem.empty:
901
            # the channel itself
902
            _mem.set_raw("\xFF" * 16)
903
            # the name tag
904
            _names.set_raw("\xFF" * 16)
905
            return
906

    
907
        # frequency
908
        _mem.rxfreq = mem.freq / 10
909

    
910
        # duplex
911
        if mem.duplex == "+":
912
            _mem.txfreq = (mem.freq + mem.offset) / 10
913
        elif mem.duplex == "-":
914
            _mem.txfreq = (mem.freq - mem.offset) / 10
915
        elif mem.duplex == "off":
916
            for i in _mem.txfreq:
917
                i.set_raw("\xFF")
918
        elif mem.duplex == "split":
919
            _mem.txfreq = mem.offset / 10
920
        else:
921
            _mem.txfreq = mem.freq / 10
922

    
923
        # tone data
924
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
925
            chirp_common.split_tone_encode(mem)
926
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
927
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
928

    
929
        # name TAG of the channel
930
        if len(mem.name) < self.NAME_LENGTH:
931
            # we must pad to self.NAME_LENGTH chars, " " = "\xFF"
932
            mem.name = str(mem.name).ljust(self.NAME_LENGTH, " ")
933
        _names.name = str(mem.name).replace(" ", "\xFF")
934

    
935
        # power, # default power level is high
936
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
937

    
938
        # wide/narrow
939
        _mem.wide = MODES.index(mem.mode)
940

    
941
        # scan add property
942
        _mem.add = SKIP_VALUES.index(mem.skip)
943

    
944
        # reseting unknowns, this have to be set by hand
945
        _mem.unknown0 = 0
946
        _mem.unknown1 = 0
947
        _mem.unknown2 = 0
948
        _mem.unknown3 = 0
949
        _mem.unknown4 = 0
950
        _mem.unknown5 = 0
951
        _mem.unknown6 = 0
952

    
953
        # extra settings
954
        if len(mem.extra) > 0:
955
            # there are setting, parse
956
            LOG.debug("Extra-Setting supplied. Setting them.")
957
            for setting in mem.extra:
958
                setattr(_mem, setting.get_name(), setting.value)
959
        else:
960
            if mem.empty:
961
                LOG.debug("New mem is empty.")
962
            else:
963
                LOG.debug("New mem is NOT empty")
964
                # set extra-settings to default ONLY when apreviously empty or
965
                # deleted memory was edited to prevent errors such as #4121
966
                if mem_was_empty :
967
                    LOG.debug("old mem was empty. Setting default for extras.")
968
                    _mem.spmute = 0
969
                    _mem.optsig = 0
970
                    _mem.scramble = 0
971
                    _mem.bcl = 0
972
                    _mem.pttid = 0
973
                    _mem.scode = 0
974

    
975
        return mem
976

    
977
    def get_settings(self):
978
        """Translate the bit in the mem_struct into settings in the UI"""
979
        _mem = self._memobj
980
        basic = RadioSettingGroup("basic", "Basic Settings")
981
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
982
        other = RadioSettingGroup("other", "Other Settings")
983
        work = RadioSettingGroup("work", "Work Mode Settings")
984
        top = RadioSettings(basic, advanced, other, work)
985

    
986
        # Basic
987
        if self.COLOR_LCD:
988
            tmr = RadioSetting("settings.tmr", "Transceiver multi-receive",
989
                               RadioSettingValueList(
990
                                   LIST_TMR,
991
                                   LIST_TMR[_mem.settings.tmr]))
992
            basic.append(tmr)
993
        else:
994
            tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
995
                               RadioSettingValueBoolean(_mem.settings.tdr))
996
            basic.append(tdr)
997

    
998
        sql = RadioSetting("settings.sql", "Squelch level",
999
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1000
        basic.append(sql)
1001

    
1002
        tot = RadioSetting("settings.tot", "Time out timer",
1003
                           RadioSettingValueList(
1004
                               LIST_TOT,
1005
                               LIST_TOT[_mem.settings.tot]))
1006
        basic.append(tot)
1007

    
1008
        if self.VENDOR == "BTECH" or self.COLOR_LCD:
1009
            apo = RadioSetting("settings.apo", "Auto power off timer",
1010
                               RadioSettingValueList(
1011
                                   LIST_APO,
1012
                                   LIST_APO[_mem.settings.apo]))
1013
            basic.append(apo)
1014
        else:
1015
            toa = RadioSetting("settings.apo", "Time out alert timer",
1016
                               RadioSettingValueList(
1017
                                   LIST_OFF1TO10, 
1018
                                   LIST_OFF1TO10[_mem.settings.apo]))
1019
            basic.append(toa)
1020

    
1021
        abr = RadioSetting("settings.abr", "Backlight timer",
1022
                           RadioSettingValueList(
1023
                               LIST_OFF1TO50,
1024
                               LIST_OFF1TO50[_mem.settings.abr]))
1025
        basic.append(abr)
1026

    
1027
        beep = RadioSetting("settings.beep", "Key beep",
1028
                            RadioSettingValueBoolean(_mem.settings.beep))
1029
        basic.append(beep)
1030

    
1031
        dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1032
                              RadioSettingValueList(
1033
                                  LIST_DTMFST,
1034
                                  LIST_DTMFST[_mem.settings.dtmfst]))
1035
        basic.append(dtmfst)
1036

    
1037
        if not self.COLOR_LCD:
1038
            prisc = RadioSetting("settings.prisc", "Priority scan",
1039
                                 RadioSettingValueBoolean(
1040
                                     _mem.settings.prisc))
1041
            basic.append(prisc)
1042

    
1043
            prich = RadioSetting("settings.prich", "Priority channel",
1044
                                 RadioSettingValueInteger(0, 199,
1045
                                     _mem.settings.prich))
1046
            basic.append(prich)
1047

    
1048
        screv = RadioSetting("settings.screv", "Scan resume method",
1049
                             RadioSettingValueList(
1050
                                 LIST_SCREV,
1051
                                 LIST_SCREV[_mem.settings.screv]))
1052
        basic.append(screv)
1053

    
1054
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1055
                             RadioSettingValueInteger(0, 30,
1056
                                 _mem.settings.pttlt))
1057
        basic.append(pttlt)
1058

    
1059
        emctp = RadioSetting("settings.emctp", "Alarm mode",
1060
                             RadioSettingValueList(
1061
                                 LIST_EMCTP,
1062
                                 LIST_EMCTP[_mem.settings.emctp]))
1063
        basic.append(emctp)
1064

    
1065
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1066
                             RadioSettingValueInteger(0, 199,
1067
                                 _mem.settings.emcch))
1068
        basic.append(emcch)
1069

    
1070
        ringt = RadioSetting("settings.ringt", "Ring time",
1071
                             RadioSettingValueList(
1072
                                 LIST_OFF1TO9,
1073
                                 LIST_OFF1TO9[_mem.settings.ringt]))
1074
        basic.append(ringt)
1075

    
1076
        camdf = RadioSetting("settings.camdf", "Display mode A",
1077
                             RadioSettingValueList(
1078
                                 LIST_MDF,
1079
                                 LIST_MDF[_mem.settings.camdf]))
1080
        basic.append(camdf)
1081

    
1082
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1083
                             RadioSettingValueList(
1084
                                 LIST_MDF,
1085
                                 LIST_MDF[_mem.settings.cbmdf]))
1086
        basic.append(cbmdf)
1087

    
1088
        if self.COLOR_LCD:
1089
            ccmdf = RadioSetting("settings.ccmdf", "Display mode C",
1090
                                 RadioSettingValueList(
1091
                                     LIST_MDF,
1092
                                     LIST_MDF[_mem.settings.ccmdf]))
1093
            basic.append(ccmdf)
1094

    
1095
            cdmdf = RadioSetting("settings.cdmdf", "Display mode D",
1096
                                 RadioSettingValueList(
1097
                                     LIST_MDF,
1098
                                     LIST_MDF[_mem.settings.cdmdf]))
1099
            basic.append(cdmdf)
1100

    
1101
            langua = RadioSetting("settings.langua", "Language",
1102
                                  RadioSettingValueList(
1103
                                      LIST_LANGUA,
1104
                                      LIST_LANGUA[_mem.settings.langua]))
1105
            basic.append(langua)
1106

    
1107
        if self.VENDOR == "BTECH":
1108
            sync = RadioSetting("settings.sync", "A/B channel sync",
1109
                                RadioSettingValueBoolean(
1110
                                    _mem.settings.sync))
1111
            basic.append(sync)
1112
        else:
1113
            autolk = RadioSetting("settings.sync", "Auto keylock",
1114
                                  RadioSettingValueBoolean(
1115
                                      _mem.settings.sync))
1116
            basic.append(autolk)
1117

    
1118
        if not self.COLOR_LCD:
1119
            ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1120
                                  RadioSettingValueList(
1121
                                      LIST_PONMSG,
1122
                                      LIST_PONMSG[_mem.settings.ponmsg]))
1123
            basic.append(ponmsg)
1124

    
1125
        if self.COLOR_LCD:
1126
            mainfc = RadioSetting("settings.mainfc", 
1127
                                  "Main LCD foreground color",
1128
                                      RadioSettingValueList(
1129
                                          LIST_COLOR8,
1130
                                          LIST_COLOR8[_mem.settings.mainfc]))
1131
            basic.append(mainfc)
1132

    
1133
            mainbc = RadioSetting("settings.mainbc",
1134
                                  "Main LCD background color",
1135
                                      RadioSettingValueList(
1136
                                          LIST_COLOR8,
1137
                                          LIST_COLOR8[_mem.settings.mainbc]))
1138
            basic.append(mainbc)
1139

    
1140
            menufc = RadioSetting("settings.menufc", "Menu foreground color",
1141
                                  RadioSettingValueList(
1142
                                      LIST_COLOR8,
1143
                                      LIST_COLOR8[_mem.settings.menufc]))
1144
            basic.append(menufc)
1145

    
1146
            menubc = RadioSetting("settings.menubc", "Menu background color",
1147
                                  RadioSettingValueList(
1148
                                      LIST_COLOR8,
1149
                                      LIST_COLOR8[_mem.settings.menubc]))
1150
            basic.append(menubc)
1151

    
1152
            stafc = RadioSetting("settings.stafc",
1153
                                 "Top status foreground color",
1154
                                     RadioSettingValueList(
1155
                                         LIST_COLOR8,
1156
                                         LIST_COLOR8[_mem.settings.stafc]))
1157
            basic.append(stafc)
1158

    
1159
            stabc = RadioSetting("settings.stabc",
1160
                                 "Top status background color",
1161
                                     RadioSettingValueList(
1162
                                         LIST_COLOR8,
1163
                                         LIST_COLOR8[_mem.settings.stabc]))
1164
            basic.append(stabc)
1165

    
1166
            sigfc = RadioSetting("settings.sigfc",
1167
                                 "Bottom status foreground color",
1168
                                     RadioSettingValueList(
1169
                                         LIST_COLOR8,
1170
                                         LIST_COLOR8[_mem.settings.sigfc]))
1171
            basic.append(sigfc)
1172

    
1173
            sigbc = RadioSetting("settings.sigbc",
1174
                                 "Bottom status background color",
1175
                                     RadioSettingValueList(
1176
                                         LIST_COLOR8,
1177
                                         LIST_COLOR8[_mem.settings.sigbc]))
1178
            basic.append(sigbc)
1179

    
1180
            rxfc = RadioSetting("settings.rxfc", "Receiving character color",
1181
                                RadioSettingValueList(
1182
                                    LIST_COLOR8,
1183
                                    LIST_COLOR8[_mem.settings.rxfc]))
1184
            basic.append(rxfc)
1185

    
1186
            txfc = RadioSetting("settings.txfc",
1187
                                "Transmitting character color",
1188
                                    RadioSettingValueList(
1189
                                        LIST_COLOR8,
1190
                                        LIST_COLOR8[_mem.settings.txfc]))
1191
            basic.append(txfc)
1192

    
1193
            txdisp = RadioSetting("settings.txdisp",
1194
                                  "Transmitting status display",
1195
                                      RadioSettingValueList(
1196
                                          LIST_TXDISP,
1197
                                          LIST_TXDISP[_mem.settings.txdisp]))
1198
            basic.append(txdisp)
1199
        else:
1200
            wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1201
                                 RadioSettingValueList(
1202
                                     LIST_COLOR4,
1203
                                     LIST_COLOR4[_mem.settings.wtled]))
1204
            basic.append(wtled)
1205

    
1206
            rxled = RadioSetting("settings.rxled", "RX backlight Color",
1207
                                 RadioSettingValueList(
1208
                                     LIST_COLOR4,
1209
                                     LIST_COLOR4[_mem.settings.rxled]))
1210
            basic.append(rxled)
1211

    
1212
            txled = RadioSetting("settings.txled", "TX backlight Color",
1213
                                 RadioSettingValueList(
1214
                                     LIST_COLOR4,
1215
                                     LIST_COLOR4[_mem.settings.txled]))
1216
            basic.append(txled)
1217

    
1218
        anil = RadioSetting("settings.anil", "ANI length",
1219
                            RadioSettingValueList(
1220
                                LIST_ANIL,
1221
                                LIST_ANIL[_mem.settings.anil]))
1222
        basic.append(anil)
1223

    
1224
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1225
                            RadioSettingValueList(
1226
                                LIST_REPS,
1227
                                LIST_REPS[_mem.settings.reps]))
1228
        basic.append(reps)
1229

    
1230
        repm = RadioSetting("settings.repm", "Relay condition",
1231
                            RadioSettingValueList(
1232
                                LIST_REPM,
1233
                                LIST_REPM[_mem.settings.repm]))
1234
        basic.append(repm)
1235

    
1236
        if self.VENDOR == "BTECH" or self.COLOR_LCD:
1237
            if self.COLOR_LCD:
1238
                tmrmr = RadioSetting("settings.tmrmr", "TMR return time",
1239
                                     RadioSettingValueList(
1240
                                         LIST_OFF1TO50,
1241
                                         LIST_OFF1TO50[_mem.settings.tmrmr]))
1242
                basic.append(tmrmr)
1243
            else:
1244
                tdrab = RadioSetting("settings.tdrab", "TDR return time",
1245
                                     RadioSettingValueList(
1246
                                         LIST_OFF1TO50, 
1247
                                         LIST_OFF1TO50[_mem.settings.tdrab]))
1248
                basic.append(tdrab)
1249

    
1250
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1251
                               RadioSettingValueBoolean(_mem.settings.ste))
1252
            basic.append(ste)
1253

    
1254
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1255
                                 RadioSettingValueList(
1256
                                     LIST_OFF1TO9,
1257
                                     LIST_OFF1TO9[_mem.settings.rpste]))
1258
            basic.append(rpste)
1259

    
1260
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1261
                                 RadioSettingValueList(
1262
                                     LIST_RPTDL,
1263
                                     LIST_RPTDL[_mem.settings.rptdl]))
1264
            basic.append(rptdl)
1265

    
1266
        if str(_mem.fingerprint.fp) in BTECH3:
1267
            mgain = RadioSetting("settings.mgain", "Mic gain",
1268
                                 RadioSettingValueInteger(0, 120,
1269
                                     _mem.settings.mgain))
1270
            basic.append(mgain)
1271

    
1272
        if str(_mem.fingerprint.fp) in BTECH3 or self.COLOR_LCD:
1273
            dtmfg = RadioSetting("settings.dtmfg", "DTMF gain",
1274
                                 RadioSettingValueInteger(0, 60,
1275
                                     _mem.settings.dtmfg))
1276
            basic.append(dtmfg)
1277

    
1278
        # Advanced
1279
        def _filter(name):
1280
            filtered = ""
1281
            for char in str(name):
1282
                if char in VALID_CHARS:
1283
                    filtered += char
1284
                else:
1285
                    filtered += " "
1286
            return filtered
1287

    
1288
        _msg = self._memobj.poweron_msg
1289
        if self.COLOR_LCD:
1290
            line1 = RadioSetting("poweron_msg.line1",
1291
                                 "Power-on message line 1",
1292
                                     RadioSettingValueString(0, 8, _filter(
1293
                                         _msg.line1)))
1294
            advanced.append(line1)
1295
            line2 = RadioSetting("poweron_msg.line2",
1296
                                 "Power-on message line 2",
1297
                                     RadioSettingValueString(0, 8, _filter(
1298
                                         _msg.line2)))
1299
            advanced.append(line2)
1300
            line3 = RadioSetting("poweron_msg.line3",
1301
                                 "Power-on message line 3",
1302
                                     RadioSettingValueString(0, 8, _filter(
1303
                                         _msg.line3)))
1304
            advanced.append(line3)
1305
            line4 = RadioSetting("poweron_msg.line4",
1306
                                 "Power-on message line 4",
1307
                                     RadioSettingValueString(0, 8, _filter(
1308
                                         _msg.line4)))
1309
            advanced.append(line4)
1310
            line5 = RadioSetting("poweron_msg.line5",
1311
                                 "Power-on message line 5",
1312
                                     RadioSettingValueString(0, 8, _filter(
1313
                                         _msg.line5)))
1314
            advanced.append(line5)
1315
            line6 = RadioSetting("poweron_msg.line6",
1316
                                 "Power-on message line 6",
1317
                                     RadioSettingValueString(0, 8, _filter(
1318
                                         _msg.line6)))
1319
            advanced.append(line6)
1320
            line7 = RadioSetting("poweron_msg.line7",
1321
                                 "Power-on message line 7",
1322
                                     RadioSettingValueString(0, 8, _filter(
1323
                                         _msg.line7)))
1324
            advanced.append(line7)
1325
            line8 = RadioSetting("poweron_msg.line8", "Static message",
1326
                                 RadioSettingValueString(0, 8, _filter(
1327
                                     _msg.line8)))
1328
            advanced.append(line8)
1329
        else:
1330
            line1 = RadioSetting("poweron_msg.line1",
1331
                                 "Power-on message line 1",
1332
                                     RadioSettingValueString(0, 6, _filter(
1333
                                         _msg.line1)))
1334
            advanced.append(line1)
1335
            line2 = RadioSetting("poweron_msg.line2",
1336
                                 "Power-on message line 2",
1337
                                     RadioSettingValueString(0, 6, _filter(
1338
                                         _msg.line2)))
1339
            advanced.append(line2)
1340

    
1341
        if self.MODEL in ("UV-2501", "UV-5001"):
1342
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1343
                                   RadioSettingValueBoolean(
1344
                                       _mem.settings2.vfomren))
1345
            advanced.append(vfomren)
1346

    
1347
            reseten = RadioSetting("settings2.reseten", "RESET",
1348
                                   RadioSettingValueBoolean(
1349
                                       _mem.settings2.reseten))
1350
            advanced.append(reseten)
1351

    
1352
            menuen = RadioSetting("settings2.menuen", "Menu",
1353
                                  RadioSettingValueBoolean(
1354
                                      _mem.settings2.menuen))
1355
            advanced.append(menuen)
1356

    
1357
        # Other
1358
        def convert_bytes_to_limit(bytes):
1359
            limit = ""
1360
            for byte in bytes:
1361
                if byte < 10:
1362
                    limit += chr(byte + 0x30)
1363
                else:
1364
                    break
1365
            return limit
1366

    
1367
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1368
            _ranges = self._memobj.ranges220
1369
            ranges = "ranges220"
1370
        else:
1371
            _ranges = self._memobj.ranges
1372
            ranges = "ranges"
1373

    
1374
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1375
        val = RadioSettingValueString(0, 3, _limit)
1376
        val.set_mutable(False)
1377
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1378
        other.append(vhf_low)
1379

    
1380
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1381
        val = RadioSettingValueString(0, 3, _limit)
1382
        val.set_mutable(False)
1383
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1384
        other.append(vhf_high)
1385

    
1386
        if self.BANDS == 3 or self.BANDS == 4:
1387
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1388
            val = RadioSettingValueString(0, 3, _limit)
1389
            val.set_mutable(False)
1390
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1391
            other.append(vhf2_low)
1392

    
1393
            _limit = convert_bytes_to_limit(_ranges.vhf2_high)
1394
            val = RadioSettingValueString(0, 3, _limit)
1395
            val.set_mutable(False)
1396
            vhf2_high = RadioSetting("%s.vhf2_high" % ranges, "VHF2 high", val)
1397
            other.append(vhf2_high)
1398

    
1399
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1400
        val = RadioSettingValueString(0, 3, _limit)
1401
        val.set_mutable(False)
1402
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1403
        other.append(uhf_low)
1404

    
1405
        _limit = convert_bytes_to_limit(_ranges.uhf_high)
1406
        val = RadioSettingValueString(0, 3, _limit)
1407
        val.set_mutable(False)
1408
        uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
1409
        other.append(uhf_high)
1410

    
1411
        if self.BANDS == 4:
1412
            _limit = convert_bytes_to_limit(_ranges.uhf2_low)
1413
            val = RadioSettingValueString(0, 3, _limit)
1414
            val.set_mutable(False)
1415
            uhf2_low = RadioSetting("%s.uhf2_low" % ranges, "UHF2 low", val)
1416
            other.append(uhf2_low)
1417

    
1418
            _limit = convert_bytes_to_limit(_ranges.uhf2_high)
1419
            val = RadioSettingValueString(0, 3, _limit)
1420
            val.set_mutable(False)
1421
            uhf2_high = RadioSetting("%s.uhf2_high" % ranges, "UHF2 high", val)
1422
            other.append(uhf2_high)
1423

    
1424
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1425
        val.set_mutable(False)
1426
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1427
        other.append(fp)
1428

    
1429

    
1430
        # Work
1431
        if self.COLOR_LCD:
1432
            dispab = RadioSetting("settings2.dispab", "Display",
1433
                                  RadioSettingValueList(
1434
                                      LIST_ABCD,
1435
                                      LIST_ABCD[_mem.settings2.dispab]))
1436
            work.append(dispab)
1437
        else:
1438
            dispab = RadioSetting("settings2.dispab", "Display",
1439
                                  RadioSettingValueList(
1440
                                      LIST_AB,
1441
                                      LIST_AB[_mem.settings2.dispab]))
1442
            work.append(dispab)
1443

    
1444
        if self.COLOR_LCD:
1445
            vfomra = RadioSetting("settings2.vfomra", "VFO/MR A mode",
1446
                                  RadioSettingValueList(
1447
                                      LIST_VFOMR,
1448
                                      LIST_VFOMR[_mem.settings2.vfomra]))
1449
            work.append(vfomra)
1450

    
1451
            vfomrb = RadioSetting("settings2.vfomrb", "VFO/MR B mode",
1452
                                  RadioSettingValueList(
1453
                                      LIST_VFOMR,
1454
                                      LIST_VFOMR[_mem.settings2.vfomrb]))
1455
            work.append(vfomrb)
1456

    
1457
            vfomrc = RadioSetting("settings2.vfomrc", "VFO/MR C mode",
1458
                                  RadioSettingValueList(
1459
                                      LIST_VFOMR,
1460
                                      LIST_VFOMR[_mem.settings2.vfomrc]))
1461
            work.append(vfomrc)
1462

    
1463
            vfomrd = RadioSetting("settings2.vfomrd", "VFO/MR D mode",
1464
                                  RadioSettingValueList(
1465
                                      LIST_VFOMR,
1466
                                      LIST_VFOMR[_mem.settings2.vfomrd]))
1467
            work.append(vfomrd)
1468
        else:
1469
            vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1470
                                 RadioSettingValueList(
1471
                                     LIST_VFOMR,
1472
                                     LIST_VFOMR[_mem.settings2.vfomr]))
1473
            work.append(vfomr)
1474

    
1475

    
1476
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1477
                           RadioSettingValueBoolean(_mem.settings2.keylock))
1478
        work.append(keylock)
1479

    
1480
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1481
                             RadioSettingValueInteger(0, 199,
1482
                                 _mem.settings2.mrcha))
1483
        work.append(mrcha)
1484

    
1485
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1486
                             RadioSettingValueInteger(0, 199,
1487
                                 _mem.settings2.mrchb))
1488
        work.append(mrchb)
1489

    
1490
        if self.COLOR_LCD:
1491
            mrchc = RadioSetting("settings2.mrchc", "MR C channel",
1492
                                 RadioSettingValueInteger(0, 199,
1493
                                     _mem.settings2.mrchc))
1494
            work.append(mrchc)
1495

    
1496
            mrchd = RadioSetting("settings2.mrchd", "MR D channel",
1497
                                 RadioSettingValueInteger(0, 199,
1498
                                     _mem.settings2.mrchd))
1499
            work.append(mrchd)
1500

    
1501
        def convert_bytes_to_freq(bytes):
1502
            real_freq = 0
1503
            for byte in bytes:
1504
                real_freq = (real_freq * 10) + byte
1505
            return chirp_common.format_freq(real_freq * 10)
1506

    
1507
        def my_validate(value):
1508
            _vhf_lower = int(convert_bytes_to_limit(_ranges.vhf_low))
1509
            _vhf_upper = int(convert_bytes_to_limit(_ranges.vhf_high))
1510
            _uhf_lower = int(convert_bytes_to_limit(_ranges.uhf_low))
1511
            _uhf_upper = int(convert_bytes_to_limit(_ranges.uhf_high))
1512
            if self.BANDS == 3 or self.BANDS == 4:
1513
                _vhf2_lower = int(convert_bytes_to_limit(_ranges.vhf2_low))
1514
                _vhf2_upper = int(convert_bytes_to_limit(_ranges.vhf2_high))
1515
            if self.BANDS == 4:
1516
                _uhf2_lower = int(convert_bytes_to_limit(_ranges.uhf2_low))
1517
                _uhf2_upper = int(convert_bytes_to_limit(_ranges.uhf2_high))
1518

    
1519
            value = chirp_common.parse_freq(value)
1520
            msg = ("Can't be less then %i.0000")
1521
            if value > 99000000 and value < _vhf_lower * 1000000:
1522
                raise InvalidValueError(msg % (_vhf_lower))
1523
            msg = ("Can't be betweeb %i.9975-%i.0000")
1524
            if self.BANDS == 2:
1525
                if (_vhf_upper + 1) * 1000000 <= value and \
1526
                    value < _uhf_lower * 1000000:
1527
                    raise InvalidValueError(msg % (_vhf_upper, _uhf_lower))
1528
            if self.BANDS == 3:
1529
                if (_vhf_upper + 1) * 1000000 <= value and \
1530
                    value < _vhf2_lower * 1000000:
1531
                    raise InvalidValueError(msg % (_vhf_upper, _vhf2_lower))
1532
                if (_vhf2_upper + 1) * 1000000 <= value and \
1533
                    value < _uhf_lower * 1000000:
1534
                    raise InvalidValueError(msg % (_vhf2_upper, _uhf_lower))
1535
            if self.BANDS == 4:
1536
                if (_vhf_upper + 1) * 1000000 <= value and \
1537
                    value < _vhf2_lower * 1000000:
1538
                    raise InvalidValueError(msg % (_vhf_upper, _vhf2_lower))
1539
                if (_vhf2_upper + 1) * 1000000 <= value and \
1540
                    value < _uhf2_lower * 1000000:
1541
                    raise InvalidValueError(msg % (_vhf2_upper, _uhf2_lower))
1542
                if (_uhf2_upper + 1) * 1000000 <= value and \
1543
                    value < _uhf_lower * 1000000:
1544
                    raise InvalidValueError(msg % (_uhf2_upper, _uhf_lower))
1545
            msg = ("Can't be greater then %i.9975")
1546
            if value > 99000000 and value >= _uhf_upper * 1000000:
1547
                raise InvalidValueError(msg % (_uhf_upper))
1548
            return chirp_common.format_freq(value)
1549

    
1550
        def apply_freq(setting, obj):
1551
            value = chirp_common.parse_freq(str(setting.value)) / 10
1552
            for i in range(7, -1, -1):
1553
                obj.freq[i] = value % 10
1554
                value /= 10
1555

    
1556
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1557
                                        _mem.vfo.a.freq))
1558
        val1a.set_validate_callback(my_validate)
1559
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1560
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1561
        work.append(vfoafreq)
1562

    
1563
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1564
                                        _mem.vfo.b.freq))
1565
        val1b.set_validate_callback(my_validate)
1566
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1567
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1568
        work.append(vfobfreq)
1569

    
1570
        if self.COLOR_LCD:
1571
            val1c = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1572
                                            _mem.vfo.c.freq))
1573
            val1c.set_validate_callback(my_validate)
1574
            vfocfreq = RadioSetting("vfo.c.freq", "VFO C frequency", val1c)
1575
            vfocfreq.set_apply_callback(apply_freq, _mem.vfo.c)
1576
            work.append(vfocfreq)
1577

    
1578
            val1d = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1579
                                            _mem.vfo.d.freq))
1580
            val1d.set_validate_callback(my_validate)
1581
            vfodfreq = RadioSetting("vfo.d.freq", "VFO D frequency", val1d)
1582
            vfodfreq.set_apply_callback(apply_freq, _mem.vfo.d)
1583
            work.append(vfodfreq)
1584

    
1585
        vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1586
                                  RadioSettingValueList(
1587
                                      LIST_SHIFT,
1588
                                      LIST_SHIFT[_mem.vfo.a.shiftd]))
1589
        work.append(vfoashiftd)
1590

    
1591
        vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1592
                                  RadioSettingValueList(
1593
                                      LIST_SHIFT,
1594
                                      LIST_SHIFT[_mem.vfo.b.shiftd]))
1595
        work.append(vfobshiftd)
1596

    
1597
        if self.COLOR_LCD:
1598
            vfocshiftd = RadioSetting("vfo.c.shiftd", "VFO C shift",
1599
                                      RadioSettingValueList(
1600
                                          LIST_SHIFT,
1601
                                          LIST_SHIFT[_mem.vfo.c.shiftd]))
1602
            work.append(vfocshiftd)
1603

    
1604
            vfodshiftd = RadioSetting("vfo.d.shiftd", "VFO D shift",
1605
                                      RadioSettingValueList(
1606
                                          LIST_SHIFT,
1607
                                          LIST_SHIFT[_mem.vfo.d.shiftd]))
1608
            work.append(vfodshiftd)
1609

    
1610
        def convert_bytes_to_offset(bytes):
1611
            real_offset = 0
1612
            for byte in bytes:
1613
                real_offset = (real_offset * 10) + byte
1614
            return chirp_common.format_freq(real_offset * 1000)
1615

    
1616
        def apply_offset(setting, obj):
1617
            value = chirp_common.parse_freq(str(setting.value)) / 1000
1618
            for i in range(5, -1, -1):
1619
                obj.offset[i] = value % 10
1620
                value /= 10
1621

    
1622
        if self.COLOR_LCD:
1623
            val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1624
                                            _mem.vfo.a.offset))
1625
            vfoaoffset = RadioSetting("vfo.a.offset",
1626
                                      "VFO A offset (0.000-999.999)", val1a)
1627
            vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1628
            work.append(vfoaoffset)
1629

    
1630
            val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1631
                                            _mem.vfo.b.offset))
1632
            vfoboffset = RadioSetting("vfo.b.offset",
1633
                                      "VFO B offset (0.000-999.999)", val1b)
1634
            vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1635
            work.append(vfoboffset)
1636

    
1637
            val1c = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1638
                                            _mem.vfo.c.offset))
1639
            vfocoffset = RadioSetting("vfo.c.offset",
1640
                                      "VFO C offset (0.000-999.999)", val1c)
1641
            vfocoffset.set_apply_callback(apply_offset, _mem.vfo.c)
1642
            work.append(vfocoffset)
1643

    
1644
            val1d = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1645
                                            _mem.vfo.d.offset))
1646
            vfodoffset = RadioSetting("vfo.d.offset",
1647
                                      "VFO D offset (0.000-999.999)", val1d)
1648
            vfodoffset.set_apply_callback(apply_offset, _mem.vfo.d)
1649
            work.append(vfodoffset)
1650
        else:
1651
            val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1652
                                            _mem.vfo.a.offset))
1653
            vfoaoffset = RadioSetting("vfo.a.offset",
1654
                                      "VFO A offset (0.000-99.999)", val1a)
1655
            vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1656
            work.append(vfoaoffset)
1657

    
1658
            val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1659
                                            _mem.vfo.b.offset))
1660
            vfoboffset = RadioSetting("vfo.b.offset",
1661
                                      "VFO B offset (0.000-99.999)", val1b)
1662
            vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1663
            work.append(vfoboffset)
1664

    
1665

    
1666
        vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1667
                               RadioSettingValueList(
1668
                                   LIST_TXP,
1669
                                   LIST_TXP[_mem.vfo.a.power]))
1670
        work.append(vfoatxp)
1671

    
1672
        vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1673
                               RadioSettingValueList(
1674
                                   LIST_TXP,
1675
                                   LIST_TXP[_mem.vfo.b.power]))
1676
        work.append(vfobtxp)
1677

    
1678
        if self.COLOR_LCD:
1679
            vfoctxp = RadioSetting("vfo.c.power", "VFO C power",
1680
                                   RadioSettingValueList(
1681
                                       LIST_TXP,
1682
                                       LIST_TXP[_mem.vfo.c.power]))
1683
            work.append(vfoctxp)
1684

    
1685
            vfodtxp = RadioSetting("vfo.d.power", "VFO D power",
1686
                                   RadioSettingValueList(
1687
                                       LIST_TXP,
1688
                                       LIST_TXP[_mem.vfo.d.power]))
1689
            work.append(vfodtxp)
1690

    
1691
        vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1692
                                RadioSettingValueList(
1693
                                    LIST_WIDE,
1694
                                    LIST_WIDE[_mem.vfo.a.wide]))
1695
        work.append(vfoawide)
1696

    
1697
        vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1698
                                RadioSettingValueList(
1699
                                    LIST_WIDE,
1700
                                    LIST_WIDE[_mem.vfo.b.wide]))
1701
        work.append(vfobwide)
1702

    
1703
        if self.COLOR_LCD:
1704
            vfocwide = RadioSetting("vfo.c.wide", "VFO C bandwidth",
1705
                                    RadioSettingValueList(
1706
                                        LIST_WIDE,
1707
                                        LIST_WIDE[_mem.vfo.c.wide]))
1708
            work.append(vfocwide)
1709

    
1710
            vfodwide = RadioSetting("vfo.d.wide", "VFO D bandwidth",
1711
                                    RadioSettingValueList(
1712
                                        LIST_WIDE,
1713
                                        LIST_WIDE[_mem.vfo.d.wide]))
1714
            work.append(vfodwide)
1715

    
1716
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
1717
                                RadioSettingValueList(
1718
                                    LIST_STEP,
1719
                                    LIST_STEP[_mem.vfo.a.step]))
1720
        work.append(vfoastep)
1721

    
1722
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
1723
                                RadioSettingValueList(
1724
                                    LIST_STEP,
1725
                                    LIST_STEP[_mem.vfo.b.step]))
1726
        work.append(vfobstep)
1727

    
1728
        if self.COLOR_LCD:
1729
            vfocstep = RadioSetting("vfo.c.step", "VFO C step",
1730
                                    RadioSettingValueList(
1731
                                        LIST_STEP,
1732
                                        LIST_STEP[_mem.vfo.c.step]))
1733
            work.append(vfocstep)
1734

    
1735
            vfodstep = RadioSetting("vfo.d.step", "VFO D step",
1736
                                    RadioSettingValueList(
1737
                                        LIST_STEP,
1738
                                        LIST_STEP[_mem.vfo.d.step]))
1739
            work.append(vfodstep)
1740

    
1741
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
1742
                                  RadioSettingValueList(
1743
                                      OPTSIG_LIST,
1744
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
1745
        work.append(vfoaoptsig)
1746

    
1747
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
1748
                                  RadioSettingValueList(
1749
                                      OPTSIG_LIST,
1750
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
1751
        work.append(vfoboptsig)
1752

    
1753
        if self.COLOR_LCD:
1754
            vfocoptsig = RadioSetting("vfo.c.optsig", "VFO C optional signal",
1755
                                      RadioSettingValueList(
1756
                                          OPTSIG_LIST,
1757
                                          OPTSIG_LIST[_mem.vfo.c.optsig]))
1758
            work.append(vfocoptsig)
1759

    
1760
            vfodoptsig = RadioSetting("vfo.d.optsig", "VFO D optional signal",
1761
                                      RadioSettingValueList(
1762
                                          OPTSIG_LIST,
1763
                                          OPTSIG_LIST[_mem.vfo.d.optsig]))
1764
            work.append(vfodoptsig)
1765

    
1766
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
1767
                                  RadioSettingValueList(
1768
                                      SPMUTE_LIST,
1769
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
1770
        work.append(vfoaspmute)
1771

    
1772
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
1773
                                  RadioSettingValueList(
1774
                                      SPMUTE_LIST,
1775
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
1776
        work.append(vfobspmute)
1777

    
1778
        if self.COLOR_LCD:
1779
            vfocspmute = RadioSetting("vfo.c.spmute", "VFO C speaker mute",
1780
                                      RadioSettingValueList(
1781
                                          SPMUTE_LIST,
1782
                                          SPMUTE_LIST[_mem.vfo.c.spmute]))
1783
            work.append(vfocspmute)
1784

    
1785
            vfodspmute = RadioSetting("vfo.d.spmute", "VFO D speaker mute",
1786
                                      RadioSettingValueList(
1787
                                          SPMUTE_LIST,
1788
                                          SPMUTE_LIST[_mem.vfo.d.spmute]))
1789
            work.append(vfodspmute)
1790

    
1791
        vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
1792
                               RadioSettingValueBoolean(
1793
                                   _mem.vfo.a.scramble))
1794
        work.append(vfoascr)
1795

    
1796
        vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
1797
                               RadioSettingValueBoolean(
1798
                                   _mem.vfo.b.scramble))
1799
        work.append(vfobscr)
1800

    
1801
        if self.COLOR_LCD:
1802
            vfocscr = RadioSetting("vfo.c.scramble", "VFO C scramble",
1803
                                   RadioSettingValueBoolean(
1804
                                       _mem.vfo.c.scramble))
1805
            work.append(vfocscr)
1806

    
1807
            vfodscr = RadioSetting("vfo.d.scramble", "VFO D scramble",
1808
                                   RadioSettingValueBoolean(
1809
                                       _mem.vfo.d.scramble))
1810
            work.append(vfodscr)
1811

    
1812
        vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
1813
                                 RadioSettingValueList(
1814
                                     PTTIDCODE_LIST,
1815
                                     PTTIDCODE_LIST[_mem.vfo.a.scode]))
1816
        work.append(vfoascode)
1817

    
1818
        vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
1819
                                 RadioSettingValueList(
1820
                                     PTTIDCODE_LIST,
1821
                                     PTTIDCODE_LIST[_mem.vfo.b.scode]))
1822
        work.append(vfobscode)
1823

    
1824
        if self.COLOR_LCD:
1825
            vfocscode = RadioSetting("vfo.c.scode", "VFO C PTT-ID",
1826
                                     RadioSettingValueList(
1827
                                         PTTIDCODE_LIST,
1828
                                         PTTIDCODE_LIST[_mem.vfo.c.scode]))
1829
            work.append(vfocscode)
1830

    
1831
            vfodscode = RadioSetting("vfo.d.scode", "VFO D PTT-ID",
1832
                                     RadioSettingValueList(
1833
                                         PTTIDCODE_LIST,
1834
                                         PTTIDCODE_LIST[_mem.vfo.d.scode]))
1835
            work.append(vfodscode)
1836

    
1837
        pttid = RadioSetting("settings.pttid", "PTT ID",
1838
                             RadioSettingValueList(
1839
                                 PTTID_LIST,
1840
                                 PTTID_LIST[_mem.settings.pttid]))
1841
        work.append(pttid)
1842

    
1843
        if not self.COLOR_LCD:
1844
            #FM presets
1845
            fm_presets = RadioSettingGroup("fm_presets", "FM Presets")
1846
            top.append(fm_presets)
1847

    
1848
            def fm_validate(value):
1849
                if value == 0:
1850
                    return chirp_common.format_freq(value)
1851
                if not (87.5 <= value and value <= 108.0):  # 87.5-108MHz
1852
                    msg = ("FM-Preset-Frequency: Must be between 87.5 and 108 MHz")
1853
                    raise InvalidValueError(msg)
1854
                return value
1855

    
1856
            def apply_fm_preset_name(setting, obj):
1857
                valstring = str (setting.value)
1858
                for i in range(0,6):
1859
                    if valstring[i] in VALID_CHARS:
1860
                        obj[i] = valstring[i]
1861
                    else:
1862
                        obj[i] = '0xff'
1863

    
1864
            def apply_fm_freq(setting, obj):
1865
                value = chirp_common.parse_freq(str(setting.value)) / 10
1866
                for i in range(7, -1, -1):
1867
                    obj.freq[i] = value % 10
1868
                    value /= 10
1869
        
1870
            _presets = self._memobj.fm_radio_preset
1871
            i = 1
1872
            for preset in _presets:
1873
                line = RadioSetting("fm_presets_"+ str(i), 
1874
                                    "Station name " + str(i),
1875
                                        RadioSettingValueString(0, 6, _filter(
1876
                                            preset.broadcast_station_name)))
1877
                line.set_apply_callback(apply_fm_preset_name, 
1878
                                        preset.broadcast_station_name)
1879
            
1880
                val = RadioSettingValueFloat(0, 108,
1881
                                             convert_bytes_to_freq(
1882
                                                 preset.freq))
1883
                fmfreq = RadioSetting("fm_presets_"+ str(i) + "_freq",
1884
                                      "Frequency "+ str(i), val)
1885
                val.set_validate_callback(fm_validate)
1886
                fmfreq.set_apply_callback(apply_fm_freq, preset)
1887
                fm_presets.append(line)
1888
                fm_presets.append(fmfreq)
1889
            
1890
                i = i + 1
1891

    
1892
         # DTMF-Setting
1893
        dtmf_enc_settings = RadioSettingGroup ("dtmf_enc_settings",
1894
                                               "DTMF Encoding Settings")
1895
        dtmf_dec_settings = RadioSettingGroup ("dtmf_dec_settings",
1896
                                               "DTMF Decoding Settings")
1897
        top.append(dtmf_enc_settings)
1898
        top.append(dtmf_dec_settings)
1899
        txdisable = RadioSetting("dtmf_settings.txdisable", 
1900
                                 "TX-Disable",
1901
                                 RadioSettingValueBoolean(
1902
                                     _mem.dtmf_settings.txdisable))
1903
        dtmf_enc_settings.append(txdisable)
1904

    
1905
        rxdisable = RadioSetting("dtmf_settings.rxdisable", 
1906
                                 "RX-Disable",
1907
                                 RadioSettingValueBoolean(
1908
                                     _mem.dtmf_settings.rxdisable))
1909
        dtmf_enc_settings.append(rxdisable)
1910

    
1911
        dtmfspeed_on = RadioSetting(
1912
            "dtmf_settings.dtmfspeed_on",
1913
            "DTMF Speed (On Time)",
1914
            RadioSettingValueList(LIST_DTMF_SPEED,
1915
                                  LIST_DTMF_SPEED[
1916
                                      _mem.dtmf_settings.dtmfspeed_on]))
1917
        dtmf_enc_settings.append(dtmfspeed_on)
1918

    
1919
        dtmfspeed_off = RadioSetting(
1920
            "dtmf_settings.dtmfspeed_off",
1921
            "DTMF Speed (Off Time)",
1922
            RadioSettingValueList(LIST_DTMF_SPEED,
1923
                                  LIST_DTMF_SPEED[
1924
                                      _mem.dtmf_settings.dtmfspeed_off]))
1925
        dtmf_enc_settings.append(dtmfspeed_off)
1926

    
1927
        def memory2string(dmtf_mem):
1928
            dtmf_string = ""
1929
            for digit in dmtf_mem:
1930
                if digit != 255:
1931
                    index = LIST_DTMF_VALUES.index(digit)
1932
                    dtmf_string = dtmf_string + LIST_DTMF_DIGITS[index]
1933
            return dtmf_string
1934

    
1935
        def apply_dmtf_frame(setting, obj):
1936
            LOG.debug("Setting DTMF-Code: " + str(setting.value) )
1937
            val_string = str(setting.value)
1938
            for i in range(0,16):
1939
                obj[i] = 255
1940
            i = 0
1941
            for current_char in val_string:
1942
                current_char = current_char.upper()
1943
                index = LIST_DTMF_DIGITS.index(current_char)
1944
                obj[i] = LIST_DTMF_VALUES[ index ]
1945
                i = i + 1
1946

    
1947
        codes = self._memobj.dtmf_codes
1948
        i = 1
1949
        for dtmfcode in codes:
1950
            val = RadioSettingValueString(0, 16, 
1951
                                          memory2string(dtmfcode.code),
1952
                                          False, CHARSET_DTMF_DIGITS)
1953
            line = RadioSetting("dtmf_code_" + str(i) + "_code",
1954
                                "DMTF Code " + str(i), val)
1955
            line.set_apply_callback(apply_dmtf_frame, dtmfcode.code)
1956
            dtmf_enc_settings.append(line)
1957
            i = i + 1
1958

    
1959
        line = RadioSetting("dtmf_settings.mastervice", 
1960
                            "Master and Vice ID",
1961
                            RadioSettingValueBoolean(
1962
                                _mem.dtmf_settings.mastervice))
1963
        dtmf_dec_settings.append(line)
1964

    
1965
        val = RadioSettingValueString(0, 16, 
1966
                                      memory2string(
1967
                                          _mem.dtmf_settings.masterid),
1968
                                          False, CHARSET_DTMF_DIGITS)
1969
        line = RadioSetting("dtmf_settings.masterid",
1970
                            "Master Control ID ", val)
1971
        line.set_apply_callback(apply_dmtf_frame,
1972
                                _mem.dtmf_settings.masterid)
1973
        dtmf_dec_settings.append(line)
1974

    
1975
        line = RadioSetting("dtmf_settings.minspection", 
1976
                            "Master Inspection",
1977
                            RadioSettingValueBoolean(
1978
                                _mem.dtmf_settings.minspection))
1979
        dtmf_dec_settings.append(line)
1980

    
1981
        line = RadioSetting("dtmf_settings.mmonitor", 
1982
                            "Master Monitor",
1983
                            RadioSettingValueBoolean(
1984
                                _mem.dtmf_settings.mmonitor))
1985
        dtmf_dec_settings.append(line)
1986

    
1987
        line = RadioSetting("dtmf_settings.mstun", 
1988
                            "Master Stun",
1989
                            RadioSettingValueBoolean(
1990
                                _mem.dtmf_settings.mstun))
1991
        dtmf_dec_settings.append(line)
1992

    
1993
        line = RadioSetting("dtmf_settings.mkill", 
1994
                            "Master Kill",
1995
                            RadioSettingValueBoolean(
1996
                                _mem.dtmf_settings.mkill))
1997
        dtmf_dec_settings.append(line)
1998

    
1999
        line = RadioSetting("dtmf_settings.mrevive", 
2000
                            "Master Revive",
2001
                            RadioSettingValueBoolean(
2002
                                _mem.dtmf_settings.mrevive))
2003
        dtmf_dec_settings.append(line)
2004

    
2005
        val = RadioSettingValueString(0, 16, 
2006
                                      memory2string(
2007
                                          _mem.dtmf_settings.viceid),
2008
                                          False, CHARSET_DTMF_DIGITS)
2009
        line = RadioSetting("dtmf_settings.viceid",
2010
                            "Vice Control ID ", val)
2011
        line.set_apply_callback(apply_dmtf_frame,
2012
                                _mem.dtmf_settings.viceid)
2013
        dtmf_dec_settings.append(line)
2014

    
2015
        line = RadioSetting("dtmf_settings.vinspection", 
2016
                            "Vice Inspection",
2017
                            RadioSettingValueBoolean(
2018
                                _mem.dtmf_settings.vinspection))
2019
        dtmf_dec_settings.append(line)
2020

    
2021
        line = RadioSetting("dtmf_settings.vmonitor", 
2022
                            "Vice Monitor",
2023
                            RadioSettingValueBoolean(
2024
                                _mem.dtmf_settings.vmonitor))
2025
        dtmf_dec_settings.append(line)
2026

    
2027
        line = RadioSetting("dtmf_settings.vstun", 
2028
                            "Vice Stun",
2029
                            RadioSettingValueBoolean(
2030
                                _mem.dtmf_settings.vstun))
2031
        dtmf_dec_settings.append(line)
2032

    
2033
        line = RadioSetting("dtmf_settings.vkill", 
2034
                            "Vice Kill",
2035
                            RadioSettingValueBoolean(
2036
                                _mem.dtmf_settings.vkill))
2037
        dtmf_dec_settings.append(line)
2038

    
2039
        line = RadioSetting("dtmf_settings.vrevive", 
2040
                            "Vice Revive",
2041
                            RadioSettingValueBoolean(
2042
                                _mem.dtmf_settings.vrevive))
2043
        dtmf_dec_settings.append(line)
2044

    
2045
        val = RadioSettingValueString(0, 16, 
2046
                                      memory2string(
2047
                                          _mem.dtmf_settings.inspection),
2048
                                          False, CHARSET_DTMF_DIGITS)
2049
        line = RadioSetting("dtmf_settings.inspection",
2050
                            "Inspection", val)
2051
        line.set_apply_callback(apply_dmtf_frame,
2052
                                _mem.dtmf_settings.inspection)
2053
        dtmf_dec_settings.append(line)
2054

    
2055
        val = RadioSettingValueString(0, 16, 
2056
                                      memory2string(
2057
                                          _mem.dtmf_settings.alarmcode),
2058
                                          False, CHARSET_DTMF_DIGITS)
2059
        line = RadioSetting("dtmf_settings.alarmcode",
2060
                            "Alarm", val)
2061
        line.set_apply_callback(apply_dmtf_frame,
2062
                                _mem.dtmf_settings.alarmcode)
2063
        dtmf_dec_settings.append(line)
2064

    
2065
        val = RadioSettingValueString(0, 16, 
2066
                                      memory2string(
2067
                                          _mem.dtmf_settings.kill),
2068
                                          False, CHARSET_DTMF_DIGITS)
2069
        line = RadioSetting("dtmf_settings.kill",
2070
                            "Kill", val)
2071
        line.set_apply_callback(apply_dmtf_frame,
2072
                                _mem.dtmf_settings.kill)
2073
        dtmf_dec_settings.append(line)
2074

    
2075
        val = RadioSettingValueString(0, 16, 
2076
                                      memory2string(
2077
                                          _mem.dtmf_settings.monitor),
2078
                                          False, CHARSET_DTMF_DIGITS)
2079
        line = RadioSetting("dtmf_settings.monitor",
2080
                            "Monitor", val)
2081
        line.set_apply_callback(apply_dmtf_frame,
2082
                                _mem.dtmf_settings.monitor)
2083
        dtmf_dec_settings.append(line)
2084

    
2085
        val = RadioSettingValueString(0, 16, 
2086
                                      memory2string(
2087
                                          _mem.dtmf_settings.stun),
2088
                                          False, CHARSET_DTMF_DIGITS)
2089
        line = RadioSetting("dtmf_settings.stun",
2090
                            "Stun", val)
2091
        line.set_apply_callback(apply_dmtf_frame,
2092
                                _mem.dtmf_settings.stun)
2093
        dtmf_dec_settings.append(line)
2094

    
2095
        val = RadioSettingValueString(0, 16, 
2096
                                      memory2string(
2097
                                          _mem.dtmf_settings.revive),
2098
                                          False, CHARSET_DTMF_DIGITS)
2099
        line = RadioSetting("dtmf_settings.revive",
2100
                            "Revive", val)
2101
        line.set_apply_callback(apply_dmtf_frame,
2102
                                _mem.dtmf_settings.revive)
2103
        dtmf_dec_settings.append(line)
2104

    
2105
        def apply_dmtf_listvalue(setting, obj):
2106
            LOG.debug("Setting value: "+ str(setting.value) + " from list")
2107
            val = str(setting.value)
2108
            index = LIST_DTMF_SPECIAL_DIGITS.index(val)
2109
            val = LIST_DTMF_SPECIAL_VALUES[index]
2110
            obj.set_value(val)
2111

    
2112
        idx = LIST_DTMF_SPECIAL_VALUES.index(_mem.dtmf_settings.groupcode)
2113
        line = RadioSetting(
2114
            "dtmf_settings.groupcode",
2115
            "Group Code",
2116
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2117
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2118
        line.set_apply_callback(apply_dmtf_listvalue,
2119
                                _mem.dtmf_settings.groupcode)
2120
        dtmf_dec_settings.append(line)
2121

    
2122
        idx = LIST_DTMF_SPECIAL_VALUES.index(_mem.dtmf_settings.spacecode)
2123
        line = RadioSetting(
2124
            "dtmf_settings.spacecode",
2125
            "Space Code",
2126
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2127
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2128
        line.set_apply_callback(apply_dmtf_listvalue,
2129
                                _mem.dtmf_settings.spacecode)
2130
        dtmf_dec_settings.append(line)
2131

    
2132
        line = RadioSetting(
2133
            "dtmf_settings.resettime",
2134
            "Reset time",
2135
            RadioSettingValueList(LIST_5TONE_RESET,
2136
                                  LIST_5TONE_RESET[
2137
                                      _mem.dtmf_settings.resettime]))
2138
        dtmf_dec_settings.append(line)
2139

    
2140
        line = RadioSetting(
2141
            "dtmf_settings.delayproctime",
2142
            "Delay processing time",
2143
            RadioSettingValueList(LIST_DTMF_DELAY,
2144
                                  LIST_DTMF_DELAY[
2145
                                      _mem.dtmf_settings.delayproctime]))
2146
        dtmf_dec_settings.append(line)
2147

    
2148

    
2149
        # 5 Tone Settings
2150
        stds_5tone = RadioSettingGroup ("stds_5tone", "Standards")
2151
        codes_5tone = RadioSettingGroup ("codes_5tone", "Codes")
2152

    
2153
        group_5tone = RadioSettingGroup ("group_5tone", "5 Tone Settings")
2154
        group_5tone.append(stds_5tone)
2155
        group_5tone.append(codes_5tone)
2156

    
2157
        top.append(group_5tone)
2158

    
2159
        def apply_list_value(setting, obj):
2160
            options = setting.value.get_options()
2161
            obj.set_value ( options.index(str(setting.value)) )
2162

    
2163
        _5tone_standards = self._memobj._5tone_std_settings
2164
        i = 0
2165
        for standard in _5tone_standards:
2166
            std_5tone = RadioSettingGroup ("std_5tone_" + str(i), 
2167
                                           LIST_5TONE_STANDARDS[i])
2168
            stds_5tone.append(std_5tone)
2169
 
2170
            period = standard.period
2171
            if period == 255:
2172
                LOG.debug("Period for " + LIST_5TONE_STANDARDS[i] + 
2173
                          " is not yet configured. Setting to 70ms.")
2174
                period = 5
2175

    
2176
            if period <= len( LIST_5TONE_STANDARD_PERIODS ):
2177
                line = RadioSetting(
2178
                    "_5tone_std_settings_" + str(i) + "_period",
2179
                    "Period (ms)", RadioSettingValueList
2180
                    (LIST_5TONE_STANDARD_PERIODS,
2181
                     LIST_5TONE_STANDARD_PERIODS[period]))
2182
                line.set_apply_callback(apply_list_value, standard.period)
2183
                std_5tone.append(line)
2184
            else:
2185
                LOG.debug("Invalid value for 5tone period! Disabling.")
2186

    
2187
            group_tone = standard.group_tone
2188
            if group_tone == 255:
2189
                LOG.debug("Group-Tone for " + LIST_5TONE_STANDARDS[i] +
2190
                          " is not yet configured. Setting to A.")
2191
                group_tone = 10
2192

    
2193
            if group_tone <= len( LIST_5TONE_DIGITS ):
2194
                line = RadioSetting(
2195
                    "_5tone_std_settings_" + str(i) + "_grouptone",
2196
                    "Group Tone",
2197
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2198
                                          LIST_5TONE_DIGITS[
2199
                                              group_tone]))
2200
                line.set_apply_callback(apply_list_value,
2201
                                        standard.group_tone)
2202
                std_5tone.append(line)
2203
            else:
2204
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2205

    
2206
            repeat_tone = standard.repeat_tone
2207
            if repeat_tone == 255:
2208
                LOG.debug("Repeat-Tone for " + LIST_5TONE_STANDARDS[i] + 
2209
                          " is not yet configured. Setting to E.")
2210
                repeat_tone = 14
2211

    
2212
            if repeat_tone <= len( LIST_5TONE_DIGITS ):
2213
                line = RadioSetting(
2214
                    "_5tone_std_settings_" + str(i) + "_repttone",
2215
                    "Repeat Tone",
2216
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2217
                                          LIST_5TONE_DIGITS[
2218
                                              repeat_tone]))
2219
                line.set_apply_callback(apply_list_value,
2220
                                        standard.repeat_tone)
2221
                std_5tone.append(line)
2222
            else:
2223
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2224
            i = i + 1
2225

    
2226
        def my_apply_5tonestdlist_value(setting, obj):
2227
            if LIST_5TONE_STANDARDS.index(str(setting.value)) == 15:
2228
                obj.set_value(0xFF)
2229
            else:
2230
                obj.set_value( LIST_5TONE_STANDARDS.
2231
                              index(str(setting.value)) )
2232

    
2233
        def apply_5tone_frame(setting, obj):
2234
            LOG.debug("Setting 5 Tone: " + str(setting.value) )
2235
            valstring = str(setting.value)
2236
            if len(valstring) == 0:
2237
                for i in range(0,5):
2238
                    obj[i] = 255
2239
            else:
2240
                validFrame = True
2241
                for i in range(0,5):
2242
                    currentChar = valstring[i].upper()
2243
                    if currentChar in LIST_5TONE_DIGITS:
2244
                        obj[i] = LIST_5TONE_DIGITS.index(currentChar)
2245
                    else:
2246
                        validFrame = False
2247
                        LOG.debug("invalid char: " + str(currentChar))
2248
                if not validFrame:
2249
                    LOG.debug("setting whole frame to FF" )
2250
                    for i in range(0,5):
2251
                        obj[i] = 255
2252

    
2253
        def validate_5tone_frame(value):
2254
            if (len(str(value)) != 5) and (len(str(value)) != 0) :
2255
                msg = ("5 Tone must have 5 digits or 0 digits")
2256
                raise InvalidValueError(msg)
2257
            for digit in str(value):
2258
                if digit.upper() not in LIST_5TONE_DIGITS:
2259
                    msg = (str(digit) + " is not a valid digit for 5tones")
2260
                    raise InvalidValueError(msg)
2261
            return value
2262

    
2263
        def frame2string(frame):
2264
            frameString = ""
2265
            for digit in frame:
2266
                if digit != 255:
2267
                    frameString = frameString + LIST_5TONE_DIGITS[digit]
2268
            return frameString
2269

    
2270
        _5tone_codes = self._memobj._5tone_codes
2271
        i = 1
2272
        for code in _5tone_codes:
2273
            code_5tone = RadioSettingGroup ("code_5tone_" + str(i),
2274
                                            "5 Tone code " + str(i))
2275
            codes_5tone.append(code_5tone)
2276
            if (code.standard == 255 ):
2277
                currentVal = 15
2278
            else:
2279
                currentVal = code.standard
2280
            line = RadioSetting("_5tone_code_" + str(i) + "_std", 
2281
                                " Standard",
2282
                                RadioSettingValueList(LIST_5TONE_STANDARDS,
2283
                                                      LIST_5TONE_STANDARDS[
2284
                                                          currentVal]) )
2285
            line.set_apply_callback(my_apply_5tonestdlist_value,
2286
                                    code.standard)
2287
            code_5tone.append(line)
2288

    
2289
            val = RadioSettingValueString(0, 6,
2290
                                          frame2string(code.frame1), False)
2291
            line = RadioSetting("_5tone_code_" + str(i) + "_frame1", 
2292
                                " Frame 1", val)
2293
            val.set_validate_callback(validate_5tone_frame)
2294
            line.set_apply_callback(apply_5tone_frame, code.frame1)
2295
            code_5tone.append(line)
2296

    
2297
            val = RadioSettingValueString(0, 6,
2298
                                          frame2string(code.frame2), False)
2299
            line = RadioSetting("_5tone_code_" + str(i) + "_frame2",
2300
                                " Frame 2", val)
2301
            val.set_validate_callback(validate_5tone_frame)
2302
            line.set_apply_callback(apply_5tone_frame, code.frame2)
2303
            code_5tone.append(line)
2304

    
2305
            val = RadioSettingValueString(0, 6,
2306
                                          frame2string(code.frame3), False)
2307
            line = RadioSetting("_5tone_code_" + str(i) + "_frame3",
2308
                                " Frame 3", val)
2309
            val.set_validate_callback(validate_5tone_frame)
2310
            line.set_apply_callback(apply_5tone_frame, code.frame3)
2311
            code_5tone.append(line)
2312
            i = i + 1
2313

    
2314
        _5_tone_decode1 = RadioSetting(
2315
            "_5tone_settings._5tone_decode_call_frame1",
2316
            "5 Tone decode call Frame 1",
2317
            RadioSettingValueBoolean(
2318
                _mem._5tone_settings._5tone_decode_call_frame1))
2319
        group_5tone.append(_5_tone_decode1)
2320

    
2321
        _5_tone_decode2 = RadioSetting(
2322
            "_5tone_settings._5tone_decode_call_frame2",
2323
            "5 Tone decode call Frame 2",
2324
            RadioSettingValueBoolean(
2325
                _mem._5tone_settings._5tone_decode_call_frame2))
2326
        group_5tone.append(_5_tone_decode2)
2327

    
2328
        _5_tone_decode3 = RadioSetting(
2329
            "_5tone_settings._5tone_decode_call_frame3",
2330
            "5 Tone decode call Frame 3",
2331
            RadioSettingValueBoolean(
2332
                _mem._5tone_settings._5tone_decode_call_frame3))
2333
        group_5tone.append(_5_tone_decode3)
2334

    
2335
        _5_tone_decode_disp1 = RadioSetting(
2336
            "_5tone_settings._5tone_decode_disp_frame1",
2337
            "5 Tone decode disp Frame 1",
2338
            RadioSettingValueBoolean(
2339
                _mem._5tone_settings._5tone_decode_disp_frame1))
2340
        group_5tone.append(_5_tone_decode_disp1)
2341

    
2342
        _5_tone_decode_disp2 = RadioSetting(
2343
            "_5tone_settings._5tone_decode_disp_frame2",
2344
            "5 Tone decode disp Frame 2",
2345
            RadioSettingValueBoolean(
2346
                _mem._5tone_settings._5tone_decode_disp_frame2))
2347
        group_5tone.append(_5_tone_decode_disp2)
2348

    
2349
        _5_tone_decode_disp3 = RadioSetting(
2350
            "_5tone_settings._5tone_decode_disp_frame3",
2351
            "5 Tone decode disp Frame 3",
2352
            RadioSettingValueBoolean(
2353
                _mem._5tone_settings._5tone_decode_disp_frame3))
2354
        group_5tone.append(_5_tone_decode_disp3)
2355

    
2356
        decode_standard = _mem._5tone_settings.decode_standard
2357
        if decode_standard == 255:
2358
            decode_standard = 0
2359
        if decode_standard <= len (LIST_5TONE_STANDARDS_without_none) :
2360
            line = RadioSetting("_5tone_settings.decode_standard", 
2361
                                "5 Tone-decode Standard",
2362
                                RadioSettingValueList(
2363
                                    LIST_5TONE_STANDARDS_without_none,
2364
                                    LIST_5TONE_STANDARDS_without_none[
2365
                                        decode_standard]))
2366
            group_5tone.append(line)
2367
        else:
2368
            LOG.debug("Invalid decode std...")
2369
            
2370
        _5tone_delay1 = _mem._5tone_settings._5tone_delay1
2371
        if _5tone_delay1 == 255:
2372
            _5tone_delay1 = 20
2373

    
2374
        if _5tone_delay1 <= len( LIST_5TONE_DELAY ):
2375
            list = RadioSettingValueList(LIST_5TONE_DELAY, 
2376
                                         LIST_5TONE_DELAY[
2377
                                             _5tone_delay1])
2378
            line = RadioSetting("_5tone_settings._5tone_delay1",
2379
                                "5 Tone Delay Frame 1", list)
2380
            group_5tone.append(line)
2381
        else:
2382
            LOG.debug("Invalid value for 5tone delay (frame1) ! Disabling.")
2383

    
2384
        _5tone_delay2 = _mem._5tone_settings._5tone_delay2
2385
        if _5tone_delay2 == 255:
2386
            _5tone_delay2 = 20
2387
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2388

    
2389
        if _5tone_delay2 <= len( LIST_5TONE_DELAY ):
2390
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2391
                                         LIST_5TONE_DELAY[
2392
                                             _5tone_delay2])
2393
            line = RadioSetting("_5tone_settings._5tone_delay2",
2394
                                "5 Tone Delay Frame 2", list)
2395
            group_5tone.append(line)
2396
        else:
2397
            LOG.debug("Invalid value for 5tone delay (frame2)! Disabling.")
2398

    
2399
        _5tone_delay3 = _mem._5tone_settings._5tone_delay3
2400
        if _5tone_delay3 == 255:
2401
            _5tone_delay3 = 20
2402
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2403

    
2404
        if _5tone_delay3 <= len( LIST_5TONE_DELAY ):
2405
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2406
                                         LIST_5TONE_DELAY[
2407
                                             _5tone_delay3])
2408
            line = RadioSetting("_5tone_settings._5tone_delay3",
2409
                                "5 Tone Delay Frame 3", list )
2410
            group_5tone.append(line)
2411
        else:
2412
            LOG.debug("Invalid value for 5tone delay (frame3)! Disabling.")
2413

    
2414
        ext_length = _mem._5tone_settings._5tone_first_digit_ext_length
2415
        if ext_length == 255:
2416
            ext_length = 0
2417
            LOG.debug("1st Tone ext lenght unconfigured! Resetting to 0")
2418

    
2419
        if ext_length <= len(
2420
            LIST_5TONE_DELAY ):
2421
            list = RadioSettingValueList(
2422
                LIST_5TONE_DELAY, 
2423
                LIST_5TONE_DELAY[
2424
                    ext_length])
2425
            line = RadioSetting(
2426
                "_5tone_settings._5tone_first_digit_ext_length",
2427
                "First digit extend length", list)
2428
            group_5tone.append(line)
2429
        else:
2430
            LOG.debug("Invalid value for 5tone ext length! Disabling.")
2431

    
2432
        decode_reset_time = _mem._5tone_settings.decode_reset_time
2433
        if decode_reset_time == 255:
2434
            decode_reset_time = 59
2435
            LOG.debug("Decode reset time unconfigured. resetting.")
2436
        if decode_reset_time <= len(LIST_5TONE_RESET):
2437
            list = RadioSettingValueList(
2438
                LIST_5TONE_RESET,
2439
                LIST_5TONE_RESET[
2440
                    decode_reset_time])
2441
            line = RadioSetting("_5tone_settings.decode_reset_time",
2442
                                "Decode reset time", list)
2443
            group_5tone.append(line)
2444
        else:
2445
            LOG.debug("Invalid value decode reset time! Disabling.")
2446

    
2447
        # 2 Tone
2448
        encode_2tone = RadioSettingGroup ("encode_2tone", "2 Tone Encode")
2449
        decode_2tone = RadioSettingGroup ("decode_2tone", "2 Code Decode")
2450

    
2451
        top.append(encode_2tone)
2452
        top.append(decode_2tone)
2453

    
2454
        duration_1st_tone = self._memobj._2tone.duration_1st_tone
2455
        if duration_1st_tone == 255:
2456
            LOG.debug("Duration of first 2 Tone digit is not yet " +
2457
                      "configured. Setting to 600ms")
2458
            duration_1st_tone = 60
2459

    
2460
        if duration_1st_tone <= len( LIST_5TONE_DELAY ):
2461
            line = RadioSetting("_2tone.duration_1st_tone", 
2462
                                "Duration 1st Tone",
2463
                                RadioSettingValueList(LIST_5TONE_DELAY,
2464
                                                      LIST_5TONE_DELAY[
2465
                                                          duration_1st_tone]))
2466
            encode_2tone.append(line)
2467

    
2468
        duration_2nd_tone = self._memobj._2tone.duration_2nd_tone
2469
        if duration_2nd_tone == 255:
2470
            LOG.debug("Duration of second 2 Tone digit is not yet " +
2471
                      "configured. Setting to 600ms")
2472
            duration_2nd_tone = 60
2473

    
2474
        if duration_2nd_tone <= len( LIST_5TONE_DELAY ):
2475
            line = RadioSetting("_2tone.duration_2nd_tone", 
2476
                                "Duration 2nd Tone",
2477
                                RadioSettingValueList(LIST_5TONE_DELAY,
2478
                                                      LIST_5TONE_DELAY[
2479
                                                          duration_2nd_tone]))
2480
            encode_2tone.append(line)
2481

    
2482
        duration_gap = self._memobj._2tone.duration_gap
2483
        if duration_gap == 255:
2484
            LOG.debug("Duration of gap is not yet " +
2485
                      "configured. Setting to 300ms")
2486
            duration_gap = 30
2487

    
2488
        if duration_gap <= len( LIST_5TONE_DELAY ):
2489
            line = RadioSetting("_2tone.duration_gap", "Duration of gap",
2490
                                RadioSettingValueList(LIST_5TONE_DELAY,
2491
                                                      LIST_5TONE_DELAY[
2492
                                                          duration_gap]))
2493
            encode_2tone.append(line)
2494

    
2495
        def _2tone_validate(value):
2496
            if value == 0:
2497
                return 65535
2498
            if value == 65535:
2499
                return value
2500
            if not (300 <= value and value <= 3000):
2501
                msg = ("2 Tone Frequency: Must be between 300 and 3000 Hz")
2502
                raise InvalidValueError(msg)
2503
            return value
2504

    
2505
        def apply_2tone_freq(setting, obj):
2506
            val = int(setting.value)
2507
            if (val == 0) or (val == 65535):
2508
                obj.set_value(65535)
2509
            else:
2510
                obj.set_value(val)
2511

    
2512
        i = 1
2513
        for code in  self._memobj._2tone._2tone_encode:
2514
            code_2tone = RadioSettingGroup ("code_2tone_" + str(i), 
2515
                                           "Encode Code " + str(i))
2516
            encode_2tone.append(code_2tone)
2517

    
2518
            tmp = code.freq1
2519
            if tmp == 65535:
2520
                tmp = 0
2521
            val1 = RadioSettingValueInteger(0, 65535, tmp)
2522
            freq1 = RadioSetting("2tone_code_"+ str(i) + "_freq1", 
2523
                                 "Frequency 1", val1)
2524
            val1.set_validate_callback(_2tone_validate)
2525
            freq1.set_apply_callback(apply_2tone_freq, code.freq1)
2526
            code_2tone.append(freq1)
2527

    
2528
            tmp = code.freq2
2529
            if tmp == 65535:
2530
                tmp = 0
2531
            val2 = RadioSettingValueInteger(0, 65535, tmp)
2532
            freq2 = RadioSetting("2tone_code_"+ str(i) + "_freq2", 
2533
                                 "Frequency 2", val2)
2534
            val2.set_validate_callback(_2tone_validate)
2535
            freq2.set_apply_callback(apply_2tone_freq, code.freq2)
2536
            code_2tone.append(freq2)
2537

    
2538
            i = i + 1
2539

    
2540
        decode_reset_time = _mem._2tone.reset_time
2541
        if decode_reset_time == 255:
2542
            decode_reset_time = 59
2543
            LOG.debug("Decode reset time unconfigured. resetting.")
2544
        if decode_reset_time <= len(LIST_5TONE_RESET):
2545
            list = RadioSettingValueList(
2546
                LIST_5TONE_RESET,
2547
                LIST_5TONE_RESET[
2548
                    decode_reset_time])
2549
            line = RadioSetting("_2tone.reset_time",
2550
                                "Decode reset time", list)
2551
            decode_2tone.append(line)
2552
        else:
2553
            LOG.debug("Invalid value decode reset time! Disabling.")
2554

    
2555
        def apply_2tone_freq_pair(setting, obj):
2556
            val = int(setting.value)
2557
            derived_val = 65535
2558
            frqname = str(setting._name[-5:])
2559
            derivedname = "derived_from_" + frqname
2560

    
2561
            if (val == 0):
2562
                val = 65535
2563
                derived_val = 65535
2564
            else:
2565
                derived_val = int(round(2304000.0/val))
2566

    
2567
            obj[frqname].set_value( val )
2568
            obj[derivedname].set_value( derived_val )
2569

    
2570
            LOG.debug("Apply " + frqname + ": " + str(val) + " | " 
2571
                      + derivedname + ": " + str(derived_val))
2572

    
2573
        i = 1
2574
        for decode_code in  self._memobj._2tone._2tone_decode:
2575
            _2tone_dec_code = RadioSettingGroup ("code_2tone_" + str(i),
2576
                                           "Decode Code " + str(i))
2577
            decode_2tone.append(_2tone_dec_code)
2578

    
2579
            j = 1
2580
            for dec in decode_code.decs:
2581
                val = dec.dec
2582
                if val == 255:
2583
                    LOG.debug("Dec for Code " + str(i) + " Dec " + str(j) +  
2584
                              " is not yet configured. Setting to 0.")
2585
                    val = 0
2586

    
2587
                if val <= len( LIST_2TONE_DEC ):
2588
                    line = RadioSetting(
2589
                        "_2tone_dec_settings_" + str(i) + "_dec_" + str(j),
2590
                        "Dec " + str(j), RadioSettingValueList
2591
                        (LIST_2TONE_DEC,
2592
                         LIST_2TONE_DEC[val]))
2593
                    line.set_apply_callback(apply_list_value, dec.dec)
2594
                    _2tone_dec_code.append(line)
2595
                else:
2596
                    LOG.debug("Invalid value for 2tone dec! Disabling.")
2597

    
2598
                val = dec.response
2599
                if val == 255:
2600
                    LOG.debug("Response for Code " + str(i) + " Dec " + str(j)+
2601
                              " is not yet configured. Setting to 0.")
2602
                    val = 0
2603

    
2604
                if val <= len( LIST_2TONE_RESPONSE ):
2605
                    line = RadioSetting(
2606
                        "_2tone_dec_settings_" + str(i) + "_resp_" + str(j),
2607
                        "Response " + str(j), RadioSettingValueList
2608
                        (LIST_2TONE_RESPONSE,
2609
                         LIST_2TONE_RESPONSE[val]))
2610
                    line.set_apply_callback(apply_list_value, dec.response)
2611
                    _2tone_dec_code.append(line)
2612
                else:
2613
                    LOG.debug("Invalid value for 2tone response! Disabling.")
2614

    
2615
                val = dec.alert
2616
                if val == 255:
2617
                    LOG.debug("Alert for Code " + str(i) + " Dec " + str(j) +  
2618
                              " is not yet configured. Setting to 0.")
2619
                    val = 0
2620

    
2621
                if val <= len( PTTIDCODE_LIST ):
2622
                    line = RadioSetting(
2623
                        "_2tone_dec_settings_" + str(i) + "_alert_" + str(j),
2624
                        "Alert " + str(j), RadioSettingValueList
2625
                        (PTTIDCODE_LIST,
2626
                         PTTIDCODE_LIST[val]))
2627
                    line.set_apply_callback(apply_list_value, dec.alert)
2628
                    _2tone_dec_code.append(line)
2629
                else:
2630
                    LOG.debug("Invalid value for 2tone alert! Disabling.")
2631
                j = j + 1
2632

    
2633
            freq = self._memobj._2tone.freqs[i-1]
2634
            for char in ['A', 'B', 'C', 'D']:
2635
                setting_name = "freq" + str(char)
2636

    
2637
                tmp = freq[setting_name]
2638
                if tmp == 65535:
2639
                    tmp = 0
2640
                if tmp != 0:
2641
                    expected = int(round(2304000.0/tmp))
2642
                    from_mem = freq["derived_from_" + setting_name]
2643
                    if expected != from_mem:
2644
                        LOG.error("Expected " + str(expected) + 
2645
                                  " but read " + str(from_mem ) + 
2646
                                  ". Disabling 2Tone Decode Freqs!")
2647
                        break
2648
                val = RadioSettingValueInteger(0, 65535, tmp)
2649
                frq = RadioSetting("2tone_dec_"+ str(i) + "_freq" + str(char),
2650
                                         ("Decode Frequency " +str(char)), val)
2651
                val.set_validate_callback(_2tone_validate)
2652
                frq.set_apply_callback(apply_2tone_freq_pair, freq)
2653
                _2tone_dec_code.append(frq)
2654

    
2655
            i = i + 1
2656

    
2657
        return top
2658

    
2659
    def set_settings(self, settings):
2660
        _settings = self._memobj.settings
2661
        for element in settings:
2662
            if not isinstance(element, RadioSetting):
2663
                if element.get_name() == "fm_preset":
2664
                    self._set_fm_preset(element)
2665
                else:
2666
                    self.set_settings(element)
2667
                    continue
2668
            else:
2669
                try:
2670
                    name = element.get_name()
2671
                    if "." in name:
2672
                        bits = name.split(".")
2673
                        obj = self._memobj
2674
                        for bit in bits[:-1]:
2675
                            if "/" in bit:
2676
                                bit, index = bit.split("/", 1)
2677
                                index = int(index)
2678
                                obj = getattr(obj, bit)[index]
2679
                            else:
2680
                                obj = getattr(obj, bit)
2681
                        setting = bits[-1]
2682
                    else:
2683
                        obj = _settings
2684
                        setting = element.get_name()
2685

    
2686
                    if element.has_apply_callback():
2687
                        LOG.debug("Using apply callback")
2688
                        element.run_apply_callback()
2689
                    elif element.value.get_mutable():
2690
                        LOG.debug("Setting %s = %s" % (setting, element.value))
2691
                        setattr(obj, setting, element.value)
2692
                except Exception, e:
2693
                    LOG.debug(element.get_name())
2694
                    raise
2695

    
2696
    @classmethod
2697
    def match_model(cls, filedata, filename):
2698
        match_size = False
2699
        match_model = False
2700

    
2701
        # testing the file data size
2702
        if len(filedata) == MEM_SIZE:
2703
            match_size = True
2704

    
2705
        # testing the firmware model fingerprint
2706
        match_model = model_match(cls, filedata)
2707

    
2708
        if match_size and match_model:
2709
            return True
2710
        else:
2711
            return False
2712

    
2713

    
2714
MEM_FORMAT = """
2715
#seekto 0x0000;
2716
struct {
2717
  lbcd rxfreq[4];
2718
  lbcd txfreq[4];
2719
  ul16 rxtone;
2720
  ul16 txtone;
2721
  u8 unknown0:4,
2722
     scode:4;
2723
  u8 unknown1:2,
2724
     spmute:1,
2725
     unknown2:3,
2726
     optsig:2;
2727
  u8 unknown3:3,
2728
     scramble:1,
2729
     unknown4:3,
2730
     power:1;
2731
  u8 unknown5:1,
2732
     wide:1,
2733
     unknown6:2,
2734
     bcl:1,
2735
     add:1,
2736
     pttid:2;
2737
} memory[200];
2738

    
2739
#seekto 0x0E00;
2740
struct {
2741
  u8 tdr;
2742
  u8 unknown1;
2743
  u8 sql;
2744
  u8 unknown2[2];
2745
  u8 tot;
2746
  u8 apo;           // BTech radios use this as the Auto Power Off time
2747
                    // other radios use this as pre-Time Out Alert
2748
  u8 unknown3;
2749
  u8 abr;
2750
  u8 beep;
2751
  u8 unknown4[4];
2752
  u8 dtmfst;
2753
  u8 unknown5[2];
2754
  u8 prisc;
2755
  u8 prich;
2756
  u8 screv;
2757
  u8 unknown6[2];
2758
  u8 pttid;
2759
  u8 pttlt;
2760
  u8 unknown7;
2761
  u8 emctp;
2762
  u8 emcch;
2763
  u8 ringt;
2764
  u8 unknown8;
2765
  u8 camdf;
2766
  u8 cbmdf;
2767
  u8 sync;          // BTech radios use this as the display sync setting
2768
                    // other radios use this as the auto keypad lock setting
2769
  u8 ponmsg;
2770
  u8 wtled;
2771
  u8 rxled;
2772
  u8 txled;
2773
  u8 unknown9[5];
2774
  u8 anil;
2775
  u8 reps;
2776
  u8 repm;
2777
  u8 tdrab;
2778
  u8 ste;
2779
  u8 rpste;
2780
  u8 rptdl;
2781
  u8 mgain;
2782
  u8 dtmfg;
2783
} settings;
2784

    
2785
#seekto 0x0E80;
2786
struct {
2787
  u8 unknown1;
2788
  u8 vfomr;
2789
  u8 keylock;
2790
  u8 unknown2;
2791
  u8 unknown3:4,
2792
     vfomren:1,
2793
     unknown4:1,
2794
     reseten:1,
2795
     menuen:1;
2796
  u8 unknown5[11];
2797
  u8 dispab;
2798
  u8 mrcha;
2799
  u8 mrchb;
2800
  u8 menu;
2801
} settings2;
2802

    
2803
#seekto 0x0EC0;
2804
struct {
2805
  char line1[6];
2806
  char line2[6];
2807
} poweron_msg;
2808

    
2809
struct settings_vfo {
2810
  u8 freq[8];
2811
  u8 offset[6];
2812
  u8 unknown2[2];
2813
  ul16 rxtone;
2814
  ul16 txtone;
2815
  u8 scode;
2816
  u8 spmute;
2817
  u8 optsig;
2818
  u8 scramble;
2819
  u8 wide;
2820
  u8 power;
2821
  u8 shiftd;
2822
  u8 step;
2823
  u8 unknown3[4];
2824
};
2825

    
2826
#seekto 0x0F00;
2827
struct {
2828
  struct settings_vfo a;
2829
  struct settings_vfo b;
2830
} vfo;
2831

    
2832
#seekto 0x1000;
2833
struct {
2834
  char name[6];
2835
  u8 unknown1[10];
2836
} names[200];
2837

    
2838
#seekto 0x2400;
2839
struct {
2840
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
2841
  u8 group_tone;
2842
  u8 repeat_tone;
2843
  u8 unused[13];
2844
} _5tone_std_settings[15];
2845

    
2846
#seekto 0x2500;
2847
struct {
2848
  u8 frame1[5];
2849
  u8 frame2[5];
2850
  u8 frame3[5];
2851
  u8 standard;   // one out of LIST_5TONE_STANDARDS
2852
} _5tone_codes[15];
2853

    
2854
#seekto 0x25F0;
2855
struct {
2856
  u8 _5tone_delay1; // * 10ms
2857
  u8 _5tone_delay2; // * 10ms
2858
  u8 _5tone_delay3; // * 10ms
2859
  u8 _5tone_first_digit_ext_length;
2860
  u8 unknown1;
2861
  u8 unknown2;
2862
  u8 unknown3;
2863
  u8 unknown4;
2864
  u8 decode_standard;
2865
  u8 unknown5:5,
2866
     _5tone_decode_call_frame3:1,
2867
     _5tone_decode_call_frame2:1,
2868
     _5tone_decode_call_frame1:1;
2869
  u8 unknown6:5,
2870
     _5tone_decode_disp_frame3:1,
2871
     _5tone_decode_disp_frame2:1,
2872
     _5tone_decode_disp_frame1:1;
2873
  u8 decode_reset_time; // * 100 + 100ms
2874
} _5tone_settings;
2875

    
2876
#seekto 0x2900;
2877
struct {
2878
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
2879
} dtmf_codes[15];
2880

    
2881
#seekto 0x29F0;
2882
struct {
2883
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
2884
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
2885
  u8 unknown0[14];
2886
  u8 inspection[16];
2887
  u8 monitor[16];
2888
  u8 alarmcode[16];
2889
  u8 stun[16];
2890
  u8 kill[16];
2891
  u8 revive[16];
2892
  u8 unknown1[16];
2893
  u8 unknown2[16];
2894
  u8 unknown3[16];
2895
  u8 unknown4[16];
2896
  u8 unknown5[16];
2897
  u8 unknown6[16];
2898
  u8 unknown7[16];
2899
  u8 masterid[16];
2900
  u8 viceid[16];
2901
  u8 unused01:7,
2902
     mastervice:1;
2903
  u8 unused02:3,
2904
     mrevive:1,
2905
     mkill:1,
2906
     mstun:1,
2907
     mmonitor:1,
2908
     minspection:1;
2909
  u8 unused03:3,
2910
     vrevive:1,
2911
     vkill:1,
2912
     vstun:1,
2913
     vmonitor:1,
2914
     vinspection:1;
2915
  u8 unused04:6,
2916
     txdisable:1,
2917
     rxdisable:1;
2918
  u8 groupcode;
2919
  u8 spacecode;
2920
  u8 delayproctime; // * 100 + 100ms
2921
  u8 resettime;     // * 100 + 100ms
2922
} dtmf_settings;
2923

    
2924
#seekto 0x2D00;
2925
struct {
2926
  struct {
2927
    ul16 freq1;
2928
    u8 unused01[6];
2929
    ul16 freq2;
2930
    u8 unused02[6];
2931
  } _2tone_encode[15];
2932
  u8 duration_1st_tone; // *10ms
2933
  u8 duration_2nd_tone; // *10ms
2934
  u8 duration_gap;      // *10ms
2935
  u8 unused03[13];
2936
  struct {
2937
    struct {
2938
      u8 dec;      // one out of LIST_2TONE_DEC
2939
      u8 response; // one out of LIST_2TONE_RESPONSE
2940
      u8 alert;    // 1-16
2941
    } decs[4];
2942
    u8 unused04[4];
2943
  } _2tone_decode[15];
2944
  u8 unused05[16];
2945

    
2946
  struct {
2947
    ul16 freqA;
2948
    ul16 freqB;
2949
    ul16 freqC;
2950
    ul16 freqD;
2951
    // unknown what those values mean, but they are
2952
    // derived from configured frequencies
2953
    ul16 derived_from_freqA; // 2304000/freqA
2954
    ul16 derived_from_freqB; // 2304000/freqB
2955
    ul16 derived_from_freqC; // 2304000/freqC
2956
    ul16 derived_from_freqD; // 2304000/freqD
2957
  }freqs[15];
2958
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
2959
} _2tone;
2960

    
2961
#seekto 0x3000;
2962
struct {
2963
  u8 freq[8];
2964
  char broadcast_station_name[6];
2965
  u8 unknown[2];
2966
} fm_radio_preset[16];
2967

    
2968
#seekto 0x3C90;
2969
struct {
2970
  u8 vhf_low[3];
2971
  u8 vhf_high[3];
2972
  u8 uhf_low[3];
2973
  u8 uhf_high[3];
2974
} ranges;
2975

    
2976
// the UV-2501+220 & KT8900R has different zones for storing ranges
2977

    
2978
#seekto 0x3CD0;
2979
struct {
2980
  u8 vhf_low[3];
2981
  u8 vhf_high[3];
2982
  u8 unknown1[4];
2983
  u8 unknown2[6];
2984
  u8 vhf2_low[3];
2985
  u8 vhf2_high[3];
2986
  u8 unknown3[4];
2987
  u8 unknown4[6];
2988
  u8 uhf_low[3];
2989
  u8 uhf_high[3];
2990
} ranges220;
2991

    
2992
#seekto 0x3F70;
2993
struct {
2994
  char fp[6];
2995
} fingerprint;
2996

    
2997
"""
2998

    
2999

    
3000
class BTech(BTechMobileCommon):
3001
    """BTECH's UV-5001 and alike radios"""
3002
    BANDS = 2
3003
    COLOR_LCD = False
3004
    NAME_LENGTH = 6
3005

    
3006
    def set_options(self):
3007
        """This is to read the options from the image and set it in the
3008
        environment, for now just the limits of the freqs in the VHF/UHF
3009
        ranges"""
3010

    
3011
        # setting the correct ranges for each radio type
3012
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3013
            # the model 2501+220 has a segment in 220
3014
            # and a different position in the memmap
3015
            # also the QYT KT8900R
3016
            ranges = self._memobj.ranges220
3017
        else:
3018
            ranges = self._memobj.ranges
3019

    
3020
        # the normal dual bands
3021
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3022
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3023

    
3024
        # DEBUG
3025
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3026
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3027

    
3028
        # 220Mhz radios case
3029
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3030
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3031
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3032
            self._220_range = vhf2
3033

    
3034
        # set the class with the real data
3035
        self._vhf_range = vhf
3036
        self._uhf_range = uhf
3037

    
3038
    def process_mmap(self):
3039
        """Process the mem map into the mem object"""
3040

    
3041
        # Get it
3042
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
3043

    
3044
        # load specific parameters from the radio image
3045
        self.set_options()
3046

    
3047

    
3048
# Declaring Aliases (Clones of the real radios)
3049
class JT2705M(chirp_common.Alias):
3050
    VENDOR = "Jetstream"
3051
    MODEL = "JT2705M"
3052

    
3053

    
3054
class JT6188Mini(chirp_common.Alias):
3055
    VENDOR = "Juentai"
3056
    MODEL = "JT-6188 Mini"
3057

    
3058

    
3059
class JT6188Plus(chirp_common.Alias):
3060
    VENDOR = "Juentai"
3061
    MODEL = "JT-6188 Plus"
3062

    
3063

    
3064
class SSGT890(chirp_common.Alias):
3065
    VENDOR = "Sainsonic"
3066
    MODEL = "GT-890"
3067

    
3068

    
3069
class ZastoneMP300(chirp_common.Alias):
3070
    VENDOR = "Zastone"
3071
    MODEL = "MP-300"
3072

    
3073

    
3074
# real radios
3075
@directory.register
3076
class UV2501(BTech):
3077
    """Baofeng Tech UV2501"""
3078
    MODEL = "UV-2501"
3079
    _fileid = [UV2501G3_fp,
3080
               UV2501G2_fp,
3081
               UV2501pp2_fp,
3082
               UV2501pp_fp]
3083

    
3084

    
3085
@directory.register
3086
class UV2501_220(BTech):
3087
    """Baofeng Tech UV2501+220"""
3088
    MODEL = "UV-2501+220"
3089
    BANDS = 3
3090
    _magic = MSTRING_220
3091
    _id2 = UV2501_220pp_id
3092
    _fileid = [UV2501_220G3_fp,
3093
               UV2501_220G2_fp,
3094
               UV2501_220_fp,
3095
               UV2501_220pp_fp]
3096

    
3097

    
3098
@directory.register
3099
class UV5001(BTech):
3100
    """Baofeng Tech UV5001"""
3101
    MODEL = "UV-5001"
3102
    _fileid = [UV5001G3_fp,
3103
               UV5001G22_fp,
3104
               UV5001G2_fp,
3105
               UV5001alpha_fp,
3106
               UV5001pp_fp]
3107
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
3108
                     chirp_common.PowerLevel("Low", watts=10)]
3109

    
3110

    
3111
@directory.register
3112
class MINI8900(BTech):
3113
    """WACCOM MINI-8900"""
3114
    VENDOR = "WACCOM"
3115
    MODEL = "MINI-8900"
3116
    _magic = MSTRING_MINI8900
3117
    _fileid = [MINI8900_fp, ]
3118
    # Clones
3119
    ALIASES = [JT6188Plus, ]
3120

    
3121

    
3122
@directory.register
3123
class KTUV980(BTech):
3124
    """QYT KT-UV980"""
3125
    VENDOR = "QYT"
3126
    MODEL = "KT-UV980"
3127
    _vhf_range = (136000000, 175000000)
3128
    _uhf_range = (400000000, 481000000)
3129
    _magic = MSTRING_MINI8900
3130
    _fileid = [KTUV980_fp, ]
3131
    # Clones
3132
    ALIASES = [JT2705M, ]
3133

    
3134
# Please note that there is a version of this radios that is a clone of the
3135
# Waccom Mini8900, maybe an early version?
3136
@directory.register
3137
class KT9800(BTech):
3138
    """QYT KT8900"""
3139
    VENDOR = "QYT"
3140
    MODEL = "KT8900"
3141
    _vhf_range = (136000000, 175000000)
3142
    _uhf_range = (400000000, 481000000)
3143
    _magic = MSTRING_KT8900
3144
    _fileid = [KT8900_fp,
3145
               KT8900_fp1,
3146
               KT8900_fp2,
3147
               KT8900_fp3,
3148
               KT8900_fp4,
3149
               KT8900_fp5]
3150
    _id2 = KT8900_id
3151
    # Clones
3152
    ALIASES = [JT6188Mini, SSGT890, ZastoneMP300]
3153

    
3154

    
3155
@directory.register
3156
class KT9800R(BTech):
3157
    """QYT KT8900R"""
3158
    VENDOR = "QYT"
3159
    MODEL = "KT8900R"
3160
    BANDS = 3
3161
    _vhf_range = (136000000, 175000000)
3162
    _220_range = (240000000, 271000000)
3163
    _uhf_range = (400000000, 481000000)
3164
    _magic = MSTRING_KT8900R
3165
    _fileid = [KT8900R_fp,
3166
               KT8900R_fp1,
3167
               KT8900R_fp2,
3168
               KT8900R_fp3,
3169
               KT8900R_fp4]
3170
    _id2 = KT8900R_id
3171

    
3172

    
3173
@directory.register
3174
class LT588UV(BTech):
3175
    """LUITON LT-588UV"""
3176
    VENDOR = "LUITON"
3177
    MODEL = "LT-588UV"
3178
    _vhf_range = (136000000, 175000000)
3179
    _uhf_range = (400000000, 481000000)
3180
    _magic = MSTRING_KT8900
3181
    _fileid = [LT588UV_fp,
3182
               LT588UV_fp1]
3183
    _power_levels = [chirp_common.PowerLevel("High", watts=60),
3184
                     chirp_common.PowerLevel("Low", watts=10)]
3185

    
3186

    
3187
COLOR_MEM_FORMAT = """
3188
#seekto 0x0000;
3189
struct {
3190
  lbcd rxfreq[4];
3191
  lbcd txfreq[4];
3192
  ul16 rxtone;
3193
  ul16 txtone;
3194
  u8 unknown0:4,
3195
     scode:4;
3196
  u8 unknown1:2,
3197
     spmute:1,
3198
     unknown2:3,
3199
     optsig:2;
3200
  u8 unknown3:3,
3201
     scramble:1,
3202
     unknown4:3,
3203
     power:1;
3204
  u8 unknown5:1,
3205
     wide:1,
3206
     unknown6:2,
3207
     bcl:1,
3208
     add:1,
3209
     pttid:2;
3210
} memory[200];
3211

    
3212
#seekto 0x0E00;
3213
struct {
3214
  u8 tmr;           // e00 TMR
3215
  u8 unknown1;      // e01
3216
  u8 sql;           // e02 SQL
3217
  u8 unknown2[2];   // e03 e04
3218
  u8 tot;           // e05 TOT
3219
  u8 apo;           // e06 APO
3220
  u8 unknown3;      // e07
3221
  u8 abr;           // e08 ABR
3222
  u8 beep;          // e09 BEEP
3223
  u8 unknown4[4];   // e0a e0b e0c e0d
3224
  u8 dtmfst;        // e0e DTMFST
3225
  u8 unknown5[2];   // e0f e10
3226
  u8 screv;         // e11 SC-REV
3227
  u8 unknown_e12;   // e12
3228
  u8 unknown_e13;   // e13
3229
  u8 pttid;         // e14 PTT-ID
3230
  u8 pttlt;         // e15 PTT-LT
3231
  u8 unknown_e16;   // e16
3232
  u8 emctp;         // e17 EMC-TP
3233
  u8 emcch;         // e18 EMC-CH
3234
  u8 sigbp;         // e19 SIG-BP  BTech radios use this as the roger beep
3235
                    //             setting, other radios use this as ring rime
3236
  u8 unknown_e1a;   // e1a
3237
  u8 camdf;         // e1b CA-MDF
3238
  u8 cbmdf;         // e1c CB-MDF
3239
  u8 ccmdf;         // e1d CC-MDF
3240
  u8 cdmdf;         // e1e CD-MDF
3241
  u8 langua;        // e1f LANGUA
3242
  u8 sync;          // e20 SYNC    BTech radios use this as the display sync
3243
                    //             setting, other radios use this as the auto
3244
                    //             keypad lock setting
3245
  u8 mainfc;        // e21 MAINFC WHITE
3246
  u8 mainbc;        // e22 MAINBC BLUE
3247
  u8 menufc;        // e23 MENUFC YELLOW
3248
  u8 menubc;        // e24 MENUBC BLACK
3249
  u8 stafc;         // e25 STA-FC WHITE
3250
  u8 stabc;         // e26 STA-BC BLACK
3251
  u8 sigfc;         // e27 SIG-FC GREEN
3252
  u8 sigbc;         // e28 SIG-BC BLACK
3253
  u8 rxfc;          // e29 RX-FC GREEN
3254
  u8 txfc;          // e2a TX-FC RED
3255
  u8 txdisp;        // e2b TXDISP
3256
  u8 unknown_e2c;   // e2c
3257
  u8 unknown_e2d;   // e2d
3258
  u8 unknown_e2e;   // e2e
3259
  u8 unknown_e2f;   // e2f
3260
  u8 unknown_e30;   // e30
3261
  u8 anil;          // e31 ANI-L
3262
  u8 reps;          // e32 REP-S
3263
  u8 repm;          // e33 REP-M
3264
  u8 tmrmr;         // e34 TMR-MR
3265
  u8 ste;           // e35 STE
3266
  u8 rpste;         // e36 RP-STE
3267
  u8 rptdl;         // e37 RPT-DL
3268
  u8 dtmfg;         // e38 DTMF-G
3269
  u8 mgain;         // e39 M-GAIN BTech only
3270
  u8 skiptx;        // e3a SKIPTX BTech only
3271
  u8 scmode;        // e3b SC-MODE
3272
} settings;
3273

    
3274
#seekto 0x0E80;
3275
struct {
3276
  u8 unknown1;      // e80
3277
  u8 vfomr;         // e81
3278
  u8 keylock;       // e82
3279
  u8 unknown2;      // e83
3280
  u8 unknown3:4,    // e84
3281
     vfomren:1,
3282
     unknown4:1,
3283
     reseten:1,
3284
     menuen:1;
3285
  u8 unknown5[11];  // e85 e86 e87 e88 e89 e8a e8b e8c e8d e8e e8f
3286
  u8 dispab;        // e90
3287
  u8 unknown6[2];   // e91 e92
3288
  u8 menu;          // e93
3289
  u8 unknown7[7];   // e94 e95 e96 e97 e98 e99 e9a
3290
  u8 vfomra;        // e9b
3291
  u8 vfomrb;        // e9c
3292
  u8 vfomrc;        // e9d
3293
  u8 vfomrd;        // e9e
3294
  u8 mrcha;         // e9f
3295
  u8 mrchb;         // ea0
3296
  u8 mrchc;         // ea1
3297
  u8 mrchd;         // ea2
3298
} settings2;
3299

    
3300
struct settings_vfo {
3301
  u8 freq[8];
3302
  u8 offset[6];
3303
  u8 unknown2[2];
3304
  ul16 rxtone;
3305
  ul16 txtone;
3306
  u8 scode;
3307
  u8 spmute;
3308
  u8 optsig;
3309
  u8 scramble;
3310
  u8 wide;
3311
  u8 power;
3312
  u8 shiftd;
3313
  u8 step;
3314
  u8 unknown3[4];
3315
};
3316

    
3317
#seekto 0x0F00;
3318
struct {
3319
  struct settings_vfo a;
3320
  struct settings_vfo b;
3321
  struct settings_vfo c;
3322
  struct settings_vfo d;
3323
} vfo;
3324

    
3325
#seekto 0x0F80;
3326
struct {
3327
  char line1[8];
3328
  char line2[8];
3329
  char line3[8];
3330
  char line4[8];
3331
  char line5[8];
3332
  char line6[8];
3333
  char line7[8];
3334
  char line8[8];
3335
} poweron_msg;
3336

    
3337
#seekto 0x1000;
3338
struct {
3339
  char name[8];
3340
  u8 unknown1[8];
3341
} names[200];
3342

    
3343
#seekto 0x2400;
3344
struct {
3345
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3346
  u8 group_tone;
3347
  u8 repeat_tone;
3348
  u8 unused[13];
3349
} _5tone_std_settings[15];
3350

    
3351
#seekto 0x2500;
3352
struct {
3353
  u8 frame1[5];
3354
  u8 frame2[5];
3355
  u8 frame3[5];
3356
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3357
} _5tone_codes[15];
3358

    
3359
#seekto 0x25F0;
3360
struct {
3361
  u8 _5tone_delay1; // * 10ms
3362
  u8 _5tone_delay2; // * 10ms
3363
  u8 _5tone_delay3; // * 10ms
3364
  u8 _5tone_first_digit_ext_length;
3365
  u8 unknown1;
3366
  u8 unknown2;
3367
  u8 unknown3;
3368
  u8 unknown4;
3369
  u8 decode_standard;
3370
  u8 unknown5:5,
3371
     _5tone_decode_call_frame3:1,
3372
     _5tone_decode_call_frame2:1,
3373
     _5tone_decode_call_frame1:1;
3374
  u8 unknown6:5,
3375
     _5tone_decode_disp_frame3:1,
3376
     _5tone_decode_disp_frame2:1,
3377
     _5tone_decode_disp_frame1:1;
3378
  u8 decode_reset_time; // * 100 + 100ms
3379
} _5tone_settings;
3380

    
3381
#seekto 0x2900;
3382
struct {
3383
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3384
} dtmf_codes[15];
3385

    
3386
#seekto 0x29F0;
3387
struct {
3388
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
3389
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
3390
  u8 unknown0[14];
3391
  u8 inspection[16];
3392
  u8 monitor[16];
3393
  u8 alarmcode[16];
3394
  u8 stun[16];
3395
  u8 kill[16];
3396
  u8 revive[16];
3397
  u8 unknown1[16];
3398
  u8 unknown2[16];
3399
  u8 unknown3[16];
3400
  u8 unknown4[16];
3401
  u8 unknown5[16];
3402
  u8 unknown6[16];
3403
  u8 unknown7[16];
3404
  u8 masterid[16];
3405
  u8 viceid[16];
3406
  u8 unused01:7,
3407
     mastervice:1;
3408
  u8 unused02:3,
3409
     mrevive:1,
3410
     mkill:1,
3411
     mstun:1,
3412
     mmonitor:1,
3413
     minspection:1;
3414
  u8 unused03:3,
3415
     vrevive:1,
3416
     vkill:1,
3417
     vstun:1,
3418
     vmonitor:1,
3419
     vinspection:1;
3420
  u8 unused04:6,
3421
     txdisable:1,
3422
     rxdisable:1;
3423
  u8 groupcode;
3424
  u8 spacecode;
3425
  u8 delayproctime; // * 100 + 100ms
3426
  u8 resettime;     // * 100 + 100ms
3427
} dtmf_settings;
3428

    
3429
#seekto 0x2D00;
3430
struct {
3431
  struct {
3432
    ul16 freq1;
3433
    u8 unused01[6];
3434
    ul16 freq2;
3435
    u8 unused02[6];
3436
  } _2tone_encode[15];
3437
  u8 duration_1st_tone; // *10ms
3438
  u8 duration_2nd_tone; // *10ms
3439
  u8 duration_gap;      // *10ms
3440
  u8 unused03[13];
3441
  struct {
3442
    struct {
3443
      u8 dec;      // one out of LIST_2TONE_DEC
3444
      u8 response; // one out of LIST_2TONE_RESPONSE
3445
      u8 alert;    // 1-16
3446
    } decs[4];
3447
    u8 unused04[4];
3448
  } _2tone_decode[15];
3449
  u8 unused05[16];
3450

    
3451
  struct {
3452
    ul16 freqA;
3453
    ul16 freqB;
3454
    ul16 freqC;
3455
    ul16 freqD;
3456
    // unknown what those values mean, but they are
3457
    // derived from configured frequencies
3458
    ul16 derived_from_freqA; // 2304000/freqA
3459
    ul16 derived_from_freqB; // 2304000/freqB
3460
    ul16 derived_from_freqC; // 2304000/freqC
3461
    ul16 derived_from_freqD; // 2304000/freqD
3462
  }freqs[15];
3463
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
3464
} _2tone;
3465

    
3466
#seekto 0x3000;
3467
struct {
3468
  u8 freq[8];
3469
  char broadcast_station_name[6];
3470
  u8 unknown[2];
3471
} fm_radio_preset[16];
3472

    
3473
#seekto 0x3D80;
3474
struct {
3475
  u8 vhf_low[3];
3476
  u8 vhf_high[3];
3477
  u8 unknown1[4];
3478
  u8 unknown2[6];
3479
  u8 vhf2_low[3];
3480
  u8 vhf2_high[3];
3481
  u8 unknown3[4];
3482
  u8 unknown4[6];
3483
  u8 uhf_low[3];
3484
  u8 uhf_high[3];
3485
  u8 unknown5[4];
3486
  u8 unknown6[6];
3487
  u8 uhf2_low[3];
3488
  u8 uhf2_high[3];
3489
} ranges;
3490

    
3491
#seekto 0x3F70;
3492
struct {
3493
  char fp[6];
3494
} fingerprint;
3495

    
3496
"""
3497

    
3498

    
3499
class BTechColor(BTechMobileCommon):
3500
    """BTECH's UV-25X4 and alike radios"""
3501
    COLOR_LCD = True
3502
    NAME_LENGTH = 8
3503

    
3504
    def process_mmap(self):
3505
        """Process the mem map into the mem object"""
3506

    
3507
        # Get it
3508
        self._memobj = bitwise.parse(COLOR_MEM_FORMAT, self._mmap)
3509

    
3510
        # load specific parameters from the radio image
3511
        self.set_options()
3512

    
3513
    def set_options(self):
3514
        """This is to read the options from the image and set it in the
3515
        environment, for now just the limits of the freqs in the VHF/UHF
3516
        ranges"""
3517

    
3518
        # setting the correct ranges for each radio type
3519
        ranges = self._memobj.ranges
3520

    
3521
        # the normal dual bands
3522
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3523
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3524

    
3525
        # DEBUG
3526
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3527
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3528

    
3529
        # the additional bands
3530
        if self.MODEL in ["KT8900D", ]:
3531
            # 200Mhz band
3532
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3533
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3534
            self._220_range = vhf2
3535

    
3536
            # 350Mhz band
3537
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
3538
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
3539
            self._350_range = uhf2
3540

    
3541
        # set the class with the real data
3542
        self._vhf_range = vhf
3543
        self._uhf_range = uhf
3544
    
3545

    
3546
@directory.register
3547
class KT9800D(BTechColor):
3548
    """QYT KT8900D"""
3549
    VENDOR = "QYT"
3550
    MODEL = "KT8900D"
3551
    BANDS = 4
3552
    _vhf_range = (136000000, 175000000)
3553
    _220_range = (200000000, 271000000)
3554
    _uhf_range = (400000000, 481000000)
3555
    _350_range = (350000000, 371000000)
3556
    _magic = MSTRING_KT8900D
3557
    _fileid = [KT8900D_fp, ]
3558