Project

General

Profile

Feature #9825 » btech-set_kt8900_band_limits_#4.py

for KT8900 and similar radios only - Jim Unroe, 04/11/2022 02:11 AM

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

    
18
import time
19
import struct
20
import logging
21

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

    
31
LOG = logging.getLogger(__name__)
32

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

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

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

    
56
# lists
57
LIST_AB = ["A", "B"]
58
LIST_ABCD = LIST_AB + ["C", "D"]
59
LIST_ANIL = ["3", "4", "5"]
60
LIST_APO = ["Off"] + ["%s minutes" % x for x in range(30, 330, 30)]
61
LIST_COLOR4 = ["Off", "Blue", "Orange", "Purple"]
62
LIST_COLOR8 = ["White", "Red", "Blue", "Green", "Yellow", "Indego",
63
               "Purple", "Gray"]
64
LIST_COLOR9 = ["Black"] + LIST_COLOR8
65
LIST_DTMFST = ["OFF", "Keyboard", "ANI", "Keyboad + ANI"]
66
LIST_EMCTP = ["TX alarm sound", "TX ANI", "Both"]
67
LIST_EMCTPX = ["Off"] + LIST_EMCTP
68
LIST_LANGUA = ["English", "Chinese"]
69
LIST_MDF = ["Frequency", "Channel", "Name"]
70
LIST_OFF1TO9 = ["Off"] + ["%s seconds" % x for x in range(1, 10)]
71
LIST_OFF1TO10 = ["Off"] + ["%s seconds" % x for x in range(1, 11)]
72
LIST_OFF1TO50 = ["Off"] + ["%s seconds" % x for x in range(1, 51)]
73
LIST_PONMSG = ["Full", "Message", "Battery voltage"]
74
LIST_REPM = ["Off", "Carrier", "CTCSS or DCS", "Tone", "DTMF"]
75
LIST_REPS = ["1000 Hz", "1450 Hz", "1750 Hz", "2100Hz"]
76
LIST_RPTDL = ["Off"] + ["%s ms" % x for x in range(1, 11)]
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
STIMEOUT = 0.25
137

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

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

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

    
154

    
155
# #### ID strings #####################################################
156

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

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

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

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

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

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

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

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

    
205

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

    
209

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

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

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

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

    
255
# QB25 (quad band) - a clone of KT7900D
256
QB25_fp = "QB-25"
257

    
258
# KT8900D (dual band)
259
KT8900D_fp = "VC2002"
260
KT8900D_fp1 = "VC8632"
261
KT8900D_fp2 = "VC3402"
262
KT8900D_fp3 = "VC7062"
263

    
264
# LUITON LT-588UV
265
LT588UV_fp = "V2G1F4"
266
# Added by rstrickoff gen 2 id
267
LT588UV_fp1 = "V2G214"
268

    
269
# QYT KT-8R (quad band ht)
270
KT8R_fp = "MCB264"
271
KT8R_fp1 = "MCB284"
272
KT8R_fp2 = "MC5264"
273

    
274
# QYT KT5800 (dual band)
275
KT5800_fp = "VCB222"
276

    
277
# QYT KT980Plus (dual band)
278
KT980PLUS_fp = "VC2002"
279
KT980PLUS_fp1 = "VC6042"
280

    
281
# Radioddity DB25-G (gmrs)
282
DB25G_fp = "VC6182"
283
DB25G_fp1 = "VC7062"
284

    
285

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

    
307

    
308
def _clean_buffer(radio):
309
    """Cleaning the read serial buffer, hard timeout to survive an infinite
310
    data stream"""
311

    
312
    # touching the serial timeout to optimize the flushing
313
    # restored at the end to the default value
314
    radio.pipe.timeout = 0.1
315
    dump = "1"
316
    datacount = 0
317

    
318
    try:
319
        while len(dump) > 0:
320
            dump = radio.pipe.read(100)
321
            datacount += len(dump)
322
            # hard limit to survive a infinite serial data stream
323
            # 5 times bigger than a normal rx block (69 bytes)
324
            if datacount > 345:
325
                seriale = "Please check your serial port selection."
326
                raise errors.RadioError(seriale)
327

    
328
        # restore the default serial timeout
329
        radio.pipe.timeout = STIMEOUT
330

    
331
    except Exception:
332
        raise errors.RadioError("Unknown error cleaning the serial buffer")
333

    
334

    
335
def _rawrecv(radio, amount):
336
    """Raw read from the radio device, less intensive way"""
337

    
338
    data = ""
339

    
340
    try:
341
        data = radio.pipe.read(amount)
342

    
343
        # DEBUG
344
        if debug is True:
345
            LOG.debug("<== (%d) bytes:\n\n%s" %
346
                      (len(data), util.hexprint(data)))
347

    
348
        # fail if no data is received
349
        if len(data) == 0:
350
            raise errors.RadioError("No data received from radio")
351

    
352
        # notice on the logs if short
353
        if len(data) < amount:
354
            LOG.warn("Short reading %d bytes from the %d requested." %
355
                     (len(data), amount))
356

    
357
    except:
358
        raise errors.RadioError("Error reading data from radio")
359

    
360
    return data
361

    
362

    
363
def _send(radio, data):
364
    """Send data to the radio device"""
365

    
366
    try:
367
        radio.pipe.write(data)
368

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

    
376

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

    
384
    return frame
385

    
386

    
387
def _recv(radio, addr):
388
    """Get data from the radio all at once to lower syscalls load"""
389

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

    
393
    # get the whole block
394
    block = _rawrecv(radio, BLOCK_SIZE + 5)
395

    
396
    # basic check
397
    if len(block) < (BLOCK_SIZE + 5):
398
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
399

    
400
    # checking for the ack
401
    if block[0] != ACK_CMD:
402
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
403

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

    
411
    # return the data
412
    return block[5:]
413

    
414

    
415
def _start_clone_mode(radio, status):
416
    """Put the radio in clone mode and get the ident string, 3 tries"""
417

    
418
    # cleaning the serial buffer
419
    _clean_buffer(radio)
420

    
421
    # prep the data to show in the UI
422
    status.cur = 0
423
    status.msg = "Identifying the radio..."
424
    status.max = 3
425
    radio.status_fn(status)
426

    
427
    try:
428
        for a in range(0, status.max):
429
            # Update the UI
430
            status.cur = a + 1
431
            radio.status_fn(status)
432

    
433
            # send the magic word
434
            _send(radio, radio._magic)
435

    
436
            # Now you get a x06 of ACK if all goes well
437
            ack = radio.pipe.read(1)
438

    
439
            if ack == "\x06":
440
                # DEBUG
441
                LOG.info("Magic ACK received")
442
                status.cur = status.max
443
                radio.status_fn(status)
444

    
445
                return True
446

    
447
        return False
448

    
449
    except errors.RadioError:
450
        raise
451
    except Exception, e:
452
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
453

    
454

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

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

    
470
    # lengthen the timeout here as these radios are reseting due to timeout
471
    radio.pipe.timeout = 0.75
472

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

    
476
    # restore the default serial timeout
477
    radio.pipe.timeout = STIMEOUT
478

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

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

    
493
            break
494

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

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

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

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

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

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

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

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

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

    
553
            # restore the default serial timeout
554
            radio.pipe.timeout = STIMEOUT
555

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

    
559
    return True
560

    
561

    
562
def _download(radio):
563
    """Get the memory map"""
564

    
565
    # UI progress
566
    status = chirp_common.Status()
567

    
568
    # put radio in program mode and identify it
569
    _do_ident(radio, status)
570

    
571
    # pause here for the radio to catch up
572
    sleep(0.1)
573

    
574
    # the models that doesn't have the extra ID have to make a dummy read here
575
    if radio._id2 is False:
576
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
577
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
578

    
579
        if debug is True:
580
            LOG.info("Dummy first block read done, got this:\n\n %s",
581
                     util.hexprint(discard))
582

    
583
    # reset the progress bar in the UI
584
    status.max = MEM_SIZE / BLOCK_SIZE
585
    status.msg = "Cloning from radio..."
586
    status.cur = 0
587
    radio.status_fn(status)
588

    
589
    # cleaning the serial buffer
590
    _clean_buffer(radio)
591

    
592
    data = ""
593
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
594
        # sending the read request
595
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
596

    
597
        # read
598
        d = _recv(radio, addr)
599

    
600
        # aggregate the data
601
        data += d
602

    
603
        # UI Update
604
        status.cur = addr / BLOCK_SIZE
605
        status.msg = "Cloning from radio..."
606
        radio.status_fn(status)
607

    
608
    return data
609

    
610

    
611
def _upload(radio):
612
    """Upload procedure"""
613

    
614
    # The UPLOAD mem is restricted to lower than 0x3100,
615
    # so we will overide that here localy
616
    MEM_SIZE = radio.UPLOAD_MEM_SIZE
617

    
618
    # UI progress
619
    status = chirp_common.Status()
620

    
621
    # put radio in program mode and identify it
622
    _do_ident(radio, status, True)
623

    
624
    # get the data to upload to radio
625
    data = radio.get_mmap()
626

    
627
    # Reset the UI progress
628
    status.max = MEM_SIZE / TX_BLOCK_SIZE
629
    status.cur = 0
630
    status.msg = "Cloning to radio..."
631
    radio.status_fn(status)
632

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

    
637
    # cleaning the serial buffer
638
    _clean_buffer(radio)
639

    
640
    # the fun start here
641
    for addr in range(0x3C90, 0x3C9F, TX_BLOCK_SIZE):  # set band limits for KT-8900 and similar radios only
642
        # getting the block of data to send
643
        d = data[addr:addr + TX_BLOCK_SIZE]
644

    
645
        # build the frame to send
646
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
647

    
648
        # first block must not send the ACK at the beginning for the
649
        # ones that has the extra id, since this have to do a extra step
650
        if addr == 0 and radio._id2 is not False:
651
            frame = frame[1:]
652

    
653
        # send the frame
654
        _send(radio, frame)
655

    
656
        # receiving the response
657
        ack = _rawrecv(radio, 1)
658

    
659
        # basic check
660
        if len(ack) != 1:
661
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
662

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

    
666
        # UI Update
667
        status.cur = addr / TX_BLOCK_SIZE
668
        status.msg = "Cloning to radio..."
669
        radio.status_fn(status)
670

    
671

    
672
def model_match(cls, data):
673
    """Match the opened/downloaded image to the correct version"""
674
    rid = data[0x3f70:0x3f76]
675

    
676
    if rid in cls._fileid:
677
        return True
678

    
679
    return False
680

    
681

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

    
690
    return (ilow, ihigh)
691

    
692

    
693
def _split(rf, f1, f2):
694
    """Returns False if the two freqs are in the same band (no split)
695
    or True otherwise"""
696

    
697
    # determine if the two freqs are in the same band
698
    for low, high in rf.valid_bands:
699
        if f1 >= low and f1 <= high and \
700
                f2 >= low and f2 <= high:
701
            # if the two freqs are on the same Band this is not a split
702
            return False
703

    
704
    # if you get here is because the freq pairs are split
705
    return True
706

    
707

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

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

    
747
            1 - Turn off your radio
748
            2 - Connect your interface cable
749
            3 - Turn on your radio
750
            4 - Do the download of your radio data
751

    
752
            """))
753
        rp.pre_upload = _(dedent("""\
754
            Follow these instructions to upload your info:
755

    
756
            1 - Turn off your radio
757
            2 - Connect your interface cable
758
            3 - Turn on your radio
759
            4 - Do the upload of your radio data
760

    
761
            """))
762
        return rp
763

    
764
    def get_features(self):
765
        """Get the radio's features"""
766

    
767
        # we will use the following var as global
768
        global POWER_LEVELS
769

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

    
801
        # power levels
802
        POWER_LEVELS = self._power_levels
803
        rf.valid_power_levels = POWER_LEVELS
804

    
805
        # normal dual bands
806
        rf.valid_bands = [self._vhf_range, self._uhf_range]
807

    
808
        # 220 band
809
        if self.BANDS == 3 or self.BANDS == 4:
810
            rf.valid_bands.append(self._220_range)
811

    
812
        # 350 band
813
        if self.BANDS == 4:
814
            rf.valid_bands.append(self._350_range)
815

    
816
        return rf
817

    
818
    def validate_memory(self, mem):
819
        msgs = chirp_common.CloneModeRadio.validate_memory(self, mem)
820

    
821
        _msg_duplex1 = 'Memory location only supports "Low"'
822
        _msg_duplex2 = 'Memory location only supports "off"'
823
        _msg_duplex3 = 'Memory location only supports "(None)", "+" or "off"'
824

    
825
        if self._gmrs:
826
            if mem.number < 1 or mem.number > 30:
827
                if float(mem.freq) / 1000000 in GMRS_FREQS1:
828
                    if mem.duplex not in ['', 'off']:
829
                        # warn user wrong Duplex
830
                        msgs.append(chirp_common.ValidationError(_msg_duplex2))
831
                    if mem.power != self._power_levels[2]:
832
                        # warn user wrong Duplex
833
                        msgs.append(chirp_common.ValidationError(_msg_duplex1))
834

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

    
840
                if float(mem.freq) / 1000000 in GMRS_FREQS3:
841
                    if mem.duplex not in ['', '+', 'off']:
842
                        # warn user wrong Duplex
843
                        msgs.append(chirp_common.ValidationError(_msg_duplex3))
844

    
845
        return msgs
846

    
847
    def sync_in(self):
848
        """Download from radio"""
849
        data = _download(self)
850
        self._mmap = memmap.MemoryMap(data)
851
        self.process_mmap()
852

    
853
    def sync_out(self):
854
        """Upload to radio"""
855
        try:
856
            _upload(self)
857
        except errors.RadioError:
858
            raise
859
        except Exception, e:
860
            raise errors.RadioError("Error: %s" % e)
861

    
862
    def get_raw_memory(self, number):
863
        return repr(self._memobj.memory[number])
864

    
865
    def _decode_tone(self, val):
866
        """Parse the tone data to decode from mem, it returns:
867
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
868
        pol = None
869

    
870
        if val in [0, 65535]:
871
            return '', None, None
872
        elif val > 0x0258:
873
            a = val / 10.0
874
            return 'Tone', a, pol
875
        else:
876
            if val > 0x69:
877
                index = val - 0x6A
878
                pol = "R"
879
            else:
880
                index = val - 1
881
                pol = "N"
882

    
883
            tone = DTCS[index]
884
            return 'DTCS', tone, pol
885

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

    
910
    def get_memory(self, number):
911
        """Get the mem representation from the radio image"""
912
        _mem = self._memobj.memory[number]
913
        _names = self._memobj.names[number]
914

    
915
        # Create a high-level memory object to return to the UI
916
        mem = chirp_common.Memory()
917

    
918
        # Memory number
919
        mem.number = number
920

    
921
        if _mem.get_raw()[0] == "\xFF":
922
            mem.empty = True
923
            return mem
924

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

    
949
        # name TAG of the channel
950
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
951

    
952
        # power
953
        mem.power = POWER_LEVELS[int(_mem.power)]
954

    
955
        # wide/narrow
956
        mem.mode = MODES[int(_mem.wide)]
957

    
958
        # skip
959
        mem.skip = SKIP_VALUES[_mem.add]
960

    
961
        # tone data
962
        rxtone = txtone = None
963
        txtone = self._decode_tone(_mem.txtone)
964
        rxtone = self._decode_tone(_mem.rxtone)
965
        chirp_common.split_tone_decode(mem, txtone, rxtone)
966

    
967
        # Extra
968
        mem.extra = RadioSettingGroup("extra", "Extra")
969

    
970
        if not self.COLOR_LCD or \
971
                (self.COLOR_LCD and not self.VENDOR == "BTECH"):
972
            scramble = RadioSetting("scramble", "Scramble",
973
                                    RadioSettingValueBoolean(bool(
974
                                        _mem.scramble)))
975
            mem.extra.append(scramble)
976

    
977
        bcl = RadioSetting("bcl", "Busy channel lockout",
978
                           RadioSettingValueBoolean(bool(_mem.bcl)))
979
        mem.extra.append(bcl)
980

    
981
        pttid = RadioSetting("pttid", "PTT ID",
982
                             RadioSettingValueList(PTTID_LIST,
983
                                                   PTTID_LIST[_mem.pttid]))
984
        mem.extra.append(pttid)
985

    
986
        # validating scode
987
        scode = _mem.scode if _mem.scode != 15 else 0
988
        pttidcode = RadioSetting("scode", "PTT ID signal code",
989
                                 RadioSettingValueList(
990
                                     PTTIDCODE_LIST,
991
                                     PTTIDCODE_LIST[scode]))
992
        mem.extra.append(pttidcode)
993

    
994
        optsig = RadioSetting("optsig", "Optional signaling",
995
                              RadioSettingValueList(
996
                                  OPTSIG_LIST,
997
                                  OPTSIG_LIST[_mem.optsig]))
998
        mem.extra.append(optsig)
999

    
1000
        spmute = RadioSetting("spmute", "Speaker mute",
1001
                              RadioSettingValueList(
1002
                                  SPMUTE_LIST,
1003
                                  SPMUTE_LIST[_mem.spmute]))
1004
        mem.extra.append(spmute)
1005

    
1006
        return mem
1007

    
1008
    def set_memory(self, mem):
1009
        """Set the memory data in the eeprom img from the UI"""
1010
        # get the eprom representation of this channel
1011
        _mem = self._memobj.memory[mem.number]
1012
        _names = self._memobj.names[mem.number]
1013

    
1014
        mem_was_empty = False
1015
        # same method as used in get_memory for determining if mem is empty
1016
        # doing this BEFORE overwriting it with new values ...
1017
        if _mem.get_raw()[0] == "\xFF":
1018
            LOG.debug("This mem was empty before")
1019
            mem_was_empty = True
1020

    
1021
        # if empty memmory
1022
        if mem.empty:
1023
            # the channel itself
1024
            _mem.set_raw("\xFF" * 16)
1025
            # the name tag
1026
            _names.set_raw("\xFF" * 16)
1027
            return
1028

    
1029
        if mem_was_empty:
1030
            # Zero the whole memory if we're making it unempty for
1031
            # the first time
1032
            LOG.debug('Zeroing new memory')
1033
            _mem.set_raw('\x00' * 16)
1034

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

    
1070
        # frequency
1071
        _mem.rxfreq = mem.freq / 10
1072

    
1073
        # duplex
1074
        if mem.duplex == "+":
1075
            _mem.txfreq = (mem.freq + mem.offset) / 10
1076
        elif mem.duplex == "-":
1077
            _mem.txfreq = (mem.freq - mem.offset) / 10
1078
        elif mem.duplex == "off":
1079
            for i in _mem.txfreq:
1080
                i.set_raw("\xFF")
1081
        elif mem.duplex == "split":
1082
            _mem.txfreq = mem.offset / 10
1083
        else:
1084
            _mem.txfreq = mem.freq / 10
1085

    
1086
        # tone data
1087
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1088
            chirp_common.split_tone_encode(mem)
1089
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1090
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1091

    
1092
        # name TAG of the channel
1093
        if len(mem.name) < self.NAME_LENGTH:
1094
            # we must pad to self.NAME_LENGTH chars, " " = "\xFF"
1095
            mem.name = str(mem.name).ljust(self.NAME_LENGTH, " ")
1096
        _names.name = str(mem.name).replace(" ", "\xFF")
1097

    
1098
        # power, # default power level is high
1099
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1100

    
1101
        # wide/narrow
1102
        _mem.wide = MODES.index(mem.mode)
1103

    
1104
        # scan add property
1105
        _mem.add = SKIP_VALUES.index(mem.skip)
1106

    
1107
        # reseting unknowns, this have to be set by hand
1108
        _mem.unknown0 = 0
1109
        _mem.unknown1 = 0
1110
        _mem.unknown2 = 0
1111
        _mem.unknown3 = 0
1112
        _mem.unknown4 = 0
1113
        _mem.unknown5 = 0
1114
        _mem.unknown6 = 0
1115

    
1116
        def _zero_settings():
1117
            _mem.spmute = 0
1118
            _mem.optsig = 0
1119
            _mem.scramble = 0
1120
            _mem.bcl = 0
1121
            _mem.pttid = 0
1122
            _mem.scode = 0
1123

    
1124
        if self.COLOR_LCD and _mem.scramble:
1125
            LOG.info('Resetting scramble bit for BTECH COLOR_LCD variant')
1126
            _mem.scramble = 0
1127

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

    
1148
        return mem
1149

    
1150
    def set_settings(self, settings):
1151
        _settings = self._memobj.settings
1152
        for element in settings:
1153
            if not isinstance(element, RadioSetting):
1154
                if element.get_name() == "fm_preset":
1155
                    self._set_fm_preset(element)
1156
                else:
1157
                    self.set_settings(element)
1158
                    continue
1159
            else:
1160
                try:
1161
                    name = element.get_name()
1162
                    if "." in name:
1163
                        bits = name.split(".")
1164
                        obj = self._memobj
1165
                        for bit in bits[:-1]:
1166
                            if "/" in bit:
1167
                                bit, index = bit.split("/", 1)
1168
                                index = int(index)
1169
                                obj = getattr(obj, bit)[index]
1170
                            else:
1171
                                obj = getattr(obj, bit)
1172
                        setting = bits[-1]
1173
                    else:
1174
                        obj = _settings
1175
                        setting = element.get_name()
1176

    
1177
                    if element.has_apply_callback():
1178
                        LOG.debug("Using apply callback")
1179
                        element.run_apply_callback()
1180
                    elif element.value.get_mutable():
1181
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1182
                        setattr(obj, setting, element.value)
1183
                except Exception, e:
1184
                    LOG.debug(element.get_name())
1185
                    raise
1186

    
1187
    @classmethod
1188
    def match_model(cls, filedata, filename):
1189
        match_size = False
1190
        match_model = False
1191

    
1192
        # testing the file data size
1193
        if len(filedata) == MEM_SIZE:
1194
            match_size = True
1195

    
1196
        # testing the firmware model fingerprint
1197
        match_model = model_match(cls, filedata)
1198

    
1199
        if match_size and match_model:
1200
            return True
1201
        else:
1202
            return False
1203

    
1204

    
1205
MEM_FORMAT = """
1206
#seekto 0x0000;
1207
struct {
1208
  lbcd rxfreq[4];
1209
  lbcd txfreq[4];
1210
  ul16 rxtone;
1211
  ul16 txtone;
1212
  u8 unknown0:4,
1213
     scode:4;
1214
  u8 unknown1:2,
1215
     spmute:2,
1216
     unknown2:2,
1217
     optsig:2;
1218
  u8 unknown3:3,
1219
     scramble:1,
1220
     unknown4:3,
1221
     power:1;
1222
  u8 unknown5:1,
1223
     wide:1,
1224
     unknown6:2,
1225
     bcl:1,
1226
     add:1,
1227
     pttid:2;
1228
} memory[200];
1229

    
1230
#seekto 0x0E00;
1231
struct {
1232
  u8 tdr;
1233
  u8 unknown1;
1234
  u8 sql;
1235
  u8 unknown2[2];
1236
  u8 tot;
1237
  u8 apo;           // BTech radios use this as the Auto Power Off time
1238
                    // other radios use this as pre-Time Out Alert
1239
  u8 unknown3;
1240
  u8 abr;
1241
  u8 beep;
1242
  u8 unknown4[4];
1243
  u8 dtmfst;
1244
  u8 unknown5[2];
1245
  u8 prisc;
1246
  u8 prich;
1247
  u8 screv;
1248
  u8 unknown6[2];
1249
  u8 pttid;
1250
  u8 pttlt;
1251
  u8 unknown7;
1252
  u8 emctp;
1253
  u8 emcch;
1254
  u8 ringt;
1255
  u8 unknown8;
1256
  u8 camdf;
1257
  u8 cbmdf;
1258
  u8 sync;          // BTech radios use this as the display sync setting
1259
                    // other radios use this as the auto keypad lock setting
1260
  u8 ponmsg;
1261
  u8 wtled;
1262
  u8 rxled;
1263
  u8 txled;
1264
  u8 unknown9[5];
1265
  u8 anil;
1266
  u8 reps;
1267
  u8 repm;
1268
  u8 tdrab;
1269
  u8 ste;
1270
  u8 rpste;
1271
  u8 rptdl;
1272
  u8 mgain;
1273
  u8 dtmfg;
1274
} settings;
1275

    
1276
#seekto 0x0E80;
1277
struct {
1278
  u8 unknown1;
1279
  u8 vfomr;
1280
  u8 keylock;
1281
  u8 unknown2;
1282
  u8 unknown3:4,
1283
     vfomren:1,
1284
     unknown4:1,
1285
     reseten:1,
1286
     menuen:1;
1287
  u8 unknown5[11];
1288
  u8 dispab;
1289
  u8 mrcha;
1290
  u8 mrchb;
1291
  u8 menu;
1292
} settings2;
1293

    
1294
#seekto 0x0EC0;
1295
struct {
1296
  char line1[6];
1297
  char line2[6];
1298
} poweron_msg;
1299

    
1300
struct settings_vfo {
1301
  u8 freq[8];
1302
  u8 offset[6];
1303
  u8 unknown2[2];
1304
  ul16 rxtone;
1305
  ul16 txtone;
1306
  u8 scode;
1307
  u8 spmute;
1308
  u8 optsig;
1309
  u8 scramble;
1310
  u8 wide;
1311
  u8 power;
1312
  u8 shiftd;
1313
  u8 step;
1314
  u8 unknown3[4];
1315
};
1316

    
1317
#seekto 0x0F00;
1318
struct {
1319
  struct settings_vfo a;
1320
  struct settings_vfo b;
1321
} vfo;
1322

    
1323
#seekto 0x1000;
1324
struct {
1325
  char name[6];
1326
  u8 unknown1[10];
1327
} names[200];
1328

    
1329
#seekto 0x2400;
1330
struct {
1331
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
1332
  u8 group_tone;
1333
  u8 repeat_tone;
1334
  u8 unused[13];
1335
} _5tone_std_settings[15];
1336

    
1337
#seekto 0x2500;
1338
struct {
1339
  u8 frame1[5];
1340
  u8 frame2[5];
1341
  u8 frame3[5];
1342
  u8 standard;   // one out of LIST_5TONE_STANDARDS
1343
} _5tone_codes[15];
1344

    
1345
#seekto 0x25F0;
1346
struct {
1347
  u8 _5tone_delay1; // * 10ms
1348
  u8 _5tone_delay2; // * 10ms
1349
  u8 _5tone_delay3; // * 10ms
1350
  u8 _5tone_first_digit_ext_length;
1351
  u8 unknown1;
1352
  u8 unknown2;
1353
  u8 unknown3;
1354
  u8 unknown4;
1355
  u8 decode_standard;
1356
  u8 unknown5:5,
1357
     _5tone_decode_call_frame3:1,
1358
     _5tone_decode_call_frame2:1,
1359
     _5tone_decode_call_frame1:1;
1360
  u8 unknown6:5,
1361
     _5tone_decode_disp_frame3:1,
1362
     _5tone_decode_disp_frame2:1,
1363
     _5tone_decode_disp_frame1:1;
1364
  u8 decode_reset_time; // * 100 + 100ms
1365
} _5tone_settings;
1366

    
1367
#seekto 0x2900;
1368
struct {
1369
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
1370
} dtmf_codes[15];
1371

    
1372
#seekto 0x29F0;
1373
struct {
1374
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
1375
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
1376
  u8 unknown0[14];
1377
  u8 inspection[16];
1378
  u8 monitor[16];
1379
  u8 alarmcode[16];
1380
  u8 stun[16];
1381
  u8 kill[16];
1382
  u8 revive[16];
1383
  u8 unknown1[16];
1384
  u8 unknown2[16];
1385
  u8 unknown3[16];
1386
  u8 unknown4[16];
1387
  u8 unknown5[16];
1388
  u8 unknown6[16];
1389
  u8 unknown7[16];
1390
  u8 masterid[16];
1391
  u8 viceid[16];
1392
  u8 unused01:7,
1393
     mastervice:1;
1394
  u8 unused02:3,
1395
     mrevive:1,
1396
     mkill:1,
1397
     mstun:1,
1398
     mmonitor:1,
1399
     minspection:1;
1400
  u8 unused03:3,
1401
     vrevive:1,
1402
     vkill:1,
1403
     vstun:1,
1404
     vmonitor:1,
1405
     vinspection:1;
1406
  u8 unused04:6,
1407
     txdisable:1,
1408
     rxdisable:1;
1409
  u8 groupcode;
1410
  u8 spacecode;
1411
  u8 delayproctime; // * 100 + 100ms
1412
  u8 resettime;     // * 100 + 100ms
1413
} dtmf_settings;
1414

    
1415
#seekto 0x2D00;
1416
struct {
1417
  struct {
1418
    ul16 freq1;
1419
    u8 unused01[6];
1420
    ul16 freq2;
1421
    u8 unused02[6];
1422
  } _2tone_encode[15];
1423
  u8 duration_1st_tone; // *10ms
1424
  u8 duration_2nd_tone; // *10ms
1425
  u8 duration_gap;      // *10ms
1426
  u8 unused03[13];
1427
  struct {
1428
    struct {
1429
      u8 dec;      // one out of LIST_2TONE_DEC
1430
      u8 response; // one out of LIST_2TONE_RESPONSE
1431
      u8 alert;    // 1-16
1432
    } decs[4];
1433
    u8 unused04[4];
1434
  } _2tone_decode[15];
1435
  u8 unused05[16];
1436

    
1437
  struct {
1438
    ul16 freqA;
1439
    ul16 freqB;
1440
    ul16 freqC;
1441
    ul16 freqD;
1442
    // unknown what those values mean, but they are
1443
    // derived from configured frequencies
1444
    ul16 derived_from_freqA; // 2304000/freqA
1445
    ul16 derived_from_freqB; // 2304000/freqB
1446
    ul16 derived_from_freqC; // 2304000/freqC
1447
    ul16 derived_from_freqD; // 2304000/freqD
1448
  }freqs[15];
1449
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
1450
} _2tone;
1451

    
1452
#seekto 0x3000;
1453
struct {
1454
  u8 freq[8];
1455
  char broadcast_station_name[6];
1456
  u8 unknown[2];
1457
} fm_radio_preset[16];
1458

    
1459
#seekto 0x3C90;
1460
struct {
1461
  u8 vhf_low[3];
1462
  u8 vhf_high[3];
1463
  u8 uhf_low[3];
1464
  u8 uhf_high[3];
1465
} ranges;
1466

    
1467
// the UV-2501+220 & KT8900R has different zones for storing ranges
1468

    
1469
#seekto 0x3CD0;
1470
struct {
1471
  u8 vhf_low[3];
1472
  u8 vhf_high[3];
1473
  u8 unknown1[4];
1474
  u8 unknown2[6];
1475
  u8 vhf2_low[3];
1476
  u8 vhf2_high[3];
1477
  u8 unknown3[4];
1478
  u8 unknown4[6];
1479
  u8 uhf_low[3];
1480
  u8 uhf_high[3];
1481
} ranges220;
1482

    
1483
#seekto 0x3F70;
1484
struct {
1485
  char fp[6];
1486
} fingerprint;
1487

    
1488
"""
1489

    
1490

    
1491
class BTech(BTechMobileCommon):
1492
    """BTECH's UV-5001 and alike radios"""
1493
    BANDS = 2
1494
    COLOR_LCD = False
1495
    NAME_LENGTH = 6
1496

    
1497
    def set_options(self):
1498
        """This is to read the options from the image and set it in the
1499
        environment, for now just the limits of the freqs in the VHF/UHF
1500
        ranges"""
1501

    
1502
        # setting the correct ranges for each radio type
1503
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1504
            # the model 2501+220 has a segment in 220
1505
            # and a different position in the memmap
1506
            # also the QYT KT8900R
1507
            ranges = self._memobj.ranges220
1508
        else:
1509
            ranges = self._memobj.ranges
1510

    
1511
        # the normal dual bands
1512
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
1513
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
1514

    
1515
        # DEBUG
1516
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
1517
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
1518

    
1519
        # 220Mhz radios case
1520
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1521
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
1522
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
1523
            self._220_range = vhf2
1524

    
1525
        # set the class with the real data
1526
        self._vhf_range = vhf
1527
        self._uhf_range = uhf
1528

    
1529
    def process_mmap(self):
1530
        """Process the mem map into the mem object"""
1531

    
1532
        # Get it
1533
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
1534

    
1535
        # load specific parameters from the radio image
1536
        self.set_options()
1537

    
1538

    
1539
# Declaring Aliases (Clones of the real radios)
1540
class JT2705M(chirp_common.Alias):
1541
    VENDOR = "Jetstream"
1542
    MODEL = "JT2705M"
1543

    
1544

    
1545
class JT6188Mini(chirp_common.Alias):
1546
    VENDOR = "Juentai"
1547
    MODEL = "JT-6188 Mini"
1548

    
1549

    
1550
class JT6188Plus(chirp_common.Alias):
1551
    VENDOR = "Juentai"
1552
    MODEL = "JT-6188 Plus"
1553

    
1554

    
1555
class SSGT890(chirp_common.Alias):
1556
    VENDOR = "Sainsonic"
1557
    MODEL = "GT-890"
1558

    
1559

    
1560
class ZastoneMP300(chirp_common.Alias):
1561
    VENDOR = "Zastone"
1562
    MODEL = "MP-300"
1563

    
1564

    
1565
# real radios
1566
@directory.register
1567
class UV2501(BTech):
1568
    """Baofeng Tech UV2501"""
1569
    MODEL = "UV-2501"
1570
    _fileid = [UV2501G3_fp,
1571
               UV2501G2_fp,
1572
               UV2501pp2_fp,
1573
               UV2501pp_fp]
1574

    
1575

    
1576
@directory.register
1577
class UV2501_220(BTech):
1578
    """Baofeng Tech UV2501+220"""
1579
    MODEL = "UV-2501+220"
1580
    BANDS = 3
1581
    _magic = MSTRING_220
1582
    _id2 = [UV2501_220pp_id, ]
1583
    _fileid = [UV2501_220G3_fp,
1584
               UV2501_220G2_fp,
1585
               UV2501_220_fp,
1586
               UV2501_220pp_fp]
1587

    
1588

    
1589
@directory.register
1590
class UV5001(BTech):
1591
    """Baofeng Tech UV5001"""
1592
    MODEL = "UV-5001"
1593
    _fileid = [UV5001G3_fp,
1594
               UV5001G22_fp,
1595
               UV5001G2_fp,
1596
               UV5001alpha_fp,
1597
               UV5001pp_fp]
1598
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
1599
                     chirp_common.PowerLevel("Low", watts=10)]
1600

    
1601

    
1602
@directory.register
1603
class MINI8900(BTech):
1604
    """WACCOM MINI-8900"""
1605
    VENDOR = "WACCOM"
1606
    MODEL = "MINI-8900"
1607
    _magic = MSTRING_MINI8900
1608
    _fileid = [MINI8900_fp, ]
1609
    # Clones
1610
    ALIASES = [JT6188Plus, ]
1611

    
1612

    
1613
@directory.register
1614
class KTUV980(BTech):
1615
    """QYT KT-UV980"""
1616
    VENDOR = "QYT"
1617
    MODEL = "KT-UV980"
1618
    _vhf_range = (136000000, 175000000)
1619
    _uhf_range = (400000000, 481000000)
1620
    _magic = MSTRING_MINI8900
1621
    _fileid = [KTUV980_fp, ]
1622
    # Clones
1623
    ALIASES = [JT2705M, ]
1624

    
1625
# Please note that there is a version of this radios that is a clone of the
1626
# Waccom Mini8900, maybe an early version?
1627

    
1628

    
1629
class OTGRadioV1(chirp_common.Alias):
1630
    VENDOR = 'OTGSTUFF'
1631
    MODEL = 'OTG Radio v1'
1632

    
1633

    
1634
@directory.register
1635
class KT9800(BTech):
1636
    """QYT KT8900"""
1637
    VENDOR = "QYT"
1638
    MODEL = "KT8900"
1639
    _vhf_range = (136000000, 175000000)
1640
    _uhf_range = (400000000, 481000000)
1641
    _magic = MSTRING_KT8900
1642
    _fileid = [KT8900_fp,
1643
               KT8900_fp1,
1644
               KT8900_fp2,
1645
               KT8900_fp3,
1646
               KT8900_fp4,
1647
               KT8900_fp5,
1648
               KT8900_fp6,
1649
               KT8900_fp7]
1650
    _id2 = [KT8900_id, KT8900_id2]
1651
    # Clones
1652
    ALIASES = [JT6188Mini, SSGT890, ZastoneMP300]
1653

    
1654

    
1655
@directory.register
1656
class KT9800R(BTech):
1657
    """QYT KT8900R"""
1658
    VENDOR = "QYT"
1659
    MODEL = "KT8900R"
1660
    BANDS = 3
1661
    _vhf_range = (136000000, 175000000)
1662
    _220_range = (240000000, 271000000)
1663
    _uhf_range = (400000000, 481000000)
1664
    _magic = MSTRING_KT8900R
1665
    _fileid = [KT8900R_fp,
1666
               KT8900R_fp1,
1667
               KT8900R_fp2,
1668
               KT8900R_fp3,
1669
               KT8900R_fp4,
1670
               KT8900R_fp5]
1671
    _id2 = [KT8900R_id, KT8900R_id2]
1672

    
1673

    
1674
@directory.register
1675
class LT588UV(BTech):
1676
    """LUITON LT-588UV"""
1677
    VENDOR = "LUITON"
1678
    MODEL = "LT-588UV"
1679
    _vhf_range = (136000000, 175000000)
1680
    _uhf_range = (400000000, 481000000)
1681
    _magic = MSTRING_KT8900
1682
    _fileid = [LT588UV_fp,
1683
               LT588UV_fp1]
1684
    _power_levels = [chirp_common.PowerLevel("High", watts=60),
1685
                     chirp_common.PowerLevel("Low", watts=10)]
1686

    
1687

    
1688
COLOR_MEM_FORMAT = """
1689
#seekto 0x0000;
1690
struct {
1691
  lbcd rxfreq[4];
1692
  lbcd txfreq[4];
1693
  ul16 rxtone;
1694
  ul16 txtone;
1695
  u8 unknown0:4,
1696
     scode:4;
1697
  u8 unknown1:2,
1698
     spmute:2,
1699
     unknown2:2,
1700
     optsig:2;
1701
  u8 unknown3:3,
1702
     scramble:1,
1703
     unknown4:2,
1704
     power:2;
1705
  u8 unknown5:1,
1706
     wide:1,
1707
     unknown6:2,
1708
     bcl:1,
1709
     add:1,
1710
     pttid:2;
1711
} memory[200];
1712

    
1713
#seekto 0x0E00;
1714
struct {
1715
  u8 tmr;
1716
  u8 unknown1;
1717
  u8 sql;
1718
  u8 unknown2;
1719
  u8 mgain2;
1720
  u8 tot;
1721
  u8 apo;
1722
  u8 unknown3;
1723
  u8 abr;
1724
  u8 beep;
1725
  u8 unknown4[4];
1726
  u8 dtmfst;
1727
  u8 unknown5[2];
1728
  u8 screv;
1729
  u8 unknown6[2];
1730
  u8 pttid;
1731
  u8 pttlt;
1732
  u8 unknown7;
1733
  u8 emctp;
1734
  u8 emcch;
1735
  u8 sigbp;
1736
  u8 unknown8;
1737
  u8 camdf;
1738
  u8 cbmdf;
1739
  u8 ccmdf;
1740
  u8 cdmdf;
1741
  u8 langua;
1742
  u8 sync;          // BTech radios use this as the display sync
1743
                    // setting, other radios use this as the auto
1744
                    // keypad lock setting
1745
  u8 mainfc;
1746
  u8 mainbc;
1747
  u8 menufc;
1748
  u8 menubc;
1749
  u8 stafc;
1750
  u8 stabc;
1751
  u8 sigfc;
1752
  u8 sigbc;
1753
  u8 rxfc;
1754
  u8 txfc;
1755
  u8 txdisp;
1756
  u8 unknown9[5];
1757
  u8 anil;
1758
  u8 reps;
1759
  u8 repm;
1760
  u8 tmrmr;
1761
  u8 ste;
1762
  u8 rpste;
1763
  u8 rptdl;
1764
  u8 dtmfg;
1765
  u8 mgain;         // used by db25-g for ponyey
1766
  u8 skiptx;
1767
  u8 scmode;
1768
} settings;
1769

    
1770
#seekto 0x0E80;
1771
struct {
1772
  u8 unknown1;
1773
  u8 vfomr;
1774
  u8 keylock;
1775
  u8 unknown2;
1776
  u8 unknown3:4,
1777
     vfomren:1,
1778
     unknown4:1,
1779
     reseten:1,
1780
     menuen:1;
1781
  u8 unknown5[11];
1782
  u8 dispab;
1783
  u8 unknown6[2];
1784
  u8 menu;
1785
  u8 unknown7[7];
1786
  u8 vfomra;
1787
  u8 vfomrb;
1788
  u8 vfomrc;
1789
  u8 vfomrd;
1790
  u8 mrcha;
1791
  u8 mrchb;
1792
  u8 mrchc;
1793
  u8 mrchd;
1794
} settings2;
1795

    
1796
struct settings_vfo {
1797
  u8 freq[8];
1798
  u8 offset[6];
1799
  u8 unknown2[2];
1800
  ul16 rxtone;
1801
  ul16 txtone;
1802
  u8 scode;
1803
  u8 spmute;
1804
  u8 optsig;
1805
  u8 scramble;
1806
  u8 wide;
1807
  u8 power;
1808
  u8 shiftd;
1809
  u8 step;
1810
  u8 unknown3[4];
1811
};
1812

    
1813
#seekto 0x0F00;
1814
struct {
1815
  struct settings_vfo a;
1816
  struct settings_vfo b;
1817
  struct settings_vfo c;
1818
  struct settings_vfo d;
1819
} vfo;
1820

    
1821
#seekto 0x0F80;
1822
struct {
1823
  char line1[8];
1824
  char line2[8];
1825
  char line3[8];
1826
  char line4[8];
1827
  char line5[8];
1828
  char line6[8];
1829
  char line7[8];
1830
  char line8[8];
1831
} poweron_msg;
1832

    
1833
#seekto 0x1000;
1834
struct {
1835
  char name[8];
1836
  u8 unknown1[8];
1837
} names[200];
1838

    
1839
#seekto 0x2400;
1840
struct {
1841
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
1842
  u8 group_tone;
1843
  u8 repeat_tone;
1844
  u8 unused[13];
1845
} _5tone_std_settings[15];
1846

    
1847
#seekto 0x2500;
1848
struct {
1849
  u8 frame1[5];
1850
  u8 frame2[5];
1851
  u8 frame3[5];
1852
  u8 standard;   // one out of LIST_5TONE_STANDARDS
1853
} _5tone_codes[15];
1854

    
1855
#seekto 0x25F0;
1856
struct {
1857
  u8 _5tone_delay1; // * 10ms
1858
  u8 _5tone_delay2; // * 10ms
1859
  u8 _5tone_delay3; // * 10ms
1860
  u8 _5tone_first_digit_ext_length;
1861
  u8 unknown1;
1862
  u8 unknown2;
1863
  u8 unknown3;
1864
  u8 unknown4;
1865
  u8 decode_standard;
1866
  u8 unknown5:5,
1867
     _5tone_decode_call_frame3:1,
1868
     _5tone_decode_call_frame2:1,
1869
     _5tone_decode_call_frame1:1;
1870
  u8 unknown6:5,
1871
     _5tone_decode_disp_frame3:1,
1872
     _5tone_decode_disp_frame2:1,
1873
     _5tone_decode_disp_frame1:1;
1874
  u8 decode_reset_time; // * 100 + 100ms
1875
} _5tone_settings;
1876

    
1877
#seekto 0x2900;
1878
struct {
1879
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
1880
} dtmf_codes[15];
1881

    
1882
#seekto 0x29F0;
1883
struct {
1884
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
1885
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
1886
  u8 unknown0[14];
1887
  u8 inspection[16];
1888
  u8 monitor[16];
1889
  u8 alarmcode[16];
1890
  u8 stun[16];
1891
  u8 kill[16];
1892
  u8 revive[16];
1893
  u8 unknown1[16];
1894
  u8 unknown2[16];
1895
  u8 unknown3[16];
1896
  u8 unknown4[16];
1897
  u8 unknown5[16];
1898
  u8 unknown6[16];
1899
  u8 unknown7[16];
1900
  u8 masterid[16];
1901
  u8 viceid[16];
1902
  u8 unused01:7,
1903
     mastervice:1;
1904
  u8 unused02:3,
1905
     mrevive:1,
1906
     mkill:1,
1907
     mstun:1,
1908
     mmonitor:1,
1909
     minspection:1;
1910
  u8 unused03:3,
1911
     vrevive:1,
1912
     vkill:1,
1913
     vstun:1,
1914
     vmonitor:1,
1915
     vinspection:1;
1916
  u8 unused04:6,
1917
     txdisable:1,
1918
     rxdisable:1;
1919
  u8 groupcode;
1920
  u8 spacecode;
1921
  u8 delayproctime; // * 100 + 100ms
1922
  u8 resettime;     // * 100 + 100ms
1923
} dtmf_settings;
1924

    
1925
#seekto 0x2D00;
1926
struct {
1927
  struct {
1928
    ul16 freq1;
1929
    u8 unused01[6];
1930
    ul16 freq2;
1931
    u8 unused02[6];
1932
  } _2tone_encode[15];
1933
  u8 duration_1st_tone; // *10ms
1934
  u8 duration_2nd_tone; // *10ms
1935
  u8 duration_gap;      // *10ms
1936
  u8 unused03[13];
1937
  struct {
1938
    struct {
1939
      u8 dec;      // one out of LIST_2TONE_DEC
1940
      u8 response; // one out of LIST_2TONE_RESPONSE
1941
      u8 alert;    // 1-16
1942
    } decs[4];
1943
    u8 unused04[4];
1944
  } _2tone_decode[15];
1945
  u8 unused05[16];
1946

    
1947
  struct {
1948
    ul16 freqA;
1949
    ul16 freqB;
1950
    ul16 freqC;
1951
    ul16 freqD;
1952
    // unknown what those values mean, but they are
1953
    // derived from configured frequencies
1954
    ul16 derived_from_freqA; // 2304000/freqA
1955
    ul16 derived_from_freqB; // 2304000/freqB
1956
    ul16 derived_from_freqC; // 2304000/freqC
1957
    ul16 derived_from_freqD; // 2304000/freqD
1958
  }freqs[15];
1959
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
1960
} _2tone;
1961

    
1962
#seekto 0x3D80;
1963
struct {
1964
  u8 vhf_low[3];
1965
  u8 vhf_high[3];
1966
  u8 unknown1[4];
1967
  u8 unknown2[6];
1968
  u8 vhf2_low[3];
1969
  u8 vhf2_high[3];
1970
  u8 unknown3[4];
1971
  u8 unknown4[6];
1972
  u8 uhf_low[3];
1973
  u8 uhf_high[3];
1974
  u8 unknown5[4];
1975
  u8 unknown6[6];
1976
  u8 uhf2_low[3];
1977
  u8 uhf2_high[3];
1978
} ranges;
1979

    
1980
#seekto 0x3F70;
1981
struct {
1982
  char fp[6];
1983
} fingerprint;
1984

    
1985
"""
1986

    
1987

    
1988
class BTechColor(BTechMobileCommon):
1989
    """BTECH's Color LCD Mobile and alike radios"""
1990
    COLOR_LCD = True
1991
    NAME_LENGTH = 8
1992
    LIST_TMR = LIST_TMR16
1993

    
1994
    def process_mmap(self):
1995
        """Process the mem map into the mem object"""
1996

    
1997
        # Get it
1998
        self._memobj = bitwise.parse(COLOR_MEM_FORMAT, self._mmap)
1999

    
2000
        # load specific parameters from the radio image
2001
        self.set_options()
2002

    
2003
    def set_options(self):
2004
        """This is to read the options from the image and set it in the
2005
        environment, for now just the limits of the freqs in the VHF/UHF
2006
        ranges"""
2007

    
2008
        # setting the correct ranges for each radio type
2009
        ranges = self._memobj.ranges
2010

    
2011
        # the normal dual bands
2012
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
2013
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
2014

    
2015
        # DEBUG
2016
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
2017
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
2018

    
2019
        # the additional bands
2020
        if self.MODEL in ["UV-25X4", "KT7900D"]:
2021
            # 200Mhz band
2022
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
2023
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
2024
            self._220_range = vhf2
2025

    
2026
            # 350Mhz band
2027
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
2028
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
2029
            self._350_range = uhf2
2030

    
2031
        # set the class with the real data
2032
        self._vhf_range = vhf
2033
        self._uhf_range = uhf
2034

    
2035

    
2036
# Declaring Aliases (Clones of the real radios)
2037
class SKT8900D(chirp_common.Alias):
2038
    VENDOR = "Surecom"
2039
    MODEL = "S-KT8900D"
2040

    
2041

    
2042
class QB25(chirp_common.Alias):
2043
    VENDOR = "Radioddity"
2044
    MODEL = "QB25"
2045

    
2046

    
2047
# real radios
2048
@directory.register
2049
class UV25X2(BTechColor):
2050
    """Baofeng Tech UV25X2"""
2051
    MODEL = "UV-25X2"
2052
    BANDS = 2
2053
    _vhf_range = (130000000, 180000000)
2054
    _uhf_range = (400000000, 521000000)
2055
    _magic = MSTRING_UV25X2
2056
    _fileid = [UV25X2_fp, ]
2057

    
2058

    
2059
@directory.register
2060
class UV25X4(BTechColor):
2061
    """Baofeng Tech UV25X4"""
2062
    MODEL = "UV-25X4"
2063
    BANDS = 4
2064
    _vhf_range = (130000000, 180000000)
2065
    _220_range = (200000000, 271000000)
2066
    _uhf_range = (400000000, 521000000)
2067
    _350_range = (350000000, 391000000)
2068
    _magic = MSTRING_UV25X4
2069
    _fileid = [UV25X4_fp, ]
2070

    
2071

    
2072
@directory.register
2073
class UV50X2(BTechColor):
2074
    """Baofeng Tech UV50X2"""
2075
    MODEL = "UV-50X2"
2076
    BANDS = 2
2077
    _vhf_range = (130000000, 180000000)
2078
    _uhf_range = (400000000, 521000000)
2079
    _magic = MSTRING_UV25X2
2080
    _fileid = [UV50X2_fp, ]
2081
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
2082
                     chirp_common.PowerLevel("Low", watts=10)]
2083

    
2084

    
2085
@directory.register
2086
class KT7900D(BTechColor):
2087
    """QYT KT7900D"""
2088
    VENDOR = "QYT"
2089
    MODEL = "KT7900D"
2090
    BANDS = 4
2091
    LIST_TMR = LIST_TMR15
2092
    _vhf_range = (136000000, 175000000)
2093
    _220_range = (200000000, 271000000)
2094
    _uhf_range = (400000000, 481000000)
2095
    _350_range = (350000000, 371000000)
2096
    _magic = MSTRING_KT8900D
2097
    _fileid = [KT7900D_fp, KT7900D_fp1, KT7900D_fp2, KT7900D_fp3, KT7900D_fp4,
2098
               KT7900D_fp5, KT7900D_fp6, KT7900D_fp7, QB25_fp, ]
2099
    # Clones
2100
    ALIASES = [SKT8900D, QB25, ]
2101

    
2102

    
2103
@directory.register
2104
class KT8900D(BTechColor):
2105
    """QYT KT8900D"""
2106
    VENDOR = "QYT"
2107
    MODEL = "KT8900D"
2108
    BANDS = 2
2109
    LIST_TMR = LIST_TMR15
2110
    _vhf_range = (136000000, 175000000)
2111
    _uhf_range = (400000000, 481000000)
2112
    _magic = MSTRING_KT8900D
2113
    _fileid = [KT8900D_fp3, KT8900D_fp2, KT8900D_fp1, KT8900D_fp]
2114

    
2115
    # Clones
2116
    ALIASES = [OTGRadioV1]
2117

    
2118

    
2119
@directory.register
2120
class KT5800(BTechColor):
2121
    """QYT KT5800"""
2122
    VENDOR = "QYT"
2123
    MODEL = "KT5800"
2124
    BANDS = 2
2125
    LIST_TMR = LIST_TMR15
2126
    _vhf_range = (136000000, 175000000)
2127
    _uhf_range = (400000000, 481000000)
2128
    _magic = MSTRING_KT8900D
2129
    _fileid = [KT5800_fp, ]
2130

    
2131

    
2132
@directory.register
2133
class KT980PLUS(BTechColor):
2134
    """QYT KT980PLUS"""
2135
    VENDOR = "QYT"
2136
    MODEL = "KT980PLUS"
2137
    BANDS = 2
2138
    LIST_TMR = LIST_TMR15
2139
    _vhf_range = (136000000, 175000000)
2140
    _uhf_range = (400000000, 481000000)
2141
    _magic = MSTRING_KT8900D
2142
    _fileid = [KT980PLUS_fp1, KT980PLUS_fp]
2143
    _power_levels = [chirp_common.PowerLevel("High", watts=75),
2144
                     chirp_common.PowerLevel("Low", watts=55)]
2145

    
2146
    @classmethod
2147
    def match_model(cls, filedata, filename):
2148
        # This model is only ever matched via metadata
2149
        return False
2150

    
2151

    
2152
@directory.register
2153
class DB25G(BTechColor):
2154
    """Radioddity DB25-G"""
2155
    VENDOR = "Radioddity"
2156
    MODEL = "DB25-G"
2157
    BANDS = 2
2158
    LIST_TMR = LIST_TMR15
2159
    _vhf_range = (136000000, 175000000)
2160
    _uhf_range = (400000000, 481000000)
2161
    _magic = MSTRING_KT8900D
2162
    _fileid = [DB25G_fp1, DB25G_fp]
2163
    _gmrs = True
2164
    _power_levels = [chirp_common.PowerLevel("High", watts=25),
2165
                     chirp_common.PowerLevel("Mid", watts=15),
2166
                     chirp_common.PowerLevel("Low", watts=5)]
2167

    
2168
    @classmethod
2169
    def match_model(cls, filedata, filename):
2170
        # This model is only ever matched via metadata
2171
        return False
2172

    
2173

    
2174
GMRS_MEM_FORMAT = """
2175
#seekto 0x0000;
2176
struct {
2177
  lbcd rxfreq[4];
2178
  lbcd txfreq[4];
2179
  ul16 rxtone;
2180
  ul16 txtone;
2181
  u8 unknown0:4,
2182
     scode:4;
2183
  u8 unknown1:2,
2184
     spmute:2,
2185
     unknown2:2,
2186
     optsig:2;
2187
  u8 unknown3:3,
2188
     scramble:1,
2189
     unknown4:2,
2190
     power:2;
2191
  u8 unknown5:1,
2192
     wide:1,
2193
     unknown6:2,
2194
     bcl:1,
2195
     add:1,
2196
     pttid:2;
2197
} memory[256];
2198

    
2199
#seekto 0x1000;
2200
struct {
2201
  char name[7];
2202
  u8 unknown1[9];
2203
} names[256];
2204

    
2205
#seekto 0x2400;
2206
struct {
2207
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
2208
  u8 group_tone;
2209
  u8 repeat_tone;
2210
  u8 unused[13];
2211
} _5tone_std_settings[15];
2212

    
2213
#seekto 0x2500;
2214
struct {
2215
  u8 frame1[5];
2216
  u8 frame2[5];
2217
  u8 frame3[5];
2218
  u8 standard;   // one out of LIST_5TONE_STANDARDS
2219
} _5tone_codes[15];
2220

    
2221
#seekto 0x25F0;
2222
struct {
2223
  u8 _5tone_delay1; // * 10ms
2224
  u8 _5tone_delay2; // * 10ms
2225
  u8 _5tone_delay3; // * 10ms
2226
  u8 _5tone_first_digit_ext_length;
2227
  u8 unknown1;
2228
  u8 unknown2;
2229
  u8 unknown3;
2230
  u8 unknown4;
2231
  u8 decode_standard;
2232
  u8 unknown5:5,
2233
     _5tone_decode_call_frame3:1,
2234
     _5tone_decode_call_frame2:1,
2235
     _5tone_decode_call_frame1:1;
2236
  u8 unknown6:5,
2237
     _5tone_decode_disp_frame3:1,
2238
     _5tone_decode_disp_frame2:1,
2239
     _5tone_decode_disp_frame1:1;
2240
  u8 decode_reset_time; // * 100 + 100ms
2241
} _5tone_settings;
2242

    
2243
#seekto 0x2900;
2244
struct {
2245
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
2246
} dtmf_codes[15];
2247

    
2248
#seekto 0x29F0;
2249
struct {
2250
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
2251
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
2252
  u8 unknown0[14];
2253
  u8 inspection[16];
2254
  u8 monitor[16];
2255
  u8 alarmcode[16];
2256
  u8 stun[16];
2257
  u8 kill[16];
2258
  u8 revive[16];
2259
  u8 unknown1[16];
2260
  u8 unknown2[16];
2261
  u8 unknown3[16];
2262
  u8 unknown4[16];
2263
  u8 unknown5[16];
2264
  u8 unknown6[16];
2265
  u8 unknown7[16];
2266
  u8 masterid[16];
2267
  u8 viceid[16];
2268
  u8 unused01:7,
2269
     mastervice:1;
2270
  u8 unused02:3,
2271
     mrevive:1,
2272
     mkill:1,
2273
     mstun:1,
2274
     mmonitor:1,
2275
     minspection:1;
2276
  u8 unused03:3,
2277
     vrevive:1,
2278
     vkill:1,
2279
     vstun:1,
2280
     vmonitor:1,
2281
     vinspection:1;
2282
  u8 unused04:6,
2283
     txdisable:1,
2284
     rxdisable:1;
2285
  u8 groupcode;
2286
  u8 spacecode;
2287
  u8 delayproctime; // * 100 + 100ms
2288
  u8 resettime;     // * 100 + 100ms
2289
} dtmf_settings;
2290

    
2291
#seekto 0x2D00;
2292
struct {
2293
  struct {
2294
    ul16 freq1;
2295
    u8 unused01[6];
2296
    ul16 freq2;
2297
    u8 unused02[6];
2298
  } _2tone_encode[15];
2299
  u8 duration_1st_tone; // *10ms
2300
  u8 duration_2nd_tone; // *10ms
2301
  u8 duration_gap;      // *10ms
2302
  u8 unused03[13];
2303
  struct {
2304
    struct {
2305
      u8 dec;      // one out of LIST_2TONE_DEC
2306
      u8 response; // one out of LIST_2TONE_RESPONSE
2307
      u8 alert;    // 1-16
2308
    } decs[4];
2309
    u8 unused04[4];
2310
  } _2tone_decode[15];
2311
  u8 unused05[16];
2312

    
2313
  struct {
2314
    ul16 freqA;
2315
    ul16 freqB;
2316
    ul16 freqC;
2317
    ul16 freqD;
2318
    // unknown what those values mean, but they are
2319
    // derived from configured frequencies
2320
    ul16 derived_from_freqA; // 2304000/freqA
2321
    ul16 derived_from_freqB; // 2304000/freqB
2322
    ul16 derived_from_freqC; // 2304000/freqC
2323
    ul16 derived_from_freqD; // 2304000/freqD
2324
  }freqs[15];
2325
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
2326
} _2tone;
2327

    
2328
#seekto 0x3000;
2329
struct {
2330
  u8 freq[8];
2331
  char broadcast_station_name[6];
2332
  u8 unknown[2];
2333
} fm_radio_preset[16];
2334

    
2335
#seekto 0x3200;
2336
struct {
2337
  u8 tmr;
2338
  u8 unknown1;
2339
  u8 sql;
2340
  u8 unknown2;
2341
  u8 autolk;
2342
  u8 tot;
2343
  u8 apo;
2344
  u8 unknown3;
2345
  u8 abr;
2346
  u8 beep;
2347
  u8 unknown4[4];
2348
  u8 dtmfst;
2349
  u8 unknown5[2];
2350
  u8 screv;
2351
  u8 unknown6[2];
2352
  u8 pttid;
2353
  u8 pttlt;
2354
  u8 unknown7;
2355
  u8 emctp;
2356
  u8 emcch;
2357
  u8 sigbp;
2358
  u8 unknown8;
2359
  u8 camdf;
2360
  u8 cbmdf;
2361
  u8 ccmdf;
2362
  u8 cdmdf;
2363
  u8 langua;
2364
  u8 sync;
2365

    
2366

    
2367
  u8 stfc;
2368
  u8 mffc;
2369
  u8 sfafc;
2370
  u8 sfbfc;
2371
  u8 sfcfc;
2372
  u8 sfdfc;
2373
  u8 subfc;
2374
  u8 fmfc;
2375
  u8 sigfc;
2376
  u8 modfc;
2377
  u8 menufc;
2378
  u8 txfc;
2379
  u8 txdisp;
2380
  u8 unknown9[5];
2381
  u8 anil;
2382
  u8 reps;
2383
  u8 repm;
2384
  u8 tmrmr;
2385
  u8 ste;
2386
  u8 rpste;
2387
  u8 rptdl;
2388
  u8 dtmfg;
2389
  u8 mgain;
2390
  u8 skiptx;
2391
  u8 scmode;
2392
} settings;
2393

    
2394
#seekto 0x3280;
2395
struct {
2396
  u8 unknown1;
2397
  u8 vfomr;
2398
  u8 keylock;
2399
  u8 unknown2;
2400
  u8 unknown3:4,
2401
     vfomren:1,
2402
     unknown4:1,
2403
     reseten:1,
2404
     menuen:1;
2405
  u8 unknown5[11];
2406
  u8 dispab;
2407
  u8 unknown6[2];
2408
  u8 smenu;
2409
  u8 unknown7[7];
2410
  u8 vfomra;
2411
  u8 vfomrb;
2412
  u8 vfomrc;
2413
  u8 vfomrd;
2414
  u8 mrcha;
2415
  u8 mrchb;
2416
  u8 mrchc;
2417
  u8 mrchd;
2418
} settings2;
2419

    
2420
struct settings_vfo {
2421
  u8 freq[8];
2422
  u8 offset[6];
2423
  u8 unknown2[2];
2424
  ul16 rxtone;
2425
  ul16 txtone;
2426
  u8 scode;
2427
  u8 spmute;
2428
  u8 optsig;
2429
  u8 scramble;
2430
  u8 wide;
2431
  u8 power;
2432
  u8 shiftd;
2433
  u8 step;
2434
  u8 unknown3[4];
2435
};
2436

    
2437
#seekto 0x3300;
2438
struct {
2439
  struct settings_vfo a;
2440
  struct settings_vfo b;
2441
  struct settings_vfo c;
2442
  struct settings_vfo d;
2443
} vfo;
2444

    
2445
#seekto 0x3D80;
2446
struct {
2447
  u8 vhf_low[3];
2448
  u8 vhf_high[3];
2449
  u8 unknown1[4];
2450
  u8 unknown2[6];
2451
  u8 vhf2_low[3];
2452
  u8 vhf2_high[3];
2453
  u8 unknown3[4];
2454
  u8 unknown4[6];
2455
  u8 uhf_low[3];
2456
  u8 uhf_high[3];
2457
  u8 unknown5[4];
2458
  u8 unknown6[6];
2459
  u8 uhf2_low[3];
2460
  u8 uhf2_high[3];
2461
} ranges;
2462

    
2463
#seekto 0x33B0;
2464
struct {
2465
  char line[16];
2466
} static_msg;
2467

    
2468
#seekto 0x3F70;
2469
struct {
2470
  char fp[6];
2471
} fingerprint;
2472

    
2473
"""
2474

    
2475

    
2476
class BTechGMRS(BTechMobileCommon):
2477
    """BTECH's GMRS Mobile"""
2478
    COLOR_LCD = True
2479
    COLOR_LCD2 = True
2480
    NAME_LENGTH = 7
2481
    UPLOAD_MEM_SIZE = 0X3400
2482

    
2483
    def process_mmap(self):
2484
        """Process the mem map into the mem object"""
2485

    
2486
        # Get it
2487
        self._memobj = bitwise.parse(GMRS_MEM_FORMAT, self._mmap)
2488

    
2489
        # load specific parameters from the radio image
2490
        self.set_options()
2491

    
2492
    def set_options(self):
2493
        """This is to read the options from the image and set it in the
2494
        environment, for now just the limits of the freqs in the VHF/UHF
2495
        ranges"""
2496

    
2497
        # setting the correct ranges for each radio type
2498
        ranges = self._memobj.ranges
2499

    
2500
        # the normal dual bands
2501
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
2502
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
2503

    
2504
        # DEBUG
2505
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
2506
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
2507

    
2508
        # set the class with the real data
2509
        self._vhf_range = vhf
2510
        self._uhf_range = uhf
2511

    
2512

    
2513
# real radios
2514
@directory.register
2515
class GMRS50X1(BTechGMRS):
2516
    """Baofeng Tech GMRS50X1"""
2517
    MODEL = "GMRS-50X1"
2518
    BANDS = 2
2519
    LIST_TMR = LIST_TMR16
2520
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
2521
                     chirp_common.PowerLevel("Mid", watts=10),
2522
                     chirp_common.PowerLevel("Low", watts=5)]
2523
    _vhf_range = (136000000, 175000000)
2524
    _uhf_range = (400000000, 521000000)
2525
    _upper = 255
2526
    _magic = MSTRING_GMRS50X1
2527
    _fileid = [GMRS50X1_fp1, GMRS50X1_fp, ]
2528

    
2529

    
2530
COLORHT_MEM_FORMAT = """
2531
#seekto 0x0000;
2532
struct {
2533
  lbcd rxfreq[4];
2534
  lbcd txfreq[4];
2535
  ul16 rxtone;
2536
  ul16 txtone;
2537
  u8 unknown0:4,
2538
     scode:4;
2539
  u8 unknown1:2,
2540
     spmute:2,
2541
     unknown2:2,
2542
     optsig:2;
2543
  u8 unknown3:3,
2544
     scramble:1,
2545
     unknown4:3,
2546
     power:1;
2547
  u8 unknown5:1,
2548
     wide:1,
2549
     unknown6:2,
2550
     bcl:1,
2551
     add:1,
2552
     pttid:2;
2553
} memory[200];
2554

    
2555
#seekto 0x0E00;
2556
struct {
2557
  u8 tmr;
2558
  u8 unknownE01;
2559
  u8 sql;
2560
  u8 unknownE03[2];
2561
  u8 tot;
2562
  u8 save;
2563
  u8 unknownE07;
2564
  u8 abr;
2565
  u8 beep;
2566
  u8 unknownE0A[4];
2567
  u8 dsub;
2568
  u8 dtmfst;
2569
  u8 screv;
2570
  u8 unknownE11[3];
2571
  u8 pttid;
2572
  u8 unknownE15;
2573
  u8 pttlt;
2574
  u8 unknownE17;
2575
  u8 emctp;
2576
  u8 emcch;
2577
  u8 sigbp;
2578
  u8 unknownE1B;
2579
  u8 camdf;
2580
  u8 cbmdf;
2581
  u8 ccmdf;
2582
  u8 cdmdf;
2583
  u8 langua;
2584
  u8 voice;
2585
  u8 vox;
2586
  u8 voxt;
2587
  u8 sync;          // BTech radios use this as the display sync setting
2588
                    // other radios use this as the auto keypad lock setting
2589
  u8 stfc;
2590
  u8 mffc;
2591
  u8 sfafc;
2592
  u8 sfbfc;
2593
  u8 sfcfc;
2594
  u8 sfdfc;
2595
  u8 subfc;
2596
  u8 fmfc;
2597
  u8 sigfc;
2598
  u8 menufc;
2599
  u8 txfc;
2600
  u8 rxfc;
2601
  u8 unknownE31[5];
2602
  u8 anil;
2603
  u8 reps;
2604
  u8 tmrmr;
2605
  u8 ste;
2606
  u8 rpste;
2607
  u8 rptdl;
2608
  u8 dtmfg;
2609
  u8 tmrtx;
2610
} settings;
2611

    
2612
#seekto 0x0E80;
2613
struct {
2614
  u8 unknown1;
2615
  u8 vfomr;
2616
  u8 keylock;
2617
  u8 unknown2;
2618
  u8 unknown3:4,
2619
     vfomren:1,
2620
     unknown4:1,
2621
     reseten:1,
2622
     menuen:1;
2623
  u8 unknown5[11];
2624
  u8 dispab;
2625
  u8 unknown6[2];
2626
  u8 menu;
2627
  u8 unknown7[7];
2628
  u8 vfomra;
2629
  u8 vfomrb;
2630
  u8 vfomrc;
2631
  u8 vfomrd;
2632
  u8 mrcha;
2633
  u8 mrchb;
2634
  u8 mrchc;
2635
  u8 mrchd;
2636
} settings2;
2637

    
2638
struct settings_vfo {
2639
  u8 freq[8];
2640
  u8 offset[6];
2641
  u8 unknown2[2];
2642
  ul16 rxtone;
2643
  ul16 txtone;
2644
  u8 scode;
2645
  u8 spmute;
2646
  u8 optsig;
2647
  u8 scramble;
2648
  u8 wide;
2649
  u8 power;
2650
  u8 shiftd;
2651
  u8 step;
2652
  u8 unknown3[4];
2653
};
2654

    
2655
#seekto 0x0F00;
2656
struct {
2657
  struct settings_vfo a;
2658
  struct settings_vfo b;
2659
  struct settings_vfo c;
2660
  struct settings_vfo d;
2661
} vfo;
2662

    
2663
#seekto 0x0FE0;
2664
struct {
2665
  char line[16];
2666
} static_msg;
2667

    
2668
#seekto 0x1000;
2669
struct {
2670
  char name[8];
2671
  u8 unknown1[8];
2672
} names[200];
2673

    
2674
#seekto 0x2400;
2675
struct {
2676
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
2677
  u8 group_tone;
2678
  u8 repeat_tone;
2679
  u8 unused[13];
2680
} _5tone_std_settings[15];
2681

    
2682
#seekto 0x2500;
2683
struct {
2684
  u8 frame1[5];
2685
  u8 frame2[5];
2686
  u8 frame3[5];
2687
  u8 standard;   // one out of LIST_5TONE_STANDARDS
2688
} _5tone_codes[15];
2689

    
2690
#seekto 0x25F0;
2691
struct {
2692
  u8 _5tone_delay1; // * 10ms
2693
  u8 _5tone_delay2; // * 10ms
2694
  u8 _5tone_delay3; // * 10ms
2695
  u8 _5tone_first_digit_ext_length;
2696
  u8 unknown1;
2697
  u8 unknown2;
2698
  u8 unknown3;
2699
  u8 unknown4;
2700
  u8 decode_standard;
2701
  u8 unknown5:5,
2702
     _5tone_decode_call_frame3:1,
2703
     _5tone_decode_call_frame2:1,
2704
     _5tone_decode_call_frame1:1;
2705
  u8 unknown6:5,
2706
     _5tone_decode_disp_frame3:1,
2707
     _5tone_decode_disp_frame2:1,
2708
     _5tone_decode_disp_frame1:1;
2709
  u8 decode_reset_time; // * 100 + 100ms
2710
} _5tone_settings;
2711

    
2712
#seekto 0x2900;
2713
struct {
2714
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
2715
} dtmf_codes[15];
2716

    
2717
#seekto 0x29F0;
2718
struct {
2719
  u8 dtmfspeed_on;  //list with 50..2000ms in steps of 10
2720
  u8 dtmfspeed_off; //list with 50..2000ms in steps of 10
2721
  u8 unknown0[14];
2722
  u8 inspection[16];
2723
  u8 monitor[16];
2724
  u8 alarmcode[16];
2725
  u8 stun[16];
2726
  u8 kill[16];
2727
  u8 revive[16];
2728
  u8 unknown1[16];
2729
  u8 unknown2[16];
2730
  u8 unknown3[16];
2731
  u8 unknown4[16];
2732
  u8 unknown5[16];
2733
  u8 unknown6[16];
2734
  u8 unknown7[16];
2735
  u8 masterid[16];
2736
  u8 viceid[16];
2737
  u8 unused01:7,
2738
     mastervice:1;
2739
  u8 unused02:3,
2740
     mrevive:1,
2741
     mkill:1,
2742
     mstun:1,
2743
     mmonitor:1,
2744
     minspection:1;
2745
  u8 unused03:3,
2746
     vrevive:1,
2747
     vkill:1,
2748
     vstun:1,
2749
     vmonitor:1,
2750
     vinspection:1;
2751
  u8 unused04:6,
2752
     txdisable:1,
2753
     rxdisable:1;
2754
  u8 groupcode;
2755
  u8 spacecode;
2756
  u8 delayproctime; // * 100 + 100ms
2757
  u8 resettime;     // * 100 + 100ms
2758
} dtmf_settings;
2759

    
2760
#seekto 0x2D00;
2761
struct {
2762
  struct {
2763
    ul16 freq1;
2764
    u8 unused01[6];
2765
    ul16 freq2;
2766
    u8 unused02[6];
2767
  } _2tone_encode[15];
2768
  u8 duration_1st_tone; // *10ms
2769
  u8 duration_2nd_tone; // *10ms
2770
  u8 duration_gap;      // *10ms
2771
  u8 unused03[13];
2772
  struct {
2773
    struct {
2774
      u8 dec;      // one out of LIST_2TONE_DEC
2775
      u8 response; // one out of LIST_2TONE_RESPONSE
2776
      u8 alert;    // 1-16
2777
    } decs[4];
2778
    u8 unused04[4];
2779
  } _2tone_decode[15];
2780
  u8 unused05[16];
2781

    
2782
  struct {
2783
    ul16 freqA;
2784
    ul16 freqB;
2785
    ul16 freqC;
2786
    ul16 freqD;
2787
    // unknown what those values mean, but they are
2788
    // derived from configured frequencies
2789
    ul16 derived_from_freqA; // 2304000/freqA
2790
    ul16 derived_from_freqB; // 2304000/freqB
2791
    ul16 derived_from_freqC; // 2304000/freqC
2792
    ul16 derived_from_freqD; // 2304000/freqD
2793
  }freqs[15];
2794
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
2795
} _2tone;
2796

    
2797
#seekto 0x3D80;
2798
struct {
2799
  u8 vhf_low[3];
2800
  u8 vhf_high[3];
2801
  u8 unknown1[4];
2802
  u8 unknown2[6];
2803
  u8 vhf2_low[3];
2804
  u8 vhf2_high[3];
2805
  u8 unknown3[4];
2806
  u8 unknown4[6];
2807
  u8 uhf_low[3];
2808
  u8 uhf_high[3];
2809
  u8 unknown5[4];
2810
  u8 unknown6[6];
2811
  u8 uhf2_low[3];
2812
  u8 uhf2_high[3];
2813
} ranges;
2814

    
2815
#seekto 0x3F70;
2816
struct {
2817
  char fp[6];
2818
} fingerprint;
2819

    
2820
"""
2821

    
2822

    
2823
class QYTColorHT(BTechMobileCommon):
2824
    """QTY's Color LCD Handheld and alike radios"""
2825
    COLOR_LCD = True
2826
    COLOR_LCD3 = True
2827
    NAME_LENGTH = 8
2828
    LIST_TMR = LIST_TMR15
2829

    
2830
    def process_mmap(self):
2831
        """Process the mem map into the mem object"""
2832

    
2833
        # Get it
2834
        self._memobj = bitwise.parse(COLORHT_MEM_FORMAT, self._mmap)
2835

    
2836
        # load specific parameters from the radio image
2837
        self.set_options()
2838

    
2839
    def set_options(self):
2840
        """This is to read the options from the image and set it in the
2841
        environment, for now just the limits of the freqs in the VHF/UHF
2842
        ranges"""
2843

    
2844
        # setting the correct ranges for each radio type
2845
        ranges = self._memobj.ranges
2846

    
2847
        # the normal dual bands
2848
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
2849
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
2850

    
2851
        # DEBUG
2852
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
2853
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
2854

    
2855
        # the additional bands
2856
        if self.MODEL in ["KT-8R"]:
2857
            # 200Mhz band
2858
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
2859
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
2860
            self._220_range = vhf2
2861

    
2862
            # 350Mhz band
2863
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
2864
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
2865
            self._350_range = uhf2
2866

    
2867
        # set the class with the real data
2868
        self._vhf_range = vhf
2869
        self._uhf_range = uhf
2870

    
2871

    
2872
# real radios
2873
@directory.register
2874
class KT8R(QYTColorHT):
2875
    """QYT KT8R"""
2876
    VENDOR = "QYT"
2877
    MODEL = "KT-8R"
2878
    BANDS = 4
2879
    LIST_TMR = LIST_TMR16
2880
    _vhf_range = (136000000, 175000000)
2881
    _220_range = (200000000, 261000000)
2882
    _uhf_range = (400000000, 481000000)
2883
    _350_range = (350000000, 391000000)
2884
    _magic = MSTRING_KT8R
2885
    _fileid = [KT8R_fp2, KT8R_fp1, KT8R_fp, ]
2886
    _power_levels = [chirp_common.PowerLevel("High", watts=5),
2887
                     chirp_common.PowerLevel("Low", watts=1)]
(12-12/16)