Project

General

Profile

New Model #6843 » btech kt-8r_some-1.py

Settings Tabs: Basic, Advanced, Other and Work Mode - Jim Unroe, 11/14/2020 12:13 PM

 
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
from time import sleep
23
from chirp import chirp_common, directory, memmap
24
from chirp import bitwise, errors, util
25
from chirp.settings import RadioSettingGroup, RadioSetting, \
26
    RadioSettingValueBoolean, RadioSettingValueList, \
27
    RadioSettingValueString, RadioSettingValueInteger, \
28
    RadioSettingValueFloat, RadioSettings, InvalidValueError
29
from textwrap import dedent
30

    
31
LOG = logging.getLogger(__name__)
32

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

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

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

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

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

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

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

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

    
147

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

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

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

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

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

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

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

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

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

    
198

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

    
202

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

    
206
# QYT KT8900
207
KT8900_fp = "M29154"
208
# New generations KT8900
209
KT8900_fp1 = "M2C234"
210
KT8900_fp2 = "M2G1F4"
211
KT8900_fp3 = "M2G2F4"
212
KT8900_fp4 = "M2G304"
213
KT8900_fp5 = "M2G314"
214
# this radio has an extra ID
215
KT8900_id = "303688"
216

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

    
232
# KT7900D (quad band)
233
KT7900D_fp = "VC4004"
234
KT7900D_fp1 = "VC4284"
235
KT7900D_fp2 = "VC4264"
236
KT7900D_fp3 = "VC4114"
237
KT7900D_fp4 = "VC4104"
238
KT7900D_fp5 = "VC4254"
239

    
240
# QB25 (quad band) - a clone of KT7900D
241
QB25_fp = "QB-25"
242

    
243
# KT8900D (dual band)
244
KT8900D_fp = "VC2002"
245
KT8900D_fp1 = "VC8632"
246

    
247
# LUITON LT-588UV
248
LT588UV_fp = "V2G1F4"
249
# Added by rstrickoff gen 2 id
250
LT588UV_fp1 = "V2G214"
251

    
252
# QYT KT-8R (quad band ht)
253
KT8R_fp = "MCB264"
254
KT8R_fp1 = "MCB284"
255

    
256

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

    
278

    
279
def _clean_buffer(radio):
280
    """Cleaning the read serial buffer, hard timeout to survive an infinite
281
    data stream"""
282

    
283
    # touching the serial timeout to optimize the flushing
284
    # restored at the end to the default value
285
    radio.pipe.timeout = 0.1
286
    dump = "1"
287
    datacount = 0
288

    
289
    try:
290
        while len(dump) > 0:
291
            dump = radio.pipe.read(100)
292
            datacount += len(dump)
293
            # hard limit to survive a infinite serial data stream
294
            # 5 times bigger than a normal rx block (69 bytes)
295
            if datacount > 345:
296
                seriale = "Please check your serial port selection."
297
                raise errors.RadioError(seriale)
298

    
299
        # restore the default serial timeout
300
        radio.pipe.timeout = STIMEOUT
301

    
302
    except Exception:
303
        raise errors.RadioError("Unknown error cleaning the serial buffer")
304

    
305

    
306
def _rawrecv(radio, amount):
307
    """Raw read from the radio device, less intensive way"""
308

    
309
    data = ""
310

    
311
    try:
312
        data = radio.pipe.read(amount)
313

    
314
        # DEBUG
315
        if debug is True:
316
            LOG.debug("<== (%d) bytes:\n\n%s" %
317
                      (len(data), util.hexprint(data)))
318

    
319
        # fail if no data is received
320
        if len(data) == 0:
321
            raise errors.RadioError("No data received from radio")
322

    
323
        # notice on the logs if short
324
        if len(data) < amount:
325
            LOG.warn("Short reading %d bytes from the %d requested." %
326
                     (len(data), amount))
327

    
328
    except:
329
        raise errors.RadioError("Error reading data from radio")
330

    
331
    return data
332

    
333

    
334
def _send(radio, data):
335
    """Send data to the radio device"""
336

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

    
352
        # DEBUG
353
        if debug is True:
354
            LOG.debug("==> (%d) bytes:\n\n%s" %
355
                      (len(data), util.hexprint(data)))
356
    except:
357
        raise errors.RadioError("Error sending data to radio")
358

    
359

    
360
def _make_frame(cmd, addr, length, data=""):
361
    """Pack the info in the headder format"""
362
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
363
    # add the data if set
364
    if len(data) != 0:
365
        frame += data
366

    
367
    return frame
368

    
369

    
370
def _recv(radio, addr):
371
    """Get data from the radio all at once to lower syscalls load"""
372

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

    
376
    # get the whole block
377
    block = _rawrecv(radio, BLOCK_SIZE + 5)
378

    
379
    # basic check
380
    if len(block) < (BLOCK_SIZE + 5):
381
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
382

    
383
    # checking for the ack
384
    if block[0] != ACK_CMD:
385
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
386

    
387
    # header validation
388
    c, a, l = struct.unpack(">BHB", block[1:5])
389
    if a != addr or l != BLOCK_SIZE or c != ord("X"):
390
        LOG.debug("Invalid header for block 0x%04x" % addr)
391
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
392
        raise errors.RadioError("Invalid header for block 0x%04x:" % addr)
393

    
394
    # return the data
395
    return block[5:]
396

    
397

    
398
def _start_clone_mode(radio, status):
399
    """Put the radio in clone mode and get the ident string, 3 tries"""
400

    
401
    # cleaning the serial buffer
402
    _clean_buffer(radio)
403

    
404
    # prep the data to show in the UI
405
    status.cur = 0
406
    status.msg = "Identifying the radio..."
407
    status.max = 3
408
    radio.status_fn(status)
409

    
410
    try:
411
        for a in range(0, status.max):
412
            # Update the UI
413
            status.cur = a + 1
414
            radio.status_fn(status)
415

    
416
            # send the magic word
417
            _send(radio, radio._magic)
418

    
419
            # Now you get a x06 of ACK if all goes well
420
            ack = radio.pipe.read(1)
421

    
422
            if ack == "\x06":
423
                # DEBUG
424
                LOG.info("Magic ACK received")
425
                status.cur = status.max
426
                radio.status_fn(status)
427

    
428
                return True
429

    
430
        return False
431

    
432
    except errors.RadioError:
433
        raise
434
    except Exception, e:
435
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
436

    
437

    
438
def _do_ident(radio, status, upload=False):
439
    """Put the radio in PROGRAM mode & identify it"""
440
    #  set the serial discipline
441
    radio.pipe.baudrate = 9600
442
    radio.pipe.parity = "N"
443

    
444
    # open the radio into program mode
445
    if _start_clone_mode(radio, status) is False:
446
        msg = "Radio did not enter clone mode"
447
        # warning about old versions of QYT KT8900
448
        if radio.MODEL == "KT8900":
449
            msg += ". You may want to try it as a WACCOM MINI-8900, there is a"
450
            msg += " known variant of this radios that is a clone of it."
451
        raise errors.RadioError(msg)
452

    
453
    # Ok, get the ident string
454
    ident = _rawrecv(radio, 49)
455

    
456
    # basic check for the ident
457
    if len(ident) != 49:
458
        raise errors.RadioError("Radio send a short ident block.")
459

    
460
    # check if ident is OK
461
    itis = False
462
    for fp in radio._fileid:
463
        if fp in ident:
464
            # got it!
465
            itis = True
466
            # checking if we are dealing with a Gen 3 BTECH
467
            if radio.VENDOR == "BTECH" and fp in BTECH3:
468
                radio.btech3 = True
469

    
470
            break
471

    
472
    if itis is False:
473
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
474
        raise errors.RadioError("Radio identification failed.")
475

    
476
    # some radios needs a extra read and check for a code on it, this ones
477
    # has the check value in the _id2 var, others simply False
478
    if radio._id2 is not False:
479
        # lower the timeout here as this radios are reseting due to timeout
480
        radio.pipe.timeout = 0.05
481

    
482
        # query & receive the extra ID
483
        _send(radio, _make_frame("S", 0x3DF0, 16))
484
        id2 = _rawrecv(radio, 21)
485

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

    
493
        # ok, the correct string must be in the received data
494
        # the radio._id2 var will be always a list
495
        flag2 = False
496
        for _id2 in radio._id2:
497
            if _id2 in id2:
498
                flag2 = True
499

    
500
        if not flag2:
501
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
502
                      (radio.MODEL, util.hexprint(id2)))
503
            raise errors.RadioError("The extra ID is wrong, aborting.")
504

    
505
        # this radios need a extra request/answer here on the upload
506
        # the amount of data received depends of the radio type
507
        #
508
        # also the first block of TX must no have the ACK at the beginning
509
        # see _upload for this.
510
        if upload is True:
511
            # send an ACK
512
            _send(radio, ACK_CMD)
513

    
514
            # the amount of data depend on the radio, so far we have two radios
515
            # reading two bytes with an ACK at the end and just ONE with just
516
            # one byte (QYT KT8900)
517
            # the JT-6188 appears a clone of the last, but reads TWO bytes.
518
            #
519
            # we will read two bytes with a custom timeout to not penalize the
520
            # users for this.
521
            #
522
            # we just check for a response and last byte being a ACK, that is
523
            # the common stone for all radios (3 so far)
524
            ack = _rawrecv(radio, 2)
525

    
526
            # checking
527
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
528
                raise errors.RadioError("Radio didn't ACK the upload")
529

    
530
            # restore the default serial timeout
531
            radio.pipe.timeout = STIMEOUT
532

    
533
    # DEBUG
534
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
535

    
536
    return True
537

    
538

    
539
def _download(radio):
540
    """Get the memory map"""
541

    
542
    # UI progress
543
    status = chirp_common.Status()
544

    
545
    # put radio in program mode and identify it
546
    _do_ident(radio, status)
547

    
548
    # the models that doesn't have the extra ID have to make a dummy read here
549
    if radio._id2 is False:
550
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
551
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
552

    
553
        if debug is True:
554
            LOG.info("Dummy first block read done, got this:\n\n %s",
555
                     util.hexprint(discard))
556

    
557
    # reset the progress bar in the UI
558
    status.max = MEM_SIZE / BLOCK_SIZE
559
    status.msg = "Cloning from radio..."
560
    status.cur = 0
561
    radio.status_fn(status)
562

    
563
    # cleaning the serial buffer
564
    _clean_buffer(radio)
565

    
566
    data = ""
567
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
568
        # sending the read request
569
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
570

    
571
        # read
572
        d = _recv(radio, addr)
573

    
574
        # aggregate the data
575
        data += d
576

    
577
        # UI Update
578
        status.cur = addr / BLOCK_SIZE
579
        status.msg = "Cloning from radio..."
580
        radio.status_fn(status)
581

    
582
    return data
583

    
584

    
585
def _upload(radio):
586
    """Upload procedure"""
587

    
588
    # The UPLOAD mem is restricted to lower than 0x3100,
589
    # so we will overide that here localy
590
    MEM_SIZE = radio.UPLOAD_MEM_SIZE
591

    
592
    # UI progress
593
    status = chirp_common.Status()
594

    
595
    # put radio in program mode and identify it
596
    _do_ident(radio, status, True)
597

    
598
    # get the data to upload to radio
599
    data = radio.get_mmap()
600

    
601
    # Reset the UI progress
602
    status.max = MEM_SIZE / TX_BLOCK_SIZE
603
    status.cur = 0
604
    status.msg = "Cloning to radio..."
605
    radio.status_fn(status)
606

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

    
611
    # cleaning the serial buffer
612
    _clean_buffer(radio)
613

    
614
    # the fun start here
615
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
616
        # getting the block of data to send
617
        d = data[addr:addr + TX_BLOCK_SIZE]
618

    
619
        # build the frame to send
620
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
621

    
622
        # first block must not send the ACK at the beginning for the
623
        # ones that has the extra id, since this have to do a extra step
624
        if addr == 0 and radio._id2 is not False:
625
            frame = frame[1:]
626

    
627
        # send the frame
628
        _send(radio, frame)
629

    
630
        # receiving the response
631
        ack = _rawrecv(radio, 1)
632

    
633
        # basic check
634
        if len(ack) != 1:
635
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
636

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

    
640
        # UI Update
641
        status.cur = addr / TX_BLOCK_SIZE
642
        status.msg = "Cloning to radio..."
643
        radio.status_fn(status)
644

    
645

    
646
def model_match(cls, data):
647
    """Match the opened/downloaded image to the correct version"""
648
    rid = data[0x3f70:0x3f76]
649

    
650
    if rid in cls._fileid:
651
        return True
652

    
653
    return False
654

    
655

    
656
def _decode_ranges(low, high):
657
    """Unpack the data in the ranges zones in the memmap and return
658
    a tuple with the integer corresponding to the Mhz it means"""
659
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
660
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
661
    ilow *= 1000000
662
    ihigh *= 1000000
663

    
664
    return (ilow, ihigh)
665

    
666

    
667
def _split(rf, f1, f2):
668
    """Returns False if the two freqs are in the same band (no split)
669
    or True otherwise"""
670

    
671
    # determine if the two freqs are in the same band
672
    for low, high in rf.valid_bands:
673
        if f1 >= low and f1 <= high and \
674
                f2 >= low and f2 <= high:
675
            # if the two freqs are on the same Band this is not a split
676
            return False
677

    
678
    # if you get here is because the freq pairs are split
679
    return True
680

    
681

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

    
706
    @classmethod
707
    def get_prompts(cls):
708
        rp = chirp_common.RadioPrompts()
709
        rp.experimental = \
710
            ('This driver is experimental.\n'
711
             '\n'
712
             'Please keep a copy of your memories with the original software '
713
             'if you treasure them, this driver is new and may contain'
714
             ' bugs.\n'
715
             '\n'
716
             )
717
        rp.pre_download = _(dedent("""\
718
            Follow these instructions to download your info:
719

    
720
            1 - Turn off your radio
721
            2 - Connect your interface cable
722
            3 - Turn on your radio
723
            4 - Do the download of your radio data
724

    
725
            """))
726
        rp.pre_upload = _(dedent("""\
727
            Follow these instructions to upload your info:
728

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

    
734
            """))
735
        return rp
736

    
737
    def get_features(self):
738
        """Get the radio's features"""
739

    
740
        # we will use the following var as global
741
        global POWER_LEVELS
742

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

    
774
        # power levels
775
        POWER_LEVELS = self._power_levels
776
        rf.valid_power_levels = POWER_LEVELS
777

    
778
        # normal dual bands
779
        rf.valid_bands = [self._vhf_range, self._uhf_range]
780

    
781
        # 220 band
782
        if self.BANDS == 3 or self.BANDS == 4:
783
            rf.valid_bands.append(self._220_range)
784

    
785
        # 350 band
786
        if self.BANDS == 4:
787
            rf.valid_bands.append(self._350_range)
788

    
789
        return rf
790

    
791
    def sync_in(self):
792
        """Download from radio"""
793
        data = _download(self)
794
        self._mmap = memmap.MemoryMap(data)
795
        self.process_mmap()
796

    
797
    def sync_out(self):
798
        """Upload to radio"""
799
        try:
800
            _upload(self)
801
        except errors.RadioError:
802
            raise
803
        except Exception, e:
804
            raise errors.RadioError("Error: %s" % e)
805

    
806
    def get_raw_memory(self, number):
807
        return repr(self._memobj.memory[number])
808

    
809
    def _decode_tone(self, val):
810
        """Parse the tone data to decode from mem, it returns:
811
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
812
        pol = None
813

    
814
        if val in [0, 65535]:
815
            return '', None, None
816
        elif val > 0x0258:
817
            a = val / 10.0
818
            return 'Tone', a, pol
819
        else:
820
            if val > 0x69:
821
                index = val - 0x6A
822
                pol = "R"
823
            else:
824
                index = val - 1
825
                pol = "N"
826

    
827
            tone = DTCS[index]
828
            return 'DTCS', tone, pol
829

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

    
854
    def get_memory(self, number):
855
        """Get the mem representation from the radio image"""
856
        _mem = self._memobj.memory[number]
857
        _names = self._memobj.names[number]
858

    
859
        # Create a high-level memory object to return to the UI
860
        mem = chirp_common.Memory()
861

    
862
        # Memory number
863
        mem.number = number
864

    
865
        if _mem.get_raw()[0] == "\xFF":
866
            mem.empty = True
867
            return mem
868

    
869
        # Freq and offset
870
        mem.freq = int(_mem.rxfreq) * 10
871
        # tx freq can be blank
872
        if _mem.get_raw()[4] == "\xFF":
873
            # TX freq not set
874
            mem.offset = 0
875
            mem.duplex = "off"
876
        else:
877
            # TX freq set
878
            offset = (int(_mem.txfreq) * 10) - mem.freq
879
            if offset != 0:
880
                if _split(self.get_features(), mem.freq, int(
881
                          _mem.txfreq) * 10):
882
                    mem.duplex = "split"
883
                    mem.offset = int(_mem.txfreq) * 10
884
                elif offset < 0:
885
                    mem.offset = abs(offset)
886
                    mem.duplex = "-"
887
                elif offset > 0:
888
                    mem.offset = offset
889
                    mem.duplex = "+"
890
            else:
891
                mem.offset = 0
892

    
893
        # name TAG of the channel
894
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
895

    
896
        # power
897
        mem.power = POWER_LEVELS[int(_mem.power)]
898

    
899
        # wide/narrow
900
        mem.mode = MODES[int(_mem.wide)]
901

    
902
        # skip
903
        mem.skip = SKIP_VALUES[_mem.add]
904

    
905
        # tone data
906
        rxtone = txtone = None
907
        txtone = self._decode_tone(_mem.txtone)
908
        rxtone = self._decode_tone(_mem.rxtone)
909
        chirp_common.split_tone_decode(mem, txtone, rxtone)
910

    
911
        # Extra
912
        mem.extra = RadioSettingGroup("extra", "Extra")
913

    
914
        if not self.COLOR_LCD or \
915
                (self.COLOR_LCD and not self.VENDOR == "BTECH"):
916
            scramble = RadioSetting("scramble", "Scramble",
917
                                    RadioSettingValueBoolean(bool(
918
                                        _mem.scramble)))
919
            mem.extra.append(scramble)
920

    
921
        bcl = RadioSetting("bcl", "Busy channel lockout",
922
                           RadioSettingValueBoolean(bool(_mem.bcl)))
923
        mem.extra.append(bcl)
924

    
925
        pttid = RadioSetting("pttid", "PTT ID",
926
                             RadioSettingValueList(PTTID_LIST,
927
                                                   PTTID_LIST[_mem.pttid]))
928
        mem.extra.append(pttid)
929

    
930
        # validating scode
931
        scode = _mem.scode if _mem.scode != 15 else 0
932
        pttidcode = RadioSetting("scode", "PTT ID signal code",
933
                                 RadioSettingValueList(
934
                                     PTTIDCODE_LIST,
935
                                     PTTIDCODE_LIST[scode]))
936
        mem.extra.append(pttidcode)
937

    
938
        optsig = RadioSetting("optsig", "Optional signaling",
939
                              RadioSettingValueList(
940
                                  OPTSIG_LIST,
941
                                  OPTSIG_LIST[_mem.optsig]))
942
        mem.extra.append(optsig)
943

    
944
        spmute = RadioSetting("spmute", "Speaker mute",
945
                              RadioSettingValueList(
946
                                  SPMUTE_LIST,
947
                                  SPMUTE_LIST[_mem.spmute]))
948
        mem.extra.append(spmute)
949

    
950
        return mem
951

    
952
    def set_memory(self, mem):
953
        """Set the memory data in the eeprom img from the UI"""
954
        # get the eprom representation of this channel
955
        _mem = self._memobj.memory[mem.number]
956
        _names = self._memobj.names[mem.number]
957

    
958
        mem_was_empty = False
959
        # same method as used in get_memory for determining if mem is empty
960
        # doing this BEFORE overwriting it with new values ...
961
        if _mem.get_raw()[0] == "\xFF":
962
            LOG.debug("This mem was empty before")
963
            mem_was_empty = True
964

    
965
        # if empty memmory
966
        if mem.empty:
967
            # the channel itself
968
            _mem.set_raw("\xFF" * 16)
969
            # the name tag
970
            _names.set_raw("\xFF" * 16)
971
            return
972

    
973
        if mem_was_empty:
974
            # Zero the whole memory if we're making it unempty for
975
            # the first time
976
            LOG.debug('Zeroing new memory')
977
            _mem.set_raw('\x00' * 16)
978

    
979
        # frequency
980
        _mem.rxfreq = mem.freq / 10
981

    
982
        # duplex
983
        if mem.duplex == "+":
984
            _mem.txfreq = (mem.freq + mem.offset) / 10
985
        elif mem.duplex == "-":
986
            _mem.txfreq = (mem.freq - mem.offset) / 10
987
        elif mem.duplex == "off":
988
            for i in _mem.txfreq:
989
                i.set_raw("\xFF")
990
        elif mem.duplex == "split":
991
            _mem.txfreq = mem.offset / 10
992
        else:
993
            _mem.txfreq = mem.freq / 10
994

    
995
        # tone data
996
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
997
            chirp_common.split_tone_encode(mem)
998
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
999
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1000

    
1001
        # name TAG of the channel
1002
        if len(mem.name) < self.NAME_LENGTH:
1003
            # we must pad to self.NAME_LENGTH chars, " " = "\xFF"
1004
            mem.name = str(mem.name).ljust(self.NAME_LENGTH, " ")
1005
        _names.name = str(mem.name).replace(" ", "\xFF")
1006

    
1007
        # power, # default power level is high
1008
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1009

    
1010
        # wide/narrow
1011
        _mem.wide = MODES.index(mem.mode)
1012

    
1013
        # scan add property
1014
        _mem.add = SKIP_VALUES.index(mem.skip)
1015

    
1016
        # reseting unknowns, this have to be set by hand
1017
        _mem.unknown0 = 0
1018
        _mem.unknown1 = 0
1019
        _mem.unknown2 = 0
1020
        _mem.unknown3 = 0
1021
        _mem.unknown4 = 0
1022
        _mem.unknown5 = 0
1023
        _mem.unknown6 = 0
1024

    
1025
        def _zero_settings():
1026
            _mem.spmute = 0
1027
            _mem.optsig = 0
1028
            _mem.scramble = 0
1029
            _mem.bcl = 0
1030
            _mem.pttid = 0
1031
            _mem.scode = 0
1032

    
1033
        if self.COLOR_LCD and _mem.scramble:
1034
            LOG.info('Resetting scramble bit for BTECH COLOR_LCD variant')
1035
            _mem.scramble = 0
1036

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

    
1057
        return mem
1058

    
1059
    def get_settings(self):
1060
        """Translate the bit in the mem_struct into settings in the UI"""
1061
        _mem = self._memobj
1062
        basic = RadioSettingGroup("basic", "Basic Settings")
1063
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1064
        other = RadioSettingGroup("other", "Other Settings")
1065
        work = RadioSettingGroup("work", "Work Mode Settings")
1066
        top = RadioSettings(basic, advanced, other, work)
1067

    
1068
        # Basic
1069
        if self.COLOR_LCD:
1070
            tmr = RadioSetting("settings.tmr", "Transceiver multi-receive",
1071
                               RadioSettingValueList(
1072
                                   self.LIST_TMR,
1073
                                   self.LIST_TMR[_mem.settings.tmr]))
1074
            basic.append(tmr)
1075
        else:
1076
            tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1077
                               RadioSettingValueBoolean(_mem.settings.tdr))
1078
            basic.append(tdr)
1079

    
1080
        sql = RadioSetting("settings.sql", "Squelch level",
1081
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1082
        basic.append(sql)
1083

    
1084
        if self.MODEL == "GMRS-50X1":
1085
            autolk = RadioSetting("settings.autolk", "Auto keylock",
1086
                                  RadioSettingValueBoolean(
1087
                                      _mem.settings.autolk))
1088
            basic.append(autolk)
1089

    
1090
        tot = RadioSetting("settings.tot", "Time out timer",
1091
                           RadioSettingValueList(
1092
                               LIST_TOT,
1093
                               LIST_TOT[_mem.settings.tot]))
1094
        basic.append(tot)
1095

    
1096
        if self.MODEL == "KT-8R":
1097
                save = RadioSetting("settings.save", "Battery Save",
1098
                                    RadioSettingValueBoolean(
1099
                                        _mem.settings.save))
1100
                basic.append(save)
1101

    
1102
        if not self.COLOR_LCD3:
1103
            if self.VENDOR == "BTECH" or self.COLOR_LCD:
1104
                apo = RadioSetting("settings.apo", "Auto power off timer",
1105
                                   RadioSettingValueList(
1106
                                       LIST_APO,
1107
                                       LIST_APO[_mem.settings.apo]))
1108
                basic.append(apo)
1109
            else:
1110
                toa = RadioSetting("settings.apo", "Time out alert timer",
1111
                                   RadioSettingValueList(
1112
                                       LIST_OFF1TO10,
1113
                                       LIST_OFF1TO10[_mem.settings.apo]))
1114
                basic.append(toa)
1115

    
1116
        abr = RadioSetting("settings.abr", "Backlight timer",
1117
                           RadioSettingValueList(
1118
                               LIST_OFF1TO50,
1119
                               LIST_OFF1TO50[_mem.settings.abr]))
1120
        basic.append(abr)
1121

    
1122
        beep = RadioSetting("settings.beep", "Key beep",
1123
                            RadioSettingValueBoolean(_mem.settings.beep))
1124
        basic.append(beep)
1125

    
1126
        if self.MODEL == "KT-8R":
1127
                dsub = RadioSetting("settings.dsub", "CTCSS/DCS code display",
1128
                                    RadioSettingValueBoolean(
1129
                                        _mem.settings.dsub))
1130
                basic.append(dsub)
1131

    
1132
        if self.MODEL == "KT-8R":
1133
                dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1134
                                    RadioSettingValueBoolean(
1135
                                        _mem.settings.dtmfst))
1136
                basic.append(dtmfst)
1137
        else:
1138
            dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1139
                                  RadioSettingValueList(
1140
                                      LIST_DTMFST,
1141
                                      LIST_DTMFST[_mem.settings.dtmfst]))
1142
            basic.append(dtmfst)
1143

    
1144
        if not self.COLOR_LCD:
1145
            prisc = RadioSetting("settings.prisc", "Priority scan",
1146
                                 RadioSettingValueBoolean(
1147
                                     _mem.settings.prisc))
1148
            basic.append(prisc)
1149

    
1150
            prich = RadioSetting("settings.prich", "Priority channel",
1151
                                 RadioSettingValueInteger(0, self._upper,
1152
                                                          _mem.settings.prich))
1153
            basic.append(prich)
1154

    
1155
        screv = RadioSetting("settings.screv", "Scan resume method",
1156
                             RadioSettingValueList(
1157
                                 LIST_SCREV,
1158
                                 LIST_SCREV[_mem.settings.screv]))
1159
        basic.append(screv)
1160

    
1161
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1162
                             RadioSettingValueInteger(0, 30,
1163
                                                      _mem.settings.pttlt))
1164
        basic.append(pttlt)
1165

    
1166
        if self.VENDOR == "BTECH" and self.COLOR_LCD:
1167
            emctp = RadioSetting("settings.emctp", "Alarm mode",
1168
                                 RadioSettingValueList(
1169
                                     LIST_EMCTPX,
1170
                                     LIST_EMCTPX[_mem.settings.emctp]))
1171
            basic.append(emctp)
1172
        else:
1173
            emctp = RadioSetting("settings.emctp", "Alarm mode",
1174
                                 RadioSettingValueList(
1175
                                     LIST_EMCTP,
1176
                                     LIST_EMCTP[_mem.settings.emctp]))
1177
            basic.append(emctp)
1178

    
1179
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1180
                             RadioSettingValueInteger(0, self._upper,
1181
                                                      _mem.settings.emcch))
1182
        basic.append(emcch)
1183

    
1184
        if self.COLOR_LCD:
1185
            if _mem.settings.sigbp > 0x01:
1186
                val = 0x00
1187
            else:
1188
                val = _mem.settings.sigbp
1189
            sigbp = RadioSetting("settings.sigbp", "Signal beep",
1190
                                 RadioSettingValueBoolean(val))
1191
            basic.append(sigbp)
1192
        else:
1193
            ringt = RadioSetting("settings.ringt", "Ring time",
1194
                                 RadioSettingValueList(
1195
                                     LIST_OFF1TO9,
1196
                                     LIST_OFF1TO9[_mem.settings.ringt]))
1197
            basic.append(ringt)
1198

    
1199
        camdf = RadioSetting("settings.camdf", "Display mode A",
1200
                             RadioSettingValueList(
1201
                                 LIST_MDF,
1202
                                 LIST_MDF[_mem.settings.camdf]))
1203
        basic.append(camdf)
1204

    
1205
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1206
                             RadioSettingValueList(
1207
                                 LIST_MDF,
1208
                                 LIST_MDF[_mem.settings.cbmdf]))
1209
        basic.append(cbmdf)
1210

    
1211
        if self.COLOR_LCD:
1212
            ccmdf = RadioSetting("settings.ccmdf", "Display mode C",
1213
                                 RadioSettingValueList(
1214
                                     LIST_MDF,
1215
                                     LIST_MDF[_mem.settings.ccmdf]))
1216
            basic.append(ccmdf)
1217

    
1218
            cdmdf = RadioSetting("settings.cdmdf", "Display mode D",
1219
                                 RadioSettingValueList(
1220
                                     LIST_MDF,
1221
                                     LIST_MDF[_mem.settings.cdmdf]))
1222
            basic.append(cdmdf)
1223

    
1224
            langua = RadioSetting("settings.langua", "Language",
1225
                                  RadioSettingValueList(
1226
                                      LIST_LANGUA,
1227
                                      LIST_LANGUA[_mem.settings.langua]))
1228
            basic.append(langua)
1229

    
1230
        if self.MODEL == "KT-8R":
1231
            voice = RadioSetting("settings.voice", "Voice prompt",
1232
                                  RadioSettingValueList(
1233
                                      LIST_VOICE,
1234
                                      LIST_VOICE[_mem.settings.voice]))
1235
            basic.append(voice)
1236

    
1237
            vox = RadioSetting("settings.vox", "VOX",
1238
                                  RadioSettingValueList(
1239
                                      LIST_VOX,
1240
                                      LIST_VOX[_mem.settings.vox]))
1241
            basic.append(vox)
1242

    
1243
            voxt = RadioSetting("settings.voxt", "VOX delay time",
1244
                                  RadioSettingValueList(
1245
                                      LIST_VOXT,
1246
                                      LIST_VOXT[_mem.settings.voxt]))
1247
            basic.append(voxt)
1248

    
1249
        if self.VENDOR == "BTECH":
1250
            if self.COLOR_LCD:
1251
                sync = RadioSetting("settings.sync", "Channel display sync",
1252
                                    RadioSettingValueList(
1253
                                        LIST_SYNC,
1254
                                        LIST_SYNC[_mem.settings.sync]))
1255
                basic.append(sync)
1256
            else:
1257
                sync = RadioSetting("settings.sync", "A/B channel sync",
1258
                                    RadioSettingValueBoolean(
1259
                                        _mem.settings.sync))
1260
                basic.append(sync)
1261
        else:
1262
            autolk = RadioSetting("settings.sync", "Auto keylock",
1263
                                  RadioSettingValueBoolean(
1264
                                      _mem.settings.sync))
1265
            basic.append(autolk)
1266

    
1267
        if not self.COLOR_LCD:
1268
            ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1269
                                  RadioSettingValueList(
1270
                                      LIST_PONMSG,
1271
                                      LIST_PONMSG[_mem.settings.ponmsg]))
1272
            basic.append(ponmsg)
1273

    
1274
        if self.COLOR_LCD and not (self.COLOR_LCD2 or self.COLOR_LCD3):
1275
            mainfc = RadioSetting("settings.mainfc",
1276
                                  "Main LCD foreground color",
1277
                                  RadioSettingValueList(
1278
                                      LIST_COLOR8,
1279
                                      LIST_COLOR8[_mem.settings.mainfc]))
1280
            basic.append(mainfc)
1281

    
1282
            mainbc = RadioSetting("settings.mainbc",
1283
                                  "Main LCD background color",
1284
                                  RadioSettingValueList(
1285
                                      LIST_COLOR8,
1286
                                      LIST_COLOR8[_mem.settings.mainbc]))
1287
            basic.append(mainbc)
1288

    
1289
            menufc = RadioSetting("settings.menufc", "Menu foreground color",
1290
                                  RadioSettingValueList(
1291
                                      LIST_COLOR8,
1292
                                      LIST_COLOR8[_mem.settings.menufc]))
1293
            basic.append(menufc)
1294

    
1295
            menubc = RadioSetting("settings.menubc", "Menu background color",
1296
                                  RadioSettingValueList(
1297
                                      LIST_COLOR8,
1298
                                      LIST_COLOR8[_mem.settings.menubc]))
1299
            basic.append(menubc)
1300

    
1301
            stafc = RadioSetting("settings.stafc",
1302
                                 "Top status foreground color",
1303
                                 RadioSettingValueList(
1304
                                     LIST_COLOR8,
1305
                                     LIST_COLOR8[_mem.settings.stafc]))
1306
            basic.append(stafc)
1307

    
1308
            stabc = RadioSetting("settings.stabc",
1309
                                 "Top status background color",
1310
                                 RadioSettingValueList(
1311
                                     LIST_COLOR8,
1312
                                     LIST_COLOR8[_mem.settings.stabc]))
1313
            basic.append(stabc)
1314

    
1315
            sigfc = RadioSetting("settings.sigfc",
1316
                                 "Bottom status foreground color",
1317
                                 RadioSettingValueList(
1318
                                     LIST_COLOR8,
1319
                                     LIST_COLOR8[_mem.settings.sigfc]))
1320
            basic.append(sigfc)
1321

    
1322
            sigbc = RadioSetting("settings.sigbc",
1323
                                 "Bottom status background color",
1324
                                 RadioSettingValueList(
1325
                                     LIST_COLOR8,
1326
                                     LIST_COLOR8[_mem.settings.sigbc]))
1327
            basic.append(sigbc)
1328

    
1329
            rxfc = RadioSetting("settings.rxfc", "Receiving character color",
1330
                                RadioSettingValueList(
1331
                                    LIST_COLOR8,
1332
                                    LIST_COLOR8[_mem.settings.rxfc]))
1333
            basic.append(rxfc)
1334

    
1335
            txfc = RadioSetting("settings.txfc",
1336
                                "Transmitting character color",
1337
                                RadioSettingValueList(
1338
                                    LIST_COLOR8,
1339
                                    LIST_COLOR8[_mem.settings.txfc]))
1340
            basic.append(txfc)
1341

    
1342
            txdisp = RadioSetting("settings.txdisp",
1343
                                  "Transmitting status display",
1344
                                  RadioSettingValueList(
1345
                                      LIST_TXDISP,
1346
                                      LIST_TXDISP[_mem.settings.txdisp]))
1347
            basic.append(txdisp)
1348
        elif self.COLOR_LCD2 or self.COLOR_LCD3:
1349
            stfc = RadioSetting("settings.stfc",
1350
                                "ST-FC",
1351
                                RadioSettingValueList(
1352
                                    LIST_COLOR7,
1353
                                    LIST_COLOR7[_mem.settings.stfc]))
1354
            basic.append(stfc)
1355

    
1356
            mffc = RadioSetting("settings.mffc",
1357
                                "MF-FC",
1358
                                RadioSettingValueList(
1359
                                    LIST_COLOR7,
1360
                                    LIST_COLOR7[_mem.settings.mffc]))
1361
            basic.append(mffc)
1362

    
1363
            sfafc = RadioSetting("settings.sfafc",
1364
                                 "SFA-FC",
1365
                                 RadioSettingValueList(
1366
                                     LIST_COLOR7,
1367
                                     LIST_COLOR7[_mem.settings.sfafc]))
1368
            basic.append(sfafc)
1369

    
1370
            sfbfc = RadioSetting("settings.sfbfc",
1371
                                 "SFB-FC",
1372
                                 RadioSettingValueList(
1373
                                     LIST_COLOR7,
1374
                                     LIST_COLOR7[_mem.settings.sfbfc]))
1375
            basic.append(sfbfc)
1376

    
1377
            sfcfc = RadioSetting("settings.sfcfc",
1378
                                 "SFC-FC",
1379
                                 RadioSettingValueList(
1380
                                     LIST_COLOR7,
1381
                                     LIST_COLOR7[_mem.settings.sfcfc]))
1382
            basic.append(sfcfc)
1383

    
1384
            sfdfc = RadioSetting("settings.sfdfc",
1385
                                 "SFD-FC",
1386
                                 RadioSettingValueList(
1387
                                     LIST_COLOR7,
1388
                                     LIST_COLOR7[_mem.settings.sfdfc]))
1389
            basic.append(sfdfc)
1390

    
1391
            subfc = RadioSetting("settings.subfc",
1392
                                 "SUB-FC",
1393
                                 RadioSettingValueList(
1394
                                     LIST_COLOR7,
1395
                                     LIST_COLOR7[_mem.settings.subfc]))
1396
            basic.append(subfc)
1397

    
1398
            fmfc = RadioSetting("settings.fmfc",
1399
                                "FM-FC",
1400
                                RadioSettingValueList(
1401
                                    LIST_COLOR7,
1402
                                    LIST_COLOR7[_mem.settings.fmfc]))
1403
            basic.append(fmfc)
1404

    
1405
            sigfc = RadioSetting("settings.sigfc",
1406
                                 "SIG-FC",
1407
                                 RadioSettingValueList(
1408
                                     LIST_COLOR7,
1409
                                     LIST_COLOR7[_mem.settings.sigfc]))
1410
            basic.append(sigfc)
1411

    
1412
            if not self.MODEL == "KT-8R":
1413
                modfc = RadioSetting("settings.modfc",
1414
                                     "MOD-FC",
1415
                                     RadioSettingValueList(
1416
                                         LIST_COLOR7,
1417
                                         LIST_COLOR7[_mem.settings.modfc]))
1418
                basic.append(modfc)
1419

    
1420
            menufc = RadioSetting("settings.menufc",
1421
                                  "MENUFC",
1422
                                  RadioSettingValueList(
1423
                                      LIST_COLOR7,
1424
                                      LIST_COLOR7[_mem.settings.menufc]))
1425
            basic.append(menufc)
1426

    
1427
            txfc = RadioSetting("settings.txfc",
1428
                                "TX-FC",
1429
                                RadioSettingValueList(
1430
                                    LIST_COLOR7,
1431
                                    LIST_COLOR7[_mem.settings.txfc]))
1432
            basic.append(txfc)
1433

    
1434
            if self.MODEL == "KT-8R":
1435
                rxfc = RadioSetting("settings.rxfc",
1436
                                    "RX-FC",
1437
                                    RadioSettingValueList(
1438
                                        LIST_COLOR7,
1439
                                        LIST_COLOR7[_mem.settings.rxfc]))
1440
                basic.append(rxfc)
1441

    
1442
            if not self.MODEL == "KT-8R":
1443
                txdisp = RadioSetting("settings.txdisp",
1444
                                      "Transmitting status display",
1445
                                      RadioSettingValueList(
1446
                                          LIST_TXDISP,
1447
                                          LIST_TXDISP[_mem.settings.txdisp]))
1448
                basic.append(txdisp)
1449
        else:
1450
            wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1451
                                 RadioSettingValueList(
1452
                                     LIST_COLOR4,
1453
                                     LIST_COLOR4[_mem.settings.wtled]))
1454
            basic.append(wtled)
1455

    
1456
            rxled = RadioSetting("settings.rxled", "RX backlight Color",
1457
                                 RadioSettingValueList(
1458
                                     LIST_COLOR4,
1459
                                     LIST_COLOR4[_mem.settings.rxled]))
1460
            basic.append(rxled)
1461

    
1462
            txled = RadioSetting("settings.txled", "TX backlight Color",
1463
                                 RadioSettingValueList(
1464
                                     LIST_COLOR4,
1465
                                     LIST_COLOR4[_mem.settings.txled]))
1466
            basic.append(txled)
1467

    
1468
        anil = RadioSetting("settings.anil", "ANI length",
1469
                            RadioSettingValueList(
1470
                                LIST_ANIL,
1471
                                LIST_ANIL[_mem.settings.anil]))
1472
        basic.append(anil)
1473

    
1474
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1475
                            RadioSettingValueList(
1476
                                LIST_REPS,
1477
                                LIST_REPS[_mem.settings.reps]))
1478
        basic.append(reps)
1479

    
1480
        if not self.MODEL == "GMRS-50X1" and not self.MODEL == "KT-8R":
1481
            repm = RadioSetting("settings.repm", "Relay condition",
1482
                                RadioSettingValueList(
1483
                                    LIST_REPM,
1484
                                    LIST_REPM[_mem.settings.repm]))
1485
            basic.append(repm)
1486

    
1487
        if self.VENDOR == "BTECH" or self.COLOR_LCD:
1488
            if self.COLOR_LCD:
1489
                tmrmr = RadioSetting("settings.tmrmr", "TMR return time",
1490
                                     RadioSettingValueList(
1491
                                         LIST_OFF1TO50,
1492
                                         LIST_OFF1TO50[_mem.settings.tmrmr]))
1493
                basic.append(tmrmr)
1494
            else:
1495
                tdrab = RadioSetting("settings.tdrab", "TDR return time",
1496
                                     RadioSettingValueList(
1497
                                         LIST_OFF1TO50,
1498
                                         LIST_OFF1TO50[_mem.settings.tdrab]))
1499
                basic.append(tdrab)
1500

    
1501
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1502
                               RadioSettingValueBoolean(_mem.settings.ste))
1503
            basic.append(ste)
1504

    
1505
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1506
                                 RadioSettingValueList(
1507
                                     LIST_OFF1TO9,
1508
                                     LIST_OFF1TO9[_mem.settings.rpste]))
1509
            basic.append(rpste)
1510

    
1511
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1512
                                 RadioSettingValueList(
1513
                                     LIST_RPTDL,
1514
                                     LIST_RPTDL[_mem.settings.rptdl]))
1515
            basic.append(rptdl)
1516

    
1517
        if str(_mem.fingerprint.fp) in BTECH3:
1518
            mgain = RadioSetting("settings.mgain", "Mic gain",
1519
                                 RadioSettingValueInteger(0, 120,
1520
                                                          _mem.settings.mgain))
1521
            basic.append(mgain)
1522

    
1523
        if str(_mem.fingerprint.fp) in BTECH3 or self.COLOR_LCD:
1524
            dtmfg = RadioSetting("settings.dtmfg", "DTMF gain",
1525
                                 RadioSettingValueInteger(0, 60,
1526
                                                          _mem.settings.dtmfg))
1527
            basic.append(dtmfg)
1528

    
1529
        if self.VENDOR == "BTECH" and self.COLOR_LCD:
1530
            mgain = RadioSetting("settings.mgain", "Mic gain",
1531
                                 RadioSettingValueInteger(0, 120,
1532
                                                          _mem.settings.mgain))
1533
            basic.append(mgain)
1534

    
1535
            skiptx = RadioSetting("settings.skiptx", "Skip TX",
1536
                                  RadioSettingValueList(
1537
                                      LIST_SKIPTX,
1538
                                      LIST_SKIPTX[_mem.settings.skiptx]))
1539
            basic.append(skiptx)
1540

    
1541
            scmode = RadioSetting("settings.scmode", "Scan mode",
1542
                                  RadioSettingValueList(
1543
                                      LIST_SCMODE,
1544
                                      LIST_SCMODE[_mem.settings.scmode]))
1545
            basic.append(scmode)
1546

    
1547
        if self.MODEL == "KT-8R":
1548
            tmrtx = RadioSetting("settings.tmrtx", "TX in multi-standby",
1549
                                  RadioSettingValueList(
1550
                                      LIST_TMRTX,
1551
                                      LIST_TMRTX[_mem.settings.tmrtx]))
1552
            basic.append(tmrtx)
1553

    
1554
        # Advanced
1555
        def _filter(name):
1556
            filtered = ""
1557
            for char in str(name):
1558
                if char in VALID_CHARS:
1559
                    filtered += char
1560
                else:
1561
                    filtered += " "
1562
            return filtered
1563

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

    
1624
        if self.MODEL in ("UV-2501", "UV-5001"):
1625
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1626
                                   RadioSettingValueBoolean(
1627
                                       _mem.settings2.vfomren))
1628
            advanced.append(vfomren)
1629

    
1630
            reseten = RadioSetting("settings2.reseten", "RESET",
1631
                                   RadioSettingValueBoolean(
1632
                                       _mem.settings2.reseten))
1633
            advanced.append(reseten)
1634

    
1635
            menuen = RadioSetting("settings2.menuen", "Menu",
1636
                                  RadioSettingValueBoolean(
1637
                                      _mem.settings2.menuen))
1638
            advanced.append(menuen)
1639

    
1640
        # Other
1641
        def convert_bytes_to_limit(bytes):
1642
            limit = ""
1643
            for byte in bytes:
1644
                if byte < 10:
1645
                    limit += chr(byte + 0x30)
1646
                else:
1647
                    break
1648
            return limit
1649

    
1650
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1651
            _ranges = self._memobj.ranges220
1652
            ranges = "ranges220"
1653
        else:
1654
            _ranges = self._memobj.ranges
1655
            ranges = "ranges"
1656

    
1657
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1658
        val = RadioSettingValueString(0, 3, _limit)
1659
        val.set_mutable(False)
1660
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1661
        other.append(vhf_low)
1662

    
1663
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1664
        val = RadioSettingValueString(0, 3, _limit)
1665
        val.set_mutable(False)
1666
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1667
        other.append(vhf_high)
1668

    
1669
        if self.BANDS == 3 or self.BANDS == 4:
1670
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1671
            val = RadioSettingValueString(0, 3, _limit)
1672
            val.set_mutable(False)
1673
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1674
            other.append(vhf2_low)
1675

    
1676
            _limit = convert_bytes_to_limit(_ranges.vhf2_high)
1677
            val = RadioSettingValueString(0, 3, _limit)
1678
            val.set_mutable(False)
1679
            vhf2_high = RadioSetting("%s.vhf2_high" % ranges, "VHF2 high", val)
1680
            other.append(vhf2_high)
1681

    
1682
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1683
        val = RadioSettingValueString(0, 3, _limit)
1684
        val.set_mutable(False)
1685
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1686
        other.append(uhf_low)
1687

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

    
1694
        if self.BANDS == 4:
1695
            _limit = convert_bytes_to_limit(_ranges.uhf2_low)
1696
            val = RadioSettingValueString(0, 3, _limit)
1697
            val.set_mutable(False)
1698
            uhf2_low = RadioSetting("%s.uhf2_low" % ranges, "UHF2 low", val)
1699
            other.append(uhf2_low)
1700

    
1701
            _limit = convert_bytes_to_limit(_ranges.uhf2_high)
1702
            val = RadioSettingValueString(0, 3, _limit)
1703
            val.set_mutable(False)
1704
            uhf2_high = RadioSetting("%s.uhf2_high" % ranges, "UHF2 high", val)
1705
            other.append(uhf2_high)
1706

    
1707
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1708
        val.set_mutable(False)
1709
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1710
        other.append(fp)
1711

    
1712
        # Work
1713
        if self.COLOR_LCD:
1714
            dispab = RadioSetting("settings2.dispab", "Display",
1715
                                  RadioSettingValueList(
1716
                                      LIST_ABCD,
1717
                                      LIST_ABCD[_mem.settings2.dispab]))
1718
            work.append(dispab)
1719
        else:
1720
            dispab = RadioSetting("settings2.dispab", "Display",
1721
                                  RadioSettingValueList(
1722
                                      LIST_AB,
1723
                                      LIST_AB[_mem.settings2.dispab]))
1724
            work.append(dispab)
1725

    
1726
        if self.COLOR_LCD:
1727
            vfomra = RadioSetting("settings2.vfomra", "VFO/MR A mode",
1728
                                  RadioSettingValueList(
1729
                                      LIST_VFOMR,
1730
                                      LIST_VFOMR[_mem.settings2.vfomra]))
1731
            work.append(vfomra)
1732

    
1733
            vfomrb = RadioSetting("settings2.vfomrb", "VFO/MR B mode",
1734
                                  RadioSettingValueList(
1735
                                      LIST_VFOMR,
1736
                                      LIST_VFOMR[_mem.settings2.vfomrb]))
1737
            work.append(vfomrb)
1738

    
1739
            vfomrc = RadioSetting("settings2.vfomrc", "VFO/MR C mode",
1740
                                  RadioSettingValueList(
1741
                                      LIST_VFOMR,
1742
                                      LIST_VFOMR[_mem.settings2.vfomrc]))
1743
            work.append(vfomrc)
1744

    
1745
            vfomrd = RadioSetting("settings2.vfomrd", "VFO/MR D mode",
1746
                                  RadioSettingValueList(
1747
                                      LIST_VFOMR,
1748
                                      LIST_VFOMR[_mem.settings2.vfomrd]))
1749
            work.append(vfomrd)
1750
        else:
1751
            vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1752
                                 RadioSettingValueList(
1753
                                     LIST_VFOMR,
1754
                                     LIST_VFOMR[_mem.settings2.vfomr]))
1755
            work.append(vfomr)
1756

    
1757
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1758
                               RadioSettingValueBoolean(
1759
                                   _mem.settings2.keylock))
1760
        work.append(keylock)
1761

    
1762
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1763
                             RadioSettingValueInteger(0, self._upper,
1764
                                                      _mem.settings2.mrcha))
1765
        work.append(mrcha)
1766

    
1767
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1768
                             RadioSettingValueInteger(0, self._upper,
1769
                                                      _mem.settings2.mrchb))
1770
        work.append(mrchb)
1771

    
1772
        if self.COLOR_LCD:
1773
            mrchc = RadioSetting("settings2.mrchc", "MR C channel",
1774
                                 RadioSettingValueInteger(
1775
                                     0, self._upper, _mem.settings2.mrchc))
1776
            work.append(mrchc)
1777

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

    
1783
        def convert_bytes_to_freq(bytes):
1784
            real_freq = 0
1785
            for byte in bytes:
1786
                real_freq = (real_freq * 10) + byte
1787
            return chirp_common.format_freq(real_freq * 10)
1788

    
1789
        def my_validate(value):
1790
            _vhf_lower = int(convert_bytes_to_limit(_ranges.vhf_low))
1791
            _vhf_upper = int(convert_bytes_to_limit(_ranges.vhf_high))
1792
            _uhf_lower = int(convert_bytes_to_limit(_ranges.uhf_low))
1793
            _uhf_upper = int(convert_bytes_to_limit(_ranges.uhf_high))
1794
            if self.BANDS == 3 or self.BANDS == 4:
1795
                _vhf2_lower = int(convert_bytes_to_limit(_ranges.vhf2_low))
1796
                _vhf2_upper = int(convert_bytes_to_limit(_ranges.vhf2_high))
1797
            if self.BANDS == 4:
1798
                _uhf2_lower = int(convert_bytes_to_limit(_ranges.uhf2_low))
1799
                _uhf2_upper = int(convert_bytes_to_limit(_ranges.uhf2_high))
1800

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

    
1832
        def apply_freq(setting, obj):
1833
            value = chirp_common.parse_freq(str(setting.value)) / 10
1834
            for i in range(7, -1, -1):
1835
                obj.freq[i] = value % 10
1836
                value /= 10
1837

    
1838
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1839
                                        _mem.vfo.a.freq))
1840
        val1a.set_validate_callback(my_validate)
1841
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1842
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1843
        work.append(vfoafreq)
1844

    
1845
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1846
                                        _mem.vfo.b.freq))
1847
        val1b.set_validate_callback(my_validate)
1848
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1849
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1850
        work.append(vfobfreq)
1851

    
1852
        if self.COLOR_LCD:
1853
            val1c = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1854
                                            _mem.vfo.c.freq))
1855
            val1c.set_validate_callback(my_validate)
1856
            vfocfreq = RadioSetting("vfo.c.freq", "VFO C frequency", val1c)
1857
            vfocfreq.set_apply_callback(apply_freq, _mem.vfo.c)
1858
            work.append(vfocfreq)
1859

    
1860
            val1d = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1861
                                            _mem.vfo.d.freq))
1862
            val1d.set_validate_callback(my_validate)
1863
            vfodfreq = RadioSetting("vfo.d.freq", "VFO D frequency", val1d)
1864
            vfodfreq.set_apply_callback(apply_freq, _mem.vfo.d)
1865
            work.append(vfodfreq)
1866

    
1867
        if not self.MODEL == "GMRS-50X1":
1868
            vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1869
                                      RadioSettingValueList(
1870
                                          LIST_SHIFT,
1871
                                          LIST_SHIFT[_mem.vfo.a.shiftd]))
1872
            work.append(vfoashiftd)
1873

    
1874
            vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1875
                                      RadioSettingValueList(
1876
                                          LIST_SHIFT,
1877
                                          LIST_SHIFT[_mem.vfo.b.shiftd]))
1878
            work.append(vfobshiftd)
1879

    
1880
            if self.COLOR_LCD:
1881
                vfocshiftd = RadioSetting("vfo.c.shiftd", "VFO C shift",
1882
                                          RadioSettingValueList(
1883
                                              LIST_SHIFT,
1884
                                              LIST_SHIFT[_mem.vfo.c.shiftd]))
1885
                work.append(vfocshiftd)
1886

    
1887
                vfodshiftd = RadioSetting("vfo.d.shiftd", "VFO D shift",
1888
                                          RadioSettingValueList(
1889
                                              LIST_SHIFT,
1890
                                              LIST_SHIFT[_mem.vfo.d.shiftd]))
1891
                work.append(vfodshiftd)
1892

    
1893
        def convert_bytes_to_offset(bytes):
1894
            real_offset = 0
1895
            for byte in bytes:
1896
                real_offset = (real_offset * 10) + byte
1897
            return chirp_common.format_freq(real_offset * 1000)
1898

    
1899
        def apply_offset(setting, obj):
1900
            value = chirp_common.parse_freq(str(setting.value)) / 1000
1901
            for i in range(5, -1, -1):
1902
                obj.offset[i] = value % 10
1903
                value /= 10
1904

    
1905
        if not self.MODEL == "GMRS-50X1":
1906
            if self.COLOR_LCD:
1907
                val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1908
                                                _mem.vfo.a.offset))
1909
                vfoaoffset = RadioSetting("vfo.a.offset",
1910
                                          "VFO A offset (0.000-999.999)",
1911
                                          val1a)
1912
                vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1913
                work.append(vfoaoffset)
1914

    
1915
                val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1916
                                                _mem.vfo.b.offset))
1917
                vfoboffset = RadioSetting("vfo.b.offset",
1918
                                          "VFO B offset (0.000-999.999)",
1919
                                          val1b)
1920
                vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1921
                work.append(vfoboffset)
1922

    
1923
                val1c = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1924
                                                _mem.vfo.c.offset))
1925
                vfocoffset = RadioSetting("vfo.c.offset",
1926
                                          "VFO C offset (0.000-999.999)",
1927
                                          val1c)
1928
                vfocoffset.set_apply_callback(apply_offset, _mem.vfo.c)
1929
                work.append(vfocoffset)
1930

    
1931
                val1d = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1932
                                                _mem.vfo.d.offset))
1933
                vfodoffset = RadioSetting("vfo.d.offset",
1934
                                          "VFO D offset (0.000-999.999)",
1935
                                          val1d)
1936
                vfodoffset.set_apply_callback(apply_offset, _mem.vfo.d)
1937
                work.append(vfodoffset)
1938
            else:
1939
                val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1940
                                                _mem.vfo.a.offset))
1941
                vfoaoffset = RadioSetting("vfo.a.offset",
1942
                                          "VFO A offset (0.000-99.999)", val1a)
1943
                vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1944
                work.append(vfoaoffset)
1945

    
1946
                val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1947
                                                _mem.vfo.b.offset))
1948
                vfoboffset = RadioSetting("vfo.b.offset",
1949
                                          "VFO B offset (0.000-99.999)", val1b)
1950
                vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1951
                work.append(vfoboffset)
1952

    
1953
        if not self.MODEL == "GMRS-50X1":
1954
            vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1955
                                   RadioSettingValueList(
1956
                                       LIST_TXP,
1957
                                       LIST_TXP[_mem.vfo.a.power]))
1958
            work.append(vfoatxp)
1959

    
1960
            vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1961
                                   RadioSettingValueList(
1962
                                       LIST_TXP,
1963
                                       LIST_TXP[_mem.vfo.b.power]))
1964
            work.append(vfobtxp)
1965

    
1966
            if self.COLOR_LCD:
1967
                vfoctxp = RadioSetting("vfo.c.power", "VFO C power",
1968
                                       RadioSettingValueList(
1969
                                           LIST_TXP,
1970
                                           LIST_TXP[_mem.vfo.c.power]))
1971
                work.append(vfoctxp)
1972

    
1973
                vfodtxp = RadioSetting("vfo.d.power", "VFO D power",
1974
                                       RadioSettingValueList(
1975
                                           LIST_TXP,
1976
                                           LIST_TXP[_mem.vfo.d.power]))
1977
                work.append(vfodtxp)
1978

    
1979
        if not self.MODEL == "GMRS-50X1":
1980
            vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1981
                                    RadioSettingValueList(
1982
                                        LIST_WIDE,
1983
                                        LIST_WIDE[_mem.vfo.a.wide]))
1984
            work.append(vfoawide)
1985

    
1986
            vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1987
                                    RadioSettingValueList(
1988
                                        LIST_WIDE,
1989
                                        LIST_WIDE[_mem.vfo.b.wide]))
1990
            work.append(vfobwide)
1991

    
1992
            if self.COLOR_LCD:
1993
                vfocwide = RadioSetting("vfo.c.wide", "VFO C bandwidth",
1994
                                        RadioSettingValueList(
1995
                                            LIST_WIDE,
1996
                                            LIST_WIDE[_mem.vfo.c.wide]))
1997
                work.append(vfocwide)
1998

    
1999
                vfodwide = RadioSetting("vfo.d.wide", "VFO D bandwidth",
2000
                                        RadioSettingValueList(
2001
                                            LIST_WIDE,
2002
                                            LIST_WIDE[_mem.vfo.d.wide]))
2003
                work.append(vfodwide)
2004

    
2005
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
2006
                                RadioSettingValueList(
2007
                                    LIST_STEP,
2008
                                    LIST_STEP[_mem.vfo.a.step]))
2009
        work.append(vfoastep)
2010

    
2011
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
2012
                                RadioSettingValueList(
2013
                                    LIST_STEP,
2014
                                    LIST_STEP[_mem.vfo.b.step]))
2015
        work.append(vfobstep)
2016

    
2017
        if self.COLOR_LCD:
2018
            vfocstep = RadioSetting("vfo.c.step", "VFO C step",
2019
                                    RadioSettingValueList(
2020
                                        LIST_STEP,
2021
                                        LIST_STEP[_mem.vfo.c.step]))
2022
            work.append(vfocstep)
2023

    
2024
            vfodstep = RadioSetting("vfo.d.step", "VFO D step",
2025
                                    RadioSettingValueList(
2026
                                        LIST_STEP,
2027
                                        LIST_STEP[_mem.vfo.d.step]))
2028
            work.append(vfodstep)
2029

    
2030
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
2031
                                  RadioSettingValueList(
2032
                                      OPTSIG_LIST,
2033
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
2034
        work.append(vfoaoptsig)
2035

    
2036
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
2037
                                  RadioSettingValueList(
2038
                                      OPTSIG_LIST,
2039
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
2040
        work.append(vfoboptsig)
2041

    
2042
        if self.COLOR_LCD:
2043
            vfocoptsig = RadioSetting("vfo.c.optsig", "VFO C optional signal",
2044
                                      RadioSettingValueList(
2045
                                          OPTSIG_LIST,
2046
                                          OPTSIG_LIST[_mem.vfo.c.optsig]))
2047
            work.append(vfocoptsig)
2048

    
2049
            vfodoptsig = RadioSetting("vfo.d.optsig", "VFO D optional signal",
2050
                                      RadioSettingValueList(
2051
                                          OPTSIG_LIST,
2052
                                          OPTSIG_LIST[_mem.vfo.d.optsig]))
2053
            work.append(vfodoptsig)
2054

    
2055
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
2056
                                  RadioSettingValueList(
2057
                                      SPMUTE_LIST,
2058
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
2059
        work.append(vfoaspmute)
2060

    
2061
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
2062
                                  RadioSettingValueList(
2063
                                      SPMUTE_LIST,
2064
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
2065
        work.append(vfobspmute)
2066

    
2067
        if self.COLOR_LCD:
2068
            vfocspmute = RadioSetting("vfo.c.spmute", "VFO C speaker mute",
2069
                                      RadioSettingValueList(
2070
                                          SPMUTE_LIST,
2071
                                          SPMUTE_LIST[_mem.vfo.c.spmute]))
2072
            work.append(vfocspmute)
2073

    
2074
            vfodspmute = RadioSetting("vfo.d.spmute", "VFO D speaker mute",
2075
                                      RadioSettingValueList(
2076
                                          SPMUTE_LIST,
2077
                                          SPMUTE_LIST[_mem.vfo.d.spmute]))
2078
            work.append(vfodspmute)
2079

    
2080
        if not self.COLOR_LCD or \
2081
                (self.COLOR_LCD and not self.VENDOR == "BTECH"):
2082
            vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
2083
                                   RadioSettingValueBoolean(
2084
                                       _mem.vfo.a.scramble))
2085
            work.append(vfoascr)
2086

    
2087
            vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
2088
                                   RadioSettingValueBoolean(
2089
                                       _mem.vfo.b.scramble))
2090
            work.append(vfobscr)
2091

    
2092
        if self.COLOR_LCD and not self.VENDOR == "BTECH":
2093
            vfocscr = RadioSetting("vfo.c.scramble", "VFO C scramble",
2094
                                   RadioSettingValueBoolean(
2095
                                       _mem.vfo.c.scramble))
2096
            work.append(vfocscr)
2097

    
2098
            vfodscr = RadioSetting("vfo.d.scramble", "VFO D scramble",
2099
                                   RadioSettingValueBoolean(
2100
                                       _mem.vfo.d.scramble))
2101
            work.append(vfodscr)
2102

    
2103
        if not self.MODEL == "GMRS-50X1":
2104
            vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
2105
                                     RadioSettingValueList(
2106
                                         PTTIDCODE_LIST,
2107
                                         PTTIDCODE_LIST[_mem.vfo.a.scode]))
2108
            work.append(vfoascode)
2109

    
2110
            vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
2111
                                     RadioSettingValueList(
2112
                                         PTTIDCODE_LIST,
2113
                                         PTTIDCODE_LIST[_mem.vfo.b.scode]))
2114
            work.append(vfobscode)
2115

    
2116
            if self.COLOR_LCD:
2117
                vfocscode = RadioSetting("vfo.c.scode", "VFO C PTT-ID",
2118
                                         RadioSettingValueList(
2119
                                             PTTIDCODE_LIST,
2120
                                             PTTIDCODE_LIST[_mem.vfo.c.scode]))
2121
                work.append(vfocscode)
2122

    
2123
                vfodscode = RadioSetting("vfo.d.scode", "VFO D PTT-ID",
2124
                                         RadioSettingValueList(
2125
                                             PTTIDCODE_LIST,
2126
                                             PTTIDCODE_LIST[_mem.vfo.d.scode]))
2127
                work.append(vfodscode)
2128

    
2129
        if not self.MODEL == "GMRS-50X1":
2130
            pttid = RadioSetting("settings.pttid", "PTT ID",
2131
                                 RadioSettingValueList(
2132
                                     PTTID_LIST,
2133
                                     PTTID_LIST[_mem.settings.pttid]))
2134
            work.append(pttid)
2135

    
2136
        if not self.COLOR_LCD:
2137
            # FM presets
2138
            fm_presets = RadioSettingGroup("fm_presets", "FM Presets")
2139
            top.append(fm_presets)
2140

    
2141
            def fm_validate(value):
2142
                if value == 0:
2143
                    return chirp_common.format_freq(value)
2144
                if not (87.5 <= value and value <= 108.0):  # 87.5-108MHz
2145
                    msg = ("FM-Preset-Frequency: " +
2146
                           "Must be between 87.5 and 108 MHz")
2147
                    raise InvalidValueError(msg)
2148
                return value
2149

    
2150
            def apply_fm_preset_name(setting, obj):
2151
                valstring = str(setting.value)
2152
                for i in range(0, 6):
2153
                    if valstring[i] in VALID_CHARS:
2154
                        obj[i] = valstring[i]
2155
                    else:
2156
                        obj[i] = '0xff'
2157

    
2158
            def apply_fm_freq(setting, obj):
2159
                value = chirp_common.parse_freq(str(setting.value)) / 10
2160
                for i in range(7, -1, -1):
2161
                    obj.freq[i] = value % 10
2162
                    value /= 10
2163

    
2164
            _presets = self._memobj.fm_radio_preset
2165
            i = 1
2166
            for preset in _presets:
2167
                line = RadioSetting("fm_presets_" + str(i),
2168
                                    "Station name " + str(i),
2169
                                    RadioSettingValueString(0, 6, _filter(
2170
                                        preset.broadcast_station_name)))
2171
                line.set_apply_callback(apply_fm_preset_name,
2172
                                        preset.broadcast_station_name)
2173

    
2174
                val = RadioSettingValueFloat(0, 108,
2175
                                             convert_bytes_to_freq(
2176
                                                 preset.freq))
2177
                fmfreq = RadioSetting("fm_presets_" + str(i) + "_freq",
2178
                                      "Frequency " + str(i), val)
2179
                val.set_validate_callback(fm_validate)
2180
                fmfreq.set_apply_callback(apply_fm_freq, preset)
2181
                fm_presets.append(line)
2182
                fm_presets.append(fmfreq)
2183

    
2184
                i = i + 1
2185

    
2186
        """
2187
        # DTMF-Setting
2188
        dtmf_enc_settings = RadioSettingGroup("dtmf_enc_settings",
2189
                                              "DTMF Encoding Settings")
2190
        dtmf_dec_settings = RadioSettingGroup("dtmf_dec_settings",
2191
                                              "DTMF Decoding Settings")
2192
        top.append(dtmf_enc_settings)
2193
        top.append(dtmf_dec_settings)
2194
        txdisable = RadioSetting("dtmf_settings.txdisable",
2195
                                 "TX-Disable",
2196
                                 RadioSettingValueBoolean(
2197
                                     _mem.dtmf_settings.txdisable))
2198
        dtmf_enc_settings.append(txdisable)
2199

    
2200
        rxdisable = RadioSetting("dtmf_settings.rxdisable",
2201
                                 "RX-Disable",
2202
                                 RadioSettingValueBoolean(
2203
                                     _mem.dtmf_settings.rxdisable))
2204
        dtmf_enc_settings.append(rxdisable)
2205

    
2206
        dtmfspeed_on = RadioSetting(
2207
            "dtmf_settings.dtmfspeed_on",
2208
            "DTMF Speed (On Time)",
2209
            RadioSettingValueList(LIST_DTMF_SPEED,
2210
                                  LIST_DTMF_SPEED[
2211
                                      _mem.dtmf_settings.dtmfspeed_on]))
2212
        dtmf_enc_settings.append(dtmfspeed_on)
2213

    
2214
        dtmfspeed_off = RadioSetting(
2215
            "dtmf_settings.dtmfspeed_off",
2216
            "DTMF Speed (Off Time)",
2217
            RadioSettingValueList(LIST_DTMF_SPEED,
2218
                                  LIST_DTMF_SPEED[
2219
                                      _mem.dtmf_settings.dtmfspeed_off]))
2220
        dtmf_enc_settings.append(dtmfspeed_off)
2221

    
2222
        def memory2string(dmtf_mem):
2223
            dtmf_string = ""
2224
            for digit in dmtf_mem:
2225
                if digit != 255:
2226
                    index = LIST_DTMF_VALUES.index(digit)
2227
                    dtmf_string = dtmf_string + LIST_DTMF_DIGITS[index]
2228
            return dtmf_string
2229

    
2230
        def apply_dmtf_frame(setting, obj):
2231
            LOG.debug("Setting DTMF-Code: " + str(setting.value))
2232
            val_string = str(setting.value)
2233
            for i in range(0, 16):
2234
                obj[i] = 255
2235
            i = 0
2236
            for current_char in val_string:
2237
                current_char = current_char.upper()
2238
                index = LIST_DTMF_DIGITS.index(current_char)
2239
                obj[i] = LIST_DTMF_VALUES[index]
2240
                i = i + 1
2241

    
2242
        codes = self._memobj.dtmf_codes
2243
        i = 1
2244
        for dtmfcode in codes:
2245
            val = RadioSettingValueString(0, 16, memory2string(
2246
                                              dtmfcode.code),
2247
                                          False, CHARSET_DTMF_DIGITS)
2248
            line = RadioSetting("dtmf_code_" + str(i) + "_code",
2249
                                "DMTF Code " + str(i), val)
2250
            line.set_apply_callback(apply_dmtf_frame, dtmfcode.code)
2251
            dtmf_enc_settings.append(line)
2252
            i = i + 1
2253

    
2254
        line = RadioSetting("dtmf_settings.mastervice",
2255
                            "Master and Vice ID",
2256
                            RadioSettingValueBoolean(
2257
                                _mem.dtmf_settings.mastervice))
2258
        dtmf_dec_settings.append(line)
2259

    
2260
        val = RadioSettingValueString(0, 16, memory2string(
2261
                                          _mem.dtmf_settings.masterid),
2262
                                      False, CHARSET_DTMF_DIGITS)
2263
        line = RadioSetting("dtmf_settings.masterid",
2264
                            "Master Control ID ", val)
2265
        line.set_apply_callback(apply_dmtf_frame,
2266
                                _mem.dtmf_settings.masterid)
2267
        dtmf_dec_settings.append(line)
2268

    
2269
        line = RadioSetting("dtmf_settings.minspection",
2270
                            "Master Inspection",
2271
                            RadioSettingValueBoolean(
2272
                                _mem.dtmf_settings.minspection))
2273
        dtmf_dec_settings.append(line)
2274

    
2275
        line = RadioSetting("dtmf_settings.mmonitor",
2276
                            "Master Monitor",
2277
                            RadioSettingValueBoolean(
2278
                                _mem.dtmf_settings.mmonitor))
2279
        dtmf_dec_settings.append(line)
2280

    
2281
        line = RadioSetting("dtmf_settings.mstun",
2282
                            "Master Stun",
2283
                            RadioSettingValueBoolean(
2284
                                _mem.dtmf_settings.mstun))
2285
        dtmf_dec_settings.append(line)
2286

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

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

    
2299
        val = RadioSettingValueString(0, 16, memory2string(
2300
                                          _mem.dtmf_settings.viceid),
2301
                                      False, CHARSET_DTMF_DIGITS)
2302
        line = RadioSetting("dtmf_settings.viceid",
2303
                            "Vice Control ID ", val)
2304
        line.set_apply_callback(apply_dmtf_frame,
2305
                                _mem.dtmf_settings.viceid)
2306
        dtmf_dec_settings.append(line)
2307

    
2308
        line = RadioSetting("dtmf_settings.vinspection",
2309
                            "Vice Inspection",
2310
                            RadioSettingValueBoolean(
2311
                                _mem.dtmf_settings.vinspection))
2312
        dtmf_dec_settings.append(line)
2313

    
2314
        line = RadioSetting("dtmf_settings.vmonitor",
2315
                            "Vice Monitor",
2316
                            RadioSettingValueBoolean(
2317
                                _mem.dtmf_settings.vmonitor))
2318
        dtmf_dec_settings.append(line)
2319

    
2320
        line = RadioSetting("dtmf_settings.vstun",
2321
                            "Vice Stun",
2322
                            RadioSettingValueBoolean(
2323
                                _mem.dtmf_settings.vstun))
2324
        dtmf_dec_settings.append(line)
2325

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

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

    
2338
        val = RadioSettingValueString(0, 16, memory2string(
2339
                                          _mem.dtmf_settings.inspection),
2340
                                      False, CHARSET_DTMF_DIGITS)
2341
        line = RadioSetting("dtmf_settings.inspection",
2342
                            "Inspection", val)
2343
        line.set_apply_callback(apply_dmtf_frame,
2344
                                _mem.dtmf_settings.inspection)
2345
        dtmf_dec_settings.append(line)
2346

    
2347
        val = RadioSettingValueString(0, 16, memory2string(
2348
                                          _mem.dtmf_settings.alarmcode),
2349
                                      False, CHARSET_DTMF_DIGITS)
2350
        line = RadioSetting("dtmf_settings.alarmcode",
2351
                            "Alarm", val)
2352
        line.set_apply_callback(apply_dmtf_frame,
2353
                                _mem.dtmf_settings.alarmcode)
2354
        dtmf_dec_settings.append(line)
2355

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

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

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

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

    
2392
        def apply_dmtf_listvalue(setting, obj):
2393
            LOG.debug("Setting value: " + str(setting.value) + " from list")
2394
            val = str(setting.value)
2395
            index = LIST_DTMF_SPECIAL_DIGITS.index(val)
2396
            val = LIST_DTMF_SPECIAL_VALUES[index]
2397
            obj.set_value(val)
2398

    
2399
        idx = LIST_DTMF_SPECIAL_VALUES.index(_mem.dtmf_settings.groupcode)
2400
        line = RadioSetting(
2401
            "dtmf_settings.groupcode",
2402
            "Group Code",
2403
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2404
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2405
        line.set_apply_callback(apply_dmtf_listvalue,
2406
                                _mem.dtmf_settings.groupcode)
2407
        dtmf_dec_settings.append(line)
2408

    
2409
        idx = LIST_DTMF_SPECIAL_VALUES.index(_mem.dtmf_settings.spacecode)
2410
        line = RadioSetting(
2411
            "dtmf_settings.spacecode",
2412
            "Space Code",
2413
            RadioSettingValueList(LIST_DTMF_SPECIAL_DIGITS,
2414
                                  LIST_DTMF_SPECIAL_DIGITS[idx]))
2415
        line.set_apply_callback(apply_dmtf_listvalue,
2416
                                _mem.dtmf_settings.spacecode)
2417
        dtmf_dec_settings.append(line)
2418

    
2419
        if self.COLOR_LCD:
2420
            line = RadioSetting(
2421
                "dtmf_settings.resettime",
2422
                "Reset time",
2423
                RadioSettingValueList(LIST_5TONE_RESET_COLOR,
2424
                                      LIST_5TONE_RESET_COLOR[
2425
                                          _mem.dtmf_settings.resettime]))
2426
            dtmf_dec_settings.append(line)
2427
        else:
2428
            line = RadioSetting(
2429
                "dtmf_settings.resettime",
2430
                "Reset time",
2431
                RadioSettingValueList(LIST_5TONE_RESET,
2432
                                      LIST_5TONE_RESET[
2433
                                          _mem.dtmf_settings.resettime]))
2434
            dtmf_dec_settings.append(line)
2435

    
2436
        line = RadioSetting(
2437
            "dtmf_settings.delayproctime",
2438
            "Delay processing time",
2439
            RadioSettingValueList(LIST_DTMF_DELAY,
2440
                                  LIST_DTMF_DELAY[
2441
                                      _mem.dtmf_settings.delayproctime]))
2442
        dtmf_dec_settings.append(line)
2443

    
2444
        # 5 Tone Settings
2445
        stds_5tone = RadioSettingGroup("stds_5tone", "Standards")
2446
        codes_5tone = RadioSettingGroup("codes_5tone", "Codes")
2447

    
2448
        group_5tone = RadioSettingGroup("group_5tone", "5 Tone Settings")
2449
        group_5tone.append(stds_5tone)
2450
        group_5tone.append(codes_5tone)
2451

    
2452
        top.append(group_5tone)
2453

    
2454
        def apply_list_value(setting, obj):
2455
            options = setting.value.get_options()
2456
            obj.set_value(options.index(str(setting.value)))
2457

    
2458
        _5tone_standards = self._memobj._5tone_std_settings
2459
        i = 0
2460
        for standard in _5tone_standards:
2461
            std_5tone = RadioSettingGroup("std_5tone_" + str(i),
2462
                                          LIST_5TONE_STANDARDS[i])
2463
            stds_5tone.append(std_5tone)
2464

    
2465
            period = standard.period
2466
            if period == 255:
2467
                LOG.debug("Period for " + LIST_5TONE_STANDARDS[i] +
2468
                          " is not yet configured. Setting to 70ms.")
2469
                period = 5
2470

    
2471
            if period <= len(LIST_5TONE_STANDARD_PERIODS):
2472
                line = RadioSetting(
2473
                    "_5tone_std_settings_" + str(i) + "_period",
2474
                    "Period (ms)", RadioSettingValueList
2475
                    (LIST_5TONE_STANDARD_PERIODS,
2476
                     LIST_5TONE_STANDARD_PERIODS[period]))
2477
                line.set_apply_callback(apply_list_value, standard.period)
2478
                std_5tone.append(line)
2479
            else:
2480
                LOG.debug("Invalid value for 5tone period! Disabling.")
2481

    
2482
            group_tone = standard.group_tone
2483
            if group_tone == 255:
2484
                LOG.debug("Group-Tone for " + LIST_5TONE_STANDARDS[i] +
2485
                          " is not yet configured. Setting to A.")
2486
                group_tone = 10
2487

    
2488
            if group_tone <= len(LIST_5TONE_DIGITS):
2489
                line = RadioSetting(
2490
                    "_5tone_std_settings_" + str(i) + "_grouptone",
2491
                    "Group Tone",
2492
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2493
                                          LIST_5TONE_DIGITS[
2494
                                              group_tone]))
2495
                line.set_apply_callback(apply_list_value,
2496
                                        standard.group_tone)
2497
                std_5tone.append(line)
2498
            else:
2499
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2500

    
2501
            repeat_tone = standard.repeat_tone
2502
            if repeat_tone == 255:
2503
                LOG.debug("Repeat-Tone for " + LIST_5TONE_STANDARDS[i] +
2504
                          " is not yet configured. Setting to E.")
2505
                repeat_tone = 14
2506

    
2507
            if repeat_tone <= len(LIST_5TONE_DIGITS):
2508
                line = RadioSetting(
2509
                    "_5tone_std_settings_" + str(i) + "_repttone",
2510
                    "Repeat Tone",
2511
                    RadioSettingValueList(LIST_5TONE_DIGITS,
2512
                                          LIST_5TONE_DIGITS[
2513
                                              repeat_tone]))
2514
                line.set_apply_callback(apply_list_value,
2515
                                        standard.repeat_tone)
2516
                std_5tone.append(line)
2517
            else:
2518
                LOG.debug("Invalid value for 5tone digit! Disabling.")
2519
            i = i + 1
2520

    
2521
        def my_apply_5tonestdlist_value(setting, obj):
2522
            if LIST_5TONE_STANDARDS.index(str(setting.value)) == 15:
2523
                obj.set_value(0xFF)
2524
            else:
2525
                obj.set_value(LIST_5TONE_STANDARDS.
2526
                              index(str(setting.value)))
2527

    
2528
        def apply_5tone_frame(setting, obj):
2529
            LOG.debug("Setting 5 Tone: " + str(setting.value))
2530
            valstring = str(setting.value)
2531
            if len(valstring) == 0:
2532
                for i in range(0, 5):
2533
                    obj[i] = 255
2534
            else:
2535
                validFrame = True
2536
                for i in range(0, 5):
2537
                    currentChar = valstring[i].upper()
2538
                    if currentChar in LIST_5TONE_DIGITS:
2539
                        obj[i] = LIST_5TONE_DIGITS.index(currentChar)
2540
                    else:
2541
                        validFrame = False
2542
                        LOG.debug("invalid char: " + str(currentChar))
2543
                if not validFrame:
2544
                    LOG.debug("setting whole frame to FF")
2545
                    for i in range(0, 5):
2546
                        obj[i] = 255
2547

    
2548
        def validate_5tone_frame(value):
2549
            if (len(str(value)) != 5) and (len(str(value)) != 0):
2550
                msg = ("5 Tone must have 5 digits or 0 digits")
2551
                raise InvalidValueError(msg)
2552
            for digit in str(value):
2553
                if digit.upper() not in LIST_5TONE_DIGITS:
2554
                    msg = (str(digit) + " is not a valid digit for 5tones")
2555
                    raise InvalidValueError(msg)
2556
            return value
2557

    
2558
        def frame2string(frame):
2559
            frameString = ""
2560
            for digit in frame:
2561
                if digit != 255:
2562
                    frameString = frameString + LIST_5TONE_DIGITS[digit]
2563
            return frameString
2564

    
2565
        _5tone_codes = self._memobj._5tone_codes
2566
        i = 1
2567
        for code in _5tone_codes:
2568
            code_5tone = RadioSettingGroup("code_5tone_" + str(i),
2569
                                           "5 Tone code " + str(i))
2570
            codes_5tone.append(code_5tone)
2571
            if (code.standard == 255):
2572
                currentVal = 15
2573
            else:
2574
                currentVal = code.standard
2575
            line = RadioSetting("_5tone_code_" + str(i) + "_std",
2576
                                " Standard",
2577
                                RadioSettingValueList(LIST_5TONE_STANDARDS,
2578
                                                      LIST_5TONE_STANDARDS[
2579
                                                          currentVal]))
2580
            line.set_apply_callback(my_apply_5tonestdlist_value,
2581
                                    code.standard)
2582
            code_5tone.append(line)
2583

    
2584
            val = RadioSettingValueString(0, 6,
2585
                                          frame2string(code.frame1), False)
2586
            line = RadioSetting("_5tone_code_" + str(i) + "_frame1",
2587
                                " Frame 1", val)
2588
            val.set_validate_callback(validate_5tone_frame)
2589
            line.set_apply_callback(apply_5tone_frame, code.frame1)
2590
            code_5tone.append(line)
2591

    
2592
            val = RadioSettingValueString(0, 6,
2593
                                          frame2string(code.frame2), False)
2594
            line = RadioSetting("_5tone_code_" + str(i) + "_frame2",
2595
                                " Frame 2", val)
2596
            val.set_validate_callback(validate_5tone_frame)
2597
            line.set_apply_callback(apply_5tone_frame, code.frame2)
2598
            code_5tone.append(line)
2599

    
2600
            val = RadioSettingValueString(0, 6,
2601
                                          frame2string(code.frame3), False)
2602
            line = RadioSetting("_5tone_code_" + str(i) + "_frame3",
2603
                                " Frame 3", val)
2604
            val.set_validate_callback(validate_5tone_frame)
2605
            line.set_apply_callback(apply_5tone_frame, code.frame3)
2606
            code_5tone.append(line)
2607
            i = i + 1
2608

    
2609
        _5_tone_decode1 = RadioSetting(
2610
            "_5tone_settings._5tone_decode_call_frame1",
2611
            "5 Tone decode call Frame 1",
2612
            RadioSettingValueBoolean(
2613
                _mem._5tone_settings._5tone_decode_call_frame1))
2614
        group_5tone.append(_5_tone_decode1)
2615

    
2616
        _5_tone_decode2 = RadioSetting(
2617
            "_5tone_settings._5tone_decode_call_frame2",
2618
            "5 Tone decode call Frame 2",
2619
            RadioSettingValueBoolean(
2620
                _mem._5tone_settings._5tone_decode_call_frame2))
2621
        group_5tone.append(_5_tone_decode2)
2622

    
2623
        _5_tone_decode3 = RadioSetting(
2624
            "_5tone_settings._5tone_decode_call_frame3",
2625
            "5 Tone decode call Frame 3",
2626
            RadioSettingValueBoolean(
2627
                _mem._5tone_settings._5tone_decode_call_frame3))
2628
        group_5tone.append(_5_tone_decode3)
2629

    
2630
        _5_tone_decode_disp1 = RadioSetting(
2631
            "_5tone_settings._5tone_decode_disp_frame1",
2632
            "5 Tone decode disp Frame 1",
2633
            RadioSettingValueBoolean(
2634
                _mem._5tone_settings._5tone_decode_disp_frame1))
2635
        group_5tone.append(_5_tone_decode_disp1)
2636

    
2637
        _5_tone_decode_disp2 = RadioSetting(
2638
            "_5tone_settings._5tone_decode_disp_frame2",
2639
            "5 Tone decode disp Frame 2",
2640
            RadioSettingValueBoolean(
2641
                _mem._5tone_settings._5tone_decode_disp_frame2))
2642
        group_5tone.append(_5_tone_decode_disp2)
2643

    
2644
        _5_tone_decode_disp3 = RadioSetting(
2645
            "_5tone_settings._5tone_decode_disp_frame3",
2646
            "5 Tone decode disp Frame 3",
2647
            RadioSettingValueBoolean(
2648
                _mem._5tone_settings._5tone_decode_disp_frame3))
2649
        group_5tone.append(_5_tone_decode_disp3)
2650

    
2651
        decode_standard = _mem._5tone_settings.decode_standard
2652
        if decode_standard == 255:
2653
            decode_standard = 0
2654
        if decode_standard <= len(LIST_5TONE_STANDARDS_without_none):
2655
            line = RadioSetting("_5tone_settings.decode_standard",
2656
                                "5 Tone-decode Standard",
2657
                                RadioSettingValueList(
2658
                                    LIST_5TONE_STANDARDS_without_none,
2659
                                    LIST_5TONE_STANDARDS_without_none[
2660
                                        decode_standard]))
2661
            group_5tone.append(line)
2662
        else:
2663
            LOG.debug("Invalid decode std...")
2664

    
2665
        _5tone_delay1 = _mem._5tone_settings._5tone_delay1
2666
        if _5tone_delay1 == 255:
2667
            _5tone_delay1 = 20
2668

    
2669
        if _5tone_delay1 <= len(LIST_5TONE_DELAY):
2670
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2671
                                         LIST_5TONE_DELAY[
2672
                                             _5tone_delay1])
2673
            line = RadioSetting("_5tone_settings._5tone_delay1",
2674
                                "5 Tone Delay Frame 1", list)
2675
            group_5tone.append(line)
2676
        else:
2677
            LOG.debug("Invalid value for 5tone delay (frame1) ! Disabling.")
2678

    
2679
        _5tone_delay2 = _mem._5tone_settings._5tone_delay2
2680
        if _5tone_delay2 == 255:
2681
            _5tone_delay2 = 20
2682
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2683

    
2684
        if _5tone_delay2 <= len(LIST_5TONE_DELAY):
2685
            list = RadioSettingValueList(LIST_5TONE_DELAY,
2686
                                         LIST_5TONE_DELAY[
2687
                                             _5tone_delay2])
2688
            line = RadioSetting("_5tone_settings._5tone_delay2",
2689
                                "5 Tone Delay Frame 2", list)
2690
            group_5tone.append(line)
2691
        else:
2692
            LOG.debug("Invalid value for 5tone delay (frame2)! Disabling.")
2693

    
2694
        _5tone_delay3 = _mem._5tone_settings._5tone_delay3
2695
        if _5tone_delay3 == 255:
2696
            _5tone_delay3 = 20
2697
            LOG.debug("5 Tone delay unconfigured! Resetting to 200ms.")
2698

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

    
2709
        ext_length = _mem._5tone_settings._5tone_first_digit_ext_length
2710
        if ext_length == 255:
2711
            ext_length = 0
2712
            LOG.debug("1st Tone ext lenght unconfigured! Resetting to 0")
2713

    
2714
        if ext_length <= len(LIST_5TONE_DELAY):
2715
            list = RadioSettingValueList(
2716
                LIST_5TONE_DELAY,
2717
                LIST_5TONE_DELAY[
2718
                    ext_length])
2719
            line = RadioSetting(
2720
                "_5tone_settings._5tone_first_digit_ext_length",
2721
                "First digit extend length", list)
2722
            group_5tone.append(line)
2723
        else:
2724
            LOG.debug("Invalid value for 5tone ext length! Disabling.")
2725

    
2726
        decode_reset_time = _mem._5tone_settings.decode_reset_time
2727
        if decode_reset_time == 255:
2728
            decode_reset_time = 59
2729
            LOG.debug("Decode reset time unconfigured. resetting.")
2730
        if decode_reset_time <= len(LIST_5TONE_RESET):
2731
            list = RadioSettingValueList(
2732
                LIST_5TONE_RESET,
2733
                LIST_5TONE_RESET[
2734
                    decode_reset_time])
2735
            line = RadioSetting("_5tone_settings.decode_reset_time",
2736
                                "Decode reset time", list)
2737
            group_5tone.append(line)
2738
        else:
2739
            LOG.debug("Invalid value decode reset time! Disabling.")
2740

    
2741
        # 2 Tone
2742
        encode_2tone = RadioSettingGroup("encode_2tone", "2 Tone Encode")
2743
        decode_2tone = RadioSettingGroup("decode_2tone", "2 Code Decode")
2744

    
2745
        top.append(encode_2tone)
2746
        top.append(decode_2tone)
2747

    
2748
        duration_1st_tone = self._memobj._2tone.duration_1st_tone
2749
        if duration_1st_tone == 255:
2750
            LOG.debug("Duration of first 2 Tone digit is not yet " +
2751
                      "configured. Setting to 600ms")
2752
            duration_1st_tone = 60
2753

    
2754
        if duration_1st_tone <= len(LIST_5TONE_DELAY):
2755
            line = RadioSetting("_2tone.duration_1st_tone",
2756
                                "Duration 1st Tone",
2757
                                RadioSettingValueList(LIST_5TONE_DELAY,
2758
                                                      LIST_5TONE_DELAY[
2759
                                                          duration_1st_tone]))
2760
            encode_2tone.append(line)
2761

    
2762
        duration_2nd_tone = self._memobj._2tone.duration_2nd_tone
2763
        if duration_2nd_tone == 255:
2764
            LOG.debug("Duration of second 2 Tone digit is not yet " +
2765
                      "configured. Setting to 600ms")
2766
            duration_2nd_tone = 60
2767

    
2768
        if duration_2nd_tone <= len(LIST_5TONE_DELAY):
2769
            line = RadioSetting("_2tone.duration_2nd_tone",
2770
                                "Duration 2nd Tone",
2771
                                RadioSettingValueList(LIST_5TONE_DELAY,
2772
                                                      LIST_5TONE_DELAY[
2773
                                                          duration_2nd_tone]))
2774
            encode_2tone.append(line)
2775

    
2776
        duration_gap = self._memobj._2tone.duration_gap
2777
        if duration_gap == 255:
2778
            LOG.debug("Duration of gap is not yet " +
2779
                      "configured. Setting to 300ms")
2780
            duration_gap = 30
2781

    
2782
        if duration_gap <= len(LIST_5TONE_DELAY):
2783
            line = RadioSetting("_2tone.duration_gap", "Duration of gap",
2784
                                RadioSettingValueList(LIST_5TONE_DELAY,
2785
                                                      LIST_5TONE_DELAY[
2786
                                                          duration_gap]))
2787
            encode_2tone.append(line)
2788

    
2789
        def _2tone_validate(value):
2790
            if value == 0:
2791
                return 65535
2792
            if value == 65535:
2793
                return value
2794
            if not (300 <= value and value <= 3000):
2795
                msg = ("2 Tone Frequency: Must be between 300 and 3000 Hz")
2796
                raise InvalidValueError(msg)
2797
            return value
2798

    
2799
        def apply_2tone_freq(setting, obj):
2800
            val = int(setting.value)
2801
            if (val == 0) or (val == 65535):
2802
                obj.set_value(65535)
2803
            else:
2804
                obj.set_value(val)
2805

    
2806
        i = 1
2807
        for code in self._memobj._2tone._2tone_encode:
2808
            code_2tone = RadioSettingGroup("code_2tone_" + str(i),
2809
                                           "Encode Code " + str(i))
2810
            encode_2tone.append(code_2tone)
2811

    
2812
            tmp = code.freq1
2813
            if tmp == 65535:
2814
                tmp = 0
2815
            val1 = RadioSettingValueInteger(0, 65535, tmp)
2816
            freq1 = RadioSetting("2tone_code_" + str(i) + "_freq1",
2817
                                 "Frequency 1", val1)
2818
            val1.set_validate_callback(_2tone_validate)
2819
            freq1.set_apply_callback(apply_2tone_freq, code.freq1)
2820
            code_2tone.append(freq1)
2821

    
2822
            tmp = code.freq2
2823
            if tmp == 65535:
2824
                tmp = 0
2825
            val2 = RadioSettingValueInteger(0, 65535, tmp)
2826
            freq2 = RadioSetting("2tone_code_" + str(i) + "_freq2",
2827
                                 "Frequency 2", val2)
2828
            val2.set_validate_callback(_2tone_validate)
2829
            freq2.set_apply_callback(apply_2tone_freq, code.freq2)
2830
            code_2tone.append(freq2)
2831

    
2832
            i = i + 1
2833

    
2834
        decode_reset_time = _mem._2tone.reset_time
2835
        if decode_reset_time == 255:
2836
            decode_reset_time = 59
2837
            LOG.debug("Decode reset time unconfigured. resetting.")
2838
        if decode_reset_time <= len(LIST_5TONE_RESET):
2839
            list = RadioSettingValueList(
2840
                LIST_5TONE_RESET,
2841
                LIST_5TONE_RESET[
2842
                    decode_reset_time])
2843
            line = RadioSetting("_2tone.reset_time",
2844
                                "Decode reset time", list)
2845
            decode_2tone.append(line)
2846
        else:
2847
            LOG.debug("Invalid value decode reset time! Disabling.")
2848

    
2849
        def apply_2tone_freq_pair(setting, obj):
2850
            val = int(setting.value)
2851
            derived_val = 65535
2852
            frqname = str(setting._name[-5:])
2853
            derivedname = "derived_from_" + frqname
2854

    
2855
            if (val == 0):
2856
                val = 65535
2857
                derived_val = 65535
2858
            else:
2859
                derived_val = int(round(2304000.0/val))
2860

    
2861
            obj[frqname].set_value(val)
2862
            obj[derivedname].set_value(derived_val)
2863

    
2864
            LOG.debug("Apply " + frqname + ": " + str(val) + " | " +
2865
                      derivedname + ": " + str(derived_val))
2866

    
2867
        i = 1
2868
        for decode_code in self._memobj._2tone._2tone_decode:
2869
            _2tone_dec_code = RadioSettingGroup("code_2tone_" + str(i),
2870
                                                "Decode Code " + str(i))
2871
            decode_2tone.append(_2tone_dec_code)
2872

    
2873
            j = 1
2874
            for dec in decode_code.decs:
2875
                val = dec.dec
2876
                if val == 255:
2877
                    LOG.debug("Dec for Code " + str(i) + " Dec " + str(j) +
2878
                              " is not yet configured. Setting to 0.")
2879
                    val = 0
2880

    
2881
                if val <= len(LIST_2TONE_DEC):
2882
                    line = RadioSetting(
2883
                        "_2tone_dec_settings_" + str(i) + "_dec_" + str(j),
2884
                        "Dec " + str(j), RadioSettingValueList
2885
                        (LIST_2TONE_DEC,
2886
                         LIST_2TONE_DEC[val]))
2887
                    line.set_apply_callback(apply_list_value, dec.dec)
2888
                    _2tone_dec_code.append(line)
2889
                else:
2890
                    LOG.debug("Invalid value for 2tone dec! Disabling.")
2891

    
2892
                val = dec.response
2893
                if val == 255:
2894
                    LOG.debug("Response for Code " + str(i) + " Dec " +
2895
                              str(j) + " is not yet configured. Setting to 0.")
2896
                    val = 0
2897

    
2898
                if val <= len(LIST_2TONE_RESPONSE):
2899
                    line = RadioSetting(
2900
                        "_2tone_dec_settings_" + str(i) + "_resp_" + str(j),
2901
                        "Response " + str(j), RadioSettingValueList
2902
                        (LIST_2TONE_RESPONSE,
2903
                         LIST_2TONE_RESPONSE[val]))
2904
                    line.set_apply_callback(apply_list_value, dec.response)
2905
                    _2tone_dec_code.append(line)
2906
                else:
2907
                    LOG.debug("Invalid value for 2tone response! Disabling.")
2908

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

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

    
2927
            freq = self._memobj._2tone.freqs[i-1]
2928
            for char in ['A', 'B', 'C', 'D']:
2929
                setting_name = "freq" + str(char)
2930

    
2931
                tmp = freq[setting_name]
2932
                if tmp == 65535:
2933
                    tmp = 0
2934
                if tmp != 0:
2935
                    expected = int(round(2304000.0/tmp))
2936
                    from_mem = freq["derived_from_" + setting_name]
2937
                    if expected != from_mem:
2938
                        LOG.error("Expected " + str(expected) +
2939
                                  " but read " + str(from_mem) +
2940
                                  ". Disabling 2Tone Decode Freqs!")
2941
                        break
2942
                val = RadioSettingValueInteger(0, 65535, tmp)
2943
                frq = RadioSetting("2tone_dec_" + str(i) + "_freq" + str(char),
2944
                                   ("Decode Frequency " + str(char)), val)
2945
                val.set_validate_callback(_2tone_validate)
2946
                frq.set_apply_callback(apply_2tone_freq_pair, freq)
2947
                _2tone_dec_code.append(frq)
2948

    
2949
            i = i + 1
2950
        """
2951

    
2952
        return top
2953

    
2954
    def set_settings(self, settings):
2955
        _settings = self._memobj.settings
2956
        for element in settings:
2957
            if not isinstance(element, RadioSetting):
2958
                if element.get_name() == "fm_preset":
2959
                    self._set_fm_preset(element)
2960
                else:
2961
                    self.set_settings(element)
2962
                    continue
2963
            else:
2964
                try:
2965
                    name = element.get_name()
2966
                    if "." in name:
2967
                        bits = name.split(".")
2968
                        obj = self._memobj
2969
                        for bit in bits[:-1]:
2970
                            if "/" in bit:
2971
                                bit, index = bit.split("/", 1)
2972
                                index = int(index)
2973
                                obj = getattr(obj, bit)[index]
2974
                            else:
2975
                                obj = getattr(obj, bit)
2976
                        setting = bits[-1]
2977
                    else:
2978
                        obj = _settings
2979
                        setting = element.get_name()
2980

    
2981
                    if element.has_apply_callback():
2982
                        LOG.debug("Using apply callback")
2983
                        element.run_apply_callback()
2984
                    elif element.value.get_mutable():
2985
                        LOG.debug("Setting %s = %s" % (setting, element.value))
2986
                        setattr(obj, setting, element.value)
2987
                except Exception, e:
2988
                    LOG.debug(element.get_name())
2989
                    raise
2990

    
2991
    @classmethod
2992
    def match_model(cls, filedata, filename):
2993
        match_size = False
2994
        match_model = False
2995

    
2996
        # testing the file data size
2997
        if len(filedata) == MEM_SIZE:
2998
            match_size = True
2999

    
3000
        # testing the firmware model fingerprint
3001
        match_model = model_match(cls, filedata)
3002

    
3003
        if match_size and match_model:
3004
            return True
3005
        else:
3006
            return False
3007

    
3008

    
3009
MEM_FORMAT = """
3010
#seekto 0x0000;
3011
struct {
3012
  lbcd rxfreq[4];
3013
  lbcd txfreq[4];
3014
  ul16 rxtone;
3015
  ul16 txtone;
3016
  u8 unknown0:4,
3017
     scode:4;
3018
  u8 unknown1:2,
3019
     spmute:1,
3020
     unknown2:3,
3021
     optsig:2;
3022
  u8 unknown3:3,
3023
     scramble:1,
3024
     unknown4:3,
3025
     power:1;
3026
  u8 unknown5:1,
3027
     wide:1,
3028
     unknown6:2,
3029
     bcl:1,
3030
     add:1,
3031
     pttid:2;
3032
} memory[200];
3033

    
3034
#seekto 0x0E00;
3035
struct {
3036
  u8 tdr;
3037
  u8 unknown1;
3038
  u8 sql;
3039
  u8 unknown2[2];
3040
  u8 tot;
3041
  u8 apo;           // BTech radios use this as the Auto Power Off time
3042
                    // other radios use this as pre-Time Out Alert
3043
  u8 unknown3;
3044
  u8 abr;
3045
  u8 beep;
3046
  u8 unknown4[4];
3047
  u8 dtmfst;
3048
  u8 unknown5[2];
3049
  u8 prisc;
3050
  u8 prich;
3051
  u8 screv;
3052
  u8 unknown6[2];
3053
  u8 pttid;
3054
  u8 pttlt;
3055
  u8 unknown7;
3056
  u8 emctp;
3057
  u8 emcch;
3058
  u8 ringt;
3059
  u8 unknown8;
3060
  u8 camdf;
3061
  u8 cbmdf;
3062
  u8 sync;          // BTech radios use this as the display sync setting
3063
                    // other radios use this as the auto keypad lock setting
3064
  u8 ponmsg;
3065
  u8 wtled;
3066
  u8 rxled;
3067
  u8 txled;
3068
  u8 unknown9[5];
3069
  u8 anil;
3070
  u8 reps;
3071
  u8 repm;
3072
  u8 tdrab;
3073
  u8 ste;
3074
  u8 rpste;
3075
  u8 rptdl;
3076
  u8 mgain;
3077
  u8 dtmfg;
3078
} settings;
3079

    
3080
#seekto 0x0E80;
3081
struct {
3082
  u8 unknown1;
3083
  u8 vfomr;
3084
  u8 keylock;
3085
  u8 unknown2;
3086
  u8 unknown3:4,
3087
     vfomren:1,
3088
     unknown4:1,
3089
     reseten:1,
3090
     menuen:1;
3091
  u8 unknown5[11];
3092
  u8 dispab;
3093
  u8 mrcha;
3094
  u8 mrchb;
3095
  u8 menu;
3096
} settings2;
3097

    
3098
#seekto 0x0EC0;
3099
struct {
3100
  char line1[6];
3101
  char line2[6];
3102
} poweron_msg;
3103

    
3104
struct settings_vfo {
3105
  u8 freq[8];
3106
  u8 offset[6];
3107
  u8 unknown2[2];
3108
  ul16 rxtone;
3109
  ul16 txtone;
3110
  u8 scode;
3111
  u8 spmute;
3112
  u8 optsig;
3113
  u8 scramble;
3114
  u8 wide;
3115
  u8 power;
3116
  u8 shiftd;
3117
  u8 step;
3118
  u8 unknown3[4];
3119
};
3120

    
3121
#seekto 0x0F00;
3122
struct {
3123
  struct settings_vfo a;
3124
  struct settings_vfo b;
3125
} vfo;
3126

    
3127
#seekto 0x1000;
3128
struct {
3129
  char name[6];
3130
  u8 unknown1[10];
3131
} names[200];
3132

    
3133
#seekto 0x2400;
3134
struct {
3135
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3136
  u8 group_tone;
3137
  u8 repeat_tone;
3138
  u8 unused[13];
3139
} _5tone_std_settings[15];
3140

    
3141
#seekto 0x2500;
3142
struct {
3143
  u8 frame1[5];
3144
  u8 frame2[5];
3145
  u8 frame3[5];
3146
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3147
} _5tone_codes[15];
3148

    
3149
#seekto 0x25F0;
3150
struct {
3151
  u8 _5tone_delay1; // * 10ms
3152
  u8 _5tone_delay2; // * 10ms
3153
  u8 _5tone_delay3; // * 10ms
3154
  u8 _5tone_first_digit_ext_length;
3155
  u8 unknown1;
3156
  u8 unknown2;
3157
  u8 unknown3;
3158
  u8 unknown4;
3159
  u8 decode_standard;
3160
  u8 unknown5:5,
3161
     _5tone_decode_call_frame3:1,
3162
     _5tone_decode_call_frame2:1,
3163
     _5tone_decode_call_frame1:1;
3164
  u8 unknown6:5,
3165
     _5tone_decode_disp_frame3:1,
3166
     _5tone_decode_disp_frame2:1,
3167
     _5tone_decode_disp_frame1:1;
3168
  u8 decode_reset_time; // * 100 + 100ms
3169
} _5tone_settings;
3170

    
3171
#seekto 0x2900;
3172
struct {
3173
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3174
} dtmf_codes[15];
3175

    
3176
#seekto 0x29F0;
3177
struct {
3178
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
3179
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
3180
  u8 unknown0[14];
3181
  u8 inspection[16];
3182
  u8 monitor[16];
3183
  u8 alarmcode[16];
3184
  u8 stun[16];
3185
  u8 kill[16];
3186
  u8 revive[16];
3187
  u8 unknown1[16];
3188
  u8 unknown2[16];
3189
  u8 unknown3[16];
3190
  u8 unknown4[16];
3191
  u8 unknown5[16];
3192
  u8 unknown6[16];
3193
  u8 unknown7[16];
3194
  u8 masterid[16];
3195
  u8 viceid[16];
3196
  u8 unused01:7,
3197
     mastervice:1;
3198
  u8 unused02:3,
3199
     mrevive:1,
3200
     mkill:1,
3201
     mstun:1,
3202
     mmonitor:1,
3203
     minspection:1;
3204
  u8 unused03:3,
3205
     vrevive:1,
3206
     vkill:1,
3207
     vstun:1,
3208
     vmonitor:1,
3209
     vinspection:1;
3210
  u8 unused04:6,
3211
     txdisable:1,
3212
     rxdisable:1;
3213
  u8 groupcode;
3214
  u8 spacecode;
3215
  u8 delayproctime; // * 100 + 100ms
3216
  u8 resettime;     // * 100 + 100ms
3217
} dtmf_settings;
3218

    
3219
#seekto 0x2D00;
3220
struct {
3221
  struct {
3222
    ul16 freq1;
3223
    u8 unused01[6];
3224
    ul16 freq2;
3225
    u8 unused02[6];
3226
  } _2tone_encode[15];
3227
  u8 duration_1st_tone; // *10ms
3228
  u8 duration_2nd_tone; // *10ms
3229
  u8 duration_gap;      // *10ms
3230
  u8 unused03[13];
3231
  struct {
3232
    struct {
3233
      u8 dec;      // one out of LIST_2TONE_DEC
3234
      u8 response; // one out of LIST_2TONE_RESPONSE
3235
      u8 alert;    // 1-16
3236
    } decs[4];
3237
    u8 unused04[4];
3238
  } _2tone_decode[15];
3239
  u8 unused05[16];
3240

    
3241
  struct {
3242
    ul16 freqA;
3243
    ul16 freqB;
3244
    ul16 freqC;
3245
    ul16 freqD;
3246
    // unknown what those values mean, but they are
3247
    // derived from configured frequencies
3248
    ul16 derived_from_freqA; // 2304000/freqA
3249
    ul16 derived_from_freqB; // 2304000/freqB
3250
    ul16 derived_from_freqC; // 2304000/freqC
3251
    ul16 derived_from_freqD; // 2304000/freqD
3252
  }freqs[15];
3253
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
3254
} _2tone;
3255

    
3256
#seekto 0x3000;
3257
struct {
3258
  u8 freq[8];
3259
  char broadcast_station_name[6];
3260
  u8 unknown[2];
3261
} fm_radio_preset[16];
3262

    
3263
#seekto 0x3C90;
3264
struct {
3265
  u8 vhf_low[3];
3266
  u8 vhf_high[3];
3267
  u8 uhf_low[3];
3268
  u8 uhf_high[3];
3269
} ranges;
3270

    
3271
// the UV-2501+220 & KT8900R has different zones for storing ranges
3272

    
3273
#seekto 0x3CD0;
3274
struct {
3275
  u8 vhf_low[3];
3276
  u8 vhf_high[3];
3277
  u8 unknown1[4];
3278
  u8 unknown2[6];
3279
  u8 vhf2_low[3];
3280
  u8 vhf2_high[3];
3281
  u8 unknown3[4];
3282
  u8 unknown4[6];
3283
  u8 uhf_low[3];
3284
  u8 uhf_high[3];
3285
} ranges220;
3286

    
3287
#seekto 0x3F70;
3288
struct {
3289
  char fp[6];
3290
} fingerprint;
3291

    
3292
"""
3293

    
3294

    
3295
class BTech(BTechMobileCommon):
3296
    """BTECH's UV-5001 and alike radios"""
3297
    BANDS = 2
3298
    COLOR_LCD = False
3299
    NAME_LENGTH = 6
3300

    
3301
    def set_options(self):
3302
        """This is to read the options from the image and set it in the
3303
        environment, for now just the limits of the freqs in the VHF/UHF
3304
        ranges"""
3305

    
3306
        # setting the correct ranges for each radio type
3307
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3308
            # the model 2501+220 has a segment in 220
3309
            # and a different position in the memmap
3310
            # also the QYT KT8900R
3311
            ranges = self._memobj.ranges220
3312
        else:
3313
            ranges = self._memobj.ranges
3314

    
3315
        # the normal dual bands
3316
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3317
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3318

    
3319
        # DEBUG
3320
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3321
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3322

    
3323
        # 220Mhz radios case
3324
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
3325
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3326
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3327
            self._220_range = vhf2
3328

    
3329
        # set the class with the real data
3330
        self._vhf_range = vhf
3331
        self._uhf_range = uhf
3332

    
3333
    def process_mmap(self):
3334
        """Process the mem map into the mem object"""
3335

    
3336
        # Get it
3337
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
3338

    
3339
        # load specific parameters from the radio image
3340
        self.set_options()
3341

    
3342

    
3343
# Declaring Aliases (Clones of the real radios)
3344
class JT2705M(chirp_common.Alias):
3345
    VENDOR = "Jetstream"
3346
    MODEL = "JT2705M"
3347

    
3348

    
3349
class JT6188Mini(chirp_common.Alias):
3350
    VENDOR = "Juentai"
3351
    MODEL = "JT-6188 Mini"
3352

    
3353

    
3354
class JT6188Plus(chirp_common.Alias):
3355
    VENDOR = "Juentai"
3356
    MODEL = "JT-6188 Plus"
3357

    
3358

    
3359
class SSGT890(chirp_common.Alias):
3360
    VENDOR = "Sainsonic"
3361
    MODEL = "GT-890"
3362

    
3363

    
3364
class ZastoneMP300(chirp_common.Alias):
3365
    VENDOR = "Zastone"
3366
    MODEL = "MP-300"
3367

    
3368

    
3369
# real radios
3370
@directory.register
3371
class UV2501(BTech):
3372
    """Baofeng Tech UV2501"""
3373
    MODEL = "UV-2501"
3374
    _fileid = [UV2501G3_fp,
3375
               UV2501G2_fp,
3376
               UV2501pp2_fp,
3377
               UV2501pp_fp]
3378

    
3379

    
3380
@directory.register
3381
class UV2501_220(BTech):
3382
    """Baofeng Tech UV2501+220"""
3383
    MODEL = "UV-2501+220"
3384
    BANDS = 3
3385
    _magic = MSTRING_220
3386
    _id2 = [UV2501_220pp_id, ]
3387
    _fileid = [UV2501_220G3_fp,
3388
               UV2501_220G2_fp,
3389
               UV2501_220_fp,
3390
               UV2501_220pp_fp]
3391

    
3392

    
3393
@directory.register
3394
class UV5001(BTech):
3395
    """Baofeng Tech UV5001"""
3396
    MODEL = "UV-5001"
3397
    _fileid = [UV5001G3_fp,
3398
               UV5001G22_fp,
3399
               UV5001G2_fp,
3400
               UV5001alpha_fp,
3401
               UV5001pp_fp]
3402
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
3403
                     chirp_common.PowerLevel("Low", watts=10)]
3404

    
3405

    
3406
@directory.register
3407
class MINI8900(BTech):
3408
    """WACCOM MINI-8900"""
3409
    VENDOR = "WACCOM"
3410
    MODEL = "MINI-8900"
3411
    _magic = MSTRING_MINI8900
3412
    _fileid = [MINI8900_fp, ]
3413
    # Clones
3414
    ALIASES = [JT6188Plus, ]
3415

    
3416

    
3417
@directory.register
3418
class KTUV980(BTech):
3419
    """QYT KT-UV980"""
3420
    VENDOR = "QYT"
3421
    MODEL = "KT-UV980"
3422
    _vhf_range = (136000000, 175000000)
3423
    _uhf_range = (400000000, 481000000)
3424
    _magic = MSTRING_MINI8900
3425
    _fileid = [KTUV980_fp, ]
3426
    # Clones
3427
    ALIASES = [JT2705M, ]
3428

    
3429
# Please note that there is a version of this radios that is a clone of the
3430
# Waccom Mini8900, maybe an early version?
3431

    
3432

    
3433
@directory.register
3434
class KT9800(BTech):
3435
    """QYT KT8900"""
3436
    VENDOR = "QYT"
3437
    MODEL = "KT8900"
3438
    _vhf_range = (136000000, 175000000)
3439
    _uhf_range = (400000000, 481000000)
3440
    _magic = MSTRING_KT8900
3441
    _fileid = [KT8900_fp,
3442
               KT8900_fp1,
3443
               KT8900_fp2,
3444
               KT8900_fp3,
3445
               KT8900_fp4,
3446
               KT8900_fp5]
3447
    _id2 = [KT8900_id, ]
3448
    # Clones
3449
    ALIASES = [JT6188Mini, SSGT890, ZastoneMP300]
3450

    
3451

    
3452
@directory.register
3453
class KT9800R(BTech):
3454
    """QYT KT8900R"""
3455
    VENDOR = "QYT"
3456
    MODEL = "KT8900R"
3457
    BANDS = 3
3458
    _vhf_range = (136000000, 175000000)
3459
    _220_range = (240000000, 271000000)
3460
    _uhf_range = (400000000, 481000000)
3461
    _magic = MSTRING_KT8900R
3462
    _fileid = [KT8900R_fp,
3463
               KT8900R_fp1,
3464
               KT8900R_fp2,
3465
               KT8900R_fp3,
3466
               KT8900R_fp4]
3467
    _id2 = [KT8900R_id, KT8900R_id2]
3468

    
3469

    
3470
@directory.register
3471
class LT588UV(BTech):
3472
    """LUITON LT-588UV"""
3473
    VENDOR = "LUITON"
3474
    MODEL = "LT-588UV"
3475
    _vhf_range = (136000000, 175000000)
3476
    _uhf_range = (400000000, 481000000)
3477
    _magic = MSTRING_KT8900
3478
    _fileid = [LT588UV_fp,
3479
               LT588UV_fp1]
3480
    _power_levels = [chirp_common.PowerLevel("High", watts=60),
3481
                     chirp_common.PowerLevel("Low", watts=10)]
3482

    
3483

    
3484
COLOR_MEM_FORMAT = """
3485
#seekto 0x0000;
3486
struct {
3487
  lbcd rxfreq[4];
3488
  lbcd txfreq[4];
3489
  ul16 rxtone;
3490
  ul16 txtone;
3491
  u8 unknown0:4,
3492
     scode:4;
3493
  u8 unknown1:2,
3494
     spmute:1,
3495
     unknown2:3,
3496
     optsig:2;
3497
  u8 unknown3:3,
3498
     scramble:1,
3499
     unknown4:3,
3500
     power:1;
3501
  u8 unknown5:1,
3502
     wide:1,
3503
     unknown6:2,
3504
     bcl:1,
3505
     add:1,
3506
     pttid:2;
3507
} memory[200];
3508

    
3509
#seekto 0x0E00;
3510
struct {
3511
  u8 tmr;
3512
  u8 unknown1;
3513
  u8 sql;
3514
  u8 unknown2[2];
3515
  u8 tot;
3516
  u8 apo;
3517
  u8 unknown3;
3518
  u8 abr;
3519
  u8 beep;
3520
  u8 unknown4[4];
3521
  u8 dtmfst;
3522
  u8 unknown5[2];
3523
  u8 screv;
3524
  u8 unknown6[2];
3525
  u8 pttid;
3526
  u8 pttlt;
3527
  u8 unknown7;
3528
  u8 emctp;
3529
  u8 emcch;
3530
  u8 sigbp;
3531
  u8 unknown8;
3532
  u8 camdf;
3533
  u8 cbmdf;
3534
  u8 ccmdf;
3535
  u8 cdmdf;
3536
  u8 langua;
3537
  u8 sync;          // BTech radios use this as the display sync
3538
                    // setting, other radios use this as the auto
3539
                    // keypad lock setting
3540
  u8 mainfc;
3541
  u8 mainbc;
3542
  u8 menufc;
3543
  u8 menubc;
3544
  u8 stafc;
3545
  u8 stabc;
3546
  u8 sigfc;
3547
  u8 sigbc;
3548
  u8 rxfc;
3549
  u8 txfc;
3550
  u8 txdisp;
3551
  u8 unknown9[5];
3552
  u8 anil;
3553
  u8 reps;
3554
  u8 repm;
3555
  u8 tmrmr;
3556
  u8 ste;
3557
  u8 rpste;
3558
  u8 rptdl;
3559
  u8 dtmfg;
3560
  u8 mgain;
3561
  u8 skiptx;
3562
  u8 scmode;
3563
} settings;
3564

    
3565
#seekto 0x0E80;
3566
struct {
3567
  u8 unknown1;
3568
  u8 vfomr;
3569
  u8 keylock;
3570
  u8 unknown2;
3571
  u8 unknown3:4,
3572
     vfomren:1,
3573
     unknown4:1,
3574
     reseten:1,
3575
     menuen:1;
3576
  u8 unknown5[11];
3577
  u8 dispab;
3578
  u8 unknown6[2];
3579
  u8 menu;
3580
  u8 unknown7[7];
3581
  u8 vfomra;
3582
  u8 vfomrb;
3583
  u8 vfomrc;
3584
  u8 vfomrd;
3585
  u8 mrcha;
3586
  u8 mrchb;
3587
  u8 mrchc;
3588
  u8 mrchd;
3589
} settings2;
3590

    
3591
struct settings_vfo {
3592
  u8 freq[8];
3593
  u8 offset[6];
3594
  u8 unknown2[2];
3595
  ul16 rxtone;
3596
  ul16 txtone;
3597
  u8 scode;
3598
  u8 spmute;
3599
  u8 optsig;
3600
  u8 scramble;
3601
  u8 wide;
3602
  u8 power;
3603
  u8 shiftd;
3604
  u8 step;
3605
  u8 unknown3[4];
3606
};
3607

    
3608
#seekto 0x0F00;
3609
struct {
3610
  struct settings_vfo a;
3611
  struct settings_vfo b;
3612
  struct settings_vfo c;
3613
  struct settings_vfo d;
3614
} vfo;
3615

    
3616
#seekto 0x0F80;
3617
struct {
3618
  char line1[8];
3619
  char line2[8];
3620
  char line3[8];
3621
  char line4[8];
3622
  char line5[8];
3623
  char line6[8];
3624
  char line7[8];
3625
  char line8[8];
3626
} poweron_msg;
3627

    
3628
#seekto 0x1000;
3629
struct {
3630
  char name[8];
3631
  u8 unknown1[8];
3632
} names[200];
3633

    
3634
#seekto 0x2400;
3635
struct {
3636
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3637
  u8 group_tone;
3638
  u8 repeat_tone;
3639
  u8 unused[13];
3640
} _5tone_std_settings[15];
3641

    
3642
#seekto 0x2500;
3643
struct {
3644
  u8 frame1[5];
3645
  u8 frame2[5];
3646
  u8 frame3[5];
3647
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3648
} _5tone_codes[15];
3649

    
3650
#seekto 0x25F0;
3651
struct {
3652
  u8 _5tone_delay1; // * 10ms
3653
  u8 _5tone_delay2; // * 10ms
3654
  u8 _5tone_delay3; // * 10ms
3655
  u8 _5tone_first_digit_ext_length;
3656
  u8 unknown1;
3657
  u8 unknown2;
3658
  u8 unknown3;
3659
  u8 unknown4;
3660
  u8 decode_standard;
3661
  u8 unknown5:5,
3662
     _5tone_decode_call_frame3:1,
3663
     _5tone_decode_call_frame2:1,
3664
     _5tone_decode_call_frame1:1;
3665
  u8 unknown6:5,
3666
     _5tone_decode_disp_frame3:1,
3667
     _5tone_decode_disp_frame2:1,
3668
     _5tone_decode_disp_frame1:1;
3669
  u8 decode_reset_time; // * 100 + 100ms
3670
} _5tone_settings;
3671

    
3672
#seekto 0x2900;
3673
struct {
3674
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3675
} dtmf_codes[15];
3676

    
3677
#seekto 0x29F0;
3678
struct {
3679
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
3680
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
3681
  u8 unknown0[14];
3682
  u8 inspection[16];
3683
  u8 monitor[16];
3684
  u8 alarmcode[16];
3685
  u8 stun[16];
3686
  u8 kill[16];
3687
  u8 revive[16];
3688
  u8 unknown1[16];
3689
  u8 unknown2[16];
3690
  u8 unknown3[16];
3691
  u8 unknown4[16];
3692
  u8 unknown5[16];
3693
  u8 unknown6[16];
3694
  u8 unknown7[16];
3695
  u8 masterid[16];
3696
  u8 viceid[16];
3697
  u8 unused01:7,
3698
     mastervice:1;
3699
  u8 unused02:3,
3700
     mrevive:1,
3701
     mkill:1,
3702
     mstun:1,
3703
     mmonitor:1,
3704
     minspection:1;
3705
  u8 unused03:3,
3706
     vrevive:1,
3707
     vkill:1,
3708
     vstun:1,
3709
     vmonitor:1,
3710
     vinspection:1;
3711
  u8 unused04:6,
3712
     txdisable:1,
3713
     rxdisable:1;
3714
  u8 groupcode;
3715
  u8 spacecode;
3716
  u8 delayproctime; // * 100 + 100ms
3717
  u8 resettime;     // * 100 + 100ms
3718
} dtmf_settings;
3719

    
3720
#seekto 0x2D00;
3721
struct {
3722
  struct {
3723
    ul16 freq1;
3724
    u8 unused01[6];
3725
    ul16 freq2;
3726
    u8 unused02[6];
3727
  } _2tone_encode[15];
3728
  u8 duration_1st_tone; // *10ms
3729
  u8 duration_2nd_tone; // *10ms
3730
  u8 duration_gap;      // *10ms
3731
  u8 unused03[13];
3732
  struct {
3733
    struct {
3734
      u8 dec;      // one out of LIST_2TONE_DEC
3735
      u8 response; // one out of LIST_2TONE_RESPONSE
3736
      u8 alert;    // 1-16
3737
    } decs[4];
3738
    u8 unused04[4];
3739
  } _2tone_decode[15];
3740
  u8 unused05[16];
3741

    
3742
  struct {
3743
    ul16 freqA;
3744
    ul16 freqB;
3745
    ul16 freqC;
3746
    ul16 freqD;
3747
    // unknown what those values mean, but they are
3748
    // derived from configured frequencies
3749
    ul16 derived_from_freqA; // 2304000/freqA
3750
    ul16 derived_from_freqB; // 2304000/freqB
3751
    ul16 derived_from_freqC; // 2304000/freqC
3752
    ul16 derived_from_freqD; // 2304000/freqD
3753
  }freqs[15];
3754
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
3755
} _2tone;
3756

    
3757
#seekto 0x3D80;
3758
struct {
3759
  u8 vhf_low[3];
3760
  u8 vhf_high[3];
3761
  u8 unknown1[4];
3762
  u8 unknown2[6];
3763
  u8 vhf2_low[3];
3764
  u8 vhf2_high[3];
3765
  u8 unknown3[4];
3766
  u8 unknown4[6];
3767
  u8 uhf_low[3];
3768
  u8 uhf_high[3];
3769
  u8 unknown5[4];
3770
  u8 unknown6[6];
3771
  u8 uhf2_low[3];
3772
  u8 uhf2_high[3];
3773
} ranges;
3774

    
3775
#seekto 0x3F70;
3776
struct {
3777
  char fp[6];
3778
} fingerprint;
3779

    
3780
"""
3781

    
3782

    
3783
class BTechColor(BTechMobileCommon):
3784
    """BTECH's Color LCD Mobile and alike radios"""
3785
    COLOR_LCD = True
3786
    NAME_LENGTH = 8
3787
    LIST_TMR = LIST_TMR16
3788

    
3789
    def process_mmap(self):
3790
        """Process the mem map into the mem object"""
3791

    
3792
        # Get it
3793
        self._memobj = bitwise.parse(COLOR_MEM_FORMAT, self._mmap)
3794

    
3795
        # load specific parameters from the radio image
3796
        self.set_options()
3797

    
3798
    def set_options(self):
3799
        """This is to read the options from the image and set it in the
3800
        environment, for now just the limits of the freqs in the VHF/UHF
3801
        ranges"""
3802

    
3803
        # setting the correct ranges for each radio type
3804
        ranges = self._memobj.ranges
3805

    
3806
        # the normal dual bands
3807
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
3808
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
3809

    
3810
        # DEBUG
3811
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
3812
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
3813

    
3814
        # the additional bands
3815
        if self.MODEL in ["UV-25X4", "KT7900D"]:
3816
            # 200Mhz band
3817
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
3818
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
3819
            self._220_range = vhf2
3820

    
3821
            # 350Mhz band
3822
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
3823
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
3824
            self._350_range = uhf2
3825

    
3826
        # set the class with the real data
3827
        self._vhf_range = vhf
3828
        self._uhf_range = uhf
3829

    
3830

    
3831
# Declaring Aliases (Clones of the real radios)
3832
class SKT8900D(chirp_common.Alias):
3833
    VENDOR = "Surecom"
3834
    MODEL = "S-KT8900D"
3835

    
3836

    
3837
class QB25(chirp_common.Alias):
3838
    VENDOR = "Radioddity"
3839
    MODEL = "QB25"
3840

    
3841

    
3842
# real radios
3843
@directory.register
3844
class UV25X2(BTechColor):
3845
    """Baofeng Tech UV25X2"""
3846
    MODEL = "UV-25X2"
3847
    BANDS = 2
3848
    _vhf_range = (130000000, 180000000)
3849
    _uhf_range = (400000000, 521000000)
3850
    _magic = MSTRING_UV25X2
3851
    _fileid = [UV25X2_fp, ]
3852

    
3853

    
3854
@directory.register
3855
class UV25X4(BTechColor):
3856
    """Baofeng Tech UV25X4"""
3857
    MODEL = "UV-25X4"
3858
    BANDS = 4
3859
    _vhf_range = (130000000, 180000000)
3860
    _220_range = (200000000, 271000000)
3861
    _uhf_range = (400000000, 521000000)
3862
    _350_range = (350000000, 391000000)
3863
    _magic = MSTRING_UV25X4
3864
    _fileid = [UV25X4_fp, ]
3865

    
3866

    
3867
@directory.register
3868
class UV50X2(BTechColor):
3869
    """Baofeng Tech UV50X2"""
3870
    MODEL = "UV-50X2"
3871
    BANDS = 2
3872
    _vhf_range = (130000000, 180000000)
3873
    _uhf_range = (400000000, 521000000)
3874
    _magic = MSTRING_UV25X2
3875
    _fileid = [UV50X2_fp, ]
3876
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
3877
                     chirp_common.PowerLevel("Low", watts=10)]
3878

    
3879

    
3880
@directory.register
3881
class KT7900D(BTechColor):
3882
    """QYT KT7900D"""
3883
    VENDOR = "QYT"
3884
    MODEL = "KT7900D"
3885
    BANDS = 4
3886
    LIST_TMR = LIST_TMR15
3887
    _vhf_range = (136000000, 175000000)
3888
    _220_range = (200000000, 271000000)
3889
    _uhf_range = (400000000, 481000000)
3890
    _350_range = (350000000, 371000000)
3891
    _magic = MSTRING_KT8900D
3892
    _fileid = [KT7900D_fp, KT7900D_fp1, KT7900D_fp2, KT7900D_fp3, KT7900D_fp4,
3893
               KT7900D_fp5, QB25_fp, ]
3894
    # Clones
3895
    ALIASES = [SKT8900D, QB25, ]
3896

    
3897

    
3898
@directory.register
3899
class KT8900D(BTechColor):
3900
    """QYT KT8900D"""
3901
    VENDOR = "QYT"
3902
    MODEL = "KT8900D"
3903
    BANDS = 2
3904
    LIST_TMR = LIST_TMR15
3905
    _vhf_range = (136000000, 175000000)
3906
    _uhf_range = (400000000, 481000000)
3907
    _magic = MSTRING_KT8900D
3908
    _fileid = [KT8900D_fp, KT8900D_fp1]
3909

    
3910

    
3911
GMRS_MEM_FORMAT = """
3912
#seekto 0x0000;
3913
struct {
3914
  lbcd rxfreq[4];
3915
  lbcd txfreq[4];
3916
  ul16 rxtone;
3917
  ul16 txtone;
3918
  u8 unknown0:4,
3919
     scode:4;
3920
  u8 unknown1:2,
3921
     spmute:1,
3922
     unknown2:3,
3923
     optsig:2;
3924
  u8 unknown3:3,
3925
     scramble:1,
3926
     unknown4:2,
3927
     power:2;
3928
  u8 unknown5:1,
3929
     wide:1,
3930
     unknown6:2,
3931
     bcl:1,
3932
     add:1,
3933
     pttid:2;
3934
} memory[256];
3935

    
3936
#seekto 0x1000;
3937
struct {
3938
  char name[7];
3939
  u8 unknown1[9];
3940
} names[256];
3941

    
3942
#seekto 0x2400;
3943
struct {
3944
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
3945
  u8 group_tone;
3946
  u8 repeat_tone;
3947
  u8 unused[13];
3948
} _5tone_std_settings[15];
3949

    
3950
#seekto 0x2500;
3951
struct {
3952
  u8 frame1[5];
3953
  u8 frame2[5];
3954
  u8 frame3[5];
3955
  u8 standard;   // one out of LIST_5TONE_STANDARDS
3956
} _5tone_codes[15];
3957

    
3958
#seekto 0x25F0;
3959
struct {
3960
  u8 _5tone_delay1; // * 10ms
3961
  u8 _5tone_delay2; // * 10ms
3962
  u8 _5tone_delay3; // * 10ms
3963
  u8 _5tone_first_digit_ext_length;
3964
  u8 unknown1;
3965
  u8 unknown2;
3966
  u8 unknown3;
3967
  u8 unknown4;
3968
  u8 decode_standard;
3969
  u8 unknown5:5,
3970
     _5tone_decode_call_frame3:1,
3971
     _5tone_decode_call_frame2:1,
3972
     _5tone_decode_call_frame1:1;
3973
  u8 unknown6:5,
3974
     _5tone_decode_disp_frame3:1,
3975
     _5tone_decode_disp_frame2:1,
3976
     _5tone_decode_disp_frame1:1;
3977
  u8 decode_reset_time; // * 100 + 100ms
3978
} _5tone_settings;
3979

    
3980
#seekto 0x2900;
3981
struct {
3982
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
3983
} dtmf_codes[15];
3984

    
3985
#seekto 0x29F0;
3986
struct {
3987
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
3988
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
3989
  u8 unknown0[14];
3990
  u8 inspection[16];
3991
  u8 monitor[16];
3992
  u8 alarmcode[16];
3993
  u8 stun[16];
3994
  u8 kill[16];
3995
  u8 revive[16];
3996
  u8 unknown1[16];
3997
  u8 unknown2[16];
3998
  u8 unknown3[16];
3999
  u8 unknown4[16];
4000
  u8 unknown5[16];
4001
  u8 unknown6[16];
4002
  u8 unknown7[16];
4003
  u8 masterid[16];
4004
  u8 viceid[16];
4005
  u8 unused01:7,
4006
     mastervice:1;
4007
  u8 unused02:3,
4008
     mrevive:1,
4009
     mkill:1,
4010
     mstun:1,
4011
     mmonitor:1,
4012
     minspection:1;
4013
  u8 unused03:3,
4014
     vrevive:1,
4015
     vkill:1,
4016
     vstun:1,
4017
     vmonitor:1,
4018
     vinspection:1;
4019
  u8 unused04:6,
4020
     txdisable:1,
4021
     rxdisable:1;
4022
  u8 groupcode;
4023
  u8 spacecode;
4024
  u8 delayproctime; // * 100 + 100ms
4025
  u8 resettime;     // * 100 + 100ms
4026
} dtmf_settings;
4027

    
4028
#seekto 0x2D00;
4029
struct {
4030
  struct {
4031
    ul16 freq1;
4032
    u8 unused01[6];
4033
    ul16 freq2;
4034
    u8 unused02[6];
4035
  } _2tone_encode[15];
4036
  u8 duration_1st_tone; // *10ms
4037
  u8 duration_2nd_tone; // *10ms
4038
  u8 duration_gap;      // *10ms
4039
  u8 unused03[13];
4040
  struct {
4041
    struct {
4042
      u8 dec;      // one out of LIST_2TONE_DEC
4043
      u8 response; // one out of LIST_2TONE_RESPONSE
4044
      u8 alert;    // 1-16
4045
    } decs[4];
4046
    u8 unused04[4];
4047
  } _2tone_decode[15];
4048
  u8 unused05[16];
4049

    
4050
  struct {
4051
    ul16 freqA;
4052
    ul16 freqB;
4053
    ul16 freqC;
4054
    ul16 freqD;
4055
    // unknown what those values mean, but they are
4056
    // derived from configured frequencies
4057
    ul16 derived_from_freqA; // 2304000/freqA
4058
    ul16 derived_from_freqB; // 2304000/freqB
4059
    ul16 derived_from_freqC; // 2304000/freqC
4060
    ul16 derived_from_freqD; // 2304000/freqD
4061
  }freqs[15];
4062
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
4063
} _2tone;
4064

    
4065
#seekto 0x3000;
4066
struct {
4067
  u8 freq[8];
4068
  char broadcast_station_name[6];
4069
  u8 unknown[2];
4070
} fm_radio_preset[16];
4071

    
4072
#seekto 0x3200;
4073
struct {
4074
  u8 tmr;
4075
  u8 unknown1;
4076
  u8 sql;
4077
  u8 unknown2;
4078
  u8 autolk;
4079
  u8 tot;
4080
  u8 apo;
4081
  u8 unknown3;
4082
  u8 abr;
4083
  u8 beep;
4084
  u8 unknown4[4];
4085
  u8 dtmfst;
4086
  u8 unknown5[2];
4087
  u8 screv;
4088
  u8 unknown6[2];
4089
  u8 pttid;
4090
  u8 pttlt;
4091
  u8 unknown7;
4092
  u8 emctp;
4093
  u8 emcch;
4094
  u8 sigbp;
4095
  u8 unknown8;
4096
  u8 camdf;
4097
  u8 cbmdf;
4098
  u8 ccmdf;
4099
  u8 cdmdf;
4100
  u8 langua;
4101
  u8 sync;
4102

    
4103

    
4104
  u8 stfc;
4105
  u8 mffc;
4106
  u8 sfafc;
4107
  u8 sfbfc;
4108
  u8 sfcfc;
4109
  u8 sfdfc;
4110
  u8 subfc;
4111
  u8 fmfc;
4112
  u8 sigfc;
4113
  u8 modfc;
4114
  u8 menufc;
4115
  u8 txfc;
4116
  u8 txdisp;
4117
  u8 unknown9[5];
4118
  u8 anil;
4119
  u8 reps;
4120
  u8 repm;
4121
  u8 tmrmr;
4122
  u8 ste;
4123
  u8 rpste;
4124
  u8 rptdl;
4125
  u8 dtmfg;
4126
  u8 mgain;
4127
  u8 skiptx;
4128
  u8 scmode;
4129
} settings;
4130

    
4131
#seekto 0x3280;
4132
struct {
4133
  u8 unknown1;
4134
  u8 vfomr;
4135
  u8 keylock;
4136
  u8 unknown2;
4137
  u8 unknown3:4,
4138
     vfomren:1,
4139
     unknown4:1,
4140
     reseten:1,
4141
     menuen:1;
4142
  u8 unknown5[11];
4143
  u8 dispab;
4144
  u8 unknown6[2];
4145
  u8 smenu;
4146
  u8 unknown7[7];
4147
  u8 vfomra;
4148
  u8 vfomrb;
4149
  u8 vfomrc;
4150
  u8 vfomrd;
4151
  u8 mrcha;
4152
  u8 mrchb;
4153
  u8 mrchc;
4154
  u8 mrchd;
4155
} settings2;
4156

    
4157
struct settings_vfo {
4158
  u8 freq[8];
4159
  u8 offset[6];
4160
  u8 unknown2[2];
4161
  ul16 rxtone;
4162
  ul16 txtone;
4163
  u8 scode;
4164
  u8 spmute;
4165
  u8 optsig;
4166
  u8 scramble;
4167
  u8 wide;
4168
  u8 power;
4169
  u8 shiftd;
4170
  u8 step;
4171
  u8 unknown3[4];
4172
};
4173

    
4174
#seekto 0x3300;
4175
struct {
4176
  struct settings_vfo a;
4177
  struct settings_vfo b;
4178
  struct settings_vfo c;
4179
  struct settings_vfo d;
4180
} vfo;
4181

    
4182
#seekto 0x3D80;
4183
struct {
4184
  u8 vhf_low[3];
4185
  u8 vhf_high[3];
4186
  u8 unknown1[4];
4187
  u8 unknown2[6];
4188
  u8 vhf2_low[3];
4189
  u8 vhf2_high[3];
4190
  u8 unknown3[4];
4191
  u8 unknown4[6];
4192
  u8 uhf_low[3];
4193
  u8 uhf_high[3];
4194
  u8 unknown5[4];
4195
  u8 unknown6[6];
4196
  u8 uhf2_low[3];
4197
  u8 uhf2_high[3];
4198
} ranges;
4199

    
4200
#seekto 0x33B0;
4201
struct {
4202
  char line[16];
4203
} static_msg;
4204

    
4205
#seekto 0x3F70;
4206
struct {
4207
  char fp[6];
4208
} fingerprint;
4209

    
4210
"""
4211

    
4212

    
4213
class BTechGMRS(BTechMobileCommon):
4214
    """BTECH's GMRS Mobile"""
4215
    COLOR_LCD = True
4216
    COLOR_LCD2 = True
4217
    NAME_LENGTH = 7
4218
    UPLOAD_MEM_SIZE = 0X3400
4219

    
4220
    def process_mmap(self):
4221
        """Process the mem map into the mem object"""
4222

    
4223
        # Get it
4224
        self._memobj = bitwise.parse(GMRS_MEM_FORMAT, self._mmap)
4225

    
4226
        # load specific parameters from the radio image
4227
        self.set_options()
4228

    
4229
    def set_options(self):
4230
        """This is to read the options from the image and set it in the
4231
        environment, for now just the limits of the freqs in the VHF/UHF
4232
        ranges"""
4233

    
4234
        # setting the correct ranges for each radio type
4235
        ranges = self._memobj.ranges
4236

    
4237
        # the normal dual bands
4238
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
4239
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
4240

    
4241
        # DEBUG
4242
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
4243
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
4244

    
4245
        # set the class with the real data
4246
        self._vhf_range = vhf
4247
        self._uhf_range = uhf
4248

    
4249

    
4250
# real radios
4251
@directory.register
4252
class GMRS50X1(BTechGMRS):
4253
    """Baofeng Tech GMRS50X1"""
4254
    MODEL = "GMRS-50X1"
4255
    BANDS = 2
4256
    LIST_TMR = LIST_TMR16
4257
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
4258
                     chirp_common.PowerLevel("Mid", watts=10),
4259
                     chirp_common.PowerLevel("Low", watts=5)]
4260
    _vhf_range = (136000000, 175000000)
4261
    _uhf_range = (400000000, 521000000)
4262
    _upper = 255
4263
    _magic = MSTRING_GMRS50X1
4264
    _fileid = [GMRS50X1_fp1, GMRS50X1_fp, ]
4265

    
4266

    
4267
COLORHT_MEM_FORMAT = """
4268
#seekto 0x0000;
4269
struct {
4270
  lbcd rxfreq[4];
4271
  lbcd txfreq[4];
4272
  ul16 rxtone;
4273
  ul16 txtone;
4274
  u8 unknown0:4,
4275
     scode:4;
4276
  u8 unknown1:2,
4277
     spmute:2,
4278
     unknown2:2,
4279
     optsig:2;
4280
  u8 unknown3:3,
4281
     scramble:1,
4282
     unknown4:3,
4283
     power:1;
4284
  u8 unknown5:1,
4285
     wide:1,
4286
     unknown6:2,
4287
     bcl:1,
4288
     add:1,
4289
     pttid:2;
4290
} memory[200];
4291

    
4292
#seekto 0x0E00;
4293
struct {
4294
  u8 tmr;            // ok
4295
  u8 unknownE01;
4296
  u8 sql;            // ok
4297
  u8 unknownE03[2];
4298
  u8 tot;            // ok
4299
  u8 save;           // ok
4300
  u8 unknownE07;
4301
  u8 abr;            // ok
4302
  u8 beep;           // ok
4303
  u8 unknownE0A[4];
4304
  u8 dsub;           // ok
4305
  u8 dtmfst;         // ok
4306
  u8 screv;          // ok
4307
  u8 unknownE11[3];
4308
  u8 pttid;
4309
  u8 unknownE15;
4310
  u8 pttlt;          // ok
4311
  u8 unknownE17;
4312
  u8 emctp;          // ok
4313
  u8 emcch;          // ok
4314
  u8 sigbp;          // ok
4315
  u8 unknownE1B;
4316
  u8 camdf;          // ok
4317
  u8 cbmdf;          // ok
4318
  u8 ccmdf;          // ok
4319
  u8 cdmdf;          // ok
4320
  u8 langua;         // ok          E20
4321
  u8 voice;          // ok
4322
  u8 vox;            // ok
4323
  u8 voxt;           // ok
4324
  u8 sync;          // BTech radios use this as the display sync setting  //ok
4325
                    // other radios use this as the auto keypad lock setting
4326
  u8 stfc;           // ok
4327
  u8 mffc;           // ok
4328
  u8 sfafc;          // ok
4329
  u8 sfbfc;          // ok
4330
  u8 sfcfc;          // ok
4331
  u8 sfdfc;          // ok
4332
  u8 subfc;          // ok
4333
  u8 fmfc;           // ok
4334
  u8 sigfc;          // ok
4335
  u8 menufc;         // ok
4336
  u8 txfc;           // ok
4337
  u8 rxfc;           // ok          E30
4338
  u8 unknownE31[5];  // ANI
4339
  u8 anil;           // ok
4340
  u8 reps;           // ok
4341
  u8 tmrmr;          // ok
4342
  u8 ste;            // ok
4343
  u8 rpste;          // ok
4344
  u8 rptdl;          // ok
4345
  u8 dtmfg;          // ok
4346
  u8 tmrtx;          // ok
4347
} settings;
4348

    
4349
#seekto 0x0E80;
4350
struct {
4351
  u8 unknown1;
4352
  u8 vfomr;
4353
  u8 keylock;
4354
  u8 unknown2;
4355
  u8 unknown3:4,
4356
     vfomren:1,
4357
     unknown4:1,
4358
     reseten:1,
4359
     menuen:1;
4360
  u8 unknown5[11];
4361
  u8 dispab;
4362
  u8 unknown6[2];
4363
  u8 menu;
4364
  u8 unknown7[7];
4365
  u8 vfomra;
4366
  u8 vfomrb;
4367
  u8 vfomrc;
4368
  u8 vfomrd;
4369
  u8 mrcha;
4370
  u8 mrchb;
4371
  u8 mrchc;
4372
  u8 mrchd;
4373
} settings2;
4374

    
4375
struct settings_vfo {
4376
  u8 freq[8];
4377
  u8 offset[6];
4378
  u8 unknown2[2];
4379
  ul16 rxtone;
4380
  ul16 txtone;
4381
  u8 scode;
4382
  u8 spmute;
4383
  u8 optsig;
4384
  u8 scramble;
4385
  u8 wide;
4386
  u8 power;
4387
  u8 shiftd;
4388
  u8 step;
4389
  u8 unknown3[4];
4390
};
4391

    
4392
#seekto 0x0F00;
4393
struct {
4394
  struct settings_vfo a;
4395
  struct settings_vfo b;
4396
  struct settings_vfo c;
4397
  struct settings_vfo d;
4398
} vfo;
4399

    
4400
#seekto 0x0FE0;
4401
struct {
4402
  char line[16];
4403
} static_msg;
4404

    
4405
#seekto 0x1000;
4406
struct {
4407
  char name[8];
4408
  u8 unknown1[8];
4409
} names[200];
4410

    
4411
#seekto 0x2400;
4412
struct {
4413
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
4414
  u8 group_tone;
4415
  u8 repeat_tone;
4416
  u8 unused[13];
4417
} _5tone_std_settings[15];
4418

    
4419
#seekto 0x2500;
4420
struct {
4421
  u8 frame1[5];
4422
  u8 frame2[5];
4423
  u8 frame3[5];
4424
  u8 standard;   // one out of LIST_5TONE_STANDARDS
4425
} _5tone_codes[15];
4426

    
4427
#seekto 0x25F0;
4428
struct {
4429
  u8 _5tone_delay1; // * 10ms
4430
  u8 _5tone_delay2; // * 10ms
4431
  u8 _5tone_delay3; // * 10ms
4432
  u8 _5tone_first_digit_ext_length;
4433
  u8 unknown1;
4434
  u8 unknown2;
4435
  u8 unknown3;
4436
  u8 unknown4;
4437
  u8 decode_standard;
4438
  u8 unknown5:5,
4439
     _5tone_decode_call_frame3:1,
4440
     _5tone_decode_call_frame2:1,
4441
     _5tone_decode_call_frame1:1;
4442
  u8 unknown6:5,
4443
     _5tone_decode_disp_frame3:1,
4444
     _5tone_decode_disp_frame2:1,
4445
     _5tone_decode_disp_frame1:1;
4446
  u8 decode_reset_time; // * 100 + 100ms
4447
} _5tone_settings;
4448

    
4449
#seekto 0x2900;
4450
struct {
4451
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
4452
} dtmf_codes[15];
4453

    
4454
#seekto 0x29F0;
4455
struct {
4456
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
4457
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
4458
  u8 unknown0[14];
4459
  u8 inspection[16];
4460
  u8 monitor[16];
4461
  u8 alarmcode[16];
4462
  u8 stun[16];
4463
  u8 kill[16];
4464
  u8 revive[16];
4465
  u8 unknown1[16];
4466
  u8 unknown2[16];
4467
  u8 unknown3[16];
4468
  u8 unknown4[16];
4469
  u8 unknown5[16];
4470
  u8 unknown6[16];
4471
  u8 unknown7[16];
4472
  u8 masterid[16];
4473
  u8 viceid[16];
4474
  u8 unused01:7,
4475
     mastervice:1;
4476
  u8 unused02:3,
4477
     mrevive:1,
4478
     mkill:1,
4479
     mstun:1,
4480
     mmonitor:1,
4481
     minspection:1;
4482
  u8 unused03:3,
4483
     vrevive:1,
4484
     vkill:1,
4485
     vstun:1,
4486
     vmonitor:1,
4487
     vinspection:1;
4488
  u8 unused04:6,
4489
     txdisable:1,
4490
     rxdisable:1;
4491
  u8 groupcode;
4492
  u8 spacecode;
4493
  u8 delayproctime; // * 100 + 100ms
4494
  u8 resettime;     // * 100 + 100ms
4495
} dtmf_settings;
4496

    
4497
#seekto 0x2D00;
4498
struct {
4499
  struct {
4500
    ul16 freq1;
4501
    u8 unused01[6];
4502
    ul16 freq2;
4503
    u8 unused02[6];
4504
  } _2tone_encode[15];
4505
  u8 duration_1st_tone; // *10ms
4506
  u8 duration_2nd_tone; // *10ms
4507
  u8 duration_gap;      // *10ms
4508
  u8 unused03[13];
4509
  struct {
4510
    struct {
4511
      u8 dec;      // one out of LIST_2TONE_DEC
4512
      u8 response; // one out of LIST_2TONE_RESPONSE
4513
      u8 alert;    // 1-16
4514
    } decs[4];
4515
    u8 unused04[4];
4516
  } _2tone_decode[15];
4517
  u8 unused05[16];
4518

    
4519
  struct {
4520
    ul16 freqA;
4521
    ul16 freqB;
4522
    ul16 freqC;
4523
    ul16 freqD;
4524
    // unknown what those values mean, but they are
4525
    // derived from configured frequencies
4526
    ul16 derived_from_freqA; // 2304000/freqA
4527
    ul16 derived_from_freqB; // 2304000/freqB
4528
    ul16 derived_from_freqC; // 2304000/freqC
4529
    ul16 derived_from_freqD; // 2304000/freqD
4530
  }freqs[15];
4531
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
4532
} _2tone;
4533

    
4534
#seekto 0x3D80;
4535
struct {
4536
  u8 vhf_low[3];
4537
  u8 vhf_high[3];
4538
  u8 unknown1[4];
4539
  u8 unknown2[6];
4540
  u8 vhf2_low[3];
4541
  u8 vhf2_high[3];
4542
  u8 unknown3[4];
4543
  u8 unknown4[6];
4544
  u8 uhf_low[3];
4545
  u8 uhf_high[3];
4546
  u8 unknown5[4];
4547
  u8 unknown6[6];
4548
  u8 uhf2_low[3];
4549
  u8 uhf2_high[3];
4550
} ranges;
4551

    
4552
#seekto 0x3F70;
4553
struct {
4554
  char fp[6];
4555
} fingerprint;
4556

    
4557
"""
4558

    
4559

    
4560
class QYTColorHT(BTechMobileCommon):
4561
    """QTY's Color LCD Handheld and alike radios"""
4562
    COLOR_LCD = True
4563
    COLOR_LCD3 = True
4564
    NAME_LENGTH = 8
4565
    LIST_TMR = LIST_TMR15
4566

    
4567
    def process_mmap(self):
4568
        """Process the mem map into the mem object"""
4569

    
4570
        # Get it
4571
        self._memobj = bitwise.parse(COLORHT_MEM_FORMAT, self._mmap)
4572

    
4573
        # load specific parameters from the radio image
4574
        self.set_options()
4575

    
4576
    def set_options(self):
4577
        """This is to read the options from the image and set it in the
4578
        environment, for now just the limits of the freqs in the VHF/UHF
4579
        ranges"""
4580

    
4581
        # setting the correct ranges for each radio type
4582
        ranges = self._memobj.ranges
4583

    
4584
        # the normal dual bands
4585
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
4586
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
4587

    
4588
        # DEBUG
4589
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
4590
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
4591

    
4592
        # the additional bands
4593
        if self.MODEL in ["KT-8R"]:
4594
            # 200Mhz band
4595
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
4596
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
4597
            self._220_range = vhf2
4598

    
4599
            # 350Mhz band
4600
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
4601
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
4602
            self._350_range = uhf2
4603

    
4604
        # set the class with the real data
4605
        self._vhf_range = vhf
4606
        self._uhf_range = uhf
4607

    
4608

    
4609
# real radios
4610
@directory.register
4611
class KT8R(QYTColorHT):
4612
    """QYT KT8R"""
4613
    VENDOR = "QYT"
4614
    MODEL = "KT-8R"
4615
    BANDS = 4
4616
    LIST_TMR = LIST_TMR15
4617
    _vhf_range = (136000000, 175000000)
4618
    _220_range = (200000000, 261000000)
4619
    _uhf_range = (400000000, 481000000)
4620
    _350_range = (350000000, 391000000)
4621
    _magic = MSTRING_KT8R
4622
    _fileid = [KT8R_fp1, KT8R_fp, ]
4623
    _power_levels = [chirp_common.PowerLevel("High", watts=5),
4624
                     chirp_common.PowerLevel("Low", watts=1)]
4625

    
4626
    #def get_features(self):
4627
    #    rf = BTechMobileCommon.get_features(self)
4628
    #    rf.has_settings = False
4629
    #    return rf
(3-3/7)