Project

General

Profile

New Model #9816 » KT8900R.py

Matthew Breit, 04/01/2022 03:35 AM

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

    
18
import time
19
import struct
20
import logging
21

    
22
LOG = logging.getLogger(__name__)
23

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

    
32
MEM_FORMAT = """
33
#seekto 0x0000;
34
struct {
35
  lbcd rxfreq[4];
36
  lbcd txfreq[4];
37
  ul16 rxtone;
38
  ul16 txtone;
39
  u8 unknown0:4,
40
     scode:4;
41
  u8 unknown1:2,
42
     spmute:1,
43
     unknown2:3,
44
     optsig:2;
45
  u8 unknown3:3,
46
     scramble:1,
47
     unknown4:3,
48
     power:1;
49
  u8 unknown5:1,
50
     wide:1,
51
     unknown6:2,
52
     bcl:1,
53
     add:1,
54
     pttid:2;
55
} memory[200];
56

    
57
#seekto 0x0E00;
58
struct {
59
  u8 tdr;
60
  u8 unknown1;
61
  u8 sql;
62
  u8 unknown2[2];
63
  u8 tot;
64
  u8 apo;           // BTech radios use this as the Auto Power Off time
65
                    // other radios use this as pre-Time Out Alert
66
  u8 unknown3;
67
  u8 abr;
68
  u8 beep;
69
  u8 unknown4[4];
70
  u8 dtmfst;
71
  u8 unknown5[2];
72
  u8 prisc;
73
  u8 prich;
74
  u8 screv;
75
  u8 unknown6[2];
76
  u8 pttid;
77
  u8 pttlt;
78
  u8 unknown7;
79
  u8 emctp;
80
  u8 emcch;
81
  u8 ringt;
82
  u8 unknown8;
83
  u8 camdf;
84
  u8 cbmdf;
85
  u8 sync;          // BTech radios use this as the display sync setting
86
                    // other radios use this as the auto keypad lock setting
87
  u8 ponmsg;
88
  u8 wtled;
89
  u8 rxled;
90
  u8 txled;
91
  u8 unknown9[5];
92
  u8 anil;
93
  u8 reps;
94
  u8 repm;
95
  u8 tdrab;
96
  u8 ste;
97
  u8 rpste;
98
  u8 rptdl;
99
  u8 mgain;
100
  u8 dtmfg;
101
} settings;
102

    
103
#seekto 0x0E80;
104
struct {
105
  u8 unknown1;
106
  u8 vfomr;
107
  u8 keylock;
108
  u8 unknown2;
109
  u8 unknown3:4,
110
     vfomren:1,
111
     unknown4:1,
112
     reseten:1,
113
     menuen:1;
114
  u8 unknown5[11];
115
  u8 dispab;
116
  u8 mrcha;
117
  u8 mrchb;
118
  u8 menu;
119
} settings2;
120

    
121
#seekto 0x0EC0;
122
struct {
123
  char line1[6];
124
  char line2[6];
125
} poweron_msg;
126

    
127
struct settings_vfo {
128
  u8 freq[8];
129
  u8 unknown1;
130
  u8 offset[4];
131
  u8 unknown2[3];
132
  ul16 rxtone;
133
  ul16 txtone;
134
  u8 scode;
135
  u8 spmute;
136
  u8 optsig;
137
  u8 scramble;
138
  u8 wide;
139
  u8 power;
140
  u8 shiftd;
141
  u8 step;
142
  u8 unknown3[4];
143
};
144

    
145
#seekto 0x0F00;
146
struct {
147
  struct settings_vfo a;
148
  struct settings_vfo b;
149
} vfo;
150

    
151
#seekto 0x1000;
152
struct {
153
  char name[6];
154
  u8 unknown1[10];
155
} names[200];
156

    
157
#seekto 0x3C90;
158
struct {
159
  u8 vhf_low[3];
160
  u8 vhf_high[3];
161
  u8 uhf_low[3];
162
  u8 uhf_high[3];
163
} ranges;
164

    
165
// the UV-2501+220 & KT8900R has different zones for storing ranges
166

    
167
#seekto 0x3CD0;
168
struct {
169
  u8 vhf_low[3];
170
  u8 vhf_high[3];
171
  u8 unknown1[4];
172
  u8 unknown2[6];
173
  u8 vhf2_low[3];
174
  u8 vhf2_high[3];
175
  u8 unknown3[4];
176
  u8 unknown4[6];
177
  u8 uhf_low[3];
178
  u8 uhf_high[3];
179
} ranges220;
180

    
181
#seekto 0x3F70;
182
struct {
183
  char fp[6];
184
} fingerprint;
185

    
186
"""
187

    
188
# A note about the memmory in these radios
189
#
190
# The real memory of these radios extends to 0x4000
191
# On read the factory software only uses up to 0x3200
192
# On write it just uploads the contents up to 0x3100
193
#
194
# The mem beyond 0x3200 holds the ID data
195

    
196
MEM_SIZE = 0x4000
197
BLOCK_SIZE = 0x40
198
TX_BLOCK_SIZE = 0x10
199
ACK_CMD = "\x06"
200
MODES = ["FM", "NFM"]
201
SKIP_VALUES = ["S", ""]
202
TONES = chirp_common.TONES
203
DTCS = sorted(chirp_common.DTCS_CODES + [645])
204
NAME_LENGTH = 6
205
PTTID_LIST = ["OFF", "BOT", "EOT", "BOTH"]
206
PTTIDCODE_LIST = ["%s" % x for x in range(1, 16)]
207
OPTSIG_LIST = ["OFF", "DTMF", "2TONE", "5TONE"]
208
SPMUTE_LIST = ["Tone/DTCS", "Tone/DTCS and Optsig", "Tone/DTCS or Optsig"]
209

    
210
LIST_TOT = ["%s sec" % x for x in range(15, 615, 15)]
211
LIST_TOA = ["Off"] + ["%s seconds" % x for x in range(1, 11)]
212
LIST_APO = ["Off"] + ["%s minutes" % x for x in range(30, 330, 30)]
213
LIST_ABR = ["Off"] + ["%s seconds" % x for x in range(1, 51)]
214
LIST_DTMFST = ["OFF", "Keyboard", "ANI", "Keyboad + ANI"]
215
LIST_SCREV = ["TO (timeout)", "CO (carrier operated)", "SE (search)"]
216
LIST_EMCTP = ["TX alarm sound", "TX ANI", "Both"]
217
LIST_RINGT = ["Off"] + ["%s seconds" % x for x in range(1, 10)]
218
LIST_MDF = ["Frequency", "Channel", "Name"]
219
LIST_PONMSG = ["Full", "Message", "Battery voltage"]
220
LIST_COLOR = ["Off", "Blue", "Orange", "Purple"]
221
LIST_REPS = ["1000 Hz", "1450 Hz", "1750 Hz", "2100Hz"]
222
LIST_REPM = ["Off", "Carrier", "CTCSS or DCS", "Tone", "DTMF"]
223
LIST_RPTDL = ["Off"] + ["%s ms" % x for x in range(1, 10)]
224
LIST_ANIL = ["3", "4", "5"]
225
LIST_AB = ["A", "B"]
226
LIST_VFOMR = ["Frequency", "Channel"]
227
LIST_SHIFT = ["Off", "+", "-"]
228
LIST_TXP = ["High", "Low"]
229
LIST_WIDE = ["Wide", "Narrow"]
230
STEPS = [2.5, 5.0, 6.25, 10.0, 12.5, 25.0]
231
LIST_STEP = [str(x) for x in STEPS]
232

    
233
# This is a general serial timeout for all serial read functions.
234
# Practice has show that about 0.7 sec will be enough to cover all radios.
235
STIMEOUT = 0.7
236

    
237
# this var controls the verbosity in the debug and by default it's low (False)
238
# make it True and you will to get a very verbose debug.log
239
debug = False
240

    
241
# Power Levels
242
NORMAL_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=25),
243
                       chirp_common.PowerLevel("Low", watts=10)]
244
UV5001_POWER_LEVELS = [chirp_common.PowerLevel("High", watts=50),
245
                       chirp_common.PowerLevel("Low", watts=10)]
246

    
247
# this must be defined globaly
248
POWER_LEVELS = None
249

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

    
254

    
255
##### ID strings #####################################################
256

    
257
# BTECH UV2501 pre-production units
258
UV2501pp_fp = "M2C294"
259
# BTECH UV2501 pre-production units 2 + and 1st Gen radios
260
UV2501pp2_fp = "M29204"
261
# B-TECH UV-2501 second generation (2G) radios
262
UV2501G2_fp = "BTG214"
263
# B-TECH UV-2501 third generation (3G) radios
264
UV2501G3_fp = "BTG324"
265

    
266
# B-TECH UV-2501+220 pre-production units
267
UV2501_220pp_fp = "M3C281"
268
# extra block read for the 2501+220 pre-production units
269
# the same for all of this radios so far
270
UV2501_220pp_id = "      280528"
271
# B-TECH UV-2501+220
272
UV2501_220_fp = "M3G201"
273
# new variant, let's call it Generation 2
274
UV2501_220G2_fp = "BTG211"
275
# B-TECH UV-2501+220 third generation (3G)
276
UV2501_220G3_fp = "BTG311"
277

    
278
# B-TECH UV-5001 pre-production units + 1st Gen radios
279
UV5001pp_fp = "V19204"
280
# B-TECH UV-5001 alpha units
281
UV5001alpha_fp = "V28204"
282
# B-TECH UV-5001 second generation (2G) radios
283
UV5001G2_fp = "BTG214"
284
# B-TECH UV-5001 second generation (2G2)
285
UV5001G22_fp = "V2G204"
286
# B-TECH UV-5001 third generation (3G)
287
UV5001G3_fp = "BTG304"
288

    
289
# special var to know when we found a BTECH Gen 3
290
BTECH3 = [UV2501G3_fp, UV2501_220G3_fp, UV5001G3_fp]
291

    
292

    
293
# WACCOM Mini-8900
294
MINI8900_fp = "M28854"
295

    
296

    
297
# QYT KT-UV980
298
KTUV980_fp = "H28854"
299

    
300
# QYT KT8900
301
KT8900_fp = "M29154"
302
# New generations KT8900
303
KT8900_fp1 = "M2C234"
304
KT8900_fp2 = "M2G1F4"
305
KT8900_fp3 = "M2G2F4"
306
KT8900_fp4 = "M2G304"
307
# this radio has an extra ID
308
KT8900_id = "      303688"
309

    
310
# KT8900R
311
KT8900R_fp = "M3G1F4"
312
# Second Generation
313
KT8900R_fp1 = "M3G214"
314
# another model
315
KT8900R_fp2 = "M3C234"
316
# another model G4?
317
KT8900R_fp3 = "M39164"
318
# AC3MB: another id
319
KT8900R_fp4 = "M3B064"
320
# this radio has an extra ID
321
# AC3MB: Fingerprint M3B064 does not have an extra ID 
322
# KT8900R_id = "280528"
323
KT8900R_id = ""
324

    
325
# LUITON LT-588UV
326
LT588UV_fp = "V2G1F4"
327

    
328

    
329
#### MAGICS
330
# for the Waccom Mini-8900
331
MSTRING_MINI8900 = "\x55\xA5\xB5\x45\x55\x45\x4d\x02"
332
# for the B-TECH UV-2501+220 (including pre production ones)
333
MSTRING_220 = "\x55\x20\x15\x12\x12\x01\x4d\x02"
334
# for the QYT KT8900 & R
335
MSTRING_KT8900 = "\x55\x20\x15\x09\x16\x45\x4D\x02"
336
MSTRING_KT8900R = "\x55\x20\x15\x09\x25\x01\x4D\x02"
337
# magic string for all other models
338
MSTRING = "\x55\x20\x15\x09\x20\x45\x4d\x02"
339

    
340

    
341
def _clean_buffer(radio):
342
    """Cleaning the read serial buffer, hard timeout to survive an infinite
343
    data stream"""
344

    
345
    # touching the serial timeout to optimize the flushing
346
    # restored at the end to the default value
347
    radio.pipe.timeout = 0.1
348
    dump = "1"
349
    datacount = 0
350

    
351
    try:
352
        while len(dump) > 0:
353
            dump = radio.pipe.read(100)
354
            datacount += len(dump)
355
            # hard limit to survive a infinite serial data stream
356
            # 5 times bigger than a normal rx block (69 bytes)
357
            if datacount > 345:
358
                seriale = "Please check your serial port selection."
359
                raise errors.RadioError(seriale)
360

    
361
        # restore the default serial timeout
362
        radio.pipe.timeout = STIMEOUT
363

    
364
    except Exception:
365
        raise errors.RadioError("Unknown error cleaning the serial buffer")
366

    
367

    
368
def _rawrecv(radio, amount):
369
    """Raw read from the radio device, less intensive way"""
370

    
371
    data = ""
372

    
373
    try:
374
        data = radio.pipe.read(amount)
375

    
376
        # DEBUG
377
        if debug is True:
378
            LOG.debug("<== (%d) bytes:\n\n%s" %
379
                      (len(data), util.hexprint(data)))
380

    
381
        # fail if no data is received
382
        if len(data) == 0:
383
            raise errors.RadioError("No data received from radio")
384

    
385
        # notice on the logs if short
386
        if len(data) < amount:
387
            LOG.warn("Short reading %d bytes from the %d requested." %
388
                     (len(data), amount))
389

    
390
    except:
391
        raise errors.RadioError("Error reading data from radio")
392

    
393
    return data
394

    
395

    
396
def _send(radio, data):
397
    """Send data to the radio device"""
398

    
399
    try:
400
        for byte in data:
401
            radio.pipe.write(byte)
402

    
403
        # DEBUG
404
        if debug is True:
405
            LOG.debug("==> (%d) bytes:\n\n%s" %
406
                      (len(data), util.hexprint(data)))
407
    except:
408
        raise errors.RadioError("Error sending data to radio")
409

    
410

    
411
def _make_frame(cmd, addr, length, data=""):
412
    """Pack the info in the headder format"""
413
    frame = "\x06" + struct.pack(">BHB", ord(cmd), addr, length)
414
    # add the data if set
415
    if len(data) != 0:
416
        frame += data
417

    
418
    return frame
419

    
420

    
421
def _recv(radio, addr):
422
    """Get data from the radio all at once to lower syscalls load"""
423

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

    
427
    # get the whole block
428
    block = _rawrecv(radio, BLOCK_SIZE + 5)
429

    
430
    # basic check
431
    if len(block) < (BLOCK_SIZE + 5):
432
        raise errors.RadioError("Short read of the block 0x%04x" % addr)
433

    
434
    # checking for the ack
435
    if block[0] != ACK_CMD:
436
        raise errors.RadioError("Bad ack from radio in block 0x%04x" % addr)
437

    
438
    # header validation
439
    c, a, l = struct.unpack(">BHB", block[1:5])
440
    if a != addr or l != BLOCK_SIZE or c != ord("X"):
441
        LOG.debug("Invalid header for block 0x%04x" % addr)
442
        LOG.debug("CMD: %s  ADDR: %04x  SIZE: %02x" % (c, a, l))
443
        raise errors.RadioError("Invalid header for block 0x%04x:" % addr)
444

    
445
    # return the data
446
    return block[5:]
447

    
448

    
449
def _start_clone_mode(radio, status):
450
    """Put the radio in clone mode and get the ident string, 3 tries"""
451

    
452
    # cleaning the serial buffer
453
    _clean_buffer(radio)
454

    
455
    # prep the data to show in the UI
456
    status.cur = 0
457
    status.msg = "Identifying the radio..."
458
    status.max = 3
459
    radio.status_fn(status)
460

    
461
    try:
462
        for a in range(0, status.max):
463
            # Update the UI
464
            status.cur = a + 1
465
            radio.status_fn(status)
466

    
467
            # send the magic word
468
            _send(radio, radio._magic)
469

    
470
            # Now you get a x06 of ACK if all goes well
471
            ack = radio.pipe.read(1)
472

    
473
            if ack == "\x06":
474
                # DEBUG
475
                LOG.info("Magic ACK received")
476
                status.cur = status.max
477
                radio.status_fn(status)
478

    
479
                return True
480

    
481
        return False
482

    
483
    except errors.RadioError:
484
        raise
485
    except Exception, e:
486
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
487

    
488

    
489
def _do_ident(radio, status, upload=False):
490
    """Put the radio in PROGRAM mode & identify it"""
491
    #  set the serial discipline
492
    radio.pipe.baudrate = 9600
493
    radio.pipe.parity = "N"
494

    
495
    # open the radio into program mode
496
    if _start_clone_mode(radio, status) is False:
497
        msg = "Radio did not enter clone mode"
498
        # warning about old versions of QYT KT8900
499
        if radio.MODEL == "KT8900":
500
            msg += ". You may want to try it as a WACCOM MINI-8900, there is a"
501
            msg += " known variant of this radios that is a clone of it."
502
        raise errors.RadioError(msg)
503

    
504
    # Ok, get the ident string
505
    ident = _rawrecv(radio, 49)
506

    
507
    # basic check for the ident
508
    if len(ident) != 49:
509
        raise errors.RadioError("Radio send a short ident block.")
510

    
511
    # check if ident is OK
512
    itis = False
513
    for fp in radio._fileid:
514
        if fp in ident:
515
            # got it!
516
            itis = True
517
            # checking if we are dealing with a Gen 3 BTECH
518
            if radio.VENDOR == "BTECH" and fp in BTECH3:
519
                radio.btech3 = True
520

    
521
            break
522

    
523
    if itis is False:
524
        LOG.debug("Incorrect model ID, got this:\n\n" + util.hexprint(ident))
525
        raise errors.RadioError("Radio identification failed.")
526

    
527
    # some radios needs a extra read and check for a code on it, this ones
528
    # has the check value in the _id2 var, others simply False
529
    if radio._id2 is not False:
530
        # lower the timeout here as this radios are reseting due to timeout
531
        radio.pipe.timeout = 0.05
532

    
533
        # query & receive the extra ID
534
        _send(radio, _make_frame("S", 0x3DF0, 16))
535
        id2 = _rawrecv(radio, 21)
536

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

    
544
        # ok, the correct string must be in the received data
545
        if radio._id2 not in id2:
546
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
547
                      (radio.MODEL, util.hexprint(id2)))
548
            raise errors.RadioError("The extra ID is wrong, aborting.")
549

    
550
        # this radios need a extra request/answer here on the upload
551
        # the amount of data received depends of the radio type
552
        #
553
        # also the first block of TX must no have the ACK at the beginning
554
        # see _upload for this.
555
        if upload is True:
556
            # send an ACK
557
            _send(radio, ACK_CMD)
558

    
559
            # the amount of data depend on the radio, so far we have two radios
560
            # reading two bytes with an ACK at the end and just ONE with just
561
            # one byte (QYT KT8900)
562
            # the JT-6188 appears a clone of the last, but reads TWO bytes.
563
            #
564
            # we will read two bytes with a custom timeout to not penalize the
565
            # users for this.
566
            #
567
            # we just check for a response and last byte being a ACK, that is
568
            # the common stone for all radios (3 so far)
569
            ack = _rawrecv(radio, 2)
570

    
571
            # checking
572
            if len(ack) == 0 or ack[-1:] != ACK_CMD:
573
                raise errors.RadioError("Radio didn't ACK the upload")
574

    
575
            # restore the default serial timeout
576
            radio.pipe.timeout = STIMEOUT
577

    
578
    # DEBUG
579
    LOG.info("Positive ident, this is a %s %s" % (radio.VENDOR, radio.MODEL))
580

    
581
    return True
582

    
583

    
584
def _download(radio):
585
    """Get the memory map"""
586

    
587
    # UI progress
588
    status = chirp_common.Status()
589

    
590
    # put radio in program mode and identify it
591
    _do_ident(radio, status)
592

    
593
    # the models that doesn't have the extra ID have to make a dummy read here
594
    if radio._id2 is False:
595
        _send(radio, _make_frame("S", 0, BLOCK_SIZE))
596
        discard = _rawrecv(radio, BLOCK_SIZE + 5)
597

    
598
        if debug is True:
599
            LOG.info("Dummy first block read done, got this:\n\n %s",
600
                     util.hexprint(discard))
601

    
602
    # reset the progress bar in the UI
603
    status.max = MEM_SIZE / BLOCK_SIZE
604
    status.msg = "Cloning from radio..."
605
    status.cur = 0
606
    radio.status_fn(status)
607

    
608
    # cleaning the serial buffer
609
    _clean_buffer(radio)
610

    
611
    data = ""
612
    for addr in range(0, MEM_SIZE, BLOCK_SIZE):
613
        # sending the read request
614
        _send(radio, _make_frame("S", addr, BLOCK_SIZE))
615

    
616
        # read
617
        d = _recv(radio, addr)
618

    
619
        # aggregate the data
620
        data += d
621

    
622
        # UI Update
623
        status.cur = addr / BLOCK_SIZE
624
        status.msg = "Cloning from radio..."
625
        radio.status_fn(status)
626

    
627
    return data
628

    
629

    
630
def _upload(radio):
631
    """Upload procedure"""
632

    
633
    # The UPLOAD mem is restricted to lower than 0x3100,
634
    # so we will overide that here localy
635
    MEM_SIZE = 0x3100
636

    
637
    # UI progress
638
    status = chirp_common.Status()
639

    
640
    # put radio in program mode and identify it
641
    _do_ident(radio, status, True)
642

    
643
    # get the data to upload to radio
644
    data = radio.get_mmap()
645

    
646
    # Reset the UI progress
647
    status.max = MEM_SIZE / TX_BLOCK_SIZE
648
    status.cur = 0
649
    status.msg = "Cloning to radio..."
650
    radio.status_fn(status)
651

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

    
656
    # cleaning the serial buffer
657
    _clean_buffer(radio)
658

    
659
    # the fun start here
660
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
661
        # getting the block of data to send
662
        d = data[addr:addr + TX_BLOCK_SIZE]
663

    
664
        # build the frame to send
665
        frame = _make_frame("X", addr, TX_BLOCK_SIZE, d)
666

    
667
        # first block must not send the ACK at the beginning for the
668
        # ones that has the extra id, since this have to do a extra step
669
        if addr == 0 and radio._id2 is not False:
670
            frame = frame[1:]
671

    
672
        # send the frame
673
        _send(radio, frame)
674

    
675
        # receiving the response
676
        ack = _rawrecv(radio, 1)
677

    
678
        # basic check
679
        if len(ack) != 1:
680
            raise errors.RadioError("No ACK when writing block 0x%04x" % addr)
681

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

    
685
         # UI Update
686
        status.cur = addr / TX_BLOCK_SIZE
687
        status.msg = "Cloning to radio..."
688
        radio.status_fn(status)
689

    
690

    
691
def model_match(cls, data):
692
    """Match the opened/downloaded image to the correct version"""
693
    rid = data[0x3f70:0x3f76]
694

    
695
    if rid in cls._fileid:
696
        return True
697

    
698
    return False
699

    
700

    
701
def _decode_ranges(low, high):
702
    """Unpack the data in the ranges zones in the memmap and return
703
    a tuple with the integer corresponding to the Mhz it means"""
704
    ilow = int(low[0]) * 100 + int(low[1]) * 10 + int(low[2])
705
    ihigh = int(high[0]) * 100 + int(high[1]) * 10 + int(high[2])
706
    ilow *= 1000000
707
    ihigh *= 1000000
708

    
709
    return (ilow, ihigh)
710

    
711

    
712
def _split(rf, f1, f2):
713
    """Returns False if the two freqs are in the same band (no split)
714
    or True otherwise"""
715

    
716
    # determine if the two freqs are in the same band
717
    for low, high in rf.valid_bands:
718
        if f1 >= low and f1 <= high and \
719
                f2 >= low and f2 <= high:
720
            # if the two freqs are on the same Band this is not a split
721
            return False
722

    
723
    # if you get here is because the freq pairs are split
724
    return False
725

    
726

    
727
class BTech(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
728
    """BTECH's UV-5001 and alike radios"""
729
    VENDOR = "BTECH"
730
    MODEL = ""
731
    IDENT = ""
732
    _vhf_range = (130000000, 180000000)
733
    _220_range = (210000000, 231000000)
734
    _uhf_range = (400000000, 521000000)
735
    _upper = 199
736
    _magic = MSTRING
737
    _fileid = None
738
    _id2 = False
739
    btech3 = False
740

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

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

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

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

    
769
            """))
770
        return rp
771

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

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

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

    
809
        # power levels
810
        if self.MODEL == "UV-5001":
811
            POWER_LEVELS = UV5001_POWER_LEVELS  # Higher power (50W)
812
        else:
813
            POWER_LEVELS = NORMAL_POWER_LEVELS  # Lower power (25W)
814

    
815
        rf.valid_power_levels = POWER_LEVELS
816

    
817
        # bands
818
        rf.valid_bands = [self._vhf_range, self._uhf_range]
819

    
820
        # 2501+220 & KT8900R
821
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
822
            rf.valid_bands.append(self._220_range)
823

    
824
        return rf
825

    
826
    def sync_in(self):
827
        """Download from radio"""
828
        data = _download(self)
829
        self._mmap = memmap.MemoryMap(data)
830
        self.process_mmap()
831

    
832
    def sync_out(self):
833
        """Upload to radio"""
834
        try:
835
            _upload(self)
836
        except errors.RadioError:
837
            raise
838
        except Exception, e:
839
            raise errors.RadioError("Error: %s" % e)
840

    
841
    def set_options(self):
842
        """This is to read the options from the image and set it in the
843
        environment, for now just the limits of the freqs in the VHF/UHF
844
        ranges"""
845

    
846
        # setting the correct ranges for each radio type
847
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
848
            # the model 2501+220 has a segment in 220
849
            # and a different position in the memmap
850
            # also the QYT KT8900R
851
            ranges = self._memobj.ranges220
852
        else:
853
            ranges = self._memobj.ranges
854

    
855
        # the normal dual bands
856
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
857
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
858

    
859
        # DEBUG
860
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
861
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
862

    
863
        # 220Mhz radios case
864
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
865
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
866
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
867
            self._220_range = vhf2
868

    
869
        # set the class with the real data
870
        self._vhf_range = vhf
871
        self._uhf_range = uhf
872

    
873
    def process_mmap(self):
874
        """Process the mem map into the mem object"""
875

    
876
        # Get it
877
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
878

    
879
        # load specific parameters from the radio image
880
        self.set_options()
881

    
882
    def get_raw_memory(self, number):
883
        return repr(self._memobj.memory[number])
884

    
885
    def _decode_tone(self, val):
886
        """Parse the tone data to decode from mem, it returns:
887
        Mode (''|DTCS|Tone), Value (None|###), Polarity (None,N,R)"""
888
        pol = None
889

    
890
        if val in [0, 65535]:
891
            return '', None, None
892
        elif val > 0x0258:
893
            a = val / 10.0
894
            return 'Tone', a, pol
895
        else:
896
            if val > 0x69:
897
                index = val - 0x6A
898
                pol = "R"
899
            else:
900
                index = val - 1
901
                pol = "N"
902

    
903
            tone = DTCS[index]
904
            return 'DTCS', tone, pol
905

    
906
    def _encode_tone(self, memval, mode, val, pol):
907
        """Parse the tone data to encode from UI to mem"""
908
        if mode == '' or mode is None:
909
            memval.set_raw("\x00\x00")
910
        elif mode == 'Tone':
911
            memval.set_value(val * 10)
912
        elif mode == 'DTCS':
913
            # detect the index in the DTCS list
914
            try:
915
                index = DTCS.index(val)
916
                if pol == "N":
917
                    index += 1
918
                else:
919
                    index += 0x6A
920
                memval.set_value(index)
921
            except:
922
                msg = "Digital Tone '%d' is not supported" % value
923
                LOG.error(msg)
924
                raise errors.RadioError(msg)
925
        else:
926
            msg = "Internal error: invalid mode '%s'" % mode
927
            LOG.error(msg)
928
            raise errors.InvalidDataError(msg)
929

    
930
    def get_memory(self, number):
931
        """Get the mem representation from the radio image"""
932
        _mem = self._memobj.memory[number]
933
        _names = self._memobj.names[number]
934

    
935
        # Create a high-level memory object to return to the UI
936
        mem = chirp_common.Memory()
937

    
938
        # Memory number
939
        mem.number = number
940

    
941
        if _mem.get_raw()[0] == "\xFF":
942
            mem.empty = True
943
            return mem
944

    
945
        # Freq and offset
946
        mem.freq = int(_mem.rxfreq) * 10
947
        # tx freq can be blank
948
        if _mem.get_raw()[4] == "\xFF":
949
            # TX freq not set
950
            mem.offset = 0
951
            mem.duplex = "off"
952
        else:
953
            # TX freq set
954
            offset = (int(_mem.txfreq) * 10) - mem.freq
955
            if offset != 0:
956
                if _split(self.get_features(), mem.freq, int(_mem.txfreq) * 10):
957
                    mem.duplex = "split"
958
                    mem.offset = int(_mem.txfreq) * 10
959
                elif offset < 0:
960
                    mem.offset = abs(offset)
961
                    mem.duplex = "-"
962
                elif offset > 0:
963
                    mem.offset = offset
964
                    mem.duplex = "+"
965
            else:
966
                mem.offset = 0
967

    
968
        # name TAG of the channel
969
        mem.name = str(_names.name).rstrip("\xFF").replace("\xFF", " ")
970

    
971
        # power
972
        mem.power = POWER_LEVELS[int(_mem.power)]
973

    
974
        # wide/narrow
975
        mem.mode = MODES[int(_mem.wide)]
976

    
977
        # skip
978
        mem.skip = SKIP_VALUES[_mem.add]
979

    
980
        # tone data
981
        rxtone = txtone = None
982
        txtone = self._decode_tone(_mem.txtone)
983
        rxtone = self._decode_tone(_mem.rxtone)
984
        chirp_common.split_tone_decode(mem, txtone, rxtone)
985

    
986
        # Extra
987
        mem.extra = RadioSettingGroup("extra", "Extra")
988

    
989
        scramble = RadioSetting("scramble", "Scramble",
990
                                RadioSettingValueBoolean(bool(_mem.scramble)))
991
        mem.extra.append(scramble)
992

    
993
        bcl = RadioSetting("bcl", "Busy channel lockout",
994
                           RadioSettingValueBoolean(bool(_mem.bcl)))
995
        mem.extra.append(bcl)
996

    
997
        pttid = RadioSetting("pttid", "PTT ID",
998
                             RadioSettingValueList(PTTID_LIST,
999
                                                   PTTID_LIST[_mem.pttid]))
1000
        mem.extra.append(pttid)
1001

    
1002
        # validating scode
1003
        scode = _mem.scode if _mem.scode != 15 else 0
1004
        pttidcode = RadioSetting("scode", "PTT ID signal code",
1005
                                 RadioSettingValueList(
1006
                                     PTTIDCODE_LIST,
1007
                                     PTTIDCODE_LIST[scode]))
1008
        mem.extra.append(pttidcode)
1009

    
1010
        optsig = RadioSetting("optsig", "Optional signaling",
1011
                              RadioSettingValueList(
1012
                                  OPTSIG_LIST,
1013
                                  OPTSIG_LIST[_mem.optsig]))
1014
        mem.extra.append(optsig)
1015

    
1016
        spmute = RadioSetting("spmute", "Speaker mute",
1017
                              RadioSettingValueList(
1018
                                  SPMUTE_LIST,
1019
                                  SPMUTE_LIST[_mem.spmute]))
1020
        mem.extra.append(spmute)
1021

    
1022
        return mem
1023

    
1024
    def set_memory(self, mem):
1025
        """Set the memory data in the eeprom img from the UI"""
1026
        # get the eprom representation of this channel
1027
        _mem = self._memobj.memory[mem.number]
1028
        _names = self._memobj.names[mem.number]
1029

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

    
1038
        # frequency
1039
        _mem.rxfreq = mem.freq / 10
1040

    
1041
        # duplex
1042
        if mem.duplex == "+":
1043
            _mem.txfreq = (mem.freq + mem.offset) / 10
1044
        elif mem.duplex == "-":
1045
            _mem.txfreq = (mem.freq - mem.offset) / 10
1046
        elif mem.duplex == "off":
1047
            for i in _mem.txfreq:
1048
                i.set_raw("\xFF")
1049
        elif mem.duplex == "split":
1050
            _mem.txfreq = mem.offset / 10
1051
        else:
1052
            _mem.txfreq = mem.freq / 10
1053

    
1054
        # tone data
1055
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1056
            chirp_common.split_tone_encode(mem)
1057
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1058
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1059

    
1060
        # name TAG of the channel
1061
        if len(mem.name) < NAME_LENGTH:
1062
            # we must pad to NAME_LENGTH chars, " " = "\xFF"
1063
            mem.name = str(mem.name).ljust(NAME_LENGTH, " ")
1064
        _names.name = str(mem.name).replace(" ", "\xFF")
1065

    
1066
        # power, # default power level is high
1067
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1068

    
1069
        # wide/narrow
1070
        _mem.wide = MODES.index(mem.mode)
1071

    
1072
        # scan add property
1073
        _mem.add = SKIP_VALUES.index(mem.skip)
1074

    
1075
        # reseting unknowns, this have to be set by hand
1076
        _mem.unknown0 = 0
1077
        _mem.unknown1 = 0
1078
        _mem.unknown2 = 0
1079
        _mem.unknown3 = 0
1080
        _mem.unknown4 = 0
1081
        _mem.unknown5 = 0
1082
        _mem.unknown6 = 0
1083

    
1084
        # extra settings
1085
        if len(mem.extra) > 0:
1086
            # there are setting, parse
1087
            for setting in mem.extra:
1088
                setattr(_mem, setting.get_name(), setting.value)
1089
        else:
1090
            # there is no extra settings, load defaults
1091
            _mem.spmute = 0
1092
            _mem.optsig = 0
1093
            _mem.scramble = 0
1094
            _mem.bcl = 0
1095
            _mem.pttid = 0
1096
            _mem.scode = 0
1097

    
1098
        return mem
1099

    
1100
    def get_settings(self):
1101
        """Translate the bit in the mem_struct into settings in the UI"""
1102
        _mem = self._memobj
1103
        basic = RadioSettingGroup("basic", "Basic Settings")
1104
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1105
        other = RadioSettingGroup("other", "Other Settings")
1106
        work = RadioSettingGroup("work", "Work Mode Settings")
1107
        top = RadioSettings(basic, advanced, other, work)
1108

    
1109
        # Basic
1110
        tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1111
                           RadioSettingValueBoolean(_mem.settings.tdr))
1112
        basic.append(tdr)
1113

    
1114
        sql = RadioSetting("settings.sql", "Squelch level",
1115
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1116
        basic.append(sql)
1117

    
1118
        tot = RadioSetting("settings.tot", "Time out timer",
1119
                           RadioSettingValueList(LIST_TOT, LIST_TOT[
1120
                               _mem.settings.tot]))
1121
        basic.append(tot)
1122

    
1123
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1124
            apo = RadioSetting("settings.apo", "Auto power off timer",
1125
                               RadioSettingValueList(LIST_APO, LIST_APO[
1126
                                   _mem.settings.apo]))
1127
            basic.append(apo)
1128
        else:
1129
            toa = RadioSetting("settings.apo", "Time out alert timer",
1130
                               RadioSettingValueList(LIST_TOA, LIST_TOA[
1131
                                   _mem.settings.apo]))
1132
            basic.append(toa)
1133

    
1134
        abr = RadioSetting("settings.abr", "Backlight timer",
1135
                           RadioSettingValueList(LIST_ABR, LIST_ABR[
1136
                               _mem.settings.abr]))
1137
        basic.append(abr)
1138

    
1139
        beep = RadioSetting("settings.beep", "Key beep",
1140
                            RadioSettingValueBoolean(_mem.settings.beep))
1141
        basic.append(beep)
1142

    
1143
        dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1144
                              RadioSettingValueList(LIST_DTMFST, LIST_DTMFST[
1145
                                  _mem.settings.dtmfst]))
1146
        basic.append(dtmfst)
1147

    
1148
        prisc = RadioSetting("settings.prisc", "Priority scan",
1149
                             RadioSettingValueBoolean(_mem.settings.prisc))
1150
        basic.append(prisc)
1151

    
1152
        prich = RadioSetting("settings.prich", "Priority channel",
1153
                             RadioSettingValueInteger(0, 199,
1154
                                 _mem.settings.prich))
1155
        basic.append(prich)
1156

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

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

    
1167
        emctp = RadioSetting("settings.emctp", "Alarm mode",
1168
                             RadioSettingValueList(LIST_EMCTP, LIST_EMCTP[
1169
                                 _mem.settings.emctp]))
1170
        basic.append(emctp)
1171

    
1172
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1173
                             RadioSettingValueInteger(0, 199,
1174
                                 _mem.settings.emcch))
1175
        basic.append(emcch)
1176

    
1177
        ringt = RadioSetting("settings.ringt", "Ring time",
1178
                             RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1179
                                 _mem.settings.ringt]))
1180
        basic.append(ringt)
1181

    
1182
        camdf = RadioSetting("settings.camdf", "Display mode A",
1183
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1184
                                 _mem.settings.camdf]))
1185
        basic.append(camdf)
1186

    
1187
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1188
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1189
                                 _mem.settings.cbmdf]))
1190
        basic.append(cbmdf)
1191

    
1192
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1193
           sync = RadioSetting("settings.sync", "A/B channel sync",
1194
                               RadioSettingValueBoolean(_mem.settings.sync))
1195
           basic.append(sync)
1196
        else:
1197
           autolk = RadioSetting("settings.sync", "Auto keylock",
1198
                                 RadioSettingValueBoolean(_mem.settings.sync))
1199
           basic.append(autolk)
1200

    
1201
        ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1202
                              RadioSettingValueList(LIST_PONMSG, LIST_PONMSG[
1203
                                  _mem.settings.ponmsg]))
1204
        basic.append(ponmsg)
1205

    
1206
        wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1207
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1208
                                 _mem.settings.wtled]))
1209
        basic.append(wtled)
1210

    
1211
        rxled = RadioSetting("settings.rxled", "RX backlight Color",
1212
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1213
                                 _mem.settings.rxled]))
1214
        basic.append(rxled)
1215

    
1216
        txled = RadioSetting("settings.txled", "TX backlight Color",
1217
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1218
                                 _mem.settings.txled]))
1219
        basic.append(txled)
1220

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

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

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

    
1236
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1237
            tdrab = RadioSetting("settings.tdrab", "TDR return time",
1238
                                 RadioSettingValueList(LIST_ABR, LIST_ABR[
1239
                                     _mem.settings.tdrab]))
1240
            basic.append(tdrab)
1241

    
1242
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1243
                               RadioSettingValueBoolean(_mem.settings.ste))
1244
            basic.append(ste)
1245

    
1246
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1247
                                 RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1248
                                     _mem.settings.rpste]))
1249
            basic.append(rpste)
1250

    
1251
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1252
                                 RadioSettingValueList(LIST_RPTDL, LIST_RPTDL[
1253
                                     _mem.settings.rptdl]))
1254
            basic.append(rptdl)
1255

    
1256
        if str(_mem.fingerprint.fp) in BTECH3:
1257

    
1258
            mgain = RadioSetting("settings.mgain", "Mic gain",
1259
                                 RadioSettingValueInteger(0, 120,
1260
                                     _mem.settings.mgain))
1261
            basic.append(mgain)
1262

    
1263
            dtmfg = RadioSetting("settings.dtmfg", "DTMF gain",
1264
                                 RadioSettingValueInteger(0, 60,
1265
                                     _mem.settings.dtmfg))
1266
            basic.append(dtmfg)
1267

    
1268
        # Advanced
1269
        def _filter(name):
1270
            filtered = ""
1271
            for char in str(name):
1272
                if char in VALID_CHARS:
1273
                    filtered += char
1274
                else:
1275
                    filtered += " "
1276
            return filtered
1277

    
1278
        _msg = self._memobj.poweron_msg
1279
        line1 = RadioSetting("poweron_msg.line1", "Power-on message line 1",
1280
                             RadioSettingValueString(0, 6, _filter(
1281
                                 _msg.line1)))
1282
        advanced.append(line1)
1283
        line2 = RadioSetting("poweron_msg.line2", "Power-on message line 2",
1284
                             RadioSettingValueString(0, 6, _filter(
1285
                                 _msg.line2)))
1286
        advanced.append(line2)
1287

    
1288
        if self.MODEL in ("UV-2501", "UV-5001"):
1289
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1290
                                   RadioSettingValueBoolean(
1291
                                       not _mem.settings2.vfomren))
1292
            advanced.append(vfomren)
1293

    
1294
            reseten = RadioSetting("settings2.reseten", "RESET",
1295
                                   RadioSettingValueBoolean(
1296
                                       _mem.settings2.reseten))
1297
            advanced.append(reseten)
1298

    
1299
            menuen = RadioSetting("settings2.menuen", "Menu",
1300
                                  RadioSettingValueBoolean(
1301
                                      _mem.settings2.menuen))
1302
            advanced.append(menuen)
1303

    
1304
        # Other
1305
        def convert_bytes_to_limit(bytes):
1306
            limit = ""
1307
            for byte in bytes:
1308
                if byte < 10:
1309
                    limit += chr(byte + 0x30)
1310
                else:
1311
                    break
1312
            return limit
1313

    
1314
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1315
            _ranges = self._memobj.ranges220
1316
            ranges = "ranges220"
1317
        else:
1318
            _ranges = self._memobj.ranges
1319
            ranges = "ranges"
1320

    
1321
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1322
        val = RadioSettingValueString(0, 3, _limit)
1323
        val.set_mutable(False)
1324
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1325
        other.append(vhf_low)
1326

    
1327
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1328
        val = RadioSettingValueString(0, 3, _limit)
1329
        val.set_mutable(False)
1330
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1331
        other.append(vhf_high)
1332

    
1333
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1334
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1335
            val = RadioSettingValueString(0, 3, _limit)
1336
            val.set_mutable(False)
1337
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1338
            other.append(vhf2_low)
1339

    
1340
            _limit = convert_bytes_to_limit(_ranges.vhf2_high)
1341
            val = RadioSettingValueString(0, 3, _limit)
1342
            val.set_mutable(False)
1343
            vhf2_high = RadioSetting("%s.vhf2_high" % ranges, "VHF2 high", val)
1344
            other.append(vhf2_high)
1345

    
1346
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1347
        val = RadioSettingValueString(0, 3, _limit)
1348
        val.set_mutable(False)
1349
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1350
        other.append(uhf_low)
1351

    
1352
        _limit = convert_bytes_to_limit(_ranges.uhf_high)
1353
        val = RadioSettingValueString(0, 3, _limit)
1354
        val.set_mutable(False)
1355
        uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
1356
        other.append(uhf_high)
1357

    
1358
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1359
        val.set_mutable(False)
1360
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1361
        other.append(fp)
1362

    
1363
        # Work
1364
        dispab = RadioSetting("settings2.dispab", "Display",
1365
                              RadioSettingValueList(LIST_AB,LIST_AB[
1366
                                  _mem.settings2.dispab]))
1367
        work.append(dispab)
1368

    
1369
        vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1370
                             RadioSettingValueList(LIST_VFOMR,LIST_VFOMR[
1371
                                 _mem.settings2.vfomr]))
1372
        work.append(vfomr)
1373

    
1374
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1375
                           RadioSettingValueBoolean(_mem.settings2.keylock))
1376
        work.append(keylock)
1377

    
1378
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1379
                             RadioSettingValueInteger(0, 199,
1380
                                 _mem.settings2.mrcha))
1381
        work.append(mrcha)
1382

    
1383
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1384
                             RadioSettingValueInteger(0, 199,
1385
                                 _mem.settings2.mrchb))
1386
        work.append(mrchb)
1387

    
1388
        def convert_bytes_to_freq(bytes):
1389
            real_freq = 0
1390
            for byte in bytes:
1391
                real_freq = (real_freq * 10) + byte
1392
            return chirp_common.format_freq(real_freq * 10)
1393

    
1394
        def my_validate(value):
1395
            value = chirp_common.parse_freq(value)
1396
            if "+220" in self.MODEL:
1397
                if 180000000 <= value and value < 210000000:
1398
                    msg = ("Can't be between 180.00000-210.00000")
1399
                    raise InvalidValueError(msg)
1400
                elif 231000000 <= value and value < 400000000:
1401
                    msg = ("Can't be between 231.00000-400.00000")
1402
                    raise InvalidValueError(msg)
1403
            elif "8900R" in self.MODEL:
1404
                if 180000000 <= value and value < 240000000:
1405
                    msg = ("Can't be between 180.00000-240.00000")
1406
                    raise InvalidValueError(msg)
1407
                elif 271000000 <= value and value < 400000000:
1408
                    msg = ("Can't be between 271.00000-400.00000")
1409
                    raise InvalidValueError(msg)
1410
            elif 180000000 <= value and value < 400000000:
1411
                msg = ("Can't be between 180.00000-400.00000")
1412
                raise InvalidValueError(msg)
1413
            return chirp_common.format_freq(value)
1414

    
1415
        def apply_freq(setting, obj):
1416
            value = chirp_common.parse_freq(str(setting.value)) / 10
1417
            for i in range(7, -1, -1):
1418
                obj.freq[i] = value % 10
1419
                value /= 10
1420

    
1421
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1422
                                        _mem.vfo.a.freq))
1423
        val1a.set_validate_callback(my_validate)
1424
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1425
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1426
        work.append(vfoafreq)
1427

    
1428
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1429
                                        _mem.vfo.b.freq))
1430
        val1b.set_validate_callback(my_validate)
1431
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1432
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1433
        work.append(vfobfreq)
1434

    
1435
        vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1436
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1437
                                      _mem.vfo.a.shiftd]))
1438
        work.append(vfoashiftd)
1439

    
1440
        vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1441
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1442
                                      _mem.vfo.b.shiftd]))
1443
        work.append(vfobshiftd)
1444

    
1445
        def convert_bytes_to_offset(bytes):
1446
            real_offset = 0
1447
            for byte in bytes:
1448
                real_offset = (real_offset * 10) + byte
1449
            return chirp_common.format_freq(real_offset * 10000)
1450

    
1451
        def apply_offset(setting, obj):
1452
            value = chirp_common.parse_freq(str(setting.value)) / 10000
1453
            for i in range(3, -1, -1):
1454
                obj.offset[i] = value % 10
1455
                value /= 10
1456

    
1457
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1458
                                        _mem.vfo.a.offset))
1459
        vfoaoffset = RadioSetting("vfo.a.offset",
1460
                                  "VFO A offset (0.00-99.95)", val1a)
1461
        vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1462
        work.append(vfoaoffset)
1463

    
1464
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1465
                                        _mem.vfo.b.offset))
1466
        vfoboffset = RadioSetting("vfo.b.offset",
1467
                                  "VFO B offset (0.00-99.95)", val1b)
1468
        vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1469
        work.append(vfoboffset)
1470

    
1471
        vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1472
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1473
                                    _mem.vfo.a.power]))
1474
        work.append(vfoatxp)
1475

    
1476
        vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1477
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1478
                                    _mem.vfo.b.power]))
1479
        work.append(vfobtxp)
1480

    
1481
        vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1482
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1483
                                    _mem.vfo.a.wide]))
1484
        work.append(vfoawide)
1485

    
1486
        vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1487
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1488
                                    _mem.vfo.b.wide]))
1489
        work.append(vfobwide)
1490

    
1491
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
1492
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1493
                                    _mem.vfo.a.step]))
1494
        work.append(vfoastep)
1495

    
1496
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
1497
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1498
                                    _mem.vfo.b.step]))
1499
        work.append(vfobstep)
1500

    
1501
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
1502
                                  RadioSettingValueList(OPTSIG_LIST,
1503
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
1504
        work.append(vfoaoptsig)
1505

    
1506
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
1507
                                  RadioSettingValueList(OPTSIG_LIST,
1508
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
1509
        work.append(vfoboptsig)
1510

    
1511
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
1512
                                  RadioSettingValueList(SPMUTE_LIST,
1513
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
1514
        work.append(vfoaspmute)
1515

    
1516
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
1517
                                  RadioSettingValueList(SPMUTE_LIST,
1518
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
1519
        work.append(vfobspmute)
1520

    
1521
        vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
1522
                               RadioSettingValueBoolean(_mem.vfo.a.scramble))
1523
        work.append(vfoascr)
1524

    
1525
        vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
1526
                               RadioSettingValueBoolean(_mem.vfo.b.scramble))
1527
        work.append(vfobscr)
1528

    
1529
        vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
1530
                                 RadioSettingValueList(PTTIDCODE_LIST,
1531
                                     PTTIDCODE_LIST[_mem.vfo.a.scode]))
1532
        work.append(vfoascode)
1533

    
1534
        vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
1535
                                 RadioSettingValueList(PTTIDCODE_LIST,
1536
                                     PTTIDCODE_LIST[_mem.vfo.b.scode]))
1537
        work.append(vfobscode)
1538

    
1539
        pttid = RadioSetting("settings.pttid", "PTT ID",
1540
                             RadioSettingValueList(PTTID_LIST,
1541
                                 PTTID_LIST[_mem.settings.pttid]))
1542
        work.append(pttid)
1543

    
1544
        return top
1545

    
1546
    def set_settings(self, settings):
1547
        _settings = self._memobj.settings
1548
        for element in settings:
1549
            if not isinstance(element, RadioSetting):
1550
                if element.get_name() == "fm_preset":
1551
                    self._set_fm_preset(element)
1552
                else:
1553
                    self.set_settings(element)
1554
                    continue
1555
            else:
1556
                try:
1557
                    name = element.get_name()
1558
                    if "." in name:
1559
                        bits = name.split(".")
1560
                        obj = self._memobj
1561
                        for bit in bits[:-1]:
1562
                            if "/" in bit:
1563
                                bit, index = bit.split("/", 1)
1564
                                index = int(index)
1565
                                obj = getattr(obj, bit)[index]
1566
                            else:
1567
                                obj = getattr(obj, bit)
1568
                        setting = bits[-1]
1569
                    else:
1570
                        obj = _settings
1571
                        setting = element.get_name()
1572

    
1573
                    if element.has_apply_callback():
1574
                        LOG.debug("Using apply callback")
1575
                        element.run_apply_callback()
1576
                    elif setting == "vfomren":
1577
                        setattr(obj, setting, not int(element.value))
1578
                    elif element.value.get_mutable():
1579
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1580
                        setattr(obj, setting, element.value)
1581
                except Exception, e:
1582
                    LOG.debug(element.get_name())
1583
                    raise
1584

    
1585
    @classmethod
1586
    def match_model(cls, filedata, filename):
1587
        match_size = False
1588
        match_model = False
1589

    
1590
        # testing the file data size
1591
        if len(filedata) == MEM_SIZE:
1592
            match_size = True
1593

    
1594
        # testing the firmware model fingerprint
1595
        match_model = model_match(cls, filedata)
1596

    
1597
        if match_size and match_model:
1598
            return True
1599
        else:
1600
            return False
1601

    
1602

    
1603
# Declaring Aliases (Clones of the real radios)
1604
class JT2705M(chirp_common.Alias):
1605
    VENDOR = "Jetstream"
1606
    MODEL = "JT2705M"
1607

    
1608

    
1609
class JT6188Mini(chirp_common.Alias):
1610
    VENDOR = "Juentai"
1611
    MODEL = "JT-6188 Mini"
1612

    
1613

    
1614
class JT6188Plus(chirp_common.Alias):
1615
    VENDOR = "Juentai"
1616
    MODEL = "JT-6188 Plus"
1617

    
1618

    
1619
class SSGT890(chirp_common.Alias):
1620
    VENDOR = "Sainsonic"
1621
    MODEL = "GT-890"
1622

    
1623

    
1624
class ZastoneMP300(chirp_common.Alias):
1625
    VENDOR = "Zastone"
1626
    MODEL = "MP-300"
1627

    
1628

    
1629
# real radios
1630
@directory.register
1631
class UV2501(BTech):
1632
    """Baofeng Tech UV2501"""
1633
    MODEL = "UV-2501"
1634
    _fileid = [UV2501G3_fp,
1635
               UV2501G2_fp,
1636
               UV2501pp2_fp,
1637
               UV2501pp_fp]
1638

    
1639

    
1640
@directory.register
1641
class UV2501_220(BTech):
1642
    """Baofeng Tech UV2501+220"""
1643
    MODEL = "UV-2501+220"
1644
    _magic = MSTRING_220
1645
    _id2 = UV2501_220pp_id
1646
    _fileid = [UV2501_220G3_fp,
1647
               UV2501_220G2_fp,
1648
               UV2501_220_fp,
1649
               UV2501_220pp_fp]
1650

    
1651

    
1652
@directory.register
1653
class UV5001(BTech):
1654
    """Baofeng Tech UV5001"""
1655
    MODEL = "UV-5001"
1656
    _fileid = [UV5001G3_fp,
1657
               UV5001G22_fp,
1658
               UV5001G2_fp,
1659
               UV5001alpha_fp,
1660
               UV5001pp_fp]
1661

    
1662

    
1663
@directory.register
1664
class MINI8900(BTech):
1665
    """WACCOM MINI-8900"""
1666
    VENDOR = "WACCOM"
1667
    MODEL = "MINI-8900"
1668
    _magic = MSTRING_MINI8900
1669
    _fileid = [MINI8900_fp, ]
1670
    # Clones
1671
    ALIASES = [JT6188Plus, ]
1672

    
1673

    
1674
@directory.register
1675
class KTUV980(BTech):
1676
    """QYT KT-UV980"""
1677
    VENDOR = "QYT"
1678
    MODEL = "KT-UV980"
1679
    _vhf_range = (136000000, 175000000)
1680
    _uhf_range = (400000000, 481000000)
1681
    _magic = MSTRING_MINI8900
1682
    _fileid = [KTUV980_fp, ]
1683
    # Clones
1684
    ALIASES = [JT2705M, ]
1685

    
1686
# Please note that there is a version of this radios that is a clone of the
1687
# Waccom Mini8900, maybe an early version?
1688
@directory.register
1689
class KT9800(BTech):
1690
    """QYT KT8900"""
1691
    VENDOR = "QYT"
1692
    MODEL = "KT8900"
1693
    _vhf_range = (136000000, 175000000)
1694
    _uhf_range = (400000000, 481000000)
1695
    _magic = MSTRING_KT8900
1696
    _fileid = [KT8900_fp,
1697
               KT8900_fp1,
1698
               KT8900_fp2,
1699
               KT8900_fp3,
1700
               KT8900_fp4]
1701
    _id2 = KT8900_id
1702
    # Clones
1703
    ALIASES = [JT6188Mini, SSGT890, ZastoneMP300]
1704

    
1705

    
1706
@directory.register
1707
class KT9800R(BTech):
1708
    """QYT KT8900R"""
1709
    VENDOR = "QYT"
1710
    MODEL = "KT8900R"
1711
    _vhf_range = (136000000, 175000000)
1712
    _220_range = (240000000, 271000000)
1713
    _uhf_range = (400000000, 481000000)
1714
    _magic = MSTRING_KT8900R
1715
    _fileid = [KT8900R_fp,
1716
               KT8900R_fp1,
1717
               KT8900R_fp2,
1718
               KT8900R_fp3,
1719
			   KT8900R_fp4]
1720
    _id2 = KT8900R_id
1721

    
1722

    
1723
@directory.register
1724
class LT588UV(BTech):
1725
    """LUITON LT-588UV"""
1726
    VENDOR = "LUITON"
1727
    MODEL = "LT-588UV"
1728
    _vhf_range = (136000000, 175000000)
1729
    _uhf_range = (400000000, 481000000)
1730
    _magic = MSTRING_KT8900
1731
    _fileid = [LT588UV_fp, ]
(1-1/3)