Project

General

Profile

Feature #9825 » btech-set_kt8900_band_limits_#5.py

for KT8900 and similar radios only - Jim Unroe, 04/11/2022 02:42 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
# 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
GMRS_FREQS1 = [462.5625, 462.5875, 462.6125, 462.6375, 462.6625,
148
               462.6875, 462.7125]
149
GMRS_FREQS2 = [467.5625, 467.5875, 467.6125, 467.6375, 467.6625,
150
               467.6875, 467.7125]
151
GMRS_FREQS3 = [462.5500, 462.5750, 462.6000, 462.6250, 462.6500,
152
               462.6750, 462.7000, 462.7250]
153
GMRS_FREQS = GMRS_FREQS1 + GMRS_FREQS2 + GMRS_FREQS3 * 2
154

    
155

    
156
# #### ID strings #####################################################
157

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

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

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

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

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

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

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

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

    
206

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

    
210

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

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

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

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

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

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

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

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

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

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

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

    
286

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

    
308

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

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

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

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

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

    
335

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

    
339
    data = ""
340

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

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

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

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

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

    
361
    return data
362

    
363

    
364
def _send(radio, data, upload=False):
365
    """Send data to the radio device"""
366

    
367
    try:
368
        for byte in data:
369
            radio.pipe.write(byte)
370
            # Some OS (mainly Linux ones) are too fast on the serial and
371
            # get the MCU inside the radio stuck in the early stages, this
372
            # hits some models more than others.
373
            #
374
            # To cope with that we introduce a delay on the writes.
375
            # Many option have been tested (delaying only after error occures,
376
            # after short reads, only for linux, ...)
377
            # Finally, a static delay was chosen as simplest of all solutions
378
            # (Michael Wagner, OE4AMW)
379
            # (for details, see issue 3993)
380
            #
381
            # skip 'sleep()' when uploading added by Jim Unroe, KC9HI
382
            if upload is False:
383
                sleep(0.002)
384

    
385
        # DEBUG
386
        if debug is True:
387
            LOG.debug("==> (%d) bytes:\n\n%s" %
388
                      (len(data), util.hexprint(data)))
389
    except:
390
        raise errors.RadioError("Error sending data to radio")
391

    
392

    
393
def _make_frame(cmd, addr, length, data=""):
394
    """Pack the info in the headder format"""
395
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
396
    # add the data if set
397
    if len(data) != 0:
398
        frame += data
399

    
400
    return frame
401

    
402

    
403
def _recv(radio, addr):
404
    """Get data from the radio all at once to lower syscalls load"""
405

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

    
409
    # get the whole block
410
    block = _rawrecv(radio, BLOCK_SIZE + 5)
411

    
412
    # basic check
413
    if len(block) < (BLOCK_SIZE + 5):
414
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
415

    
416
    # checking for the ack
417
    if block[0] != ACK_CMD:
418
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
419

    
420
    # header validation
421
    c, a, l = struct.unpack(">BHB", block[1:5])
422
    if a != addr or l != BLOCK_SIZE or c != ord("X"):
423
        LOG.debug("Invalid header for block 0x%04x" % addr)
424
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
425
        raise errors.RadioError("Invalid header for block 0x%04x:" % addr)
426

    
427
    # return the data
428
    return block[5:]
429

    
430

    
431
def _start_clone_mode(radio, status):
432
    """Put the radio in clone mode and get the ident string, 3 tries"""
433

    
434
    # cleaning the serial buffer
435
    _clean_buffer(radio)
436

    
437
    # prep the data to show in the UI
438
    status.cur = 0
439
    status.msg = "Identifying the radio..."
440
    status.max = 3
441
    radio.status_fn(status)
442

    
443
    try:
444
        for a in range(0, status.max):
445
            # Update the UI
446
            status.cur = a + 1
447
            radio.status_fn(status)
448

    
449
            # send the magic word
450
            _send(radio, radio._magic)
451

    
452
            # Now you get a x06 of ACK if all goes well
453
            ack = radio.pipe.read(1)
454

    
455
            if ack == "\x06":
456
                # DEBUG
457
                LOG.info("Magic ACK received")
458
                status.cur = status.max
459
                radio.status_fn(status)
460

    
461
                return True
462

    
463
        return False
464

    
465
    except errors.RadioError:
466
        raise
467
    except Exception, e:
468
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
469

    
470

    
471
def _do_ident(radio, status, upload=False):
472
    """Put the radio in PROGRAM mode & identify it"""
473
    #  set the serial discipline
474
    radio.pipe.baudrate = 9600
475
    radio.pipe.parity = "N"
476

    
477
    # open the radio into program mode
478
    if _start_clone_mode(radio, status) is False:
479
        msg = "Radio did not enter clone mode"
480
        # warning about old versions of QYT KT8900
481
        if radio.MODEL == "KT8900":
482
            msg += ". You may want to try it as a WACCOM MINI-8900, there is a"
483
            msg += " known variant of this radios that is a clone of it."
484
        raise errors.RadioError(msg)
485

    
486
    # Ok, get the ident string
487
    ident = _rawrecv(radio, 49)
488

    
489
    # basic check for the ident
490
    if len(ident) != 49:
491
        raise errors.RadioError("Radio send a short ident block.")
492

    
493
    # check if ident is OK
494
    itis = False
495
    for fp in radio._fileid:
496
        if fp in ident:
497
            # got it!
498
            itis = True
499
            # checking if we are dealing with a Gen 3 BTECH
500
            if radio.VENDOR == "BTECH" and fp in BTECH3:
501
                radio.btech3 = True
502

    
503
            break
504

    
505
    if itis is False:
506
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
507
        raise errors.RadioError("Radio identification failed.")
508

    
509
    # some radios needs a extra read and check for a code on it, this ones
510
    # has the check value in the _id2 var, others simply False
511
    if radio._id2 is not False:
512
        # lower the timeout here as this radios are reseting due to timeout
513
        radio.pipe.timeout = 0.05
514

    
515
        # query & receive the extra ID
516
        _send(radio, _make_frame("S", 0x3DF0, 16))
517
        id2 = _rawrecv(radio, 21)
518

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

    
526
        # ok, the correct string must be in the received data
527
        # the radio._id2 var will be always a list
528
        flag2 = False
529
        for _id2 in radio._id2:
530
            if _id2 in id2:
531
                flag2 = True
532

    
533
        if not flag2:
534
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
535
                      (radio.MODEL, util.hexprint(id2)))
536
            raise errors.RadioError("The extra ID is wrong, aborting.")
537

    
538
        # this radios need a extra request/answer here on the upload
539
        # the amount of data received depends of the radio type
540
        #
541
        # also the first block of TX must no have the ACK at the beginning
542
        # see _upload for this.
543
        if upload is True:
544
            # send an ACK
545
            _send(radio, ACK_CMD)
546

    
547
            # the amount of data depend on the radio, so far we have two radios
548
            # reading two bytes with an ACK at the end and just ONE with just
549
            # one byte (QYT KT8900)
550
            # the JT-6188 appears a clone of the last, but reads TWO bytes.
551
            #
552
            # we will read two bytes with a custom timeout to not penalize the
553
            # users for this.
554
            #
555
            # we just check for a response and last byte being a ACK, that is
556
            # the common stone for all radios (3 so far)
557
            ack = _rawrecv(radio, 2)
558

    
559
            # checking
560
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
561
                raise errors.RadioError("Radio didn't ACK the upload")
562

    
563
            # restore the default serial timeout
564
            radio.pipe.timeout = STIMEOUT
565

    
566
    # DEBUG
567
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
568

    
569
    return True
570

    
571

    
572
def _download(radio):
573
    """Get the memory map"""
574

    
575
    # UI progress
576
    status = chirp_common.Status()
577

    
578
    # put radio in program mode and identify it
579
    _do_ident(radio, status)
580

    
581
    # the models that doesn't have the extra ID have to make a dummy read here
582
    if radio._id2 is False:
583
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
584
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
585

    
586
        if debug is True:
587
            LOG.info("Dummy first block read done, got this:\n\n %s",
588
                     util.hexprint(discard))
589

    
590
    # reset the progress bar in the UI
591
    status.max = MEM_SIZE / BLOCK_SIZE
592
    status.msg = "Cloning from radio..."
593
    status.cur = 0
594
    radio.status_fn(status)
595

    
596
    # cleaning the serial buffer
597
    _clean_buffer(radio)
598

    
599
    data = ""
600
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
601
        # sending the read request
602
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
603

    
604
        # read
605
        d = _recv(radio, addr)
606

    
607
        # aggregate the data
608
        data += d
609

    
610
        # UI Update
611
        status.cur = addr / BLOCK_SIZE
612
        status.msg = "Cloning from radio..."
613
        radio.status_fn(status)
614

    
615
    return data
616

    
617

    
618
def _upload(radio):
619
    """Upload procedure"""
620

    
621
    # The UPLOAD mem is restricted to lower than 0x3100,
622
    # so we will overide that here localy
623
    MEM_SIZE = radio.UPLOAD_MEM_SIZE
624

    
625
    # UI progress
626
    status = chirp_common.Status()
627

    
628
    # put radio in program mode and identify it
629
    _do_ident(radio, status, True)
630

    
631
    # get the data to upload to radio
632
    data = radio.get_mmap()
633

    
634
    # Reset the UI progress
635
    status.max = MEM_SIZE / TX_BLOCK_SIZE
636
    status.cur = 0
637
    status.msg = "Cloning to radio..."
638
    radio.status_fn(status)
639

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

    
644
    # cleaning the serial buffer
645
    _clean_buffer(radio)
646

    
647
    # the fun start here
648
    for addr in range(0x3C90, 0x3C9F, TX_BLOCK_SIZE):  # set band limits for KT-8900 and similar radios only
649
        # getting the block of data to send
650
        d = data[addr:addr + TX_BLOCK_SIZE]
651

    
652
        # build the frame to send
653
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
654

    
655
        # first block must not send the ACK at the beginning for the
656
        # ones that has the extra id, since this have to do a extra step
657
        if addr == 0 and radio._id2 is not False:
658
            frame = frame[1:]
659

    
660
        # send the frame
661
        _send(radio, frame, True)
662

    
663
        # receiving the response
664
        ack = _rawrecv(radio, 1)
665

    
666
        # basic check
667
        if len(ack) != 1:
668
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
669

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

    
673
        # UI Update
674
        status.cur = addr / TX_BLOCK_SIZE
675
        status.msg = "Cloning to radio..."
676
        radio.status_fn(status)
677

    
678

    
679
def model_match(cls, data):
680
    """Match the opened/downloaded image to the correct version"""
681
    rid = data[0x3f70:0x3f76]
682

    
683
    if rid in cls._fileid:
684
        return True
685

    
686
    return False
687

    
688

    
689
def _decode_ranges(low, high):
690
    """Unpack the data in the ranges zones in the memmap and return
691
    a tuple with the integer corresponding to the Mhz it means"""
692
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
693
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
694
    ilow *= 1000000
695
    ihigh *= 1000000
696

    
697
    return (ilow, ihigh)
698

    
699

    
700
def _split(rf, f1, f2):
701
    """Returns False if the two freqs are in the same band (no split)
702
    or True otherwise"""
703

    
704
    # determine if the two freqs are in the same band
705
    for low, high in rf.valid_bands:
706
        if f1 >= low and f1 <= high and \
707
                f2 >= low and f2 <= high:
708
            # if the two freqs are on the same Band this is not a split
709
            return False
710

    
711
    # if you get here is because the freq pairs are split
712
    return True
713

    
714

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

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

    
754
            1 - Turn off your radio
755
            2 - Connect your interface cable
756
            3 - Turn on your radio
757
            4 - Do the download of your radio data
758

    
759
            """))
760
        rp.pre_upload = _(dedent("""\
761
            Follow these instructions to upload your info:
762

    
763
            1 - Turn off your radio
764
            2 - Connect your interface cable
765
            3 - Turn on your radio
766
            4 - Do the upload of your radio data
767

    
768
            """))
769
        return rp
770

    
771
    def get_features(self):
772
        """Get the radio's features"""
773

    
774
        # we will use the following var as global
775
        global POWER_LEVELS
776

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

    
808
        # power levels
809
        POWER_LEVELS = self._power_levels
810
        rf.valid_power_levels = POWER_LEVELS
811

    
812
        # normal dual bands
813
        rf.valid_bands = [self._vhf_range, self._uhf_range]
814

    
815
        # 220 band
816
        if self.BANDS == 3 or self.BANDS == 4:
817
            rf.valid_bands.append(self._220_range)
818

    
819
        # 350 band
820
        if self.BANDS == 4:
821
            rf.valid_bands.append(self._350_range)
822

    
823
        return rf
824

    
825
    def validate_memory(self, mem):
826
        msgs = chirp_common.CloneModeRadio.validate_memory(self, mem)
827

    
828
        _msg_duplex1 = 'Memory location only supports "Low"'
829
        _msg_duplex2 = 'Memory location only supports "off"'
830
        _msg_duplex3 = 'Memory location only supports "(None)", "+" or "off"'
831

    
832
        if self._gmrs:
833
            if mem.number < 1 or mem.number > 30:
834
                if float(mem.freq) / 1000000 in GMRS_FREQS1:
835
                    if mem.duplex not in ['', 'off']:
836
                        # warn user wrong Duplex
837
                        msgs.append(chirp_common.ValidationError(_msg_duplex2))
838
                    if mem.power != self._power_levels[2]:
839
                        # warn user wrong Duplex
840
                        msgs.append(chirp_common.ValidationError(_msg_duplex1))
841

    
842
                if float(mem.freq) / 1000000 in GMRS_FREQS2:
843
                    if mem.duplex not in ['off', ]:
844
                        # warn user wrong Duplex
845
                        msgs.append(chirp_common.ValidationError(_msg_duplex2))
846

    
847
                if float(mem.freq) / 1000000 in GMRS_FREQS3:
848
                    if mem.duplex not in ['', '+', 'off']:
849
                        # warn user wrong Duplex
850
                        msgs.append(chirp_common.ValidationError(_msg_duplex3))
851

    
852
        return msgs
853

    
854
    def sync_in(self):
855
        """Download from radio"""
856
        data = _download(self)
857
        self._mmap = memmap.MemoryMap(data)
858
        self.process_mmap()
859

    
860
    def sync_out(self):
861
        """Upload to radio"""
862
        try:
863
            _upload(self)
864
        except errors.RadioError:
865
            raise
866
        except Exception, e:
867
            raise errors.RadioError("Error: %s" % e)
868

    
869
    def get_raw_memory(self, number):
870
        return repr(self._memobj.memory[number])
871

    
872
    def _decode_tone(self, val):
873
        """Parse the tone data to decode from mem, it returns:
874
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
875
        pol = None
876

    
877
        if val in [0, 65535]:
878
            return '', None, None
879
        elif val > 0x0258:
880
            a = val / 10.0
881
            return 'Tone', a, pol
882
        else:
883
            if val > 0x69:
884
                index = val - 0x6A
885
                pol = "R"
886
            else:
887
                index = val - 1
888
                pol = "N"
889

    
890
            tone = DTCS[index]
891
            return 'DTCS', tone, pol
892

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

    
917
    def get_memory(self, number):
918
        """Get the mem representation from the radio image"""
919
        _mem = self._memobj.memory[number]
920
        _names = self._memobj.names[number]
921

    
922
        # Create a high-level memory object to return to the UI
923
        mem = chirp_common.Memory()
924

    
925
        # Memory number
926
        mem.number = number
927

    
928
        if _mem.get_raw()[0] == "\xFF":
929
            mem.empty = True
930
            return mem
931

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

    
956
        # name TAG of the channel
957
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
958

    
959
        # power
960
        mem.power = POWER_LEVELS[int(_mem.power)]
961

    
962
        # wide/narrow
963
        mem.mode = MODES[int(_mem.wide)]
964

    
965
        # skip
966
        mem.skip = SKIP_VALUES[_mem.add]
967

    
968
        # tone data
969
        rxtone = txtone = None
970
        txtone = self._decode_tone(_mem.txtone)
971
        rxtone = self._decode_tone(_mem.rxtone)
972
        chirp_common.split_tone_decode(mem, txtone, rxtone)
973

    
974
        # Extra
975
        mem.extra = RadioSettingGroup("extra", "Extra")
976

    
977
        if not self.COLOR_LCD or \
978
                (self.COLOR_LCD and not self.VENDOR == "BTECH"):
979
            scramble = RadioSetting("scramble", "Scramble",
980
                                    RadioSettingValueBoolean(bool(
981
                                        _mem.scramble)))
982
            mem.extra.append(scramble)
983

    
984
        bcl = RadioSetting("bcl", "Busy channel lockout",
985
                           RadioSettingValueBoolean(bool(_mem.bcl)))
986
        mem.extra.append(bcl)
987

    
988
        pttid = RadioSetting("pttid", "PTT ID",
989
                             RadioSettingValueList(PTTID_LIST,
990
                                                   PTTID_LIST[_mem.pttid]))
991
        mem.extra.append(pttid)
992

    
993
        # validating scode
994
        scode = _mem.scode if _mem.scode != 15 else 0
995
        pttidcode = RadioSetting("scode", "PTT ID signal code",
996
                                 RadioSettingValueList(
997
                                     PTTIDCODE_LIST,
998
                                     PTTIDCODE_LIST[scode]))
999
        mem.extra.append(pttidcode)
1000

    
1001
        optsig = RadioSetting("optsig", "Optional signaling",
1002
                              RadioSettingValueList(
1003
                                  OPTSIG_LIST,
1004
                                  OPTSIG_LIST[_mem.optsig]))
1005
        mem.extra.append(optsig)
1006

    
1007
        spmute = RadioSetting("spmute", "Speaker mute",
1008
                              RadioSettingValueList(
1009
                                  SPMUTE_LIST,
1010
                                  SPMUTE_LIST[_mem.spmute]))
1011
        mem.extra.append(spmute)
1012

    
1013
        return mem
1014

    
1015
    def set_memory(self, mem):
1016
        """Set the memory data in the eeprom img from the UI"""
1017
        # get the eprom representation of this channel
1018
        _mem = self._memobj.memory[mem.number]
1019
        _names = self._memobj.names[mem.number]
1020

    
1021
        mem_was_empty = False
1022
        # same method as used in get_memory for determining if mem is empty
1023
        # doing this BEFORE overwriting it with new values ...
1024
        if _mem.get_raw()[0] == "\xFF":
1025
            LOG.debug("This mem was empty before")
1026
            mem_was_empty = True
1027

    
1028
        # if empty memmory
1029
        if mem.empty:
1030
            # the channel itself
1031
            _mem.set_raw("\xFF" * 16)
1032
            # the name tag
1033
            _names.set_raw("\xFF" * 16)
1034
            return
1035

    
1036
        if mem_was_empty:
1037
            # Zero the whole memory if we're making it unempty for
1038
            # the first time
1039
            LOG.debug('Zeroing new memory')
1040
            _mem.set_raw('\x00' * 16)
1041

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

    
1077
        # frequency
1078
        _mem.rxfreq = mem.freq / 10
1079

    
1080
        # duplex
1081
        if mem.duplex == "+":
1082
            _mem.txfreq = (mem.freq + mem.offset) / 10
1083
        elif mem.duplex == "-":
1084
            _mem.txfreq = (mem.freq - mem.offset) / 10
1085
        elif mem.duplex == "off":
1086
            for i in _mem.txfreq:
1087
                i.set_raw("\xFF")
1088
        elif mem.duplex == "split":
1089
            _mem.txfreq = mem.offset / 10
1090
        else:
1091
            _mem.txfreq = mem.freq / 10
1092

    
1093
        # tone data
1094
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1095
            chirp_common.split_tone_encode(mem)
1096
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1097
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1098

    
1099
        # name TAG of the channel
1100
        if len(mem.name) < self.NAME_LENGTH:
1101
            # we must pad to self.NAME_LENGTH chars, " " = "\xFF"
1102
            mem.name = str(mem.name).ljust(self.NAME_LENGTH, " ")
1103
        _names.name = str(mem.name).replace(" ", "\xFF")
1104

    
1105
        # power, # default power level is high
1106
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1107

    
1108
        # wide/narrow
1109
        _mem.wide = MODES.index(mem.mode)
1110

    
1111
        # scan add property
1112
        _mem.add = SKIP_VALUES.index(mem.skip)
1113

    
1114
        # reseting unknowns, this have to be set by hand
1115
        _mem.unknown0 = 0
1116
        _mem.unknown1 = 0
1117
        _mem.unknown2 = 0
1118
        _mem.unknown3 = 0
1119
        _mem.unknown4 = 0
1120
        _mem.unknown5 = 0
1121
        _mem.unknown6 = 0
1122

    
1123
        def _zero_settings():
1124
            _mem.spmute = 0
1125
            _mem.optsig = 0
1126
            _mem.scramble = 0
1127
            _mem.bcl = 0
1128
            _mem.pttid = 0
1129
            _mem.scode = 0
1130

    
1131
        if self.COLOR_LCD and _mem.scramble:
1132
            LOG.info('Resetting scramble bit for BTECH COLOR_LCD variant')
1133
            _mem.scramble = 0
1134

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

    
1155
        return mem
1156

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

    
1184
                    if element.has_apply_callback():
1185
                        LOG.debug("Using apply callback")
1186
                        element.run_apply_callback()
1187
                    elif element.value.get_mutable():
1188
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1189
                        setattr(obj, setting, element.value)
1190
                except Exception, e:
1191
                    LOG.debug(element.get_name())
1192
                    raise
1193

    
1194
    @classmethod
1195
    def match_model(cls, filedata, filename):
1196
        match_size = False
1197
        match_model = False
1198

    
1199
        # testing the file data size
1200
        if len(filedata) == MEM_SIZE:
1201
            match_size = True
1202

    
1203
        # testing the firmware model fingerprint
1204
        match_model = model_match(cls, filedata)
1205

    
1206
        if match_size and match_model:
1207
            return True
1208
        else:
1209
            return False
1210

    
1211

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

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

    
1283
#seekto 0x0E80;
1284
struct {
1285
  u8 unknown1;
1286
  u8 vfomr;
1287
  u8 keylock;
1288
  u8 unknown2;
1289
  u8 unknown3:4,
1290
     vfomren:1,
1291
     unknown4:1,
1292
     reseten:1,
1293
     menuen:1;
1294
  u8 unknown5[11];
1295
  u8 dispab;
1296
  u8 mrcha;
1297
  u8 mrchb;
1298
  u8 menu;
1299
} settings2;
1300

    
1301
#seekto 0x0EC0;
1302
struct {
1303
  char line1[6];
1304
  char line2[6];
1305
} poweron_msg;
1306

    
1307
struct settings_vfo {
1308
  u8 freq[8];
1309
  u8 offset[6];
1310
  u8 unknown2[2];
1311
  ul16 rxtone;
1312
  ul16 txtone;
1313
  u8 scode;
1314
  u8 spmute;
1315
  u8 optsig;
1316
  u8 scramble;
1317
  u8 wide;
1318
  u8 power;
1319
  u8 shiftd;
1320
  u8 step;
1321
  u8 unknown3[4];
1322
};
1323

    
1324
#seekto 0x0F00;
1325
struct {
1326
  struct settings_vfo a;
1327
  struct settings_vfo b;
1328
} vfo;
1329

    
1330
#seekto 0x1000;
1331
struct {
1332
  char name[6];
1333
  u8 unknown1[10];
1334
} names[200];
1335

    
1336
#seekto 0x2400;
1337
struct {
1338
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
1339
  u8 group_tone;
1340
  u8 repeat_tone;
1341
  u8 unused[13];
1342
} _5tone_std_settings[15];
1343

    
1344
#seekto 0x2500;
1345
struct {
1346
  u8 frame1[5];
1347
  u8 frame2[5];
1348
  u8 frame3[5];
1349
  u8 standard;   // one out of LIST_5TONE_STANDARDS
1350
} _5tone_codes[15];
1351

    
1352
#seekto 0x25F0;
1353
struct {
1354
  u8 _5tone_delay1; // * 10ms
1355
  u8 _5tone_delay2; // * 10ms
1356
  u8 _5tone_delay3; // * 10ms
1357
  u8 _5tone_first_digit_ext_length;
1358
  u8 unknown1;
1359
  u8 unknown2;
1360
  u8 unknown3;
1361
  u8 unknown4;
1362
  u8 decode_standard;
1363
  u8 unknown5:5,
1364
     _5tone_decode_call_frame3:1,
1365
     _5tone_decode_call_frame2:1,
1366
     _5tone_decode_call_frame1:1;
1367
  u8 unknown6:5,
1368
     _5tone_decode_disp_frame3:1,
1369
     _5tone_decode_disp_frame2:1,
1370
     _5tone_decode_disp_frame1:1;
1371
  u8 decode_reset_time; // * 100 + 100ms
1372
} _5tone_settings;
1373

    
1374
#seekto 0x2900;
1375
struct {
1376
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
1377
} dtmf_codes[15];
1378

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

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

    
1444
  struct {
1445
    ul16 freqA;
1446
    ul16 freqB;
1447
    ul16 freqC;
1448
    ul16 freqD;
1449
    // unknown what those values mean, but they are
1450
    // derived from configured frequencies
1451
    ul16 derived_from_freqA; // 2304000/freqA
1452
    ul16 derived_from_freqB; // 2304000/freqB
1453
    ul16 derived_from_freqC; // 2304000/freqC
1454
    ul16 derived_from_freqD; // 2304000/freqD
1455
  }freqs[15];
1456
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
1457
} _2tone;
1458

    
1459
#seekto 0x3000;
1460
struct {
1461
  u8 freq[8];
1462
  char broadcast_station_name[6];
1463
  u8 unknown[2];
1464
} fm_radio_preset[16];
1465

    
1466
#seekto 0x3C90;
1467
struct {
1468
  u8 vhf_low[3];
1469
  u8 vhf_high[3];
1470
  u8 uhf_low[3];
1471
  u8 uhf_high[3];
1472
} ranges;
1473

    
1474
// the UV-2501+220 & KT8900R has different zones for storing ranges
1475

    
1476
#seekto 0x3CD0;
1477
struct {
1478
  u8 vhf_low[3];
1479
  u8 vhf_high[3];
1480
  u8 unknown1[4];
1481
  u8 unknown2[6];
1482
  u8 vhf2_low[3];
1483
  u8 vhf2_high[3];
1484
  u8 unknown3[4];
1485
  u8 unknown4[6];
1486
  u8 uhf_low[3];
1487
  u8 uhf_high[3];
1488
} ranges220;
1489

    
1490
#seekto 0x3F70;
1491
struct {
1492
  char fp[6];
1493
} fingerprint;
1494

    
1495
"""
1496

    
1497

    
1498
class BTech(BTechMobileCommon):
1499
    """BTECH's UV-5001 and alike radios"""
1500
    BANDS = 2
1501
    COLOR_LCD = False
1502
    NAME_LENGTH = 6
1503

    
1504
    def set_options(self):
1505
        """This is to read the options from the image and set it in the
1506
        environment, for now just the limits of the freqs in the VHF/UHF
1507
        ranges"""
1508

    
1509
        # setting the correct ranges for each radio type
1510
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1511
            # the model 2501+220 has a segment in 220
1512
            # and a different position in the memmap
1513
            # also the QYT KT8900R
1514
            ranges = self._memobj.ranges220
1515
        else:
1516
            ranges = self._memobj.ranges
1517

    
1518
        # the normal dual bands
1519
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
1520
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
1521

    
1522
        # DEBUG
1523
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
1524
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
1525

    
1526
        # 220Mhz radios case
1527
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1528
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
1529
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
1530
            self._220_range = vhf2
1531

    
1532
        # set the class with the real data
1533
        self._vhf_range = vhf
1534
        self._uhf_range = uhf
1535

    
1536
    def process_mmap(self):
1537
        """Process the mem map into the mem object"""
1538

    
1539
        # Get it
1540
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
1541

    
1542
        # load specific parameters from the radio image
1543
        self.set_options()
1544

    
1545

    
1546
# Declaring Aliases (Clones of the real radios)
1547
class JT2705M(chirp_common.Alias):
1548
    VENDOR = "Jetstream"
1549
    MODEL = "JT2705M"
1550

    
1551

    
1552
class JT6188Mini(chirp_common.Alias):
1553
    VENDOR = "Juentai"
1554
    MODEL = "JT-6188 Mini"
1555

    
1556

    
1557
class JT6188Plus(chirp_common.Alias):
1558
    VENDOR = "Juentai"
1559
    MODEL = "JT-6188 Plus"
1560

    
1561

    
1562
class SSGT890(chirp_common.Alias):
1563
    VENDOR = "Sainsonic"
1564
    MODEL = "GT-890"
1565

    
1566

    
1567
class ZastoneMP300(chirp_common.Alias):
1568
    VENDOR = "Zastone"
1569
    MODEL = "MP-300"
1570

    
1571

    
1572
# real radios
1573
@directory.register
1574
class UV2501(BTech):
1575
    """Baofeng Tech UV2501"""
1576
    MODEL = "UV-2501"
1577
    _fileid = [UV2501G3_fp,
1578
               UV2501G2_fp,
1579
               UV2501pp2_fp,
1580
               UV2501pp_fp]
1581

    
1582

    
1583
@directory.register
1584
class UV2501_220(BTech):
1585
    """Baofeng Tech UV2501+220"""
1586
    MODEL = "UV-2501+220"
1587
    BANDS = 3
1588
    _magic = MSTRING_220
1589
    _id2 = [UV2501_220pp_id, ]
1590
    _fileid = [UV2501_220G3_fp,
1591
               UV2501_220G2_fp,
1592
               UV2501_220_fp,
1593
               UV2501_220pp_fp]
1594

    
1595

    
1596
@directory.register
1597
class UV5001(BTech):
1598
    """Baofeng Tech UV5001"""
1599
    MODEL = "UV-5001"
1600
    _fileid = [UV5001G3_fp,
1601
               UV5001G22_fp,
1602
               UV5001G2_fp,
1603
               UV5001alpha_fp,
1604
               UV5001pp_fp]
1605
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
1606
                     chirp_common.PowerLevel("Low", watts=10)]
1607

    
1608

    
1609
@directory.register
1610
class MINI8900(BTech):
1611
    """WACCOM MINI-8900"""
1612
    VENDOR = "WACCOM"
1613
    MODEL = "MINI-8900"
1614
    _magic = MSTRING_MINI8900
1615
    _fileid = [MINI8900_fp, ]
1616
    # Clones
1617
    ALIASES = [JT6188Plus, ]
1618

    
1619

    
1620
@directory.register
1621
class KTUV980(BTech):
1622
    """QYT KT-UV980"""
1623
    VENDOR = "QYT"
1624
    MODEL = "KT-UV980"
1625
    _vhf_range = (136000000, 175000000)
1626
    _uhf_range = (400000000, 481000000)
1627
    _magic = MSTRING_MINI8900
1628
    _fileid = [KTUV980_fp, ]
1629
    # Clones
1630
    ALIASES = [JT2705M, ]
1631

    
1632
# Please note that there is a version of this radios that is a clone of the
1633
# Waccom Mini8900, maybe an early version?
1634

    
1635

    
1636
class OTGRadioV1(chirp_common.Alias):
1637
    VENDOR = 'OTGSTUFF'
1638
    MODEL = 'OTG Radio v1'
1639

    
1640

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

    
1661

    
1662
@directory.register
1663
class KT9800R(BTech):
1664
    """QYT KT8900R"""
1665
    VENDOR = "QYT"
1666
    MODEL = "KT8900R"
1667
    BANDS = 3
1668
    _vhf_range = (136000000, 175000000)
1669
    _220_range = (240000000, 271000000)
1670
    _uhf_range = (400000000, 481000000)
1671
    _magic = MSTRING_KT8900R
1672
    _fileid = [KT8900R_fp,
1673
               KT8900R_fp1,
1674
               KT8900R_fp2,
1675
               KT8900R_fp3,
1676
               KT8900R_fp4,
1677
               KT8900R_fp5]
1678
    _id2 = [KT8900R_id, KT8900R_id2]
1679

    
1680

    
1681
@directory.register
1682
class LT588UV(BTech):
1683
    """LUITON LT-588UV"""
1684
    VENDOR = "LUITON"
1685
    MODEL = "LT-588UV"
1686
    _vhf_range = (136000000, 175000000)
1687
    _uhf_range = (400000000, 481000000)
1688
    _magic = MSTRING_KT8900
1689
    _fileid = [LT588UV_fp,
1690
               LT588UV_fp1]
1691
    _power_levels = [chirp_common.PowerLevel("High", watts=60),
1692
                     chirp_common.PowerLevel("Low", watts=10)]
1693

    
1694

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

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

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

    
1803
struct settings_vfo {
1804
  u8 freq[8];
1805
  u8 offset[6];
1806
  u8 unknown2[2];
1807
  ul16 rxtone;
1808
  ul16 txtone;
1809
  u8 scode;
1810
  u8 spmute;
1811
  u8 optsig;
1812
  u8 scramble;
1813
  u8 wide;
1814
  u8 power;
1815
  u8 shiftd;
1816
  u8 step;
1817
  u8 unknown3[4];
1818
};
1819

    
1820
#seekto 0x0F00;
1821
struct {
1822
  struct settings_vfo a;
1823
  struct settings_vfo b;
1824
  struct settings_vfo c;
1825
  struct settings_vfo d;
1826
} vfo;
1827

    
1828
#seekto 0x0F80;
1829
struct {
1830
  char line1[8];
1831
  char line2[8];
1832
  char line3[8];
1833
  char line4[8];
1834
  char line5[8];
1835
  char line6[8];
1836
  char line7[8];
1837
  char line8[8];
1838
} poweron_msg;
1839

    
1840
#seekto 0x1000;
1841
struct {
1842
  char name[8];
1843
  u8 unknown1[8];
1844
} names[200];
1845

    
1846
#seekto 0x2400;
1847
struct {
1848
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
1849
  u8 group_tone;
1850
  u8 repeat_tone;
1851
  u8 unused[13];
1852
} _5tone_std_settings[15];
1853

    
1854
#seekto 0x2500;
1855
struct {
1856
  u8 frame1[5];
1857
  u8 frame2[5];
1858
  u8 frame3[5];
1859
  u8 standard;   // one out of LIST_5TONE_STANDARDS
1860
} _5tone_codes[15];
1861

    
1862
#seekto 0x25F0;
1863
struct {
1864
  u8 _5tone_delay1; // * 10ms
1865
  u8 _5tone_delay2; // * 10ms
1866
  u8 _5tone_delay3; // * 10ms
1867
  u8 _5tone_first_digit_ext_length;
1868
  u8 unknown1;
1869
  u8 unknown2;
1870
  u8 unknown3;
1871
  u8 unknown4;
1872
  u8 decode_standard;
1873
  u8 unknown5:5,
1874
     _5tone_decode_call_frame3:1,
1875
     _5tone_decode_call_frame2:1,
1876
     _5tone_decode_call_frame1:1;
1877
  u8 unknown6:5,
1878
     _5tone_decode_disp_frame3:1,
1879
     _5tone_decode_disp_frame2:1,
1880
     _5tone_decode_disp_frame1:1;
1881
  u8 decode_reset_time; // * 100 + 100ms
1882
} _5tone_settings;
1883

    
1884
#seekto 0x2900;
1885
struct {
1886
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
1887
} dtmf_codes[15];
1888

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

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

    
1954
  struct {
1955
    ul16 freqA;
1956
    ul16 freqB;
1957
    ul16 freqC;
1958
    ul16 freqD;
1959
    // unknown what those values mean, but they are
1960
    // derived from configured frequencies
1961
    ul16 derived_from_freqA; // 2304000/freqA
1962
    ul16 derived_from_freqB; // 2304000/freqB
1963
    ul16 derived_from_freqC; // 2304000/freqC
1964
    ul16 derived_from_freqD; // 2304000/freqD
1965
  }freqs[15];
1966
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
1967
} _2tone;
1968

    
1969
#seekto 0x3D80;
1970
struct {
1971
  u8 vhf_low[3];
1972
  u8 vhf_high[3];
1973
  u8 unknown1[4];
1974
  u8 unknown2[6];
1975
  u8 vhf2_low[3];
1976
  u8 vhf2_high[3];
1977
  u8 unknown3[4];
1978
  u8 unknown4[6];
1979
  u8 uhf_low[3];
1980
  u8 uhf_high[3];
1981
  u8 unknown5[4];
1982
  u8 unknown6[6];
1983
  u8 uhf2_low[3];
1984
  u8 uhf2_high[3];
1985
} ranges;
1986

    
1987
#seekto 0x3F70;
1988
struct {
1989
  char fp[6];
1990
} fingerprint;
1991

    
1992
"""
1993

    
1994

    
1995
class BTechColor(BTechMobileCommon):
1996
    """BTECH's Color LCD Mobile and alike radios"""
1997
    COLOR_LCD = True
1998
    NAME_LENGTH = 8
1999
    LIST_TMR = LIST_TMR16
2000

    
2001
    def process_mmap(self):
2002
        """Process the mem map into the mem object"""
2003

    
2004
        # Get it
2005
        self._memobj = bitwise.parse(COLOR_MEM_FORMAT, self._mmap)
2006

    
2007
        # load specific parameters from the radio image
2008
        self.set_options()
2009

    
2010
    def set_options(self):
2011
        """This is to read the options from the image and set it in the
2012
        environment, for now just the limits of the freqs in the VHF/UHF
2013
        ranges"""
2014

    
2015
        # setting the correct ranges for each radio type
2016
        ranges = self._memobj.ranges
2017

    
2018
        # the normal dual bands
2019
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
2020
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
2021

    
2022
        # DEBUG
2023
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
2024
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
2025

    
2026
        # the additional bands
2027
        if self.MODEL in ["UV-25X4", "KT7900D"]:
2028
            # 200Mhz band
2029
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
2030
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
2031
            self._220_range = vhf2
2032

    
2033
            # 350Mhz band
2034
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
2035
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
2036
            self._350_range = uhf2
2037

    
2038
        # set the class with the real data
2039
        self._vhf_range = vhf
2040
        self._uhf_range = uhf
2041

    
2042

    
2043
# Declaring Aliases (Clones of the real radios)
2044
class SKT8900D(chirp_common.Alias):
2045
    VENDOR = "Surecom"
2046
    MODEL = "S-KT8900D"
2047

    
2048

    
2049
class QB25(chirp_common.Alias):
2050
    VENDOR = "Radioddity"
2051
    MODEL = "QB25"
2052

    
2053

    
2054
# real radios
2055
@directory.register
2056
class UV25X2(BTechColor):
2057
    """Baofeng Tech UV25X2"""
2058
    MODEL = "UV-25X2"
2059
    BANDS = 2
2060
    _vhf_range = (130000000, 180000000)
2061
    _uhf_range = (400000000, 521000000)
2062
    _magic = MSTRING_UV25X2
2063
    _fileid = [UV25X2_fp, ]
2064

    
2065

    
2066
@directory.register
2067
class UV25X4(BTechColor):
2068
    """Baofeng Tech UV25X4"""
2069
    MODEL = "UV-25X4"
2070
    BANDS = 4
2071
    _vhf_range = (130000000, 180000000)
2072
    _220_range = (200000000, 271000000)
2073
    _uhf_range = (400000000, 521000000)
2074
    _350_range = (350000000, 391000000)
2075
    _magic = MSTRING_UV25X4
2076
    _fileid = [UV25X4_fp, ]
2077

    
2078

    
2079
@directory.register
2080
class UV50X2(BTechColor):
2081
    """Baofeng Tech UV50X2"""
2082
    MODEL = "UV-50X2"
2083
    BANDS = 2
2084
    _vhf_range = (130000000, 180000000)
2085
    _uhf_range = (400000000, 521000000)
2086
    _magic = MSTRING_UV25X2
2087
    _fileid = [UV50X2_fp, ]
2088
    _power_levels = [chirp_common.PowerLevel("High", watts=50),
2089
                     chirp_common.PowerLevel("Low", watts=10)]
2090

    
2091

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

    
2109

    
2110
@directory.register
2111
class KT8900D(BTechColor):
2112
    """QYT KT8900D"""
2113
    VENDOR = "QYT"
2114
    MODEL = "KT8900D"
2115
    BANDS = 2
2116
    LIST_TMR = LIST_TMR15
2117
    _vhf_range = (136000000, 175000000)
2118
    _uhf_range = (400000000, 481000000)
2119
    _magic = MSTRING_KT8900D
2120
    _fileid = [KT8900D_fp3, KT8900D_fp2, KT8900D_fp1, KT8900D_fp]
2121

    
2122
    # Clones
2123
    ALIASES = [OTGRadioV1]
2124

    
2125

    
2126
@directory.register
2127
class KT5800(BTechColor):
2128
    """QYT KT5800"""
2129
    VENDOR = "QYT"
2130
    MODEL = "KT5800"
2131
    BANDS = 2
2132
    LIST_TMR = LIST_TMR15
2133
    _vhf_range = (136000000, 175000000)
2134
    _uhf_range = (400000000, 481000000)
2135
    _magic = MSTRING_KT8900D
2136
    _fileid = [KT5800_fp, ]
2137

    
2138

    
2139
@directory.register
2140
class KT980PLUS(BTechColor):
2141
    """QYT KT980PLUS"""
2142
    VENDOR = "QYT"
2143
    MODEL = "KT980PLUS"
2144
    BANDS = 2
2145
    LIST_TMR = LIST_TMR15
2146
    _vhf_range = (136000000, 175000000)
2147
    _uhf_range = (400000000, 481000000)
2148
    _magic = MSTRING_KT8900D
2149
    _fileid = [KT980PLUS_fp1, KT980PLUS_fp]
2150
    _power_levels = [chirp_common.PowerLevel("High", watts=75),
2151
                     chirp_common.PowerLevel("Low", watts=55)]
2152

    
2153
    @classmethod
2154
    def match_model(cls, filedata, filename):
2155
        # This model is only ever matched via metadata
2156
        return False
2157

    
2158

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

    
2175
    @classmethod
2176
    def match_model(cls, filedata, filename):
2177
        # This model is only ever matched via metadata
2178
        return False
2179

    
2180

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

    
2206
#seekto 0x1000;
2207
struct {
2208
  char name[7];
2209
  u8 unknown1[9];
2210
} names[256];
2211

    
2212
#seekto 0x2400;
2213
struct {
2214
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
2215
  u8 group_tone;
2216
  u8 repeat_tone;
2217
  u8 unused[13];
2218
} _5tone_std_settings[15];
2219

    
2220
#seekto 0x2500;
2221
struct {
2222
  u8 frame1[5];
2223
  u8 frame2[5];
2224
  u8 frame3[5];
2225
  u8 standard;   // one out of LIST_5TONE_STANDARDS
2226
} _5tone_codes[15];
2227

    
2228
#seekto 0x25F0;
2229
struct {
2230
  u8 _5tone_delay1; // * 10ms
2231
  u8 _5tone_delay2; // * 10ms
2232
  u8 _5tone_delay3; // * 10ms
2233
  u8 _5tone_first_digit_ext_length;
2234
  u8 unknown1;
2235
  u8 unknown2;
2236
  u8 unknown3;
2237
  u8 unknown4;
2238
  u8 decode_standard;
2239
  u8 unknown5:5,
2240
     _5tone_decode_call_frame3:1,
2241
     _5tone_decode_call_frame2:1,
2242
     _5tone_decode_call_frame1:1;
2243
  u8 unknown6:5,
2244
     _5tone_decode_disp_frame3:1,
2245
     _5tone_decode_disp_frame2:1,
2246
     _5tone_decode_disp_frame1:1;
2247
  u8 decode_reset_time; // * 100 + 100ms
2248
} _5tone_settings;
2249

    
2250
#seekto 0x2900;
2251
struct {
2252
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
2253
} dtmf_codes[15];
2254

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

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

    
2320
  struct {
2321
    ul16 freqA;
2322
    ul16 freqB;
2323
    ul16 freqC;
2324
    ul16 freqD;
2325
    // unknown what those values mean, but they are
2326
    // derived from configured frequencies
2327
    ul16 derived_from_freqA; // 2304000/freqA
2328
    ul16 derived_from_freqB; // 2304000/freqB
2329
    ul16 derived_from_freqC; // 2304000/freqC
2330
    ul16 derived_from_freqD; // 2304000/freqD
2331
  }freqs[15];
2332
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
2333
} _2tone;
2334

    
2335
#seekto 0x3000;
2336
struct {
2337
  u8 freq[8];
2338
  char broadcast_station_name[6];
2339
  u8 unknown[2];
2340
} fm_radio_preset[16];
2341

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

    
2373

    
2374
  u8 stfc;
2375
  u8 mffc;
2376
  u8 sfafc;
2377
  u8 sfbfc;
2378
  u8 sfcfc;
2379
  u8 sfdfc;
2380
  u8 subfc;
2381
  u8 fmfc;
2382
  u8 sigfc;
2383
  u8 modfc;
2384
  u8 menufc;
2385
  u8 txfc;
2386
  u8 txdisp;
2387
  u8 unknown9[5];
2388
  u8 anil;
2389
  u8 reps;
2390
  u8 repm;
2391
  u8 tmrmr;
2392
  u8 ste;
2393
  u8 rpste;
2394
  u8 rptdl;
2395
  u8 dtmfg;
2396
  u8 mgain;
2397
  u8 skiptx;
2398
  u8 scmode;
2399
} settings;
2400

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

    
2427
struct settings_vfo {
2428
  u8 freq[8];
2429
  u8 offset[6];
2430
  u8 unknown2[2];
2431
  ul16 rxtone;
2432
  ul16 txtone;
2433
  u8 scode;
2434
  u8 spmute;
2435
  u8 optsig;
2436
  u8 scramble;
2437
  u8 wide;
2438
  u8 power;
2439
  u8 shiftd;
2440
  u8 step;
2441
  u8 unknown3[4];
2442
};
2443

    
2444
#seekto 0x3300;
2445
struct {
2446
  struct settings_vfo a;
2447
  struct settings_vfo b;
2448
  struct settings_vfo c;
2449
  struct settings_vfo d;
2450
} vfo;
2451

    
2452
#seekto 0x3D80;
2453
struct {
2454
  u8 vhf_low[3];
2455
  u8 vhf_high[3];
2456
  u8 unknown1[4];
2457
  u8 unknown2[6];
2458
  u8 vhf2_low[3];
2459
  u8 vhf2_high[3];
2460
  u8 unknown3[4];
2461
  u8 unknown4[6];
2462
  u8 uhf_low[3];
2463
  u8 uhf_high[3];
2464
  u8 unknown5[4];
2465
  u8 unknown6[6];
2466
  u8 uhf2_low[3];
2467
  u8 uhf2_high[3];
2468
} ranges;
2469

    
2470
#seekto 0x33B0;
2471
struct {
2472
  char line[16];
2473
} static_msg;
2474

    
2475
#seekto 0x3F70;
2476
struct {
2477
  char fp[6];
2478
} fingerprint;
2479

    
2480
"""
2481

    
2482

    
2483
class BTechGMRS(BTechMobileCommon):
2484
    """BTECH's GMRS Mobile"""
2485
    COLOR_LCD = True
2486
    COLOR_LCD2 = True
2487
    NAME_LENGTH = 7
2488
    UPLOAD_MEM_SIZE = 0X3400
2489

    
2490
    def process_mmap(self):
2491
        """Process the mem map into the mem object"""
2492

    
2493
        # Get it
2494
        self._memobj = bitwise.parse(GMRS_MEM_FORMAT, self._mmap)
2495

    
2496
        # load specific parameters from the radio image
2497
        self.set_options()
2498

    
2499
    def set_options(self):
2500
        """This is to read the options from the image and set it in the
2501
        environment, for now just the limits of the freqs in the VHF/UHF
2502
        ranges"""
2503

    
2504
        # setting the correct ranges for each radio type
2505
        ranges = self._memobj.ranges
2506

    
2507
        # the normal dual bands
2508
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
2509
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
2510

    
2511
        # DEBUG
2512
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
2513
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
2514

    
2515
        # set the class with the real data
2516
        self._vhf_range = vhf
2517
        self._uhf_range = uhf
2518

    
2519

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

    
2536

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

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

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

    
2645
struct settings_vfo {
2646
  u8 freq[8];
2647
  u8 offset[6];
2648
  u8 unknown2[2];
2649
  ul16 rxtone;
2650
  ul16 txtone;
2651
  u8 scode;
2652
  u8 spmute;
2653
  u8 optsig;
2654
  u8 scramble;
2655
  u8 wide;
2656
  u8 power;
2657
  u8 shiftd;
2658
  u8 step;
2659
  u8 unknown3[4];
2660
};
2661

    
2662
#seekto 0x0F00;
2663
struct {
2664
  struct settings_vfo a;
2665
  struct settings_vfo b;
2666
  struct settings_vfo c;
2667
  struct settings_vfo d;
2668
} vfo;
2669

    
2670
#seekto 0x0FE0;
2671
struct {
2672
  char line[16];
2673
} static_msg;
2674

    
2675
#seekto 0x1000;
2676
struct {
2677
  char name[8];
2678
  u8 unknown1[8];
2679
} names[200];
2680

    
2681
#seekto 0x2400;
2682
struct {
2683
  u8 period; // one out of LIST_5TONE_STANDARD_PERIODS
2684
  u8 group_tone;
2685
  u8 repeat_tone;
2686
  u8 unused[13];
2687
} _5tone_std_settings[15];
2688

    
2689
#seekto 0x2500;
2690
struct {
2691
  u8 frame1[5];
2692
  u8 frame2[5];
2693
  u8 frame3[5];
2694
  u8 standard;   // one out of LIST_5TONE_STANDARDS
2695
} _5tone_codes[15];
2696

    
2697
#seekto 0x25F0;
2698
struct {
2699
  u8 _5tone_delay1; // * 10ms
2700
  u8 _5tone_delay2; // * 10ms
2701
  u8 _5tone_delay3; // * 10ms
2702
  u8 _5tone_first_digit_ext_length;
2703
  u8 unknown1;
2704
  u8 unknown2;
2705
  u8 unknown3;
2706
  u8 unknown4;
2707
  u8 decode_standard;
2708
  u8 unknown5:5,
2709
     _5tone_decode_call_frame3:1,
2710
     _5tone_decode_call_frame2:1,
2711
     _5tone_decode_call_frame1:1;
2712
  u8 unknown6:5,
2713
     _5tone_decode_disp_frame3:1,
2714
     _5tone_decode_disp_frame2:1,
2715
     _5tone_decode_disp_frame1:1;
2716
  u8 decode_reset_time; // * 100 + 100ms
2717
} _5tone_settings;
2718

    
2719
#seekto 0x2900;
2720
struct {
2721
  u8 code[16]; // 0=x0A, A=0x0D, B=0x0E, C=0x0F, D=0x00, #=0x0C *=0x0B
2722
} dtmf_codes[15];
2723

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

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

    
2789
  struct {
2790
    ul16 freqA;
2791
    ul16 freqB;
2792
    ul16 freqC;
2793
    ul16 freqD;
2794
    // unknown what those values mean, but they are
2795
    // derived from configured frequencies
2796
    ul16 derived_from_freqA; // 2304000/freqA
2797
    ul16 derived_from_freqB; // 2304000/freqB
2798
    ul16 derived_from_freqC; // 2304000/freqC
2799
    ul16 derived_from_freqD; // 2304000/freqD
2800
  }freqs[15];
2801
  u8 reset_time;  // * 100 + 100ms - 100-8000ms
2802
} _2tone;
2803

    
2804
#seekto 0x3D80;
2805
struct {
2806
  u8 vhf_low[3];
2807
  u8 vhf_high[3];
2808
  u8 unknown1[4];
2809
  u8 unknown2[6];
2810
  u8 vhf2_low[3];
2811
  u8 vhf2_high[3];
2812
  u8 unknown3[4];
2813
  u8 unknown4[6];
2814
  u8 uhf_low[3];
2815
  u8 uhf_high[3];
2816
  u8 unknown5[4];
2817
  u8 unknown6[6];
2818
  u8 uhf2_low[3];
2819
  u8 uhf2_high[3];
2820
} ranges;
2821

    
2822
#seekto 0x3F70;
2823
struct {
2824
  char fp[6];
2825
} fingerprint;
2826

    
2827
"""
2828

    
2829

    
2830
class QYTColorHT(BTechMobileCommon):
2831
    """QTY's Color LCD Handheld and alike radios"""
2832
    COLOR_LCD = True
2833
    COLOR_LCD3 = True
2834
    NAME_LENGTH = 8
2835
    LIST_TMR = LIST_TMR15
2836

    
2837
    def process_mmap(self):
2838
        """Process the mem map into the mem object"""
2839

    
2840
        # Get it
2841
        self._memobj = bitwise.parse(COLORHT_MEM_FORMAT, self._mmap)
2842

    
2843
        # load specific parameters from the radio image
2844
        self.set_options()
2845

    
2846
    def set_options(self):
2847
        """This is to read the options from the image and set it in the
2848
        environment, for now just the limits of the freqs in the VHF/UHF
2849
        ranges"""
2850

    
2851
        # setting the correct ranges for each radio type
2852
        ranges = self._memobj.ranges
2853

    
2854
        # the normal dual bands
2855
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
2856
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
2857

    
2858
        # DEBUG
2859
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
2860
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
2861

    
2862
        # the additional bands
2863
        if self.MODEL in ["KT-8R"]:
2864
            # 200Mhz band
2865
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
2866
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
2867
            self._220_range = vhf2
2868

    
2869
            # 350Mhz band
2870
            uhf2 = _decode_ranges(ranges.uhf2_low, ranges.uhf2_high)
2871
            LOG.info("Radio ranges: UHF(350) %d to %d" % uhf2)
2872
            self._350_range = uhf2
2873

    
2874
        # set the class with the real data
2875
        self._vhf_range = vhf
2876
        self._uhf_range = uhf
2877

    
2878

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