btech.py

Dev version with support for the QYT KT8900R for testing before inclusion on the daily - Pavel Milanes, 05/16/2016 10:28 am

Download (53.1 kB)

 
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
} settings;
100

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

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

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

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

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

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

    
163
// the 2501+220 has a different zone for storing ranges
164
// Also the KT8900R
165

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

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

    
185
"""
186

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

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

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

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

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

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

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

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

    
253

    
254
##### ID strings #####################################################
255

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

    
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

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

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

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

    
296

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

    
300

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

    
310
# KT8900R
311
KT8900R_fp = "M3G214"
312
KT8900R_id = "      280528"
313

    
314
#### MAGICS
315
# for the Waccom Mini-8900
316
MSTRING_MINI8900 = "\x55\xA5\xB5\x45\x55\x45\x4d\x02"
317
# for the B-TECH UV-2501+220 (including pre production ones)
318
MSTRING_220 = "\x55\x20\x15\x12\x12\x01\x4d\x02"
319
# for the QYT KT8900 & R
320
MSTRING_KT8900 = "\x55\x20\x15\x09\x16\x45\x4D\x02"
321
MSTRING_KT8900R = "\x55\x20\x15\x09\x25\x01\x4D\x02"
322
# magic string for all other models
323
MSTRING = "\x55\x20\x15\x09\x20\x45\x4d\x02"
324

    
325

    
326
def _clean_buffer(radio):
327
    """Cleaning the read serial buffer, hard timeout to survive an infinite
328
    data stream"""
329

    
330
    # touching the serial timeout to optimize the flushing
331
    # restored at the end to the default value
332
    radio.pipe.setTimeout(0.1)
333
    dump = "1"
334
    datacount = 0
335

    
336
    try:
337
        while len(dump) > 0:
338
            dump = radio.pipe.read(100)
339
            datacount += len(dump)
340
            # hard limit to survive a infinite serial data stream
341
            # 5 times bigger than a normal rx block (69 bytes)
342
            if datacount > 345:
343
                seriale = "Please check your serial port selection."
344
                raise errors.RadioError(seriale)
345

    
346
        # restore the default serial timeout
347
        radio.pipe.setTimeout(STIMEOUT)
348

    
349
    except Exception:
350
        raise errors.RadioError("Unknown error cleaning the serial buffer")
351

    
352

    
353
def _rawrecv(radio, amount):
354
    """Raw read from the radio device, less intensive way"""
355

    
356
    data = ""
357

    
358
    try:
359
        data = radio.pipe.read(amount)
360

    
361
        # DEBUG
362
        if debug is True:
363
            LOG.debug("<== (%d) bytes:\n\n%s" %
364
                      (len(data), util.hexprint(data)))
365

    
366
        # fail if no data is received
367
        if len(data) == 0:
368
            raise errors.RadioError("No data received from radio")
369

    
370
        # notice on the logs if short
371
        if len(data) < amount:
372
            LOG.warn("Short reading %d bytes from the %d requested." %
373
                     (len(data), amount))
374

    
375
    except:
376
        raise errors.RadioError("Error reading data from radio")
377

    
378
    return data
379

    
380

    
381
def _send(radio, data):
382
    """Send data to the radio device"""
383

    
384
    try:
385
        for byte in data:
386
            radio.pipe.write(byte)
387

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

    
395

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

    
403
    return frame
404

    
405

    
406
def _recv(radio, addr):
407
    """Get data from the radio all at once to lower syscalls load"""
408

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

    
412
    # get the whole block
413
    block = _rawrecv(radio, BLOCK_SIZE + 5)
414

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

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

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

    
430
    # return the data
431
    return block[5:]
432

    
433

    
434
def _start_clone_mode(radio, status):
435
    """Put the radio in clone mode and get the ident string, 3 tries"""
436

    
437
    # cleaning the serial buffer
438
    _clean_buffer(radio)
439

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

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

    
452
            # send the magic word
453
            _send(radio, radio._magic)
454

    
455
            # Now you get a x06 of ACK if all goes well
456
            ack = radio.pipe.read(1)
457

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

    
464
                return True
465

    
466
        return False
467

    
468
    except errors.RadioError:
469
        raise
470
    except Exception, e:
471
        raise errors.RadioError("Error sending Magic to radio:\n%s" % e)
472

    
473

    
474
def _do_ident(radio, status, upload=False):
475
    """Put the radio in PROGRAM mode & identify it"""
476
    #  set the serial discipline
477
    radio.pipe.setBaudrate(9600)
478
    radio.pipe.setParity("N")
479

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

    
489
    # Ok, get the ident string
490
    ident = _rawrecv(radio, 49)
491

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

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

    
506
            break
507

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

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

    
518
        # query & receive the extra ID
519
        _send(radio, _make_frame("S", 0x3DF0, 16))
520
        id2 = _rawrecv(radio, 21)
521

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

    
529
        # ok, the correct string must be in the received data
530
        if radio._id2 not in id2:
531
            LOG.debug("Full *BAD* extra ID on the %s is: \n%s" %
532
                      (radio.MODEL, util.hexprint(id2)))
533
            raise errors.RadioError("The extra ID is wrong, aborting.")
534

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

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

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

    
560
            # restore the default serial timeout
561
            radio.pipe.setTimeout(STIMEOUT)
562

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

    
566
    return True
567

    
568

    
569
def _download(radio):
570
    """Get the memory map"""
571

    
572
    # UI progress
573
    status = chirp_common.Status()
574

    
575
    # put radio in program mode and identify it
576
    _do_ident(radio, status)
577

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

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

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

    
593
    # cleaning the serial buffer
594
    _clean_buffer(radio)
595

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

    
601
        # read
602
        d = _recv(radio, addr)
603

    
604
        # aggregate the data
605
        data += d
606

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

    
612
    return data
613

    
614

    
615
def _upload(radio):
616
    """Upload procedure"""
617

    
618
    # The UPLOAD mem is restricted to lower than 0x3100,
619
    # so we will overide that here localy
620
    MEM_SIZE = 0x3100
621

    
622
    # UI progress
623
    status = chirp_common.Status()
624

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

    
628
    # get the data to upload to radio
629
    data = radio.get_mmap()
630

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

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

    
641
    # cleaning the serial buffer
642
    _clean_buffer(radio)
643

    
644
    # the fun start here
645
    for addr in range(0, MEM_SIZE, TX_BLOCK_SIZE):
646
        # getting the block of data to send
647
        d = data[addr:addr + TX_BLOCK_SIZE]
648

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

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

    
657
        # send the frame
658
        _send(radio, frame)
659

    
660
        # receiving the response
661
        ack = _rawrecv(radio, 1)
662

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

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

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

    
675

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

    
680
    if rid in cls._fileid:
681
        return True
682

    
683
    return False
684

    
685

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

    
694
    return (ilow, ihigh)
695

    
696

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

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

    
708
    # if you get here is because the freq pairs are split
709
    return False
710

    
711

    
712
class BTech(chirp_common.CloneModeRadio, chirp_common.ExperimentalRadio):
713
    """BTECH's UV-5001 and alike radios"""
714
    VENDOR = "BTECH"
715
    MODEL = ""
716
    IDENT = ""
717
    _vhf_range = (130000000, 180000000)
718
    _220_range = (210000000, 231000000)
719
    _uhf_range = (400000000, 521000000)
720
    _upper = 199
721
    _magic = MSTRING
722
    _fileid = None
723
    _id2 = False
724
    btech3 = False
725

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

    
740
            1 - Turn off your radio
741
            2 - Connect your interface cable
742
            3 - Turn on your radio
743
            4 - Do the download of your radio data
744

    
745
            """))
746
        rp.pre_upload = _(dedent("""\
747
            Follow these instructions to upload 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 upload of your radio data
753

    
754
            """))
755
        return rp
756

    
757
    def get_features(self):
758
        """Get the radio's features"""
759

    
760
        # we will use the following var as global
761
        global POWER_LEVELS
762

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

    
793
        # power levels
794
        if self.MODEL == "UV-5001":
795
            POWER_LEVELS = UV5001_POWER_LEVELS  # Higher power (50W)
796
        else:
797
            POWER_LEVELS = NORMAL_POWER_LEVELS  # Lower power (25W)
798

    
799
        rf.valid_power_levels = POWER_LEVELS
800

    
801
        # bands
802
        rf.valid_bands = [self._vhf_range, self._uhf_range]
803

    
804
        # 2501+220 & KT8900R
805
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
806
            rf.valid_bands.append(self._220_range)
807

    
808
        return rf
809

    
810
    def sync_in(self):
811
        """Download from radio"""
812
        data = _download(self)
813
        self._mmap = memmap.MemoryMap(data)
814
        self.process_mmap()
815

    
816
    def sync_out(self):
817
        """Upload to radio"""
818
        try:
819
            _upload(self)
820
        except errors.RadioError:
821
            raise
822
        except Exception, e:
823
            raise errors.RadioError("Error: %s" % e)
824

    
825
    def set_options(self):
826
        """This is to read the options from the image and set it in the
827
        environment, for now just the limits of the freqs in the VHF/UHF
828
        ranges"""
829

    
830
        # setting the correct ranges for each radio type
831
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
832
            # the model 2501+220 has a segment in 220
833
            # and a different position in the memmap
834
            # also the KT8900R
835
            ranges = self._memobj.ranges220
836
        else:
837
            ranges = self._memobj.ranges
838

    
839
        # the normal dual bands
840
        vhf = _decode_ranges(ranges.vhf_low, ranges.vhf_high)
841
        uhf = _decode_ranges(ranges.uhf_low, ranges.uhf_high)
842

    
843
        # DEBUG
844
        LOG.info("Radio ranges: VHF %d to %d" % vhf)
845
        LOG.info("Radio ranges: UHF %d to %d" % uhf)
846

    
847
        # 220Mhz case
848
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
849
            vhf2 = _decode_ranges(ranges.vhf2_low, ranges.vhf2_high)
850
            LOG.info("Radio ranges: VHF(220) %d to %d" % vhf2)
851
            self._220_range = vhf2
852

    
853
        # set the class with the real data
854
        self._vhf_range = vhf
855
        self._uhf_range = uhf
856

    
857
    def process_mmap(self):
858
        """Process the mem map into the mem object"""
859

    
860
        # Get it
861
        self._memobj = bitwise.parse(MEM_FORMAT, self._mmap)
862

    
863
        # load specific parameters from the radio image
864
        self.set_options()
865

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

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

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

    
887
            tone = DTCS[index]
888
            return 'DTCS', tone, pol
889

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

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

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

    
922
        # Memory number
923
        mem.number = number
924

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

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

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

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

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

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

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

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

    
973
        scramble = RadioSetting("scramble", "Scramble",
974
                                RadioSettingValueBoolean(bool(_mem.scramble)))
975
        mem.extra.append(scramble)
976

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

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

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

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

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

    
1006
        return mem
1007

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

    
1014
        # if empty memmory
1015
        if mem.empty:
1016
            # the channel itself
1017
            _mem.set_raw("\xFF" * 16)
1018
            # the name tag
1019
            _names.set_raw("\xFF" * 16)
1020
            return
1021

    
1022
        # frequency
1023
        _mem.rxfreq = mem.freq / 10
1024

    
1025
        # duplex
1026
        if mem.duplex == "+":
1027
            _mem.txfreq = (mem.freq + mem.offset) / 10
1028
        elif mem.duplex == "-":
1029
            _mem.txfreq = (mem.freq - mem.offset) / 10
1030
        elif mem.duplex == "off":
1031
            for i in _mem.txfreq:
1032
                i.set_raw("\xFF")
1033
        elif mem.duplex == "split":
1034
            _mem.txfreq = mem.offset / 10
1035
        else:
1036
            _mem.txfreq = mem.freq / 10
1037

    
1038
        # tone data
1039
        ((txmode, txtone, txpol), (rxmode, rxtone, rxpol)) = \
1040
            chirp_common.split_tone_encode(mem)
1041
        self._encode_tone(_mem.txtone, txmode, txtone, txpol)
1042
        self._encode_tone(_mem.rxtone, rxmode, rxtone, rxpol)
1043

    
1044
        # name TAG of the channel
1045
        if len(mem.name) < NAME_LENGTH:
1046
            # we must pad to NAME_LENGTH chars, " " = "\xFF"
1047
            mem.name = str(mem.name).ljust(NAME_LENGTH, " ")
1048
        _names.name = str(mem.name).replace(" ", "\xFF")
1049

    
1050
        # power, # default power level is high
1051
        _mem.power = 0 if mem.power is None else POWER_LEVELS.index(mem.power)
1052

    
1053
        # wide/narrow
1054
        _mem.wide = MODES.index(mem.mode)
1055

    
1056
        # scan add property
1057
        _mem.add = SKIP_VALUES.index(mem.skip)
1058

    
1059
        # reseting unknowns, this have to be set by hand
1060
        _mem.unknown0 = 0
1061
        _mem.unknown1 = 0
1062
        _mem.unknown2 = 0
1063
        _mem.unknown3 = 0
1064
        _mem.unknown4 = 0
1065
        _mem.unknown5 = 0
1066
        _mem.unknown6 = 0
1067

    
1068
        # extra settings
1069
        if len(mem.extra) > 0:
1070
            # there are setting, parse
1071
            for setting in mem.extra:
1072
                setattr(_mem, setting.get_name(), setting.value)
1073
        else:
1074
            # there is no extra settings, load defaults
1075
            _mem.spmute = 0
1076
            _mem.optsig = 0
1077
            _mem.scramble = 0
1078
            _mem.bcl = 0
1079
            _mem.pttid = 0
1080
            _mem.scode = 0
1081

    
1082
        return mem
1083

    
1084
    def get_settings(self):
1085
        """Translate the bit in the mem_struct into settings in the UI"""
1086
        _mem = self._memobj
1087
        basic = RadioSettingGroup("basic", "Basic Settings")
1088
        advanced = RadioSettingGroup("advanced", "Advanced Settings")
1089
        other = RadioSettingGroup("other", "Other Settings")
1090
        work = RadioSettingGroup("work", "Work Mode Settings")
1091
        top = RadioSettings(basic, advanced, other, work)
1092

    
1093
        # Basic
1094
        tdr = RadioSetting("settings.tdr", "Transceiver dual receive",
1095
                           RadioSettingValueBoolean(_mem.settings.tdr))
1096
        basic.append(tdr)
1097

    
1098
        sql = RadioSetting("settings.sql", "Squelch level",
1099
                           RadioSettingValueInteger(0, 9, _mem.settings.sql))
1100
        basic.append(sql)
1101

    
1102
        tot = RadioSetting("settings.tot", "Time out timer",
1103
                           RadioSettingValueList(LIST_TOT, LIST_TOT[
1104
                               _mem.settings.tot]))
1105
        basic.append(tot)
1106

    
1107
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1108
            apo = RadioSetting("settings.apo", "Auto power off timer",
1109
                               RadioSettingValueList(LIST_APO, LIST_APO[
1110
                                   _mem.settings.apo]))
1111
            basic.append(apo)
1112
        else:
1113
            toa = RadioSetting("settings.apo", "Time out alert timer",
1114
                               RadioSettingValueList(LIST_TOA, LIST_TOA[
1115
                                   _mem.settings.apo]))
1116
            basic.append(toa)
1117

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

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

    
1127
        dtmfst = RadioSetting("settings.dtmfst", "DTMF side tone",
1128
                              RadioSettingValueList(LIST_DTMFST, LIST_DTMFST[
1129
                                  _mem.settings.dtmfst]))
1130
        basic.append(dtmfst)
1131

    
1132
        prisc = RadioSetting("settings.prisc", "Priority scan",
1133
                             RadioSettingValueBoolean(_mem.settings.prisc))
1134
        basic.append(prisc)
1135

    
1136
        prich = RadioSetting("settings.prich", "Priority channel",
1137
                             RadioSettingValueInteger(0, 199,
1138
                                 _mem.settings.prich))
1139
        basic.append(prich)
1140

    
1141
        screv = RadioSetting("settings.screv", "Scan resume method",
1142
                             RadioSettingValueList(LIST_SCREV, LIST_SCREV[
1143
                                 _mem.settings.screv]))
1144
        basic.append(screv)
1145

    
1146
        pttlt = RadioSetting("settings.pttlt", "PTT transmit delay",
1147
                             RadioSettingValueInteger(0, 30,
1148
                                 _mem.settings.pttlt))
1149
        basic.append(pttlt)
1150

    
1151
        emctp = RadioSetting("settings.emctp", "Alarm mode",
1152
                             RadioSettingValueList(LIST_EMCTP, LIST_EMCTP[
1153
                                 _mem.settings.emctp]))
1154
        basic.append(emctp)
1155

    
1156
        emcch = RadioSetting("settings.emcch", "Alarm channel",
1157
                             RadioSettingValueInteger(0, 199,
1158
                                 _mem.settings.emcch))
1159
        basic.append(emcch)
1160

    
1161
        ringt = RadioSetting("settings.ringt", "Ring time",
1162
                             RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1163
                                 _mem.settings.ringt]))
1164
        basic.append(ringt)
1165

    
1166
        camdf = RadioSetting("settings.camdf", "Display mode A",
1167
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1168
                                 _mem.settings.camdf]))
1169
        basic.append(camdf)
1170

    
1171
        cbmdf = RadioSetting("settings.cbmdf", "Display mode B",
1172
                             RadioSettingValueList(LIST_MDF, LIST_MDF[
1173
                                 _mem.settings.cbmdf]))
1174
        basic.append(cbmdf)
1175

    
1176
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1177
           sync = RadioSetting("settings.sync", "A/B channel sync",
1178
                               RadioSettingValueBoolean(_mem.settings.sync))
1179
           basic.append(sync)
1180
        else:
1181
           autolk = RadioSetting("settings.sync", "Auto keylock",
1182
                                 RadioSettingValueBoolean(_mem.settings.sync))
1183
           basic.append(autolk)
1184

    
1185
        ponmsg = RadioSetting("settings.ponmsg", "Power-on message",
1186
                              RadioSettingValueList(LIST_PONMSG, LIST_PONMSG[
1187
                                  _mem.settings.ponmsg]))
1188
        basic.append(ponmsg)
1189

    
1190
        wtled = RadioSetting("settings.wtled", "Standby backlight Color",
1191
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1192
                                 _mem.settings.wtled]))
1193
        basic.append(wtled)
1194

    
1195
        rxled = RadioSetting("settings.rxled", "RX backlight Color",
1196
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1197
                                 _mem.settings.rxled]))
1198
        basic.append(rxled)
1199

    
1200
        txled = RadioSetting("settings.txled", "TX backlight Color",
1201
                             RadioSettingValueList(LIST_COLOR, LIST_COLOR[
1202
                                 _mem.settings.txled]))
1203
        basic.append(txled)
1204

    
1205
        anil = RadioSetting("settings.anil", "ANI length",
1206
                            RadioSettingValueList(LIST_ANIL, LIST_ANIL[
1207
                                _mem.settings.anil]))
1208
        basic.append(anil)
1209

    
1210
        reps = RadioSetting("settings.reps", "Relay signal (tone burst)",
1211
                            RadioSettingValueList(LIST_REPS, LIST_REPS[
1212
                                _mem.settings.reps]))
1213
        basic.append(reps)
1214

    
1215
        repm = RadioSetting("settings.repm", "Relay condition",
1216
                            RadioSettingValueList(LIST_REPM, LIST_REPM[
1217
                                _mem.settings.repm]))
1218
        basic.append(repm)
1219

    
1220
        if self.MODEL in ("UV-2501", "UV-2501+220", "UV-5001"):
1221
            tdrab = RadioSetting("settings.tdrab", "TDR return time",
1222
                                 RadioSettingValueList(LIST_ABR, LIST_ABR[
1223
                                     _mem.settings.tdrab]))
1224
            basic.append(tdrab)
1225

    
1226
            ste = RadioSetting("settings.ste", "Squelch tail eliminate",
1227
                               RadioSettingValueBoolean(_mem.settings.ste))
1228
            basic.append(ste)
1229

    
1230
            rpste = RadioSetting("settings.rpste", "Repeater STE",
1231
                                 RadioSettingValueList(LIST_RINGT, LIST_RINGT[
1232
                                     _mem.settings.rpste]))
1233
            basic.append(rpste)
1234

    
1235
            rptdl = RadioSetting("settings.rptdl", "Repeater STE delay",
1236
                                 RadioSettingValueList(LIST_RPTDL, LIST_RPTDL[
1237
                                     _mem.settings.rptdl]))
1238
            basic.append(rptdl)
1239

    
1240
        # Advanced
1241
        def _filter(name):
1242
            filtered = ""
1243
            for char in str(name):
1244
                if char in VALID_CHARS:
1245
                    filtered += char
1246
                else:
1247
                    filtered += " "
1248
            return filtered
1249

    
1250
        _msg = self._memobj.poweron_msg
1251
        line1 = RadioSetting("poweron_msg.line1", "Power-on message line 1",
1252
                             RadioSettingValueString(0, 6, _filter(
1253
                                 _msg.line1)))
1254
        advanced.append(line1)
1255
        line2 = RadioSetting("poweron_msg.line2", "Power-on message line 2",
1256
                             RadioSettingValueString(0, 6, _filter(
1257
                                 _msg.line2)))
1258
        advanced.append(line2)
1259

    
1260
        if self.MODEL in ("UV-2501", "UV-5001"):
1261
            vfomren = RadioSetting("settings2.vfomren", "VFO/MR switching",
1262
                                   RadioSettingValueBoolean(
1263
                                       not _mem.settings2.vfomren))
1264
            advanced.append(vfomren)
1265

    
1266
            reseten = RadioSetting("settings2.reseten", "RESET",
1267
                                   RadioSettingValueBoolean(
1268
                                       _mem.settings2.reseten))
1269
            advanced.append(reseten)
1270

    
1271
            menuen = RadioSetting("settings2.menuen", "Menu",
1272
                                  RadioSettingValueBoolean(
1273
                                      _mem.settings2.menuen))
1274
            advanced.append(menuen)
1275

    
1276
        # Other
1277
        def convert_bytes_to_limit(bytes):
1278
            limit = ""
1279
            for byte in bytes:
1280
                if byte < 10:
1281
                    limit += chr(byte + 0x30)
1282
                else:
1283
                    break
1284
            return limit
1285

    
1286
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1287
            _ranges = self._memobj.ranges220
1288
            ranges = "ranges220"
1289
        else:
1290
            _ranges = self._memobj.ranges
1291
            ranges = "ranges"
1292

    
1293
        _limit = convert_bytes_to_limit(_ranges.vhf_low)
1294
        val = RadioSettingValueString(0, 3, _limit)
1295
        val.set_mutable(False)
1296
        vhf_low = RadioSetting("%s.vhf_low" % ranges, "VHF low", val)
1297
        other.append(vhf_low)
1298

    
1299
        _limit = convert_bytes_to_limit(_ranges.vhf_high)
1300
        val = RadioSettingValueString(0, 3, _limit)
1301
        val.set_mutable(False)
1302
        vhf_high = RadioSetting("%s.vhf_high" % ranges, "VHF high", val)
1303
        other.append(vhf_high)
1304

    
1305
        if self.MODEL in ["UV-2501+220", "KT8900R"]:
1306
            _limit = convert_bytes_to_limit(_ranges.vhf2_low)
1307
            val = RadioSettingValueString(0, 3, _limit)
1308
            val.set_mutable(False)
1309
            vhf2_low = RadioSetting("%s.vhf2_low" % ranges, "VHF2 low", val)
1310
            other.append(vhf2_low)
1311

    
1312
            _limit = convert_bytes_to_limit(_ranges.vhf2_high)
1313
            val = RadioSettingValueString(0, 3, _limit)
1314
            val.set_mutable(False)
1315
            vhf2_high = RadioSetting("%s.vhf2_high" % ranges, "VHF2 high", val)
1316
            other.append(vhf2_high)
1317

    
1318
        _limit = convert_bytes_to_limit(_ranges.uhf_low)
1319
        val = RadioSettingValueString(0, 3, _limit)
1320
        val.set_mutable(False)
1321
        uhf_low = RadioSetting("%s.uhf_low" % ranges, "UHF low", val)
1322
        other.append(uhf_low)
1323

    
1324
        _limit = convert_bytes_to_limit(_ranges.uhf_high)
1325
        val = RadioSettingValueString(0, 3, _limit)
1326
        val.set_mutable(False)
1327
        uhf_high = RadioSetting("%s.uhf_high" % ranges, "UHF high", val)
1328
        other.append(uhf_high)
1329

    
1330
        val = RadioSettingValueString(0, 6, _filter(_mem.fingerprint.fp))
1331
        val.set_mutable(False)
1332
        fp = RadioSetting("fingerprint.fp", "Fingerprint", val)
1333
        other.append(fp)
1334

    
1335
        # Work
1336
        dispab = RadioSetting("settings2.dispab", "Display",
1337
                              RadioSettingValueList(LIST_AB,LIST_AB[
1338
                                  _mem.settings2.dispab]))
1339
        work.append(dispab)
1340

    
1341
        vfomr = RadioSetting("settings2.vfomr", "VFO/MR mode",
1342
                             RadioSettingValueList(LIST_VFOMR,LIST_VFOMR[
1343
                                 _mem.settings2.vfomr]))
1344
        work.append(vfomr)
1345

    
1346
        keylock = RadioSetting("settings2.keylock", "Keypad lock",
1347
                           RadioSettingValueBoolean(_mem.settings2.keylock))
1348
        work.append(keylock)
1349

    
1350
        mrcha = RadioSetting("settings2.mrcha", "MR A channel",
1351
                             RadioSettingValueInteger(0, 199,
1352
                                 _mem.settings2.mrcha))
1353
        work.append(mrcha)
1354

    
1355
        mrchb = RadioSetting("settings2.mrchb", "MR B channel",
1356
                             RadioSettingValueInteger(0, 199,
1357
                                 _mem.settings2.mrchb))
1358
        work.append(mrchb)
1359

    
1360
        def convert_bytes_to_freq(bytes):
1361
            real_freq = 0
1362
            for byte in bytes:
1363
                real_freq = (real_freq * 10) + byte
1364
            return chirp_common.format_freq(real_freq * 10)
1365

    
1366
        def my_validate(value):
1367
            value = chirp_common.parse_freq(value)
1368
            if 180000000 <= value and value < 210000000:
1369
                msg = ("Can't be between 180.00000-210.00000")
1370
                raise InvalidValueError(msg)
1371
            elif 231000000 <= value and value < 400000000:
1372
                msg = ("Can't be between 231.00000-400.00000")
1373
                raise InvalidValueError(msg)
1374
            elif 210000000 <= value and value < 231000000 \
1375
                and "+220" not in self.MODEL:
1376
                msg = ("Can't be between 210.00000-231.00000")
1377
                raise InvalidValueError(msg)
1378
            elif 240000000 <= value and value < 271000000 \
1379
                and "8900R" not in self.MODEL:
1380
                msg = ("Can't be between 240.00000-271.00000")
1381
                raise InvalidValueError(msg)
1382
            return chirp_common.format_freq(value)
1383

    
1384
        def apply_freq(setting, obj):
1385
            value = chirp_common.parse_freq(str(setting.value)) / 10
1386
            for i in range(7, -1, -1):
1387
                obj.freq[i] = value % 10
1388
                value /= 10
1389

    
1390
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1391
                                        _mem.vfo.a.freq))
1392
        val1a.set_validate_callback(my_validate)
1393
        vfoafreq = RadioSetting("vfo.a.freq", "VFO A frequency", val1a)
1394
        vfoafreq.set_apply_callback(apply_freq, _mem.vfo.a)
1395
        work.append(vfoafreq)
1396

    
1397
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_freq(
1398
                                        _mem.vfo.b.freq))
1399
        val1b.set_validate_callback(my_validate)
1400
        vfobfreq = RadioSetting("vfo.b.freq", "VFO B frequency", val1b)
1401
        vfobfreq.set_apply_callback(apply_freq, _mem.vfo.b)
1402
        work.append(vfobfreq)
1403

    
1404
        vfoashiftd = RadioSetting("vfo.a.shiftd", "VFO A shift",
1405
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1406
                                      _mem.vfo.a.shiftd]))
1407
        work.append(vfoashiftd)
1408

    
1409
        vfobshiftd = RadioSetting("vfo.b.shiftd", "VFO B shift",
1410
                                  RadioSettingValueList(LIST_SHIFT, LIST_SHIFT[
1411
                                      _mem.vfo.b.shiftd]))
1412
        work.append(vfobshiftd)
1413

    
1414
        def convert_bytes_to_offset(bytes):
1415
            real_offset = 0
1416
            for byte in bytes:
1417
                real_offset = (real_offset * 10) + byte
1418
            return chirp_common.format_freq(real_offset * 10000)
1419

    
1420
        def apply_offset(setting, obj):
1421
            value = chirp_common.parse_freq(str(setting.value)) / 10000
1422
            for i in range(3, -1, -1):
1423
                obj.offset[i] = value % 10
1424
                value /= 10
1425

    
1426
        val1a = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1427
                                        _mem.vfo.a.offset))
1428
        vfoaoffset = RadioSetting("vfo.a.offset",
1429
                                  "VFO A offset (0.00-99.95)", val1a)
1430
        vfoaoffset.set_apply_callback(apply_offset, _mem.vfo.a)
1431
        work.append(vfoaoffset)
1432

    
1433
        val1b = RadioSettingValueString(0, 10, convert_bytes_to_offset(
1434
                                        _mem.vfo.b.offset))
1435
        vfoboffset = RadioSetting("vfo.b.offset",
1436
                                  "VFO B offset (0.00-99.95)", val1b)
1437
        vfoboffset.set_apply_callback(apply_offset, _mem.vfo.b)
1438
        work.append(vfoboffset)
1439

    
1440
        vfoatxp = RadioSetting("vfo.a.power", "VFO A power",
1441
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1442
                                    _mem.vfo.a.power]))
1443
        work.append(vfoatxp)
1444

    
1445
        vfobtxp = RadioSetting("vfo.b.power", "VFO B power",
1446
                                RadioSettingValueList(LIST_TXP,LIST_TXP[
1447
                                    _mem.vfo.b.power]))
1448
        work.append(vfobtxp)
1449

    
1450
        vfoawide = RadioSetting("vfo.a.wide", "VFO A bandwidth",
1451
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1452
                                    _mem.vfo.a.wide]))
1453
        work.append(vfoawide)
1454

    
1455
        vfobwide = RadioSetting("vfo.b.wide", "VFO B bandwidth",
1456
                                RadioSettingValueList(LIST_WIDE,LIST_WIDE[
1457
                                    _mem.vfo.b.wide]))
1458
        work.append(vfobwide)
1459

    
1460
        vfoastep = RadioSetting("vfo.a.step", "VFO A step",
1461
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1462
                                    _mem.vfo.a.step]))
1463
        work.append(vfoastep)
1464

    
1465
        vfobstep = RadioSetting("vfo.b.step", "VFO B step",
1466
                                RadioSettingValueList(LIST_STEP,LIST_STEP[
1467
                                    _mem.vfo.b.step]))
1468
        work.append(vfobstep)
1469

    
1470
        vfoaoptsig = RadioSetting("vfo.a.optsig", "VFO A optional signal",
1471
                                  RadioSettingValueList(OPTSIG_LIST,
1472
                                      OPTSIG_LIST[_mem.vfo.a.optsig]))
1473
        work.append(vfoaoptsig)
1474

    
1475
        vfoboptsig = RadioSetting("vfo.b.optsig", "VFO B optional signal",
1476
                                  RadioSettingValueList(OPTSIG_LIST,
1477
                                      OPTSIG_LIST[_mem.vfo.b.optsig]))
1478
        work.append(vfoboptsig)
1479

    
1480
        vfoaspmute = RadioSetting("vfo.a.spmute", "VFO A speaker mute",
1481
                                  RadioSettingValueList(SPMUTE_LIST,
1482
                                      SPMUTE_LIST[_mem.vfo.a.spmute]))
1483
        work.append(vfoaspmute)
1484

    
1485
        vfobspmute = RadioSetting("vfo.b.spmute", "VFO B speaker mute",
1486
                                  RadioSettingValueList(SPMUTE_LIST,
1487
                                      SPMUTE_LIST[_mem.vfo.b.spmute]))
1488
        work.append(vfobspmute)
1489

    
1490
        vfoascr = RadioSetting("vfo.a.scramble", "VFO A scramble",
1491
                               RadioSettingValueBoolean(_mem.vfo.a.scramble))
1492
        work.append(vfoascr)
1493

    
1494
        vfobscr = RadioSetting("vfo.b.scramble", "VFO B scramble",
1495
                               RadioSettingValueBoolean(_mem.vfo.b.scramble))
1496
        work.append(vfobscr)
1497

    
1498
        vfoascode = RadioSetting("vfo.a.scode", "VFO A PTT-ID",
1499
                                 RadioSettingValueList(PTTIDCODE_LIST,
1500
                                     PTTIDCODE_LIST[_mem.vfo.a.scode]))
1501
        work.append(vfoascode)
1502

    
1503
        vfobscode = RadioSetting("vfo.b.scode", "VFO B PTT-ID",
1504
                                 RadioSettingValueList(PTTIDCODE_LIST,
1505
                                     PTTIDCODE_LIST[_mem.vfo.b.scode]))
1506
        work.append(vfobscode)
1507

    
1508
        pttid = RadioSetting("settings.pttid", "PTT ID",
1509
                             RadioSettingValueList(PTTID_LIST,
1510
                                 PTTID_LIST[_mem.settings.pttid]))
1511
        work.append(pttid)
1512

    
1513
        return top
1514

    
1515
    def set_settings(self, settings):
1516
        _settings = self._memobj.settings
1517
        for element in settings:
1518
            if not isinstance(element, RadioSetting):
1519
                if element.get_name() == "fm_preset":
1520
                    self._set_fm_preset(element)
1521
                else:
1522
                    self.set_settings(element)
1523
                    continue
1524
            else:
1525
                try:
1526
                    name = element.get_name()
1527
                    if "." in name:
1528
                        bits = name.split(".")
1529
                        obj = self._memobj
1530
                        for bit in bits[:-1]:
1531
                            if "/" in bit:
1532
                                bit, index = bit.split("/", 1)
1533
                                index = int(index)
1534
                                obj = getattr(obj, bit)[index]
1535
                            else:
1536
                                obj = getattr(obj, bit)
1537
                        setting = bits[-1]
1538
                    else:
1539
                        obj = _settings
1540
                        setting = element.get_name()
1541

    
1542
                    if element.has_apply_callback():
1543
                        LOG.debug("Using apply callback")
1544
                        element.run_apply_callback()
1545
                    elif setting == "vfomren":
1546
                        setattr(obj, setting, not int(element.value))
1547
                    elif element.value.get_mutable():
1548
                        LOG.debug("Setting %s = %s" % (setting, element.value))
1549
                        setattr(obj, setting, element.value)
1550
                except Exception, e:
1551
                    LOG.debug(element.get_name())
1552
                    raise
1553

    
1554
    @classmethod
1555
    def match_model(cls, filedata, filename):
1556
        match_size = False
1557
        match_model = False
1558

    
1559
        # testing the file data size
1560
        if len(filedata) == MEM_SIZE:
1561
            match_size = True
1562

    
1563
        # testing the firmware model fingerprint
1564
        match_model = model_match(cls, filedata)
1565

    
1566
        if match_size and match_model:
1567
            return True
1568
        else:
1569
            return False
1570

    
1571

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

    
1581

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

    
1593

    
1594
@directory.register
1595
class UV5001(BTech):
1596
    """Baofeng Tech UV5001"""
1597
    MODEL = "UV-5001"
1598
    _fileid = [UV5001G3_fp,
1599
               UV5001G22_fp,
1600
               UV5001G2_fp,
1601
               UV5001alpha_fp,
1602
               UV5001pp_fp]
1603

    
1604

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

    
1613

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

    
1624

    
1625
@directory.register
1626
class KT9800(BTech):
1627
    """QYT KT8900"""
1628
    VENDOR = "QYT"
1629
    MODEL = "KT8900"
1630
    _vhf_range = (136000000, 175000000)
1631
    _uhf_range = (400000000, 481000000)
1632
    _magic = MSTRING_KT8900
1633
    _fileid = [KT8900_fp, KT8900_fp1, KT8900_fp2, KT8900_fp3]
1634
    _id2 = KT8900_id
1635

    
1636

    
1637
@directory.register
1638
class KT9800R(BTech):
1639
    """QYT KT8900R"""
1640
    VENDOR = "QYT"
1641
    MODEL = "KT8900R"
1642
    _vhf_range = (136000000, 175000000)
1643
    _220_range = (240000000, 271000000)
1644
    _uhf_range = (400000000, 481000000)
1645
    _magic = MSTRING_KT8900R
1646
    _fileid = [KT8900R_fp]
1647
    _id2 = KT8900R_id