Project

General

Profile

Feature #9825 » btech-set_kt8900_band_limits.py

for KT8900 and similar radios only - Jim Unroe, 04/10/2022 06:28 PM

 
1
# Copyright 2016-2021:
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
# this radio has an extra ID
240
KT8900R_id = "280528"
241
# another extra ID in dec/2018
242
KT8900R_id2 = "\x05\x58\x3d\xf0\x10"
243

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

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

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

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

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

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

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

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

    
284

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

    
306

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

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

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

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

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

    
333

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

    
337
    data = ""
338

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

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

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

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

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

    
359
    return data
360

    
361

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

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

    
380
        # DEBUG
381
        if debug is True:
382
            LOG.debug("==> (%d) bytes:\n\n%s" %
383
                      (len(data), util.hexprint(data)))
384
    except:
385
        raise errors.RadioError("Error sending data to radio")
386

    
387

    
388
def _make_frame(cmd, addr, length, data=""):
389
    """Pack the info in the headder format"""
390
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
391
    # add the data if set
392
    if len(data) != 0:
393
        frame += data
394

    
395
    return frame
396

    
397

    
398
def _recv(radio, addr):
399
    """Get data from the radio all at once to lower syscalls load"""
400

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

    
404
    # get the whole block
405
    block = _rawrecv(radio, BLOCK_SIZE + 5)
406

    
407
    # basic check
408
    if len(block) < (BLOCK_SIZE + 5):
409
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
410

    
411
    # checking for the ack
412
    if block[0] != ACK_CMD:
413
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
414

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

    
422
    # return the data
423
    return block[5:]
424

    
425

    
426
def _start_clone_mode(radio, status):
427
    """Put the radio in clone mode and get the ident string, 3 tries"""
428

    
429
    # cleaning the serial buffer
430
    _clean_buffer(radio)
431

    
432
    # prep the data to show in the UI
433
    status.cur = 0
434
    status.msg = "Identifying the radio..."
435
    status.max = 3
436
    radio.status_fn(status)
437

    
438
    try:
439
        for a in range(0, status.max):
440
            # Update the UI
441
            status.cur = a + 1
442
            radio.status_fn(status)
443

    
444
            # send the magic word
445
            _send(radio, radio._magic)
446

    
447
            # Now you get a x06 of ACK if all goes well
448
            ack = radio.pipe.read(1)
449

    
450
            if ack == "\x06":
451
                # DEBUG
452
                LOG.info("Magic ACK received")
453
                status.cur = status.max
454
                radio.status_fn(status)
455

    
456
                return True
457

    
458
        return False
459

    
460
    except errors.RadioError:
461
        raise
462
    except Exception, e:
463
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
464

    
465

    
466
def _do_ident(radio, status, upload=False):
467
    """Put the radio in PROGRAM mode & identify it"""
468
    #  set the serial discipline
469
    radio.pipe.baudrate = 9600
470
    radio.pipe.parity = "N"
471

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

    
481
    # Ok, get the ident string
482
    ident = _rawrecv(radio, 49)
483

    
484
    # basic check for the ident
485
    if len(ident) != 49:
486
        raise errors.RadioError("Radio send a short ident block.")
487

    
488
    # check if ident is OK
489
    itis = False
490
    for fp in radio._fileid:
491
        if fp in ident:
492
            # got it!
493
            itis = True
494
            # checking if we are dealing with a Gen 3 BTECH
495
            if radio.VENDOR == "BTECH" and fp in BTECH3:
496
                radio.btech3 = True
497

    
498
            break
499

    
500
    if itis is False:
501
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
502
        raise errors.RadioError("Radio identification failed.")
503

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

    
510
        # query & receive the extra ID
511
        _send(radio, _make_frame("S", 0x3DF0, 16))
512
        id2 = _rawrecv(radio, 21)
513

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

    
521
        # ok, the correct string must be in the received data
522
        # the radio._id2 var will be always a list
523
        flag2 = False
524
        for _id2 in radio._id2:
525
            if _id2 in id2:
526
                flag2 = True
527

    
528
        if not flag2:
529
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
530
                      (radio.MODEL, util.hexprint(id2)))
531
            raise errors.RadioError("The extra ID is wrong, aborting.")
532

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

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

    
554
            # checking
555
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
556
                raise errors.RadioError("Radio didn't ACK the upload")
557

    
558
            # restore the default serial timeout
559
            radio.pipe.timeout = STIMEOUT
560

    
561
    # DEBUG
562
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
563

    
564
    return True
565

    
566

    
567
def _download(radio):
568
    """Get the memory map"""
569

    
570
    # UI progress
571
    status = chirp_common.Status()
572

    
573
    # put radio in program mode and identify it
574
    _do_ident(radio, status)
575

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

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

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

    
591
    # cleaning the serial buffer
592
    _clean_buffer(radio)
593

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

    
599
        # read
600
        d = _recv(radio, addr)
601

    
602
        # aggregate the data
603
        data += d
604

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

    
610
    return data
611

    
612

    
613
def _upload(radio):
614
    """Upload procedure"""
615

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

    
620
    # UI progress
621
    status = chirp_common.Status()
622

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

    
626
    # get the data to upload to radio
627
    data = radio.get_mmap()
628

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

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

    
639
    # cleaning the serial buffer
640
    _clean_buffer(radio)
641

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

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

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

    
655
        # send the frame
656
        _send(radio, frame)
657

    
658
        # receiving the response
659
        ack = _rawrecv(radio, 1)
660

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

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

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

    
673

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

    
678
    if rid in cls._fileid:
679
        return True
680

    
681
    return False
682

    
683

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

    
692
    return (ilow, ihigh)
693

    
694

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

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

    
706
    # if you get here is because the freq pairs are split
707
    return True
708

    
709

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

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

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

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

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

    
763
            """))
764
        return rp
765

    
766
    def get_features(self):
767
        """Get the radio's features"""
768

    
769
        # we will use the following var as global
770
        global POWER_LEVELS
771

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

    
803
        # power levels
804
        POWER_LEVELS = self._power_levels
805
        rf.valid_power_levels = POWER_LEVELS
806

    
807
        # normal dual bands
808
        rf.valid_bands = [self._vhf_range, self._uhf_range]
809

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

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

    
818
        return rf
819

    
820
    def validate_memory(self, mem):
821
        msgs = chirp_common.CloneModeRadio.validate_memory(self, mem)
822

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

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

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

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

    
847
        return msgs
848

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

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

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

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

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

    
885
            tone = DTCS[index]
886
            return 'DTCS', tone, pol
887

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

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

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

    
920
        # Memory number
921
        mem.number = number
922

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

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

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

    
954
        # power
955
        mem.power = POWER_LEVELS[int(_mem.power)]
956

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

    
960
        # skip
961
        mem.skip = SKIP_VALUES[_mem.add]
962

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

    
969
        # Extra
970
        mem.extra = RadioSettingGroup("extra", "Extra")
971

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

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

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

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

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

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

    
1008
        return mem
1009

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

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

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

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

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

    
1072
        # frequency
1073
        _mem.rxfreq = mem.freq / 10
1074

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

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

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

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

    
1103
        # wide/narrow
1104
        _mem.wide = MODES.index(mem.mode)
1105

    
1106
        # scan add property
1107
        _mem.add = SKIP_VALUES.index(mem.skip)
1108

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

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

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

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

    
1150
        return mem
1151

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

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

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

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

    
1198
        # testing the firmware model fingerprint
1199
        match_model = model_match(cls, filedata)
1200

    
1201
        if match_size and match_model:
1202
            return True
1203
        else:
1204
            return False
1205

    
1206

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1469
// the UV-2501+220 & KT8900R has different zones for storing ranges
1470

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

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

    
1490
"""
1491

    
1492

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

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

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

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

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

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

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

    
1531
    def process_mmap(self):
1532
        """Process the mem map into the mem object"""
1533

    
1534
        # Get it
1535
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
1536

    
1537
        # load specific parameters from the radio image
1538
        self.set_options()
1539

    
1540

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

    
1546

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

    
1551

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

    
1556

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

    
1561

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

    
1566

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

    
1577

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

    
1590

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

    
1603

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

    
1614

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

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

    
1630

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

    
1635

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

    
1656

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

    
1674

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

    
1688

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1986
"""
1987

    
1988

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

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

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

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

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

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

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

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

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

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

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

    
2036

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

    
2042

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

    
2047

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

    
2059

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

    
2072

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

    
2085

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

    
2103

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

    
2116
    # Clones
2117
    ALIASES = [OTGRadioV1]
2118

    
2119

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

    
2132

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

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

    
2152

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

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

    
2174

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

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

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

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

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

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

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

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

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

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

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

    
2367

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

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

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

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

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

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

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

    
2474
"""
2475

    
2476

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

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

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

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

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

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

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

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

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

    
2513

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

    
2530

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2821
"""
2822

    
2823

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

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

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

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

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

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

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

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

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

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

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

    
2872

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